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 * lightgrey | 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=-1, 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 SEPARATE_QUANTITY_FIELDS(_)
158 #define ALL_ACCUMULATE_FIELDS(_) \
159 ALL_PLAIN_ACCUMULATE_FIELDS(_) \
163 #define F_VAR(f,...) \
164 static value this_##f;
167 #define Q_FLD(f,t,l) { "POWER_SUPPLY_" #l, &this_##f },
168 #define E_FLD(f,t,l,vl...) { "POWER_SUPPLY_" #l, &this_##f, { vl } },
170 static const batinfo_field uevent_fields[]= {
171 UEVENT_ESSENTIAL_QUANTITY_FIELDS(Q_FLD)
172 UEVENT_FUNKY_QUANTITY_FIELDS(Q_FLD)
173 UEVENT_OPTIONAL_QUANTITY_FIELDS(Q_FLD)
174 UEVENT_ENUM_FIELDS(E_FLD)
178 #define S_FLD(f,t,fn,vl...) \
179 static const batinfo_field bif_##f = { 0, &this_##f, { vl } };
180 SEPARATE_QUANTITY_FIELDS(S_FLD)
182 #define S_FILE(f,t,fn,vl...) { fn, parse_separate, &bif_##f },
184 static const fileinfo files[]= {
185 { "uevent", parse_uevent, uevent_fields },
186 SEPARATE_QUANTITY_FIELDS(S_FILE)
190 /*---------- parsing of one thingx in /sys/class/power/... ----------*/
192 /* variables private to the parser and its error handlers */
193 static char batlinebuf[1000];
194 static FILE *batfile;
195 static const char *batdirname;
196 static const char *batfilename;
197 static const char *batlinevalue;
199 static int batfailf(const char *why) {
201 fprintf(stderr,"%s/%s: %s value `%s': %s\n",
202 batdirname,batfilename, batlinebuf,batlinevalue,why);
204 fprintf(stderr,"%s/%s: %s: `%s'\n",
205 batdirname,batfilename, why, batlinebuf);
210 static int batfailc(const char *why) {
211 fprintf(stderr,"%s/%s: %s\n",
212 batdirname,batfilename, why);
216 static int batfaile(const char *syscall, const char *target) {
217 fprintf(stderr,"%s: failed to %s %s: %s\n",
218 batdirname ? batdirname : "*", syscall, target, strerror(errno));
222 static int chdir_base(void) {
225 r= chdir("/sys/class/power_supply");
226 if (r) return batfaile("chdir","/sys/class/power_supply");
231 static void tidybattery(void) {
232 if (batfile) { fclose(batfile); batfile=0; }
235 static int parse_value(const fileinfo *cfile, const batinfo_field *field) {
236 if (*field->valuep != VAL_NOTFOUND)
237 return batfailf("value specified multiple times");
239 if (!field->enumarray[0]) {
242 *field->valuep= strtoull(batlinevalue,&ep,10);
244 batfailf("value number syntax incorrect");
248 const char *const *enumsearch;
249 for (*field->valuep=0, enumsearch=field->enumarray;
250 *enumsearch && strcmp(*enumsearch,batlinevalue);
251 (*field->valuep)++, enumsearch++);
253 batfailf("unknown enum value");
259 static int parse_uevent(const fileinfo *cfile) {
260 char *equals= strchr(batlinebuf,'=');
262 return batfailf("line without a equals");
264 batlinevalue = equals+1;
266 const batinfo_field *field;
267 for (field=cfile->extra; field->label; field++) {
268 if (!strcmp(field->label,batlinebuf))
274 return parse_value(cfile, field);
277 static int readbattery(void) { /* 0=>ok, -1=>couldn't */
279 const fileinfo *cfile;
286 r= chdir(batdirname);
287 if (r) return batfaile("chdir",batdirname);
289 #define V_NOTFOUND(f,...) \
290 this_##f = VAL_NOTFOUND;
294 (batfilename= cfile->filename);
296 batfile= fopen(batfilename,"r");
298 if (errno == ENOENT) continue;
299 return batfaile("open",batfilename);
305 sr= fgets(batlinebuf,sizeof(batlinebuf),batfile);
306 if (ferror(batfile)) return batfaile("read",batfilename);
307 if (!sr && feof(batfile)) break;
308 l= strlen(batlinebuf);
310 if (batlinebuf[l-1] != '\n')
311 return batfailf("line too long");
314 if (cfile->parse(cfile))
323 printf("%s:\n",batdirname);
324 #define V_PRINT(f,...) \
325 printf(" %-30s = %20"PRId64"\n", #f, (int64_t)this_##f);
326 ALL_DIRECT_VARS(V_PRINT)
329 int needsfields_MAINS = this_type == TYPE_MAINS;
330 int needsfields_BATTERY = this_type == TYPE_BATTERY;
331 int needsfields_BOTH = 1;
335 #define V_NEEDED(f,t,...) \
336 if (needsfields_##t && this_##f == VAL_NOTFOUND) { \
337 fprintf(stderr,"%s: %s: not found\n", \
341 ALL_NEEDED_FIELDS(V_NEEDED)
343 if (missing) return -1;
348 /*---------- data collection and analysis ----------*/
350 /* These next three variables are the results of the charging state */
351 static unsigned charging_mask; /* 1u<<CHGST_* | ... */
352 static double nondegraded_norm, fill_norm, ratepersec_norm;
355 #define Q_VAR(f,t,...) \
356 static double total_##f;
357 ALL_ACCUMULATE_FIELDS(Q_VAR)
359 static void acquiredata(void) {
367 if (debug) printf("\n");
369 #define Q_ZERO(f,t,...) \
371 ALL_ACCUMULATE_FIELDS(Q_ZERO)
376 di= opendir("."); if (!di) { batfaile("opendir","battery"); goto bad; }
377 while ((de= readdir(di))) {
378 if (de->d_name[0]==0 || de->d_name[0]=='.') continue;
380 batdirname= de->d_name;
386 charging_mask |= (1u << CHGST_ERROR);
390 if (this_type == TYPE_BATTERY) {
394 charging_mask |= 1u << this_state;
396 #define QTY_SUPPLIED(f,...) this_##f != VAL_NOTFOUND &&
397 #define QTY_USE_ENERGY(f,...) this_##f = this_##f##_energy;
398 #define QTY_USE_CHARGE(f,...) this_##f = this_##f##_charge;
400 double funky_multiplier;
401 if (BAT_QTYS(QTY_SUPPLIED,_energy,,) 1) {
402 if (debug) printf(" using energy\n");
403 BAT_QTYS(QTY_USE_ENERGY,,,);
404 funky_multiplier = 1.0;
405 } else if (BAT_QTYS(QTY_SUPPLIED,_charge,,)
406 this_voltage != VAL_NOTFOUND) {
407 if (debug) printf(" using charge\n");
408 BAT_QTYS(QTY_USE_CHARGE,,,);
409 funky_multiplier = this_voltage * 1e-6;
411 batfailc("neither complete set of energy nor charge");
414 if (this_state == CHGST_DISCHARGING)
416 total_present_rate -= 2.0 * this_present_rate * funky_multiplier;
418 #define Q_ACCUMULATE_FUNKY(f,...) \
419 total_##f += this_##f * funky_multiplier;
420 BAT_QTYS(Q_ACCUMULATE_FUNKY,,,)
423 #define Q_ACCUMULATE_PLAIN(f,t,...) \
424 if (this_type == TYPE_##t) \
425 total_##f += this_##f;
426 ALL_PLAIN_ACCUMULATE_FIELDS(Q_ACCUMULATE_PLAIN)
430 if (di) closedir(di);
434 printf(" %-30s = %#20x\n", "mask", charging_mask);
435 #define T_PRINT(f,...) \
436 printf(" %-30s = %20.6f\n", #f, total_##f);
438 ALL_PLAIN_ACCUMULATE_FIELDS(T_PRINT)
441 if ((charging_mask & (1u<<CHGST_DISCHARGING)) &&
442 !total_online/*mains*/) {
443 double time_remaining =
444 -total_remaining_capacity * 3600.0 / total_present_rate;
445 if (debug) printf(" %-30s = %20.6f\n", "time remaining", time_remaining);
446 if (time_remaining < alarmlevel)
450 if (total_design_capacity < 0.5)
451 total_design_capacity= 1.0;
453 if (total_last_full_capacity < total_remaining_capacity)
454 total_last_full_capacity= total_remaining_capacity;
455 if (total_design_capacity < total_last_full_capacity)
456 total_design_capacity= total_last_full_capacity;
458 nondegraded_norm= total_last_full_capacity / total_design_capacity;
459 fill_norm= total_remaining_capacity / total_design_capacity;
460 ratepersec_norm= total_present_rate
461 / (3600.0 * total_design_capacity);
464 static void initacquire(void) {
467 /*---------- argument parsing ----------*/
470 C(blue, discharging) \
473 C(lightgrey, notcharging) \
477 C(dimgrey, degraded) \
478 C(darkgreen, absent) \
480 C(white, equilibrium) \
485 static XrmDatabase xrm;
486 static Display *disp;
488 static const char *parentwindow;
490 static const char defaultresources[]=
493 "*" #u "Color: " #c "\n"
499 #define S(s) ((char*)(s))
500 static const XrmOptionDescRec optiontable[]= {
501 { S("-debug"), S("*debug"), XrmoptionIsArg },
502 { S("-warningTime"), S("*warningTime"), XrmoptionSepArg },
503 { S("-display"), S("*display"), XrmoptionSepArg },
504 { S("-geometry"), S("*geometry"), XrmoptionSepArg },
505 { S("-into"), S("*parentWindow"), XrmoptionSepArg },
506 { S("-iconic"), S("*iconic"), XrmoptionIsArg },
507 { S("-withdrawn"), S("*withdrawn"), XrmoptionIsArg },
510 { S("-" #u "Color"), S("*" #u "Color"), XrmoptionSepArg }, \
511 { S("-" #u "Colour"), S("*" #u "Color"), XrmoptionSepArg },
517 static const char *getresource(const char *want) {
518 char name_buf[256], class_buf[256];
520 char *rep_type_dummy;
523 assert(strlen(want) < 128);
524 sprintf(name_buf,"xacpi-simple.%s",want);
525 sprintf(class_buf,"Xacpi-Simple.%s",want);
527 r= XrmGetResource(xrm, name_buf,class_buf, &rep_type_dummy, &val);
533 static int getresource_bool(const char *want, int def, int *cache) {
534 /* *cache should be initialised to -1 and will be set to !!value
535 * alternatively cache==0 is allowed */
537 if (cache && *cache >= 0) return *cache;
539 const char *str= getresource(want);
543 long l= strtol(str,&ep,0);
548 case 't': case 'T': case 'y': case 'Y': result= 1; break;
549 case 'f': case 'F': case 'n': case 'N': result= 0; break;
550 case '-': /* option name from XrmoptionIsArg */ result= 1; break;
555 if (cache) *cache= result;
559 static void more_resources(const char *str, const char *why) {
564 more= XrmGetStringDatabase((char*)str);
565 if (!more) fail(why);
566 XrmCombineDatabase(more,&xrm,0);
569 static void parseargs(int argc, char **argv) {
570 Screen *screenscreen;
574 XrmParseCommand(&xrm, (XrmOptionDescRec*)optiontable,
575 sizeof(optiontable)/sizeof(*optiontable),
576 program_name, &argc, argv);
578 if (argc>1) badusage();
580 getresource_bool("debug",0,&debug);
582 const char *alarmlevel_string= getresource("alarmLevel");
583 alarmlevel = alarmlevel_string ? atoi(alarmlevel_string) : 300;
585 parentwindow = getresource("parentWindow");
587 disp= XOpenDisplay(getresource("display"));
588 if (!disp) fail("could not open display");
590 screen= DefaultScreen(disp);
592 screenscreen= ScreenOfDisplay(disp,screen);
593 if (!screenscreen) fail("screenofdisplay");
594 more_resources(XScreenResourceString(screenscreen), "screen resources");
595 more_resources(XResourceManagerString(disp), "display resources");
596 more_resources(defaultresources, "default resources");
599 /*---------- display ----------*/
602 static int width, height;
603 static Colormap cmap;
604 static unsigned long lastbackground;
608 unsigned long lastfg;
611 #define C(c,u) static unsigned long pix_##u;
612 #define GC(g) static Gcstate gc_##g;
617 static void refresh(void);
619 #define CHGMASK_CHG_DIS ((1u<<CHGST_CHARGING) | (1u<<CHGST_DISCHARGING))
621 static void failr(const char *m, int r) {
622 fprintf(stderr,"error: %s (code %d)\n", m, r);
626 static void setbackground(unsigned long newbg) {
629 if (newbg == lastbackground) return;
630 r= XSetWindowBackground(disp,win,newbg);
631 if (!r) fail("XSetWindowBackground");
632 lastbackground= newbg;
635 static void setforeground(Gcstate *g, unsigned long px) {
639 if (g->lastfg == px) return;
641 memset(&gcv,0,sizeof(gcv));
642 g->lastfg= gcv.foreground= px;
643 r= XChangeGC(disp,g->gc,GCForeground,&gcv);
644 if (!r) fail("XChangeGC");
647 static void show_solid(unsigned long px) {
649 XClearWindow(disp,win);
652 static void show(void) {
654 int i, leftmost_lit, leftmost_nondeg, beyond, first_beyond;
657 return show_solid(pix_absent);
659 if (charging_mask & (1u << CHGST_ERROR))
660 return show_solid(pix_error);
662 setbackground(pix_degraded);
663 XClearWindow(disp,win);
665 setforeground(&gc_remain,
666 !(charging_mask & CHGMASK_CHG_DIS) ?
667 (~charging_mask & (1u << CHGST_CHARGED) ?
668 pix_notcharging : pix_charged) :
669 !(~charging_mask & CHGMASK_CHG_DIS) ? pix_confusing :
670 charging_mask & (1u<<CHGST_CHARGING)
671 ? pix_charging : pix_discharging);
673 setforeground(&gc_empty, alarmed ? pix_low : pix_normal);
675 for (i=0, first_beyond=1; i<height; i++) {
678 TOP * exp( (double)i / (height-2) * log( (double)BOTTOM/TOP ) );
680 then= fill_norm + ratepersec_norm * elap;
683 ((charging_mask & (1u<<CHGST_DISCHARGING) && then <= 0.0) ||
684 (charging_mask & (1u<<CHGST_CHARGING) && then>=nondegraded_norm));
686 if (then <= 0.0) then= 0.0;
687 else if (then >= nondegraded_norm) then= nondegraded_norm;
689 leftmost_lit= width * then;
690 leftmost_nondeg= width * nondegraded_norm;
692 if (beyond && first_beyond) {
693 XDrawLine(disp, win, gc_white.gc, 0,i, leftmost_nondeg,i);
696 if (leftmost_lit < leftmost_nondeg)
697 XDrawLine(disp, win, gc_empty.gc,
698 leftmost_lit,i, leftmost_nondeg,i);
699 if (leftmost_lit >= 0)
700 XDrawLine(disp, win, gc_remain.gc, 0,i, leftmost_lit,i);
705 static void initgc(Gcstate *gc_r) {
708 memset(&gcv,0,sizeof(gcv));
709 gcv.function= GXcopy;
711 gc_r->lastfg= gcv.foreground= pix_equilibrium;
712 gc_r->gc= XCreateGC(disp,win, GCFunction|GCLineWidth|GCForeground, &gcv);
715 static void colour(unsigned long *pix_r, const char *whichcolour) {
720 name= getresource(whichcolour);
721 if (!name) fail("get colour resource");
723 st= XAllocNamedColor(disp,cmap,name,&xc,&xc);
729 static void initgraphics(int argc, char **argv) {
731 const char *geom_string;
732 XSizeHints *normal_hints;
734 XClassHint *class_hint;
735 int pos_x, pos_y, gravity;
736 char *program_name_silly;
738 program_name_silly= (char*)program_name;
740 normal_hints= XAllocSizeHints();
741 wm_hints= XAllocWMHints();
742 class_hint= XAllocClassHint();
744 if (!normal_hints || !wm_hints || !class_hint)
745 fail("could not alloc hint(s)");
747 geom_string= getresource("geometry");
749 xwmgr= XWMGeometry(disp,screen, geom_string,"128x32", 0,
755 unsigned long parentwindowid;
757 parentwindowid = strtoul(parentwindow,0,0);
759 parentwindowid = DefaultRootWindow(disp);
761 win= XCreateSimpleWindow(disp,parentwindowid,
762 pos_x,pos_y,width,height,0,0,0);
763 cmap= DefaultColormap(disp,screen);
765 #define C(c,u) colour(&pix_##u, #u "Color");
766 #define GC(g) initgc(&gc_##g);
771 r= XSetWindowBackground(disp,win,pix_degraded);
772 if (!r) fail("init set background");
773 lastbackground= pix_degraded;
775 normal_hints->flags= PWinGravity;
776 normal_hints->win_gravity= gravity;
777 normal_hints->x= pos_x;
778 normal_hints->y= pos_y;
779 normal_hints->width= width;
780 normal_hints->height= height;
781 if ((xwmgr & XValue) || (xwmgr & YValue))
782 normal_hints->flags |= USPosition;
784 wm_hints->flags= InputHint;
785 wm_hints->input= False;
786 wm_hints->initial_state=
787 (getresource_bool("withdrawn",0,0) ? WithdrawnState :
788 getresource_bool("iconic",0,0) ? IconicState
791 class_hint->res_name= program_name_silly;
792 class_hint->res_class= program_name_silly;
794 XmbSetWMProperties(disp,win, program_name,program_name,
795 argv,argc, normal_hints, wm_hints, class_hint);
797 XSelectInput(disp,win, ExposureMask|StructureNotifyMask);
798 XMapWindow(disp,win);
801 static void refresh(void) {
806 static void newgeometry(void) {
810 XGetGeometry(disp,win, &dummyw,&dummy,&dummy, &width,&height, &dummy,&dummy);
813 static void eventloop(void) {
824 pfd.fd= ConnectionNumber(disp);
825 pfd.events= POLLIN|POLLERR;
827 timeout= !(charging_mask & (1u << CHGST_ERROR)) ? TIMEOUT : TIMEOUT_ONERROR;
828 r= poll(&pfd,1,timeout);
829 if (r==-1 && errno!=EINTR) failr("poll",errno);
831 while (XPending(disp)) {
832 XNextEvent(disp,&ev);
833 if (ev.type == ConfigureNotify) {
834 XConfigureEvent *ce= (void*)&ev;
843 int main(int argc, char **argv) {
844 parseargs(argc,argv);
846 initgraphics(argc,argv);