55 lines
1.1 KiB
Go
55 lines
1.1 KiB
Go
package monitor
|
|
|
|
import (
|
|
"sync"
|
|
"time"
|
|
|
|
"lan-ups/internal/nut"
|
|
)
|
|
|
|
type Snapshot struct {
|
|
Source string `json:"source"`
|
|
Health string `json:"health"`
|
|
LastOK *time.Time `json:"lastOK,omitempty"`
|
|
Values map[string]string `json:"values,omitempty"`
|
|
Error string `json:"error,omitempty"`
|
|
}
|
|
|
|
type Monitor struct {
|
|
address string
|
|
name string
|
|
mu sync.RWMutex
|
|
state Snapshot
|
|
}
|
|
|
|
func New(address, name string) *Monitor {
|
|
return &Monitor{
|
|
address: address,
|
|
name: name,
|
|
state: Snapshot{Source: name + "@" + address, Health: "waiting"},
|
|
}
|
|
}
|
|
|
|
func (m *Monitor) Run(interval time.Duration) {
|
|
for {
|
|
values, err := nut.ReadUPS(m.address, m.name, 2*time.Second)
|
|
m.mu.Lock()
|
|
if err != nil {
|
|
m.state.Health, m.state.Error = "stale", err.Error()
|
|
} else {
|
|
now := time.Now()
|
|
m.state.Health, m.state.Error = "live", ""
|
|
m.state.LastOK, m.state.Values = &now, values
|
|
}
|
|
m.mu.Unlock()
|
|
time.Sleep(interval)
|
|
}
|
|
}
|
|
|
|
// Snapshot returns the current state. Its values must be treated as read-only.
|
|
func (m *Monitor) Snapshot() Snapshot {
|
|
m.mu.RLock()
|
|
defer m.mu.RUnlock()
|
|
return m.state
|
|
}
|