Xinqi Bao's Git

battery_perc: Port to OpenBSD.
[slstatus.git] / components / battery.c
1 /* See LICENSE file for copyright and license details. */
2 #include <err.h>
3 #include <stdio.h>
4 #ifdef __linux__
5 #include <limits.h>
6 #include <string.h>
7 #elif __OpenBSD__
8 #include <sys/ioctl.h>
9 #include <fcntl.h>
10 #include <unistd.h>
11 #include <machine/apmvar.h>
12 #endif
13
14 #include "../util.h"
15
16 const char *
17 battery_perc(const char *bat)
18 {
19 #ifdef __linux__
20 int perc;
21 char path[PATH_MAX];
22
23 snprintf(path, sizeof(path), "%s%s%s", "/sys/class/power_supply/", bat, "/capacity");
24 return (pscanf(path, "%i", &perc) == 1) ?
25 bprintf("%d", perc) : NULL;
26 #elif __OpenBSD__
27 struct apm_power_info apm_info;
28 int fd;
29
30 fd = open("/dev/apm", O_RDONLY);
31 if (fd < 0) {
32 warn("Failed to open file /dev/apm");
33 return NULL;
34 }
35
36 if (ioctl(fd, APM_IOC_GETPOWER, &apm_info) < 0) {
37 warn("Failed to get battery info");
38 close(fd);
39 return NULL;
40 }
41 close(fd);
42
43 return bprintf("%d", apm_info.battery_life);
44 #endif
45 }
46
47 #ifdef __linux__
48 const char *
49 battery_power(const char *bat)
50 {
51 int watts;
52 char path[PATH_MAX];
53
54 snprintf(path, sizeof(path), "%s%s%s", "/sys/class/power_supply/", bat, "/power_now");
55 return (pscanf(path, "%i", &watts) == 1) ?
56 bprintf("%d", (watts + 500000) / 1000000) : NULL;
57 }
58
59 const char *
60 battery_state(const char *bat)
61 {
62 struct {
63 char *state;
64 char *symbol;
65 } map[] = {
66 { "Charging", "+" },
67 { "Discharging", "-" },
68 { "Full", "=" },
69 { "Unknown", "/" },
70 };
71 size_t i;
72 char path[PATH_MAX], state[12];
73
74 snprintf(path, sizeof(path), "%s%s%s", "/sys/class/power_supply/", bat, "/status");
75 if (pscanf(path, "%12s", state) != 1) {
76 return NULL;
77 }
78
79 for (i = 0; i < LEN(map); i++) {
80 if (!strcmp(map[i].state, state)) {
81 break;
82 }
83 }
84 return (i == LEN(map)) ? "?" : map[i].symbol;
85 }
86 #endif