Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 20 additions & 4 deletions pymodbus/server/async.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
from binascii import b2a_hex
from twisted.internet import protocol
from twisted.internet.protocol import ServerFactory
from twisted.internet import reactor

from pymodbus.constants import Defaults
from pymodbus.factory import ServerDecoder
Expand All @@ -18,7 +19,7 @@
from pymodbus.pdu import ModbusExceptions as merror
from pymodbus.internal.ptwisted import InstallManagementConsole
from pymodbus.compat import byte2int
from twisted.internet import reactor
from pymodbus.compat import IS_PYTHON3

#---------------------------------------------------------------------------#
# Logging
Expand Down Expand Up @@ -204,6 +205,21 @@ def _send(self, message, addr):
#---------------------------------------------------------------------------#
# Starting Factories
#---------------------------------------------------------------------------#
def _is_main_thread():
import threading

if IS_PYTHON3:
if threading.current_thread() != threading.main_thread():
_logger.debug("Starting in spawned thread")
return False
else:
if not isinstance(threading.current_thread(), threading._MainThread):
_logger.debug("Starting in spawned thread")
return False
_logger.debug("Starting in Main thread")
return True


def StartTcpServer(context, identity=None, address=None, console=False, **kwargs):
''' Helper method to start the Modbus Async TCP server

Expand All @@ -223,7 +239,7 @@ def StartTcpServer(context, identity=None, address=None, console=False, **kwargs

_logger.info("Starting Modbus TCP Server on %s:%s" % address)
reactor.listenTCP(address[1], factory, interface=address[0])
reactor.run()
reactor.run(installSignalHandlers=_is_main_thread())


def StartUdpServer(context, identity=None, address=None, **kwargs):
Expand All @@ -242,7 +258,7 @@ def StartUdpServer(context, identity=None, address=None, **kwargs):

_logger.info("Starting Modbus UDP Server on %s:%s" % address)
reactor.listenUDP(address[1], server, interface=address[0])
reactor.run()
reactor.run(installSignalHandlers=_is_main_thread())


def StartSerialServer(context, identity=None,
Expand Down Expand Up @@ -272,7 +288,7 @@ def StartSerialServer(context, identity=None,
protocol = factory.buildProtocol(None)
SerialPort.getHost = lambda self: port # hack for logging
SerialPort(protocol, port, reactor, baudrate)
reactor.run()
reactor.run(installSignalHandlers=_is_main_thread())

#---------------------------------------------------------------------------#
# Exported symbols
Expand Down