pymodbus:从Modbus设备发出读取字符串和多种类型的数据

2024-04-29 14:53:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图从Modbus TCP设备读取String(Usecase-1)&;multiple type of data in one request(Usecase-2)数据,但未能正确解码。在

系统配置:

Python 3.6.5
Pymodbus: 2.1.0
Platform: Windows 10 64-bit

Modbus TCP服务器:

import logging

from pymodbus.constants import Endian
from pymodbus.datastore import ModbusSequentialDataBlock
from pymodbus.datastore import ModbusSlaveContext, ModbusServerContext
from pymodbus.device import ModbusDeviceIdentification
from pymodbus.payload import BinaryPayloadBuilder
from pymodbus.server.sync import StartTcpServer

class ModbusTCPServer(object):
    # initialize your data store:
    hrBuilder = BinaryPayloadBuilder(byteorder=Endian.Big, wordorder=Endian.Big)
    # Usecase-1
    hrBuilder.add_string("abcdefghij")

    #Uncomment below three lines for usecase-2
    # hrBuilder.add_32bit_float(20.5) 
    # hrBuilder.add_32bit_int(45) 
    # hrBuilder.add_bits([1, 0, 0, 0, 0, 0, 0, 0])

    hrBlock = ModbusSequentialDataBlock(0, hrBuilder.to_registers() * 100)
    store = ModbusSlaveContext(hr=hrBlock, ir=hrBlock, di=hrBlock, co=hrBlock)
    slaves = {
        1: store,
    }
    context = ModbusServerContext(slaves=slaves, single=False)

    # initialize the server information    
    identity = ModbusDeviceIdentification()

    modbusDeviceAddress = "127.0.0.1"
    modbusDevicePort = 501
    # run the TCP server

    # TCP:
    print("Modbus TCP Server started.")
    StartTcpServer(context, identity=identity, address=(modbusDeviceAddress, modbusDevicePort))


if __name__ == "__main__":
    print("Reading application configurations...")
    ModbusTCPServer();

Modbus TCP客户端:

^{pr2}$

输出用例1:

Result :  ReadRegisterResponse (5)
name     cdefghijab

Modbus客户端应该将字符串解码为abcdefghij,但它将其解码为cdefghijab。在

输出用例2:

Result :  ReadRegisterResponse (5)
temp     0.0
rpm  2949376
status   [True, False, False, False, False, False, True, False]

看看上面读取多个寄存器的输出,输出值与BinaryPayloadBuilder的输入值不匹配。在

我已经尝试过byteorder&;wordorder的所有组合,但它对任何情况都不起作用。在

请帮助我理解为什么数据会这样解码?在编码或解码这些数据时,我是否遗漏了一些要添加的内容?在

仅供参考:此解决方案与Pymodbus 1.5.1版本配合良好。最近我升级了版本,但未能如期工作。在

任何帮助都将不胜感激。在


Tags: 数据fromimportaddfalseserver解码modbus
1条回答
网友
1楼 · 发布于 2024-04-29 14:53:45

dr.在ModbusSlaveContext中使用zero_mode=True。在

如果要将客户机中的寄存器[0..n]映射到服务器中的[0..n]。默认情况下,pymodbus服务器将地址[0..n]的寄存器读取映射到其内部存储中的寄存器[1..n]。这是为了遵守modbus规范。引用pymodbus源代码。在

#The slave context can also be initialized in zero_mode which means that a
# request to address(0-7) will map to the address (0-7). The default is
# False which is based on section 4.4 of the specification, so address(0-7)
# will map to (1-8)::

所以在您的例子中,您可以将ModbusSequentialDataBlock的起始地址设置为1,或者使用zero_mode=True初始化{}。在

    hrBlock = ModbusSequentialDataBlock(1, hrBuilder.to_registers() * 100)
    # Or
    store = ModbusSlaveContext(hr=hrBlock, ir=hrBlock, di=hrBlock, co=hrBlock, zero_mode=True)

相关问题 更多 >