Fix buffer sizes
[dwm-status.git] / battery.c
blobbbdff15375710aa791bd923272a1b3f6676115db
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 <unistd.h>
17 #include <dev/acpica/acpiio.h>
18 #include <sys/ioctl.h>
20 #include "battery.h"
21 #include "buffers.h"
22 #include "tools.h"
24 static const char *ACPIDEV = "/dev/acpi";
26 struct battery_context {
27 int fd;
28 char battery_str[BATTERY_BUFFLEN];
31 struct battery_context *
32 battery_context_open()
34 struct battery_context *ctx;
36 if ((ctx = malloc(sizeof(*ctx))) == NULL)
37 err(EXIT_FAILURE, "malloc(%d) battery_context", sizeof(*ctx));
38 if ((ctx->fd = open(ACPIDEV, O_RDONLY)) == -1)
39 err(EXIT_FAILURE, "open(%s)", ACPIDEV);
41 return (ctx);
44 void
45 battery_context_close(struct battery_context *ctx)
47 assert(ctx != NULL);
49 if (close(ctx->fd) == -1)
50 err(EXIT_FAILURE, "close(%s)", ACPIDEV);
51 free(ctx);
54 char *
55 battery_str(struct battery_context *ctx)
57 union acpi_battery_ioctl_arg battio;
58 const char *state;
59 char cap[4];
61 assert(ctx != NULL);
63 battio.unit = ACPI_BATTERY_ALL_UNITS;
64 if (ioctl(ctx->fd, ACPIIO_BATT_GET_BATTINFO, &battio) == -1)
65 err(EXIT_FAILURE, "ioctl(ACPIIO_BATT_GET_BATTINFO)");
67 if (battio.battinfo.state == 0)
68 state = "=";
69 else if (battio.battinfo.state & ACPI_BATT_STAT_CRITICAL)
70 state = "!";
71 else if (battio.battinfo.state & ACPI_BATT_STAT_DISCHARG)
72 state = "-";
73 else if (battio.battinfo.state & ACPI_BATT_STAT_CHARGING)
74 state = "+";
75 else
76 state = "?";
78 assert(battio.battinfo.cap >= 0 && battio.battinfo.cap <= 100 && sizeof(cap) > 3);
79 sprintf(cap, "%d", battio.battinfo.cap);
81 tools_catitems(ctx->battery_str, sizeof(ctx->battery_str), cap, "% [", state, "]", NULL);
83 return (ctx->battery_str);