Standardize battery.c
[dwm-status.git] / battery.c
blobef678dce6c8e90732c173e627c4abb4b06036249
1 /*-
2 * "THE BEER-WARE LICENSE" (Revision 42):
3 * <tobias.rehbein@web.de> wrote this file. As long as you retain this notice
4 * you can do whatever you want with this stuff. If we meet some day, and you
5 * think this stuff is worth it, you can buy me a beer in return.
6 * Tobias Rehbein
7 */
9 #define _POSIX_C_SOURCE 199506
11 #include <assert.h>
12 #include <err.h>
13 #include <fcntl.h>
14 #include <stdio.h>
15 #include <stdlib.h>
16 #include <sysexits.h>
17 #include <unistd.h>
18 #include <dev/acpica/acpiio.h>
19 #include <sys/ioctl.h>
21 #include "battery.h"
22 #include "buffers.h"
23 #include "tools.h"
25 static const char *ACPIDEV = "/dev/acpi";
27 struct battery_context {
28 int fd;
29 char battery_str[BATTERY_BUFFLEN];
32 struct battery_context *
33 battery_context_open()
35 struct battery_context *ctx;
37 if ((ctx = malloc(sizeof(*ctx))) == NULL)
38 err(EX_SOFTWARE, "malloc(%d) battery_context", sizeof(*ctx));
39 if ((ctx->fd = open(ACPIDEV, O_RDONLY)) == -1)
40 err(EX_OSFILE, "open(%s)", ACPIDEV);
42 return (ctx);
45 void
46 battery_context_close(struct battery_context *ctx)
48 assert(ctx != NULL);
50 if (close(ctx->fd) == -1)
51 err(EX_OSFILE, "close(%s)", ACPIDEV);
52 free(ctx);
55 char *
56 battery_str(struct battery_context *ctx)
58 union acpi_battery_ioctl_arg battio;
59 const char *state;
60 char cap[3 + 1]; /* capacity is a percentage so the
61 * string representation will be at
62 * most three character long */
64 assert(ctx != NULL);
66 battio.unit = ACPI_BATTERY_ALL_UNITS;
67 if (ioctl(ctx->fd, ACPIIO_BATT_GET_BATTINFO, &battio) == -1)
68 err(EX_IOERR, "ioctl(ACPIIO_BATT_GET_BATTINFO)");
70 if (battio.battinfo.state == 0)
71 state = "=";
72 else if (battio.battinfo.state & ACPI_BATT_STAT_CRITICAL)
73 state = "!";
74 else if (battio.battinfo.state & ACPI_BATT_STAT_DISCHARG)
75 state = "-";
76 else if (battio.battinfo.state & ACPI_BATT_STAT_CHARGING)
77 state = "+";
78 else
79 state = "?";
81 sprintf(cap, "%d", battio.battinfo.cap);
82 tools_catitems(ctx->battery_str, sizeof(ctx->battery_str), cap, "% [", state, "]", NULL);
84 return (ctx->battery_str);