Xinqi Bao's Git

Get rid of err.h as it is not portable
[slstatus.git] / components / battery.c
1 /* See LICENSE file for copyright and license details. */
2 #include <stdio.h>
3 #if defined(__linux__)
4 #include <limits.h>
5 #include <string.h>
6 #elif defined(__OpenBSD__)
7 #include <sys/ioctl.h>
8 #include <fcntl.h>
9 #include <unistd.h>
10 #include <machine/apmvar.h>
11 #endif
12
13 #include "../util.h"
14
15 const char *
16 battery_perc(const char *bat)
17 {
18 #if defined(__linux__)
19 int perc;
20 char path[PATH_MAX];
21
22 snprintf(path, sizeof(path), "%s%s%s", "/sys/class/power_supply/", bat, "/capacity");
23 return (pscanf(path, "%i", &perc) == 1) ?
24 bprintf("%d", perc) : NULL;
25 #elif defined(__OpenBSD__)
26 struct apm_power_info apm_info;
27 int fd;
28
29 fd = open("/dev/apm", O_RDONLY);
30 if (fd < 0) {
31 fprintf(stderr, "Failed to open file /dev/apm");
32 return NULL;
33 }
34
35 if (ioctl(fd, APM_IOC_GETPOWER, &apm_info) < 0) {
36 fprintf(stderr, "Failed to get battery info");
37 close(fd);
38 return NULL;
39 }
40 close(fd);
41
42 return bprintf("%d", apm_info.battery_life);
43 #endif
44 }
45
46 #if defined(__linux__)
47 const char *
48 battery_power(const char *bat)
49 {
50 int watts;
51 char path[PATH_MAX];
52
53 snprintf(path, sizeof(path), "%s%s%s", "/sys/class/power_supply/", bat, "/power_now");
54 return (pscanf(path, "%i", &watts) == 1) ?
55 bprintf("%d", (watts + 500000) / 1000000) : NULL;
56 }
57
58 const char *
59 battery_state(const char *bat)
60 {
61 struct {
62 char *state;
63 char *symbol;
64 } map[] = {
65 { "Charging", "+" },
66 { "Discharging", "-" },
67 { "Full", "=" },
68 { "Unknown", "/" },
69 };
70 size_t i;
71 char path[PATH_MAX], state[12];
72
73 snprintf(path, sizeof(path), "%s%s%s", "/sys/class/power_supply/", bat, "/status");
74 if (pscanf(path, "%12s", state) != 1) {
75 return NULL;
76 }
77
78 for (i = 0; i < LEN(map); i++) {
79 if (!strcmp(map[i].state, state)) {
80 break;
81 }
82 }
83 return (i == LEN(map)) ? "?" : map[i].symbol;
84 }
85 #endif