6 * display outputs, per line:
8 * Remaining: | Empty: | Degraded:
9 * blue | black | dimgrey discharging
10 * green | black | dimgrey charging
11 * cyan | black | dimgrey charged
12 * grey | black | dimgrey charging&discharching!
13 * darkcyan | black | dimgrey none of the above
14 * blue | red | dimgrey discharging - low!
15 * green | red | dimgrey charging - low
16 * cyan | red | dimgrey charged - low [1]
17 * grey | red | dimgrey charging&discharching, low [1]
18 * ... darkgreen ... no batteries present
19 * ... yellow ... error
21 * [1] battery must be quite badly degraded
24 * Copyright (C) 2004 Ian Jackson <ian@davenant.greenend.org.uk>
26 * This is free software; you can redistribute it and/or modify
27 * it under the terms of the GNU General Public License as
28 * published by the Free Software Foundation; either version 3,
29 * or (at your option) any later version.
31 * This is distributed in the hope that it will be useful, but
32 * WITHOUT ANY WARRANTY; without even the implied warranty of
33 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
34 * GNU General Public License for more details.
36 * You should have received a copy of the GNU General Public
37 * License along with this file; if not, consult the Free Software
38 * 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";
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;
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(_, _ec, EC_, PC_) \
106 _(design_capacity##_ec, BATTERY, EC_##FULL_DESIGN ) \
107 _(last_full_capacity##_ec, BATTERY, EC_##FULL ) \
108 _(remaining_capacity##_ec, BATTERY, EC_##NOW ) \
109 _(present_rate##_ec, BATTERY, PC_##NOW )
110 /* ENERGY [mWh]; POWER [mW]; CHARGE [uAh]; CURRENT [uA] */
112 #define UEVENT_ESSENTIAL_QUANTITY_FIELDS(_) \
113 _(present, BATTERY, PRESENT /* bool */ ) \
114 _(online, MAINS, ONLINE /* bool */ )
116 #define UEVENT_FUNKY_QUANTITY_FIELDS(_) \
117 BAT_QTYS(_,_energy,ENERGY_,POWER_) \
118 BAT_QTYS(_,_charge,CHARGE_,CURRENT_)
120 #define UEVENT_OPTIONAL_QUANTITY_FIELDS(_) \
121 _(voltage, BATTERY, VOLTAGE_NOW /* uV */ )
123 #define UEVENT_ENUM_FIELDS(_) \
124 _(state, BATTERY, STATUS, "Discharging","Charging","Full","Unknown" ) \
125 _(type, BOTH, TYPE, "Mains", "Battery" )
127 #define CHGST_DISCHARGING 0 /* Reflects order in _(state,...) above */
128 #define CHGST_CHARGING 1 /* Also, much code assumes exactly */
129 #define CHGST_CHARGED 2 /* these three possible states. */
130 #define CHGST_UNKNOWN 3 /* these three possible states. */
131 #define CHGST_ERROR 8 /* Except that this one is an extra bit. */
133 #define TYPE_MAINS 0 /* Reflects order in _(type,...) above */
134 #define TYPE_BATTERY 1 /* Also, much code assumes exactly these two */
135 #define TYPE_BOTH 100 /* Except this is a magic invalid value. */
137 #define SEPARATE_QUANTITY_FIELDS(_) \
138 _(alarm, BATTERY, "alarm", "0", "1")
141 #define ALL_DIRECT_VARS(_) \
142 UEVENT_ESSENTIAL_QUANTITY_FIELDS(_) \
143 UEVENT_FUNKY_QUANTITY_FIELDS(_) \
144 UEVENT_OPTIONAL_QUANTITY_FIELDS(_) \
145 UEVENT_ENUM_FIELDS(_) \
146 SEPARATE_QUANTITY_FIELDS(_)
148 #define ALL_VARS(_) \
152 #define ALL_NEEDED_FIELDS(_) \
153 UEVENT_ESSENTIAL_QUANTITY_FIELDS(_) \
154 UEVENT_ENUM_FIELDS(_) \
155 SEPARATE_QUANTITY_FIELDS(_)
157 #define ALL_PLAIN_ACCUMULATE_FIELDS(_) \
158 UEVENT_ESSENTIAL_QUANTITY_FIELDS(_) \
159 UEVENT_ENUM_FIELDS(_) \
160 SEPARATE_QUANTITY_FIELDS(_)
162 #define ALL_ACCUMULATE_FIELDS(_) \
163 ALL_PLAIN_ACCUMULATE_FIELDS(_) \
167 #define F_VAR(f,...) \
168 static value this_##f;
171 #define Q_FLD(f,t,l) { "POWER_SUPPLY_" #l, &this_##f },
172 #define E_FLD(f,t,l,vl...) { "POWER_SUPPLY_" #l, &this_##f, { vl } },
174 static const batinfo_field uevent_fields[]= {
175 UEVENT_ESSENTIAL_QUANTITY_FIELDS(Q_FLD)
176 UEVENT_FUNKY_QUANTITY_FIELDS(Q_FLD)
177 UEVENT_OPTIONAL_QUANTITY_FIELDS(Q_FLD)
178 UEVENT_ENUM_FIELDS(E_FLD)
182 #define S_FLD(f,t,fn,vl...) \
183 static const batinfo_field bif_##f = { 0, &this_##f, { vl } };
184 SEPARATE_QUANTITY_FIELDS(S_FLD)
186 #define S_FILE(f,t,fn,vl...) { fn, parse_separate, &bif_##f },
188 static const fileinfo files[]= {
189 { "uevent", parse_uevent, uevent_fields },
190 SEPARATE_QUANTITY_FIELDS(S_FILE)
194 /*---------- parsing of one thingx in /sys/class/power/... ----------*/
196 /* variables private to the parser and its error handlers */
197 static char batlinebuf[1000];
198 static FILE *batfile;
199 static const char *batdirname;
200 static const char *batfilename;
201 static const char *batlinevalue;
203 static int batfailf(const char *why) {
205 fprintf(stderr,"%s/%s: %s value `%s': %s\n",
206 batdirname,batfilename, batlinebuf,batlinevalue,why);
208 fprintf(stderr,"%s/%s: %s: `%s'\n",
209 batdirname,batfilename, why, batlinebuf);
214 static int batfailc(const char *why) {
215 fprintf(stderr,"%s/%s: %s\n",
216 batdirname,batfilename, why);
220 static int batfaile(const char *syscall, const char *target) {
221 fprintf(stderr,"%s: failed to %s %s: %s\n",
222 batdirname ? batdirname : "*", syscall, target, strerror(errno));
226 static int chdir_base(void) {
229 r= chdir("/sys/class/power_supply");
230 if (r) return batfaile("chdir","/sys/class/power_supply");
235 static void tidybattery(void) {
236 if (batfile) { fclose(batfile); batfile=0; }
239 static int parse_value(const fileinfo *cfile, const batinfo_field *field) {
240 if (*field->valuep != VAL_NOTFOUND)
241 return batfailf("value specified multiple times");
243 if (!field->enumarray[0]) {
246 *field->valuep= strtoull(batlinevalue,&ep,10);
248 batfailf("value number syntax incorrect");
252 const char *const *enumsearch;
253 for (*field->valuep=0, enumsearch=field->enumarray;
254 *enumsearch && strcmp(*enumsearch,batlinevalue);
255 (*field->valuep)++, enumsearch++);
257 batfailf("unknown enum value");
263 static int parse_uevent(const fileinfo *cfile) {
264 char *equals= strchr(batlinebuf,'=');
266 return batfailf("line without a equals");
268 batlinevalue = equals+1;
270 const batinfo_field *field;
271 for (field=cfile->extra; field->label; field++) {
272 if (!strcmp(field->label,batlinebuf))
278 return parse_value(cfile, field);
281 static int readbattery(void) { /* 0=>ok, -1=>couldn't */
283 const fileinfo *cfile;
290 r= chdir(batdirname);
291 if (r) return batfaile("chdir",batdirname);
293 #define V_NOTFOUND(f,...) \
294 this_##f = VAL_NOTFOUND;
298 (batfilename= cfile->filename);
300 batfile= fopen(batfilename,"r");
302 if (errno == ENOENT) continue;
303 return batfaile("open",batfilename);
309 sr= fgets(batlinebuf,sizeof(batlinebuf),batfile);
310 if (ferror(batfile)) return batfaile("read",batfilename);
311 if (!sr && feof(batfile)) break;
312 l= strlen(batlinebuf);
314 if (batlinebuf[l-1] != '\n')
315 return batfailf("line too long");
318 if (cfile->parse(cfile))
327 printf("%s:\n",batdirname);
328 #define V_PRINT(f,...) \
329 printf(" %-30s = %20"PRId64"\n", #f, (int64_t)this_##f);
330 ALL_DIRECT_VARS(V_PRINT)
333 int needsfields_MAINS = this_type == TYPE_MAINS;
334 int needsfields_BATTERY = this_type == TYPE_BATTERY;
335 int needsfields_BOTH = 1;
339 #define V_NEEDED(f,t,...) \
340 if (needsfields_##t && this_##f == VAL_NOTFOUND) { \
341 fprintf(stderr,"%s: %s: not found\n", \
345 ALL_NEEDED_FIELDS(V_NEEDED)
347 if (missing) return -1;
352 /*---------- data collection and analysis ----------*/
354 /* These next three variables are the results of the charging state */
355 static unsigned charging_mask; /* 1u<<CHGST_* | ... */
356 static double nondegraded_norm, fill_norm, ratepersec_norm;
357 static int alarm_level; /* 0=ok, 1=low */
359 #define Q_VAR(f,t,...) \
360 static double total_##f;
361 ALL_ACCUMULATE_FIELDS(Q_VAR)
363 static void acquiredata(void) {
370 #define Q_ZERO(f,t,...) \
372 ALL_ACCUMULATE_FIELDS(Q_ZERO)
377 di= opendir("."); if (!di) { batfaile("opendir","battery"); goto bad; }
378 while ((de= readdir(di))) {
379 if (de->d_name[0]==0 || de->d_name[0]=='.') continue;
381 batdirname= de->d_name;
387 charging_mask |= (1u << CHGST_ERROR);
391 if (this_type == TYPE_BATTERY) {
395 charging_mask |= 1u << this_state;
397 #define QTY_SUPPLIED(f,...) this_##f != VAL_NOTFOUND &&
398 #define QTY_USE_ENERGY(f,...) this_##f = this_##f##_energy;
399 #define QTY_USE_CHARGE(f,...) this_##f = this_##f##_charge;
401 double funky_multiplier;
402 if (BAT_QTYS(QTY_SUPPLIED,_energy,,) 1) {
403 if (debug) printf(" using energy\n");
404 BAT_QTYS(QTY_USE_ENERGY,,,);
405 funky_multiplier = 1.0;
406 } else if (BAT_QTYS(QTY_SUPPLIED,_charge,,)
407 this_voltage != VAL_NOTFOUND) {
408 if (debug) printf(" using charge\n");
409 BAT_QTYS(QTY_USE_CHARGE,,,);
410 funky_multiplier = this_voltage * 1e-6;
412 batfailc("neither complete set of energy nor charge");
415 if (this_state == CHGST_DISCHARGING)
417 total_present_rate -= 2.0 * this_present_rate * funky_multiplier;
419 #define Q_ACCUMULATE_FUNKY(f,...) \
420 total_##f += this_##f * funky_multiplier;
421 BAT_QTYS(Q_ACCUMULATE_FUNKY,,,)
424 #define Q_ACCUMULATE_PLAIN(f,t,...) \
425 if (this_type == TYPE_##t) \
426 total_##f += this_##f;
427 ALL_PLAIN_ACCUMULATE_FIELDS(Q_ACCUMULATE_PLAIN)
434 #define T_PRINT(f,...) \
435 printf(" %-30s = %20.6f\n", #f, total_##f);
437 ALL_PLAIN_ACCUMULATE_FIELDS(T_PRINT)
439 if (total_design_capacity < 0.5)
440 total_design_capacity= 1.0;
442 if (total_last_full_capacity < total_remaining_capacity)
443 total_last_full_capacity= total_remaining_capacity;
444 if (total_design_capacity < total_last_full_capacity)
445 total_design_capacity= total_last_full_capacity;
447 alarm_level= total_alarm && (charging_mask & 1u << CHGST_DISCHARGING);
449 nondegraded_norm= total_last_full_capacity / total_design_capacity;
450 fill_norm= total_remaining_capacity / total_design_capacity;
451 ratepersec_norm= total_present_rate
452 / (3600.0 * total_design_capacity);
455 static void initacquire(void) {
458 /*---------- argument parsing ----------*/
461 C(blue, discharging) \
464 C(darkcyan, notcharging) \
468 C(dimgrey, degraded) \
469 C(darkgreen, absent) \
471 C(white, equilibrium) \
476 static XrmDatabase xrm;
477 static Display *disp;
480 static const char defaultresources[]=
483 "*" #u "Color: " #c "\n"
489 #define S(s) ((char*)(s))
490 static const XrmOptionDescRec optiontable[]= {
491 { S("-debug"), S("*debug"), XrmoptionIsArg },
492 { S("-display"), S("*display"), XrmoptionSepArg },
493 { S("-geometry"), S("*geometry"), XrmoptionSepArg },
496 { S("-" #u "Color"), S("*" #u "Color"), XrmoptionSepArg }, \
497 { S("-" #u "Colour"), S("*" #u "Color"), XrmoptionSepArg },
503 static const char *getresource(const char *want) {
504 char name_buf[256], class_buf[256];
506 char *rep_type_dummy;
509 assert(strlen(want) < 128);
510 sprintf(name_buf,"xacpi-simple.%s",want);
511 sprintf(class_buf,"Xacpi-Simple.%s",want);
513 r= XrmGetResource(xrm, name_buf,class_buf, &rep_type_dummy, &val);
519 static void more_resources(const char *str, const char *why) {
524 more= XrmGetStringDatabase((char*)str);
525 if (!more) fail(why);
526 XrmCombineDatabase(more,&xrm,0);
529 static void parseargs(int argc, char **argv) {
530 Screen *screenscreen;
534 XrmParseCommand(&xrm, (XrmOptionDescRec*)optiontable,
535 sizeof(optiontable)/sizeof(*optiontable),
536 program_name, &argc, argv);
538 if (argc>1) badusage();
540 debug= !!getresource("debug");
542 disp= XOpenDisplay(getresource("display"));
543 if (!disp) fail("could not open display");
545 screen= DefaultScreen(disp);
547 screenscreen= ScreenOfDisplay(disp,screen);
548 if (!screenscreen) fail("screenofdisplay");
549 more_resources(XScreenResourceString(screenscreen), "screen resources");
550 more_resources(XResourceManagerString(disp), "display resources");
551 more_resources(defaultresources, "default resources");
554 /*---------- display ----------*/
557 static int width, height;
558 static Colormap cmap;
559 static unsigned long lastbackground;
563 unsigned long lastfg;
566 #define C(c,u) static unsigned long pix_##c;
567 #define GC(g) static Gcstate gc_##g;
572 static void refresh(void);
574 #define CHGMASK_CHG_DIS ((1u<<CHGST_CHARGING) | (1u<<CHGST_DISCHARGING))
576 static void failr(const char *m, int r) {
577 fprintf(stderr,"error: %s (code %d)\n", m, r);
581 static void setbackground(unsigned long newbg) {
584 if (newbg == lastbackground) return;
585 r= XSetWindowBackground(disp,win,newbg);
586 if (!r) fail("XSetWindowBackground");
587 lastbackground= newbg;
590 static void setforeground(Gcstate *g, unsigned long px) {
594 if (g->lastfg == px) return;
596 memset(&gcv,0,sizeof(gcv));
597 g->lastfg= gcv.foreground= px;
598 r= XChangeGC(disp,g->gc,GCForeground,&gcv);
599 if (!r) fail("XChangeGC");
602 static void show_solid(unsigned long px) {
604 XClearWindow(disp,win);
607 static void show(void) {
609 int i, leftmost_lit, leftmost_nondeg, beyond, first_beyond;
612 return show_solid(pix_darkgreen);
614 if (charging_mask & (1u << CHGST_ERROR))
615 return show_solid(pix_yellow);
617 setbackground(pix_dimgrey);
618 XClearWindow(disp,win);
620 setforeground(&gc_remain,
621 !(charging_mask & CHGMASK_CHG_DIS) ?
622 (~charging_mask & (1u << CHGST_CHARGED) ?
623 pix_darkcyan : pix_cyan) :
624 !(~charging_mask & CHGMASK_CHG_DIS) ? pix_grey :
625 charging_mask & (1u<<CHGST_CHARGING)
626 ? pix_green : pix_blue);
628 setforeground(&gc_empty, alarm_level ? pix_red : pix_black);
630 for (i=0, first_beyond=1; i<height; i++) {
633 TOP * exp( (double)i / (height-2) * log( (double)BOTTOM/TOP ) );
635 then= fill_norm + ratepersec_norm * elap;
638 ((charging_mask & (1u<<CHGST_DISCHARGING) && then <= 0.0) ||
639 (charging_mask & (1u<<CHGST_CHARGING) && then>=nondegraded_norm));
641 if (then <= 0.0) then= 0.0;
642 else if (then >= nondegraded_norm) then= nondegraded_norm;
644 leftmost_lit= width * then;
645 leftmost_nondeg= width * nondegraded_norm;
647 if (beyond && first_beyond) {
648 XDrawLine(disp, win, gc_white.gc, 0,i, leftmost_nondeg,i);
651 if (leftmost_lit < leftmost_nondeg)
652 XDrawLine(disp, win, gc_empty.gc,
653 leftmost_lit,i, leftmost_nondeg,i);
654 if (leftmost_lit >= 0)
655 XDrawLine(disp, win, gc_remain.gc, 0,i, leftmost_lit,i);
660 static void initgc(Gcstate *gc_r) {
663 memset(&gcv,0,sizeof(gcv));
664 gcv.function= GXcopy;
666 gc_r->lastfg= gcv.foreground= pix_white;
667 gc_r->gc= XCreateGC(disp,win, GCFunction|GCLineWidth|GCForeground, &gcv);
670 static void colour(unsigned long *pix_r, const char *whichcolour) {
675 name= getresource(whichcolour);
676 if (!name) fail("get colour resource");
678 st= XAllocNamedColor(disp,cmap,name,&xc,&xc);
684 static void initgraphics(int argc, char **argv) {
686 const char *geom_string;
687 XSizeHints *normal_hints;
689 XClassHint *class_hint;
690 int pos_x, pos_y, gravity;
691 char *program_name_silly;
693 program_name_silly= (char*)program_name;
695 normal_hints= XAllocSizeHints();
696 wm_hints= XAllocWMHints();
697 class_hint= XAllocClassHint();
699 if (!normal_hints || !wm_hints || !class_hint)
700 fail("could not alloc hint(s)");
702 geom_string= getresource("geometry");
704 xwmgr= XWMGeometry(disp,screen, geom_string,"128x32", 0,
710 win= XCreateSimpleWindow(disp,DefaultRootWindow(disp),
711 pos_x,pos_y,width,height,0,0,0);
712 cmap= DefaultColormap(disp,screen);
714 #define C(c,u) colour(&pix_##c, #u "Color");
715 #define GC(g) initgc(&gc_##g);
720 r= XSetWindowBackground(disp,win,pix_dimgrey);
721 if (!r) fail("init set background");
722 lastbackground= pix_dimgrey;
724 normal_hints->flags= PWinGravity;
725 normal_hints->win_gravity= gravity;
726 normal_hints->x= pos_x;
727 normal_hints->y= pos_y;
728 normal_hints->width= width;
729 normal_hints->height= height;
730 if ((xwmgr & XValue) || (xwmgr & YValue))
731 normal_hints->flags |= USPosition;
733 wm_hints->flags= InputHint;
734 wm_hints->input= False;
736 class_hint->res_name= program_name_silly;
737 class_hint->res_class= program_name_silly;
739 XmbSetWMProperties(disp,win, program_name,program_name,
740 argv,argc, normal_hints, wm_hints, class_hint);
742 XSelectInput(disp,win, ExposureMask|StructureNotifyMask);
743 XMapWindow(disp,win);
746 static void refresh(void) {
751 static void newgeometry(void) {
753 unsigned int udummy, gotwidth, gotheight;
756 XGetGeometry(disp,win, &dummyw,&dummy,&dummy, &gotwidth,&gotheight,
758 assert(gotwidth < INT_MAX);
759 assert(gotheight < INT_MAX);
764 static void eventloop(void) {
775 pfd.fd= ConnectionNumber(disp);
776 pfd.events= POLLIN|POLLERR;
778 timeout= !(charging_mask & (1u << CHGST_ERROR)) ? TIMEOUT : TIMEOUT_ONERROR;
779 r= poll(&pfd,1,timeout);
780 if (r==-1 && errno!=EINTR) failr("poll",errno);
782 while (XPending(disp)) {
783 XNextEvent(disp,&ev);
784 if (ev.type == ConfigureNotify) {
785 XConfigureEvent *ce= (void*)&ev;
794 int main(int argc, char **argv) {
795 parseargs(argc,argv);
797 initgraphics(argc,argv);