Python 读取文件记录的modbus lib

Python modbus lib for reading file record

有没有pythonmodbus库实现读写文件记录的功能(功能码:20、21)。流行的 Python modbus 库(pymodbus、pymodbusTCP)提供这些功能但不实现它们。谢谢。

Pymodbus 确实支持 ReadFileRecordRequest (0x14),使用起来有点棘手,请求需要查询记录列表作为其负载的一部分。每条记录都是一个子请求,具有以下属性。

The reference type: 1 byte (must be specified as 6)

The File number: 2 bytes

The starting record number within the file: 2 bytes

The length of the record to be read: 2 bytes.

为了方便创建这些子请求,pymodbus 提供了一个 class FileRecord 可以用来表示每个子请求。请注意,对于要读取的数据量(253 字节)也有限制,因此您需要确保记录的总长度小于 .

这是示例代码。

import logging

logging.basicConfig()

log = logging.getLogger()
log.setLevel(logging.DEBUG)

from pymodbus.file_message import FileRecord, ReadFileRecordRequest

from pymodbus.client.sync import ModbusSerialClient


client = ModbusSerialClient(method="rtu", port="/dev/ptyp0", baudrate=9600, timeout=2)

records = []
# Create records to be read and append to records
record1 = FileRecord(reference_type=0x06, file_number=0x01, record_number=0x01, record_length=0x01)
records.append(record1)

request = ReadFileRecordRequest(records=records, unit=1)
response = client.execute(request)
if not response.isError():
    # List of Records could be accessed with response.records
    print(response.records)
else:
    # Handle Error
    print(response)

注意。此功能几乎没有经过测试,如果您在使用此功能时遇到任何问题,请随时提出 github 问题。