Battery.c 1.81 KB
Newer Older
1
2
3
4
5
6
7
8
9
/*
htop - openbsd/Battery.c
(C) 2015 Hisham H. Muhammad
(C) 2015 Michael McConville
Released under the GNU GPL, see the COPYING file
in the source distribution for its full text.
*/

#include "BatteryMeter.h"
nerd972's avatar
nerd972 committed
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <sys/sysctl.h>
#include <sys/sensors.h>
#include <errno.h>

static bool findDevice(const char* name, int* mib, struct sensordev* snsrdev, size_t* sdlen) {
   for (int devn = 0;; devn++) {
      mib[2] = devn;
      if (sysctl(mib, 3, snsrdev, sdlen, NULL, 0) == -1) {
         if (errno == ENXIO)
            continue;
         if (errno == ENOENT)
            return false;
      }
      if (strcmp(name, snsrdev->xname) == 0) {
         return true;
      }
   }
}
28
29

void Battery_getData(double* level, ACPresence* isOnAC) {
nerd972's avatar
nerd972 committed
30
31
32
33
34
35
36
37
   static int mib[] = {CTL_HW, HW_SENSORS, 0, 0, 0};
   struct sensor s;
   size_t slen = sizeof(struct sensor);
   struct sensordev snsrdev;
   size_t sdlen = sizeof(struct sensordev);

   bool found = findDevice("acpibat0", mib, &snsrdev, &sdlen);
   
38
   *level = -1;
nerd972's avatar
nerd972 committed
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
   if (found) {
      /* last full capacity */
      mib[3] = 7;
      mib[4] = 0;
      double last_full_capacity = 0;
      if (sysctl(mib, 5, &s, &slen, NULL, 0) != -1) {
         last_full_capacity = s.value;
      }
      if (last_full_capacity > 0) {
         /*  remaining capacity */
         mib[3] = 7;
         mib[4] = 3;
         if (sysctl(mib, 5, &s, &slen, NULL, 0) != -1) {
            double charge = s.value;
            *level = 100*(charge / last_full_capacity);
            if (charge >= last_full_capacity) {
               *level = 100;
            }
         }
      }
   }
   
   found = findDevice("acpiac0", mib, &snsrdev, &sdlen);
   
63
   *isOnAC = AC_ERROR;
nerd972's avatar
nerd972 committed
64
65
66
67
68
69
70
   if (found) {
      mib[3] = 9;
      mib[4] = 0;
      if (sysctl(mib, 5, &s, &slen, NULL, 0) != -1) {
         *isOnAC = s.value;
      }
   }
71
}