14 Commits

Author SHA1 Message Date
ccfc7f0736 Merge branch 'main' of https://git.whblueocean.cn/communication-protocol/modbus into cfy-feat-dev 2026-01-06 16:55:58 +08:00
67b5a4df7f 删除一些无用代码&tcp自定义0x41功能码读取数据 2026-01-06 16:55:53 +08:00
50add55c87 Merge pull request '帧间间隔时间10ms->100ms' (#11) from cfy-feat-fix into main
Reviewed-on: #11
2025-12-29 11:49:48 +08:00
fb90bbf207 Merge branch 'main' of https://git.whblueocean.cn/communication-protocol/modbus into cfy-feat-fix 2025-12-29 11:48:54 +08:00
343292b9b2 帧间间隔时间10ms->100ms 2025-12-29 11:48:45 +08:00
a635b8af4e Merge pull request '修复标定信息读取问题' (#10) from cfy-feat-fix into main
Reviewed-on: #10
2025-11-26 16:05:49 +08:00
7ba768b8c2 Merge branch 'main' into cfy-feat-fix 2025-11-26 16:05:42 +08:00
b45b8e1d8d 修复标定信息读取问题 2025-11-26 16:04:57 +08:00
1df66eccd1 Merge pull request '读标定信息写入优化' (#9) from cfy-feat-dev into main
Reviewed-on: #9
2025-11-26 15:51:31 +08:00
34b8d0fedd 读标定信息写入优化 2025-11-26 15:51:04 +08:00
08a89aa3bb Merge pull request '完善自定义读取数据&优化自定义写入数据' (#7) from cfy-feat-dev into main
Reviewed-on: #7
2025-11-19 13:37:02 +08:00
a064755998 Merge branch 'main' of https://git.whblueocean.cn/communication-protocol/modbus into cfy-feat-dev 2025-11-19 13:36:17 +08:00
718f3f21aa 优化自定义写入数据 2025-11-19 13:36:12 +08:00
706eb8c0a9 Merge pull request '自定义实时数据读取&读标定信息' (#6) from cfy-feat-dev into main
Reviewed-on: #6
2025-11-17 11:02:24 +08:00
4 changed files with 82 additions and 62 deletions

View File

@@ -1212,8 +1212,8 @@ func (mc *ModbusClient) readRegistersWithFunctionCode(addr uint16, quantity uint
return return
} }
// 16 * 16 * 40 // 16 * 40
if quantity > 10240 { if quantity > 640 {
err = ErrUnexpectedParameters err = ErrUnexpectedParameters
mc.logger.Error("quantity of registers exceeds 10240") mc.logger.Error("quantity of registers exceeds 10240")
return return

View File

@@ -80,7 +80,6 @@ func (rt *rtuTransport) ExecuteRequest(req *pdu) (res *pdu, err error) {
// build an RTU ADU out of the request object and // build an RTU ADU out of the request object and
// send the final ADU+CRC on the wire // send the final ADU+CRC on the wire
n, err = rt.link.Write(rt.assembleRTUFrame(req)) n, err = rt.link.Write(rt.assembleRTUFrame(req))
fmt.Printf("send: %X\n", rt.assembleRTUFrame(req))
if err != nil { if err != nil {
fmt.Printf("write error: %s", err.Error()) fmt.Printf("write error: %s", err.Error())
return return
@@ -206,9 +205,9 @@ func (rt *rtuTransport) readRTUFrame() (res *pdu, err error) {
err = ErrShortFrame err = ErrShortFrame
return return
} }
if uint8(rxbuf[1]) == fcCustomize { // if uint8(rxbuf[1]) == fcCustomize {
fmt.Printf("receive: %v\n", rxbuf[0:3]) // fmt.Printf("receive: %v\n", rxbuf[0:3])
} // }
if err != nil && err != io.ErrUnexpectedEOF { if err != nil && err != io.ErrUnexpectedEOF {
return return
} }
@@ -233,7 +232,6 @@ func (rt *rtuTransport) readRTUFrame() (res *pdu, err error) {
// 数据长度位于 rxbuf[4] 和 rxbuf[5] // 数据长度位于 rxbuf[4] 和 rxbuf[5]
dataLength := bytesToUint16(BIG_ENDIAN, rxbuf[4:6]) dataLength := bytesToUint16(BIG_ENDIAN, rxbuf[4:6])
bytesNeeded = int(dataLength) bytesNeeded = int(dataLength)
fmt.Println(bytesNeeded)
// 3. 计算总共需要读取的字节数 // 3. 计算总共需要读取的字节数
// 数据域长度 + 2 字节 CRC // 数据域长度 + 2 字节 CRC
@@ -276,22 +274,32 @@ func (rt *rtuTransport) readRTUFrame() (res *pdu, err error) {
// 7. CRC 校验 // 7. CRC 校验
crcEndIndex := totalFrameSize - 2 // CRC 校验范围的结束索引 (不包含) crcEndIndex := totalFrameSize - 2 // CRC 校验范围的结束索引 (不包含)
fmt.Println("crc end index", crcEndIndex)
// if checkCRC(rxbuf, totalFrameSize) {
// fmt.Println("66666666666666")
// }
crc.init() crc.init()
crc.add(rxbuf[0:crcEndIndex]) // 校验范围从 rxbuf[0] 到数据域结束 crc.add(rxbuf[0:crcEndIndex]) // 校验范围从 rxbuf[0] 到数据域结束
// 比较接收到的 CRC // 比较接收到的 CRC
// recvCRCLow := rxbuf[crcEndIndex] sentHigh := rxbuf[crcEndIndex] // C_high (例如 0x8B)
// recvCRCHigh := rxbuf[crcEndIndex+1] sentLow := rxbuf[crcEndIndex+1] // C_low (例如 0xB0)
// fmt.Println("len: ", len(rxbuf[6:crcEndIndex])) // 由于 isEqual 期望 (low, high),我们需要将 sentLow 传给 low
// if !crc.isEqual(recvCRCLow, recvCRCHigh) { // fmt.Printf("ddd: % X\n", rxbuf)
// err = ErrBadCRC // fmt.Println("c.crc: ", crc.crc)
// fmt.Println("crc: ", recvCRCLow, recvCRCHigh, "byte needed: ", bytesNeeded) // fmt.Println("sentLow: ", sentLow, "sentHigh: ", sentHigh)
// return // 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 // 8. 构造 PDU
// Payload 包含:自定义数据 (4 bytes) + Data (N bytes) // Payload 包含:自定义数据 (4 bytes) + Data (N bytes)
@@ -408,7 +416,8 @@ func (rt *rtuTransport) readRTUFrameWithRes() (res *pdu, err error) {
// 标准modbus响应已读取完成现在读取自定义数据 // 标准modbus响应已读取完成现在读取自定义数据
// 设置5秒超时来读取自定义数据 // 设置5秒超时来读取自定义数据
customDataTimeout := 5 * time.Second customDataTimeout := 5 * time.Second
err = rt.link.SetDeadline(time.Now().Add(customDataTimeout)) deadline := time.Now().Add(customDataTimeout)
err = rt.link.SetDeadline(deadline)
if err != nil { if err != nil {
return return
} }
@@ -417,8 +426,19 @@ func (rt *rtuTransport) readRTUFrameWithRes() (res *pdu, err error) {
tempBuf := make([]byte, 256) // 每次读取最多256字节 tempBuf := make([]byte, 256) // 每次读取最多256字节
totalRead := 0 totalRead := 0
startPos := 3 + bytesNeeded startPos := 3 + bytesNeeded
var lastErr error // 记录最后一次非超时错误
for { for {
// 检查是否已经超时
if time.Now().After(deadline) {
// 超时时间到,退出循环
// 如果有之前记录的错误使用它否则err保持为nil超时是正常的
if lastErr != nil {
err = lastErr
}
break
}
// 检查缓冲区是否还有空间 // 检查缓冲区是否还有空间
if startPos+totalRead+len(tempBuf) > len(rxbuf) { if startPos+totalRead+len(tempBuf) > len(rxbuf) {
// 如果缓冲区不够,扩展它 // 如果缓冲区不够,扩展它
@@ -435,31 +455,23 @@ func (rt *rtuTransport) readRTUFrameWithRes() (res *pdu, err error) {
totalRead += n totalRead += n
} }
// 如果遇到超时错误,说明没有更多数据了 // 如果遇到超时错误,说明超时时间到了,退出循环
if readErr != nil { if readErr != nil {
if os.IsTimeout(readErr) { if os.IsTimeout(readErr) {
// 超时是正常的,说明自定义数据读取完成 // 超时时间到,退出循环
// 如果有之前记录的错误使用它否则err保持为nil超时是正常的
if lastErr != nil {
err = lastErr
}
break break
} }
// 其他错误需要检查是否是EOF数据读取完成 // 记录非超时错误,但继续等待直到超时
if readErr == io.EOF { lastErr = readErr
break // 继续循环,等待超时
}
// 对于其他错误,如果已经读取了一些数据,继续处理
if totalRead == 0 {
err = readErr
return
}
break
} }
// 如果读取的字节数少于请求的,说明没有更多数据了
if n < len(tempBuf) {
break
}
} }
// 返回标准响应的payload地址+值4字节+ 自定义数据
// 标准响应的payload在 rxbuf[2:3+bytesNeeded-2] 位置 // 标准响应的payload在 rxbuf[2:3+bytesNeeded-2] 位置
standardPayloadStart := 2 standardPayloadStart := 2
standardPayloadEnd := 3 + bytesNeeded - 2 standardPayloadEnd := 3 + bytesNeeded - 2
@@ -474,8 +486,7 @@ func (rt *rtuTransport) readRTUFrameWithRes() (res *pdu, err error) {
res = &pdu{ res = &pdu{
unitId: rxbuf[0], unitId: rxbuf[0],
functionCode: rxbuf[1], functionCode: rxbuf[1],
// payload包含标准响应的payload + 自定义数据 payload: completePayload,
payload: completePayload,
} }
return return

View File

@@ -1,6 +1,6 @@
package modbus package modbus
import ( import (
"time" "time"
"github.com/goburrow/serial" "github.com/goburrow/serial"
@@ -10,43 +10,46 @@ import (
// 1) satisfy the rtuLink interface and // 1) satisfy the rtuLink interface and
// 2) add Read() deadline/timeout support. // 2) add Read() deadline/timeout support.
type serialPortWrapper struct { type serialPortWrapper struct {
conf *serialPortConfig conf *serialPortConfig
port serial.Port port serial.Port
deadline time.Time deadline time.Time
} }
type serialPortConfig struct { type serialPortConfig struct {
Device string Device string
Speed uint Speed uint
DataBits uint DataBits uint
Parity uint Parity uint
StopBits uint StopBits uint
} }
func newSerialPortWrapper(conf *serialPortConfig) (spw *serialPortWrapper) { func newSerialPortWrapper(conf *serialPortConfig) (spw *serialPortWrapper) {
spw = &serialPortWrapper{ spw = &serialPortWrapper{
conf: conf, conf: conf,
} }
return return
} }
func (spw *serialPortWrapper) Open() (err error) { func (spw *serialPortWrapper) Open() (err error) {
var parity string var parity string
switch spw.conf.Parity { switch spw.conf.Parity {
case PARITY_NONE: parity = "N" case PARITY_NONE:
case PARITY_EVEN: parity = "E" parity = "N"
case PARITY_ODD: parity = "O" case PARITY_EVEN:
parity = "E"
case PARITY_ODD:
parity = "O"
} }
spw.port, err = serial.Open(&serial.Config{ spw.port, err = serial.Open(&serial.Config{
Address: spw.conf.Device, Address: spw.conf.Device,
BaudRate: int(spw.conf.Speed), BaudRate: int(spw.conf.Speed),
DataBits: int(spw.conf.DataBits), DataBits: int(spw.conf.DataBits),
Parity: parity, Parity: parity,
StopBits: int(spw.conf.StopBits), StopBits: int(spw.conf.StopBits),
Timeout: 10 * time.Millisecond, Timeout: 100 * time.Millisecond,
}) })
return return
@@ -64,11 +67,12 @@ func (spw *serialPortWrapper) Close() (err error) {
// attempting to read from the serial port. // attempting to read from the serial port.
// If Read() is called before the deadline, a read attempt to 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: // 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() // - the serial port's receive buffer has one or more bytes and port.Read()
// returns immediately (partial or full read), // returns immediately (partial or full read),
// - the serial port's receive buffer is empty: port.Read() blocks for // - the serial port's receive buffer is empty: port.Read() blocks for
// up to 10ms and returns serial.ErrTimeout. The serial timeout error is // up to 10ms and returns serial.ErrTimeout. The serial timeout error is
// masked and Read() returns with no data. // masked and Read() returns with no data.
//
// As the higher-level methods use io.ReadFull(), Read() will be called // 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 // as many times as necessary until either enough bytes have been read or an
// error is returned (ErrRequestTimedOut or any other i/o error). // error is returned (ErrRequestTimedOut or any other i/o error).

View File

@@ -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 // the byte count includes the unit ID field, which we already have
bytesNeeded-- bytesNeeded--
maxTCPFrameLen := maxTCPFrameLength
if rxbuf[1] == fcCustomize {
maxTCPFrameLen = 647
}
// never read more than the max allowed frame length // never read more than the max allowed frame length
if bytesNeeded+mbapHeaderLength > maxTCPFrameLength { if bytesNeeded+mbapHeaderLength > maxTCPFrameLen {
err = ErrProtocolError err = ErrProtocolError
return return
} }