pymodbus: request creation and response receiving

2019-03-01 21:52发布

Can anyone explain how to create the request and get the response in right way using pymodbus via Modbus TCP/IP?

I have the PLC wich I want to use as slave and PC - as master.

I trying to do it in such way:

from pymodbus.client.sync import ModbusTcpClient

host = '192.168.56.9'
port = 502   

client = ModbusTcpClient(host, port)
client.connect()

#Register address 0x102A (4138dec) with a word count of 1
#Value - MODBUS/TCP Connections
#Access - Read
#Description - Number of TCP connections

request = client.read_holding_registers(4138, 1) 
response = client.execute(request)

print response

>>> ReadRegisterResponse (1)

2条回答
Ridiculous、
2楼-- · 2019-03-01 22:06

Set the unit argument and use the print(request.registers) instead of print(request).

Here's an example:

request = client.read_holding_registers(4138, 1, unit=1)  # Notice: Set the unit argument.

if not request.isError():
    '''isError() method implemented in pymodbus 1.4.0 and above'''

    result = request.registers  # Your problem is here.
    print(result)

else:
    # Handle Error.
    print('Unable to read or there is the connection problem.')
查看更多
3楼-- · 2019-03-01 22:07

You could execute dir(response) to check what the response is composed of but if pymodbus TCP master is similar to RTU serial master implementation then the data is available in Registers field so try to print response.Registers instead of response. The response.Registers should be a one-element array containing the value of register your requested for reading.

查看更多
登录 后发表回答