Xinqi Bao's Git

wifi_perc: Simplify
[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 #elif defined(__OpenBSD__)
49 #include <fcntl.h>
50 #include <machine/apmvar.h>
51 #include <sys/ioctl.h>
52 #include <unistd.h>
53
54 const char *
55 battery_perc(const char *null)
56 {
57 struct apm_power_info apm_info;
58 int fd;
59
60 fd = open("/dev/apm", O_RDONLY);
61 if (fd < 0) {
62 fprintf(stderr, "open '/dev/apm': %s\n", strerror(errno));
63 return NULL;
64 }
65
66 if (ioctl(fd, APM_IOC_GETPOWER, &apm_info) < 0) {
67 fprintf(stderr, "ioctl 'APM_IOC_GETPOWER': %s\n",
68 strerror(errno));
69 close(fd);
70 return NULL;
71 }
72 close(fd);
73
74 return bprintf("%d", apm_info.battery_life);
75 }
76
77 const char *
78 battery_state(const char *bat)
79 {
80 int fd;
81 size_t i;
82 struct apm_power_info apm_info;
83 struct {
84 unsigned int state;
85 char *symbol;
86 } map[] = {
87 { APM_AC_ON, "+" },
88 { APM_AC_OFF, "-" },
89 };
90
91 fd = open("/dev/apm", O_RDONLY);
92 if (fd < 0) {
93 fprintf(stderr, "open '/dev/apm': %s\n", strerror(errno));
94 return NULL;
95 }
96
97 if (ioctl(fd, APM_IOC_GETPOWER, &apm_info) < 0) {
98 fprintf(stderr, "ioctl 'APM_IOC_GETPOWER': %s\n",
99 strerror(errno));
100 close(fd);
101 return NULL;
102 }
103 close(fd);
104
105 for (i = 0; i < LEN(map); i++) {
106 if (map[i].state == apm_info.ac_state) {
107 break;
108 }
109 }
110 return (i == LEN(map)) ? "?" : map[i].symbol;
111 }
112 #endif