X-Git-Url: http://www.chiark.greenend.org.uk/ucgi/~ian/git?p=chiark-utils.git;a=blobdiff_plain;f=cprogs%2Fxacpi-simple.c;h=cd2a1c7f37f34a8633b211aae674eea68485991a;hp=96ba1051a6097b746e4fe8a60d58488868d09454;hb=d537b0b5f235d49af42e4718786a8ffb170a0c53;hpb=ea390adc72dc10795b3e09cc9e569dd3b572528d diff --git a/cprogs/xacpi-simple.c b/cprogs/xacpi-simple.c index 96ba105..cd2a1c7 100644 --- a/cprogs/xacpi-simple.c +++ b/cprogs/xacpi-simple.c @@ -1,118 +1,667 @@ /* + * display outputs, per line: + * + * Remaining: | Empty: | Degraded: + * blue | black | dimgrey discharging + * green | black | dimgrey charging + * cyan | black | dimgrey charged + * grey | black | dimgrey charging&discharching! + * blue | red | dimgrey discharging - low! + * green | red | dimgrey charging - low + * cyan | red | dimgrey charged - low [1] + * grey | red | dimgrey charging&discharching, low [1] + * ... darkgreen ... no batteries present + * ... yellow ... error + * + * [1] battery must be quite badly degraded + */ +/* + * Copyright (C) 2004 Ian Jackson + * + * This is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation; either version 3, + * or (at your option) any later version. + * + * This is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this file; if not, consult the Free Software + * Foundation's website at www.fsf.org, or the GNU Project website at + * www.gnu.org. */ #include +#include #include #include +#include +#include #include +#include +#include + +#include +#include +#include #include +#include +#include + +#define TOP 60 +#define BOTTOM 3600 + +#define TIMEOUT 5000 /* milliseconds */ +#define TIMEOUT_ONERROR 3333 /* milliseconds */ + +static const char program_name[]= "xacpi-simple"; + +/*---------- general utility stuff and declarations ----------*/ static void fail(const char *m) { fprintf(stderr,"error: %s\n", m); - sleep(5); exit(-1); } static void badusage(void) { fail("bad usage"); } -static Display *d; -static Window w; +typedef struct fileinfo fileinfo; +struct fileinfo { + const char *filename; + void (*parse)(const fileinfo*); + const void *extra; +}; + +/*---------- structure of and results from /sys/class/power/... ----------*/ +/* variables thisbat_... are the results from readbattery(); + * if readbattery() succeeds they are all valid and not VAL_NOTFOUND + */ + +typedef struct batinfo_field { + const char *label; + uint64_t *valuep; + const char *enumarray[10]; +} batinfo_field; + +#define UEVENT_QUANTITY_FIELDS(q) \ + q(design_capacity, CHARGE_FULL_DESIGN ) /* uAh */ \ + q(last_full_capacity, CHARGE_FULL ) /* uAh */ \ + q(present_rate, CURRENT_NOW ) /* uA */ \ + q(remaining_capacity, CHARGE_NOW ) /* uAh */ \ + q(present, PRESENT ) /* boolean */ \ + q(online, ONLINE ) /* boolean */ + +#define UEVENT_ENUM_FIELDS(e) \ + e(type, TYPE, "Battery", "Mains" ) \ + e(state, STATUS, "Discharging", "Charging", "Charged" ) + +#define CHGST_DISCHARGING 0 /* Reflects order in e(state,...) above */ +#define CHGST_CHARGING 1 /* Also, much code assumes exadtly */ +#define CHGST_CHARGED 2 /* these three possible states. */ +#define CHGST_ERROR 8 /* Except that this one is an extra bit. */ + +#define Q_FLD(f,l) { "POWER_SUPPLY_" #l, &thisbat_##f }, +#define E_FLD(f,l,vl...) { "POWER_SUPPLY_" #l, &thisbat_##f, { vl } }, + +#define ALL_FIELDS(i) \ + UEVENT_QUANTITY_FIELDS(i) \ + UEVENT_ENUM_FIELDS(i) \ + i(thisbat_alarm) + +#define F_VAR(f,...) static uint64_t thisbat_##f; + ALL_FIELDS(F_VAR) + +static const batinfo_field uevent_fields[]= { + UEVENT_QUANTITY_FIELDS(Q_FLD) + UEVENT_ENUM_FIELDS(E_FLD) + { 0 } +}; + +#define VAL_NOTFOUND (~0UL) + +static const fileinfo files[]= { + { "uevent", parse_fields, uevent_fields }, + { "alarm", parse_boolean, &thisbat_alarm }, + { 0 } +}; + +/*---------- parsing of one battery in /proc/acpi/battery/... ----------*/ + +/* variables private to the parser and its error handlers */ +static char batlinebuf[1000]; +static FILE *batfile; +static const char *batdirname; +static const char *batfilename; +static const char *batlinevalue; + +static int batfailf(const char *why) { + if (batlinevalue) { + fprintf(stderr,"battery/%s/%s: %s value `%s': %s\n", + batdirname,batfilename, batlinebuf,batlinevalue,why); + } else { + fprintf(stderr,"battery/%s/%s: %s: `%s'\n", + batdirname,batfilename, why, batlinebuf); + } + return -1; +} + +static int batfaile(const char *syscall, const char *target) { + fprintf(stderr,"battery/%s: failed to %s %s: %s\n", + batdirname ? batdirname : "*", syscall, target, strerror(errno)); + return -1; +} + +static void chdir_base(void) { + int r; + + r= chdir("/sys/class/power_supply"); + if (r) batfaile("chdir","/sys/class/power_supply"); +} + +static void tidybattery(void) { + if (batfile) { fclose(batfile); batfile=0; } + if (batdirname) { chdir_base(); batdirname=0; } +} + +static void parse_fields(const fileinfo *cfile, char *batlinebuf) { + equals= strchr(batlinebuf,'='); + if (!equals) + return batfailf("line without a equals"); + *equals++= 0; + + for (field=fields; field->file; field++) { + if (!strcmp(field->label,batlinebuf)) + goto found; + } + return; + + found: + if (!field->enumarray[0]) { + + *field->valuep= strtoull(equals,&ep,10); + if (*ep) + batfailf("value number syntax incorrect"); + + } else { + + for (*field->valuep=0, enumsearch=field->enumarray; + *enumsearch && strcmp(*enumsearch,equals); + (*field->valuep)++, enumsearch++); + if (!*enumsearch) + batfailf("unknown enum value"); + + } +} + +static int readbattery(void) { /* 0=>ok, -1=>couldn't */ + const batinfo_field *field; + const fileinfo *cfile; + const char *const *enumsearch; + char *colon, *ep, *sr, *p; + int r, l, missing; + + r= chdir(batdirname); + if (r) return batfaile("chdir",batdirname); + +#define V_NOTFOUND(f,...) thisbat_##f = VAL_NOTFOUND; + ALL_FIELDS(V_NOTFOUND) + + for (field=fields; field->file; field++) + *field->valuep= VAL_NOTFOUND; + + for (cfile=files; + (batfilename= cfile->filename); + cfile++++) { + batfile= fopen(batfilename,"r"); + if (!batfile) return batfaile("open",batfilename); + + for (;;) { + batlinevalue= 0; + + sr= fgets(batlinebuf,sizeof(batlinebuf),batfile); + if (ferror(batfile)) return batfaile("read",batfilename); + if (!sr && feof(batfile)) break; + l= strlen(batlinebuf); + assert(l>0); + if (batlinebuf[l-1] != '\n') + return batfailf("line too long"); + batlinebuf[l-1]= 0; + + cfile->parse(cfile, batlinebuf); + } + + fclose(batfile); + batfile= 0; + } + + if (!(thisbat_alarm_present==0 || + thisbat_state_present==0 || thisbat_info_present==0)) { + if (thisbat_alarm_present == VAL_NOTFOUND) + thisbat_alarm_present= 1; + + for (field=fields, missing=0; + field->file; + field++) { + if (*field->valuep == VAL_NOTFOUND) { + fprintf(stderr,"battery/%s/%s: %s: not found\n", + batdirname, field->file,field->label); + missing++; + } + } + if (missing) return -1; + } + + r= chdir(".."); + if (r) return batfaile("chdir",".."); + batdirname= 0; + + return 0; +} + +/*---------- data collection and analysis ----------*/ + +/* These next three variables are the results of the charging state */ +static unsigned charging_state_mask; /* 1u<d_name[0]==0 || de->d_name[0]=='.') continue; + + batdirname= de->d_name; + r= readbattery(); + tidybattery(); + + if (r) { charging_state_mask |= CHGST_ERROR; continue; } + + if (!thisbat_info_present || !thisbat_state_present) + continue; + + charging_state_mask |= 1u << thisbat_state_charging_state; + +#define QF(f,l,u) \ + total_##f##_##l += thisbat_##f##_##l; + QUANTITY_FIELDS +#undef QF + + if (thisbat_state_charging_state == CHGST_DISCHARGING) + /* negate it */ + total_state_present_rate -= 2.0 * thisbat_state_present_rate; + + } + closedir(di); + + if (total_info_design_capacity < 0.5) + total_info_design_capacity= 1.0; + + if (total_info_last_full_capacity < total_state_remaining_capacity) + total_info_last_full_capacity= total_state_remaining_capacity; + if (total_info_design_capacity < total_info_last_full_capacity) + total_info_design_capacity= total_info_last_full_capacity; + + alarm_level= + (total_state_remaining_capacity < total_alarm_alarm && + !(charging_state_mask & 1u << CHGST_CHARGING)); + + nondegraded_norm= total_info_last_full_capacity / total_info_design_capacity; + fill_norm= total_state_remaining_capacity / total_info_design_capacity; + ratepersec_norm= total_state_present_rate + / (3600.0 * total_info_design_capacity); +} + +static void initacquire(void) { + chdir_base(); +} + +/*---------- argument parsing ----------*/ + +#define COLOURS \ + C(blue, discharging) \ + C(green, charging) \ + C(cyan, charged) \ + C(grey, confusing) \ + C(black, normal) \ + C(red, low) \ + C(dimgrey, degraded) \ + C(darkgreen, absent) \ + C(yellow, error) \ + C(white, equilibrium) \ + GC(remain) \ + GC(white) \ + GC(empty) + +static XrmDatabase xrm; +static Display *disp; +static int screen; + +static const char defaultresources[]= +#define GC(g) +#define C(c,u) \ + "*" #u "Color: " #c "\n" + COLOURS +#undef GC +#undef C + ; + +#define S(s) ((char*)(s)) +static const XrmOptionDescRec optiontable[]= { + { S("-display"), S("*display"), XrmoptionSepArg }, + { S("-geometry"), S("*geometry"), XrmoptionSepArg }, +#define GC(g) +#define C(c,u) \ + { S("-" #u "Color"), S("*" #u "Color"), XrmoptionSepArg }, \ + { S("-" #u "Colour"), S("*" #u "Color"), XrmoptionSepArg }, + COLOURS +#undef GC +#undef C +}; + +static const char *getresource(const char *want) { + char name_buf[256], class_buf[256]; + XrmValue val; + char *rep_type_dummy; + int r; + + assert(strlen(want) < 128); + sprintf(name_buf,"xacpi-simple.%s",want); + sprintf(class_buf,"Xacpi-Simple.%s",want); + + r= XrmGetResource(xrm, name_buf,class_buf, &rep_type_dummy, &val); + if (!r) return 0; + + return val.addr; +} + +static void more_resources(const char *str, const char *why) { + XrmDatabase more; + + if (!str) return; + + more= XrmGetStringDatabase((char*)str); + if (!more) fail(why); + XrmCombineDatabase(more,&xrm,0); +} + +static void parseargs(int argc, char **argv) { + Screen *screenscreen; + + XrmInitialize(); + + XrmParseCommand(&xrm, (XrmOptionDescRec*)optiontable, + sizeof(optiontable)/sizeof(*optiontable), + program_name, &argc, argv); + + if (argc>1) badusage(); + + disp= XOpenDisplay(getresource("display")); + if (!disp) fail("could not open display"); + + screen= DefaultScreen(disp); + + screenscreen= ScreenOfDisplay(disp,screen); + if (!screenscreen) fail("screenofdisplay"); + more_resources(XScreenResourceString(screenscreen), "screen resources"); + more_resources(XResourceManagerString(disp), "display resources"); + more_resources(defaultresources, "default resources"); +} + +/*---------- display ----------*/ + +static Window win; static int width, height; -static GC gc_green, gc_red, gc_yellow, gc_blue; static Colormap cmap; -static int screen; +static unsigned long lastbackground; -#define TOP 60 -#define BOTTOM 3600 +typedef struct { + GC gc; + unsigned long lastfg; +} Gcstate; + +#define C(c,u) static unsigned long pix_##c; +#define GC(g) static Gcstate gc_##g; + COLOURS +#undef C +#undef GC static void refresh(void); -static void geometry(void) { - int dummy; - Window dummyw; +#define CHGMASK_CHG_DIS (1u<lastfg == px) return; + + memset(&gcv,0,sizeof(gcv)); + g->lastfg= gcv.foreground= px; + r= XChangeGC(disp,g->gc,GCForeground,&gcv); + if (!r) fail("XChangeGC"); +} + +static void show_solid(unsigned long px) { + setbackground(px); + XClearWindow(disp,win); } -static void show(double fill_norm, double ratepersec_norm, int ac) { +static void show(void) { double elap, then; - int i, leftmost_lit; + int i, leftmost_lit, leftmost_nondeg, beyond, first_beyond; - for (i=0; i= 1.0 ? width : - width * then; - -fprintf(stderr," width=%d height=%d i=%d elap=%f then=%f leftmost_lit=%d\n", - (unsigned long)w, - width,height,i,then,leftmost_lit); - if (leftmost_lit >= 0) - XDrawLine(d, w, ac ? gc_blue : gc_green, 0,i, leftmost_lit,i); - if (leftmost_lit < width) - XDrawLine(d, w, then >= 0 ? gc_red : gc_yellow, - leftmost_lit+1,i, width,i); + beyond= + ((charging_state_mask & (1u<=nondegraded_norm)); + + if (then <= 0.0) then= 0.0; + else if (then >= nondegraded_norm) then= nondegraded_norm; + + leftmost_lit= width * then; + leftmost_nondeg= width * nondegraded_norm; + + if (beyond && first_beyond) { + XDrawLine(disp, win, gc_white.gc, 0,i, leftmost_nondeg,i); + first_beyond= 0; + } else { + if (leftmost_lit < leftmost_nondeg) + XDrawLine(disp, win, gc_empty.gc, + leftmost_lit,i, leftmost_nondeg,i); + if (leftmost_lit >= 0) + XDrawLine(disp, win, gc_remain.gc, 0,i, leftmost_lit,i); + } } } -static void refresh(void) { - show(0.3, 0.5/3600, 1); +static void initgc(Gcstate *gc_r) { + XGCValues gcv; + + memset(&gcv,0,sizeof(gcv)); + gcv.function= GXcopy; + gcv.line_width= 1; + gc_r->lastfg= gcv.foreground= pix_white; + gc_r->gc= XCreateGC(disp,win, GCFunction|GCLineWidth|GCForeground, &gcv); } -static void colour(GC *gc_r, const char *name) { +static void colour(unsigned long *pix_r, const char *whichcolour) { XColor xc; + const char *name; Status st; - XGCValues gcv; + + name= getresource(whichcolour); + if (!name) fail("get colour resource"); - st= XAllocNamedColor(d,cmap,name,&xc,&xc); - if (!st) fail("couldn't allocate colour"); + st= XAllocNamedColor(disp,cmap,name,&xc,&xc); + if (!st) fail(name); - gcv.function= GXcopy; - gcv.line_width= 1; - gcv.foreground= xc.pixel; - *gc_r= XCreateGC(d,w, GCFunction|GCForeground|GCLineWidth, &gcv); + *pix_r= xc.pixel; } -int main(int argc, const char *const *argv) { - const char *windowid_string; - char *ep; - XEvent ev; +static void initgraphics(int argc, char **argv) { + int xwmgr, r; + const char *geom_string; + XSizeHints *normal_hints; + XWMHints *wm_hints; + XClassHint *class_hint; + int pos_x, pos_y, gravity; + char *program_name_silly; - d= XOpenDisplay(0); if (!d) fail("could not open display"); - - if (!argv[0] || argv[1]) - badusage(); + program_name_silly= (char*)program_name; - /* if (!(windowid_string= getenv("WINDOWID"))) - badusage(); w= strtoul(windowid_string,&ep,0); - if (*ep) badusage(); + normal_hints= XAllocSizeHints(); + wm_hints= XAllocWMHints(); + class_hint= XAllocClassHint(); -*/ + if (!normal_hints || !wm_hints || !class_hint) + fail("could not alloc hint(s)"); - screen= DefaultScreen(d); + geom_string= getresource("geometry"); - w= XCreateSimpleWindow(d,DefaultRootWindow(d),0,0,50,50,0,0,0); + xwmgr= XWMGeometry(disp,screen, geom_string,"128x32", 0, + normal_hints, + &pos_x, &pos_y, + &width, &height, + &gravity); - cmap= DefaultColormap(d,screen); + win= XCreateSimpleWindow(disp,DefaultRootWindow(disp), + pos_x,pos_y,width,height,0,0,0); + cmap= DefaultColormap(disp,screen); - colour(&gc_green, "green"); - colour(&gc_red, "darkred"); - colour(&gc_yellow, "yellow"); - colour(&gc_blue, "blue"); +#define C(c,u) colour(&pix_##c, #u "Color"); +#define GC(g) initgc(&gc_##g); + COLOURS +#undef C +#undef GC + + r= XSetWindowBackground(disp,win,pix_dimgrey); + if (!r) fail("init set background"); + lastbackground= pix_dimgrey; + + normal_hints->flags= PWinGravity; + normal_hints->win_gravity= gravity; + normal_hints->x= pos_x; + normal_hints->y= pos_y; + normal_hints->width= width; + normal_hints->height= height; + if ((xwmgr & XValue) || (xwmgr & YValue)) + normal_hints->flags |= USPosition; - XSelectInput(d,w, ExposureMask|VisibilityChangeMask); - XMapWindow(d,w); + wm_hints->flags= InputHint; + wm_hints->input= False; + + class_hint->res_name= program_name_silly; + class_hint->res_class= program_name_silly; + + XmbSetWMProperties(disp,win, program_name,program_name, + argv,argc, normal_hints, wm_hints, class_hint); + + XSelectInput(disp,win, ExposureMask|StructureNotifyMask); + XMapWindow(disp,win); +} + +static void refresh(void) { + acquiredata(); + show(); +} + +static void newgeometry(void) { + int dummy; + Window dummyw; - geometry(); + XGetGeometry(disp,win, &dummyw,&dummy,&dummy, &width,&height, &dummy,&dummy); +} + +static void eventloop(void) { + XEvent ev; + struct pollfd pfd; + int r, timeout; + newgeometry(); + refresh(); + for (;;) { - XNextEvent(d,&ev); - geometry(); + XFlush(disp); + + pfd.fd= ConnectionNumber(disp); + pfd.events= POLLIN|POLLERR; + + timeout= !(charging_state_mask & CHGST_ERROR) ? TIMEOUT : TIMEOUT_ONERROR; + r= poll(&pfd,1,timeout); + if (r==-1 && errno!=EINTR) failr("poll",errno); + + while (XPending(disp)) { + XNextEvent(disp,&ev); + if (ev.type == ConfigureNotify) { + XConfigureEvent *ce= (void*)&ev; + width= ce->width; + height= ce->height; + } + } + refresh(); } } + +int main(int argc, char **argv) { + parseargs(argc,argv); + initacquire(); + initgraphics(argc,argv); + eventloop(); + return 0; +}