summaryrefslogtreecommitdiff
path: root/src/status/battery.c
blob: 65fdd1bc93bb9eb53a16bfc972a3945ed2ea0a26 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>

#include "common.h"
#include "tools.h"

#ifndef POWER_BASEDIR
  #define POWER_BASEDIR "/sys/class/power_supply/"
#endif


void status_battery(GlobalData *g, char *batname)
{
  StatusItem s;
  char text[32] = { 0 };

  char batpath[256];
  int batpathlen;

  char stline[16];
  ssize_t stlen;

  int chargeNow = 0;
  int chargeFull = -1;
  int chargePercent = -1;
  int battW = 1;
  float battTime = -1;


  statusitem_init(&s);
  s.text = text;

  /* Prepare path */
  batpathlen = sizeof(POWER_BASEDIR) - 1 + strlen(batname);
  if (batpathlen + 1 + sizeof("/energy_full") >= sizeof(batpath)) {
    statusError("status_battery",
                "batpath buffer too small",
                batname);
    return;
  }
  strcpy(batpath, POWER_BASEDIR);
  strcat(batpath, batname);


  /* Is the battery present? */
  if (access(batpath, F_OK)) {
    //printf(" ^fg(grey)[%s] ", batname);
    return;
  }


  /* Get info */
  strcpy(&batpath[batpathlen], "/energy_now");
  stlen = fileRead(stline, sizeof(stline), batpath);
  if (stlen > 0) {
    chargeNow = atoi(stline);
  }

  strcpy(&batpath[batpathlen], "/energy_full");
  stlen = fileRead(stline, sizeof(stline), batpath);
  if (stlen > 0) {
    chargeFull = atoi(stline);
  }

  strcpy(&batpath[batpathlen], "/power_now");
  stlen = fileRead(stline, sizeof(stline), batpath);
  if (stlen > 0) {
    battW = atoi(stline);
  }


  /* Prettyprint */
  if (chargeFull > 0) {
    chargePercent = chargeNow / (chargeFull / 100);
  }

  if (chargePercent <= 40) {
    if (chargePercent <= 25) {
      if (chargePercent <= 10) {
        s.color = "red";
      } else {
        // 11-25%
        s.color = "orange";
      }
    } else {
      // 26-40%
      s.color = "yellow";
    }
  } else {
    if (chargePercent > 70) {
      s.color = "white";
    } else {
      // 41-70%
      s.color = "green";
    }
  }

  battTime = (float)chargeNow / (float)battW;

  if (battW == 0) {
    // fully charged and not in use
    snprintf(text, sizeof(text), "%s: %d%% _ _",
              batname, chargePercent);
  } else {
    snprintf(text, sizeof(text), "%s: %d%% %.1fh %.1fW",
              batname, chargePercent, battTime, (float)battW / 1000000.0);
  }

  line_append_item(g, &s);
}