ljean / modbus-tk

Create Modbus app easily with Python
Other
569 stars 213 forks source link

Make sure struct.unpack will work even when there are ascii in bytearray #148

Closed an3l closed 2 years ago

an3l commented 3 years ago

Read string: logger.info(master.execute(1, cst.READ_HOLDING_REGISTERS, 49, 3,data_format='>s'))

Example of generated error:

2021-04-25 11:10:12,072 DEBUG   modbus.execute  MainThread      -> 1-3-0-49-0-3-84-4
2021-04-25 11:10:12,101 DEBUG   modbus.execute  MainThread      <- 1-3-6-80-77-50-50-50-48-187-40
bytearray(b'\x03\x06PM2220')
Traceback (most recent call last):
  File "rtu_master_example_anel.py", line 59, in <module>
    main()
  File "rtu_master_example_anel.py", line 44, in main
    logger.info(master.execute(1, cst.READ_HOLDING_REGISTERS, 49, 3,data_format='>s'))
  File "C:\Users\B.I.O.S. S\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\modbus_tk\utils.py", line 39, in new
    raise excpt
  File "C:\Users\B.I.O.S. S\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\modbus_tk\utils.py", line 37, in new
    ret = fcn(*args, **kwargs)
  File "C:\Users\B.I.O.S. S\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\modbus_tk\modbus.py", line 338, in execute
    result = struct.unpack(data_format, data)
struct.error: unpack requires a buffer of 1 bytes

Result of the patch:

2021-04-25 11:11:26,398 DEBUG   modbus.execute  MainThread      -> 1-3-0-49-0-3-84-4
2021-04-25 11:11:26,449 DEBUG   modbus.execute  MainThread      <- 1-3-6-80-77-50-50-50-48-187-40
bytearray(b'\x03\x06PM2220')
2021-04-25 11:11:26,450 INFO    rtu_master_example_anel.main    MainThread      PM2220