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 unsigned long *valuep;
85 const char *enumarray[10];
88 #define QUANTITY_FIELDS \
89 QF(info, design_capacity, "mWh") \
90 QF(info, last_full_capacity, "mWh") \
91 QF(state, present_rate, "mW") \
92 QF(state, remaining_capacity, "mWh") \
93 QF(alarm, alarm, "mWh")
95 #define QF(f,l,u) static unsigned long thisbat_##f##_##l;
99 static unsigned long thisbat_alarm_present, thisbat_info_present;
100 static unsigned long thisbat_state_present, thisbat_state_charging_state;
102 #define VAL_NOTFOUND (~0UL)
104 static const batinfo_field fields[]= {
105 #define E(f,l) #f, #l, &thisbat_##f##_##l, 0
106 #define QF(f,l,u) { #f, #l, &thisbat_##f##_##l, u },
107 { E(alarm, present), { "no", "yes" } },
108 { E(info, present), { "no", "yes" } },
109 { E(state,present), { "no", "yes" } },
110 { E(state,charging_state), { "discharging", "charging", "charged" } },
111 QUANTITY_FIELDS /* take care re charging_state values order - */
112 { 0 } /* if you must change it, search for CHGST_... */
117 static const char *files[]= { "info", "state", "alarm" };
119 /*---------- parsing of one battery in /proc/acpi/battery/... ----------*/
121 /* variables private to the parser and its error handlers */
122 static char batlinebuf[1000];
123 static FILE *batfile;
124 static const char *batdirname;
125 static const char *batfilename;
126 static const char *batlinevalue;
128 static int batfailf(const char *why) {
130 fprintf(stderr,"battery/%s/%s: %s value `%s': %s\n",
131 batdirname,batfilename, batlinebuf,batlinevalue,why);
133 fprintf(stderr,"battery/%s/%s: %s: `%s'\n",
134 batdirname,batfilename, why, batlinebuf);
139 static int batfaile(const char *syscall, const char *target) {
140 fprintf(stderr,"battery/%s: failed to %s %s: %s\n",
141 batdirname ? batdirname : "*", syscall, target, strerror(errno));
145 static void chdir_base(void) {
148 r= chdir("/proc/acpi/battery");
149 if (r) batfaile("chdir","/proc/acpi/battery");
152 static void tidybattery(void) {
153 if (batfile) { fclose(batfile); batfile=0; }
154 if (batdirname) { chdir_base(); batdirname=0; }
157 static int readbattery(void) { /* 0=>ok, -1=>couldn't */
158 const batinfo_field *field;
159 const char *const *cfilename, *const *enumsearch;
160 char *colon, *ep, *sr, *p;
163 r= chdir(batdirname);
164 if (r) return batfaile("chdir",batdirname);
166 for (field=fields; field->file; field++)
167 *field->valuep= VAL_NOTFOUND;
169 for (cfilename=files;
170 (batfilename= *cfilename);
172 batfile= fopen(batfilename,"r");
173 if (!batfile) return batfaile("open",batfilename);
178 sr= fgets(batlinebuf,sizeof(batlinebuf),batfile);
179 if (ferror(batfile)) return batfaile("read",batfilename);
180 if (!sr && feof(batfile)) break;
181 l= strlen(batlinebuf);
183 if (batlinebuf[l-1] != '\n')
184 return batfailf("line too long");
186 colon= strchr(batlinebuf,':');
188 return batfailf("line without a colon");
191 for (batlinevalue= colon+1;
192 *batlinevalue && isspace((unsigned char)*batlinevalue);
195 if (!strcmp(batlinebuf,"ERROR"))
196 return batfailf("kernel reports error");
198 for (p=batlinebuf; p<colon; p++)
202 for (field=fields; field->file; field++) {
203 if (!strcmp(field->file,batfilename) &&
204 !strcmp(field->label,batlinebuf))
205 goto label_interesting;
212 *field->valuep= strtoul(batlinevalue,&ep,10);
213 if (ep==batlinevalue || *ep!=' ')
214 batfailf("value number syntax incorrect");
215 if (strcmp(ep+1,field->unit)) batfailf("incorrect unit");
219 for (*field->valuep=0, enumsearch=field->enumarray;
220 *enumsearch && strcmp(*enumsearch,batlinevalue);
221 (*field->valuep)++, enumsearch++);
223 batfailf("unknown enum value");
232 if (!(thisbat_alarm_present==0 ||
233 thisbat_info_present==0 ||
234 thisbat_state_present==0)) {
235 if (thisbat_alarm_present == VAL_NOTFOUND)
236 thisbat_alarm_present= 1;
238 for (field=fields, missing=0;
241 if (*field->valuep == VAL_NOTFOUND) {
242 fprintf(stderr,"battery/%s/%s: %s: not found\n",
243 batdirname, field->file,field->label);
247 if (missing) return -1;
251 if (r) return batfaile("chdir","..");
257 /*---------- data collection and analysis ----------*/
259 /* These next three variables are the results of the charging state */
260 static unsigned charging_state_mask; /* 1u<<CHGST_* | ... */
261 static double nondegraded_norm, fill_norm, ratepersec_norm;
262 static int alarm_level; /* 0=ok, 1=low */
265 static double total_##f##_##l;
269 static void acquiredata(void) {
274 charging_state_mask= 0;
281 di= opendir("."); if (!di) batfaile("opendir","battery");
282 while ((de= readdir(di))) {
283 if (de->d_name[0]==0 || de->d_name[0]=='.') continue;
285 batdirname= de->d_name;
289 if (r) { charging_state_mask |= CHGST_ERROR; continue; }
291 if (!thisbat_info_present || !thisbat_state_present)
294 charging_state_mask |= 1u << thisbat_state_charging_state;
297 total_##f##_##l += thisbat_##f##_##l;
301 if (thisbat_state_charging_state == CHGST_DISCHARGING)
303 total_state_present_rate -= 2.0 * thisbat_state_present_rate;
308 if (total_info_design_capacity < 0.5)
309 total_info_design_capacity= 1.0;
311 if (total_info_last_full_capacity < total_state_remaining_capacity)
312 total_info_last_full_capacity= total_state_remaining_capacity;
313 if (total_info_design_capacity < total_info_last_full_capacity)
314 total_info_design_capacity= total_info_last_full_capacity;
317 (total_state_remaining_capacity < total_alarm_alarm &&
318 !(charging_state_mask & 1u << CHGST_CHARGING));
320 nondegraded_norm= total_info_last_full_capacity / total_info_design_capacity;
321 fill_norm= total_state_remaining_capacity / total_info_design_capacity;
322 ratepersec_norm= total_state_present_rate
323 / (3600.0 * total_info_design_capacity);
326 static void initacquire(void) {
330 /*---------- argument parsing ----------*/
333 C(blue, discharging) \
339 C(dimgrey, degraded) \
340 C(darkgreen, absent) \
342 C(white, equilibrium) \
347 static XrmDatabase xrm;
348 static Display *disp;
351 static const char defaultresources[]=
354 "*" #u "Color: " #c "\n"
360 #define S(s) ((char*)(s))
361 static const XrmOptionDescRec optiontable[]= {
362 { S("-display"), S("*display"), XrmoptionSepArg },
363 { S("-geometry"), S("*geometry"), XrmoptionSepArg },
366 { S("-" #u "Color"), S("*" #u "Color"), XrmoptionSepArg }, \
367 { S("-" #u "Colour"), S("*" #u "Color"), XrmoptionSepArg },
373 static const char *getresource(const char *want) {
374 char name_buf[256], class_buf[256];
376 char *rep_type_dummy;
379 assert(strlen(want) < 128);
380 sprintf(name_buf,"xacpi-simple.%s",want);
381 sprintf(class_buf,"Xacpi-Simple.%s",want);
383 r= XrmGetResource(xrm, name_buf,class_buf, &rep_type_dummy, &val);
389 static void more_resources(const char *str, const char *why) {
394 more= XrmGetStringDatabase((char*)str);
395 if (!more) fail(why);
396 XrmCombineDatabase(more,&xrm,0);
399 static void parseargs(int argc, char **argv) {
400 Screen *screenscreen;
404 XrmParseCommand(&xrm, (XrmOptionDescRec*)optiontable,
405 sizeof(optiontable)/sizeof(*optiontable),
406 program_name, &argc, argv);
408 if (argc>1) badusage();
410 disp= XOpenDisplay(getresource("display"));
411 if (!disp) fail("could not open display");
413 screen= DefaultScreen(disp);
415 screenscreen= ScreenOfDisplay(disp,screen);
416 if (!screenscreen) fail("screenofdisplay");
417 more_resources(XScreenResourceString(screenscreen), "screen resources");
418 more_resources(XResourceManagerString(disp), "display resources");
419 more_resources(defaultresources, "default resources");
422 /*---------- display ----------*/
425 static int width, height;
426 static Colormap cmap;
427 static unsigned long lastbackground;
431 unsigned long lastfg;
434 #define C(c,u) static unsigned long pix_##c;
435 #define GC(g) static Gcstate gc_##g;
440 static void refresh(void);
442 #define CHGMASK_CHG_DIS (1u<<CHGST_CHARGING | 1u<<CHGST_DISCHARGING)
444 static void failr(const char *m, int r) {
445 fprintf(stderr,"error: %s (code %d)\n", m, r);
449 static void setbackground(unsigned long newbg) {
452 if (newbg == lastbackground) return;
453 r= XSetWindowBackground(disp,win,newbg);
454 if (!r) fail("XSetWindowBackground");
455 lastbackground= newbg;
458 static void setforeground(Gcstate *g, unsigned long px) {
462 if (g->lastfg == px) return;
464 memset(&gcv,0,sizeof(gcv));
465 g->lastfg= gcv.foreground= px;
466 r= XChangeGC(disp,g->gc,GCForeground,&gcv);
467 if (!r) fail("XChangeGC");
470 static void show_solid(unsigned long px) {
472 XClearWindow(disp,win);
475 static void show(void) {
477 int i, leftmost_lit, leftmost_nondeg, beyond, first_beyond;
479 if (!charging_state_mask)
480 return show_solid(pix_darkgreen);
482 if (charging_state_mask & CHGST_ERROR)
483 return show_solid(pix_yellow);
485 setbackground(pix_dimgrey);
486 XClearWindow(disp,win);
488 setforeground(&gc_remain,
489 !(charging_state_mask & CHGMASK_CHG_DIS) ? pix_cyan :
490 !(~charging_state_mask & CHGMASK_CHG_DIS) ? pix_grey :
491 charging_state_mask & (1u<<CHGST_CHARGING)
492 ? pix_green : pix_blue);
494 setforeground(&gc_empty, alarm_level ? pix_red : pix_black);
496 for (i=0, first_beyond=1; i<height; i++) {
499 TOP * exp( (double)i / (height-2) * log( (double)BOTTOM/TOP ) );
501 then= fill_norm + ratepersec_norm * elap;
504 ((charging_state_mask & (1u<<CHGST_DISCHARGING) && then <= 0.0) ||
505 (charging_state_mask & (1u<<CHGST_CHARGING) && then>=nondegraded_norm));
507 if (then <= 0.0) then= 0.0;
508 else if (then >= nondegraded_norm) then= nondegraded_norm;
510 leftmost_lit= width * then;
511 leftmost_nondeg= width * nondegraded_norm;
513 if (beyond && first_beyond) {
514 XDrawLine(disp, win, gc_white.gc, 0,i, leftmost_nondeg,i);
517 if (leftmost_lit < leftmost_nondeg)
518 XDrawLine(disp, win, gc_empty.gc,
519 leftmost_lit,i, leftmost_nondeg,i);
520 if (leftmost_lit >= 0)
521 XDrawLine(disp, win, gc_remain.gc, 0,i, leftmost_lit,i);
526 static void initgc(Gcstate *gc_r) {
529 memset(&gcv,0,sizeof(gcv));
530 gcv.function= GXcopy;
532 gc_r->lastfg= gcv.foreground= pix_white;
533 gc_r->gc= XCreateGC(disp,win, GCFunction|GCLineWidth|GCForeground, &gcv);
536 static void colour(unsigned long *pix_r, const char *whichcolour) {
541 name= getresource(whichcolour);
542 if (!name) fail("get colour resource");
544 st= XAllocNamedColor(disp,cmap,name,&xc,&xc);
550 static void initgraphics(int argc, char **argv) {
552 const char *geom_string;
553 XSizeHints *normal_hints;
555 XClassHint *class_hint;
556 int pos_x, pos_y, gravity;
557 char *program_name_silly;
559 program_name_silly= (char*)program_name;
561 normal_hints= XAllocSizeHints();
562 wm_hints= XAllocWMHints();
563 class_hint= XAllocClassHint();
565 if (!normal_hints || !wm_hints || !class_hint)
566 fail("could not alloc hint(s)");
568 geom_string= getresource("geometry");
570 xwmgr= XWMGeometry(disp,screen, geom_string,"128x32", 0,
576 win= XCreateSimpleWindow(disp,DefaultRootWindow(disp),
577 pos_x,pos_y,width,height,0,0,0);
578 cmap= DefaultColormap(disp,screen);
580 #define C(c,u) colour(&pix_##c, #u "Color");
581 #define GC(g) initgc(&gc_##g);
586 r= XSetWindowBackground(disp,win,pix_dimgrey);
587 if (!r) fail("init set background");
588 lastbackground= pix_dimgrey;
590 normal_hints->flags= PWinGravity;
591 normal_hints->win_gravity= gravity;
592 normal_hints->x= pos_x;
593 normal_hints->y= pos_y;
594 normal_hints->width= width;
595 normal_hints->height= height;
596 if ((xwmgr & XValue) || (xwmgr & YValue))
597 normal_hints->flags |= USPosition;
599 wm_hints->flags= InputHint;
600 wm_hints->input= False;
602 class_hint->res_name= program_name_silly;
603 class_hint->res_class= program_name_silly;
605 XmbSetWMProperties(disp,win, program_name,program_name,
606 argv,argc, normal_hints, wm_hints, class_hint);
608 XSelectInput(disp,win, ExposureMask|StructureNotifyMask);
609 XMapWindow(disp,win);
612 static void refresh(void) {
617 static void newgeometry(void) {
621 XGetGeometry(disp,win, &dummyw,&dummy,&dummy, &width,&height, &dummy,&dummy);
624 static void eventloop(void) {
635 pfd.fd= ConnectionNumber(disp);
636 pfd.events= POLLIN|POLLERR;
638 timeout= !(charging_state_mask & CHGST_ERROR) ? TIMEOUT : TIMEOUT_ONERROR;
639 r= poll(&pfd,1,timeout);
640 if (r==-1 && errno!=EINTR) failr("poll",errno);
642 while (XPending(disp)) {
643 XNextEvent(disp,&ev);
644 if (ev.type == ConfigureNotify) {
645 XConfigureEvent *ce= (void*)&ev;
654 int main(int argc, char **argv) {
655 parseargs(argc,argv);
657 initgraphics(argc,argv);