5 Commits

Author SHA1 Message Date
8c33fd2a89 Set read deadline correctly 2023-02-25 22:30:31 +01:00
ebdbc92693 Remove a Printf 2023-02-25 15:05:39 +01:00
7b1533b3e6 Improve error messages, close conn on transactionID mismatch. 2023-02-25 13:04:25 +01:00
ce537e1373 Improve error handling 2023-02-25 11:08:53 +01:00
9a92e47837 Fix lockup on io timeout
When the client got a IO timeout the timer were never reset
Adjusting timeouts
2023-02-24 22:59:39 +01:00
2 changed files with 65 additions and 13 deletions

View File

@@ -17,10 +17,11 @@ type Mbclient struct {
conn net.Conn
t *time.Timer
keepAliveDuration time.Duration
timeOut time.Duration
wg sync.WaitGroup
}
func New(Address string, Unit uint8, KeepAlive time.Duration) (*Mbclient, error) {
func New(Address string, Unit uint8, KeepAlive, TimeOut time.Duration) (*Mbclient, error) {
c := new(Mbclient)
c.address = Address
@@ -28,6 +29,7 @@ func New(Address string, Unit uint8, KeepAlive time.Duration) (*Mbclient, error)
c.t = time.NewTimer(0)
<-c.t.C
c.keepAliveDuration = KeepAlive
c.timeOut = TimeOut
return c, nil
}
@@ -35,9 +37,18 @@ func (m *Mbclient) closer() {
<-m.t.C
m.conn.Close()
m.transactionCounter = 0
m.wg.Done()
}
// closeConn can be called when a tcp communication failure require the current
// connection to be closed, it should only be used when closer routine is running
// and the timer is stopped.
func (m *Mbclient) closeConn() {
m.t.Reset(0)
m.wg.Wait()
}
func (m *Mbclient) ReadRegisters(first uint16, numRegs uint16) ([]uint16, error) {
var err error
// If The timer is expired, conn is closed and needs to be reopened
@@ -45,7 +56,7 @@ func (m *Mbclient) ReadRegisters(first uint16, numRegs uint16) ([]uint16, error)
// Wait for closer to exit to mitigate race condiion
// between closer routine and this code path
m.wg.Wait()
m.conn, err = net.Dial("tcp", m.address)
m.conn, err = net.DialTimeout("tcp", m.address, m.timeOut)
if err != nil {
return nil, err
}
@@ -66,34 +77,52 @@ func (m *Mbclient) ReadRegisters(first uint16, numRegs uint16) ([]uint16, error)
req[7] = 3 //FunctionCode
binary.BigEndian.PutUint16(req[8:10], first-1)
binary.BigEndian.PutUint16(req[10:12], numRegs)
m.conn.SetDeadline(time.Now().Add(10 * time.Second))
m.conn.SetDeadline(time.Now().Add(5 * time.Second))
byteswritten, err := m.conn.Write(req)
if err != nil {
m.closeConn()
return nil, err
}
if byteswritten != requestLength {
m.closeConn()
return nil, fmt.Errorf("failed to send request")
}
m.conn.SetDeadline(time.Now().Add(10 * time.Second))
m.conn.SetDeadline(time.Now().Add(m.timeOut))
_, err = io.ReadFull(m.conn, m.header[:])
if err != nil {
m.closeConn()
return nil, err
}
responseHeader.unMarshal(m.header)
expectedDataLength := responseHeader.length - 1
if m.transactionCounter != responseHeader.transactionID {
m.closeConn()
return nil, fmt.Errorf("modbus transaction mismatch %v != %v", m.transactionCounter, responseHeader.transactionID)
}
response := make([]byte, expectedDataLength)
_, err = m.conn.Read(response)
m.conn.SetDeadline(time.Now().Add(m.timeOut))
bytesRead, err := io.ReadFull(m.conn, response)
if err != nil {
m.closeConn()
return nil, err
}
if uint16(bytesRead) != expectedDataLength {
m.t.Reset(m.keepAliveDuration)
return nil, fmt.Errorf("failed to read complete package")
}
err = mbpayload.unMarshal(response)
if mbpayload.functionCode != 3 {
return nil, fmt.Errorf("modbus exception %v", mbpayload.functionCode&0x7F)
m.t.Reset(m.keepAliveDuration)
return nil, fmt.Errorf("modbus exception %v req: %x", mbpayload.functionCode&0x7F, req)
}
if err != nil {
m.t.Reset(m.keepAliveDuration)
return nil, err
}
m.t.Reset(m.keepAliveDuration)
return mbpayload.registers, nil
}
@@ -105,10 +134,6 @@ type mbapHeader struct {
unitIdentifier byte
}
// func (m *mbapHeader) marshalBinary() ([]byte, error) {
// }
func (m *mbapHeader) unMarshal(data [7]byte) error {
m.transactionID = binary.BigEndian.Uint16(data[0:2])
m.protocolIdentifier = binary.BigEndian.Uint16(data[2:4])
@@ -128,7 +153,7 @@ func (d *mbPDU) unMarshal(data []byte) error {
d.functionCode = data[0]
d.length = data[1]
if d.length+2 != uint8(len(data)) {
return fmt.Errorf("lenght mismatch in modbus payload")
return fmt.Errorf("length mismatch in modbus payload")
}
d.registers = make([]uint16, d.length/2)
var n uint8

View File

@@ -8,7 +8,7 @@ import (
)
func TestReadOneRegisterKeepAlive(t *testing.T) {
c, err := New("IAM_248000012514.solver.nu:502", 1, 100*time.Millisecond)
c, err := New("IAM_248000012514.solver.nu:502", 1, 100*time.Millisecond, 5*time.Second)
t.Log("Connect")
assert.NoError(t, err)
for n := 0; n < 5; n++ {
@@ -36,7 +36,7 @@ func TestReadOneRegisterKeepAlive(t *testing.T) {
}
func TestReadOneRegisterShortKeepAlive(t *testing.T) {
c, err := New("IAM_248000012514.solver.nu:502", 1, 10*time.Nanosecond)
c, err := New("IAM_248000012514.solver.nu:502", 1, 10*time.Nanosecond, 5*time.Second)
t.Log("Connect")
assert.NoError(t, err)
for n := 0; n < 5; n++ {
@@ -66,3 +66,30 @@ func TestReadOneRegisterShortKeepAlive(t *testing.T) {
}
time.Sleep(1 * time.Second)
}
func TestReadALot(t *testing.T) {
c, err := New("IAM_248000012514.solver.nu:502", 1, 100*time.Millisecond, 5*time.Second)
t.Log("Connect")
assert.NoError(t, err)
for n := 0; n < 500; n++ {
t.Log(n)
_, err := c.ReadRegisters(12401, 2)
if err != nil {
t.Log(err)
}
_, err = c.ReadRegisters(12102, 2)
if err != nil {
t.Log(err)
}
_, err = c.ReadRegisters(12544, 1)
if err != nil {
t.Log(err)
}
_, err = c.ReadRegisters(12136, 1)
if err != nil {
t.Log(err)
}
}
time.Sleep(200 * time.Millisecond)
}