2 * The display is a lin-log chart of the charge over time.
3 * Time is on a log scale.
4 * The top pixel line is 60s from now.
5 * The bottom of the window is 1h from now.
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&discharging!
14 * lightgrey | 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&discharging, 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
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[]= "xbatmon-simple";
70 static int debug=-1, alarmlevel;
72 /*---------- general utility stuff and declarations ----------*/
74 static void fail(const char *m) {
75 fprintf(stderr,"error: %s\n", m);
78 static void badusage(void) { fail("bad usage"); }
80 typedef uint64_t value;
81 #define VAL_NOTFOUND (~(value)0)
83 typedef struct fileinfo fileinfo;
84 typedef int parser(const fileinfo*);
86 static parser parse_uevent;
94 /*---------- structure of and results from /sys/class/power/... ----------*/
95 /* variables this_... are the results from readbattery();
96 * if readbattery() succeeds the appropriate ones are all valid
97 * and not VAL_NOTFOUND
100 typedef struct batinfo_field {
103 const char *enumarray[10];
106 #define BAT_QTYS(_, _ec, EC_, PC_) \
107 _(design_capacity##_ec, BATTERY, EC_##FULL_DESIGN ) \
108 _(last_full_capacity##_ec, BATTERY, EC_##FULL ) \
109 _(remaining_capacity##_ec, BATTERY, EC_##NOW ) \
110 _(present_rate##_ec, BATTERY, PC_##NOW )
111 /* ENERGY [mWh]; POWER [mW]; CHARGE [uAh]; CURRENT [uA] */
113 #define UEVENT_ESSENTIAL_QUANTITY_FIELDS(_) \
114 _(present, BATTERY, PRESENT /* bool */ ) \
115 _(online, MAINS, ONLINE /* bool */ )
117 #define UEVENT_FUNKY_QUANTITY_FIELDS(_) \
118 BAT_QTYS(_,_energy,ENERGY_,POWER_) \
119 BAT_QTYS(_,_charge,CHARGE_,CURRENT_)
121 #define UEVENT_OPTIONAL_QUANTITY_FIELDS(_) \
122 _(voltage, BATTERY, VOLTAGE_NOW /* uV */ )
124 #define UEVENT_ENUM_FIELDS(_) \
125 _(state, BATTERY, STATUS, "Discharging","Charging","Full","Unknown" ) \
126 _(type, BOTH, TYPE, "Mains", "Battery" )
128 #define CHGST_DISCHARGING 0 /* Reflects order in _(state,...) above */
129 #define CHGST_CHARGING 1 /* Also, much code assumes exactly */
130 #define CHGST_CHARGED 2 /* these three possible states. */
131 #define CHGST_UNKNOWN 3 /* these three possible states. */
132 #define CHGST_ERROR 8 /* Except that this one is an extra bit. */
134 #define TYPE_MAINS 0 /* Reflects order in _(type,...) above */
135 #define TYPE_BATTERY 1 /* Also, much code assumes exactly these two */
136 #define TYPE_BOTH 100 /* Except this is a magic invalid value. */
138 #define SEPARATE_QUANTITY_FIELDS(_) \
139 /* See commit ec6f5f0be800bc5f2a27046833dba04e0c67ffac for
140 the code needed to use this */
143 #define ALL_DIRECT_VARS(_) \
144 UEVENT_ESSENTIAL_QUANTITY_FIELDS(_) \
145 UEVENT_FUNKY_QUANTITY_FIELDS(_) \
146 UEVENT_OPTIONAL_QUANTITY_FIELDS(_) \
147 UEVENT_ENUM_FIELDS(_) \
148 SEPARATE_QUANTITY_FIELDS(_)
150 #define ALL_VARS(_) \
154 #define ALL_NEEDED_FIELDS(_) \
155 UEVENT_ESSENTIAL_QUANTITY_FIELDS(_) \
156 UEVENT_ENUM_FIELDS(_) \
157 SEPARATE_QUANTITY_FIELDS(_)
159 #define ALL_PLAIN_ACCUMULATE_FIELDS(_) \
160 UEVENT_ESSENTIAL_QUANTITY_FIELDS(_) \
161 SEPARATE_QUANTITY_FIELDS(_)
163 #define ALL_ACCUMULATE_FIELDS(_) \
164 ALL_PLAIN_ACCUMULATE_FIELDS(_) \
168 #define F_VAR(f,...) \
169 static value this_##f;
172 #define Q_FLD(f,t,l) { "POWER_SUPPLY_" #l, &this_##f },
173 #define E_FLD(f,t,l,vl...) { "POWER_SUPPLY_" #l, &this_##f, { vl } },
175 static const batinfo_field uevent_fields[]= {
176 UEVENT_ESSENTIAL_QUANTITY_FIELDS(Q_FLD)
177 UEVENT_FUNKY_QUANTITY_FIELDS(Q_FLD)
178 UEVENT_OPTIONAL_QUANTITY_FIELDS(Q_FLD)
179 UEVENT_ENUM_FIELDS(E_FLD)
183 #define S_FLD(f,t,fn,vl...) \
184 static const batinfo_field bif_##f = { 0, &this_##f, { vl } };
185 SEPARATE_QUANTITY_FIELDS(S_FLD)
187 #define S_FILE(f,t,fn,vl...) { fn, parse_separate, &bif_##f },
189 static const fileinfo files[]= {
190 { "uevent", parse_uevent, uevent_fields },
191 SEPARATE_QUANTITY_FIELDS(S_FILE)
195 /*---------- parsing of one thingx in /sys/class/power/... ----------*/
197 /* variables private to the parser and its error handlers */
198 static char batlinebuf[1000];
199 static FILE *batfile;
200 static const char *batdirname;
201 static const char *batfilename;
202 static const char *batlinevalue;
204 static int batfailf(const char *why) {
206 fprintf(stderr,"%s/%s: %s value `%s': %s\n",
207 batdirname,batfilename, batlinebuf,batlinevalue,why);
209 fprintf(stderr,"%s/%s: %s: `%s'\n",
210 batdirname,batfilename, why, batlinebuf);
215 static int batfailc(const char *why) {
216 fprintf(stderr,"%s/%s: %s\n",
217 batdirname,batfilename, why);
221 static int batfaile(const char *syscall, const char *target) {
222 fprintf(stderr,"%s: failed to %s %s: %s\n",
223 batdirname ? batdirname : "*", syscall, target, strerror(errno));
227 static int chdir_base(void) {
230 r= chdir("/sys/class/power_supply");
231 if (r) return batfaile("chdir","/sys/class/power_supply");
236 static void tidybattery(void) {
237 if (batfile) { fclose(batfile); batfile=0; }
240 static int parse_value(const fileinfo *cfile, const batinfo_field *field) {
241 if (*field->valuep != VAL_NOTFOUND)
242 return batfailf("value specified multiple times");
244 if (!field->enumarray[0]) {
247 *field->valuep= strtoull(batlinevalue,&ep,10);
249 batfailf("value number syntax incorrect");
253 const char *const *enumsearch;
254 for (*field->valuep=0, enumsearch=field->enumarray;
255 *enumsearch && strcmp(*enumsearch,batlinevalue);
256 (*field->valuep)++, enumsearch++);
258 batfailf("unknown enum value");
264 static int parse_uevent(const fileinfo *cfile) {
265 char *equals= strchr(batlinebuf,'=');
267 return batfailf("line without a equals");
269 batlinevalue = equals+1;
271 const batinfo_field *field;
272 for (field=cfile->extra; field->label; field++) {
273 if (!strcmp(field->label,batlinebuf))
279 return parse_value(cfile, field);
282 static int readbattery(void) { /* 0=>ok, -1=>couldn't */
284 const fileinfo *cfile;
291 r= chdir(batdirname);
292 if (r) return batfaile("chdir",batdirname);
294 #define V_NOTFOUND(f,...) \
295 this_##f = VAL_NOTFOUND;
299 (batfilename= cfile->filename);
301 batfile= fopen(batfilename,"r");
303 if (errno == ENOENT) continue;
304 return batfaile("open",batfilename);
310 sr= fgets(batlinebuf,sizeof(batlinebuf),batfile);
311 if (ferror(batfile)) return batfaile("read",batfilename);
312 if (!sr && feof(batfile)) break;
313 l= strlen(batlinebuf);
315 if (batlinebuf[l-1] != '\n')
316 return batfailf("line too long");
319 if (cfile->parse(cfile))
328 printf("%s:\n",batdirname);
329 #define V_PRINT(f,...) \
330 printf(" %-30s = %20"PRId64"\n", #f, (int64_t)this_##f);
331 ALL_DIRECT_VARS(V_PRINT)
334 if (this_type == -1) {
335 /* some kernels don't seem to provide TYPE in the uevent
336 * guess the type from whether we see "present" or "online" */
337 if (this_online >= 0 && this_present == -1) this_type = TYPE_MAINS;
338 if (this_online == -1 && this_present >= 0) this_type = TYPE_BATTERY;
340 printf(" type absent from uevent %6s guessed %12s %"PRId64"\n",
344 int needsfields_MAINS = this_type == TYPE_MAINS;
345 int needsfields_BATTERY = this_type == TYPE_BATTERY;
346 int needsfields_BOTH = 1;
350 #define V_NEEDED(f,t,...) \
351 if (needsfields_##t && this_##f == VAL_NOTFOUND) { \
352 fprintf(stderr,"%s: %s: not found\n", \
356 ALL_NEEDED_FIELDS(V_NEEDED)
358 if (missing) return -1;
363 /*---------- data collection and analysis ----------*/
365 /* These next three variables are the results of the charging state */
366 static unsigned charging_mask; /* 1u<<CHGST_* | ... */
367 static double nondegraded_norm, fill_norm, ratepersec_norm;
370 #define Q_VAR(f,t,...) \
371 static double total_##f;
372 ALL_ACCUMULATE_FIELDS(Q_VAR)
374 static void acquiredata(void) {
382 if (debug) printf("\n");
384 #define Q_ZERO(f,t,...) \
386 ALL_ACCUMULATE_FIELDS(Q_ZERO)
391 di= opendir("."); if (!di) { batfaile("opendir","battery"); goto bad; }
392 while ((de= readdir(di))) {
393 if (de->d_name[0]==0 || de->d_name[0]=='.') continue;
395 batdirname= de->d_name;
401 charging_mask |= (1u << CHGST_ERROR);
405 if (this_type == TYPE_BATTERY) {
409 charging_mask |= 1u << this_state;
411 #define QTY_SUPPLIED(f,...) this_##f != VAL_NOTFOUND &&
412 #define QTY_USE_ENERGY(f,...) this_##f = this_##f##_energy;
413 #define QTY_USE_CHARGE(f,...) this_##f = this_##f##_charge;
415 double funky_multiplier;
416 if (BAT_QTYS(QTY_SUPPLIED,_energy,,) 1) {
417 if (debug) printf(" using energy\n");
418 BAT_QTYS(QTY_USE_ENERGY,,,);
419 funky_multiplier = 1.0;
420 } else if (BAT_QTYS(QTY_SUPPLIED,_charge,,)
421 this_voltage != VAL_NOTFOUND) {
422 if (debug) printf(" using charge\n");
423 BAT_QTYS(QTY_USE_CHARGE,,,);
424 funky_multiplier = this_voltage * 1e-6;
426 batfailc("neither complete set of energy nor charge");
429 if (this_state == CHGST_DISCHARGING)
431 total_present_rate -= 2.0 * this_present_rate * funky_multiplier;
433 #define Q_ACCUMULATE_FUNKY(f,...) \
434 total_##f += this_##f * funky_multiplier;
435 BAT_QTYS(Q_ACCUMULATE_FUNKY,,,)
438 #define Q_ACCUMULATE_PLAIN(f,t,...) \
439 if (this_type == TYPE_##t) \
440 total_##f += this_##f;
441 ALL_PLAIN_ACCUMULATE_FIELDS(Q_ACCUMULATE_PLAIN)
445 if (di) closedir(di);
449 printf(" %-30s = %#20x\n", "mask", charging_mask);
450 #define T_PRINT(f,...) \
451 printf(" %-30s = %20.6f\n", #f, total_##f);
453 ALL_PLAIN_ACCUMULATE_FIELDS(T_PRINT)
456 if ((charging_mask & (1u<<CHGST_DISCHARGING)) &&
457 !total_online/*mains*/) {
458 double time_remaining =
459 -total_remaining_capacity * 3600.0 / total_present_rate;
460 if (debug) printf(" %-30s = %20.6f\n", "time remaining", time_remaining);
461 if (time_remaining < alarmlevel)
465 if (total_design_capacity < 0.5)
466 total_design_capacity= 1.0;
468 if (total_last_full_capacity < total_remaining_capacity)
469 total_last_full_capacity= total_remaining_capacity;
470 if (total_design_capacity < total_last_full_capacity)
471 total_design_capacity= total_last_full_capacity;
473 nondegraded_norm= total_last_full_capacity / total_design_capacity;
474 fill_norm= total_remaining_capacity / total_design_capacity;
475 ratepersec_norm= total_present_rate
476 / (3600.0 * total_design_capacity);
479 static void initacquire(void) {
482 /*---------- argument parsing ----------*/
485 C(blue, discharging) \
488 C(lightgrey, notcharging) \
492 C(dimgrey, degraded) \
493 C(darkgreen, absent) \
495 C(white, equilibrium) \
500 static XrmDatabase xrm;
501 static Display *disp;
503 static const char *parentwindow;
505 static const char defaultresources[]=
508 "*" #u "Color: " #c "\n"
514 #define S(s) ((char*)(s))
515 static const XrmOptionDescRec optiontable[]= {
516 { S("-debug"), S("*debug"), XrmoptionIsArg },
517 { S("-warningTime"), S("*warningTime"), XrmoptionSepArg },
518 { S("-display"), S("*display"), XrmoptionSepArg },
519 { S("-geometry"), S("*geometry"), XrmoptionSepArg },
520 { S("-into"), S("*parentWindow"), XrmoptionSepArg },
521 { S("-iconic"), S("*iconic"), XrmoptionIsArg },
522 { S("-withdrawn"), S("*withdrawn"), XrmoptionIsArg },
525 { S("-" #u "Color"), S("*" #u "Color"), XrmoptionSepArg }, \
526 { S("-" #u "Colour"), S("*" #u "Color"), XrmoptionSepArg },
532 static const char *getresource(const char *want) {
533 char name_buf[256], class_buf[256];
535 char *rep_type_dummy;
538 assert(strlen(want) < 128);
540 sprintf(name_buf,"xbatmon-simple.%s",want);
541 sprintf(class_buf,"Xbatmon-Simple.%s",want);
543 r= XrmGetResource(xrm, name_buf,class_buf, &rep_type_dummy, &val);
544 if (r) return val.addr;
546 sprintf(name_buf,"xacpi-simple.%s",want);
547 sprintf(class_buf,"Xacpi-Simple.%s",want);
549 r= XrmGetResource(xrm, name_buf,class_buf, &rep_type_dummy, &val);
550 if (r) return val.addr;
555 static int getresource_bool(const char *want, int def, int *cache) {
556 /* *cache should be initialised to -1 and will be set to !!value
557 * alternatively cache==0 is allowed */
559 if (cache && *cache >= 0) return *cache;
561 const char *str= getresource(want);
565 long l= strtol(str,&ep,0);
570 case 't': case 'T': case 'y': case 'Y': result= 1; break;
571 case 'f': case 'F': case 'n': case 'N': result= 0; break;
572 case '-': /* option name from XrmoptionIsArg */ result= 1; break;
577 if (cache) *cache= result;
581 static void more_resources(const char *str, const char *why) {
586 more= XrmGetStringDatabase((char*)str);
587 if (!more) fail(why);
588 XrmCombineDatabase(more,&xrm,0);
591 static void parseargs(int argc, char **argv) {
592 Screen *screenscreen;
596 XrmParseCommand(&xrm, (XrmOptionDescRec*)optiontable,
597 sizeof(optiontable)/sizeof(*optiontable),
598 program_name, &argc, argv);
600 if (argc>1) badusage();
602 getresource_bool("debug",0,&debug);
604 const char *alarmlevel_string= getresource("alarmLevel");
605 alarmlevel = alarmlevel_string ? atoi(alarmlevel_string) : 300;
607 parentwindow = getresource("parentWindow");
609 disp= XOpenDisplay(getresource("display"));
610 if (!disp) fail("could not open display");
612 screen= DefaultScreen(disp);
614 screenscreen= ScreenOfDisplay(disp,screen);
615 if (!screenscreen) fail("screenofdisplay");
616 more_resources(XScreenResourceString(screenscreen), "screen resources");
617 more_resources(XResourceManagerString(disp), "display resources");
618 more_resources(defaultresources, "default resources");
621 /*---------- display ----------*/
624 static int width, height;
625 static Colormap cmap;
626 static unsigned long lastbackground;
630 unsigned long lastfg;
633 #define C(c,u) static unsigned long pix_##u;
634 #define GC(g) static Gcstate gc_##g;
639 static void refresh(void);
641 #define CHGMASK_CHG_DIS ((1u<<CHGST_CHARGING) | (1u<<CHGST_DISCHARGING))
643 static void failr(const char *m, int r) {
644 fprintf(stderr,"error: %s (code %d)\n", m, r);
648 static void setbackground(unsigned long newbg) {
651 if (newbg == lastbackground) return;
652 r= XSetWindowBackground(disp,win,newbg);
653 if (!r) fail("XSetWindowBackground");
654 lastbackground= newbg;
657 static void setforeground(Gcstate *g, unsigned long px) {
661 if (g->lastfg == px) return;
663 memset(&gcv,0,sizeof(gcv));
664 g->lastfg= gcv.foreground= px;
665 r= XChangeGC(disp,g->gc,GCForeground,&gcv);
666 if (!r) fail("XChangeGC");
669 static void show_solid(unsigned long px) {
671 XClearWindow(disp,win);
674 static void show(void) {
676 int i, leftmost_lit, leftmost_nondeg, beyond, first_beyond;
679 return show_solid(pix_absent);
681 if (charging_mask & (1u << CHGST_ERROR))
682 return show_solid(pix_error);
684 setbackground(pix_degraded);
685 XClearWindow(disp,win);
687 setforeground(&gc_remain,
688 !(charging_mask & CHGMASK_CHG_DIS) ?
689 (~charging_mask & (1u << CHGST_CHARGED) ?
690 pix_notcharging : pix_charged) :
691 !(~charging_mask & CHGMASK_CHG_DIS) ? pix_confusing :
692 charging_mask & (1u<<CHGST_CHARGING)
693 ? pix_charging : pix_discharging);
695 setforeground(&gc_empty, alarmed ? pix_low : pix_normal);
697 for (i=0, first_beyond=1; i<height; i++) {
700 TOP * exp( (double)i / (height-2) * log( (double)BOTTOM/TOP ) );
702 then= fill_norm + ratepersec_norm * elap;
705 ((charging_mask & (1u<<CHGST_DISCHARGING) && then <= 0.0) ||
706 (charging_mask & (1u<<CHGST_CHARGING) && then>=nondegraded_norm));
708 if (then <= 0.0) then= 0.0;
709 else if (then >= nondegraded_norm) then= nondegraded_norm;
711 leftmost_lit= width * then;
712 leftmost_nondeg= width * nondegraded_norm;
714 if (beyond && first_beyond) {
715 XDrawLine(disp, win, gc_white.gc, 0,i, leftmost_nondeg,i);
718 if (leftmost_lit < leftmost_nondeg)
719 XDrawLine(disp, win, gc_empty.gc,
720 leftmost_lit,i, leftmost_nondeg,i);
721 if (leftmost_lit >= 0)
722 XDrawLine(disp, win, gc_remain.gc, 0,i, leftmost_lit,i);
727 static void initgc(Gcstate *gc_r) {
730 memset(&gcv,0,sizeof(gcv));
731 gcv.function= GXcopy;
733 gc_r->lastfg= gcv.foreground= pix_equilibrium;
734 gc_r->gc= XCreateGC(disp,win, GCFunction|GCLineWidth|GCForeground, &gcv);
737 static void colour(unsigned long *pix_r, const char *whichcolour) {
742 name= getresource(whichcolour);
743 if (!name) fail("get colour resource");
745 st= XAllocNamedColor(disp,cmap,name,&xc,&xc);
751 static void initgraphics(int argc, char **argv) {
753 const char *geom_string;
754 XSizeHints *normal_hints;
756 XClassHint *class_hint;
757 int pos_x, pos_y, gravity;
758 char *program_name_silly;
760 program_name_silly= (char*)program_name;
762 normal_hints= XAllocSizeHints();
763 wm_hints= XAllocWMHints();
764 class_hint= XAllocClassHint();
766 if (!normal_hints || !wm_hints || !class_hint)
767 fail("could not alloc hint(s)");
769 geom_string= getresource("geometry");
771 xwmgr= XWMGeometry(disp,screen, geom_string,"128x32", 0,
777 unsigned long parentwindowid;
779 parentwindowid = strtoul(parentwindow,0,0);
781 parentwindowid = DefaultRootWindow(disp);
783 win= XCreateSimpleWindow(disp,parentwindowid,
784 pos_x,pos_y,width,height,0,0,0);
785 cmap= DefaultColormap(disp,screen);
787 #define C(c,u) colour(&pix_##u, #u "Color");
788 #define GC(g) initgc(&gc_##g);
793 r= XSetWindowBackground(disp,win,pix_degraded);
794 if (!r) fail("init set background");
795 lastbackground= pix_degraded;
797 normal_hints->flags= PWinGravity;
798 normal_hints->win_gravity= gravity;
799 normal_hints->x= pos_x;
800 normal_hints->y= pos_y;
801 normal_hints->width= width;
802 normal_hints->height= height;
803 if ((xwmgr & XValue) || (xwmgr & YValue))
804 normal_hints->flags |= USPosition;
806 wm_hints->flags= InputHint;
807 wm_hints->input= False;
808 wm_hints->initial_state=
809 (getresource_bool("withdrawn",0,0) ? WithdrawnState :
810 getresource_bool("iconic",0,0) ? IconicState
813 class_hint->res_name= program_name_silly;
814 class_hint->res_class= program_name_silly;
816 XmbSetWMProperties(disp,win, program_name,program_name,
817 argv,argc, normal_hints, wm_hints, class_hint);
819 XSelectInput(disp,win, ExposureMask|StructureNotifyMask);
820 XMapWindow(disp,win);
823 static void refresh(void) {
828 static void newgeometry(void) {
832 XGetGeometry(disp,win, &dummyw,&dummy,&dummy, &width,&height, &dummy,&dummy);
835 static void eventloop(void) {
846 pfd.fd= ConnectionNumber(disp);
847 pfd.events= POLLIN|POLLERR;
849 timeout= !(charging_mask & (1u << CHGST_ERROR)) ? TIMEOUT : TIMEOUT_ONERROR;
850 r= poll(&pfd,1,timeout);
851 if (r==-1 && errno!=EINTR) failr("poll",errno);
853 while (XPending(disp)) {
854 XNextEvent(disp,&ev);
855 if (ev.type == ConfigureNotify) {
856 XConfigureEvent *ce= (void*)&ev;
865 int main(int argc, char **argv) {
866 parseargs(argc,argv);
868 initgraphics(argc,argv);