Xinqi Bao's Git

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