Skip to content

Commit

Permalink
feat(linux): ✨ don't send swap sensors if there is no swap enabled
Browse files Browse the repository at this point in the history
Only send swap sensors when swap is enabled. Will stop and start sending swap sensors as swap is disabled/enabled.
  • Loading branch information
joshuar committed Apr 29, 2024
1 parent e1ce86b commit f8508e2
Showing 1 changed file with 37 additions and 24 deletions.
61 changes: 37 additions & 24 deletions internal/linux/mem/memUsage.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,23 +11,14 @@ import (

"github.com/rs/zerolog/log"
"github.com/shirou/gopsutil/v3/mem"
"github.com/sourcegraph/conc/pool"

"github.com/joshuar/go-hass-agent/internal/device/helpers"
"github.com/joshuar/go-hass-agent/internal/hass/sensor"
"github.com/joshuar/go-hass-agent/internal/hass/sensor/types"
"github.com/joshuar/go-hass-agent/internal/linux"
)

var stats = []linux.SensorTypeValue{
linux.SensorMemTotal,
linux.SensorMemAvail,
linux.SensorMemUsed,
linux.SensorMemPc,
linux.SensorSwapTotal,
linux.SensorSwapFree,
linux.SensorSwapPc,
}

type memorySensor struct {
linux.Sensor
}
Expand All @@ -43,7 +34,7 @@ func (s *memorySensor) Attributes() any {
}

func Updater(ctx context.Context) chan sensor.Details {
sensorCh := make(chan sensor.Details, 5)
sensorCh := make(chan sensor.Details)
sendMemStats := func(_ time.Duration) {
var memDetails *mem.VirtualMemoryStat
var err error
Expand All @@ -52,21 +43,43 @@ func Updater(ctx context.Context) chan sensor.Details {
Msg("Problem fetching memory stats.")
return
}

// Memory stats to track as sensors.
stats := []linux.SensorTypeValue{
linux.SensorMemTotal,
linux.SensorMemAvail,
linux.SensorMemUsed,
linux.SensorMemPc,
}
// If this system has swap enabled, track swap stats as sensors as well.
if memDetails.SwapTotal > 0 {
stats = append(stats,
linux.SensorSwapTotal,
linux.SensorSwapFree,
linux.SensorSwapPc,
)
}

p := pool.New()

for _, stat := range stats {
value, unit, deviceClass, stateClass := parseSensorType(stat, memDetails)
state := &memorySensor{
linux.Sensor{
Value: value,
SensorTypeValue: stat,
IconString: "mdi:memory",
UnitsString: unit,
SensorSrc: linux.DataSrcProcfs,
DeviceClassValue: deviceClass,
StateClassValue: stateClass,
},
}
sensorCh <- state
p.Go(func() {
value, unit, deviceClass, stateClass := parseSensorType(stat, memDetails)
state := &memorySensor{
linux.Sensor{
Value: value,
SensorTypeValue: stat,
IconString: "mdi:memory",
UnitsString: unit,
SensorSrc: linux.DataSrcProcfs,
DeviceClassValue: deviceClass,
StateClassValue: stateClass,
},
}
sensorCh <- state
})
}
p.Wait()
}

go helpers.PollSensors(ctx, sendMemStats, time.Minute, time.Second*5)
Expand Down

0 comments on commit f8508e2

Please sign in to comment.