fix(battery): handle no batteries being present

This commit is contained in:
2023-12-16 01:14:56 +00:00
parent 8077357e17
commit a3dc259e3b
2 changed files with 24 additions and 1 deletions

View File

@@ -3,6 +3,7 @@
package battery
import (
"bytes"
"os/exec"
"howett.net/plist"
@@ -39,6 +40,11 @@ func getAllRaw() ([]*batteryRaw, error) {
}
batteries := []*batteryRaw{}
if len(bytes.TrimSpace(b)) == 0 {
return batteries, nil
}
_, err = plist.Unmarshal(b, &batteries)
if err != nil {
return nil, err

View File

@@ -17,7 +17,9 @@ const (
)
type Collector struct {
descInfo *prometheus.Desc
descInfo *prometheus.Desc
descBatteryCount *prometheus.Desc
descBatteryCellDisconnectCount *prometheus.Desc
descChargeRateAmps *prometheus.Desc
descChargeRateWatts *prometheus.Desc
@@ -47,6 +49,14 @@ func NewCollector(namespace string) *Collector {
[]string{serialLabel, deviceNameLabel, builtInLabel},
nil,
),
descBatteryCount: prometheus.NewDesc(
prometheus.BuildFQName(
namespace, "battery", "count",
),
"Total number of batteries.",
nil,
nil,
),
descBatteryCellDisconnectCount: prometheus.NewDesc(
prometheus.BuildFQName(
namespace, "battery", "cell_disconnect_count",
@@ -191,6 +201,7 @@ func NewCollector(namespace string) *Collector {
func (c *Collector) Describe(ch chan<- *prometheus.Desc) {
ch <- c.descInfo
ch <- c.descBatteryCount
ch <- c.descBatteryCellDisconnectCount
ch <- c.descChargeRateAmps
ch <- c.descChargeRateWatts
@@ -220,6 +231,12 @@ func (c *Collector) Collect(ch chan<- prometheus.Metric) {
return
}
ch <- prometheus.MustNewConstMetric(
c.descBatteryCount,
prometheus.GaugeValue,
float64(len(batteries)),
)
for _, battery := range batteries {
labels := []string{battery.Serial}