Xinqi Bao's Git

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