Xinqi Bao's Git

Remove battery_power for various reasons
[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 { "Unknown", "/" },
34 };
35 size_t i;
36 char path[PATH_MAX], state[12];
37
38 snprintf(path, sizeof(path), "%s%s%s", "/sys/class/power_supply/",
39 bat, "/status");
40 if (pscanf(path, "%12s", state) != 1) {
41 return NULL;
42 }
43
44 for (i = 0; i < LEN(map); i++) {
45 if (!strcmp(map[i].state, state)) {
46 break;
47 }
48 }
49 return (i == LEN(map)) ? "?" : map[i].symbol;
50 }
51 #elif defined(__OpenBSD__)
52 #include <fcntl.h>
53 #include <machine/apmvar.h>
54 #include <sys/ioctl.h>
55 #include <unistd.h>
56
57 const char *
58 battery_perc(const char *null)
59 {
60 struct apm_power_info apm_info;
61 int fd;
62
63 fd = open("/dev/apm", O_RDONLY);
64 if (fd < 0) {
65 fprintf(stderr, "open '/dev/apm': %s\n", strerror(errno));
66 return NULL;
67 }
68
69 if (ioctl(fd, APM_IOC_GETPOWER, &apm_info) < 0) {
70 fprintf(stderr, "ioctl 'APM_IOC_GETPOWER': %s\n",
71 strerror(errno));
72 close(fd);
73 return NULL;
74 }
75 close(fd);
76
77 return bprintf("%d", apm_info.battery_life);
78 }
79
80 const char *
81 battery_state(const char *bat)
82 {
83 int fd;
84 size_t i;
85 struct apm_power_info apm_info;
86 struct {
87 unsigned int state;
88 char *symbol;
89 } map[] = {
90 { APM_AC_ON, "+" },
91 { APM_AC_OFF, "-" },
92 { APM_AC_UNKNOWN, "/" },
93 };
94
95 fd = open("/dev/apm", O_RDONLY);
96 if (fd < 0) {
97 fprintf(stderr, "open '/dev/apm': %s\n", strerror(errno));
98 return NULL;
99 }
100
101 if (ioctl(fd, APM_IOC_GETPOWER, &apm_info) < 0) {
102 fprintf(stderr, "ioctl 'APM_IOC_GETPOWER': %s\n",
103 strerror(errno));
104 close(fd);
105 return NULL;
106 }
107 close(fd);
108
109 for (i = 0; i < LEN(map); i++) {
110 if (map[i].state == apm_info.ac_state) {
111 break;
112 }
113 }
114 return (i == LEN(map)) ? "?" : map[i].symbol;
115 }
116 #endif