ljean / modbus-tk

Create Modbus app easily with Python
Other
566 stars 212 forks source link

Modbus RTU over TCP #115

Closed travijuu closed 4 years ago

travijuu commented 5 years ago

Hello, In our case, we need to read modbus device(irradiation sensor) over Moxa NPort 5150. Our device connected to Moxa via TCP and Moxa connected to irradiation sensor over RTU. Moxa is a bridge in here. We need to make RTU request over TCP. However, I couldn't find this feature in modbus-tk. How can I achieve? This feature exists in pymodbus by using framer=ModbusRtuFramer. You can check from the link.

https://stackoverflow.com/a/53431738/1645480

sfcaracciolo commented 4 years ago

I have same problem!

travijuu commented 4 years ago

@sfcaracciolo We created a simple working solution for this. You can try if you want.

from modbus_tk import utils
from modbus_tk.modbus_rtu import RtuQuery
from modbus_tk.modbus_tcp import TcpMaster

class RtuOverTcpMaster(TcpMaster):

    def _make_query(self):
        return RtuQuery()

    def _recv(self, expected_length=-1):
        response = utils.to_data('')
        length = 255
        while len(response) < length:
            rcv_byte = self._sock.recv(1)
            if rcv_byte:
                response += rcv_byte
            if expected_length >= 0 and len(response) >= expected_length:
                break
        return response
sfcaracciolo commented 4 years ago

@travijuu Thank you very much! It works excellent :)

ljean commented 4 years ago

Hello @travijuu Thanks for your answer and for this piece of code. Would you be ok to add it to the project? I let you create a PR if you are ok. Thanks Best luc

pepe12311 commented 3 years ago

You would need an example of how to implement RTU over TCP communication. I have something done in tcp, but I have to modify it. Do you have an example? Greetings