diff --git a/tcpclient.go b/tcpclient.go index 4e53c73..53abce5 100644 --- a/tcpclient.go +++ b/tcpclient.go @@ -56,12 +56,13 @@ type tcpPackager struct { } // Encode adds modbus application protocol header: -// Transaction identifier: 2 bytes -// Protocol identifier: 2 bytes -// Length: 2 bytes -// Unit identifier: 1 byte -// Function code: 1 byte -// Data: n bytes +// +// Transaction identifier: 2 bytes +// Protocol identifier: 2 bytes +// Length: 2 bytes +// Unit identifier: 1 byte +// Function code: 1 byte +// Data: n bytes func (mb *tcpPackager) Encode(pdu *ProtocolDataUnit) (adu []byte, err error) { adu = make([]byte, tcpHeaderSize+1+len(pdu.Data)) @@ -107,10 +108,11 @@ func (mb *tcpPackager) Verify(aduRequest []byte, aduResponse []byte) (err error) } // Decode extracts PDU from TCP frame: -// Transaction identifier: 2 bytes -// Protocol identifier: 2 bytes -// Length: 2 bytes -// Unit identifier: 1 byte +// +// Transaction identifier: 2 bytes +// Protocol identifier: 2 bytes +// Length: 2 bytes +// Unit identifier: 1 byte func (mb *tcpPackager) Decode(adu []byte) (pdu *ProtocolDataUnit, err error) { // Read length value in the header length := binary.BigEndian.Uint16(adu[4:]) @@ -167,6 +169,8 @@ func (mb *tcpTransporter) Send(aduRequest []byte) (aduResponse []byte, err error // Send data mb.logf("modbus: sending % x", aduRequest) if _, err = mb.conn.Write(aduRequest); err != nil { + // Once an error occurs, set conn nil vai close() for the next request to reconnect + mb.close() return } // Read header first