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