chiark / gitweb /
37a2e31d2f4368eaf620ee6212546162903312b0
[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 TIMEOUT 5000 /* milliseconds */
34
35 /*---------- general utility stuff and declarations ----------*/
36
37 static void fail(const char *m) {
38   fprintf(stderr,"error: %s\n", m);
39   exit(-1);
40 }
41 static void badusage(void) { fail("bad usage"); }
42
43 #define CHGST_DISCHARGING 0 /* Reflects order in E(state,charging_state)  */
44 #define CHGST_CHARGING    1 /*  in fields table.  Also, much code assumes */
45 #define CHGST_CHARGED     2 /*  exactly these three possible states.      */
46
47 /*---------- structure of and results from /proc/acpi/battery/... ----------*/
48 /* variables thisbat_... are the results from readbattery();
49  * if readbattery() succeeds they are all valid and not VAL_NOTFOUND
50  */
51
52 typedef struct batinfo_field {
53   const char *file;
54   const char *label;
55   unsigned long *valuep;
56   const char *unit;
57   const char *enumarray[10];
58 } batinfo_field;
59
60 #define QUANTITY_FIELDS                         \
61   QF(info,  design_capacity,    "mWh")          \
62   QF(info,  last_full_capacity, "mWh")          \
63   QF(state, present_rate,       "mW")           \
64   QF(state, remaining_capacity, "mWh")          \
65   QF(alarm, alarm,              "mWh")
66
67 #define QF(f,l,u) static unsigned long thisbat_##f##_##l;
68   QUANTITY_FIELDS
69 #undef QF
70
71 static unsigned long thisbat_info_present, thisbat_state_present;
72 static unsigned long thisbat_state_charging_state;
73
74 #define VAL_NOTFOUND (~0UL)
75
76 static const batinfo_field fields[]= {
77 #define E(f,l)       #f, #l, &thisbat_##f##_##l, 0
78 #define QF(f,l,u)  { #f, #l, &thisbat_##f##_##l, u },
79   { E(info, present),            { "no", "yes" }                          },
80   { E(state,present),            { "no", "yes" }                          },
81   { E(state,charging_state),     { "discharging", "charging", "charged" } },
82   QUANTITY_FIELDS           /* take care re charging_state values order -  */
83   { 0 }                     /* if you must change it, search for CHGST_... */
84 #undef E
85 #undef QF
86 };
87
88 static const char *files[]= { "info", "state", "alarm" };
89
90 /*---------- parsing of one battery in /proc/acpi/battery/... ----------*/
91
92 /* variables private to the parser and its error handlers */
93 static char batlinebuf[1000];
94 static FILE *batfile;
95 static const char *batdirname;
96 static const char *batfilename;
97 static const char *batlinevalue;
98
99 static int batfailf(const char *why) {
100   if (batlinevalue) {
101     fprintf(stderr,"battery/%s/%s: %s value `%s': %s\n",
102             batdirname,batfilename, batlinebuf,batlinevalue,why);
103   } else {
104     fprintf(stderr,"battery/%s/%s: %s: `%s'\n",
105             batdirname,batfilename, why, batlinebuf);
106   }
107   return -1;
108 }
109
110 static int batfaile(const char *syscall, const char *target) {
111   fprintf(stderr,"battery/%s: failed to %s %s: %s\n",
112           batdirname ? batdirname : "*", syscall, target, strerror(errno));
113   return -1;
114 }
115
116 static void chdir_base(void) {
117   int r;
118   
119   r= chdir("/proc/acpi/battery");
120   if (r) batfaile("chdir","/proc/acpi/battery");
121 }
122
123 static void tidybattery(void) {
124   if (batfile) { fclose(batfile); batfile=0; }
125   if (batdirname) { chdir_base(); batdirname=0; }
126 }
127
128 static int readbattery(void) { /* 0=>ok, -1=>couldn't */
129   const batinfo_field *field;
130   const char *const *cfilename, *const *enumsearch;
131   char *colon, *ep, *sr, *p;
132   int r, l, missing;
133   
134   r= chdir(batdirname);
135   if (r) return batfaile("chdir",batdirname);
136
137   for (field=fields; field->file; field++)
138     *field->valuep= VAL_NOTFOUND;
139
140   for (cfilename=files;
141        (batfilename= *cfilename);
142        cfilename++) {
143     batfile= fopen(batfilename,"r");
144     if (!batfile) return batfaile("open",batfilename);
145
146     for (;;) {
147       batlinevalue= 0;
148       
149       sr= fgets(batlinebuf,sizeof(batlinebuf),batfile);
150       if (ferror(batfile)) return batfaile("read",batfilename);
151       if (!sr && feof(batfile)) break;
152       l= strlen(batlinebuf);
153       assert(l>0);
154       if (batlinebuf[l-1] != '\n')
155         return batfailf("line too long");
156       batlinebuf[l-1]= 0;
157       colon= strchr(batlinebuf,':');
158       if (!colon)
159         return batfailf("line without a colon");
160       *colon= 0;
161
162       for (p=batlinebuf; p<colon; p++)
163         if (*p == ' ')
164           *p= '_';
165
166       for (field=fields; field->file; field++) {
167         if (!strcmp(field->file,batfilename) &&
168             !strcmp(field->label,batlinebuf))
169           goto label_interesting;
170       }
171       continue;
172
173     label_interesting:
174       for (batlinevalue= colon+1;
175            *batlinevalue && isspace((unsigned char)*batlinevalue);
176            batlinevalue++);
177
178       if (field->unit) {
179
180         *field->valuep= strtoul(batlinevalue,&ep,10);
181         if (ep==batlinevalue || *ep!=' ')
182           batfailf("value number syntax incorrect");
183         if (strcmp(ep+1,field->unit)) batfailf("incorrect unit");
184
185       } else {
186         
187         for (*field->valuep=0, enumsearch=field->enumarray;
188              *enumsearch && strcmp(*enumsearch,batlinevalue);
189              (*field->valuep)++, enumsearch++);
190         if (!*enumsearch)
191           batfailf("unknown enum value");
192
193       }
194     }
195
196     fclose(batfile);
197     batfile= 0;
198   }
199
200   r= chdir("..");
201   if (r) return batfaile("chdir","..");
202   batdirname= 0;
203
204   for (field=fields, missing=0;
205        field->file;
206        field++) {
207     if (*field->valuep == VAL_NOTFOUND) {
208       fprintf(stderr,"battery/%s/%s: %s: not found\n",
209               batdirname, field->file,field->label);
210       missing++;
211     }
212   }
213   if (missing) return -1;
214
215   return 0;
216 }   
217
218 /*---------- data collection and analysis ----------*/
219
220 /* These next three variables are the results of the charging state */
221 static unsigned charging_state_mask; /* 1u<<CHGST_* | ... */
222 static double nondegraded_norm, fill_norm, ratepersec_norm;
223 static int alarm_level; /* 0=ok, 1=low */
224
225 #define QF(f,l,u) \
226   static double total_##f##_##l;
227   QUANTITY_FIELDS
228 #undef QF
229
230 static void acquiredata(void) {
231   DIR *di;
232   struct dirent *de;
233   int r;
234   
235   charging_state_mask= 0;
236
237 #define QF(f,l,u) \
238   total_##f##_##l= 0;
239   QUANTITY_FIELDS
240 #undef QF
241
242   di= opendir(".");  if (!di) batfaile("opendir","battery");
243   while ((de= readdir(di))) {
244     if (de->d_name[0]==0 || de->d_name[0]=='.') continue;
245
246     batdirname= de->d_name;
247     r= readbattery();
248     tidybattery();
249
250     if (r) continue;
251
252     if (!thisbat_info_present || !thisbat_state_present) {
253       printf("battery/%s not present\n",de->d_name);
254       continue;
255     }
256
257     charging_state_mask |= 1u << thisbat_state_charging_state;
258
259 #define QF(f,l,u) \
260     total_##f##_##l += thisbat_##f##_##l;
261     QUANTITY_FIELDS
262 #undef QF
263
264     if (thisbat_state_charging_state == CHGST_DISCHARGING)
265       /* negate it */
266       total_state_present_rate -= 2.0 * thisbat_state_present_rate;
267       
268   }
269   closedir(di);
270
271   if (total_info_design_capacity < 0.5)
272     total_info_design_capacity= 1.0;
273
274   if (total_info_last_full_capacity < total_state_remaining_capacity)
275     total_info_last_full_capacity= total_state_remaining_capacity;
276   if (total_info_design_capacity < total_info_last_full_capacity)
277     total_info_design_capacity= total_info_last_full_capacity;
278
279   alarm_level=
280     (total_state_remaining_capacity < total_alarm_alarm &&
281      !(charging_state_mask & 1u << CHGST_CHARGING));
282
283   nondegraded_norm= total_info_last_full_capacity / total_info_design_capacity;
284   fill_norm= total_state_remaining_capacity / total_info_design_capacity;
285   ratepersec_norm=  total_state_present_rate
286     / (3600.0 * total_info_design_capacity);
287 }
288
289 static void initacquire(void) {
290   chdir_base();
291 }  
292
293 /*---------- display ----------*/
294
295 #define TOP      60
296 #define BOTTOM 3600
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|VisibilityChangeMask);
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   int *fds, nfds, npfds, *fdp, i, r;
469   struct pollfd *pfds, *pfd;
470   
471   newgeometry();
472
473   npfds= 0;
474   pfds= 0;
475   for (;;) {
476     r= XInternalConnectionNumbers(disp, &fds, &nfds);
477     if (!r) fail("XInternalConnectionNumbers");
478
479     if (npfds != nfds) {
480       pfds= realloc(pfds, sizeof(*pfds) * nfds);
481       if (!pfds) failr("realloc for pollfds",errno);
482       npfds= nfds;
483     }
484     for (i=0, pfd=pfds, fdp=fds;
485          i<nfds;
486          i++, pfd++, fdp++) {
487       pfd->fd= *fdp;
488       pfd->events= POLLIN|POLLERR;
489     }
490     XFree(fds);
491
492     r= poll(pfds,npfds,TIMEOUT);
493     if (r==-1) failr("poll",errno);
494
495     for (i=0, pfd=pfds;
496          i<nfds;
497          i++, pfd++) {
498       if (pfd->revents)
499         XProcessInternalConnection(disp,pfd->fd);
500     }
501
502     while (XPending(disp)) {
503       XNextEvent(disp,&ev);
504       if (ev.type == ConfigureNotify)
505         newgeometry();
506     }
507     
508     refresh();
509   }
510 }
511
512 int main(int argc, const char *const *argv) {
513   if (!argv[0] || argv[1])
514     badusage();
515
516   initacquire();
517   initgraphics();
518   eventloop();
519   return 0;
520 }