Xinqi Bao's Git

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