mirror of
https://github.com/jimeh/macos-battery-exporter.git
synced 2026-02-19 01:16:40 +00:00
fix(battery): handle no batteries being present
This commit is contained in:
@@ -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
|
||||
|
||||
@@ -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}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user