status

statusbar program for dwm
git clone anongit@rnpnr.xyz:status.git
Log | Files | Refs | Feed | README | LICENSE

battery.c (1600B)


      1 /* See LICENSE for license details. */
      2 #include <limits.h>
      3 
      4 struct bat_arg {
      5 	char *bat; /* BAT name (ex. BAT0) */
      6 	char *pre; /* prefix for percentages less than thres */
      7 	char *suf; /* suffix for percentages less than thres */
      8 	int thres; /* % threshold to consider low (-1 to disable) */
      9 };
     10 
     11 static size_t
     12 batinfo(struct Block *b)
     13 {
     14 	struct bat_arg *ba = b->arg;
     15 	char *pre = ba->pre ? ba->pre : "";
     16 	char *suf = ba->suf ? ba->suf : "";
     17 	char path[PATH_MAX], state[12];
     18 	int perc, s;
     19 	unsigned long power_now, energy_now, h, m;
     20 	double timeleft;
     21 
     22 	snprintf(path, sizeof(path), "/sys/class/power_supply/%s/capacity", ba->bat);
     23 	if (pscanf(path, "%d", &perc) != 1)
     24 		perc = 0;
     25 
     26 	s = perc < ba->thres;
     27 
     28 	snprintf(path, sizeof(path), "/sys/class/power_supply/%s/status", ba->bat);
     29 	if (pscanf(path, "%12s", &state) != 1)
     30 		snprintf(state, sizeof(state), "Unknown");
     31 
     32 	if (!strcmp(state, "Discharging")) {
     33 		snprintf(path, sizeof(path),
     34 		         "/sys/class/power_supply/%s/power_now", ba->bat);
     35 		if (pscanf(path, "%lu", &power_now) != 1)
     36 			power_now = 1;
     37 
     38 		snprintf(path, sizeof(path),
     39 		         "/sys/class/power_supply/%s/energy_now", ba->bat);
     40 		if (pscanf(path, "%lu", &energy_now) != 1)
     41 			energy_now = 0;
     42 
     43 		timeleft = (double)energy_now / (double)power_now;
     44 		h = timeleft;
     45 		m = (timeleft - (double)h) * 60;
     46 
     47 		snprintf(buf, sizeof(buf), "%s%d%% (%lu:%02lu)%s", s ? pre : "",
     48 		         perc, h, m, s ? suf : "");
     49 	} else {
     50 		snprintf(buf, sizeof(buf), "%s%d%% (%s)%s", s ? pre : "", perc,
     51 		         state, s ? suf : "");
     52 	}
     53 
     54 	return snprintf(b->curstr, LEN(b->curstr), b->fmt, buf);
     55 }