Skip to content

Commit

Permalink
Keep 3.5 char delay between serial RTU frames
Browse files Browse the repository at this point in the history
  • Loading branch information
Cougar committed Aug 15, 2014
1 parent 727f8e2 commit 9044524
Showing 1 changed file with 17 additions and 2 deletions.
19 changes: 17 additions & 2 deletions pymodbus/client/sync.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import socket
import serial
import time

from pymodbus.constants import Defaults
from pymodbus.factory import ClientDecoder
Expand Down Expand Up @@ -328,6 +329,8 @@ def connect(self):
except serial.SerialException, msg:
_logger.error(msg)
self.close()
self._last_frame_end = time.time()
self._silent_interval = 3.5 * (1 + 8 + 2) / self.baudrate
return self.socket != None

def close(self):
Expand All @@ -342,12 +345,20 @@ def _send(self, request):
If receive buffer still holds some data then flush it.
Sleep if last send finished less than 3.5 character
times ago.
:param request: The encoded request to send
:return: The number of bytes written
'''
if not self.socket:
raise ConnectionException(self.__str__())
if request:
ts = time.time()
if ts < self._last_frame_end + self._silent_interval:
_logger.debug("will sleep to wait for 3.5 char")
time.sleep(self._last_frame_end + self._silent_interval - ts)

try:
waitingbytes = self.socket.inWaiting()
if waitingbytes:
Expand All @@ -357,7 +368,9 @@ def _send(self, request):
except NotImplementedError:
pass

return self.socket.write(request)
size = self.socket.write(request)
self._last_frame_end = time.time()
return size
return 0

def _recv(self, size):
Expand All @@ -368,7 +381,9 @@ def _recv(self, size):
'''
if not self.socket:
raise ConnectionException(self.__str__())
return self.socket.read(size)
result = self.socket.read(size)
self._last_frame_end = time.time()
return result

def __str__(self):
''' Builds a string representation of the connection
Expand Down

0 comments on commit 9044524

Please sign in to comment.