chiark / gitweb /
actually reads /proc - compiles but untested
authorianmdlvl <ianmdlvl>
Sat, 11 Dec 2004 19:19:16 +0000 (19:19 +0000)
committerianmdlvl <ianmdlvl>
Sat, 11 Dec 2004 19:19:16 +0000 (19:19 +0000)
cprogs/xacpi-simple.c

index bb5cb65..687127a 100644 (file)
@@ -1,13 +1,36 @@
 /*
+ * display outputs, per line:
+ *
+ *    Remaining: | Empty:   | Degraded:
+ *     green     |  red     |  black      discharging
+ *     blue      |  red     |  black      charging
+ *     cyan      |  red     |  black      charged
+ *     grey      |  red     |  black      charging&discharching!
+ *     green     |  yellow  |  black      discharging - low!
+ *     blue      |  yellow  |  black      charging - low
+ *     cyan      |  yellow  |  black      charged - low [1]
+ *     grey      |  yellow  |  black      charging&discharching! - low [1]
+ *       ...  dark grey  ...              no batteries present
+ *
+ * [1] battery must be quite badly degraded
  */
 
 #include <stdio.h>
+#include <assert.h>
 #include <math.h>
 #include <stdlib.h>
+#include <string.h>
+#include <errno.h>
 #include <unistd.h>
+#include <ctype.h>
+
+#include <sys/types.h>
+#include <dirent.h>
 
 #include <X11/Xlib.h>
 
+/*---------- general utility stuff and declarations ----------*/
+
 static void fail(const char *m) {
   fprintf(stderr,"error: %s\n", m);
   sleep(5);
@@ -15,29 +38,332 @@ static void fail(const char *m) {
 }
 static void badusage(void) { fail("bad usage"); }
 
-static Display *d;
-static Window w;
+#define CHGST_DISCHARGING 0 /* Reflects order in E(state,charging_state)  */
+#define CHGST_CHARGING    1 /*  in fields table.  Also, much code assumes */
+#define CHGST_CHARGED     2 /*  exactly these three possible states.      */
+
+/*---------- structure of and results from /proc/acpi/battery/... ----------*/
+/* variables thisbat_... are the results from readbattery();
+ * if readbattery() succeeds they are all valid and not VAL_NOTFOUND
+ */
+
+typedef struct batinfo_field {
+  const char *file;
+  const char *label;
+  unsigned long *valuep;
+  const char *unit;
+  const char *enumarray[10];
+} batinfo_field;
+
+#define QUANTITY_FIELDS                                \
+  QF(info,  design_capacity, "mWh")            \
+  QF(info,  last_full_capacity, "mWh")         \
+  QF(state, present_rate,       "mW")          \
+  QF(state, remaining_capacity, "mWh")         \
+  QF(alarm, alarm,              "mWh")
+
+#define QF(f,l,u) static unsigned long thisbat_##f##_##l;
+  QUANTITY_FIELDS
+#undef QF
+
+static unsigned long thisbat_info_present, thisbat_state_present;
+static unsigned long thisbat_state_charging_state;
+
+#define VAL_NOTFOUND (~0UL)
+
+static const batinfo_field fields[]= {
+#define E(f,l)       #f, #l, &thisbat_##f##_##l, 0
+#define QF(f,l,u)  { #f, #l, &thisbat_##f##_##l, u },
+  { E(info, present),            { "no", "yes" }                    },
+  { E(state,present),            { "no", "yes" }                    },
+  { E(state,charging_state),     { "discharging charging charged" } },
+  QUANTITY_FIELDS           /* take care re charging_state values order -  */
+  { 0 }                     /* if you must change it, search for CHGST_... */
+#undef E
+#undef QF
+};
+
+static const char *files[]= { "info", "state", "alarm" };
+
+/*---------- parsing of one battery in /proc/acpi/battery/... ----------*/
+
+/* variables private to the parser and its error handlers */
+static char batlinebuf[1000];
+static FILE *batfile;
+static const char *batdirname;
+static const char *batfilename;
+static const char *batlinevalue;
+
+static int batfailf(const char *why) {
+  if (batlinevalue) {
+    fprintf(stderr,"battery/%s/%s: %s value `%s': %s\n",
+           batdirname,batfilename, batlinebuf,batlinevalue,why);
+  } else {
+    fprintf(stderr,"battery/%s/%s: %s: `%s'\n",
+           batdirname,batfilename, why, batlinebuf);
+  }
+  return -1;
+}
+
+static int batfaile(const char *syscall, const char *target) {
+  fprintf(stderr,"battery/%s: failed to %s %s: %s\n",
+         batdirname ? batdirname : "*", syscall, target, strerror(errno));
+  return -1;
+}
+
+static void chdir_base(void) {
+  int r;
+  
+  r= chdir("/proc/acpi/battery");
+  if (r) batfaile("chdir","/proc/acpi/battery");
+}
+
+static void tidybattery(void) {
+  if (batfile) { fclose(batfile); batfile=0; }
+  if (batdirname) { chdir_base(); batdirname=0; }
+}
+
+static int readbattery(void) { /* 0=>ok, -1=>couldn't */
+  const batinfo_field *field;
+  const char *const *cfilename, *const *enumsearch;
+  char *colon, *ep;
+  int r, l, missing;
+  
+  r= chdir(batdirname);
+  if (r) return batfaile("chdir",batdirname);
+
+  for (field=fields; field->file; field++)
+    *field->valuep= VAL_NOTFOUND;
+
+  for (cfilename=files;
+       (batfilename= *cfilename);
+       cfilename++) {
+    batfile= fopen(batfilename,"r");
+    if (!batfile) return batfaile("open",batfilename);
+
+    for (;;) {
+      batlinevalue= 0;
+      
+      fgets(batlinebuf,sizeof(batlinebuf),batfile);
+      if (ferror(batfile)) return batfaile("read",batfilename);
+      l= strlen(batlinebuf);
+      if (l==0 && feof(batfile)) break;
+      assert(l>0);
+      if (batlinebuf[l-1] != '\n')
+       return batfailf("line too long");
+      batlinebuf[l-1]= 0;
+      colon= strchr(batlinebuf,':');
+      if (!colon)
+       return batfailf("line without a colon");
+      *colon= 0;
+
+      for (field=fields; ; field++) {
+       if (!strcmp(field->file,batfilename) &&
+           !strcmp(field->label,batlinebuf))
+         goto label_interesting;
+      }
+      continue;
+
+    label_interesting:
+      for (batlinevalue= colon+1;
+          *batlinevalue && isspace((unsigned char)*batlinevalue);
+          batlinevalue++);
+
+      if (field->unit) {
+
+       *field->valuep= strtoul(batlinevalue,&ep,10);
+       if (ep==batlinevalue || *ep!=' ')
+         batfailf("value number syntax incorrect");
+       if (strcmp(ep+1,field->unit)) batfailf("incorrect unit");
+
+      } else {
+       
+       for (*field->valuep=0, enumsearch=field->enumarray;
+            *enumsearch && strcmp(*enumsearch,batlinevalue);
+            (*field->valuep)++, enumsearch++);
+       if (!*enumsearch)
+         batfailf("unknown enum value");
+
+      }
+    }
+
+    fclose(batfile);
+    batfile= 0;
+  }
+
+  r= chdir(batdirname);
+  if (r) return batfaile("chdir","..");
+  batdirname= 0;
+
+  for (field=fields, missing=0;
+       field->file;
+       field++) {
+    if (*field->valuep == VAL_NOTFOUND) {
+      fprintf(stderr,"battery/%s/%s: %s: not found\n",
+             batdirname, field->file,field->label);
+      missing++;
+    }
+  }
+  if (missing) return -1;
+
+  return 0;
+}   
+
+/*---------- data collection and analysis ----------*/
+
+/* These next three variables are the results of the charging state */
+static unsigned charging_state_mask; /* 1u<<CHGST_* | ... */
+static double nondegraded_norm, fill_norm, ratepersec_norm;
+static int alarm_level; /* 0=ok, 1=low */
+
+#define QF(f,l,u) \
+  static double total_##f##_##l;
+  QUANTITY_FIELDS
+#undef QF
+
+static void acquiredata(void) {
+  DIR *di;
+  struct dirent *de;
+  int r;
+  
+  charging_state_mask= 0;
+
+#define QF(f,l,u) \
+  total_##f##_##l= 0;
+  QUANTITY_FIELDS
+#undef QF
+
+  di= opendir(".");  if (!di) batfaile("opendir","battery");
+  while ((de= readdir(di))) {
+    if (de->d_name[0]==0 || de->d_name[0]=='.') continue;
+
+    batdirname= de->d_name;
+    r= readbattery();
+    tidybattery();
+
+    if (r) continue;
+
+    if (!thisbat_info_present || !thisbat_state_present) {
+      printf("battery/%s not present\n",de->d_name);
+      continue;
+    }
+
+    charging_state_mask |= 1u << thisbat_state_charging_state;
+
+#define QF(f,l,u) \
+    total_##f##_##l += thisbat_##f##_##l;
+    QUANTITY_FIELDS
+#undef QF
+
+    if (thisbat_state_charging_state == CHGST_DISCHARGING)
+      /* negate it */
+      total_state_present_rate -= 2.0 * thisbat_state_present_rate;
+      
+  }
+  closedir(di);
+
+  if (total_info_design_capacity < 0.5)
+    total_info_design_capacity= 1.0;
+
+  if (total_info_last_full_capacity < total_state_remaining_capacity)
+    total_info_last_full_capacity= total_state_remaining_capacity;
+  if (total_info_design_capacity < total_info_last_full_capacity)
+    total_info_design_capacity= total_info_last_full_capacity;
+
+  alarm_level=
+    (total_state_remaining_capacity < total_alarm_alarm &&
+     !(charging_state_mask & 1u << CHGST_CHARGING));
+
+  nondegraded_norm= total_info_last_full_capacity / total_info_design_capacity;
+  fill_norm= total_state_remaining_capacity / total_info_design_capacity;
+  ratepersec_norm=  total_state_present_rate
+    / (3600.0 * total_info_design_capacity);
+}
+
+static void initacquire(void) {
+  chdir_base();
+}  
+
+/*---------- display ----------*/
+
+#define TOP      60
+#define BOTTOM 3600
+
+#define COLOURS                                        \
+  C(black)                                     \
+  C(green)                                     \
+  C(red)                                       \
+  C(yellow)                                    \
+  C(blue)                                      \
+  C(cyan)                                      \
+  C(grey)                                      \
+  C(darkgrey)                                  \
+  GC(remain)                                   \
+  GC(empty)
+
+static Display *disp;
+static Window win;
 static int width, height;
-static GC gc_green, gc_red, gc_yellow, gc_blue;
 static Colormap cmap;
 static int screen;
+static unsigned long lastbackground;
 
-#define TOP      60
-#define BOTTOM 3600
+typedef struct {
+  GC gc;
+  unsigned long lastfg;
+} Gcstate;
+
+#define C(c) static unsigned long pix_##c;
+#define GC(g) static Gcstate gc_##g;
+  COLOURS
+#undef C
+#undef GC
 
 static void refresh(void);
 
-static void geometry(void) {
-  int dummy;
-  Window dummyw;
+#define CHGMASK_CHG_DIS (1u<<CHGST_CHARGING | 1u<<CHGST_DISCHARGING)
+
+static void setbackground(unsigned long newbg) {
+  int r;
   
-  XGetGeometry(d,w, &dummyw,&dummy,&dummy, &width,&height, &dummy,&dummy);
-  refresh();
+  if (newbg == lastbackground) return;
+  r= XSetWindowBackground(disp,win,newbg);
+  if (r) fail("XSetWindowBackground");
+  lastbackground= newbg;
 }
 
-static void show(double fill_norm, double ratepersec_norm, int ac) {
+static void setforeground(Gcstate *g, unsigned long px) {
+  XGCValues gcv;
+  int r;
+  
+  if (g->lastfg == px) return;
+  
+  memset(&gcv,0,sizeof(gcv));
+  g->lastfg= gcv.foreground= px;
+  r= XChangeGC(disp,g->gc,GCForeground,&gcv);
+  if (r) fail("XChangeGC");
+}
+
+static void show(void) {
   double elap, then;
-  int i, leftmost_lit;
+  int i, leftmost_lit, leftmost_nondeg;
+
+  if (!charging_state_mask) {
+    setbackground(pix_darkgrey);
+    XClearWindow(disp,win);
+    return;
+  }
+
+  setbackground(pix_black);
+  XClearWindow(disp,win);
+  
+  setforeground(&gc_remain,
+               !(charging_state_mask & CHGMASK_CHG_DIS) ? pix_cyan :
+               !(~charging_state_mask & CHGMASK_CHG_DIS) ? pix_grey :
+               charging_state_mask & (1u<<CHGST_CHARGING)
+               ? pix_blue : pix_green);
+               
+  setforeground(&gc_empty, alarm_level ? pix_yellow : pix_red);
 
   for (i=0; i<height; i++) {
     elap= !i ? 0 :
@@ -45,63 +371,93 @@ static void show(double fill_norm, double ratepersec_norm, int ac) {
       TOP * exp( (double)i / (height-2) * log( (double)BOTTOM/TOP ) );
     
     then= fill_norm + ratepersec_norm * elap;
+    if (then <= 0.0) then= 0.0;
+    else if (then >= nondegraded_norm) then= nondegraded_norm;
 
-    leftmost_lit= then <= 0 ? -1 :
-      then >= 1.0 ? width :
-      width * then;
+    leftmost_lit= width * then;
+    leftmost_nondeg= width * nondegraded_norm;
 
     if (leftmost_lit >= 0)
-      XDrawLine(d, w, ac ? gc_blue : gc_green, 0,i, leftmost_lit,i);
-    if (leftmost_lit < width)
-      XDrawLine(d, w, then >= 0 ? gc_red : gc_yellow,
-               leftmost_lit+1,i, width,i);
+      XDrawLine(disp, win, gc_remain.gc, 0,i, leftmost_lit,i);
+    if (leftmost_lit < leftmost_nondeg)
+      XDrawLine(disp, win, gc_empty.gc,
+               leftmost_lit+1,i, leftmost_nondeg,i);
   }
 }
 
-static void refresh(void) {
-  show(0.3, 0.5/3600, 1);
+static void initgc(Gcstate *gc_r) {
+  XGCValues gcv;
+
+  memset(&gcv,0,sizeof(gcv));
+  gcv.function= GXcopy;
+  gcv.line_width= 1;
+  gc_r->lastfg= gcv.foreground= pix_black;
+  gc_r->gc= XCreateGC(disp,win, GCFunction|GCLineWidth|GCForeground, &gcv);
 }
 
-static void colour(GC *gc_r, const char *name) {
+static void colour(unsigned long *pix_r, const char *name) {
   XColor xc;
   Status st;
-  XGCValues gcv;
   
-  st= XAllocNamedColor(d,cmap,name,&xc,&xc);
+  st= XAllocNamedColor(disp,cmap,name,&xc,&xc);
   if (!st) fail("couldn't allocate colour");
   
-  gcv.function= GXcopy;
-  gcv.line_width= 1;
-  gcv.foreground= xc.pixel;
-  *gc_r= XCreateGC(d,w, GCFunction|GCForeground|GCLineWidth, &gcv);
+  *pix_r= xc.pixel;
 }
 
-int main(int argc, const char *const *argv) {
-  XEvent ev;
+static void initgraphics(void) {
+  int r;
   
-  d= XOpenDisplay(0); if (!d) fail("could not open display");
+  disp= XOpenDisplay(0); if (!disp) fail("could not open display");
 
-  if (!argv[0] || argv[1])
-    badusage();
+  screen= DefaultScreen(disp);
+  win= XCreateSimpleWindow(disp,DefaultRootWindow(disp),0,0,100,20,0,0,0);
+  cmap= DefaultColormap(disp,screen);
+  
+#define C(c) colour(&pix_##c, #c);
+#define GC(g) initgc(&gc_##g);
+  COLOURS
+#undef C
+#undef GC
 
-  screen= DefaultScreen(d);
+  r= XSetWindowBackground(disp,win,pix_black);
+  if (r) fail("init set background");
+  lastbackground= pix_black;
 
-  w= XCreateSimpleWindow(d,DefaultRootWindow(d),0,0,100,20,0,0,0);
+  XSelectInput(disp,win, ExposureMask|VisibilityChangeMask);
+  XMapWindow(disp,win);
+}
+static void refresh(void) {
+  acquiredata();
+  show();
+}
 
-  cmap= DefaultColormap(d,screen);
+static void newgeometry(void) {
+  int dummy;
+  Window dummyw;
   
-  colour(&gc_green,  "green");
-  colour(&gc_red,    "red");
-  colour(&gc_yellow, "yellow");
-  colour(&gc_blue,   "blue");
+  XGetGeometry(disp,win, &dummyw,&dummy,&dummy, &width,&height, &dummy,&dummy);
+  refresh();
+}
 
-  XSelectInput(d,w, ExposureMask|VisibilityChangeMask);
-  XMapWindow(d,w);
+static void eventloop(void) {
+  XEvent ev;
   
-  geometry();
+  newgeometry();
   
   for (;;) {
-    XNextEvent(d,&ev);
-    geometry();
+    XNextEvent(disp,&ev);
+    newgeometry();
   }
 }
+
+int main(int argc, const char *const *argv) {
+  if (!argv[0] || argv[1])
+    badusage();
+
+  initacquire();
+  initgraphics();
+  eventloop();
+  return 0;
+}