Xinqi Bao's Git

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