@@ -92,6 +92,7 @@ def __init__(self, owner):
9292 self .running = False
9393 self .receive_queue = asyncio .Queue ()
9494 self .handler_task = None # coroutine to be run on asyncio loop
95+ self ._sent = b"" # for handle_local_echo
9596
9697 def _log_exception (self ):
9798 """Show log exception."""
@@ -450,6 +451,19 @@ def connection_lost(self, call_exc):
450451
451452 def data_received (self , data ):
452453 """Receive data."""
454+ if (
455+ hasattr (self .server , "handle_local_echo" )
456+ and self .server .handle_local_echo is True
457+ and self ._sent
458+ ):
459+ if self ._sent in data :
460+ data , self ._sent = data .replace (self ._sent , b"" , 1 ), b""
461+ elif self ._sent .startswith (data ):
462+ self ._sent , data = self ._sent .replace (data , b"" , 1 ), b""
463+ else :
464+ self ._sent = b""
465+ if not data :
466+ return
453467 self .receive_queue .put_nowait (data )
454468
455469 async def _recv_ (self ):
@@ -458,6 +472,11 @@ async def _recv_(self):
458472 def _send_ (self , data ):
459473 if self .transport is not None :
460474 self .transport .write (data )
475+ if (
476+ hasattr (self .server , "handle_local_echo" )
477+ and self .server .handle_local_echo is True
478+ ):
479+ self ._sent = data
461480
462481
463482# --------------------------------------------------------------------------- #
@@ -758,7 +777,7 @@ async def server_close(self):
758777 self .protocol = None
759778
760779
761- class ModbusSerialServer :
780+ class ModbusSerialServer : # pylint: disable=too-many-instance-attributes
762781 """A modbus threaded serial socket server.
763782
764783 We inherit and overload the socket server so that we
@@ -784,6 +803,7 @@ def __init__(
784803 :param parity: Which kind of parity to use
785804 :param baudrate: The baud rate to use for the serial device
786805 :param timeout: The timeout to use for the serial device
806+ :param handle_local_echo: (optional) Discard local echo from dongle.
787807 :param ignore_missing_slaves: True to not send errors on a request
788808 to a missing slave
789809 :param broadcast_enable: True to treat unit_id 0 as broadcast address,
@@ -800,6 +820,9 @@ def __init__(
800820 self .timeout = kwargs .get ("timeout" , Defaults .Timeout )
801821 self .device = kwargs .get ("port" , 0 )
802822 self .stopbits = kwargs .get ("stopbits" , Defaults .Stopbits )
823+ self .handle_local_echo = kwargs .get (
824+ "handle_local_echo" , Defaults .HandleLocalEcho
825+ )
803826 self .ignore_missing_slaves = kwargs .get (
804827 "ignore_missing_slaves" , Defaults .IgnoreMissingSlaves
805828 )
0 commit comments