You are not logged in.

#1 2015-12-02 19:21:38

Neven
Member
Registered: 2014-05-02
Posts: 75

Hibernate when battery becomes low: a small Go program

It hibernates with

systemctl hibernate

when battery
"percentage" is low and battery isn't being charged.
Don't be put off if you don't know Go, it's trivial to build
(all deps are specified in source), you just do

go run

or

go build

.



package main

import (
	"io/ioutil"
	"os/exec"
	"time"
)

func hib() {
	exec.Command("systemctl", "hibernate").Run()
}

func c(e error) {
	if e != nil {
		panic(e)
	}
}

func main() {
	const sysbat = "/sys/class/power_supply/BAT0" // "BAT0" is system specific
	// Battery "percentage", can even be eg. 101
	const cp = sysbat + "/capacity"
	// eg. "Charging\n", "Discharging\n", "Full\n" ...
	const st = sysbat + "/status"

	for {
		//This doesn't make sense because ioutil.ReadFile allocates
		//a bigger slice anyway.
		//r := make([]byte, 0, 4) //3 (possible) digits and the newline

		r, err := ioutil.ReadFile(cp)
		c(err)

		stat, err := ioutil.ReadFile(st)
		c(err)

		digits := len(r) - 1
		if (digits < 2 || digits < 3 &&
			(r[0] == '1' || r[0] == '2')) &&
			string(stat) != "Charging\n" {
			hib()
		}

		time.Sleep(3 * time.Minute)
	}
}

Last edited by Neven (2016-01-25 22:14:09)

Offline

#2 2015-12-02 19:43:15

jasonwryan
Anarchist
From: .nz
Registered: 2009-05-09
Posts: 30,424
Website

Re: Hibernate when battery becomes low: a small Go program

A couple of suggestions:

1. You could make the battery and the percentage variables so people could easily set them at the start of the script
2. You could write a PKGBUILD
3. Comments in English might help tongue


Arch + dwm   •   Mercurial repos  •   Surfraw

Registered Linux User #482438

Offline

Board footer

Powered by FluxBB