update HasReadableBattery to check all batteries

This commit is contained in:
henrygd
2025-10-25 14:06:25 -04:00
parent d608cf0955
commit 1dee63a0eb

View File

@@ -5,8 +5,6 @@ package battery
import ( import (
"errors" "errors"
"fmt"
"os"
"log/slog" "log/slog"
"github.com/distatus/battery" "github.com/distatus/battery"
@@ -21,22 +19,20 @@ func HasReadableBattery() bool {
return systemHasBattery return systemHasBattery
} }
haveCheckedBattery = true haveCheckedBattery = true
batteries,err := battery.GetAll() batteries, err := battery.GetAll()
if err != nil { for _, bat := range batteries {
// even if there's errors getting some batteries, the system if bat.Full > 0 {
// definitely has a battery if the list is not empty. systemHasBattery = true
// This list will include everything `battery` can find, break
// including things like bluetooth devices. }
fmt.Fprintln(os.Stderr, err)
} }
systemHasBattery = len(batteries) > 0
if !systemHasBattery { if !systemHasBattery {
slog.Debug("No battery found", "err", err) slog.Debug("No battery found", "err", err)
} }
return systemHasBattery return systemHasBattery
} }
// GetBatteryStats returns the current battery percent and charge state // GetBatteryStats returns the current battery percent and charge state
// percent = (current charge of all batteries) / (sum of designed/full capacity of all batteries) // percent = (current charge of all batteries) / (sum of designed/full capacity of all batteries)
func GetBatteryStats() (batteryPercent uint8, batteryState uint8, err error) { func GetBatteryStats() (batteryPercent uint8, batteryState uint8, err error) {
if !HasReadableBattery() { if !HasReadableBattery() {
@@ -58,7 +54,7 @@ func GetBatteryStats() (batteryPercent uint8, batteryState uint8, err error) {
// if there were some errors, like missing data, skip it // if there were some errors, like missing data, skip it
continue continue
} }
if bat.Full == 0 { if bat.Full == 0 {
// skip batteries with no capacity. Charge is unlikely to ever be zero, but // skip batteries with no capacity. Charge is unlikely to ever be zero, but
// we can't guarantee that, so don't skip based on charge. // we can't guarantee that, so don't skip based on charge.
continue continue