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