Xinqi Bao's Git

battery_state: Unify unknown state with "?" symbol
[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
6 #include "../util.h"
7
8 #if defined(__linux__)
9 #include <limits.h>
10
11 const char *
12 battery_perc(const char *bat)
13 {
14 int perc;
15 char path[PATH_MAX];
16
17 snprintf(path, sizeof(path), "%s%s%s", "/sys/class/power_supply/",
18 bat, "/capacity");
19 return (pscanf(path, "%i", &perc) == 1) ?
20 bprintf("%d", perc) : NULL;
21 }
22
23 const char *
24 battery_state(const char *bat)
25 {
26 struct {
27 char *state;
28 char *symbol;
29 } map[] = {
30 { "Charging", "+" },
31 { "Discharging", "-" },
32 { "Full", "=" },
33 };
34 size_t i;
35 char path[PATH_MAX], state[12];
36
37 snprintf(path, sizeof(path), "%s%s%s", "/sys/class/power_supply/",
38 bat, "/status");
39 if (pscanf(path, "%12s", state) != 1) {
40 return NULL;
41 }
42
43 for (i = 0; i < LEN(map); i++) {
44 if (!strcmp(map[i].state, state)) {
45 break;
46 }
47 }
48 return (i == LEN(map)) ? "?" : map[i].symbol;
49 }
50 #elif defined(__OpenBSD__)
51 #include <fcntl.h>
52 #include <machine/apmvar.h>
53 #include <sys/ioctl.h>
54 #include <unistd.h>
55
56 const char *
57 battery_perc(const char *null)
58 {
59 struct apm_power_info apm_info;
60 int fd;
61
62 fd = open("/dev/apm", O_RDONLY);
63 if (fd < 0) {
64 fprintf(stderr, "open '/dev/apm': %s\n", strerror(errno));
65 return NULL;
66 }
67
68 if (ioctl(fd, APM_IOC_GETPOWER, &apm_info) < 0) {
69 fprintf(stderr, "ioctl 'APM_IOC_GETPOWER': %s\n",
70 strerror(errno));
71 close(fd);
72 return NULL;
73 }
74 close(fd);
75
76 return bprintf("%d", apm_info.battery_life);
77 }
78
79 const char *
80 battery_state(const char *bat)
81 {
82 int fd;
83 size_t i;
84 struct apm_power_info apm_info;
85 struct {
86 unsigned int state;
87 char *symbol;
88 } map[] = {
89 { APM_AC_ON, "+" },
90 { APM_AC_OFF, "-" },
91 };
92
93 fd = open("/dev/apm", O_RDONLY);
94 if (fd < 0) {
95 fprintf(stderr, "open '/dev/apm': %s\n", strerror(errno));
96 return NULL;
97 }
98
99 if (ioctl(fd, APM_IOC_GETPOWER, &apm_info) < 0) {
100 fprintf(stderr, "ioctl 'APM_IOC_GETPOWER': %s\n",
101 strerror(errno));
102 close(fd);
103 return NULL;
104 }
105 close(fd);
106
107 for (i = 0; i < LEN(map); i++) {
108 if (map[i].state == apm_info.ac_state) {
109 break;
110 }
111 }
112 return (i == LEN(map)) ? "?" : map[i].symbol;
113 }
114 #endif