66from binascii import b2a_hex
77from twisted .internet import protocol
88from twisted .internet .protocol import ServerFactory
9+ from twisted .internet import reactor
910
1011from pymodbus .constants import Defaults
1112from pymodbus .factory import ServerDecoder
1819from pymodbus .pdu import ModbusExceptions as merror
1920from pymodbus .internal .ptwisted import InstallManagementConsole
2021from pymodbus .compat import byte2int
21- from twisted . internet import reactor
22+ from pymodbus . compat import IS_PYTHON3
2223
2324#---------------------------------------------------------------------------#
2425# Logging
@@ -204,6 +205,21 @@ def _send(self, message, addr):
204205#---------------------------------------------------------------------------#
205206# Starting Factories
206207#---------------------------------------------------------------------------#
208+ def _is_main_thread ():
209+ import threading
210+
211+ if IS_PYTHON3 :
212+ if threading .current_thread () != threading .main_thread ():
213+ _logger .debug ("Starting in spawned thread" )
214+ return False
215+ else :
216+ if not isinstance (threading .current_thread (), threading ._MainThread ):
217+ _logger .debug ("Starting in spawned thread" )
218+ return False
219+ _logger .debug ("Starting in Main thread" )
220+ return True
221+
222+
207223def StartTcpServer (context , identity = None , address = None , console = False , ** kwargs ):
208224 ''' Helper method to start the Modbus Async TCP server
209225
@@ -223,7 +239,7 @@ def StartTcpServer(context, identity=None, address=None, console=False, **kwargs
223239
224240 _logger .info ("Starting Modbus TCP Server on %s:%s" % address )
225241 reactor .listenTCP (address [1 ], factory , interface = address [0 ])
226- reactor .run ()
242+ reactor .run (installSignalHandlers = _is_main_thread () )
227243
228244
229245def StartUdpServer (context , identity = None , address = None , ** kwargs ):
@@ -242,7 +258,7 @@ def StartUdpServer(context, identity=None, address=None, **kwargs):
242258
243259 _logger .info ("Starting Modbus UDP Server on %s:%s" % address )
244260 reactor .listenUDP (address [1 ], server , interface = address [0 ])
245- reactor .run ()
261+ reactor .run (installSignalHandlers = _is_main_thread () )
246262
247263
248264def StartSerialServer (context , identity = None ,
@@ -272,7 +288,7 @@ def StartSerialServer(context, identity=None,
272288 protocol = factory .buildProtocol (None )
273289 SerialPort .getHost = lambda self : port # hack for logging
274290 SerialPort (protocol , port , reactor , baudrate )
275- reactor .run ()
291+ reactor .run (installSignalHandlers = _is_main_thread () )
276292
277293#---------------------------------------------------------------------------#
278294# Exported symbols
0 commit comments