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