Skip to content

Instantly share code, notes, and snippets.

@dews
Created April 9, 2019 06:38
Show Gist options
  • Save dews/ae8a4fd97262e4f253046d0af714439c to your computer and use it in GitHub Desktop.
Save dews/ae8a4fd97262e4f253046d0af714439c to your computer and use it in GitHub Desktop.
ModbusClient.py
#!/usr/bin/env python
"""
Pymodbus Synchronous Client Examples
--------------------------------------------------------------------------
The following is an example of how to use the synchronous modbus client
implementation from pymodbus.
It should be noted that the client can also be used with
the guard construct that is available in python 2.5 and up::
with ModbusClient('127.0.0.1') as client:
result = client.read_coils(1,10)
print result
"""
# --------------------------------------------------------------------------- #
# import the various server implementations
# --------------------------------------------------------------------------- #
# from pymodbus.client.sync import ModbusTcpClient as ModbusClient
# from pymodbus.client.sync import ModbusUdpClient as ModbusClient
from pymodbus.client.sync import ModbusSerialClient as ModbusClient
# --------------------------------------------------------------------------- #
# configure the client logging
# --------------------------------------------------------------------------- #
import logging
FORMAT = ('%(asctime)-15s %(threadName)-15s '
'%(levelname)-8s %(module)-15s:%(lineno)-8s %(message)s')
logging.basicConfig(format=FORMAT)
log = logging.getLogger()
log.setLevel(logging.DEBUG)
UNIT = 0x1
def run_sync_client():
client = ModbusClient(method='rtu', port='/dev/cu.wchusbserial14310', timeout=1,
baudrate=9600, stopbits=2)
client.connect()
log.debug("Read registeres")
rr = client.read_holding_registers(0, 8, unit=UNIT)
log.info(rr.registers[0]) # test the expected value
# ----------------------------------------------------------------------- #
# close the client
# ----------------------------------------------------------------------- #
client.close()
if __name__ == "__main__":
run_sync_client()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment