chiark / gitweb /
50b7965bee5dfdcc016fde3dfdb63187b21205ef
[chiark-utils.git] / cprogs / xacpi-simple.c
1 /*
2  * display outputs, per line:
3  *
4  *   Remaining: | Empty:        | Degraded:
5  *     blue     |  black        |  dimgrey      discharging
6  *     green    |  black        |  dimgrey      charging
7  *     cyan     |  black        |  dimgrey      charged
8  *     grey     |  black        |  dimgrey      charging&discharching!
9  *     blue     |  red          |  dimgrey      discharging - low!
10  *     green    |  red          |  dimgrey      charging - low
11  *     cyan     |  red          |  dimgrey      charged - low [1]
12  *     grey     |  red          |  dimgrey      charging&discharching, low [1]
13  *       ...  darkmagenta  ...                  no batteries present
14  *
15  * [1] battery must be quite badly degraded
16  */
17
18 #include <stdio.h>
19 #include <assert.h>
20 #include <math.h>
21 #include <stdlib.h>
22 #include <string.h>
23 #include <errno.h>
24 #include <unistd.h>
25 #include <ctype.h>
26
27 #include <sys/poll.h>
28 #include <sys/types.h>
29 #include <dirent.h>
30
31 #include <X11/Xlib.h>
32
33 #define TOP      60
34 #define BOTTOM 3600
35
36 #define TIMEOUT 5000 /* milliseconds */
37
38 /*---------- general utility stuff and declarations ----------*/
39
40 static void fail(const char *m) {
41   fprintf(stderr,"error: %s\n", m);
42   exit(-1);
43 }
44 static void badusage(void) { fail("bad usage"); }
45
46 #define CHGST_DISCHARGING 0 /* Reflects order in E(state,charging_state)  */
47 #define CHGST_CHARGING    1 /*  in fields table.  Also, much code assumes */
48 #define CHGST_CHARGED     2 /*  exactly these three possible states.      */
49
50 /*---------- structure of and results from /proc/acpi/battery/... ----------*/
51 /* variables thisbat_... are the results from readbattery();
52  * if readbattery() succeeds they are all valid and not VAL_NOTFOUND
53  */
54
55 typedef struct batinfo_field {
56   const char *file;
57   const char *label;
58   unsigned long *valuep;
59   const char *unit;
60   const char *enumarray[10];
61 } batinfo_field;
62
63 #define QUANTITY_FIELDS                         \
64   QF(info,  design_capacity,    "mWh")          \
65   QF(info,  last_full_capacity, "mWh")          \
66   QF(state, present_rate,       "mW")           \
67   QF(state, remaining_capacity, "mWh")          \
68   QF(alarm, alarm,              "mWh")
69
70 #define QF(f,l,u) static unsigned long thisbat_##f##_##l;
71   QUANTITY_FIELDS
72 #undef QF
73
74 static unsigned long thisbat_info_present, thisbat_state_present;
75 static unsigned long thisbat_state_charging_state;
76
77 #define VAL_NOTFOUND (~0UL)
78
79 static const batinfo_field fields[]= {
80 #define E(f,l)       #f, #l, &thisbat_##f##_##l, 0
81 #define QF(f,l,u)  { #f, #l, &thisbat_##f##_##l, u },
82   { E(info, present),            { "no", "yes" }                          },
83   { E(state,present),            { "no", "yes" }                          },
84   { E(state,charging_state),     { "discharging", "charging", "charged" } },
85   QUANTITY_FIELDS           /* take care re charging_state values order -  */
86   { 0 }                     /* if you must change it, search for CHGST_... */
87 #undef E
88 #undef QF
89 };
90
91 static const char *files[]= { "info", "state", "alarm" };
92
93 /*---------- parsing of one battery in /proc/acpi/battery/... ----------*/
94
95 /* variables private to the parser and its error handlers */
96 static char batlinebuf[1000];
97 static FILE *batfile;
98 static const char *batdirname;
99 static const char *batfilename;
100 static const char *batlinevalue;
101
102 static int batfailf(const char *why) {
103   if (batlinevalue) {
104     fprintf(stderr,"battery/%s/%s: %s value `%s': %s\n",
105             batdirname,batfilename, batlinebuf,batlinevalue,why);
106   } else {
107     fprintf(stderr,"battery/%s/%s: %s: `%s'\n",
108             batdirname,batfilename, why, batlinebuf);
109   }
110   return -1;
111 }
112
113 static int batfaile(const char *syscall, const char *target) {
114   fprintf(stderr,"battery/%s: failed to %s %s: %s\n",
115           batdirname ? batdirname : "*", syscall, target, strerror(errno));
116   return -1;
117 }
118
119 static void chdir_base(void) {
120   int r;
121   
122   r= chdir("/proc/acpi/battery");
123   if (r) batfaile("chdir","/proc/acpi/battery");
124 }
125
126 static void tidybattery(void) {
127   if (batfile) { fclose(batfile); batfile=0; }
128   if (batdirname) { chdir_base(); batdirname=0; }
129 }
130
131 static int readbattery(void) { /* 0=>ok, -1=>couldn't */
132   const batinfo_field *field;
133   const char *const *cfilename, *const *enumsearch;
134   char *colon, *ep, *sr, *p;
135   int r, l, missing;
136   
137   r= chdir(batdirname);
138   if (r) return batfaile("chdir",batdirname);
139
140   for (field=fields; field->file; field++)
141     *field->valuep= VAL_NOTFOUND;
142
143   for (cfilename=files;
144        (batfilename= *cfilename);
145        cfilename++) {
146     batfile= fopen(batfilename,"r");
147     if (!batfile) return batfaile("open",batfilename);
148
149     for (;;) {
150       batlinevalue= 0;
151       
152       sr= fgets(batlinebuf,sizeof(batlinebuf),batfile);
153       if (ferror(batfile)) return batfaile("read",batfilename);
154       if (!sr && feof(batfile)) break;
155       l= strlen(batlinebuf);
156       assert(l>0);
157       if (batlinebuf[l-1] != '\n')
158         return batfailf("line too long");
159       batlinebuf[l-1]= 0;
160       colon= strchr(batlinebuf,':');
161       if (!colon)
162         return batfailf("line without a colon");
163       *colon= 0;
164
165       for (p=batlinebuf; p<colon; p++)
166         if (*p == ' ')
167           *p= '_';
168
169       for (field=fields; field->file; field++) {
170         if (!strcmp(field->file,batfilename) &&
171             !strcmp(field->label,batlinebuf))
172           goto label_interesting;
173       }
174       continue;
175
176     label_interesting:
177       for (batlinevalue= colon+1;
178            *batlinevalue && isspace((unsigned char)*batlinevalue);
179            batlinevalue++);
180
181       if (field->unit) {
182
183         *field->valuep= strtoul(batlinevalue,&ep,10);
184         if (ep==batlinevalue || *ep!=' ')
185           batfailf("value number syntax incorrect");
186         if (strcmp(ep+1,field->unit)) batfailf("incorrect unit");
187
188       } else {
189         
190         for (*field->valuep=0, enumsearch=field->enumarray;
191              *enumsearch && strcmp(*enumsearch,batlinevalue);
192              (*field->valuep)++, enumsearch++);
193         if (!*enumsearch)
194           batfailf("unknown enum value");
195
196       }
197     }
198
199     fclose(batfile);
200     batfile= 0;
201   }
202
203   r= chdir("..");
204   if (r) return batfaile("chdir","..");
205   batdirname= 0;
206
207   for (field=fields, missing=0;
208        field->file;
209        field++) {
210     if (*field->valuep == VAL_NOTFOUND) {
211       fprintf(stderr,"battery/%s/%s: %s: not found\n",
212               batdirname, field->file,field->label);
213       missing++;
214     }
215   }
216   if (missing) return -1;
217
218   return 0;
219 }   
220
221 /*---------- data collection and analysis ----------*/
222
223 /* These next three variables are the results of the charging state */
224 static unsigned charging_state_mask; /* 1u<<CHGST_* | ... */
225 static double nondegraded_norm, fill_norm, ratepersec_norm;
226 static int alarm_level; /* 0=ok, 1=low */
227
228 #define QF(f,l,u) \
229   static double total_##f##_##l;
230   QUANTITY_FIELDS
231 #undef QF
232
233 static void acquiredata(void) {
234   DIR *di;
235   struct dirent *de;
236   int r;
237   
238   charging_state_mask= 0;
239
240 #define QF(f,l,u) \
241   total_##f##_##l= 0;
242   QUANTITY_FIELDS
243 #undef QF
244
245   di= opendir(".");  if (!di) batfaile("opendir","battery");
246   while ((de= readdir(di))) {
247     if (de->d_name[0]==0 || de->d_name[0]=='.') continue;
248
249     batdirname= de->d_name;
250     r= readbattery();
251     tidybattery();
252
253     if (r) continue;
254
255     if (!thisbat_info_present || !thisbat_state_present) {
256       printf("battery/%s not present\n",de->d_name);
257       continue;
258     }
259
260     charging_state_mask |= 1u << thisbat_state_charging_state;
261
262 #define QF(f,l,u) \
263     total_##f##_##l += thisbat_##f##_##l;
264     QUANTITY_FIELDS
265 #undef QF
266
267     if (thisbat_state_charging_state == CHGST_DISCHARGING)
268       /* negate it */
269       total_state_present_rate -= 2.0 * thisbat_state_present_rate;
270       
271   }
272   closedir(di);
273
274   if (total_info_design_capacity < 0.5)
275     total_info_design_capacity= 1.0;
276
277   if (total_info_last_full_capacity < total_state_remaining_capacity)
278     total_info_last_full_capacity= total_state_remaining_capacity;
279   if (total_info_design_capacity < total_info_last_full_capacity)
280     total_info_design_capacity= total_info_last_full_capacity;
281
282   alarm_level=
283     (total_state_remaining_capacity < total_alarm_alarm &&
284      !(charging_state_mask & 1u << CHGST_CHARGING));
285
286   nondegraded_norm= total_info_last_full_capacity / total_info_design_capacity;
287   fill_norm= total_state_remaining_capacity / total_info_design_capacity;
288   ratepersec_norm=  total_state_present_rate
289     / (3600.0 * total_info_design_capacity);
290 }
291
292 static void initacquire(void) {
293   chdir_base();
294 }  
295
296 /*---------- display ----------*/
297
298 #define COLOURS                                 \
299   C(dimgrey)                                    \
300   C(blue)                                       \
301   C(black)                                      \
302   C(red)                                        \
303   C(green)                                      \
304   C(cyan)                                       \
305   C(grey)                                       \
306   C(darkmagenta)                                \
307   C(white)                                      \
308   GC(remain)                                    \
309   GC(white)                                     \
310   GC(empty)
311
312 static Display *disp;
313 static Window win;
314 static int width, height;
315 static Colormap cmap;
316 static int screen;
317 static unsigned long lastbackground;
318
319 typedef struct {
320   GC gc;
321   unsigned long lastfg;
322 } Gcstate;
323
324 #define C(c) static unsigned long pix_##c;
325 #define GC(g) static Gcstate gc_##g;
326   COLOURS
327 #undef C
328 #undef GC
329
330 static void refresh(void);
331
332 #define CHGMASK_CHG_DIS (1u<<CHGST_CHARGING | 1u<<CHGST_DISCHARGING)
333
334 static void failr(const char *m, int r) {
335   fprintf(stderr,"error: %s (code %d)\n", m, r);
336   exit(-1);
337 }
338
339 static void setbackground(unsigned long newbg) {
340   int r;
341   
342   if (newbg == lastbackground) return;
343   r= XSetWindowBackground(disp,win,newbg);
344   if (r) failr("XSetWindowBackground",r);
345   lastbackground= newbg;
346 }
347
348 static void setforeground(Gcstate *g, unsigned long px) {
349   XGCValues gcv;
350   int r;
351   
352   if (g->lastfg == px) return;
353   
354   memset(&gcv,0,sizeof(gcv));
355   g->lastfg= gcv.foreground= px;
356   r= XChangeGC(disp,g->gc,GCForeground,&gcv);
357   if (!r) fail("XChangeGC");
358 }
359
360 static void show(void) {
361   double elap, then;
362   int i, leftmost_lit, leftmost_nondeg, beyond, first_beyond;
363
364   if (!charging_state_mask) {
365     setbackground(pix_darkmagenta);
366     XClearWindow(disp,win);
367     return;
368   }
369
370   setbackground(pix_dimgrey);
371   XClearWindow(disp,win);
372   
373   setforeground(&gc_remain,
374                 !(charging_state_mask & CHGMASK_CHG_DIS) ? pix_cyan :
375                 !(~charging_state_mask & CHGMASK_CHG_DIS) ? pix_grey :
376                 charging_state_mask & (1u<<CHGST_CHARGING)
377                 ? pix_green : pix_blue);
378                 
379   setforeground(&gc_empty, alarm_level ? pix_red : pix_black);
380
381   for (i=0, first_beyond=1; i<height; i++) {
382     elap= !i ? 0 :
383       height==2 ? BOTTOM :
384       TOP * exp( (double)i / (height-2) * log( (double)BOTTOM/TOP ) );
385     
386     then= fill_norm + ratepersec_norm * elap;
387
388     beyond=
389       ((charging_state_mask & (1u<<CHGST_DISCHARGING) && then <= 0.0) ||
390        (charging_state_mask & (1u<<CHGST_CHARGING) && then>=nondegraded_norm));
391
392     if (then <= 0.0) then= 0.0;
393     else if (then >= nondegraded_norm) then= nondegraded_norm;
394
395     leftmost_lit= width * then;
396     leftmost_nondeg= width * nondegraded_norm;
397
398     if (beyond && first_beyond) {
399       XDrawLine(disp, win, gc_white.gc, 0,i, leftmost_nondeg,i);
400       first_beyond= 0;
401     } else {
402       if (leftmost_lit < leftmost_nondeg)
403         XDrawLine(disp, win, gc_empty.gc,
404                   leftmost_lit,i, leftmost_nondeg,i);
405       if (leftmost_lit >= 0)
406         XDrawLine(disp, win, gc_remain.gc, 0,i, leftmost_lit,i);
407     }
408   }
409 }
410
411 static void initgc(Gcstate *gc_r) {
412   XGCValues gcv;
413
414   memset(&gcv,0,sizeof(gcv));
415   gcv.function= GXcopy;
416   gcv.line_width= 1;
417   gc_r->lastfg= gcv.foreground= pix_white;
418   gc_r->gc= XCreateGC(disp,win, GCFunction|GCLineWidth|GCForeground, &gcv);
419 }
420
421 static void colour(unsigned long *pix_r, const char *name) {
422   XColor xc;
423   Status st;
424   
425   st= XAllocNamedColor(disp,cmap,name,&xc,&xc);
426   if (!st) fail(name);
427   
428   *pix_r= xc.pixel;
429 }
430
431 static void initgraphics(void) {
432   int r;
433   
434   disp= XOpenDisplay(0); if (!disp) fail("could not open display");
435
436   screen= DefaultScreen(disp);
437   win= XCreateSimpleWindow(disp,DefaultRootWindow(disp),0,0,100,20,0,0,0);
438   cmap= DefaultColormap(disp,screen);
439   
440 #define C(c) colour(&pix_##c, #c);
441 #define GC(g) initgc(&gc_##g);
442   COLOURS
443 #undef C
444 #undef GC
445
446   r= XSetWindowBackground(disp,win,pix_dimgrey);
447   if (!r) fail("init set background");
448   lastbackground= pix_dimgrey;
449
450   XSelectInput(disp,win, ExposureMask|StructureNotifyMask);
451   XMapWindow(disp,win);
452 }
453  
454 static void refresh(void) {
455   acquiredata();
456   show();
457 }
458
459 static void newgeometry(void) {
460   int dummy;
461   Window dummyw;
462   
463   XGetGeometry(disp,win, &dummyw,&dummy,&dummy, &width,&height, &dummy,&dummy);
464 }
465
466 static void eventloop(void) {
467   XEvent ev;
468   struct pollfd pfd;
469   int r;
470   
471   newgeometry();
472   refresh();
473
474   for (;;) {
475     pfd.fd= ConnectionNumber(disp);
476     pfd.events= POLLIN|POLLERR;
477
478     r= poll(&pfd,1,TIMEOUT);
479     if (r==-1 && errno!=EINTR) failr("poll",errno);
480
481     while (XPending(disp)) {
482       XNextEvent(disp,&ev);
483       if (ev.type == ConfigureNotify) {
484         XConfigureEvent *ce= (void*)&ev;
485         width= ce->width;
486         height= ce->height;
487       }
488     }
489     
490     refresh();
491     XFlush(disp);
492   }
493 }
494
495 int main(int argc, const char *const *argv) {
496   if (!argv[0] || argv[1])
497     badusage();
498
499   initacquire();
500   initgraphics();
501   eventloop();
502   return 0;
503 }