1

I am trying to read Modbus TCP data over my AWS cloud EC2 instance. As I have one machine which is generating MODBUS TCP(Slave) data and sending it to Cloud. And at cloud I'm receiving data using TCP server program written in python using socket. Following is my receiving code which is running on EC2 instance:

import socket

bind_ip = '13.2x4.29.18x' #is my instance Public IPv4   
bind_port = 45000

server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((bind_ip, bind_port))
server.listen(5)  # max backlog of connections

print('Listening on {}:{}'.format(bind_ip, bind_port))


def handle_client_connection(client_socket):
    request = client_socket.recv(1024)
    x=str(request)
    print("Received Data:",x)
    client_socket.close()
try:
    while True:
        client_sock, address = server.accept()
        print('Accepted connection from {}:{}'.format(address[0], address[1]))
        client_handler = threading.Thread(
            target=handle_client_connection,
            args=(client_sock,)  
            )
        client_handler.start()
except KeyboardInterrupt as e:
    print("Connection Terminated")

And this what I am receiving after running above code:

b'\x00\x00\x00\x00\x00\x06\x01\x03\x00\x00\x00\n'

Desired Output is:

0001 0000 0009 11 03 06 022B 0064 007F # According to Modbus TCP packet

Now I want parse this message in readable format and separate out register data. What I have tried as of now is python struct unpack,

import struct
data = bytearray(b'\x00\x00\x00\x00\x00\x06\x01\x03\x00\x00\x00\n')
number = struct.unpack("<d", data)

But here in above code I am getting this error:

struct.error: unpack requires a bytes object of length 8

Then I tried pymodbus message parser and minimalmodbus decoding method. I tried many possible solution, but couldn't fetch one. Or may be I was doing wrong.

So how can I achieve this? And what are the possible solution for this?

Shriniwas
  • 664
  • 3
  • 11
  • 25
  • 1
    What is the type of your data (how many bytes)? Did you try by `" – Benyamin Jafari Apr 01 '19 at 17:26
  • @BenyaminJafari Ohkay. As you can see above at desired output (according to Modbus TCP packet format), Its 2 2 2 1 1 1 2 2 2 in bytes respectively. So I tried this struct.unpack('HHHBBBHHH', data) and I got output in decimals. In this case I knew how many registers I am reading or receiving but in case of uknown number register how I am gonna unpack the register values? – Shriniwas Apr 01 '19 at 19:18
  • what is stopping you from directly using pymodbus or any other python modules supporting Modbus TCP ? That could save you a lot of trouble with parsing the incoming data. Pymodbus comes up with both sync and async client implementations and rich [payload decoders](https://pymodbus.readthedocs.io/en/latest/source/library/pymodbus.html#pymodbus.payload.BinaryPayloadDecoder) to parse the incoming data to desired data type. – Sanju Apr 02 '19 at 07:29

0 Answers0