11import logging
22from classes .protocol_settings import Registry_Type , protocol_settings
3- from pymodbus .client .sync import ModbusSerialClient
3+
4+ import inspect
5+
6+
7+ try :
8+ from pymodbus .client .sync import ModbusSerialClient
9+ except ImportError :
10+ from pymodbus .client import ModbusSerialClient
11+
412from .modbus_base import modbus_base
513from configparser import SectionProxy
614from defs .common import find_usb_serial_port , get_usb_serial_port_info , strtoint
@@ -11,6 +19,8 @@ class modbus_rtu(modbus_base):
1119 baudrate : int = 9600
1220 client : ModbusSerialClient
1321
22+ pymodbus_slave_arg = 'unit'
23+
1424 def __init__ (self , settings : SectionProxy , protocolSettings : protocol_settings = None ):
1525 #logger = logging.getLogger(__name__)
1626 #logging.basicConfig(level=logging.DEBUG)
@@ -33,16 +43,34 @@ def __init__(self, settings : SectionProxy, protocolSettings : protocol_settings
3343 address : int = settings .getint ("address" , 0 )
3444 self .addresses = [address ]
3545
36- self .client = ModbusSerialClient (method = 'rtu' , port = self .port ,
37- baudrate = int (self .baudrate ),
38- stopbits = 1 , parity = 'N' , bytesize = 8 , timeout = 2
39- )
46+ # pymodbus compatability; unit was renamed to address
47+ if 'slave' in inspect .signature (ModbusSerialClient .read_holding_registers ).parameters :
48+ self .pymodbus_slave_arg = 'slave'
49+
50+
51+ # Get the signature of the __init__ method
52+ init_signature = inspect .signature (ModbusSerialClient .__init__ )
53+
54+ if 'method' in init_signature .parameters :
55+ self .client = ModbusSerialClient (method = 'rtu' , port = self .port ,
56+ baudrate = int (self .baudrate ),
57+ stopbits = 1 , parity = 'N' , bytesize = 8 , timeout = 2
58+ )
59+ else :
60+ self .client = ModbusSerialClient (port = self .port ,
61+ baudrate = int (self .baudrate ),
62+ stopbits = 1 , parity = 'N' , bytesize = 8 , timeout = 2
63+ )
4064
4165 def read_registers (self , start , count = 1 , registry_type : Registry_Type = Registry_Type .INPUT , ** kwargs ):
4266
4367 if 'unit' not in kwargs :
4468 kwargs = {'unit' : int (self .addresses [0 ]), ** kwargs }
4569
70+ #compatability
71+ if self .pymodbus_slave_arg != 'unit' :
72+ kwargs ['slave' ] = kwargs .pop ('unit' )
73+
4674 if registry_type == Registry_Type .INPUT :
4775 return self .client .read_input_registers (start , count , ** kwargs )
4876 elif registry_type == Registry_Type .HOLDING :
@@ -55,6 +83,10 @@ def write_register(self, register : int, value : int, **kwargs):
5583 if 'unit' not in kwargs :
5684 kwargs = {'unit' : self .addresses [0 ], ** kwargs }
5785
86+ #compatability
87+ if self .pymodbus_slave_arg != 'unit' :
88+ kwargs ['slave' ] = kwargs .pop ('unit' )
89+
5890 self .client .write_register (register , value , ** kwargs ) #function code 0x06 writes to holding register
5991
6092 def connect (self ):
0 commit comments