Files
devplacepy/nodes/client/battery_linux.go
T

54 lines
1.1 KiB
Go
Raw Normal View History

//go:build linux
package main
import (
"os"
"path/filepath"
"strings"
)
const powerSupplyRoot = "/sys/class/power_supply"
func systemBattery() (bool, error) {
return sysfsOnBattery(powerSupplyRoot)
}
func readSupplyField(dir, name string) string {
data, err := os.ReadFile(filepath.Join(dir, name))
if err != nil {
return ""
}
return strings.TrimSpace(string(data))
}
func isMainsType(kind string) bool {
return kind == "Mains" || kind == "ADP" || strings.HasPrefix(kind, "USB")
}
func sysfsOnBattery(root string) (bool, error) {
entries, err := os.ReadDir(root)
if err != nil {
return false, err
}
discharging := false
for _, entry := range entries {
dir := filepath.Join(root, entry.Name())
if readSupplyField(dir, "scope") == "Device" {
continue
}
kind := readSupplyField(dir, "type")
switch {
case kind == "Battery":
if readSupplyField(dir, "status") == "Discharging" {
discharging = true
}
case isMainsType(kind):
if readSupplyField(dir, "online") == "1" {
return false, nil
}
}
}
return discharging, nil
}