modbus-tk getting Modbus Error: Exception code = 2

modbus-tk getting Modbus Error: Exception code = 2

我正在使用 modbus-tk 模拟 modbus 设备进行单元测试。

我添加了2块数据。

def add_test_1(self):
    point = "Test_1"
    addr = 40003
    self.slave_1.add_block(point, mbdefines.HOLDING_REGISTERS, addr, 1)
    self.slave_1.set_values(point, addr, 5)

def add_test_2(self):
    point = "Test_2"
    addr = 40004
    self.slave_1.add_block(point, mbdefines.HOLDING_REGISTERS, addr, 2)
    self.slave_1.set_values(point, addr, (16560, 0))

但是当我使用modbus-tk读取多寄存器时

result = modbus_client.execute(1, mbdefines.READ_HOLDING_REGISTERS, 40003, 3)
print(result)

出现异常。

Modbus Error: Exception code = 2

同时,我仍然可以使用这个读取真实Modbus设备中的多数据

result = modbus_client.execute(1, mbdefines.READ_HOLDING_REGISTERS, 40003, 3)
print(result)

数据看起来像我之前显示的块数据

我正在使用 python 3.7.3 64 位

问题是您创建了两个不同的块。

def add_test_1(self):
    point = "Test_1"
    addr = 40003
    self.slave_1.add_block(point, mbdefines.HOLDING_REGISTERS, addr, 1)
    self.slave_1.set_values(point, addr, 5)

def add_test_2(self):
    point = "Test_2"
    addr = 40004
    self.slave_1.add_block(point, mbdefines.HOLDING_REGISTERS, addr, 2)
    self.slave_1.set_values(point, addr, (16560, 0))

两个块都可以读取,但是有两个不同的命令:

result_test_1 = modbus_client.execute(1, mbdefines.READ_HOLDING_REGISTERS, 40003, 1)
print(result_test_1 )
# (5, )

result_test_2 = modbus_client.execute(1, mbdefines.READ_HOLDING_REGISTERS, 40004, 2)
print(result_test_2 )
# (16560, 0, )

您也可以创建一个单独的块并读取它:

def add_test():
    point = "Test_1"
    addr = 40003
    slave_1.add_block(point, cst.HOLDING_REGISTERS, addr, 3)
    slave_1.set_values(point, addr, (5, 16560, 0))

result_test = modbus_client.execute(1, mbdefines.READ_HOLDING_REGISTERS, 40003, 3)
print(result_test)
# (5, 16560, 0, )

正如您在github上看到的那样,有一个名为_get_block_and_offset that is called by _read_registers. When you read from your slave the server call the function _read_holding_registers that return the result of _read_registers, but when it reach the call to _get_block_and_offset it raise ModbusError(defines.ILLEGAL_DATA_ADDRESS)的函数,因为不满足条件address >= block.starting_addressblock.size >= offset + length,所以return block, offset从未达到。