+typedef uint64_t value;
+#define VAL_NOTFOUND (~(value)0)
+
+typedef struct fileinfo fileinfo;
+typedef int parser(const fileinfo*);
+
+static parser parse_uevent;
+
+struct fileinfo {
+ const char *filename;
+ parser *parse;
+ const void *extra;
+};
+
+/*---------- structure of and results from /sys/class/power/... ----------*/
+/* variables this_... are the results from readbattery();
+ * if readbattery() succeeds the appropriate ones are all valid
+ * and not VAL_NOTFOUND
+ */
+
+typedef struct batinfo_field {
+ const char *label;
+ value *valuep;
+ const char *enumarray[10];
+} batinfo_field;
+
+#define BAT_QTYS(_, _ec, EC_, PC_) \
+ _(design_capacity##_ec, BATTERY, EC_##FULL_DESIGN ) \
+ _(last_full_capacity##_ec, BATTERY, EC_##FULL ) \
+ _(remaining_capacity##_ec, BATTERY, EC_##NOW ) \
+ _(present_rate##_ec, BATTERY, PC_##NOW )
+ /* ENERGY [mWh]; POWER [mW]; CHARGE [uAh]; CURRENT [uA] */
+
+#define UEVENT_ESSENTIAL_QUANTITY_FIELDS(_) \
+ _(present, BATTERY, PRESENT /* bool */ ) \
+ _(online, MAINS, ONLINE /* bool */ )
+
+#define UEVENT_FUNKY_QUANTITY_FIELDS(_) \
+ BAT_QTYS(_,_energy,ENERGY_,POWER_) \
+ BAT_QTYS(_,_charge,CHARGE_,CURRENT_)
+
+#define UEVENT_OPTIONAL_QUANTITY_FIELDS(_) \
+ _(voltage, BATTERY, VOLTAGE_NOW /* uV */ )
+
+#define UEVENT_ENUM_FIELDS(_) \
+ _(state, BATTERY, STATUS, "Discharging","Charging","Full","Unknown" ) \
+ _(type, BOTH, TYPE, "Mains", "Battery" )
+
+#define CHGST_DISCHARGING 0 /* Reflects order in _(state,...) above */
+#define CHGST_CHARGING 1 /* Also, much code assumes exactly */
+#define CHGST_CHARGED 2 /* these three possible states. */
+#define CHGST_UNKNOWN 3 /* these three possible states. */
+#define CHGST_ERROR 8 /* Except that this one is an extra bit. */
+
+#define TYPE_MAINS 0 /* Reflects order in _(type,...) above */
+#define TYPE_BATTERY 1 /* Also, much code assumes exactly these two */
+#define TYPE_BOTH 100 /* Except this is a magic invalid value. */
+
+#define SEPARATE_QUANTITY_FIELDS(_) \
+ /* See commit ec6f5f0be800bc5f2a27046833dba04e0c67ffac for
+ the code needed to use this */
+
+
+#define ALL_DIRECT_VARS(_) \
+ UEVENT_ESSENTIAL_QUANTITY_FIELDS(_) \
+ UEVENT_FUNKY_QUANTITY_FIELDS(_) \
+ UEVENT_OPTIONAL_QUANTITY_FIELDS(_) \
+ UEVENT_ENUM_FIELDS(_) \
+ SEPARATE_QUANTITY_FIELDS(_)
+
+#define ALL_VARS(_) \
+ ALL_DIRECT_VARS(_) \
+ BAT_QTYS(_,,,)
+
+#define ALL_NEEDED_FIELDS(_) \
+ UEVENT_ESSENTIAL_QUANTITY_FIELDS(_) \
+ UEVENT_ENUM_FIELDS(_) \
+ SEPARATE_QUANTITY_FIELDS(_)
+
+#define ALL_PLAIN_ACCUMULATE_FIELDS(_) \
+ UEVENT_ESSENTIAL_QUANTITY_FIELDS(_) \
+ SEPARATE_QUANTITY_FIELDS(_)
+
+#define ALL_ACCUMULATE_FIELDS(_) \
+ ALL_PLAIN_ACCUMULATE_FIELDS(_) \
+ BAT_QTYS(_,,,)
+
+
+#define F_VAR(f,...) \
+static value this_##f;
+ALL_VARS(F_VAR)
+
+#define Q_FLD(f,t,l) { "POWER_SUPPLY_" #l, &this_##f },
+#define E_FLD(f,t,l,vl...) { "POWER_SUPPLY_" #l, &this_##f, { vl } },
+
+static const batinfo_field uevent_fields[]= {
+ UEVENT_ESSENTIAL_QUANTITY_FIELDS(Q_FLD)
+ UEVENT_FUNKY_QUANTITY_FIELDS(Q_FLD)
+ UEVENT_OPTIONAL_QUANTITY_FIELDS(Q_FLD)
+ UEVENT_ENUM_FIELDS(E_FLD)
+ { 0 }
+};
+
+#define S_FLD(f,t,fn,vl...) \
+static const batinfo_field bif_##f = { 0, &this_##f, { vl } };
+ SEPARATE_QUANTITY_FIELDS(S_FLD)
+
+#define S_FILE(f,t,fn,vl...) { fn, parse_separate, &bif_##f },
+
+static const fileinfo files[]= {
+ { "uevent", parse_uevent, uevent_fields },
+ SEPARATE_QUANTITY_FIELDS(S_FILE)
+ { 0 }
+};
+
+/*---------- parsing of one thingx in /sys/class/power/... ----------*/
+
+/* 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,"%s/%s: %s value `%s': %s\n",
+ batdirname,batfilename, batlinebuf,batlinevalue,why);
+ } else {
+ fprintf(stderr,"%s/%s: %s: `%s'\n",
+ batdirname,batfilename, why, batlinebuf);
+ }
+ return -1;
+}
+
+static int batfailc(const char *why) {
+ fprintf(stderr,"%s/%s: %s\n",
+ batdirname,batfilename, why);
+ return -1;
+}
+
+static int batfaile(const char *syscall, const char *target) {
+ fprintf(stderr,"%s: failed to %s %s: %s\n",
+ batdirname ? batdirname : "*", syscall, target, strerror(errno));
+ return -1;
+}
+
+static int chdir_base(void) {
+ int r;
+
+ r= chdir("/sys/class/power_supply");
+ if (r) return batfaile("chdir","/sys/class/power_supply");
+
+ return 0;
+}
+
+static void tidybattery(void) {
+ if (batfile) { fclose(batfile); batfile=0; }
+}
+
+static int parse_value(const fileinfo *cfile, const batinfo_field *field) {
+ if (*field->valuep != VAL_NOTFOUND)
+ return batfailf("value specified multiple times");
+
+ if (!field->enumarray[0]) {
+
+ char *ep;
+ *field->valuep= strtoull(batlinevalue,&ep,10);
+ if (*ep)
+ batfailf("value number syntax incorrect");
+
+ } else {
+
+ const char *const *enumsearch;
+ for (*field->valuep=0, enumsearch=field->enumarray;
+ *enumsearch && strcmp(*enumsearch,batlinevalue);
+ (*field->valuep)++, enumsearch++);
+ if (!*enumsearch)
+ batfailf("unknown enum value");
+
+ }
+ return 0;
+}
+
+static int parse_uevent(const fileinfo *cfile) {
+ char *equals= strchr(batlinebuf,'=');
+ if (!equals)
+ return batfailf("line without a equals");
+ *equals= 0;
+ batlinevalue = equals+1;
+
+ const batinfo_field *field;
+ for (field=cfile->extra; field->label; field++) {
+ if (!strcmp(field->label,batlinebuf))
+ goto found;
+ }
+ return 0;
+
+ found:
+ return parse_value(cfile, field);
+}
+
+static int readbattery(void) { /* 0=>ok, -1=>couldn't */
+
+ const fileinfo *cfile;
+ char *sr;
+ int r, l;
+
+ r= chdir_base();
+ if (r) return r;
+
+ r= chdir(batdirname);
+ if (r) return batfaile("chdir",batdirname);
+
+#define V_NOTFOUND(f,...) \
+ this_##f = VAL_NOTFOUND;
+ALL_VARS(V_NOTFOUND)
+
+ for (cfile=files;
+ (batfilename= cfile->filename);
+ cfile++) {
+ batfile= fopen(batfilename,"r");
+ if (!batfile) {
+ if (errno == ENOENT) continue;
+ 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;
+
+ if (cfile->parse(cfile))
+ return -1;
+ }
+
+ fclose(batfile);
+ batfile= 0;
+ }
+
+ if (debug) {
+ printf("%s:\n",batdirname);
+#define V_PRINT(f,...) \
+ printf(" %-30s = %20"PRId64"\n", #f, (int64_t)this_##f);
+ALL_DIRECT_VARS(V_PRINT)
+ }
+
+ int needsfields_MAINS = this_type == TYPE_MAINS;
+ int needsfields_BATTERY = this_type == TYPE_BATTERY;
+ int needsfields_BOTH = 1;
+
+ int missing = 0;
+
+#define V_NEEDED(f,t,...) \
+ if (needsfields_##t && this_##f == VAL_NOTFOUND) { \
+ fprintf(stderr,"%s: %s: not found\n", \
+ batdirname, #f); \
+ missing++; \
+ }
+ALL_NEEDED_FIELDS(V_NEEDED)
+
+ if (missing) return -1;
+
+ return 0;
+}
+
+/*---------- data collection and analysis ----------*/
+
+/* These next three variables are the results of the charging state */
+static unsigned charging_mask; /* 1u<<CHGST_* | ... */
+static double nondegraded_norm, fill_norm, ratepersec_norm;
+static int alarmed;
+
+#define Q_VAR(f,t,...) \
+static double total_##f;
+ ALL_ACCUMULATE_FIELDS(Q_VAR)
+
+static void acquiredata(void) {
+ DIR *di = 0;
+ struct dirent *de;
+ int r;
+
+ charging_mask= 0;
+ alarmed = 0;
+
+ if (debug) printf("\n");
+
+#define Q_ZERO(f,t,...) \
+ total_##f= 0;
+ALL_ACCUMULATE_FIELDS(Q_ZERO)
+
+ r = chdir_base();
+ if (r) goto bad;
+
+ di= opendir("."); if (!di) { batfaile("opendir","battery"); goto bad; }
+ while ((de= readdir(di))) {
+ if (de->d_name[0]==0 || de->d_name[0]=='.') continue;
+
+ batdirname= de->d_name;
+ r= readbattery();
+ tidybattery();
+
+ if (r) {
+ bad:
+ charging_mask |= (1u << CHGST_ERROR);
+ break;
+ }
+
+ if (this_type == TYPE_BATTERY) {
+ if (!this_present)
+ continue;
+
+ charging_mask |= 1u << this_state;
+
+#define QTY_SUPPLIED(f,...) this_##f != VAL_NOTFOUND &&
+#define QTY_USE_ENERGY(f,...) this_##f = this_##f##_energy;
+#define QTY_USE_CHARGE(f,...) this_##f = this_##f##_charge;
+
+ double funky_multiplier;
+ if (BAT_QTYS(QTY_SUPPLIED,_energy,,) 1) {
+ if (debug) printf(" using energy\n");
+ BAT_QTYS(QTY_USE_ENERGY,,,);
+ funky_multiplier = 1.0;
+ } else if (BAT_QTYS(QTY_SUPPLIED,_charge,,)
+ this_voltage != VAL_NOTFOUND) {
+ if (debug) printf(" using charge\n");
+ BAT_QTYS(QTY_USE_CHARGE,,,);
+ funky_multiplier = this_voltage * 1e-6;
+ } else {
+ batfailc("neither complete set of energy nor charge");
+ continue;
+ }
+ if (this_state == CHGST_DISCHARGING)
+ /* negate it */
+ total_present_rate -= 2.0 * this_present_rate * funky_multiplier;
+
+#define Q_ACCUMULATE_FUNKY(f,...) \
+ total_##f += this_##f * funky_multiplier;
+BAT_QTYS(Q_ACCUMULATE_FUNKY,,,)
+ }
+
+#define Q_ACCUMULATE_PLAIN(f,t,...) \
+ if (this_type == TYPE_##t) \
+ total_##f += this_##f;
+ALL_PLAIN_ACCUMULATE_FIELDS(Q_ACCUMULATE_PLAIN)
+
+
+ }
+ if (di) closedir(di);
+
+ if (debug) {
+ printf("TOTAL:\n");
+ printf(" %-30s = %#20x\n", "mask", charging_mask);
+#define T_PRINT(f,...) \
+ printf(" %-30s = %20.6f\n", #f, total_##f);
+BAT_QTYS(T_PRINT,,,)
+ALL_PLAIN_ACCUMULATE_FIELDS(T_PRINT)
+ }
+
+ if ((charging_mask & (1u<<CHGST_DISCHARGING)) &&
+ !total_online/*mains*/) {
+ double time_remaining =
+ -total_remaining_capacity * 3600.0 / total_present_rate;
+ if (debug) printf(" %-30s = %20.6f\n", "time remaining", time_remaining);
+ if (time_remaining < alarmlevel)
+ alarmed = 1;
+ }
+
+ if (total_design_capacity < 0.5)
+ total_design_capacity= 1.0;
+
+ if (total_last_full_capacity < total_remaining_capacity)
+ total_last_full_capacity= total_remaining_capacity;
+ if (total_design_capacity < total_last_full_capacity)
+ total_design_capacity= total_last_full_capacity;
+
+ nondegraded_norm= total_last_full_capacity / total_design_capacity;
+ fill_norm= total_remaining_capacity / total_design_capacity;
+ ratepersec_norm= total_present_rate
+ / (3600.0 * total_design_capacity);
+}
+
+static void initacquire(void) {
+}
+
+/*---------- argument parsing ----------*/
+
+#define COLOURS \
+ C(blue, discharging) \
+ C(green, charging) \
+ C(cyan, charged) \
+ C(lightgrey, notcharging) \
+ 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("-debug"), S("*debug"), XrmoptionIsArg },
+ { S("-warningTime"), S("*warningTime"), XrmoptionSepArg },
+ { 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();
+
+ debug= !!getresource("debug");
+
+ const char *alarmlevel_string= getresource("alarmLevel");
+ alarmlevel = alarmlevel_string ? atoi(alarmlevel_string) : 300;
+
+ 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;