Skip to content

Instantly share code, notes, and snippets.

@bryanjhv
Created August 1, 2024 02:39
Show Gist options
  • Save bryanjhv/6451005b3d314d6ca03ec73a9bf9400d to your computer and use it in GitHub Desktop.
Save bryanjhv/6451005b3d314d6ca03ec73a9bf9400d to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"maps"
"slices"
"sort"
"github.com/godbus/dbus/v5"
)
const (
intf = "org.freedesktop.UPower.Device"
path = "/org/freedesktop/UPower/devices/battery_BAT0"
meta = "org.freedesktop.DBus.Properties"
)
var props = []string{
"NativePath", // string
"Vendor", // string
"Model", // string
"Serial", // string
"UpdateTime", // uint64
"Type", // uint32
"PowerSupply", // bool
"HasHistory", // bool
"HasStatistics", // bool
"Online", // bool
"Energy", // float64
"EnergyEmpty", // float64
"EnergyFull", // float64
"EnergyFullDesign", // float64
"EnergyRate", // float64
"Voltage", // float64
"ChargeCycles", // int32
"Luminosity", // float64
"TimeToEmpty", // int64
"TimeToFull", // int64
"Percentage", // float64
"Temperature", // float64
"IsPresent", // bool
"State", // uint32
"IsRechargeable", // bool
"Capacity", // float64
"Technology", // uint32
"WarningLevel", // uint32
"BatteryLevel", // uint32
"IconName", // string
}
func main() {
bus := must(dbus.ConnectSystemBus())
defer bus.Close()
var bat map[string]dbus.Variant
obj := bus.Object(intf[:22], path)
throw(obj.Call(meta+".GetAll", 0, intf).Store(&bat))
show(bat)
throw(bus.AddMatchSignal(
dbus.WithMatchInterface(meta),
dbus.WithMatchMember("PropertiesChanged"),
dbus.WithMatchObjectPath(path),
dbus.WithMatchArg(0, intf),
))
ch := make(chan *dbus.Signal, 10)
bus.Signal(ch)
for sig := range ch {
diff := sig.Body[1].(map[string]dbus.Variant)
maps.Copy(bat, diff)
show(diff)
}
}
func show(dic map[string]dbus.Variant) {
var keys []string
for key, _ := range dic {
if slices.Contains(props, key) {
keys = append(keys, key)
}
}
sort.Strings(keys)
for _, key := range keys {
fmt.Printf("%s = %v\n", key, dic[key].Value())
}
fmt.Println()
}
func throw(err error) {
if err != nil {
panic(err)
}
}
func must[T any](val T, err error) T {
throw(err)
return val
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment