modbus返回数据校验 #4

Merged
Fuyao merged 2 commits from cfy-feat-dev into main 2025-11-13 15:51:43 +08:00
Showing only changes of commit a77c072cb5 - Show all commits

View File

@@ -1232,21 +1232,53 @@ func (mc *ModbusClient) readRegistersWithFunctionCode(addr uint16, quantity uint
} }
// validate the response code // validate the response code
// 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
// }
// // 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 {
// err = ErrProtocolError
// return
// }
// err = mapExceptionCodeToError(res.payload[0])
// default:
// err = ErrProtocolError
// mc.logger.Warningf("unexpected response code (%v)", res.functionCode)
// }
switch { switch {
case res.functionCode == req.functionCode: case res.functionCode == req.functionCode:
// 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) {
err = ErrProtocolError // err = ErrProtocolError
return // return
} // }
// validate the byte count field // validate the byte count field
// (2 bytes per register * number of registers) // (2 bytes per register * number of registers)
if uint(res.payload[0]) != 2*uint(quantity) { // if uint(res.payload[0]) != 2*uint(quantity) {
err = ErrProtocolError // err = ErrProtocolError
return // return
} // }
// 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:]