RWMutex; update lastValues all at once

This commit is contained in:
Josh Deprez 2023-01-21 20:48:47 +11:00
parent fa7b18bc2d
commit 8408517b7d
Signed by: josh
SSH key fingerprint: SHA256:zZji7w1Ilh2RuUpbQcqkLPrqmRwpiCSycbF2EfKm6Kw
2 changed files with 18 additions and 11 deletions

21
main.go
View file

@ -42,7 +42,7 @@ var (
scrapeInterval = flag.Duration("scrape-interval", 15*time.Second, "Period of modbus scraping loop")
promHandler = promhttp.Handler()
scrapeMu sync.Mutex
scrapeMu sync.RWMutex
lastScrape time.Time
lastValues = make(map[uint16]float64)
@ -128,7 +128,7 @@ func dialInverter() (*sungrowConn, error) {
}
// Called under scrapeMu.
func readRegs(client modbus.Client, start, qty uint16) error {
func readRegs(vals map[uint16]float64, client modbus.Client, start, qty uint16) error {
data, err := client.ReadInputRegisters(start, qty)
if err != nil {
return fmt.Errorf("read input registers %d-%d: %v", start+1, start+qty, err)
@ -149,7 +149,7 @@ func readRegs(client modbus.Client, start, qty uint16) error {
return fmt.Errorf("parse input register data at %d: %v", addr, err)
}
//fmt.Printf("%s: %v %s\n", reg.name, val, reg.unit)
lastValues[addr] = val
vals[addr] = val
}
return nil
}
@ -168,17 +168,20 @@ func scrape() error {
client := modbus.NewClient(handler)
vals := make(map[uint16]float64)
start := time.Now()
scrapeStart.SetToCurrentTime()
if err := readRegs(client, 5000, 50); err != nil {
if err := readRegs(vals, client, 5000, 50); err != nil {
return err
}
if err := readRegs(client, 5050, 50); err != nil {
if err := readRegs(vals, client, 5050, 50); err != nil {
return err
}
if err := readRegs(client, 5100, 50); err != nil {
if err := readRegs(vals, client, 5100, 50); err != nil {
return err
}
lastValues = vals
scrapeEnd.SetToCurrentTime()
lastScrape = time.Now()
scrapeDuration.Set(time.Since(start).Seconds())
@ -223,7 +226,11 @@ func main() {
Name: reg.name,
Help: fmt.Sprintf("addr: %d, unit: %s", addr, reg.unit),
},
func() float64 { return lastValues[addr] },
func() float64 {
scrapeMu.RLock()
defer scrapeMu.RUnlock()
return lastValues[addr]
},
)
}

View file

@ -75,7 +75,7 @@ var sungrowInputRegs = map[uint16]*register{
5148: {"frequency_2", frequency2, 0.01, "Hz"},
}
var errSkippableRead = errors.New("skip read")
var errSkippableRead = errors.New("skippable misread")
func frequency2(data []byte) (float64, error) {
n := binary.BigEndian.Uint16(data)
@ -83,9 +83,9 @@ func frequency2(data []byte) (float64, error) {
// probably a misread
return 0, fmt.Errorf("likely misread: frequency_2 read %v", n)
}
if n == 100 {
// this translates as 1 Hz, which is unlikely
return 0, fmt.Errorf("%w: frequency_2 is 1.00Hz", errSkippableRead)
if n <= 100 {
// 100 translates as 1 Hz, which is... unlikely
return 0, fmt.Errorf("%w: frequency_2 is %d", errSkippableRead, n)
}
return float64(n), nil
}