5375ea1efa4d396cdedfb91f2ba5a1b077edfaff
[sysstatus.git] / statuses / battery.c
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <unistd.h>
4 #include "string.h"
5 #include "battery.h"
6
7 #ifndef POWER_BASEDIR
8   #define POWER_BASEDIR "/sys/class/power_supply/"
9 #endif
10
11
12 void status_battery(char *batname)
13 {
14   char batpath[256];
15   int batpathlen;
16
17   char stline[16];
18   ssize_t stlen;
19
20   int chargeNow = 0;
21   int chargeFull = -1;
22   int chargePercent = -1;
23   int battW = 1;
24   int battV = 0;
25   float battTime = -1;
26
27
28   /* Prepare path */
29   batpathlen = sizeof(POWER_BASEDIR) - 1 + strlen(batname);
30   if (batpathlen + 1 + sizeof("/energy_full") >= sizeof(batpath)) {
31     statusError("status_battery",
32                 "batpath buffer too small",
33                 batname);
34     return;
35   }
36   strcpy(batpath, POWER_BASEDIR);
37   strcat(batpath, batname);
38
39
40   /* Is the battery present? */
41   if (access(batpath, F_OK)) {
42     //printf(" ^fg(grey)[%s] ", batname);
43     return;
44   }
45
46
47   /* Get info */
48   strcpy(&batpath[batpathlen], "/energy_now");
49   stlen = fileRead(stline, sizeof(stline), batpath);
50   if (stlen > 0) {
51     chargeNow = atoi(stline);
52   }
53
54   strcpy(&batpath[batpathlen], "/energy_full");
55   stlen = fileRead(stline, sizeof(stline), batpath);
56   if (stlen > 0) {
57     chargeFull = atoi(stline);
58   }
59
60   strcpy(&batpath[batpathlen], "/power_now");
61   stlen = fileRead(stline, sizeof(stline), batpath);
62   if (stlen > 0) {
63     battW = atoi(stline);
64   }
65
66   strcpy(&batpath[batpathlen], "/voltage_now");
67   stlen = fileRead(stline, sizeof(stline), batpath);
68   if (stlen > 0) {
69     battV = atoi(stline);
70   }
71
72
73   /* Prettyprint */
74   if (chargeFull > 0) {
75     chargePercent = chargeNow / (chargeFull / 100);
76   }
77
78   if (chargePercent <= 40) {
79     if (chargePercent <= 25) {
80       if (chargePercent <= 10) {
81         fputs("^fg(red)", stdout);
82       } else {
83         // 11-25%
84         fputs("^fg(orange)", stdout);
85       }
86     } else {
87       // 26-40%
88       fputs("^fg(yellow)", stdout);
89     }
90   } else {
91     if (chargePercent > 70) {
92       fputs("^fg(white)", stdout);
93     } else {
94       // 41-70%
95       fputs("^fg(green)", stdout);
96     }
97   }
98
99   battTime = (float)chargeNow / (float)battW;
100
101   if (battW == 0) {
102     // fully charged and not in use
103     printf(" %s: %d%% _ _ ",
104             batname, chargePercent);
105   } else {
106     printf(" %s: %d%% %.1fh %.1fW ",
107             batname, chargePercent, battTime, (float)battW / 1000000.0);
108   }
109 }