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