slb

Sleep on Low Battery
Log | Files | Refs | README | LICENSE

commit 77c9da3a1909c0d3e870957fb2247ca6a3ab73c8
Author: zerous Naveen Narayanan <zerous@nocebo.space>
Date:   Wed, 30 Oct 2019 18:54:42 +0100

Initial commit

Diffstat:
AMakefile | 8++++++++
AREADME | 25+++++++++++++++++++++++++
Aconfig.h | 17+++++++++++++++++
Aslb.c | 66++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
4 files changed, 116 insertions(+), 0 deletions(-)

diff --git a/Makefile b/Makefile @@ -0,0 +1,8 @@ +all: slb + +slb: config.h + +.PHONY: clean + +clean: + rm -f slb 2>/dev/null diff --git a/README b/README @@ -0,0 +1,25 @@ + _ _ + ___| | |__ +/ __| | '_ \ +\__ \ | |_) | +|___/_|_.__/ + -- zerous +============= + +What is it? +=========== + +slb (acroynm for sleep on low battery) is a daemon which hibernates +your machine when your battery is below a certain threshold. + +Building +======== + + Customize config.h + make + +Contact +======= + +To report bugs and/or submit patches, you can reach us through +irc.2f30.org at #2f30 diff --git a/config.h b/config.h @@ -0,0 +1,17 @@ +int delay = 10; + +/* threshold below which system should hibernate */ +int threshold = 10; + +const char bat[][64] = { + "/sys/class/power_supply/BAT0/capacity", + "/sys/class/power_supply/BAT1/capacity" +}; + +const char ac[64] = { + "/sys/class/power_supply/AC/online" +}; + +const char cmd[64] = { + "/bin/ZZZ" +}; diff --git a/slb.c b/slb.c @@ -0,0 +1,66 @@ +#include <err.h> +#include <fcntl.h> +#include <stdio.h> +#include <stdlib.h> +#include <sys/types.h> +#include <sys/stat.h> +#include <sys/wait.h> +#include <unistd.h> + +#include "config.h" + +int +pwread(const char *bat) +{ + char buf[4]; + int fd; + int t; + + if ((fd = open(bat, O_RDONLY)) == -1) { + err(1, "open failed"); + } + + if ((t = read(fd,buf,3)) == -1) { + err(1, "read failed"); + } + + buf[t]=0; + + return atoi(buf); +} + +int +main(int argc, char **argv) +{ + (void) argc; + (void) argv; + + int tpow; + int t; + pid_t p; + + + for (;;) { + tpow = 0; + + for (int i = 0; i < sizeof(bat)/64; i++) { + tpow += pwread(bat[i]); + } + + if (!pwread(ac) && (tpow < threshold)) { + if ((p = fork()) == -1) + err(1, "fork failed"); + else if (p > 0) { + wait(NULL); + } + else if (p == 0) { + if ((t = execve(cmd,NULL,NULL)) == -1) + err(1, "execve failed"); + } + } + + sleep(delay); + } + + return 0; +}