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