Xinqi Bao's Git

152777ef46da27dcbeb8594623cbfb2d74b1c34b
[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) ? bprintf("%d", perc) : NULL;
20 }
21
22 const char *
23 battery_state(const char *bat)
24 {
25 struct {
26 char *state;
27 char *symbol;
28 } map[] = {
29 { "Charging", "+" },
30 { "Discharging", "-" },
31 };
32 size_t i;
33 char path[PATH_MAX], state[12];
34
35 snprintf(path, sizeof(path), "%s%s%s", "/sys/class/power_supply/",
36 bat, "/status");
37 if (pscanf(path, "%12s", state) != 1) {
38 return NULL;
39 }
40
41 for (i = 0; i < LEN(map); i++) {
42 if (!strcmp(map[i].state, state)) {
43 break;
44 }
45 }
46 return (i == LEN(map)) ? "?" : map[i].symbol;
47 }
48
49 const char *
50 battery_remaining(const char *bat)
51 {
52 /* TODO: Implement */
53 return NULL;
54 }
55 #elif defined(__OpenBSD__)
56 #include <fcntl.h>
57 #include <machine/apmvar.h>
58 #include <sys/ioctl.h>
59 #include <unistd.h>
60
61 static int
62 load_apm_power_info(struct apm_power_info *apm_info)
63 {
64 int fd;
65
66 fd = open("/dev/apm", O_RDONLY);
67 if (fd < 0) {
68 warn("open '/dev/apm':");
69 return 0;
70 }
71
72 memset(apm_info, 0, sizeof(struct apm_power_info));
73 if (ioctl(fd, APM_IOC_GETPOWER, apm_info) < 0) {
74 warn("ioctl 'APM_IOC_GETPOWER':");
75 close(fd);
76 return 0;
77 }
78 return close(fd), 1;
79 }
80
81 const char *
82 battery_perc(const char *unused)
83 {
84 struct apm_power_info apm_info;
85
86 if (load_apm_power_info(&apm_info)) {
87 return bprintf("%d", apm_info.battery_life);
88 }
89
90 return NULL;
91 }
92
93 const char *
94 battery_state(const char *unused)
95 {
96 struct apm_power_info apm_info;
97 size_t i;
98 struct {
99 unsigned int state;
100 char *symbol;
101 } map[] = {
102 { APM_AC_ON, "+" },
103 { APM_AC_OFF, "-" },
104 };
105
106 if (load_apm_power_info(&apm_info)) {
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
115 return NULL;
116 }
117
118 const char *
119 battery_remaining(const char *unused)
120 {
121 struct apm_power_info apm_info;
122
123 if (load_apm_power_info(&apm_info)) {
124 return bprintf("%u:%02u", apm_info.minutes_left / 60,
125 apm_info.minutes_left % 60);
126 }
127
128 return NULL;
129 }
130 #endif