2 * display outputs, per line:
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 * ... yellow ... error
16 * [1] battery must be quite badly degraded
29 #include <sys/types.h>
33 #include <X11/Xutil.h>
34 #include <X11/Xresource.h>
39 #define TIMEOUT 5000 /* milliseconds */
40 #define TIMEOUT_ONERROR 3333 /* milliseconds */
42 static const char program_name[]= "xacpi-simple";
44 /*---------- general utility stuff and declarations ----------*/
46 static void fail(const char *m) {
47 fprintf(stderr,"error: %s\n", m);
50 static void badusage(void) { fail("bad usage"); }
52 #define CHGST_DISCHARGING 0 /* Reflects order in E(state,charging_state) */
53 #define CHGST_CHARGING 1 /* in fields table. Also, much code assumes */
54 #define CHGST_CHARGED 2 /* exactly these three possible states. */
55 #define CHGST_ERROR 8 /* Except that this one is an extra bit. */
57 /*---------- structure of and results from /proc/acpi/battery/... ----------*/
58 /* variables thisbat_... are the results from readbattery();
59 * if readbattery() succeeds they are all valid and not VAL_NOTFOUND
62 typedef struct batinfo_field {
65 unsigned long *valuep;
67 const char *enumarray[10];
70 #define QUANTITY_FIELDS \
71 QF(info, design_capacity, "mWh") \
72 QF(info, last_full_capacity, "mWh") \
73 QF(state, present_rate, "mW") \
74 QF(state, remaining_capacity, "mWh") \
75 QF(alarm, alarm, "mWh")
77 #define QF(f,l,u) static unsigned long thisbat_##f##_##l;
81 static unsigned long thisbat_alarm_present, thisbat_info_present;
82 static unsigned long thisbat_state_present, thisbat_state_charging_state;
84 #define VAL_NOTFOUND (~0UL)
86 static const batinfo_field fields[]= {
87 #define E(f,l) #f, #l, &thisbat_##f##_##l, 0
88 #define QF(f,l,u) { #f, #l, &thisbat_##f##_##l, u },
89 { E(alarm, present), { "no", "yes" } },
90 { E(info, present), { "no", "yes" } },
91 { E(state,present), { "no", "yes" } },
92 { E(state,charging_state), { "discharging", "charging", "charged" } },
93 QUANTITY_FIELDS /* take care re charging_state values order - */
94 { 0 } /* if you must change it, search for CHGST_... */
99 static const char *files[]= { "info", "state", "alarm" };
101 /*---------- parsing of one battery in /proc/acpi/battery/... ----------*/
103 /* variables private to the parser and its error handlers */
104 static char batlinebuf[1000];
105 static FILE *batfile;
106 static const char *batdirname;
107 static const char *batfilename;
108 static const char *batlinevalue;
110 static int batfailf(const char *why) {
112 fprintf(stderr,"battery/%s/%s: %s value `%s': %s\n",
113 batdirname,batfilename, batlinebuf,batlinevalue,why);
115 fprintf(stderr,"battery/%s/%s: %s: `%s'\n",
116 batdirname,batfilename, why, batlinebuf);
121 static int batfaile(const char *syscall, const char *target) {
122 fprintf(stderr,"battery/%s: failed to %s %s: %s\n",
123 batdirname ? batdirname : "*", syscall, target, strerror(errno));
127 static void chdir_base(void) {
130 r= chdir("/proc/acpi/battery");
131 if (r) batfaile("chdir","/proc/acpi/battery");
134 static void tidybattery(void) {
135 if (batfile) { fclose(batfile); batfile=0; }
136 if (batdirname) { chdir_base(); batdirname=0; }
139 static int readbattery(void) { /* 0=>ok, -1=>couldn't */
140 const batinfo_field *field;
141 const char *const *cfilename, *const *enumsearch;
142 char *colon, *ep, *sr, *p;
145 r= chdir(batdirname);
146 if (r) return batfaile("chdir",batdirname);
148 for (field=fields; field->file; field++)
149 *field->valuep= VAL_NOTFOUND;
151 for (cfilename=files;
152 (batfilename= *cfilename);
154 batfile= fopen(batfilename,"r");
155 if (!batfile) return batfaile("open",batfilename);
160 sr= fgets(batlinebuf,sizeof(batlinebuf),batfile);
161 if (ferror(batfile)) return batfaile("read",batfilename);
162 if (!sr && feof(batfile)) break;
163 l= strlen(batlinebuf);
165 if (batlinebuf[l-1] != '\n')
166 return batfailf("line too long");
168 colon= strchr(batlinebuf,':');
170 return batfailf("line without a colon");
173 for (batlinevalue= colon+1;
174 *batlinevalue && isspace((unsigned char)*batlinevalue);
177 if (!strcmp(batlinebuf,"ERROR"))
178 return batfailf("kernel reports error");
180 for (p=batlinebuf; p<colon; p++)
184 for (field=fields; field->file; field++) {
185 if (!strcmp(field->file,batfilename) &&
186 !strcmp(field->label,batlinebuf))
187 goto label_interesting;
194 *field->valuep= strtoul(batlinevalue,&ep,10);
195 if (ep==batlinevalue || *ep!=' ')
196 batfailf("value number syntax incorrect");
197 if (strcmp(ep+1,field->unit)) batfailf("incorrect unit");
201 for (*field->valuep=0, enumsearch=field->enumarray;
202 *enumsearch && strcmp(*enumsearch,batlinevalue);
203 (*field->valuep)++, enumsearch++);
205 batfailf("unknown enum value");
214 if (!(thisbat_alarm_present==0 ||
215 thisbat_info_present==0 ||
216 thisbat_state_present==0)) {
217 if (thisbat_alarm_present == VAL_NOTFOUND)
218 thisbat_alarm_present= 1;
220 for (field=fields, missing=0;
223 if (*field->valuep == VAL_NOTFOUND) {
224 fprintf(stderr,"battery/%s/%s: %s: not found\n",
225 batdirname, field->file,field->label);
229 if (missing) return -1;
233 if (r) return batfaile("chdir","..");
239 /*---------- data collection and analysis ----------*/
241 /* These next three variables are the results of the charging state */
242 static unsigned charging_state_mask; /* 1u<<CHGST_* | ... */
243 static double nondegraded_norm, fill_norm, ratepersec_norm;
244 static int alarm_level; /* 0=ok, 1=low */
247 static double total_##f##_##l;
251 static void acquiredata(void) {
256 charging_state_mask= 0;
263 di= opendir("."); if (!di) batfaile("opendir","battery");
264 while ((de= readdir(di))) {
265 if (de->d_name[0]==0 || de->d_name[0]=='.') continue;
267 batdirname= de->d_name;
271 if (r) { charging_state_mask |= CHGST_ERROR; continue; }
273 if (!thisbat_info_present || !thisbat_state_present)
276 charging_state_mask |= 1u << thisbat_state_charging_state;
279 total_##f##_##l += thisbat_##f##_##l;
283 if (thisbat_state_charging_state == CHGST_DISCHARGING)
285 total_state_present_rate -= 2.0 * thisbat_state_present_rate;
290 if (total_info_design_capacity < 0.5)
291 total_info_design_capacity= 1.0;
293 if (total_info_last_full_capacity < total_state_remaining_capacity)
294 total_info_last_full_capacity= total_state_remaining_capacity;
295 if (total_info_design_capacity < total_info_last_full_capacity)
296 total_info_design_capacity= total_info_last_full_capacity;
299 (total_state_remaining_capacity < total_alarm_alarm &&
300 !(charging_state_mask & 1u << CHGST_CHARGING));
302 nondegraded_norm= total_info_last_full_capacity / total_info_design_capacity;
303 fill_norm= total_state_remaining_capacity / total_info_design_capacity;
304 ratepersec_norm= total_state_present_rate
305 / (3600.0 * total_info_design_capacity);
308 static void initacquire(void) {
312 /*---------- argument parsing ----------*/
315 C(blue, discharging) \
321 C(dimgrey, degraded) \
322 C(darkgreen, absent) \
324 C(white, equilibrium) \
329 static XrmDatabase xrm;
330 static Display *disp;
333 static const char defaultresources[]=
336 "*" #u "Color: " #c "\n"
342 #define S(s) ((char*)(s))
343 static const XrmOptionDescRec optiontable[]= {
344 { S("-display"), S("*display"), XrmoptionSepArg },
345 { S("-geometry"), S("*geometry"), XrmoptionSepArg },
348 { S("-" #u "Color"), S("*" #u "Color"), XrmoptionSepArg }, \
349 { S("-" #u "Colour"), S("*" #u "Color"), XrmoptionSepArg },
355 static const char *getresource(const char *want) {
356 char name_buf[256], class_buf[256];
358 char *rep_type_dummy;
361 assert(strlen(want) < 128);
362 sprintf(name_buf,"xacpi-simple.%s",want);
363 sprintf(class_buf,"Xacpi-Simple.%s",want);
365 r= XrmGetResource(xrm, name_buf,class_buf, &rep_type_dummy, &val);
371 static void more_resources(const char *str, const char *why) {
376 more= XrmGetStringDatabase((char*)str);
377 if (!more) fail(why);
378 XrmCombineDatabase(more,&xrm,0);
381 static void parseargs(int argc, char **argv) {
382 Screen *screenscreen;
386 XrmParseCommand(&xrm, (XrmOptionDescRec*)optiontable,
387 sizeof(optiontable)/sizeof(*optiontable),
388 program_name, &argc, argv);
390 if (argc>1) badusage();
392 disp= XOpenDisplay(getresource("display"));
393 if (!disp) fail("could not open display");
395 screen= DefaultScreen(disp);
397 screenscreen= ScreenOfDisplay(disp,screen);
398 if (!screenscreen) fail("screenofdisplay");
399 more_resources(XScreenResourceString(screenscreen), "screen resources");
400 more_resources(XResourceManagerString(disp), "display resources");
401 more_resources(defaultresources, "default resources");
404 /*---------- display ----------*/
407 static int width, height;
408 static Colormap cmap;
409 static unsigned long lastbackground;
413 unsigned long lastfg;
416 #define C(c,u) static unsigned long pix_##c;
417 #define GC(g) static Gcstate gc_##g;
422 static void refresh(void);
424 #define CHGMASK_CHG_DIS (1u<<CHGST_CHARGING | 1u<<CHGST_DISCHARGING)
426 static void failr(const char *m, int r) {
427 fprintf(stderr,"error: %s (code %d)\n", m, r);
431 static void setbackground(unsigned long newbg) {
434 if (newbg == lastbackground) return;
435 r= XSetWindowBackground(disp,win,newbg);
436 if (!r) fail("XSetWindowBackground");
437 lastbackground= newbg;
440 static void setforeground(Gcstate *g, unsigned long px) {
444 if (g->lastfg == px) return;
446 memset(&gcv,0,sizeof(gcv));
447 g->lastfg= gcv.foreground= px;
448 r= XChangeGC(disp,g->gc,GCForeground,&gcv);
449 if (!r) fail("XChangeGC");
452 static void show_solid(unsigned long px) {
454 XClearWindow(disp,win);
457 static void show(void) {
459 int i, leftmost_lit, leftmost_nondeg, beyond, first_beyond;
461 if (!charging_state_mask)
462 return show_solid(pix_darkgreen);
464 if (charging_state_mask & CHGST_ERROR)
465 return show_solid(pix_yellow);
467 setbackground(pix_dimgrey);
468 XClearWindow(disp,win);
470 setforeground(&gc_remain,
471 !(charging_state_mask & CHGMASK_CHG_DIS) ? pix_cyan :
472 !(~charging_state_mask & CHGMASK_CHG_DIS) ? pix_grey :
473 charging_state_mask & (1u<<CHGST_CHARGING)
474 ? pix_green : pix_blue);
476 setforeground(&gc_empty, alarm_level ? pix_red : pix_black);
478 for (i=0, first_beyond=1; i<height; i++) {
481 TOP * exp( (double)i / (height-2) * log( (double)BOTTOM/TOP ) );
483 then= fill_norm + ratepersec_norm * elap;
486 ((charging_state_mask & (1u<<CHGST_DISCHARGING) && then <= 0.0) ||
487 (charging_state_mask & (1u<<CHGST_CHARGING) && then>=nondegraded_norm));
489 if (then <= 0.0) then= 0.0;
490 else if (then >= nondegraded_norm) then= nondegraded_norm;
492 leftmost_lit= width * then;
493 leftmost_nondeg= width * nondegraded_norm;
495 if (beyond && first_beyond) {
496 XDrawLine(disp, win, gc_white.gc, 0,i, leftmost_nondeg,i);
499 if (leftmost_lit < leftmost_nondeg)
500 XDrawLine(disp, win, gc_empty.gc,
501 leftmost_lit,i, leftmost_nondeg,i);
502 if (leftmost_lit >= 0)
503 XDrawLine(disp, win, gc_remain.gc, 0,i, leftmost_lit,i);
508 static void initgc(Gcstate *gc_r) {
511 memset(&gcv,0,sizeof(gcv));
512 gcv.function= GXcopy;
514 gc_r->lastfg= gcv.foreground= pix_white;
515 gc_r->gc= XCreateGC(disp,win, GCFunction|GCLineWidth|GCForeground, &gcv);
518 static void colour(unsigned long *pix_r, const char *whichcolour) {
523 name= getresource(whichcolour);
524 if (!name) fail("get colour resource");
526 st= XAllocNamedColor(disp,cmap,name,&xc,&xc);
532 static void initgraphics(int argc, char **argv) {
534 const char *geom_string;
535 XSizeHints *normal_hints;
537 XClassHint *class_hint;
538 int pos_x, pos_y, gravity;
539 char *program_name_silly;
541 program_name_silly= (char*)program_name;
543 normal_hints= XAllocSizeHints();
544 wm_hints= XAllocWMHints();
545 class_hint= XAllocClassHint();
547 if (!normal_hints || !wm_hints || !class_hint)
548 fail("could not alloc hint(s)");
550 geom_string= getresource("geometry");
552 xwmgr= XWMGeometry(disp,screen, geom_string,"128x32", 0,
558 win= XCreateSimpleWindow(disp,DefaultRootWindow(disp),
559 pos_x,pos_y,width,height,0,0,0);
560 cmap= DefaultColormap(disp,screen);
562 #define C(c,u) colour(&pix_##c, #u "Color");
563 #define GC(g) initgc(&gc_##g);
568 r= XSetWindowBackground(disp,win,pix_dimgrey);
569 if (!r) fail("init set background");
570 lastbackground= pix_dimgrey;
572 normal_hints->flags= PWinGravity;
573 normal_hints->win_gravity= gravity;
574 normal_hints->x= pos_x;
575 normal_hints->y= pos_y;
576 normal_hints->width= width;
577 normal_hints->height= height;
578 if ((xwmgr & XValue) || (xwmgr & YValue))
579 normal_hints->flags |= USPosition;
581 wm_hints->flags= InputHint;
582 wm_hints->input= False;
584 class_hint->res_name= program_name_silly;
585 class_hint->res_class= program_name_silly;
587 XmbSetWMProperties(disp,win, program_name,program_name,
588 argv,argc, normal_hints, wm_hints, class_hint);
590 XSelectInput(disp,win, ExposureMask|StructureNotifyMask);
591 XMapWindow(disp,win);
594 static void refresh(void) {
599 static void newgeometry(void) {
603 XGetGeometry(disp,win, &dummyw,&dummy,&dummy, &width,&height, &dummy,&dummy);
606 static void eventloop(void) {
617 pfd.fd= ConnectionNumber(disp);
618 pfd.events= POLLIN|POLLERR;
620 timeout= !(charging_state_mask & CHGST_ERROR) ? TIMEOUT : TIMEOUT_ONERROR;
621 r= poll(&pfd,1,timeout);
622 if (r==-1 && errno!=EINTR) failr("poll",errno);
624 while (XPending(disp)) {
625 XNextEvent(disp,&ev);
626 if (ev.type == ConfigureNotify) {
627 XConfigureEvent *ce= (void*)&ev;
636 int main(int argc, char **argv) {
637 parseargs(argc,argv);
639 initgraphics(argc,argv);