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