Search code examples
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), its 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 amount of data to be read (253 bytes), so you will need to ensure the total length of your records is less that that .

    Here is a sample code .

    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)
    

    Note. This feature is hardly tested, If you come across any issues with using this features, please feel free to raise a github issue.