Compare commits
3 Commits
64d006461f
...
v0.0.6
| Author | SHA1 | Date | |
|---|---|---|---|
| 72429c08a3 | |||
| 1c4d54df71 | |||
| 8318daf99b |
81
client.go
81
client.go
@@ -793,7 +793,7 @@ func (mc *ModbusClient) WriteRegisterWithRes(addr uint16, value uint16) (bytes [
|
|||||||
req.payload = append(req.payload, uint16ToBytes(mc.endianness, value)...)
|
req.payload = append(req.payload, uint16ToBytes(mc.endianness, value)...)
|
||||||
|
|
||||||
// run the request across the transport and wait for a response
|
// run the request across the transport and wait for a response
|
||||||
res, err = mc.executeRequest(req)
|
res, err = mc.executeRequestWithRes(req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -801,17 +801,27 @@ func (mc *ModbusClient) WriteRegisterWithRes(addr uint16, value uint16) (bytes [
|
|||||||
// validate the response code
|
// validate the response code
|
||||||
switch {
|
switch {
|
||||||
case res.functionCode == req.functionCode:
|
case res.functionCode == req.functionCode:
|
||||||
// expect 4 bytes (2 byte of address + 2 bytes of value)
|
// expect at least 4 bytes (2 byte of address + 2 bytes of value)
|
||||||
if len(res.payload) != 4 ||
|
// 后面可能还有自定义数据
|
||||||
|
if len(res.payload) < 4 {
|
||||||
|
err = ErrProtocolError
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
// bytes 1-2 should be the register address
|
// bytes 1-2 should be the register address
|
||||||
bytesToUint16(BIG_ENDIAN, res.payload[0:2]) != addr ||
|
if bytesToUint16(BIG_ENDIAN, res.payload[0:2]) != addr ||
|
||||||
// bytes 3-4 should be the value
|
// bytes 3-4 should be the value
|
||||||
bytesToUint16(mc.endianness, res.payload[2:4]) != value {
|
bytesToUint16(mc.endianness, res.payload[2:4]) != value {
|
||||||
err = ErrProtocolError
|
err = ErrProtocolError
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
bytes = req.payload[1:]
|
// 返回自定义数据(第4字节之后的数据)
|
||||||
|
if len(res.payload) > 4 {
|
||||||
|
bytes = res.payload[4:]
|
||||||
|
} else {
|
||||||
|
bytes = []byte{} // 没有自定义数据,返回空切片
|
||||||
|
}
|
||||||
|
|
||||||
case res.functionCode == (req.functionCode | 0x80):
|
case res.functionCode == (req.functionCode | 0x80):
|
||||||
if len(res.payload) != 1 {
|
if len(res.payload) != 1 {
|
||||||
@@ -1205,7 +1215,7 @@ func (mc *ModbusClient) readRegistersWithFunctionCode(addr uint16, quantity uint
|
|||||||
// 16 * 16 * 40
|
// 16 * 16 * 40
|
||||||
if quantity > 10240 {
|
if quantity > 10240 {
|
||||||
err = ErrUnexpectedParameters
|
err = ErrUnexpectedParameters
|
||||||
mc.logger.Error("quantity of registers exceeds 1024")
|
mc.logger.Error("quantity of registers exceeds 10240")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1261,6 +1271,38 @@ func (mc *ModbusClient) readRegistersWithFunctionCode(addr uint16, quantity uint
|
|||||||
|
|
||||||
switch {
|
switch {
|
||||||
case res.functionCode == req.functionCode:
|
case res.functionCode == req.functionCode:
|
||||||
|
// For custom function code 0x41, the payload format is:
|
||||||
|
// [起始地址(2字节)] [字节数(2字节)] [数据...]
|
||||||
|
if functionCode == fcCustomize {
|
||||||
|
// validate minimum payload length (start address 2 bytes + byte count 2 bytes)
|
||||||
|
if len(res.payload) < 4 {
|
||||||
|
err = ErrProtocolError
|
||||||
|
mc.logger.Errorf("payload too short for custom function code: %d bytes", len(res.payload))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// extract byte count from payload (bytes 2-3, big endian)
|
||||||
|
byteCount := bytesToUint16(BIG_ENDIAN, res.payload[2:4])
|
||||||
|
|
||||||
|
// validate payload length matches expected data length
|
||||||
|
expectedLength := 4 + int(byteCount) // start address (2) + byte count (2) + data
|
||||||
|
if len(res.payload) != expectedLength {
|
||||||
|
err = ErrProtocolError
|
||||||
|
mc.logger.Errorf("payload length mismatch: expected %d, got %d", expectedLength, len(res.payload))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// validate byte count matches requested quantity
|
||||||
|
if byteCount != 2*quantity {
|
||||||
|
err = ErrProtocolError
|
||||||
|
mc.logger.Errorf("byte count mismatch: expected %d, got %d", 2*quantity, byteCount)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// extract only the data part (skip start address and byte count)
|
||||||
|
bytes = res.payload[4:]
|
||||||
|
} else {
|
||||||
|
// standard modbus protocol handling
|
||||||
// make sure the payload length is what we expect
|
// make sure the payload length is what we expect
|
||||||
// (1 byte of length + 2 bytes per register)
|
// (1 byte of length + 2 bytes per register)
|
||||||
// if len(res.payload) != 1+2*int(quantity) {
|
// if len(res.payload) != 1+2*int(quantity) {
|
||||||
@@ -1277,6 +1319,7 @@ func (mc *ModbusClient) readRegistersWithFunctionCode(addr uint16, quantity uint
|
|||||||
|
|
||||||
// remove the byte count field from the returned slice
|
// remove the byte count field from the returned slice
|
||||||
bytes = res.payload[1:]
|
bytes = res.payload[1:]
|
||||||
|
}
|
||||||
|
|
||||||
case res.functionCode == (req.functionCode | 0x80):
|
case res.functionCode == (req.functionCode | 0x80):
|
||||||
if len(res.payload) != 1 {
|
if len(res.payload) != 1 {
|
||||||
@@ -1401,3 +1444,29 @@ func (mc *ModbusClient) executeRequest(req *pdu) (res *pdu, err error) {
|
|||||||
|
|
||||||
return
|
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
|
||||||
|
}
|
||||||
|
|||||||
258
rtu_transport.go
258
rtu_transport.go
@@ -4,6 +4,7 @@ import (
|
|||||||
"fmt"
|
"fmt"
|
||||||
"io"
|
"io"
|
||||||
"log"
|
"log"
|
||||||
|
"os"
|
||||||
"time"
|
"time"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -109,6 +110,59 @@ func (rt *rtuTransport) ExecuteRequest(req *pdu) (res *pdu, err error) {
|
|||||||
return
|
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.
|
// Reads a request from the rtu link.
|
||||||
func (rt *rtuTransport) ReadRequest() (req *pdu, err error) {
|
func (rt *rtuTransport) ReadRequest() (req *pdu, err error) {
|
||||||
// reading requests from RTU links is currently unsupported
|
// reading requests from RTU links is currently unsupported
|
||||||
@@ -139,8 +193,140 @@ func (rt *rtuTransport) readRTUFrame() (res *pdu, err error) {
|
|||||||
var byteCount int
|
var byteCount int
|
||||||
var bytesNeeded int
|
var bytesNeeded int
|
||||||
var crc crc
|
var crc crc
|
||||||
|
var dataLength uint16
|
||||||
|
|
||||||
rxbuf = make([]byte, 10243)
|
rxbuf = make([]byte, maxRTUFrameLength)
|
||||||
|
|
||||||
|
// 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
|
||||||
|
}
|
||||||
|
|
||||||
|
// handle custom function code 0x41 with special format:
|
||||||
|
// [单元ID] [功能码] [起始地址(2字节)] [字节数(2字节)] [数据...] [CRC]
|
||||||
|
if uint8(rxbuf[1]) == fcCustomize {
|
||||||
|
// read the start address (2 bytes) and byte count (2 bytes)
|
||||||
|
byteCount, err = io.ReadFull(rt.link, rxbuf[3:7])
|
||||||
|
if (byteCount > 0 || err == nil) && byteCount != 4 {
|
||||||
|
err = ErrShortFrame
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err != nil && err != io.ErrUnexpectedEOF {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// extract data length from bytes 5-6 (byte count field, big endian)
|
||||||
|
dataLength = bytesToUint16(BIG_ENDIAN, rxbuf[5:7])
|
||||||
|
bytesNeeded = int(dataLength)
|
||||||
|
|
||||||
|
// we need to read 2 additional bytes of CRC after the payload
|
||||||
|
bytesNeeded += 2
|
||||||
|
|
||||||
|
// calculate total frame size: 3 (header) + 4 (start addr + byte count) + data + 2 (CRC)
|
||||||
|
totalFrameSize := 7 + bytesNeeded
|
||||||
|
|
||||||
|
// for custom function code, we may need a larger buffer than maxRTUFrameLength
|
||||||
|
// allocate buffer dynamically if needed
|
||||||
|
if totalFrameSize > maxRTUFrameLength {
|
||||||
|
// save already read data
|
||||||
|
header := make([]byte, 7)
|
||||||
|
copy(header, rxbuf[0:7])
|
||||||
|
// resize buffer to accommodate larger frame
|
||||||
|
rxbuf = make([]byte, totalFrameSize)
|
||||||
|
// copy back the header
|
||||||
|
copy(rxbuf[0:7], header)
|
||||||
|
}
|
||||||
|
|
||||||
|
// read the data and CRC
|
||||||
|
byteCount, err = io.ReadFull(rt.link, rxbuf[7:7+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 : 7+bytesNeeded-2])
|
||||||
|
|
||||||
|
// compare CRC values
|
||||||
|
if !crc.isEqual(rxbuf[7+bytesNeeded-2], rxbuf[7+bytesNeeded-1]) {
|
||||||
|
err = ErrBadCRC
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
res = &pdu{
|
||||||
|
unitId: rxbuf[0],
|
||||||
|
functionCode: rxbuf[1],
|
||||||
|
// pass the start address (2 bytes) + byte count (2 bytes) + data as payload, without the CRC
|
||||||
|
payload: rxbuf[2 : 7+bytesNeeded-2],
|
||||||
|
}
|
||||||
|
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// standard modbus protocol handling
|
||||||
|
// 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
|
||||||
|
}
|
||||||
|
|
||||||
|
res = &pdu{
|
||||||
|
unitId: rxbuf[0],
|
||||||
|
functionCode: rxbuf[1],
|
||||||
|
// pass the byte count + trailing data as payload, withtout the CRC
|
||||||
|
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
|
// read the serial ADU header: unit id (1 byte), function code (1 byte) and
|
||||||
// PDU length/exception code (1 byte)
|
// PDU length/exception code (1 byte)
|
||||||
@@ -188,11 +374,77 @@ func (rt *rtuTransport) readRTUFrame() (res *pdu, err error) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 标准modbus响应已读取完成,现在读取自定义数据
|
||||||
|
// 设置5秒超时来读取自定义数据
|
||||||
|
customDataTimeout := 5 * time.Second
|
||||||
|
err = rt.link.SetDeadline(time.Now().Add(customDataTimeout))
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// 使用临时缓冲区循环读取自定义数据
|
||||||
|
tempBuf := make([]byte, 256) // 每次读取最多256字节
|
||||||
|
totalRead := 0
|
||||||
|
startPos := 3 + bytesNeeded
|
||||||
|
|
||||||
|
for {
|
||||||
|
// 检查缓冲区是否还有空间
|
||||||
|
if startPos+totalRead+len(tempBuf) > len(rxbuf) {
|
||||||
|
// 如果缓冲区不够,扩展它
|
||||||
|
newBuf := make([]byte, len(rxbuf)*2)
|
||||||
|
copy(newBuf, rxbuf)
|
||||||
|
rxbuf = newBuf
|
||||||
|
}
|
||||||
|
|
||||||
|
// 尝试读取数据
|
||||||
|
n, readErr := rt.link.Read(tempBuf)
|
||||||
|
if n > 0 {
|
||||||
|
// 将读取的数据复制到rxbuf
|
||||||
|
copy(rxbuf[startPos+totalRead:startPos+totalRead+n], tempBuf[:n])
|
||||||
|
totalRead += n
|
||||||
|
}
|
||||||
|
|
||||||
|
// 如果遇到超时错误,说明没有更多数据了
|
||||||
|
if readErr != nil {
|
||||||
|
if os.IsTimeout(readErr) {
|
||||||
|
// 超时是正常的,说明自定义数据读取完成
|
||||||
|
break
|
||||||
|
}
|
||||||
|
// 其他错误需要检查是否是EOF(数据读取完成)
|
||||||
|
if readErr == io.EOF {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
// 对于其他错误,如果已经读取了一些数据,继续处理
|
||||||
|
if totalRead == 0 {
|
||||||
|
err = readErr
|
||||||
|
return
|
||||||
|
}
|
||||||
|
break
|
||||||
|
}
|
||||||
|
|
||||||
|
// 如果读取的字节数少于请求的,说明没有更多数据了
|
||||||
|
if n < len(tempBuf) {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 返回标准响应的payload(地址+值,4字节)+ 自定义数据
|
||||||
|
// 标准响应的payload在 rxbuf[2:3+bytesNeeded-2] 位置
|
||||||
|
standardPayloadStart := 2
|
||||||
|
standardPayloadEnd := 3 + bytesNeeded - 2
|
||||||
|
|
||||||
|
// 构建完整的payload:标准响应payload + 自定义数据
|
||||||
|
completePayload := make([]byte, 0, standardPayloadEnd-standardPayloadStart+totalRead)
|
||||||
|
completePayload = append(completePayload, rxbuf[standardPayloadStart:standardPayloadEnd]...)
|
||||||
|
if totalRead > 0 {
|
||||||
|
completePayload = append(completePayload, rxbuf[startPos:startPos+totalRead]...)
|
||||||
|
}
|
||||||
|
|
||||||
res = &pdu{
|
res = &pdu{
|
||||||
unitId: rxbuf[0],
|
unitId: rxbuf[0],
|
||||||
functionCode: rxbuf[1],
|
functionCode: rxbuf[1],
|
||||||
// pass the byte count + trailing data as payload, withtout the CRC
|
// payload包含标准响应的payload + 自定义数据
|
||||||
payload: rxbuf[2 : 3+bytesNeeded-2],
|
payload: completePayload,
|
||||||
}
|
}
|
||||||
|
|
||||||
return
|
return
|
||||||
|
|||||||
@@ -59,6 +59,10 @@ func (tt *tcpTransport) ExecuteRequest(req *pdu) (res *pdu, err error) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (tt *tcpTransport) ExecuteRequestWithRes(req *pdu) (res *pdu, err error) {
|
||||||
|
return nil, nil
|
||||||
|
}
|
||||||
|
|
||||||
// Reads a request from the socket.
|
// Reads a request from the socket.
|
||||||
func (tt *tcpTransport) ReadRequest() (req *pdu, err error) {
|
func (tt *tcpTransport) ReadRequest() (req *pdu, err error) {
|
||||||
var txnId uint16
|
var txnId uint16
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
package modbus
|
package modbus
|
||||||
|
|
||||||
type transportType uint
|
type transportType uint
|
||||||
|
|
||||||
const (
|
const (
|
||||||
modbusRTU transportType = 1
|
modbusRTU transportType = 1
|
||||||
modbusRTUOverTCP transportType = 2
|
modbusRTUOverTCP transportType = 2
|
||||||
@@ -11,8 +12,9 @@ const (
|
|||||||
)
|
)
|
||||||
|
|
||||||
type transport interface {
|
type transport interface {
|
||||||
Close() (error)
|
Close() error
|
||||||
ExecuteRequest(*pdu) (*pdu, error)
|
ExecuteRequest(*pdu) (*pdu, error)
|
||||||
|
ExecuteRequestWithRes(*pdu) (*pdu, error)
|
||||||
ReadRequest() (*pdu, error)
|
ReadRequest() (*pdu, error)
|
||||||
WriteResponse(*pdu) (error)
|
WriteResponse(*pdu) error
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user