7 * display outputs, per line:
9 * Remaining: | Empty: | Degraded:
10 * blue | black | dimgrey discharging
11 * green | black | dimgrey charging
12 * cyan | black | dimgrey charged
13 * grey | black | dimgrey charging&discharching!
14 * darkcyan | black | dimgrey none of the above
15 * blue | red | dimgrey discharging - low!
16 * green | red | dimgrey charging - low
17 * cyan | red | dimgrey charged - low [1]
18 * grey | red | dimgrey charging&discharching, low [1]
19 * ... darkgreen ... no batteries present
20 * ... yellow ... error
22 * [1] battery must be quite badly degraded
25 * Copyright (C) 2004 Ian Jackson <ian@davenant.greenend.org.uk>
27 * This is free software; you can redistribute it and/or modify
28 * it under the terms of the GNU General Public License as
29 * published by the Free Software Foundation; either version 3,
30 * or (at your option) any later version.
32 * This is distributed in the hope that it will be useful, but
33 * WITHOUT ANY WARRANTY; without even the implied warranty of
34 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
35 * GNU General Public License for more details.
37 * You should have received a copy of the GNU General Public
38 * License along with this file; if not, consult the Free Software
39 * Foundation's website at www.fsf.org, or the GNU Project website at
55 #include <sys/types.h>
59 #include <X11/Xutil.h>
60 #include <X11/Xresource.h>
65 #define TIMEOUT 5000 /* milliseconds */
66 #define TIMEOUT_ONERROR 3333 /* milliseconds */
68 static const char program_name[]= "xacpi-simple";
70 /*---------- general utility stuff and declarations ----------*/
72 static void fail(const char *m) {
73 fprintf(stderr,"error: %s\n", m);
76 static void badusage(void) { fail("bad usage"); }
78 typedef uint64_t value;
79 #define VAL_NOTFOUND (~(value)0)
81 typedef struct fileinfo fileinfo;
82 typedef int parser(const fileinfo*);
84 static parser parse_uevent, parse_separate;
92 /*---------- structure of and results from /sys/class/power/... ----------*/
93 /* variables thisbat_... are the results from readbattery();
94 * if readbattery() succeeds the appropriate ones are all valid
95 * and not VAL_NOTFOUND
98 typedef struct batinfo_field {
101 const char *enumarray[10];
104 #define UEVENT_QUANTITY_FIELDS(f) \
105 f(design_capacity, BATTERY, CHARGE_FULL_DESIGN ) /* uAh */ \
106 f(last_full_capacity, BATTERY, CHARGE_FULL ) /* uAh */ \
107 f(present_rate, BATTERY, CURRENT_NOW ) /* uA */ \
108 f(remaining_capacity, BATTERY, CHARGE_NOW ) /* uAh */ \
109 f(present, BATTERY, PRESENT ) /* boolean */ \
110 f(online, MAINS, ONLINE ) /* boolean */
112 #define UEVENT_ENUM_FIELDS(f) \
113 f(state, BATTERY, STATUS, "Discharging","Charging","Charged","Unknown" ) \
114 f(type, BOTH, TYPE, "Mains", "Battery" )
116 #define CHGST_DISCHARGING 0 /* Reflects order in f(state,...) above */
117 #define CHGST_CHARGING 1 /* Also, much code assumes exactly */
118 #define CHGST_CHARGED 2 /* these three possible states. */
119 #define CHGST_UNKNOWN 3 /* these three possible states. */
120 #define CHGST_ERROR 8 /* Except that this one is an extra bit. */
122 #define TYPE_MAINS 0 /* Reflects order in f(type,...) above */
123 #define TYPE_BATTERY 1 /* Also, much code assumes exactly these two */
124 #define TYPE_BOTH 100 /* Except this is a magic invalid value. */
126 #define SEPARATE_QUANTITY_FIELDS(f) \
127 f(alarm, BATTERY, "alarm", "0", "1")
129 #define ALL_FIELDS(f) \
130 UEVENT_QUANTITY_FIELDS(f) \
131 UEVENT_ENUM_FIELDS(f) \
132 SEPARATE_QUANTITY_FIELDS(f)
134 #define ALL_QUANTITY_FIELDS(f) \
135 UEVENT_QUANTITY_FIELDS(f) \
136 SEPARATE_QUANTITY_FIELDS(f)
138 #define F_VAR(f,...) \
139 static value thisbat_##f;
142 #define Q_FLD(f,t,l) { "POWER_SUPPLY_" #l, &thisbat_##f },
143 #define E_FLD(f,t,l,vl...) { "POWER_SUPPLY_" #l, &thisbat_##f, { vl } },
145 static const batinfo_field uevent_fields[]= {
146 UEVENT_QUANTITY_FIELDS(Q_FLD)
147 UEVENT_ENUM_FIELDS(E_FLD)
151 #define S_FLD(f,t,fn,vl...) \
152 static const batinfo_field bif_##f = { 0, &thisbat_##f, { vl } };
153 SEPARATE_QUANTITY_FIELDS(S_FLD)
155 #define S_FILE(f,t,fn,vl...) { fn, parse_separate, &bif_##f },
157 static const fileinfo files[]= {
158 { "uevent", parse_uevent, uevent_fields },
159 SEPARATE_QUANTITY_FIELDS(S_FILE)
163 /*---------- parsing of one thingx in /sys/class/power/... ----------*/
165 /* variables private to the parser and its error handlers */
166 static char batlinebuf[1000];
167 static FILE *batfile;
168 static const char *batdirname;
169 static const char *batfilename;
170 static const char *batlinevalue;
172 static int batfailf(const char *why) {
174 fprintf(stderr,"%s/%s: %s value `%s': %s\n",
175 batdirname,batfilename, batlinebuf,batlinevalue,why);
177 fprintf(stderr,"%s/%s: %s: `%s'\n",
178 batdirname,batfilename, why, batlinebuf);
183 static int batfaile(const char *syscall, const char *target) {
184 fprintf(stderr,"%s: failed to %s %s: %s\n",
185 batdirname ? batdirname : "*", syscall, target, strerror(errno));
189 static int chdir_base(void) {
192 r= chdir("/sys/class/power_supply");
193 if (r) return batfaile("chdir","/sys/class/power_supply");
198 static void tidybattery(void) {
199 if (batfile) { fclose(batfile); batfile=0; }
202 static int parse_value(const fileinfo *cfile, const batinfo_field *field) {
203 if (*field->valuep != VAL_NOTFOUND)
204 return batfailf("value specified multiple times");
206 if (!field->enumarray[0]) {
209 *field->valuep= strtoull(batlinevalue,&ep,10);
211 batfailf("value number syntax incorrect");
215 const char *const *enumsearch;
216 for (*field->valuep=0, enumsearch=field->enumarray;
217 *enumsearch && strcmp(*enumsearch,batlinevalue);
218 (*field->valuep)++, enumsearch++);
220 batfailf("unknown enum value");
226 static int parse_separate(const fileinfo *cfile) {
227 batlinevalue = batlinebuf;
228 return parse_value(cfile, cfile->extra);
231 static int parse_uevent(const fileinfo *cfile) {
232 char *equals= strchr(batlinebuf,'=');
234 return batfailf("line without a equals");
236 batlinevalue = equals+1;
238 const batinfo_field *field;
239 for (field=cfile->extra; field->label; field++) {
240 if (!strcmp(field->label,batlinebuf))
246 return parse_value(cfile, field);
249 static int readbattery(void) { /* 0=>ok, -1=>couldn't */
251 const fileinfo *cfile;
258 r= chdir(batdirname);
259 if (r) return batfaile("chdir",batdirname);
261 #define V_NOTFOUND(f,...) \
262 thisbat_##f = VAL_NOTFOUND;
263 ALL_FIELDS(V_NOTFOUND)
266 (batfilename= cfile->filename);
268 batfile= fopen(batfilename,"r");
270 if (errno == ENOENT) continue;
271 return batfaile("open",batfilename);
277 sr= fgets(batlinebuf,sizeof(batlinebuf),batfile);
278 if (ferror(batfile)) return batfaile("read",batfilename);
279 if (!sr && feof(batfile)) break;
280 l= strlen(batlinebuf);
282 if (batlinebuf[l-1] != '\n')
283 return batfailf("line too long");
286 if (cfile->parse(cfile))
294 int needsfields_MAINS = thisbat_type == TYPE_MAINS;
295 int needsfields_BATTERY = thisbat_type == TYPE_BATTERY;
296 int needsfields_BOTH = 1;
300 #define V_NEEDED(f,t,...) \
301 if (needsfields_##t && thisbat_##f == VAL_NOTFOUND) { \
302 fprintf(stderr,"%s: %s: not found\n", \
308 if (missing) return -1;
313 /*---------- data collection and analysis ----------*/
315 /* These next three variables are the results of the charging state */
316 static unsigned charging_mask; /* 1u<<CHGST_* | ... */
317 static double nondegraded_norm, fill_norm, ratepersec_norm;
318 static int alarm_level; /* 0=ok, 1=low */
320 #define Q_VAR(f,t,...) \
321 static double total_##f;
322 ALL_QUANTITY_FIELDS(Q_VAR)
324 static void acquiredata(void) {
331 #define Q_ZERO(f,t,...) \
333 ALL_QUANTITY_FIELDS(Q_ZERO)
338 di= opendir("."); if (!di) { batfaile("opendir","battery"); goto bad; }
339 while ((de= readdir(di))) {
340 if (de->d_name[0]==0 || de->d_name[0]=='.') continue;
342 batdirname= de->d_name;
348 charging_mask |= (1u << CHGST_ERROR);
352 if (thisbat_type == TYPE_BATTERY) {
353 if (!thisbat_present)
356 charging_mask |= 1u << thisbat_state;
358 if (thisbat_state == CHGST_DISCHARGING)
360 total_present_rate -= 2.0 * thisbat_present_rate;
363 #define Q_TOTALISE(f,t,...) \
364 if (thisbat_type == TYPE_##t) \
365 total_##f += thisbat_##f;
366 ALL_QUANTITY_FIELDS(Q_TOTALISE)
371 if (total_design_capacity < 0.5)
372 total_design_capacity= 1.0;
374 if (total_last_full_capacity < total_remaining_capacity)
375 total_last_full_capacity= total_remaining_capacity;
376 if (total_design_capacity < total_last_full_capacity)
377 total_design_capacity= total_last_full_capacity;
379 alarm_level= total_alarm && (charging_mask & 1u << CHGST_DISCHARGING);
381 nondegraded_norm= total_last_full_capacity / total_design_capacity;
382 fill_norm= total_remaining_capacity / total_design_capacity;
383 ratepersec_norm= total_present_rate
384 / (3600.0 * total_design_capacity);
387 static void initacquire(void) {
390 /*---------- argument parsing ----------*/
393 C(blue, discharging) \
396 C(darkcyan, notcharging) \
400 C(dimgrey, degraded) \
401 C(darkgreen, absent) \
403 C(white, equilibrium) \
408 static XrmDatabase xrm;
409 static Display *disp;
412 static const char defaultresources[]=
415 "*" #u "Color: " #c "\n"
421 #define S(s) ((char*)(s))
422 static const XrmOptionDescRec optiontable[]= {
423 { S("-display"), S("*display"), XrmoptionSepArg },
424 { S("-geometry"), S("*geometry"), XrmoptionSepArg },
427 { S("-" #u "Color"), S("*" #u "Color"), XrmoptionSepArg }, \
428 { S("-" #u "Colour"), S("*" #u "Color"), XrmoptionSepArg },
434 static const char *getresource(const char *want) {
435 char name_buf[256], class_buf[256];
437 char *rep_type_dummy;
440 assert(strlen(want) < 128);
441 sprintf(name_buf,"xacpi-simple.%s",want);
442 sprintf(class_buf,"Xacpi-Simple.%s",want);
444 r= XrmGetResource(xrm, name_buf,class_buf, &rep_type_dummy, &val);
450 static void more_resources(const char *str, const char *why) {
455 more= XrmGetStringDatabase((char*)str);
456 if (!more) fail(why);
457 XrmCombineDatabase(more,&xrm,0);
460 static void parseargs(int argc, char **argv) {
461 Screen *screenscreen;
465 XrmParseCommand(&xrm, (XrmOptionDescRec*)optiontable,
466 sizeof(optiontable)/sizeof(*optiontable),
467 program_name, &argc, argv);
469 if (argc>1) badusage();
471 disp= XOpenDisplay(getresource("display"));
472 if (!disp) fail("could not open display");
474 screen= DefaultScreen(disp);
476 screenscreen= ScreenOfDisplay(disp,screen);
477 if (!screenscreen) fail("screenofdisplay");
478 more_resources(XScreenResourceString(screenscreen), "screen resources");
479 more_resources(XResourceManagerString(disp), "display resources");
480 more_resources(defaultresources, "default resources");
483 /*---------- display ----------*/
486 static int width, height;
487 static Colormap cmap;
488 static unsigned long lastbackground;
492 unsigned long lastfg;
495 #define C(c,u) static unsigned long pix_##c;
496 #define GC(g) static Gcstate gc_##g;
501 static void refresh(void);
503 #define CHGMASK_CHG_DIS ((1u<<CHGST_CHARGING) | (1u<<CHGST_DISCHARGING))
505 static void failr(const char *m, int r) {
506 fprintf(stderr,"error: %s (code %d)\n", m, r);
510 static void setbackground(unsigned long newbg) {
513 if (newbg == lastbackground) return;
514 r= XSetWindowBackground(disp,win,newbg);
515 if (!r) fail("XSetWindowBackground");
516 lastbackground= newbg;
519 static void setforeground(Gcstate *g, unsigned long px) {
523 if (g->lastfg == px) return;
525 memset(&gcv,0,sizeof(gcv));
526 g->lastfg= gcv.foreground= px;
527 r= XChangeGC(disp,g->gc,GCForeground,&gcv);
528 if (!r) fail("XChangeGC");
531 static void show_solid(unsigned long px) {
533 XClearWindow(disp,win);
536 static void show(void) {
538 int i, leftmost_lit, leftmost_nondeg, beyond, first_beyond;
541 return show_solid(pix_darkgreen);
543 if (charging_mask & (1u << CHGST_ERROR))
544 return show_solid(pix_yellow);
546 setbackground(pix_dimgrey);
547 XClearWindow(disp,win);
549 setforeground(&gc_remain,
550 !(charging_mask & CHGMASK_CHG_DIS) ?
551 (~charging_mask & (1u << CHGST_CHARGED) ?
552 pix_darkcyan : pix_cyan) :
553 !(~charging_mask & CHGMASK_CHG_DIS) ? pix_grey :
554 charging_mask & (1u<<CHGST_CHARGING)
555 ? pix_green : pix_blue);
557 setforeground(&gc_empty, alarm_level ? pix_red : pix_black);
559 for (i=0, first_beyond=1; i<height; i++) {
562 TOP * exp( (double)i / (height-2) * log( (double)BOTTOM/TOP ) );
564 then= fill_norm + ratepersec_norm * elap;
567 ((charging_mask & (1u<<CHGST_DISCHARGING) && then <= 0.0) ||
568 (charging_mask & (1u<<CHGST_CHARGING) && then>=nondegraded_norm));
570 if (then <= 0.0) then= 0.0;
571 else if (then >= nondegraded_norm) then= nondegraded_norm;
573 leftmost_lit= width * then;
574 leftmost_nondeg= width * nondegraded_norm;
576 if (beyond && first_beyond) {
577 XDrawLine(disp, win, gc_white.gc, 0,i, leftmost_nondeg,i);
580 if (leftmost_lit < leftmost_nondeg)
581 XDrawLine(disp, win, gc_empty.gc,
582 leftmost_lit,i, leftmost_nondeg,i);
583 if (leftmost_lit >= 0)
584 XDrawLine(disp, win, gc_remain.gc, 0,i, leftmost_lit,i);
589 static void initgc(Gcstate *gc_r) {
592 memset(&gcv,0,sizeof(gcv));
593 gcv.function= GXcopy;
595 gc_r->lastfg= gcv.foreground= pix_white;
596 gc_r->gc= XCreateGC(disp,win, GCFunction|GCLineWidth|GCForeground, &gcv);
599 static void colour(unsigned long *pix_r, const char *whichcolour) {
604 name= getresource(whichcolour);
605 if (!name) fail("get colour resource");
607 st= XAllocNamedColor(disp,cmap,name,&xc,&xc);
613 static void initgraphics(int argc, char **argv) {
615 const char *geom_string;
616 XSizeHints *normal_hints;
618 XClassHint *class_hint;
619 int pos_x, pos_y, gravity;
620 char *program_name_silly;
622 program_name_silly= (char*)program_name;
624 normal_hints= XAllocSizeHints();
625 wm_hints= XAllocWMHints();
626 class_hint= XAllocClassHint();
628 if (!normal_hints || !wm_hints || !class_hint)
629 fail("could not alloc hint(s)");
631 geom_string= getresource("geometry");
633 xwmgr= XWMGeometry(disp,screen, geom_string,"128x32", 0,
639 win= XCreateSimpleWindow(disp,DefaultRootWindow(disp),
640 pos_x,pos_y,width,height,0,0,0);
641 cmap= DefaultColormap(disp,screen);
643 #define C(c,u) colour(&pix_##c, #u "Color");
644 #define GC(g) initgc(&gc_##g);
649 r= XSetWindowBackground(disp,win,pix_dimgrey);
650 if (!r) fail("init set background");
651 lastbackground= pix_dimgrey;
653 normal_hints->flags= PWinGravity;
654 normal_hints->win_gravity= gravity;
655 normal_hints->x= pos_x;
656 normal_hints->y= pos_y;
657 normal_hints->width= width;
658 normal_hints->height= height;
659 if ((xwmgr & XValue) || (xwmgr & YValue))
660 normal_hints->flags |= USPosition;
662 wm_hints->flags= InputHint;
663 wm_hints->input= False;
665 class_hint->res_name= program_name_silly;
666 class_hint->res_class= program_name_silly;
668 XmbSetWMProperties(disp,win, program_name,program_name,
669 argv,argc, normal_hints, wm_hints, class_hint);
671 XSelectInput(disp,win, ExposureMask|StructureNotifyMask);
672 XMapWindow(disp,win);
675 static void refresh(void) {
680 static void newgeometry(void) {
682 unsigned int udummy, gotwidth, gotheight;
685 XGetGeometry(disp,win, &dummyw,&dummy,&dummy, &gotwidth,&gotheight,
687 assert(gotwidth < INT_MAX);
688 assert(gotheight < INT_MAX);
693 static void eventloop(void) {
704 pfd.fd= ConnectionNumber(disp);
705 pfd.events= POLLIN|POLLERR;
707 timeout= !(charging_mask & (1u << CHGST_ERROR)) ? TIMEOUT : TIMEOUT_ONERROR;
708 r= poll(&pfd,1,timeout);
709 if (r==-1 && errno!=EINTR) failr("poll",errno);
711 while (XPending(disp)) {
712 XNextEvent(disp,&ev);
713 if (ev.type == ConfigureNotify) {
714 XConfigureEvent *ce= (void*)&ev;
723 int main(int argc, char **argv) {
724 parseargs(argc,argv);
726 initgraphics(argc,argv);