Better file structure and build system
[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 "status/battery.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(char *batname)
15 {
16   char batpath[256];
17   int batpathlen;
18
19   char stline[16];
20   ssize_t stlen;
21
22   int chargeNow = 0;
23   int chargeFull = -1;
24   int chargePercent = -1;
25   int battW = 1;
26   float battTime = -1;
27
28
29   /* Prepare path */
30   batpathlen = sizeof(POWER_BASEDIR) - 1 + strlen(batname);
31   if (batpathlen + 1 + sizeof("/energy_full") >= sizeof(batpath)) {
32     statusError("status_battery",
33                 "batpath buffer too small",
34                 batname);
35     return;
36   }
37   strcpy(batpath, POWER_BASEDIR);
38   strcat(batpath, batname);
39
40
41   /* Is the battery present? */
42   if (access(batpath, F_OK)) {
43     //printf(" ^fg(grey)[%s] ", batname);
44     return;
45   }
46
47
48   /* Get info */
49   strcpy(&batpath[batpathlen], "/energy_now");
50   stlen = fileRead(stline, sizeof(stline), batpath);
51   if (stlen > 0) {
52     chargeNow = atoi(stline);
53   }
54
55   strcpy(&batpath[batpathlen], "/energy_full");
56   stlen = fileRead(stline, sizeof(stline), batpath);
57   if (stlen > 0) {
58     chargeFull = atoi(stline);
59   }
60
61   strcpy(&batpath[batpathlen], "/power_now");
62   stlen = fileRead(stline, sizeof(stline), batpath);
63   if (stlen > 0) {
64     battW = atoi(stline);
65   }
66
67
68   /* Prettyprint */
69   if (chargeFull > 0) {
70     chargePercent = chargeNow / (chargeFull / 100);
71   }
72
73   if (chargePercent <= 40) {
74     if (chargePercent <= 25) {
75       if (chargePercent <= 10) {
76         fputs("^fg(red)", stdout);
77       } else {
78         // 11-25%
79         fputs("^fg(orange)", stdout);
80       }
81     } else {
82       // 26-40%
83       fputs("^fg(yellow)", stdout);
84     }
85   } else {
86     if (chargePercent > 70) {
87       fputs("^fg(white)", stdout);
88     } else {
89       // 41-70%
90       fputs("^fg(green)", stdout);
91     }
92   }
93
94   battTime = (float)chargeNow / (float)battW;
95
96   if (battW == 0) {
97     // fully charged and not in use
98     printf(" %s: %d%% _ _ ",
99             batname, chargePercent);
100   } else {
101     printf(" %s: %d%% %.1fh %.1fW ",
102             batname, chargePercent, battTime, (float)battW / 1000000.0);
103   }
104 }