4 Commits

5 changed files with 269 additions and 113 deletions

View File

@@ -793,7 +793,7 @@ func (mc *ModbusClient) WriteRegisterWithRes(addr uint16, value uint16) (bytes [
req.payload = append(req.payload, uint16ToBytes(mc.endianness, value)...)
// run the request across the transport and wait for a response
res, err = mc.executeRequest(req)
res, err = mc.executeRequestWithRes(req)
if err != nil {
return
}
@@ -1188,15 +1188,9 @@ func (mc *ModbusClient) readRegistersWithFunctionCode(addr uint16, quantity uint
unitId: mc.unitId,
}
// if functionCode != fcCustomize {
// err = ErrUnexpectedParameters
// mc.logger.Errorf("unexpected function code (%d)", functionCode)
// return
// }
if functionCode == 0 {
if functionCode != fcCustomize {
err = ErrUnexpectedParameters
mc.logger.Errorf("unexpected register type (%v)", functionCode)
mc.logger.Errorf("unexpected function code (%d)", functionCode)
return
}
@@ -1208,9 +1202,10 @@ func (mc *ModbusClient) readRegistersWithFunctionCode(addr uint16, quantity uint
return
}
if quantity > 1024 {
// 16 * 16 * 40
if quantity > 10240 {
err = ErrUnexpectedParameters
mc.logger.Error("quantity of registers exceeds 1024")
mc.logger.Error("quantity of registers exceeds 10240")
return
}
@@ -1406,3 +1401,29 @@ func (mc *ModbusClient) executeRequest(req *pdu) (res *pdu, err error) {
return
}
func (mc *ModbusClient) executeRequestWithRes(req *pdu) (res *pdu, err error) {
// send the request over the wire, wait for and decode the response
res, err = mc.transport.ExecuteRequestWithRes(req)
if err != nil {
// map i/o timeouts to ErrRequestTimedOut
if os.IsTimeout(err) {
err = ErrRequestTimedOut
}
return
}
// make sure the source unit id matches that of the request
if (res.functionCode&0x80) == 0x00 && res.unitId != req.unitId {
err = ErrBadUnitId
return
}
// accept errors from gateway devices (using special unit id #255)
if (res.functionCode&0x80) == 0x80 &&
(res.unitId != req.unitId && res.unitId != 0xff) {
err = ErrBadUnitId
return
}
return
}

View File

@@ -41,7 +41,7 @@ const (
fcWriteFileRecord uint8 = 0x15
// customize
fcCustomize uint8 = 0x29
fcCustomize uint8 = 0x41
// exception codes
exIllegalFunction uint8 = 0x01

View File

@@ -21,10 +21,10 @@ type rtuTransport struct {
}
type rtuLink interface {
Close() (error)
Close() error
Read([]byte) (int, error)
Write([]byte) (int, error)
SetDeadline(time.Time) (error)
SetDeadline(time.Time) error
}
// Returns a new RTU transport.
@@ -109,6 +109,59 @@ func (rt *rtuTransport) ExecuteRequest(req *pdu) (res *pdu, err error) {
return
}
func (rt *rtuTransport) ExecuteRequestWithRes(req *pdu) (res *pdu, err error) {
var ts time.Time
var t time.Duration
var n int
// set an i/o deadline on the link
err = rt.link.SetDeadline(time.Now().Add(rt.timeout))
if err != nil {
return
}
// if the line was active less than 3.5 char times ago,
// let t3.5 expire before transmitting
t = time.Since(rt.lastActivity.Add(rt.t35))
if t < 0 {
time.Sleep(t * (-1))
}
ts = time.Now()
// build an RTU ADU out of the request object and
// send the final ADU+CRC on the wire
n, err = rt.link.Write(rt.assembleRTUFrame(req))
if err != nil {
return
}
// estimate how long the serial line was busy for.
// note that on most platforms, Write() will be buffered and return
// immediately rather than block until the buffer is drained
rt.lastActivity = ts.Add(time.Duration(n) * rt.t1)
// observe inter-frame delays
time.Sleep(rt.lastActivity.Add(rt.t35).Sub(time.Now()))
// read the response back from the wire
res, err = rt.readRTUFrameWithRes()
if err == ErrBadCRC || err == ErrProtocolError || err == ErrShortFrame {
// wait for and flush any data coming off the link to allow
// devices to re-sync
time.Sleep(time.Duration(maxRTUFrameLength) * rt.t1)
discard(rt.link)
}
// mark the time if we heard anything back
if err != ErrRequestTimedOut {
rt.lastActivity = time.Now()
}
return
}
// Reads a request from the rtu link.
func (rt *rtuTransport) ReadRequest() (req *pdu, err error) {
// reading requests from RTU links is currently unsupported
@@ -163,12 +216,12 @@ func (rt *rtuTransport) readRTUFrame() (res *pdu, err error) {
bytesNeeded += 2
// never read more than the max allowed frame length
if byteCount + bytesNeeded > maxRTUFrameLength {
if byteCount+bytesNeeded > maxRTUFrameLength {
err = ErrProtocolError
return
}
byteCount, err = io.ReadFull(rt.link, rxbuf[3:3 + bytesNeeded])
byteCount, err = io.ReadFull(rt.link, rxbuf[3:3+bytesNeeded])
if err != nil && err != io.ErrUnexpectedEOF {
return
}
@@ -180,10 +233,10 @@ func (rt *rtuTransport) readRTUFrame() (res *pdu, err error) {
// compute the CRC on the entire frame, excluding the CRC
crc.init()
crc.add(rxbuf[0:3 + bytesNeeded - 2])
crc.add(rxbuf[0 : 3+bytesNeeded-2])
// compare CRC values
if !crc.isEqual(rxbuf[3 + bytesNeeded - 2], rxbuf[3 + bytesNeeded - 1]) {
if !crc.isEqual(rxbuf[3+bytesNeeded-2], rxbuf[3+bytesNeeded-1]) {
err = ErrBadCRC
return
}
@@ -192,7 +245,76 @@ func (rt *rtuTransport) readRTUFrame() (res *pdu, err error) {
unitId: rxbuf[0],
functionCode: rxbuf[1],
// pass the byte count + trailing data as payload, withtout the CRC
payload: rxbuf[2:3 + bytesNeeded - 2],
payload: rxbuf[2 : 3+bytesNeeded-2],
}
return
}
func (rt *rtuTransport) readRTUFrameWithRes() (res *pdu, err error) {
var rxbuf []byte
var byteCount int
var bytesNeeded int
var crc crc
rxbuf = make([]byte, 4096)
// read the serial ADU header: unit id (1 byte), function code (1 byte) and
// PDU length/exception code (1 byte)
byteCount, err = io.ReadFull(rt.link, rxbuf[0:3])
if (byteCount > 0 || err == nil) && byteCount != 3 {
err = ErrShortFrame
return
}
if err != nil && err != io.ErrUnexpectedEOF {
return
}
// figure out how many further bytes to read
bytesNeeded, err = expectedResponseLenth(uint8(rxbuf[1]), uint8(rxbuf[2]))
if err != nil {
return
}
// we need to read 2 additional bytes of CRC after the payload
bytesNeeded += 2
// never read more than the max allowed frame length
if byteCount+bytesNeeded > maxRTUFrameLength {
err = ErrProtocolError
return
}
byteCount, err = io.ReadFull(rt.link, rxbuf[3:3+bytesNeeded])
if err != nil && err != io.ErrUnexpectedEOF {
return
}
if byteCount != bytesNeeded {
rt.logger.Warningf("expected %v bytes, received %v", bytesNeeded, byteCount)
err = ErrShortFrame
return
}
// compute the CRC on the entire frame, excluding the CRC
crc.init()
crc.add(rxbuf[0 : 3+bytesNeeded-2])
// compare CRC values
if !crc.isEqual(rxbuf[3+bytesNeeded-2], rxbuf[3+bytesNeeded-1]) {
err = ErrBadCRC
return
}
_, err = io.ReadFull(rt.link, rxbuf[3+bytesNeeded:])
if err != nil && err != io.ErrUnexpectedEOF {
return
}
res = &pdu{
unitId: rxbuf[0],
functionCode: rxbuf[1],
// pass the byte count + trailing data as payload, withtout the CRC
payload: rxbuf[3+bytesNeeded:],
}
return
@@ -222,12 +344,16 @@ func expectedResponseLenth(responseCode uint8, responseLength uint8) (byteCount
case fcReadHoldingRegisters,
fcReadInputRegisters,
fcReadCoils,
fcReadDiscreteInputs: byteCount = int(responseLength)
fcReadDiscreteInputs,
0x41:
byteCount = int(responseLength)
case fcWriteSingleRegister,
fcWriteMultipleRegisters,
fcWriteSingleCoil,
fcWriteMultipleCoils: byteCount = 3
case fcMaskWriteRegister: byteCount = 5
fcWriteMultipleCoils:
byteCount = 3
case fcMaskWriteRegister:
byteCount = 5
case fcReadHoldingRegisters | 0x80,
fcReadInputRegisters | 0x80,
fcReadCoils | 0x80,
@@ -236,8 +362,11 @@ func expectedResponseLenth(responseCode uint8, responseLength uint8) (byteCount
fcWriteMultipleRegisters | 0x80,
fcWriteSingleCoil | 0x80,
fcWriteMultipleCoils | 0x80,
fcMaskWriteRegister | 0x80: byteCount = 0
default: err = ErrProtocolError
fcMaskWriteRegister | 0x80,
0x41 | 0x80:
byteCount = 0
default:
err = ErrProtocolError
}
return

View File

@@ -59,6 +59,10 @@ func (tt *tcpTransport) ExecuteRequest(req *pdu) (res *pdu, err error) {
return
}
func (tt *tcpTransport) ExecuteRequestWithRes(req *pdu) (res *pdu, err error) {
return nil, nil
}
// Reads a request from the socket.
func (tt *tcpTransport) ReadRequest() (req *pdu, err error) {
var txnId uint16
@@ -111,7 +115,7 @@ func (tt *tcpTransport) readResponse() (res *pdu, err error) {
// ignore unknown transaction identifiers
if tt.lastTxnId != txnId {
tt.logger.Warningf("received unexpected transaction id " +
tt.logger.Warningf("received unexpected transaction id "+
"(expected 0x%04x, received 0x%04x)",
tt.lastTxnId, txnId)
continue
@@ -151,7 +155,7 @@ func (tt *tcpTransport) readMBAPFrame() (p *pdu, txnId uint16, err error) {
bytesNeeded--
// never read more than the max allowed frame length
if bytesNeeded + mbapHeaderLength > maxTCPFrameLength {
if bytesNeeded+mbapHeaderLength > maxTCPFrameLength {
err = ErrProtocolError
return
}
@@ -193,7 +197,7 @@ func (tt *tcpTransport) assembleMBAPFrame(txnId uint16, p *pdu) (payload []byte)
// protocol identifier (always 0x0000)
payload = append(payload, 0x00, 0x00)
// length (covers unit identifier + function code + payload fields)
payload = append(payload, uint16ToBytes(BIG_ENDIAN, uint16(2 + len(p.payload)))...)
payload = append(payload, uint16ToBytes(BIG_ENDIAN, uint16(2+len(p.payload)))...)
// unit identifier
payload = append(payload, p.unitId)
// function code

View File

@@ -1,6 +1,7 @@
package modbus
type transportType uint
const (
modbusRTU transportType = 1
modbusRTUOverTCP transportType = 2
@@ -11,8 +12,9 @@ const (
)
type transport interface {
Close() (error)
Close() error
ExecuteRequest(*pdu) (*pdu, error)
ExecuteRequestWithRes(*pdu) (*pdu, error)
ReadRequest() (*pdu, error)
WriteResponse(*pdu) (error)
WriteResponse(*pdu) error
}