Skip to content

Commit

Permalink
Merge pull request #39 from eode/master
Browse files Browse the repository at this point in the history
Add support for pymodbus 3.x.x
  • Loading branch information
graham22 authored Jan 24, 2024
2 parents 2df5c47 + d3dc1a3 commit 046bd18
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 6 deletions.
5 changes: 4 additions & 1 deletion code/Python/classic_mqtt.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
#!/usr/bin/python3

from pymodbus.client.sync import ModbusTcpClient as ModbusClient
try:
from pymodbus.client import ModbusTcpClient as ModbusClient # pymodbus 3
except ImportError:
from pymodbus.client.sync import ModbusTcpClient as ModbusClient # pymodbus 2
from paho.mqtt import client as mqttclient
from collections import OrderedDict
import json
Expand Down
20 changes: 15 additions & 5 deletions code/Python/support/classic_modbusdecoder.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,12 @@

from pymodbus.constants import Endian
from pymodbus.payload import BinaryPayloadDecoder
from pymodbus.client.sync import ModbusTcpClient as ModbusClient
from pymodbus.compat import iteritems
try:
from pymodbus.client import ModbusTcpClient as ModbusClient
MODBUS_VERSION = 3
except ImportError:
from pymodbus.client.sync import ModbusTcpClient as ModbusClient
MODBUS_VERSION = 2
from collections import OrderedDict
import logging
import sys
Expand All @@ -22,7 +26,10 @@
# --------------------------------------------------------------------------- #
def getRegisters(theClient, addr, count):
try:
result = theClient.read_holding_registers(addr, count, unit=10)
if MODBUS_VERSION == 2:
result = theClient.read_holding_registers(addr, count, unit=10)
else:
result = theClient.read_holding_registers(addr, count, slave=10)
if result.function_code >= 0x80:
log.error("error getting {} for {} bytes".format(addr, count))
return {}
Expand Down Expand Up @@ -160,11 +167,14 @@ def getModbusData(modeAwake, classicHost, classicPort):
log.debug("Opening the modbus Connection")
if modbusClient is None:
modbusClient = ModbusClient(host=classicHost, port=classicPort)

#Test for successful connect, if not, log error and mark modbusConnected = False
modbusClient.connect()

result = modbusClient.read_holding_registers(4163, 2, unit=10)
if MODBUS_VERSION == 2:
result = modbusClient.read_holding_registers(4163, 2, unit=10)
else:
result = modbusClient.read_holding_registers(4163, 2, slave=10)
if result.isError():
# close the client
log.error("MODBUS isError H:{} P:{}".format(classicHost, classicPort))
Expand Down

0 comments on commit 046bd18

Please sign in to comment.