Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 14 additions & 10 deletions tcpclient.go
Original file line number Diff line number Diff line change
Expand Up @@ -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))

Expand Down Expand Up @@ -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:])
Expand Down Expand Up @@ -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
Expand Down