Created
July 16, 2013 09:37
-
-
Save Edke/6007273 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import socket | |
import select | |
from pymodbus.client.sync import ModbusTcpClient, _logger | |
from pymodbus.constants import Defaults | |
from pymodbus.exceptions import ConnectionException | |
class ModbusTcpClientBlocking(ModbusTcpClient): | |
def connect(self): | |
""" | |
Connect to the modbus tcp server | |
:returns: True if connection succeeded, False otherwise | |
""" | |
if self.socket: | |
return True | |
try: | |
self.socket = socket.create_connection((self.host, self.port), Defaults.Timeout) | |
except socket.error, msg: | |
_logger.error('Connection to (%s, %s) failed: %s' % (self.host, self.port, msg)) | |
self.close() | |
return self.socket is not None | |
def _recv(self, size): | |
""" | |
Reads data from the underlying descriptor | |
:param size: The number of bytes to read | |
:return: The bytes read | |
""" | |
_logger.info('Receiving data with length: %s' % size) | |
if not self.socket: | |
raise ConnectionException(self.__str__()) | |
data = '' | |
while len(data) < size: | |
try: | |
chunk = self.socket.recv(size-len(data)) | |
_logger.info('Received chunk: 0x%s with length: %s' % (chunk.encode('hex'), len(chunk))) | |
except socket.timeout: | |
_logger.error('Giving up, timeout ...') | |
break | |
if chunk == '': | |
_logger.error('Socket connection broken') | |
return False | |
data = data + chunk | |
if len(data) > 0: | |
_logger.info('Complete data: 0x%s with length: %s' % (data.encode('hex'), len(data))) | |
return data |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment