Help completing Python Modbus-readout script

Hello all,

I’m busy with something for more than 4 evenings now, and I don’t get any further. I hope somebody can help me.
I have an inverter for solar-energy which ‘speaks’ Modbus. It is possible to connect to the inverter using Modbus in OpenHAB, but this makes all my modes devices extremely slow. To solve this, I’d decided to create a separate Python-script to read out some Modbus-registers and post this values to OpenHAB using the REST interface.

By using a separate ‘Modbus client program’ I succeeded requesting and reading the necessary Modbus registers in the inverter. With Wireshark I find the HEX to do a request for one of the registers;

With this information I was able to write the next script;

import socket
import struct
import time
 
# Create a TCP/IP socket
TCP_IP = '10.0.1.41'
TCP_PORT = 502
BUFFER_SIZE = 50
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((TCP_IP, TCP_PORT))
 
try:
    req = struct.pack('12B', 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x01, 0x03, 0x9c, 0x41, 0x00, 0x01)
    print("Socket requested value: ", req)
    sock.send(req)
    rec = sock.recv(1024)
    print("Socket returned value: ", rec)

finally:
    print('\nCLOSING SOCKET')
    sock.close()

When running the script, it looks like this;

As you can see, the returned value ends with ‘x02nS’. When I look with Wireshark, I can see the value ‘28243’ which I actualy need, I can also see the HEX-code and I even see this ‘nS-value’.

I’d like to have the ‘28243-value’ printed on my screen, but whatever I tried… no success. Does anybody have a idea what I’m doing wrong?

Thanks in advance,

Regards Jaco

I’d start by using a Python MODBUS library (e.g. pymodbus) instead of hand-coding the MODBUS protocol.

Take a look at this:
https://pymodbus.readthedocs.io/en/latest/

I have used it in several test-projects at work, and I find that it gets the job done very nicely.

Not an answer to your question, but -

That probably means you had a simple configuration problem invoking timeout errors. ‘Good’ modbus transfers are over in milliseconds.