diff --git a/main.go b/main.go index 392b0fc..2fa9b2a 100644 --- a/main.go +++ b/main.go @@ -74,7 +74,7 @@ func statusHandler(w http.ResponseWriter, r *http.Request) { } func readRegs(client modbus.Client, start, qty uint16) { - data, err := client.ReadInputRegisters(5000, 50) + data, err := client.ReadInputRegisters(start, qty) if err != nil { die("Couldn't read input registers %d-%d: %v", start+1, start+qty, err) } diff --git a/sungrow.go b/sungrow.go index e02f6f9..7f0f060 100644 --- a/sungrow.go +++ b/sungrow.go @@ -44,7 +44,7 @@ type sungrowConn struct { block cipher.Block fifo *bytes.Buffer - mu sync.Mutex + mu sync.RWMutex txid uint16 } @@ -54,8 +54,8 @@ func (c *sungrowConn) Write(msg []byte) (int, error) { } c.mu.Lock() + defer c.mu.Unlock() c.txid = binary.BigEndian.Uint16(msg[:2]) - c.mu.Unlock() c.fifo.Truncate(0) @@ -83,6 +83,8 @@ func (c *sungrowConn) Read(out []byte) (int, error) { } if c.fifo.Len() > 0 { + c.mu.RLock() + defer c.mu.RUnlock() return c.fifo.Read(out) } // 4-byte header describes how much to read @@ -101,9 +103,9 @@ func (c *sungrowConn) Read(out []byte) (int, error) { for cp := pkt; len(cp) > 0; cp = cp[bs:] { c.block.Decrypt(cp, cp) } - c.mu.Lock() + c.mu.RLock() + defer c.mu.RUnlock() binary.BigEndian.PutUint16(pkt, c.txid) - c.mu.Unlock() c.fifo.Write(pkt[:pktlen]) return c.fifo.Read(out) }