Xinqi Bao's Git

Mark unused parameters, fix compiler warnings
[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 *bat)
56 {
57 struct apm_power_info apm_info;
58 int fd;
59
60 UNUSED(bat); /* no way to specify battery on OpenBSD */
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 UNUSED(bat); /* no way to specify battery on OpenBSD */
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