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 * darkcyan | black | dimgrey none of the above
10 * blue | red | dimgrey discharging - low!
11 * green | red | dimgrey charging - low
12 * cyan | red | dimgrey charged - low [1]
13 * grey | red | dimgrey charging&discharching, low [1]
14 * ... darkgreen ... no batteries present
15 * ... yellow ... error
17 * [1] battery must be quite badly degraded
20 * Copyright (C) 2004 Ian Jackson <ian@davenant.greenend.org.uk>
22 * This is free software; you can redistribute it and/or modify
23 * it under the terms of the GNU General Public License as
24 * published by the Free Software Foundation; either version 3,
25 * or (at your option) any later version.
27 * This is distributed in the hope that it will be useful, but
28 * WITHOUT ANY WARRANTY; without even the implied warranty of
29 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
30 * GNU General Public License for more details.
32 * You should have received a copy of the GNU General Public
33 * License along with this file; if not, consult the Free Software
34 * Foundation's website at www.fsf.org, or the GNU Project website at
51 #include <sys/types.h>
55 #include <X11/Xutil.h>
56 #include <X11/Xresource.h>
61 #define TIMEOUT 5000 /* milliseconds */
62 #define TIMEOUT_ONERROR 3333 /* milliseconds */
64 static const char program_name[]= "xacpi-simple";
65 static int debug, alarmlevel;
67 /*---------- general utility stuff and declarations ----------*/
69 static void fail(const char *m) {
70 fprintf(stderr,"error: %s\n", m);
73 static void badusage(void) { fail("bad usage"); }
75 typedef uint64_t value;
76 #define VAL_NOTFOUND (~(value)0)
78 typedef struct fileinfo fileinfo;
79 typedef int parser(const fileinfo*);
81 static parser parse_uevent;
89 /*---------- structure of and results from /sys/class/power/... ----------*/
90 /* variables this_... are the results from readbattery();
91 * if readbattery() succeeds the appropriate ones are all valid
92 * and not VAL_NOTFOUND
95 typedef struct batinfo_field {
98 const char *enumarray[10];
101 #define BAT_QTYS(_, _ec, EC_, PC_) \
102 _(design_capacity##_ec, BATTERY, EC_##FULL_DESIGN ) \
103 _(last_full_capacity##_ec, BATTERY, EC_##FULL ) \
104 _(remaining_capacity##_ec, BATTERY, EC_##NOW ) \
105 _(present_rate##_ec, BATTERY, PC_##NOW )
106 /* ENERGY [mWh]; POWER [mW]; CHARGE [uAh]; CURRENT [uA] */
108 #define UEVENT_ESSENTIAL_QUANTITY_FIELDS(_) \
109 _(present, BATTERY, PRESENT /* bool */ ) \
110 _(online, MAINS, ONLINE /* bool */ )
112 #define UEVENT_FUNKY_QUANTITY_FIELDS(_) \
113 BAT_QTYS(_,_energy,ENERGY_,POWER_) \
114 BAT_QTYS(_,_charge,CHARGE_,CURRENT_)
116 #define UEVENT_OPTIONAL_QUANTITY_FIELDS(_) \
117 _(voltage, BATTERY, VOLTAGE_NOW /* uV */ )
119 #define UEVENT_ENUM_FIELDS(_) \
120 _(state, BATTERY, STATUS, "Discharging","Charging","Full","Unknown" ) \
121 _(type, BOTH, TYPE, "Mains", "Battery" )
123 #define CHGST_DISCHARGING 0 /* Reflects order in _(state,...) above */
124 #define CHGST_CHARGING 1 /* Also, much code assumes exactly */
125 #define CHGST_CHARGED 2 /* these three possible states. */
126 #define CHGST_UNKNOWN 3 /* these three possible states. */
127 #define CHGST_ERROR 8 /* Except that this one is an extra bit. */
129 #define TYPE_MAINS 0 /* Reflects order in _(type,...) above */
130 #define TYPE_BATTERY 1 /* Also, much code assumes exactly these two */
131 #define TYPE_BOTH 100 /* Except this is a magic invalid value. */
133 #define SEPARATE_QUANTITY_FIELDS(_) \
134 /* See commit ec6f5f0be800bc5f2a27046833dba04e0c67ffac for
135 the code needed to use this */
138 #define ALL_DIRECT_VARS(_) \
139 UEVENT_ESSENTIAL_QUANTITY_FIELDS(_) \
140 UEVENT_FUNKY_QUANTITY_FIELDS(_) \
141 UEVENT_OPTIONAL_QUANTITY_FIELDS(_) \
142 UEVENT_ENUM_FIELDS(_) \
143 SEPARATE_QUANTITY_FIELDS(_)
145 #define ALL_VARS(_) \
149 #define ALL_NEEDED_FIELDS(_) \
150 UEVENT_ESSENTIAL_QUANTITY_FIELDS(_) \
151 UEVENT_ENUM_FIELDS(_) \
152 SEPARATE_QUANTITY_FIELDS(_)
154 #define ALL_PLAIN_ACCUMULATE_FIELDS(_) \
155 UEVENT_ESSENTIAL_QUANTITY_FIELDS(_) \
156 UEVENT_ENUM_FIELDS(_) \
157 SEPARATE_QUANTITY_FIELDS(_)
159 #define ALL_ACCUMULATE_FIELDS(_) \
160 ALL_PLAIN_ACCUMULATE_FIELDS(_) \
164 #define F_VAR(f,...) \
165 static value this_##f;
168 #define Q_FLD(f,t,l) { "POWER_SUPPLY_" #l, &this_##f },
169 #define E_FLD(f,t,l,vl...) { "POWER_SUPPLY_" #l, &this_##f, { vl } },
171 static const batinfo_field uevent_fields[]= {
172 UEVENT_ESSENTIAL_QUANTITY_FIELDS(Q_FLD)
173 UEVENT_FUNKY_QUANTITY_FIELDS(Q_FLD)
174 UEVENT_OPTIONAL_QUANTITY_FIELDS(Q_FLD)
175 UEVENT_ENUM_FIELDS(E_FLD)
179 #define S_FLD(f,t,fn,vl...) \
180 static const batinfo_field bif_##f = { 0, &this_##f, { vl } };
181 SEPARATE_QUANTITY_FIELDS(S_FLD)
183 #define S_FILE(f,t,fn,vl...) { fn, parse_separate, &bif_##f },
185 static const fileinfo files[]= {
186 { "uevent", parse_uevent, uevent_fields },
187 SEPARATE_QUANTITY_FIELDS(S_FILE)
191 /*---------- parsing of one thingx in /sys/class/power/... ----------*/
193 /* variables private to the parser and its error handlers */
194 static char batlinebuf[1000];
195 static FILE *batfile;
196 static const char *batdirname;
197 static const char *batfilename;
198 static const char *batlinevalue;
200 static int batfailf(const char *why) {
202 fprintf(stderr,"%s/%s: %s value `%s': %s\n",
203 batdirname,batfilename, batlinebuf,batlinevalue,why);
205 fprintf(stderr,"%s/%s: %s: `%s'\n",
206 batdirname,batfilename, why, batlinebuf);
211 static int batfailc(const char *why) {
212 fprintf(stderr,"%s/%s: %s\n",
213 batdirname,batfilename, why);
217 static int batfaile(const char *syscall, const char *target) {
218 fprintf(stderr,"%s: failed to %s %s: %s\n",
219 batdirname ? batdirname : "*", syscall, target, strerror(errno));
223 static int chdir_base(void) {
226 r= chdir("/sys/class/power_supply");
227 if (r) return batfaile("chdir","/sys/class/power_supply");
232 static void tidybattery(void) {
233 if (batfile) { fclose(batfile); batfile=0; }
236 static int parse_value(const fileinfo *cfile, const batinfo_field *field) {
237 if (*field->valuep != VAL_NOTFOUND)
238 return batfailf("value specified multiple times");
240 if (!field->enumarray[0]) {
243 *field->valuep= strtoull(batlinevalue,&ep,10);
245 batfailf("value number syntax incorrect");
249 const char *const *enumsearch;
250 for (*field->valuep=0, enumsearch=field->enumarray;
251 *enumsearch && strcmp(*enumsearch,batlinevalue);
252 (*field->valuep)++, enumsearch++);
254 batfailf("unknown enum value");
260 static int parse_uevent(const fileinfo *cfile) {
261 char *equals= strchr(batlinebuf,'=');
263 return batfailf("line without a equals");
265 batlinevalue = equals+1;
267 const batinfo_field *field;
268 for (field=cfile->extra; field->label; field++) {
269 if (!strcmp(field->label,batlinebuf))
275 return parse_value(cfile, field);
278 static int readbattery(void) { /* 0=>ok, -1=>couldn't */
280 const fileinfo *cfile;
287 r= chdir(batdirname);
288 if (r) return batfaile("chdir",batdirname);
290 #define V_NOTFOUND(f,...) \
291 this_##f = VAL_NOTFOUND;
295 (batfilename= cfile->filename);
297 batfile= fopen(batfilename,"r");
299 if (errno == ENOENT) continue;
300 return batfaile("open",batfilename);
306 sr= fgets(batlinebuf,sizeof(batlinebuf),batfile);
307 if (ferror(batfile)) return batfaile("read",batfilename);
308 if (!sr && feof(batfile)) break;
309 l= strlen(batlinebuf);
311 if (batlinebuf[l-1] != '\n')
312 return batfailf("line too long");
315 if (cfile->parse(cfile))
324 printf("%s:\n",batdirname);
325 #define V_PRINT(f,...) \
326 printf(" %-30s = %20"PRId64"\n", #f, (int64_t)this_##f);
327 ALL_DIRECT_VARS(V_PRINT)
330 int needsfields_MAINS = this_type == TYPE_MAINS;
331 int needsfields_BATTERY = this_type == TYPE_BATTERY;
332 int needsfields_BOTH = 1;
336 #define V_NEEDED(f,t,...) \
337 if (needsfields_##t && this_##f == VAL_NOTFOUND) { \
338 fprintf(stderr,"%s: %s: not found\n", \
342 ALL_NEEDED_FIELDS(V_NEEDED)
344 if (missing) return -1;
349 /*---------- data collection and analysis ----------*/
351 /* These next three variables are the results of the charging state */
352 static unsigned charging_mask; /* 1u<<CHGST_* | ... */
353 static double nondegraded_norm, fill_norm, ratepersec_norm;
356 #define Q_VAR(f,t,...) \
357 static double total_##f;
358 ALL_ACCUMULATE_FIELDS(Q_VAR)
360 static void acquiredata(void) {
368 #define Q_ZERO(f,t,...) \
370 ALL_ACCUMULATE_FIELDS(Q_ZERO)
375 di= opendir("."); if (!di) { batfaile("opendir","battery"); goto bad; }
376 while ((de= readdir(di))) {
377 if (de->d_name[0]==0 || de->d_name[0]=='.') continue;
379 batdirname= de->d_name;
385 charging_mask |= (1u << CHGST_ERROR);
389 if (this_type == TYPE_BATTERY) {
393 charging_mask |= 1u << this_state;
395 #define QTY_SUPPLIED(f,...) this_##f != VAL_NOTFOUND &&
396 #define QTY_USE_ENERGY(f,...) this_##f = this_##f##_energy;
397 #define QTY_USE_CHARGE(f,...) this_##f = this_##f##_charge;
399 double funky_multiplier;
400 if (BAT_QTYS(QTY_SUPPLIED,_energy,,) 1) {
401 if (debug) printf(" using energy\n");
402 BAT_QTYS(QTY_USE_ENERGY,,,);
403 funky_multiplier = 1.0;
404 } else if (BAT_QTYS(QTY_SUPPLIED,_charge,,)
405 this_voltage != VAL_NOTFOUND) {
406 if (debug) printf(" using charge\n");
407 BAT_QTYS(QTY_USE_CHARGE,,,);
408 funky_multiplier = this_voltage * 1e-6;
410 batfailc("neither complete set of energy nor charge");
413 if (this_state == CHGST_DISCHARGING)
415 total_present_rate -= 2.0 * this_present_rate * funky_multiplier;
417 #define Q_ACCUMULATE_FUNKY(f,...) \
418 total_##f += this_##f * funky_multiplier;
419 BAT_QTYS(Q_ACCUMULATE_FUNKY,,,)
422 #define Q_ACCUMULATE_PLAIN(f,t,...) \
423 if (this_type == TYPE_##t) \
424 total_##f += this_##f;
425 ALL_PLAIN_ACCUMULATE_FIELDS(Q_ACCUMULATE_PLAIN)
432 #define T_PRINT(f,...) \
433 printf(" %-30s = %20.6f\n", #f, total_##f);
435 ALL_PLAIN_ACCUMULATE_FIELDS(T_PRINT)
438 if ((charging_mask & (1u<<CHGST_DISCHARGING)) &&
439 !total_online/*mains*/) {
440 double time_remaining =
441 -total_remaining_capacity * 3600.0 / total_present_rate;
442 if (debug) printf(" %-30s = %20.6f\n", "time remaining", time_remaining);
443 if (time_remaining < alarmlevel)
447 if (total_design_capacity < 0.5)
448 total_design_capacity= 1.0;
450 if (total_last_full_capacity < total_remaining_capacity)
451 total_last_full_capacity= total_remaining_capacity;
452 if (total_design_capacity < total_last_full_capacity)
453 total_design_capacity= total_last_full_capacity;
455 nondegraded_norm= total_last_full_capacity / total_design_capacity;
456 fill_norm= total_remaining_capacity / total_design_capacity;
457 ratepersec_norm= total_present_rate
458 / (3600.0 * total_design_capacity);
461 static void initacquire(void) {
464 /*---------- argument parsing ----------*/
467 C(blue, discharging) \
470 C(darkcyan, notcharging) \
474 C(dimgrey, degraded) \
475 C(darkgreen, absent) \
477 C(white, equilibrium) \
482 static XrmDatabase xrm;
483 static Display *disp;
486 static const char defaultresources[]=
489 "*" #u "Color: " #c "\n"
495 #define S(s) ((char*)(s))
496 static const XrmOptionDescRec optiontable[]= {
497 { S("-debug"), S("*debug"), XrmoptionIsArg },
498 { S("-warningTime"), S("*warningTime"), XrmoptionSepArg },
499 { S("-display"), S("*display"), XrmoptionSepArg },
500 { S("-geometry"), S("*geometry"), XrmoptionSepArg },
503 { S("-" #u "Color"), S("*" #u "Color"), XrmoptionSepArg }, \
504 { S("-" #u "Colour"), S("*" #u "Color"), XrmoptionSepArg },
510 static const char *getresource(const char *want) {
511 char name_buf[256], class_buf[256];
513 char *rep_type_dummy;
516 assert(strlen(want) < 128);
517 sprintf(name_buf,"xacpi-simple.%s",want);
518 sprintf(class_buf,"Xacpi-Simple.%s",want);
520 r= XrmGetResource(xrm, name_buf,class_buf, &rep_type_dummy, &val);
526 static void more_resources(const char *str, const char *why) {
531 more= XrmGetStringDatabase((char*)str);
532 if (!more) fail(why);
533 XrmCombineDatabase(more,&xrm,0);
536 static void parseargs(int argc, char **argv) {
537 Screen *screenscreen;
541 XrmParseCommand(&xrm, (XrmOptionDescRec*)optiontable,
542 sizeof(optiontable)/sizeof(*optiontable),
543 program_name, &argc, argv);
545 if (argc>1) badusage();
547 debug= !!getresource("debug");
549 const char *alarmlevel_string= getresource("alarmLevel");
550 alarmlevel = alarmlevel_string ? atoi(alarmlevel_string) : 300;
552 disp= XOpenDisplay(getresource("display"));
553 if (!disp) fail("could not open display");
555 screen= DefaultScreen(disp);
557 screenscreen= ScreenOfDisplay(disp,screen);
558 if (!screenscreen) fail("screenofdisplay");
559 more_resources(XScreenResourceString(screenscreen), "screen resources");
560 more_resources(XResourceManagerString(disp), "display resources");
561 more_resources(defaultresources, "default resources");
564 /*---------- display ----------*/
567 static int width, height;
568 static Colormap cmap;
569 static unsigned long lastbackground;
573 unsigned long lastfg;
576 #define C(c,u) static unsigned long pix_##c;
577 #define GC(g) static Gcstate gc_##g;
582 static void refresh(void);
584 #define CHGMASK_CHG_DIS ((1u<<CHGST_CHARGING) | (1u<<CHGST_DISCHARGING))
586 static void failr(const char *m, int r) {
587 fprintf(stderr,"error: %s (code %d)\n", m, r);
591 static void setbackground(unsigned long newbg) {
594 if (newbg == lastbackground) return;
595 r= XSetWindowBackground(disp,win,newbg);
596 if (!r) fail("XSetWindowBackground");
597 lastbackground= newbg;
600 static void setforeground(Gcstate *g, unsigned long px) {
604 if (g->lastfg == px) return;
606 memset(&gcv,0,sizeof(gcv));
607 g->lastfg= gcv.foreground= px;
608 r= XChangeGC(disp,g->gc,GCForeground,&gcv);
609 if (!r) fail("XChangeGC");
612 static void show_solid(unsigned long px) {
614 XClearWindow(disp,win);
617 static void show(void) {
619 int i, leftmost_lit, leftmost_nondeg, beyond, first_beyond;
622 return show_solid(pix_darkgreen);
624 if (charging_mask & (1u << CHGST_ERROR))
625 return show_solid(pix_yellow);
627 setbackground(pix_dimgrey);
628 XClearWindow(disp,win);
630 setforeground(&gc_remain,
631 !(charging_mask & CHGMASK_CHG_DIS) ?
632 (~charging_mask & (1u << CHGST_CHARGED) ?
633 pix_darkcyan : pix_cyan) :
634 !(~charging_mask & CHGMASK_CHG_DIS) ? pix_grey :
635 charging_mask & (1u<<CHGST_CHARGING)
636 ? pix_green : pix_blue);
638 setforeground(&gc_empty, alarmed ? pix_red : pix_black);
640 for (i=0, first_beyond=1; i<height; i++) {
643 TOP * exp( (double)i / (height-2) * log( (double)BOTTOM/TOP ) );
645 then= fill_norm + ratepersec_norm * elap;
648 ((charging_mask & (1u<<CHGST_DISCHARGING) && then <= 0.0) ||
649 (charging_mask & (1u<<CHGST_CHARGING) && then>=nondegraded_norm));
651 if (then <= 0.0) then= 0.0;
652 else if (then >= nondegraded_norm) then= nondegraded_norm;
654 leftmost_lit= width * then;
655 leftmost_nondeg= width * nondegraded_norm;
657 if (beyond && first_beyond) {
658 XDrawLine(disp, win, gc_white.gc, 0,i, leftmost_nondeg,i);
661 if (leftmost_lit < leftmost_nondeg)
662 XDrawLine(disp, win, gc_empty.gc,
663 leftmost_lit,i, leftmost_nondeg,i);
664 if (leftmost_lit >= 0)
665 XDrawLine(disp, win, gc_remain.gc, 0,i, leftmost_lit,i);
670 static void initgc(Gcstate *gc_r) {
673 memset(&gcv,0,sizeof(gcv));
674 gcv.function= GXcopy;
676 gc_r->lastfg= gcv.foreground= pix_white;
677 gc_r->gc= XCreateGC(disp,win, GCFunction|GCLineWidth|GCForeground, &gcv);
680 static void colour(unsigned long *pix_r, const char *whichcolour) {
685 name= getresource(whichcolour);
686 if (!name) fail("get colour resource");
688 st= XAllocNamedColor(disp,cmap,name,&xc,&xc);
694 static void initgraphics(int argc, char **argv) {
696 const char *geom_string;
697 XSizeHints *normal_hints;
699 XClassHint *class_hint;
700 int pos_x, pos_y, gravity;
701 char *program_name_silly;
703 program_name_silly= (char*)program_name;
705 normal_hints= XAllocSizeHints();
706 wm_hints= XAllocWMHints();
707 class_hint= XAllocClassHint();
709 if (!normal_hints || !wm_hints || !class_hint)
710 fail("could not alloc hint(s)");
712 geom_string= getresource("geometry");
714 xwmgr= XWMGeometry(disp,screen, geom_string,"128x32", 0,
720 win= XCreateSimpleWindow(disp,DefaultRootWindow(disp),
721 pos_x,pos_y,width,height,0,0,0);
722 cmap= DefaultColormap(disp,screen);
724 #define C(c,u) colour(&pix_##c, #u "Color");
725 #define GC(g) initgc(&gc_##g);
730 r= XSetWindowBackground(disp,win,pix_dimgrey);
731 if (!r) fail("init set background");
732 lastbackground= pix_dimgrey;
734 normal_hints->flags= PWinGravity;
735 normal_hints->win_gravity= gravity;
736 normal_hints->x= pos_x;
737 normal_hints->y= pos_y;
738 normal_hints->width= width;
739 normal_hints->height= height;
740 if ((xwmgr & XValue) || (xwmgr & YValue))
741 normal_hints->flags |= USPosition;
743 wm_hints->flags= InputHint;
744 wm_hints->input= False;
746 class_hint->res_name= program_name_silly;
747 class_hint->res_class= program_name_silly;
749 XmbSetWMProperties(disp,win, program_name,program_name,
750 argv,argc, normal_hints, wm_hints, class_hint);
752 XSelectInput(disp,win, ExposureMask|StructureNotifyMask);
753 XMapWindow(disp,win);
756 static void refresh(void) {
761 static void newgeometry(void) {
763 unsigned int udummy, gotwidth, gotheight;
766 XGetGeometry(disp,win, &dummyw,&dummy,&dummy, &gotwidth,&gotheight,
768 assert(gotwidth < INT_MAX);
769 assert(gotheight < INT_MAX);
774 static void eventloop(void) {
785 pfd.fd= ConnectionNumber(disp);
786 pfd.events= POLLIN|POLLERR;
788 timeout= !(charging_mask & (1u << CHGST_ERROR)) ? TIMEOUT : TIMEOUT_ONERROR;
789 r= poll(&pfd,1,timeout);
790 if (r==-1 && errno!=EINTR) failr("poll",errno);
792 while (XPending(disp)) {
793 XNextEvent(disp,&ev);
794 if (ev.type == ConfigureNotify) {
795 XConfigureEvent *ce= (void*)&ev;
804 int main(int argc, char **argv) {
805 parseargs(argc,argv);
807 initgraphics(argc,argv);