AdvancedClimateSystems / uModbus

Python implementation of the Modbus protocol.
Mozilla Public License 2.0
213 stars 83 forks source link

Add easy to use client wrapper for doing Modbus RTU and Modbus TCP/IP requests. #39

Open OrangeTux opened 8 years ago

OrangeTux commented 8 years ago

It requires quite a lot of code to do a Modbus request, see below. This could be wrapped easily in a simple wrapper.

#!/usr/bin/env python
# scripts/examples/simple_tcp_client.py
import socket

from umodbus import conf
from umodbus.client import tcp

# Enable values to be signed (default is False).
conf.SIGNED_VALUES = True

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(('localhost', 502))

# Returns a message or Application Data Unit (ADU) specific for doing
# Modbus TCP/IP.
message = tcp.write_multiple_coils(slave_id=1, starting_address=1, values=[1, 0, 1, 1])

# Response depends on Modbus function code. This particular returns the
# amount of coils written, in this case it is.
response = tcp.send_message(message, sock)

sock.close()

A solution should look something like this:

with tcp.Client('localhost', 502) as c:
    resp = c.read_holding_registers(slave_id=1,starting_address=1, quantity=3)