Xinqi Bao's Git

Build Linux-only functions only on Linux
[slstatus.git] / components / battery.c
1 /* See LICENSE file for copyright and license details. */
2 #ifdef __linux__
3 #include <limits.h>
4 #include <stdio.h>
5 #include <string.h>
6
7 #include "../util.h"
8
9 const char *
10 battery_perc(const char *bat)
11 {
12 int perc;
13 char path[PATH_MAX];
14
15 snprintf(path, sizeof(path), "%s%s%s", "/sys/class/power_supply/", bat, "/capacity");
16 return (pscanf(path, "%i", &perc) == 1) ?
17 bprintf("%d", perc) : NULL;
18 }
19
20 const char *
21 battery_power(const char *bat)
22 {
23 int watts;
24 char path[PATH_MAX];
25
26 snprintf(path, sizeof(path), "%s%s%s", "/sys/class/power_supply/", bat, "/power_now");
27 return (pscanf(path, "%i", &watts) == 1) ?
28 bprintf("%d", (watts + 500000) / 1000000) : NULL;
29 }
30
31 const char *
32 battery_state(const char *bat)
33 {
34 struct {
35 char *state;
36 char *symbol;
37 } map[] = {
38 { "Charging", "+" },
39 { "Discharging", "-" },
40 { "Full", "=" },
41 { "Unknown", "/" },
42 };
43 size_t i;
44 char path[PATH_MAX], state[12];
45
46 snprintf(path, sizeof(path), "%s%s%s", "/sys/class/power_supply/", bat, "/status");
47 if (pscanf(path, "%12s", state) != 1) {
48 return NULL;
49 }
50
51 for (i = 0; i < LEN(map); i++) {
52 if (!strcmp(map[i].state, state)) {
53 break;
54 }
55 }
56 return (i == LEN(map)) ? "?" : map[i].symbol;
57 }
58 #endif