pythonmodbus

Python modbus lib for reading file record


Is there a python modbus lib which implements the functions for reading and writting file records (function codes: 20, 21). The popular Python modbus libraries (pymodbus, pymodbusTCP) provision these functions but do not implement them. Thank you.


Solution

  • Pymodbus does support ReadFileRecordRequest (0x14). It's a bit tricky to use; the request expects a list of records to be queried as part of its payload. Each record is a sub-request with the following attributes:

    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.

    To facilitate the creation of these sub-requests, pymodbus offers a class FileRecord which could be used to represent each sub-request. Note that there is also a restriction on the amount of data to be read (253 bytes), so you will need to ensure the total length of your records is less than that.

    Here is sample code:

    import logging
    import sys
    
    from pymodbus.client.sync import ModbusSerialClient
    from pymodbus.pdu.file_message import FileRecord, ReadFileRecordRequest
    
    logging.basicConfig()
    log = logging.getLogger()
    log.setLevel(logging.DEBUG)
    
    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 response.isError():
        # Handle Error
        print(response, file=sys.stderr)
    else:
        # List of Records can be accessed as response.records
        print(response.records)
    

    Note. This feature is hardly tested. If you come across any issues with using this features, you should raise a GitHub issue.