用于读取文件记录的Python modbus lib

2024-04-24 09:03:30 发布

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

是否有python modbus lib实现读写文件记录的功能(功能代码:20、21)。流行的Python-modbus库(pymodbus,pymodbusTCP)提供了这些功能,但没有实现它们。谢谢您。在


Tags: 文件代码功能lib记录modbuspymodbuspymodbustcp
1条回答
网友
1楼 · 发布于 2024-04-24 09:03:30

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提供了一个类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问题。在

相关问题 更多 >