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 * blue | red | dimgrey discharging - low!
10 * green | red | dimgrey charging - low
11 * cyan | red | dimgrey charged - low [1]
12 * grey | red | dimgrey charging&discharching, low [1]
13 * ... darkgreen ... no batteries present
14 * ... yellow ... error
16 * [1] battery must be quite badly degraded
19 * Copyright (C) 2004 Ian Jackson <ian@davenant.greenend.org.uk>
21 * This is free software; you can redistribute it and/or modify
22 * it under the terms of the GNU General Public License as
23 * published by the Free Software Foundation; either version 3,
24 * or (at your option) any later version.
26 * This is distributed in the hope that it will be useful, but
27 * WITHOUT ANY WARRANTY; without even the implied warranty of
28 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
29 * GNU General Public License for more details.
31 * You should have received a copy of the GNU General Public
32 * License along with this file; if not, consult the Free Software
33 * Foundation's website at www.fsf.org, or the GNU Project website at
47 #include <sys/types.h>
51 #include <X11/Xutil.h>
52 #include <X11/Xresource.h>
57 #define TIMEOUT 5000 /* milliseconds */
58 #define TIMEOUT_ONERROR 3333 /* milliseconds */
60 static const char program_name[]= "xacpi-simple";
62 /*---------- general utility stuff and declarations ----------*/
64 static void fail(const char *m) {
65 fprintf(stderr,"error: %s\n", m);
68 static void badusage(void) { fail("bad usage"); }
70 #define CHGST_DISCHARGING 0 /* Reflects order in E(state,charging_state) */
71 #define CHGST_CHARGING 1 /* in fields table. Also, much code assumes */
72 #define CHGST_CHARGED 2 /* exactly these three possible states. */
73 #define CHGST_ERROR 8 /* Except that this one is an extra bit. */
75 /*---------- structure of and results from /proc/acpi/battery/... ----------*/
76 /* variables thisbat_... are the results from readbattery();
77 * if readbattery() succeeds they are all valid and not VAL_NOTFOUND
80 typedef struct batinfo_field {
83 const char *acpi_label;
84 double acpi_conversion_factor;
85 unsigned long *valuep;
87 const char *enumarray[10];
90 #define QUANTITY_FIELDS \
91 QF(info, design_capacity, "mWh", energy_full_design, 1e-3) \
92 QF(info, last_full_capacity, "mWh", energy_full, 1e-3) \
93 QF(state, present_rate, "mW", power_now, 1e-3) \
94 QF(state, remaining_capacity, "mWh", energy_now, 1e-3) \
95 QF(alarm, alarm, "mWh", alarm, 1e-3)
97 #define QF(f,l,u,a,ac) static unsigned long thisbat_##f##_##l;
101 static unsigned long thisbat_alarm_present, thisbat_info_present;
102 static unsigned long thisbat_state_present, thisbat_state_charging_state;
104 #define VAL_NOTFOUND (~0UL)
106 static const batinfo_field fields[]= {
107 #define E(f,l) #f, #l, &thisbat_##f##_##l, 0
108 #define QF(f,l,u) { #f, #l, &thisbat_##f##_##l, u },
109 { E(alarm, present), 0,0, { "no", "yes" } },
110 { E(info, present), 0,0, { "no", "yes" } },
111 { E(state,present), 0,0, { "no", "yes" } },
112 { E(state,charging_state), { "discharging", "charging", "charged" } },
113 QUANTITY_FIELDS /* take care re charging_state values order - */
114 { 0 } /* if you must change it, search for CHGST_... */
119 static const char *files[]= { "info", "state", "alarm" };
121 /*---------- parsing of one battery in /proc/acpi/battery/... ----------*/
123 /* variables private to the parser and its error handlers */
124 static char batlinebuf[1000];
125 static FILE *batfile;
126 static const char *batdirname;
127 static const char *batfilename;
128 static const char *batlinevalue;
130 static int batfailf(const char *why) {
132 fprintf(stderr,"battery/%s/%s: %s value `%s': %s\n",
133 batdirname,batfilename, batlinebuf,batlinevalue,why);
135 fprintf(stderr,"battery/%s/%s: %s: `%s'\n",
136 batdirname,batfilename, why, batlinebuf);
141 static int batfaile(const char *syscall, const char *target) {
142 fprintf(stderr,"battery/%s: failed to %s %s: %s\n",
143 batdirname ? batdirname : "*", syscall, target, strerror(errno));
147 static void chdir_base(void) {
150 r= chdir("/proc/acpi/battery");
151 if (r) batfaile("chdir","/proc/acpi/battery");
154 static void tidybattery(void) {
155 if (batfile) { fclose(batfile); batfile=0; }
156 if (batdirname) { chdir_base(); batdirname=0; }
159 static int readbattery(void) { /* 0=>ok, -1=>couldn't */
160 const batinfo_field *field;
161 const char *const *cfilename, *const *enumsearch;
162 char *colon, *ep, *sr, *p;
165 r= chdir(batdirname);
166 if (r) return batfaile("chdir",batdirname);
168 for (field=fields; field->file; field++)
169 *field->valuep= VAL_NOTFOUND;
171 for (cfilename=files;
172 (batfilename= *cfilename);
174 batfile= fopen(batfilename,"r");
175 if (!batfile) return batfaile("open",batfilename);
180 sr= fgets(batlinebuf,sizeof(batlinebuf),batfile);
181 if (ferror(batfile)) return batfaile("read",batfilename);
182 if (!sr && feof(batfile)) break;
183 l= strlen(batlinebuf);
185 if (batlinebuf[l-1] != '\n')
186 return batfailf("line too long");
188 colon= strchr(batlinebuf,':');
190 return batfailf("line without a colon");
193 for (batlinevalue= colon+1;
194 *batlinevalue && isspace((unsigned char)*batlinevalue);
197 if (!strcmp(batlinebuf,"ERROR"))
198 return batfailf("kernel reports error");
200 for (p=batlinebuf; p<colon; p++)
204 for (field=fields; field->file; field++) {
205 if (!strcmp(field->file,batfilename) &&
206 !strcmp(field->label,batlinebuf))
207 goto label_interesting;
214 *field->valuep= strtoul(batlinevalue,&ep,10);
215 if (ep==batlinevalue || *ep!=' ')
216 batfailf("value number syntax incorrect");
217 if (strcmp(ep+1,field->unit)) batfailf("incorrect unit");
221 for (*field->valuep=0, enumsearch=field->enumarray;
222 *enumsearch && strcmp(*enumsearch,batlinevalue);
223 (*field->valuep)++, enumsearch++);
225 batfailf("unknown enum value");
234 if (!(thisbat_alarm_present==0 ||
235 thisbat_state_present==0 || thisbat_info_present==0)) {
236 if (thisbat_alarm_present == VAL_NOTFOUND)
237 thisbat_alarm_present= 1;
239 for (field=fields, missing=0;
242 if (*field->valuep == VAL_NOTFOUND) {
243 fprintf(stderr,"battery/%s/%s: %s: not found\n",
244 batdirname, field->file,field->label);
248 if (missing) return -1;
252 if (r) return batfaile("chdir","..");
258 /*---------- data collection and analysis ----------*/
260 /* These next three variables are the results of the charging state */
261 static unsigned charging_state_mask; /* 1u<<CHGST_* | ... */
262 static double nondegraded_norm, fill_norm, ratepersec_norm;
263 static int alarm_level; /* 0=ok, 1=low */
266 static double total_##f##_##l;
270 static void acquiredata(void) {
275 charging_state_mask= 0;
282 di= opendir("."); if (!di) batfaile("opendir","battery");
283 while ((de= readdir(di))) {
284 if (de->d_name[0]==0 || de->d_name[0]=='.') continue;
286 batdirname= de->d_name;
290 if (r) { charging_state_mask |= CHGST_ERROR; continue; }
292 if (!thisbat_info_present || !thisbat_state_present)
295 charging_state_mask |= 1u << thisbat_state_charging_state;
298 total_##f##_##l += thisbat_##f##_##l;
302 if (thisbat_state_charging_state == CHGST_DISCHARGING)
304 total_state_present_rate -= 2.0 * thisbat_state_present_rate;
309 if (total_info_design_capacity < 0.5)
310 total_info_design_capacity= 1.0;
312 if (total_info_last_full_capacity < total_state_remaining_capacity)
313 total_info_last_full_capacity= total_state_remaining_capacity;
314 if (total_info_design_capacity < total_info_last_full_capacity)
315 total_info_design_capacity= total_info_last_full_capacity;
318 (total_state_remaining_capacity < total_alarm_alarm &&
319 !(charging_state_mask & 1u << CHGST_CHARGING));
321 nondegraded_norm= total_info_last_full_capacity / total_info_design_capacity;
322 fill_norm= total_state_remaining_capacity / total_info_design_capacity;
323 ratepersec_norm= total_state_present_rate
324 / (3600.0 * total_info_design_capacity);
327 static void initacquire(void) {
331 /*---------- argument parsing ----------*/
334 C(blue, discharging) \
340 C(dimgrey, degraded) \
341 C(darkgreen, absent) \
343 C(white, equilibrium) \
348 static XrmDatabase xrm;
349 static Display *disp;
352 static const char defaultresources[]=
355 "*" #u "Color: " #c "\n"
361 #define S(s) ((char*)(s))
362 static const XrmOptionDescRec optiontable[]= {
363 { S("-display"), S("*display"), XrmoptionSepArg },
364 { S("-geometry"), S("*geometry"), XrmoptionSepArg },
367 { S("-" #u "Color"), S("*" #u "Color"), XrmoptionSepArg }, \
368 { S("-" #u "Colour"), S("*" #u "Color"), XrmoptionSepArg },
374 static const char *getresource(const char *want) {
375 char name_buf[256], class_buf[256];
377 char *rep_type_dummy;
380 assert(strlen(want) < 128);
381 sprintf(name_buf,"xacpi-simple.%s",want);
382 sprintf(class_buf,"Xacpi-Simple.%s",want);
384 r= XrmGetResource(xrm, name_buf,class_buf, &rep_type_dummy, &val);
390 static void more_resources(const char *str, const char *why) {
395 more= XrmGetStringDatabase((char*)str);
396 if (!more) fail(why);
397 XrmCombineDatabase(more,&xrm,0);
400 static void parseargs(int argc, char **argv) {
401 Screen *screenscreen;
405 XrmParseCommand(&xrm, (XrmOptionDescRec*)optiontable,
406 sizeof(optiontable)/sizeof(*optiontable),
407 program_name, &argc, argv);
409 if (argc>1) badusage();
411 disp= XOpenDisplay(getresource("display"));
412 if (!disp) fail("could not open display");
414 screen= DefaultScreen(disp);
416 screenscreen= ScreenOfDisplay(disp,screen);
417 if (!screenscreen) fail("screenofdisplay");
418 more_resources(XScreenResourceString(screenscreen), "screen resources");
419 more_resources(XResourceManagerString(disp), "display resources");
420 more_resources(defaultresources, "default resources");
423 /*---------- display ----------*/
426 static int width, height;
427 static Colormap cmap;
428 static unsigned long lastbackground;
432 unsigned long lastfg;
435 #define C(c,u) static unsigned long pix_##c;
436 #define GC(g) static Gcstate gc_##g;
441 static void refresh(void);
443 #define CHGMASK_CHG_DIS (1u<<CHGST_CHARGING | 1u<<CHGST_DISCHARGING)
445 static void failr(const char *m, int r) {
446 fprintf(stderr,"error: %s (code %d)\n", m, r);
450 static void setbackground(unsigned long newbg) {
453 if (newbg == lastbackground) return;
454 r= XSetWindowBackground(disp,win,newbg);
455 if (!r) fail("XSetWindowBackground");
456 lastbackground= newbg;
459 static void setforeground(Gcstate *g, unsigned long px) {
463 if (g->lastfg == px) return;
465 memset(&gcv,0,sizeof(gcv));
466 g->lastfg= gcv.foreground= px;
467 r= XChangeGC(disp,g->gc,GCForeground,&gcv);
468 if (!r) fail("XChangeGC");
471 static void show_solid(unsigned long px) {
473 XClearWindow(disp,win);
476 static void show(void) {
478 int i, leftmost_lit, leftmost_nondeg, beyond, first_beyond;
480 if (!charging_state_mask)
481 return show_solid(pix_darkgreen);
483 if (charging_state_mask & CHGST_ERROR)
484 return show_solid(pix_yellow);
486 setbackground(pix_dimgrey);
487 XClearWindow(disp,win);
489 setforeground(&gc_remain,
490 !(charging_state_mask & CHGMASK_CHG_DIS) ? pix_cyan :
491 !(~charging_state_mask & CHGMASK_CHG_DIS) ? pix_grey :
492 charging_state_mask & (1u<<CHGST_CHARGING)
493 ? pix_green : pix_blue);
495 setforeground(&gc_empty, alarm_level ? pix_red : pix_black);
497 for (i=0, first_beyond=1; i<height; i++) {
500 TOP * exp( (double)i / (height-2) * log( (double)BOTTOM/TOP ) );
502 then= fill_norm + ratepersec_norm * elap;
505 ((charging_state_mask & (1u<<CHGST_DISCHARGING) && then <= 0.0) ||
506 (charging_state_mask & (1u<<CHGST_CHARGING) && then>=nondegraded_norm));
508 if (then <= 0.0) then= 0.0;
509 else if (then >= nondegraded_norm) then= nondegraded_norm;
511 leftmost_lit= width * then;
512 leftmost_nondeg= width * nondegraded_norm;
514 if (beyond && first_beyond) {
515 XDrawLine(disp, win, gc_white.gc, 0,i, leftmost_nondeg,i);
518 if (leftmost_lit < leftmost_nondeg)
519 XDrawLine(disp, win, gc_empty.gc,
520 leftmost_lit,i, leftmost_nondeg,i);
521 if (leftmost_lit >= 0)
522 XDrawLine(disp, win, gc_remain.gc, 0,i, leftmost_lit,i);
527 static void initgc(Gcstate *gc_r) {
530 memset(&gcv,0,sizeof(gcv));
531 gcv.function= GXcopy;
533 gc_r->lastfg= gcv.foreground= pix_white;
534 gc_r->gc= XCreateGC(disp,win, GCFunction|GCLineWidth|GCForeground, &gcv);
537 static void colour(unsigned long *pix_r, const char *whichcolour) {
542 name= getresource(whichcolour);
543 if (!name) fail("get colour resource");
545 st= XAllocNamedColor(disp,cmap,name,&xc,&xc);
551 static void initgraphics(int argc, char **argv) {
553 const char *geom_string;
554 XSizeHints *normal_hints;
556 XClassHint *class_hint;
557 int pos_x, pos_y, gravity;
558 char *program_name_silly;
560 program_name_silly= (char*)program_name;
562 normal_hints= XAllocSizeHints();
563 wm_hints= XAllocWMHints();
564 class_hint= XAllocClassHint();
566 if (!normal_hints || !wm_hints || !class_hint)
567 fail("could not alloc hint(s)");
569 geom_string= getresource("geometry");
571 xwmgr= XWMGeometry(disp,screen, geom_string,"128x32", 0,
577 win= XCreateSimpleWindow(disp,DefaultRootWindow(disp),
578 pos_x,pos_y,width,height,0,0,0);
579 cmap= DefaultColormap(disp,screen);
581 #define C(c,u) colour(&pix_##c, #u "Color");
582 #define GC(g) initgc(&gc_##g);
587 r= XSetWindowBackground(disp,win,pix_dimgrey);
588 if (!r) fail("init set background");
589 lastbackground= pix_dimgrey;
591 normal_hints->flags= PWinGravity;
592 normal_hints->win_gravity= gravity;
593 normal_hints->x= pos_x;
594 normal_hints->y= pos_y;
595 normal_hints->width= width;
596 normal_hints->height= height;
597 if ((xwmgr & XValue) || (xwmgr & YValue))
598 normal_hints->flags |= USPosition;
600 wm_hints->flags= InputHint;
601 wm_hints->input= False;
603 class_hint->res_name= program_name_silly;
604 class_hint->res_class= program_name_silly;
606 XmbSetWMProperties(disp,win, program_name,program_name,
607 argv,argc, normal_hints, wm_hints, class_hint);
609 XSelectInput(disp,win, ExposureMask|StructureNotifyMask);
610 XMapWindow(disp,win);
613 static void refresh(void) {
618 static void newgeometry(void) {
622 XGetGeometry(disp,win, &dummyw,&dummy,&dummy, &width,&height, &dummy,&dummy);
625 static void eventloop(void) {
636 pfd.fd= ConnectionNumber(disp);
637 pfd.events= POLLIN|POLLERR;
639 timeout= !(charging_state_mask & CHGST_ERROR) ? TIMEOUT : TIMEOUT_ONERROR;
640 r= poll(&pfd,1,timeout);
641 if (r==-1 && errno!=EINTR) failr("poll",errno);
643 while (XPending(disp)) {
644 XNextEvent(disp,&ev);
645 if (ev.type == ConfigureNotify) {
646 XConfigureEvent *ce= (void*)&ev;
655 int main(int argc, char **argv) {
656 parseargs(argc,argv);
658 initgraphics(argc,argv);