8 * display outputs, per line:
10 * Remaining: | Empty: | Degraded:
11 * blue | black | dimgrey discharging
12 * green | black | dimgrey charging
13 * cyan | black | dimgrey charged
14 * grey | black | dimgrey charging&discharching!
15 * darkcyan | black | dimgrey none of the above
16 * blue | red | dimgrey discharging - low!
17 * green | red | dimgrey charging - low
18 * cyan | red | dimgrey charged - low [1]
19 * grey | red | dimgrey charging&discharching, low [1]
20 * ... darkgreen ... no batteries present
21 * ... yellow ... error
23 * [1] battery must be quite badly degraded
26 * Copyright (C) 2004 Ian Jackson <ian@davenant.greenend.org.uk>
28 * This is free software; you can redistribute it and/or modify
29 * it under the terms of the GNU General Public License as
30 * published by the Free Software Foundation; either version 3,
31 * or (at your option) any later version.
33 * This is distributed in the hope that it will be useful, but
34 * WITHOUT ANY WARRANTY; without even the implied warranty of
35 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
36 * GNU General Public License for more details.
38 * You should have received a copy of the GNU General Public
39 * License along with this file; if not, consult the Free Software
40 * Foundation's website at www.fsf.org, or the GNU Project website at
56 #include <sys/types.h>
60 #include <X11/Xutil.h>
61 #include <X11/Xresource.h>
66 #define TIMEOUT 5000 /* milliseconds */
67 #define TIMEOUT_ONERROR 3333 /* milliseconds */
69 static const char program_name[]= "xacpi-simple";
71 /*---------- general utility stuff and declarations ----------*/
73 static void fail(const char *m) {
74 fprintf(stderr,"error: %s\n", m);
77 static void badusage(void) { fail("bad usage"); }
79 typedef uint64_t value;
80 #define VAL_NOTFOUND (~(value)0)
82 typedef struct fileinfo fileinfo;
83 typedef int parser(const fileinfo*);
85 static parser parse_uevent, parse_separate;
93 /*---------- structure of and results from /sys/class/power/... ----------*/
94 /* variables this_... are the results from readbattery();
95 * if readbattery() succeeds the appropriate ones are all valid
96 * and not VAL_NOTFOUND
99 typedef struct batinfo_field {
102 const char *enumarray[10];
105 #define BAT_QTYS(_) \
106 _(design_capacity, ENERGY, CHARGE, FULL_DESIGN ) \
107 _(last_full_capacity, ENERGY, CHARGE, FULL ) \
108 _(remaining_capacity, ENERGY, CHARGE, NOW ) \
109 _(present_rate, POWER, CURRENT, NOW )
110 /* ENERGY [mWh]; POWER [mW]; CHARGE [uAh]; CURRENT [uA] */
112 #define UEVENT_QTY_CHARGE(f,lle,llc,lr) \
113 _(f##_energy, BATTERY, lle##_##lr ) \
114 _(f##_charge, BATTERY, llc##_##lr )
116 #define UEVENT_QUANTITY_FIELDS(_) \
117 BAT_QTYS(UEVENT_QTY_CHARGE) \
118 _(present, BATTERY, PRESENT ) /* boolean */ \
119 _(online, MAINS, ONLINE ) /* boolean */
121 #define UEVENT_ENUM_FIELDS(_) \
122 _(state, BATTERY, STATUS, "Discharging","Charging","Full","Unknown" ) \
123 _(type, BOTH, TYPE, "Mains", "Battery" )
125 #define CHGST_DISCHARGING 0 /* Reflects order in _(state,...) above */
126 #define CHGST_CHARGING 1 /* Also, much code assumes exactly */
127 #define CHGST_CHARGED 2 /* these three possible states. */
128 #define CHGST_UNKNOWN 3 /* these three possible states. */
129 #define CHGST_ERROR 8 /* Except that this one is an extra bit. */
131 #define TYPE_MAINS 0 /* Reflects order in _(type,...) above */
132 #define TYPE_BATTERY 1 /* Also, much code assumes exactly these two */
133 #define TYPE_BOTH 100 /* Except this is a magic invalid value. */
135 #define SEPARATE_QUANTITY_FIELDS(_) \
136 _(alarm, BATTERY, "alarm", "0", "1")
138 #define ALL_FIELDS(_) \
139 UEVENT_QUANTITY_FIELDS(_) \
140 UEVENT_ENUM_FIELDS(_) \
141 SEPARATE_QUANTITY_FIELDS(_)
143 #define ALL_QUANTITY_FIELDS(_) \
144 UEVENT_QUANTITY_FIELDS(_) \
145 SEPARATE_QUANTITY_FIELDS(_)
147 #define ALL_VARS(_) \
151 #define F_VAR(f,...) \
152 static value this_##f;
155 #define Q_FLD(f,t,l) { "POWER_SUPPLY_" #l, &this_##f },
156 #define E_FLD(f,t,l,vl...) { "POWER_SUPPLY_" #l, &this_##f, { vl } },
158 static const batinfo_field uevent_fields[]= {
159 UEVENT_QUANTITY_FIELDS(Q_FLD)
160 UEVENT_ENUM_FIELDS(E_FLD)
164 #define S_FLD(f,t,fn,vl...) \
165 static const batinfo_field bif_##f = { 0, &this_##f, { vl } };
166 SEPARATE_QUANTITY_FIELDS(S_FLD)
168 #define S_FILE(f,t,fn,vl...) { fn, parse_separate, &bif_##f },
170 static const fileinfo files[]= {
171 { "uevent", parse_uevent, uevent_fields },
172 SEPARATE_QUANTITY_FIELDS(S_FILE)
176 /*---------- parsing of one thingx in /sys/class/power/... ----------*/
178 /* variables private to the parser and its error handlers */
179 static char batlinebuf[1000];
180 static FILE *batfile;
181 static const char *batdirname;
182 static const char *batfilename;
183 static const char *batlinevalue;
185 static int batfailf(const char *why) {
187 fprintf(stderr,"%s/%s: %s value `%s': %s\n",
188 batdirname,batfilename, batlinebuf,batlinevalue,why);
190 fprintf(stderr,"%s/%s: %s: `%s'\n",
191 batdirname,batfilename, why, batlinebuf);
196 static int batfailc(const char *why) {
197 fprintf(stderr,"%s/%s: %s\n",
198 batdirname,batfilename, why);
202 static int batfaile(const char *syscall, const char *target) {
203 fprintf(stderr,"%s: failed to %s %s: %s\n",
204 batdirname ? batdirname : "*", syscall, target, strerror(errno));
208 static int chdir_base(void) {
211 r= chdir("/sys/class/power_supply");
212 if (r) return batfaile("chdir","/sys/class/power_supply");
217 static void tidybattery(void) {
218 if (batfile) { fclose(batfile); batfile=0; }
221 static int parse_value(const fileinfo *cfile, const batinfo_field *field) {
222 if (*field->valuep != VAL_NOTFOUND)
223 return batfailf("value specified multiple times");
225 if (!field->enumarray[0]) {
228 *field->valuep= strtoull(batlinevalue,&ep,10);
230 batfailf("value number syntax incorrect");
234 const char *const *enumsearch;
235 for (*field->valuep=0, enumsearch=field->enumarray;
236 *enumsearch && strcmp(*enumsearch,batlinevalue);
237 (*field->valuep)++, enumsearch++);
239 batfailf("unknown enum value");
245 static int parse_separate(const fileinfo *cfile) {
246 batlinevalue = batlinebuf;
247 return parse_value(cfile, cfile->extra);
250 static int parse_uevent(const fileinfo *cfile) {
251 char *equals= strchr(batlinebuf,'=');
253 return batfailf("line without a equals");
255 batlinevalue = equals+1;
257 const batinfo_field *field;
258 for (field=cfile->extra; field->label; field++) {
259 if (!strcmp(field->label,batlinebuf))
265 return parse_value(cfile, field);
268 static int readbattery(void) { /* 0=>ok, -1=>couldn't */
270 const fileinfo *cfile;
277 r= chdir(batdirname);
278 if (r) return batfaile("chdir",batdirname);
280 #define V_NOTFOUND(f,...) \
281 this_##f = VAL_NOTFOUND;
285 (batfilename= cfile->filename);
287 batfile= fopen(batfilename,"r");
289 if (errno == ENOENT) continue;
290 return batfaile("open",batfilename);
296 sr= fgets(batlinebuf,sizeof(batlinebuf),batfile);
297 if (ferror(batfile)) return batfaile("read",batfilename);
298 if (!sr && feof(batfile)) break;
299 l= strlen(batlinebuf);
301 if (batlinebuf[l-1] != '\n')
302 return batfailf("line too long");
305 if (cfile->parse(cfile))
313 int needsfields_MAINS = this_type == TYPE_MAINS;
314 int needsfields_BATTERY = this_type == TYPE_BATTERY;
315 int needsfields_BOTH = 1;
319 #define V_NEEDED(f,t,...) \
320 if (needsfields_##t && this_##f == VAL_NOTFOUND) { \
321 fprintf(stderr,"%s: %s: not found\n", \
327 if (missing) return -1;
332 /*---------- data collection and analysis ----------*/
334 /* These next three variables are the results of the charging state */
335 static unsigned charging_mask; /* 1u<<CHGST_* | ... */
336 static double nondegraded_norm, fill_norm, ratepersec_norm;
337 static int alarm_level; /* 0=ok, 1=low */
339 #define Q_VAR(f,t,...) \
340 static double total_##f;
341 ALL_QUANTITY_FIELDS(Q_VAR)
343 static void acquiredata(void) {
350 #define Q_ZERO(f,t,...) \
352 ALL_QUANTITY_FIELDS(Q_ZERO)
357 di= opendir("."); if (!di) { batfaile("opendir","battery"); goto bad; }
358 while ((de= readdir(di))) {
359 if (de->d_name[0]==0 || de->d_name[0]=='.') continue;
361 batdirname= de->d_name;
367 charging_mask |= (1u << CHGST_ERROR);
371 if (this_type == TYPE_BATTERY) {
375 charging_mask |= 1u << this_state;
377 if (this_state == CHGST_DISCHARGING)
379 total_present_rate -= 2.0 * thisbat_present_rate;
381 #define QTY_ENERGY_SUPPLIED(f,...) this_##f##_energy != V_NOTFOUND &&
382 #define QTY_ENERGY_USE(f,...) this_##f = this_##f##_energy;
383 #define QTY_CHARGE_SUPPLIED(f,...) this_##f##_charge != V_NOTFOUND &&
384 #define QTY_CHARGE_USE(f,...) this_##f = this_##f##_charge;
386 if (BAT_QTYS(QTY_ENERGY_SUPPLIED) 1) {
387 BAT_QTYS(QTY_ENERGY_USE);
388 } else if (BAT_QTYS(QTY_CHARGE_SUPPLIED) 1) {
389 BAT_QTYS(QTY_CHARGE_USE);
391 return batfailc("neither complete set of energy nor charge");
395 #define Q_TOTALISE(f,t,...) \
396 if (thisbat_type == TYPE_##t) \
397 total_##f += thisbat_##f;
398 ALL_QUANTITY_FIELDS(Q_TOTALISE)
403 if (total_design_capacity < 0.5)
404 total_design_capacity= 1.0;
406 if (total_last_full_capacity < total_remaining_capacity)
407 total_last_full_capacity= total_remaining_capacity;
408 if (total_design_capacity < total_last_full_capacity)
409 total_design_capacity= total_last_full_capacity;
411 alarm_level= total_alarm && (charging_mask & 1u << CHGST_DISCHARGING);
413 nondegraded_norm= total_last_full_capacity / total_design_capacity;
414 fill_norm= total_remaining_capacity / total_design_capacity;
415 ratepersec_norm= total_present_rate
416 / (3600.0 * total_design_capacity);
419 static void initacquire(void) {
422 /*---------- argument parsing ----------*/
425 C(blue, discharging) \
428 C(darkcyan, notcharging) \
432 C(dimgrey, degraded) \
433 C(darkgreen, absent) \
435 C(white, equilibrium) \
440 static XrmDatabase xrm;
441 static Display *disp;
444 static const char defaultresources[]=
447 "*" #u "Color: " #c "\n"
453 #define S(s) ((char*)(s))
454 static const XrmOptionDescRec optiontable[]= {
455 { S("-display"), S("*display"), XrmoptionSepArg },
456 { S("-geometry"), S("*geometry"), XrmoptionSepArg },
459 { S("-" #u "Color"), S("*" #u "Color"), XrmoptionSepArg }, \
460 { S("-" #u "Colour"), S("*" #u "Color"), XrmoptionSepArg },
466 static const char *getresource(const char *want) {
467 char name_buf[256], class_buf[256];
469 char *rep_type_dummy;
472 assert(strlen(want) < 128);
473 sprintf(name_buf,"xacpi-simple.%s",want);
474 sprintf(class_buf,"Xacpi-Simple.%s",want);
476 r= XrmGetResource(xrm, name_buf,class_buf, &rep_type_dummy, &val);
482 static void more_resources(const char *str, const char *why) {
487 more= XrmGetStringDatabase((char*)str);
488 if (!more) fail(why);
489 XrmCombineDatabase(more,&xrm,0);
492 static void parseargs(int argc, char **argv) {
493 Screen *screenscreen;
497 XrmParseCommand(&xrm, (XrmOptionDescRec*)optiontable,
498 sizeof(optiontable)/sizeof(*optiontable),
499 program_name, &argc, argv);
501 if (argc>1) badusage();
503 disp= XOpenDisplay(getresource("display"));
504 if (!disp) fail("could not open display");
506 screen= DefaultScreen(disp);
508 screenscreen= ScreenOfDisplay(disp,screen);
509 if (!screenscreen) fail("screenofdisplay");
510 more_resources(XScreenResourceString(screenscreen), "screen resources");
511 more_resources(XResourceManagerString(disp), "display resources");
512 more_resources(defaultresources, "default resources");
515 /*---------- display ----------*/
518 static int width, height;
519 static Colormap cmap;
520 static unsigned long lastbackground;
524 unsigned long lastfg;
527 #define C(c,u) static unsigned long pix_##c;
528 #define GC(g) static Gcstate gc_##g;
533 static void refresh(void);
535 #define CHGMASK_CHG_DIS ((1u<<CHGST_CHARGING) | (1u<<CHGST_DISCHARGING))
537 static void failr(const char *m, int r) {
538 fprintf(stderr,"error: %s (code %d)\n", m, r);
542 static void setbackground(unsigned long newbg) {
545 if (newbg == lastbackground) return;
546 r= XSetWindowBackground(disp,win,newbg);
547 if (!r) fail("XSetWindowBackground");
548 lastbackground= newbg;
551 static void setforeground(Gcstate *g, unsigned long px) {
555 if (g->lastfg == px) return;
557 memset(&gcv,0,sizeof(gcv));
558 g->lastfg= gcv.foreground= px;
559 r= XChangeGC(disp,g->gc,GCForeground,&gcv);
560 if (!r) fail("XChangeGC");
563 static void show_solid(unsigned long px) {
565 XClearWindow(disp,win);
568 static void show(void) {
570 int i, leftmost_lit, leftmost_nondeg, beyond, first_beyond;
573 return show_solid(pix_darkgreen);
575 if (charging_mask & (1u << CHGST_ERROR))
576 return show_solid(pix_yellow);
578 setbackground(pix_dimgrey);
579 XClearWindow(disp,win);
581 setforeground(&gc_remain,
582 !(charging_mask & CHGMASK_CHG_DIS) ?
583 (~charging_mask & (1u << CHGST_CHARGED) ?
584 pix_darkcyan : pix_cyan) :
585 !(~charging_mask & CHGMASK_CHG_DIS) ? pix_grey :
586 charging_mask & (1u<<CHGST_CHARGING)
587 ? pix_green : pix_blue);
589 setforeground(&gc_empty, alarm_level ? pix_red : pix_black);
591 for (i=0, first_beyond=1; i<height; i++) {
594 TOP * exp( (double)i / (height-2) * log( (double)BOTTOM/TOP ) );
596 then= fill_norm + ratepersec_norm * elap;
599 ((charging_mask & (1u<<CHGST_DISCHARGING) && then <= 0.0) ||
600 (charging_mask & (1u<<CHGST_CHARGING) && then>=nondegraded_norm));
602 if (then <= 0.0) then= 0.0;
603 else if (then >= nondegraded_norm) then= nondegraded_norm;
605 leftmost_lit= width * then;
606 leftmost_nondeg= width * nondegraded_norm;
608 if (beyond && first_beyond) {
609 XDrawLine(disp, win, gc_white.gc, 0,i, leftmost_nondeg,i);
612 if (leftmost_lit < leftmost_nondeg)
613 XDrawLine(disp, win, gc_empty.gc,
614 leftmost_lit,i, leftmost_nondeg,i);
615 if (leftmost_lit >= 0)
616 XDrawLine(disp, win, gc_remain.gc, 0,i, leftmost_lit,i);
621 static void initgc(Gcstate *gc_r) {
624 memset(&gcv,0,sizeof(gcv));
625 gcv.function= GXcopy;
627 gc_r->lastfg= gcv.foreground= pix_white;
628 gc_r->gc= XCreateGC(disp,win, GCFunction|GCLineWidth|GCForeground, &gcv);
631 static void colour(unsigned long *pix_r, const char *whichcolour) {
636 name= getresource(whichcolour);
637 if (!name) fail("get colour resource");
639 st= XAllocNamedColor(disp,cmap,name,&xc,&xc);
645 static void initgraphics(int argc, char **argv) {
647 const char *geom_string;
648 XSizeHints *normal_hints;
650 XClassHint *class_hint;
651 int pos_x, pos_y, gravity;
652 char *program_name_silly;
654 program_name_silly= (char*)program_name;
656 normal_hints= XAllocSizeHints();
657 wm_hints= XAllocWMHints();
658 class_hint= XAllocClassHint();
660 if (!normal_hints || !wm_hints || !class_hint)
661 fail("could not alloc hint(s)");
663 geom_string= getresource("geometry");
665 xwmgr= XWMGeometry(disp,screen, geom_string,"128x32", 0,
671 win= XCreateSimpleWindow(disp,DefaultRootWindow(disp),
672 pos_x,pos_y,width,height,0,0,0);
673 cmap= DefaultColormap(disp,screen);
675 #define C(c,u) colour(&pix_##c, #u "Color");
676 #define GC(g) initgc(&gc_##g);
681 r= XSetWindowBackground(disp,win,pix_dimgrey);
682 if (!r) fail("init set background");
683 lastbackground= pix_dimgrey;
685 normal_hints->flags= PWinGravity;
686 normal_hints->win_gravity= gravity;
687 normal_hints->x= pos_x;
688 normal_hints->y= pos_y;
689 normal_hints->width= width;
690 normal_hints->height= height;
691 if ((xwmgr & XValue) || (xwmgr & YValue))
692 normal_hints->flags |= USPosition;
694 wm_hints->flags= InputHint;
695 wm_hints->input= False;
697 class_hint->res_name= program_name_silly;
698 class_hint->res_class= program_name_silly;
700 XmbSetWMProperties(disp,win, program_name,program_name,
701 argv,argc, normal_hints, wm_hints, class_hint);
703 XSelectInput(disp,win, ExposureMask|StructureNotifyMask);
704 XMapWindow(disp,win);
707 static void refresh(void) {
712 static void newgeometry(void) {
714 unsigned int udummy, gotwidth, gotheight;
717 XGetGeometry(disp,win, &dummyw,&dummy,&dummy, &gotwidth,&gotheight,
719 assert(gotwidth < INT_MAX);
720 assert(gotheight < INT_MAX);
725 static void eventloop(void) {
736 pfd.fd= ConnectionNumber(disp);
737 pfd.events= POLLIN|POLLERR;
739 timeout= !(charging_mask & (1u << CHGST_ERROR)) ? TIMEOUT : TIMEOUT_ONERROR;
740 r= poll(&pfd,1,timeout);
741 if (r==-1 && errno!=EINTR) failr("poll",errno);
743 while (XPending(disp)) {
744 XNextEvent(disp,&ev);
745 if (ev.type == ConfigureNotify) {
746 XConfigureEvent *ce= (void*)&ev;
755 int main(int argc, char **argv) {
756 parseargs(argc,argv);
758 initgraphics(argc,argv);