Compare commits
17 Commits
v0.0.5
...
cfy-feat-d
| Author | SHA1 | Date | |
|---|---|---|---|
| ccfc7f0736 | |||
| 67b5a4df7f | |||
| 50add55c87 | |||
| fb90bbf207 | |||
| 343292b9b2 | |||
| a635b8af4e | |||
| 7ba768b8c2 | |||
| b45b8e1d8d | |||
| 1df66eccd1 | |||
| 34b8d0fedd | |||
| 08a89aa3bb | |||
| a064755998 | |||
| 718f3f21aa | |||
| d78c1a0573 | |||
| 706eb8c0a9 | |||
| 72429c08a3 | |||
| 1c4d54df71 |
85
client.go
85
client.go
@@ -801,17 +801,27 @@ func (mc *ModbusClient) WriteRegisterWithRes(addr uint16, value uint16) (bytes [
|
||||
// validate the response code
|
||||
switch {
|
||||
case res.functionCode == req.functionCode:
|
||||
// expect 4 bytes (2 byte of address + 2 bytes of value)
|
||||
if len(res.payload) != 4 ||
|
||||
// bytes 1-2 should be the register address
|
||||
bytesToUint16(BIG_ENDIAN, res.payload[0:2]) != addr ||
|
||||
// expect at least 4 bytes (2 byte of address + 2 bytes of value)
|
||||
// 后面可能还有自定义数据
|
||||
if len(res.payload) < 4 {
|
||||
err = ErrProtocolError
|
||||
return
|
||||
}
|
||||
|
||||
// bytes 1-2 should be the register address
|
||||
if bytesToUint16(BIG_ENDIAN, res.payload[0:2]) != addr ||
|
||||
// bytes 3-4 should be the value
|
||||
bytesToUint16(mc.endianness, res.payload[2:4]) != value {
|
||||
err = ErrProtocolError
|
||||
return
|
||||
}
|
||||
|
||||
bytes = req.payload[1:]
|
||||
// 返回自定义数据(第4字节之后的数据)
|
||||
if len(res.payload) > 4 {
|
||||
bytes = res.payload[4:]
|
||||
} else {
|
||||
bytes = []byte{} // 没有自定义数据,返回空切片
|
||||
}
|
||||
|
||||
case res.functionCode == (req.functionCode | 0x80):
|
||||
if len(res.payload) != 1 {
|
||||
@@ -1202,8 +1212,8 @@ func (mc *ModbusClient) readRegistersWithFunctionCode(addr uint16, quantity uint
|
||||
return
|
||||
}
|
||||
|
||||
// 16 * 16 * 40
|
||||
if quantity > 10240 {
|
||||
// 16 * 40
|
||||
if quantity > 640 {
|
||||
err = ErrUnexpectedParameters
|
||||
mc.logger.Error("quantity of registers exceeds 10240")
|
||||
return
|
||||
@@ -1261,22 +1271,55 @@ func (mc *ModbusClient) readRegistersWithFunctionCode(addr uint16, quantity uint
|
||||
|
||||
switch {
|
||||
case res.functionCode == req.functionCode:
|
||||
// make sure the payload length is what we expect
|
||||
// (1 byte of length + 2 bytes per register)
|
||||
// if len(res.payload) != 1+2*int(quantity) {
|
||||
// err = ErrProtocolError
|
||||
// return
|
||||
// }
|
||||
// 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
|
||||
}
|
||||
|
||||
// validate the byte count field
|
||||
// (2 bytes per register * number of registers)
|
||||
// if uint(res.payload[0]) != 2*uint(quantity) {
|
||||
// err = ErrProtocolError
|
||||
// return
|
||||
// }
|
||||
// extract byte count from payload (bytes 2-3, big endian)
|
||||
byteCount := bytesToUint16(BIG_ENDIAN, res.payload[2:4])
|
||||
|
||||
// remove the byte count field from the returned slice
|
||||
bytes = res.payload[1:]
|
||||
// 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
|
||||
// (1 byte of length + 2 bytes per register)
|
||||
// if len(res.payload) != 1+2*int(quantity) {
|
||||
// err = ErrProtocolError
|
||||
// return
|
||||
// }
|
||||
|
||||
// validate the byte count field
|
||||
// (2 bytes per register * number of registers)
|
||||
// if uint(res.payload[0]) != 2*uint(quantity) {
|
||||
// err = ErrProtocolError
|
||||
// return
|
||||
// }
|
||||
|
||||
// remove the byte count field from the returned slice
|
||||
bytes = res.payload[1:]
|
||||
}
|
||||
|
||||
case res.functionCode == (req.functionCode | 0x80):
|
||||
if len(res.payload) != 1 {
|
||||
|
||||
180
rtu_transport.go
180
rtu_transport.go
@@ -4,6 +4,7 @@ import (
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"os"
|
||||
"time"
|
||||
)
|
||||
|
||||
@@ -80,6 +81,7 @@ func (rt *rtuTransport) ExecuteRequest(req *pdu) (res *pdu, err error) {
|
||||
// send the final ADU+CRC on the wire
|
||||
n, err = rt.link.Write(rt.assembleRTUFrame(req))
|
||||
if err != nil {
|
||||
fmt.Printf("write error: %s", err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
@@ -192,6 +194,7 @@ func (rt *rtuTransport) readRTUFrame() (res *pdu, err error) {
|
||||
var byteCount int
|
||||
var bytesNeeded int
|
||||
var crc crc
|
||||
// var dataLength uint16
|
||||
|
||||
rxbuf = make([]byte, maxRTUFrameLength)
|
||||
|
||||
@@ -202,10 +205,115 @@ func (rt *rtuTransport) readRTUFrame() (res *pdu, err error) {
|
||||
err = ErrShortFrame
|
||||
return
|
||||
}
|
||||
// if uint8(rxbuf[1]) == fcCustomize {
|
||||
// fmt.Printf("receive: %v\n", rxbuf[0:3])
|
||||
// }
|
||||
if err != nil && err != io.ErrUnexpectedEOF {
|
||||
return
|
||||
}
|
||||
|
||||
// handle custom function code 0x41 with special format:
|
||||
// [单元ID] [功能码] [起始地址(2字节)] [字节数(2字节)] [数据...] [CRC]
|
||||
if uint8(rxbuf[1]) == fcCustomize {
|
||||
// 1. 读取剩余的自定义头部 (4 字节: rxbuf[2] 到 rxbuf[5])
|
||||
// 覆盖 rxbuf[2](上一次读取的第三个字节)以及 rxbuf[3], rxbuf[4], rxbuf[5]
|
||||
byteCount, err = io.ReadFull(rt.link, rxbuf[3:6]) // <-- 关键修正:从索引 2 开始读取 4 字节
|
||||
|
||||
// 修正短帧检查逻辑
|
||||
if err != nil {
|
||||
if err == io.EOF || err == io.ErrUnexpectedEOF {
|
||||
err = ErrShortFrame
|
||||
}
|
||||
return
|
||||
}
|
||||
// 此时 byteCount 应该总是 4。
|
||||
|
||||
// 2. 提取数据长度 (关键修正点)
|
||||
// 数据长度位于 rxbuf[4] 和 rxbuf[5]
|
||||
dataLength := bytesToUint16(BIG_ENDIAN, rxbuf[4:6])
|
||||
bytesNeeded = int(dataLength)
|
||||
|
||||
// 3. 计算总共需要读取的字节数
|
||||
// 数据域长度 + 2 字节 CRC
|
||||
bytesToRead := bytesNeeded + 2
|
||||
|
||||
// 4. 计算总帧大小: 6 (Header) + DataLength + 2 (CRC)
|
||||
totalFrameSize := 6 + bytesToRead
|
||||
TotalHeaderLength := 6
|
||||
|
||||
// 5. 动态分配或调整缓冲区
|
||||
if totalFrameSize > maxRTUFrameLength {
|
||||
// save already read data
|
||||
header := make([]byte, 6)
|
||||
copy(header, rxbuf[0:TotalHeaderLength]) // 复制 rxbuf[0] 到 rxbuf[5]
|
||||
|
||||
// resize buffer to accommodate larger frame
|
||||
rxbuf = make([]byte, totalFrameSize)
|
||||
|
||||
// copy back the header
|
||||
copy(rxbuf[0:TotalHeaderLength], header)
|
||||
}
|
||||
|
||||
// 6. 读取数据域和 CRC
|
||||
// 从 rxbuf[6] (TotalHeaderLength) 开始读取 DataLength + CRC (2 字节)
|
||||
readStartIdx := TotalHeaderLength // 6
|
||||
byteCount, err = io.ReadFull(rt.link, rxbuf[readStartIdx:totalFrameSize])
|
||||
|
||||
if err != nil {
|
||||
if err == io.EOF || err == io.ErrUnexpectedEOF {
|
||||
err = ErrShortFrame
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
if byteCount != bytesToRead {
|
||||
rt.logger.Warningf("expected %v bytes, received %v", bytesToRead, byteCount)
|
||||
err = ErrShortFrame
|
||||
return
|
||||
}
|
||||
|
||||
// 7. CRC 校验
|
||||
crcEndIndex := totalFrameSize - 2 // CRC 校验范围的结束索引 (不包含)
|
||||
|
||||
// if checkCRC(rxbuf, totalFrameSize) {
|
||||
// fmt.Println("66666666666666")
|
||||
// }
|
||||
|
||||
crc.init()
|
||||
crc.add(rxbuf[0:crcEndIndex]) // 校验范围从 rxbuf[0] 到数据域结束
|
||||
|
||||
// 比较接收到的 CRC
|
||||
sentHigh := rxbuf[crcEndIndex] // C_high (例如 0x8B)
|
||||
sentLow := rxbuf[crcEndIndex+1] // C_low (例如 0xB0)
|
||||
|
||||
// 由于 isEqual 期望 (low, high),我们需要将 sentLow 传给 low
|
||||
|
||||
// fmt.Printf("ddd: % X\n", rxbuf)
|
||||
// fmt.Println("c.crc: ", crc.crc)
|
||||
// fmt.Println("sentLow: ", sentLow, "sentHigh: ", sentHigh)
|
||||
// fmt.Println("rxbuf[0:10]: ", rxbuf[0:10], "rxbuf[crcEndIndex-10:crcEndIndex]: ", rxbuf[crcEndIndex-10:crcEndIndex])
|
||||
|
||||
// fmt.Println("len: ", len(rxbuf[crcEndIndex-10:crcEndIndex]))
|
||||
|
||||
if !crc.isEqual(sentHigh, sentLow) {
|
||||
err = ErrBadCRC
|
||||
// fmt.Println("crc: ", sentLow, sentHigh, "byte needed: ", bytesNeeded)
|
||||
return
|
||||
}
|
||||
|
||||
// 8. 构造 PDU
|
||||
// Payload 包含:自定义数据 (4 bytes) + Data (N bytes)
|
||||
// 切片范围:从 rxbuf[2] (自定义数据开始) 到数据域结束 (crcEndIndex)
|
||||
res = &pdu{
|
||||
unitId: rxbuf[0],
|
||||
functionCode: rxbuf[1],
|
||||
payload: rxbuf[2:crcEndIndex],
|
||||
}
|
||||
|
||||
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 {
|
||||
@@ -305,16 +413,80 @@ func (rt *rtuTransport) readRTUFrameWithRes() (res *pdu, err error) {
|
||||
return
|
||||
}
|
||||
|
||||
_, err = io.ReadFull(rt.link, rxbuf[3+bytesNeeded:])
|
||||
if err != nil && err != io.ErrUnexpectedEOF {
|
||||
// 标准modbus响应已读取完成,现在读取自定义数据
|
||||
// 设置5秒超时来读取自定义数据
|
||||
customDataTimeout := 5 * time.Second
|
||||
deadline := time.Now().Add(customDataTimeout)
|
||||
err = rt.link.SetDeadline(deadline)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
// 使用临时缓冲区循环读取自定义数据
|
||||
tempBuf := make([]byte, 256) // 每次读取最多256字节
|
||||
totalRead := 0
|
||||
startPos := 3 + bytesNeeded
|
||||
var lastErr error // 记录最后一次非超时错误
|
||||
|
||||
for {
|
||||
// 检查是否已经超时
|
||||
if time.Now().After(deadline) {
|
||||
// 超时时间到,退出循环
|
||||
// 如果有之前记录的错误,使用它;否则err保持为nil(超时是正常的)
|
||||
if lastErr != nil {
|
||||
err = lastErr
|
||||
}
|
||||
break
|
||||
}
|
||||
|
||||
// 检查缓冲区是否还有空间
|
||||
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) {
|
||||
// 超时时间到,退出循环
|
||||
// 如果有之前记录的错误,使用它;否则err保持为nil(超时是正常的)
|
||||
if lastErr != nil {
|
||||
err = lastErr
|
||||
}
|
||||
break
|
||||
}
|
||||
// 记录非超时错误,但继续等待直到超时
|
||||
lastErr = readErr
|
||||
// 继续循环,等待超时
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// 标准响应的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{
|
||||
unitId: rxbuf[0],
|
||||
functionCode: rxbuf[1],
|
||||
// pass the byte count + trailing data as payload, withtout the CRC
|
||||
payload: rxbuf[3+bytesNeeded:],
|
||||
payload: completePayload,
|
||||
}
|
||||
|
||||
return
|
||||
|
||||
54
serial.go
54
serial.go
@@ -1,6 +1,6 @@
|
||||
package modbus
|
||||
|
||||
import (
|
||||
import (
|
||||
"time"
|
||||
|
||||
"github.com/goburrow/serial"
|
||||
@@ -10,43 +10,46 @@ import (
|
||||
// 1) satisfy the rtuLink interface and
|
||||
// 2) add Read() deadline/timeout support.
|
||||
type serialPortWrapper struct {
|
||||
conf *serialPortConfig
|
||||
port serial.Port
|
||||
deadline time.Time
|
||||
conf *serialPortConfig
|
||||
port serial.Port
|
||||
deadline time.Time
|
||||
}
|
||||
|
||||
type serialPortConfig struct {
|
||||
Device string
|
||||
Speed uint
|
||||
DataBits uint
|
||||
Parity uint
|
||||
StopBits uint
|
||||
Device string
|
||||
Speed uint
|
||||
DataBits uint
|
||||
Parity uint
|
||||
StopBits uint
|
||||
}
|
||||
|
||||
func newSerialPortWrapper(conf *serialPortConfig) (spw *serialPortWrapper) {
|
||||
spw = &serialPortWrapper{
|
||||
conf: conf,
|
||||
conf: conf,
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
func (spw *serialPortWrapper) Open() (err error) {
|
||||
var parity string
|
||||
var parity string
|
||||
|
||||
switch spw.conf.Parity {
|
||||
case PARITY_NONE: parity = "N"
|
||||
case PARITY_EVEN: parity = "E"
|
||||
case PARITY_ODD: parity = "O"
|
||||
case PARITY_NONE:
|
||||
parity = "N"
|
||||
case PARITY_EVEN:
|
||||
parity = "E"
|
||||
case PARITY_ODD:
|
||||
parity = "O"
|
||||
}
|
||||
|
||||
spw.port, err = serial.Open(&serial.Config{
|
||||
Address: spw.conf.Device,
|
||||
BaudRate: int(spw.conf.Speed),
|
||||
DataBits: int(spw.conf.DataBits),
|
||||
Parity: parity,
|
||||
StopBits: int(spw.conf.StopBits),
|
||||
Timeout: 10 * time.Millisecond,
|
||||
Address: spw.conf.Device,
|
||||
BaudRate: int(spw.conf.Speed),
|
||||
DataBits: int(spw.conf.DataBits),
|
||||
Parity: parity,
|
||||
StopBits: int(spw.conf.StopBits),
|
||||
Timeout: 100 * time.Millisecond,
|
||||
})
|
||||
|
||||
return
|
||||
@@ -64,11 +67,12 @@ func (spw *serialPortWrapper) Close() (err error) {
|
||||
// attempting to read from the serial port.
|
||||
// If Read() is called before the deadline, a read attempt to the serial port
|
||||
// is made. At this point, one of two things can happen:
|
||||
// - the serial port's receive buffer has one or more bytes and port.Read()
|
||||
// returns immediately (partial or full read),
|
||||
// - the serial port's receive buffer is empty: port.Read() blocks for
|
||||
// up to 10ms and returns serial.ErrTimeout. The serial timeout error is
|
||||
// masked and Read() returns with no data.
|
||||
// - the serial port's receive buffer has one or more bytes and port.Read()
|
||||
// returns immediately (partial or full read),
|
||||
// - the serial port's receive buffer is empty: port.Read() blocks for
|
||||
// up to 10ms and returns serial.ErrTimeout. The serial timeout error is
|
||||
// masked and Read() returns with no data.
|
||||
//
|
||||
// As the higher-level methods use io.ReadFull(), Read() will be called
|
||||
// as many times as necessary until either enough bytes have been read or an
|
||||
// error is returned (ErrRequestTimedOut or any other i/o error).
|
||||
|
||||
@@ -154,8 +154,13 @@ func (tt *tcpTransport) readMBAPFrame() (p *pdu, txnId uint16, err error) {
|
||||
// the byte count includes the unit ID field, which we already have
|
||||
bytesNeeded--
|
||||
|
||||
maxTCPFrameLen := maxTCPFrameLength
|
||||
if rxbuf[1] == fcCustomize {
|
||||
maxTCPFrameLen = 647
|
||||
}
|
||||
|
||||
// never read more than the max allowed frame length
|
||||
if bytesNeeded+mbapHeaderLength > maxTCPFrameLength {
|
||||
if bytesNeeded+mbapHeaderLength > maxTCPFrameLen {
|
||||
err = ErrProtocolError
|
||||
return
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user