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
29 #include <sys/types.h>
33 #include <X11/Xutil.h>
38 #define TIMEOUT 5000 /* milliseconds */
39 #define TIMEOUT_ONERROR 3333 /* milliseconds */
41 static const char program_name[]= "xacpi-simple";
43 /*---------- general utility stuff and declarations ----------*/
45 static void fail(const char *m) {
46 fprintf(stderr,"error: %s\n", m);
49 static void badusage(void) { fail("bad usage"); }
51 #define CHGST_DISCHARGING 0 /* Reflects order in E(state,charging_state) */
52 #define CHGST_CHARGING 1 /* in fields table. Also, much code assumes */
53 #define CHGST_CHARGED 2 /* exactly these three possible states. */
54 #define CHGST_ERROR 8 /* Except that this one is an extra bit. */
56 /*---------- structure of and results from /proc/acpi/battery/... ----------*/
57 /* variables thisbat_... are the results from readbattery();
58 * if readbattery() succeeds they are all valid and not VAL_NOTFOUND
61 typedef struct batinfo_field {
64 unsigned long *valuep;
66 const char *enumarray[10];
69 #define QUANTITY_FIELDS \
70 QF(info, design_capacity, "mWh") \
71 QF(info, last_full_capacity, "mWh") \
72 QF(state, present_rate, "mW") \
73 QF(state, remaining_capacity, "mWh") \
74 QF(alarm, alarm, "mWh")
76 #define QF(f,l,u) static unsigned long thisbat_##f##_##l;
80 static unsigned long thisbat_alarm_present, thisbat_info_present;
81 static unsigned long thisbat_state_present, thisbat_state_charging_state;
83 #define VAL_NOTFOUND (~0UL)
85 static const batinfo_field fields[]= {
86 #define E(f,l) #f, #l, &thisbat_##f##_##l, 0
87 #define QF(f,l,u) { #f, #l, &thisbat_##f##_##l, u },
88 { E(alarm, present), { "no", "yes" } },
89 { E(info, present), { "no", "yes" } },
90 { E(state,present), { "no", "yes" } },
91 { E(state,charging_state), { "discharging", "charging", "charged" } },
92 QUANTITY_FIELDS /* take care re charging_state values order - */
93 { 0 } /* if you must change it, search for CHGST_... */
98 static const char *files[]= { "info", "state", "alarm" };
100 /*---------- parsing of one battery in /proc/acpi/battery/... ----------*/
102 /* variables private to the parser and its error handlers */
103 static char batlinebuf[1000];
104 static FILE *batfile;
105 static const char *batdirname;
106 static const char *batfilename;
107 static const char *batlinevalue;
109 static int batfailf(const char *why) {
111 fprintf(stderr,"battery/%s/%s: %s value `%s': %s\n",
112 batdirname,batfilename, batlinebuf,batlinevalue,why);
114 fprintf(stderr,"battery/%s/%s: %s: `%s'\n",
115 batdirname,batfilename, why, batlinebuf);
120 static int batfaile(const char *syscall, const char *target) {
121 fprintf(stderr,"battery/%s: failed to %s %s: %s\n",
122 batdirname ? batdirname : "*", syscall, target, strerror(errno));
126 static void chdir_base(void) {
129 r= chdir("/proc/acpi/battery");
130 if (r) batfaile("chdir","/proc/acpi/battery");
133 static void tidybattery(void) {
134 if (batfile) { fclose(batfile); batfile=0; }
135 if (batdirname) { chdir_base(); batdirname=0; }
138 static int readbattery(void) { /* 0=>ok, -1=>couldn't */
139 const batinfo_field *field;
140 const char *const *cfilename, *const *enumsearch;
141 char *colon, *ep, *sr, *p;
144 r= chdir(batdirname);
145 if (r) return batfaile("chdir",batdirname);
147 for (field=fields; field->file; field++)
148 *field->valuep= VAL_NOTFOUND;
150 for (cfilename=files;
151 (batfilename= *cfilename);
153 batfile= fopen(batfilename,"r");
154 if (!batfile) return batfaile("open",batfilename);
159 sr= fgets(batlinebuf,sizeof(batlinebuf),batfile);
160 if (ferror(batfile)) return batfaile("read",batfilename);
161 if (!sr && feof(batfile)) break;
162 l= strlen(batlinebuf);
164 if (batlinebuf[l-1] != '\n')
165 return batfailf("line too long");
167 colon= strchr(batlinebuf,':');
169 return batfailf("line without a colon");
172 for (batlinevalue= colon+1;
173 *batlinevalue && isspace((unsigned char)*batlinevalue);
176 if (!strcmp(batlinebuf,"ERROR"))
177 return batfailf("kernel reports error");
179 for (p=batlinebuf; p<colon; p++)
183 for (field=fields; field->file; field++) {
184 if (!strcmp(field->file,batfilename) &&
185 !strcmp(field->label,batlinebuf))
186 goto label_interesting;
193 *field->valuep= strtoul(batlinevalue,&ep,10);
194 if (ep==batlinevalue || *ep!=' ')
195 batfailf("value number syntax incorrect");
196 if (strcmp(ep+1,field->unit)) batfailf("incorrect unit");
200 for (*field->valuep=0, enumsearch=field->enumarray;
201 *enumsearch && strcmp(*enumsearch,batlinevalue);
202 (*field->valuep)++, enumsearch++);
204 batfailf("unknown enum value");
213 if (!(thisbat_alarm_present==0 ||
214 thisbat_info_present==0 ||
215 thisbat_state_present==0)) {
216 if (thisbat_alarm_present == VAL_NOTFOUND)
217 thisbat_alarm_present= 1;
219 for (field=fields, missing=0;
222 if (*field->valuep == VAL_NOTFOUND) {
223 fprintf(stderr,"battery/%s/%s: %s: not found\n",
224 batdirname, field->file,field->label);
228 if (missing) return -1;
232 if (r) return batfaile("chdir","..");
238 /*---------- data collection and analysis ----------*/
240 /* These next three variables are the results of the charging state */
241 static unsigned charging_state_mask; /* 1u<<CHGST_* | ... */
242 static double nondegraded_norm, fill_norm, ratepersec_norm;
243 static int alarm_level; /* 0=ok, 1=low */
246 static double total_##f##_##l;
250 static void acquiredata(void) {
255 charging_state_mask= 0;
262 di= opendir("."); if (!di) batfaile("opendir","battery");
263 while ((de= readdir(di))) {
264 if (de->d_name[0]==0 || de->d_name[0]=='.') continue;
266 batdirname= de->d_name;
270 if (r) { charging_state_mask |= CHGST_ERROR; continue; }
272 if (!thisbat_info_present || !thisbat_state_present)
275 charging_state_mask |= 1u << thisbat_state_charging_state;
278 total_##f##_##l += thisbat_##f##_##l;
282 if (thisbat_state_charging_state == CHGST_DISCHARGING)
284 total_state_present_rate -= 2.0 * thisbat_state_present_rate;
289 if (total_info_design_capacity < 0.5)
290 total_info_design_capacity= 1.0;
292 if (total_info_last_full_capacity < total_state_remaining_capacity)
293 total_info_last_full_capacity= total_state_remaining_capacity;
294 if (total_info_design_capacity < total_info_last_full_capacity)
295 total_info_design_capacity= total_info_last_full_capacity;
298 (total_state_remaining_capacity < total_alarm_alarm &&
299 !(charging_state_mask & 1u << CHGST_CHARGING));
301 nondegraded_norm= total_info_last_full_capacity / total_info_design_capacity;
302 fill_norm= total_state_remaining_capacity / total_info_design_capacity;
303 ratepersec_norm= total_state_present_rate
304 / (3600.0 * total_info_design_capacity);
307 static void initacquire(void) {
311 /*---------- display ----------*/
328 static Display *disp;
330 static int width, height;
331 static Colormap cmap;
333 static unsigned long lastbackground;
337 unsigned long lastfg;
340 #define C(c) static unsigned long pix_##c;
341 #define GC(g) static Gcstate gc_##g;
346 static void refresh(void);
348 #define CHGMASK_CHG_DIS (1u<<CHGST_CHARGING | 1u<<CHGST_DISCHARGING)
350 static void failr(const char *m, int r) {
351 fprintf(stderr,"error: %s (code %d)\n", m, r);
355 static void setbackground(unsigned long newbg) {
358 if (newbg == lastbackground) return;
359 r= XSetWindowBackground(disp,win,newbg);
360 if (!r) fail("XSetWindowBackground");
361 lastbackground= newbg;
364 static void setforeground(Gcstate *g, unsigned long px) {
368 if (g->lastfg == px) return;
370 memset(&gcv,0,sizeof(gcv));
371 g->lastfg= gcv.foreground= px;
372 r= XChangeGC(disp,g->gc,GCForeground,&gcv);
373 if (!r) fail("XChangeGC");
376 static void show_solid(unsigned long px) {
378 XClearWindow(disp,win);
381 static void show(void) {
383 int i, leftmost_lit, leftmost_nondeg, beyond, first_beyond;
385 if (!charging_state_mask)
386 return show_solid(pix_darkgreen);
388 if (charging_state_mask & CHGST_ERROR)
389 return show_solid(pix_yellow);
391 setbackground(pix_dimgrey);
392 XClearWindow(disp,win);
394 setforeground(&gc_remain,
395 !(charging_state_mask & CHGMASK_CHG_DIS) ? pix_cyan :
396 !(~charging_state_mask & CHGMASK_CHG_DIS) ? pix_grey :
397 charging_state_mask & (1u<<CHGST_CHARGING)
398 ? pix_green : pix_blue);
400 setforeground(&gc_empty, alarm_level ? pix_red : pix_black);
402 for (i=0, first_beyond=1; i<height; i++) {
405 TOP * exp( (double)i / (height-2) * log( (double)BOTTOM/TOP ) );
407 then= fill_norm + ratepersec_norm * elap;
410 ((charging_state_mask & (1u<<CHGST_DISCHARGING) && then <= 0.0) ||
411 (charging_state_mask & (1u<<CHGST_CHARGING) && then>=nondegraded_norm));
413 if (then <= 0.0) then= 0.0;
414 else if (then >= nondegraded_norm) then= nondegraded_norm;
416 leftmost_lit= width * then;
417 leftmost_nondeg= width * nondegraded_norm;
419 if (beyond && first_beyond) {
420 XDrawLine(disp, win, gc_white.gc, 0,i, leftmost_nondeg,i);
423 if (leftmost_lit < leftmost_nondeg)
424 XDrawLine(disp, win, gc_empty.gc,
425 leftmost_lit,i, leftmost_nondeg,i);
426 if (leftmost_lit >= 0)
427 XDrawLine(disp, win, gc_remain.gc, 0,i, leftmost_lit,i);
432 static void initgc(Gcstate *gc_r) {
435 memset(&gcv,0,sizeof(gcv));
436 gcv.function= GXcopy;
438 gc_r->lastfg= gcv.foreground= pix_white;
439 gc_r->gc= XCreateGC(disp,win, GCFunction|GCLineWidth|GCForeground, &gcv);
442 static void colour(unsigned long *pix_r, const char *name) {
446 st= XAllocNamedColor(disp,cmap,name,&xc,&xc);
452 static void initgraphics(int argc, char **argv) {
454 const char *geom_string;
455 XSizeHints *normal_hints;
457 XClassHint *class_hint;
458 int pos_x, pos_y, gravity;
459 char *program_name_silly;
461 program_name_silly= (char*)program_name;
463 disp= XOpenDisplay(0);
464 if (!disp) fail("could not open display");
466 screen= DefaultScreen(disp);
468 normal_hints= XAllocSizeHints();
469 wm_hints= XAllocWMHints();
470 class_hint= XAllocClassHint();
472 if (!normal_hints || !wm_hints || !class_hint)
473 fail("could not alloc hint(s)");
475 geom_string= argc>=2 ? argv[1] : 0;
477 r= XWMGeometry(disp,screen, geom_string,"128x32", 0,
483 win= XCreateSimpleWindow(disp,DefaultRootWindow(disp),
484 pos_x,pos_y,width,height,0,0,0);
485 cmap= DefaultColormap(disp,screen);
487 #define C(c) colour(&pix_##c, #c);
488 #define GC(g) initgc(&gc_##g);
493 r= XSetWindowBackground(disp,win,pix_dimgrey);
494 if (!r) fail("init set background");
495 lastbackground= pix_dimgrey;
497 normal_hints->flags= PWinGravity;
498 normal_hints->win_gravity= gravity;
499 normal_hints->x= pos_x;
500 normal_hints->y= pos_y;
501 normal_hints->width= width;
502 normal_hints->height= height;
503 if (geom_string) normal_hints->flags |= USPosition;
505 wm_hints->flags= InputHint;
506 wm_hints->input= False;
508 class_hint->res_name= program_name_silly;
509 class_hint->res_class= program_name_silly;
511 XmbSetWMProperties(disp,win, program_name,program_name,
512 argv,argc, normal_hints, wm_hints, class_hint);
514 XSelectInput(disp,win, ExposureMask|StructureNotifyMask);
515 XMapWindow(disp,win);
518 static void refresh(void) {
523 static void newgeometry(void) {
527 XGetGeometry(disp,win, &dummyw,&dummy,&dummy, &width,&height, &dummy,&dummy);
530 static void eventloop(void) {
541 pfd.fd= ConnectionNumber(disp);
542 pfd.events= POLLIN|POLLERR;
544 timeout= !(charging_state_mask & CHGST_ERROR) ? TIMEOUT : TIMEOUT_ONERROR;
545 r= poll(&pfd,1,timeout);
546 if (r==-1 && errno!=EINTR) failr("poll",errno);
548 while (XPending(disp)) {
549 XNextEvent(disp,&ev);
550 if (ev.type == ConfigureNotify) {
551 XConfigureEvent *ce= (void*)&ev;
560 int main(int argc, char **argv) {
561 if (argc<1 || argc>2)
565 initgraphics(argc,argv);