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