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