class ModbusUdpClientProtocol(protocol.DatagramProtocol, ModbusClientMixin): """ This represents the base modbus client protocol. All the application layer code is deferred to a higher level wrapper. """ def __init__(self, framer=None, **kwargs): """ Initializes the framer module :param framer: The framer to use for the protocol """ self.framer = framer or ModbusSocketFramer(ClientDecoder()) if isinstance(self.framer, ModbusSocketFramer): self.transaction = DictTransactionManager(self, **kwargs) else: self.transaction = FifoTransactionManager(self, **kwargs) def datagram_received(self, data, params): """ Get response, check for valid message, decode result :param data: The data returned from the server :param params: The host parameters sending the datagram """ _logger.debug('Datagram from: {0}:{1}'.format(*params)) self.framer.process_incoming_packet(data, self._handle_response) def execute(self, request): """ Starts the producer to send the next request to consumer.write(Frame(request)) """ request.transaction_id = self.transaction.get_next_tid() packet = self.framer.build_packet(request) self.transport.write(packet) return self._build_response(request.transaction_id) def _handle_response(self, reply): """ Handle the processed response and link to correct deferred :param reply: The reply to process """ if reply is not None: tid = reply.transaction_id handler = self.transaction.get_transaction(tid) if handler: handler.callback(reply) else: _logger.debug('Unrequested message: ' + str(reply)) def _build_response(self, tid): """ Helper method to return a deferred response for the current request. :param tid: The transaction identifier for this response :returns: A defer linked to the latest request """ d = defer.Deferred() self.transaction.add_transaction(d, tid) return d
class ModbusUdpClientProtocol(protocol.DatagramProtocol, ModbusClientMixin): """ This represents the base modbus client protocol. All the application layer code is deferred to a higher level wrapper. """ def __init__(self, framer=None, **kwargs): """ Initializes the framer module :param framer: The framer to use for the protocol """ self.framer = framer or ModbusSocketFramer(ClientDecoder()) if isinstance(self.framer, ModbusSocketFramer): self.transaction = DictTransactionManager(self, **kwargs) else: self.transaction = FifoTransactionManager(self, **kwargs) def datagram_received(self, data, params): """ Get response, check for valid message, decode result :param data: The data returned from the server :param params: The host parameters sending the datagram """ _logger.debug('Datagram from: {0}:{1}'.format(*params)) self.framer.process_incoming_packet(data, self._handle_response) def execute(self, request): """ Starts the producer to send the next request to consumer.write(Frame(request)) """ request.transaction_id = self.transaction.get_next_tid() packet = self.framer.build_packet(request) self.transport.write(packet) return self._build_response(request.transaction_id) def _handle_response(self, reply): """ Handle the processed response and link to correct deferred :param reply: The reply to process """ if reply is not None: tid = reply.transaction_id handler = self.transaction.get_transaction(tid) if handler: handler.callback(reply) else: _logger.debug('Unrequested message: ' + str(reply)) def _build_response(self, tid): """ Helper method to return a deferred response for the current request. :param tid: The transaction identifier for this response :returns: A defer linked to the latest request """ d = defer.Deferred() self.transaction.add_transaction(d, tid) return d
def __init__(self, framer, **kwargs): """ Initialize a client instance :param framer: The modbus framer implementation to use """ self.framer = framer if isinstance(self.framer, ModbusSocketFramer): self.transaction = DictTransactionManager(self, **kwargs) else: self.transaction = FifoTransactionManager(self, **kwargs)
def __init__(self, framer=None, **kwargs): """ Initializes the framer module :param framer: The framer to use for the protocol """ self.framer = framer or ModbusSocketFramer(ClientDecoder()) if isinstance(self.framer, ModbusSocketFramer): self.transaction = DictTransactionManager(self, **kwargs) else: self.transaction = FifoTransactionManager(self, **kwargs)
def __init__(self, framer=None, **kwargs): """ Initializes the framer module :param framer: The framer to use for the protocol """ self.framer = framer or ModbusSocketFramer(ClientDecoder()) if isinstance(self.framer, ModbusSocketFramer): self.transaction = DictTransactionManager(self, **kwargs) else: self.transaction = FifoTransactionManager(self, **kwargs)
def __init__(self, framer, **kwargs): """ Initialize a client instance :param framer: The modbus framer implementation to use """ self.framer = framer if isinstance(self.framer, ModbusSocketFramer): self.transaction = DictTransactionManager(self, **kwargs) else: self.transaction = FifoTransactionManager(self, **kwargs)
class BaseModbusClient(ModbusClientMixin): """ Interface for a modbus synchronous client. Defined here are all the methods for performing the related request methods. Derived classes simply need to implement the transport methods and set the correct framer. """ def __init__(self, framer, **kwargs): """ Initialize a client instance :param framer: The modbus framer implementation to use """ self.framer = framer if isinstance(self.framer, ModbusSocketFramer): self.transaction = DictTransactionManager(self, **kwargs) else: self.transaction = FifoTransactionManager(self, **kwargs) # region Client Interface def connect(self): """ Connect to the modbus remote host :returns: True if connection succeeded, False otherwise """ raise NotImplementedError('Method not implemented by derived class') def close(self): """ Closes the underlying socket connection """ pass def send(self, request): """ Sends data on the underlying socket :param request: The encoded request to send :return: The number of bytes written """ raise NotImplementedError('Method not implemented by derived class') def receive(self, size): """ Reads data from the underlying descriptor :param size: The number of bytes to read :return: The bytes read """ raise NotImplementedError('Method not implemented by derived class') # endregion # region Modbus Client Methods def execute(self, request=None): """ :param request: The request to process :returns: The result of the request execution """ if not self.connect(): raise ConnectionException( 'Failed to connect[{0}]'.format(self.__str__()) ) return self.transaction.execute(request) # endregion # region Magic methods def __enter__(self): """ Implement the client with enter block :returns: The current instance of the client """ if not self.connect(): raise ConnectionException( 'Failed to connect[{0}]'.format(self.__str__()) ) return self def __exit__(self, cls, value, traceback): """ Implement the client with exit block """ self.close() def __str__(self): """ Builds a string representation of the connection :returns: The string representation """ return 'Null Transport' # endregion pass
class ModbusClientProtocol(protocol.Protocol, ModbusClientMixin): """ This represents the base modbus client protocol. All the application layer code is deferred to a higher level wrapper. """ def __init__(self, framer=None, **kwargs): """ Initializes the framer module :param framer: The framer to use for the protocol """ self._connected = False self.framer = framer or ModbusSocketFramer(ClientDecoder()) if isinstance(self.framer, ModbusSocketFramer): self.transaction = DictTransactionManager(self, **kwargs) else: self.transaction = FifoTransactionManager(self, **kwargs) def connection_made(self): """ Called upon a successful client connection. """ _logger.debug('Client connected to modbus server') self._connected = True def connection_lost(self, reason): """ Called upon a client disconnect :param reason: The reason for the disconnect """ _logger.debug('Client disconnected from modbus server: ' + str(reason)) self._connected = False for tid in list(self.transaction): self.transaction.get_transaction(tid).errback( Failure(ConnectionException('Connection lost during request')) ) def data_received(self, data): """ Get response, check for valid message, decode result :param data: The data returned from the server """ self.framer.process_incoming_packet(data, self._handle_response) def execute(self, request): """ Starts the producer to send the next request to consumer.write(Frame(request)) """ request.transaction_id = self.transaction.get_next_tid() packet = self.framer.build_packet(request) self.transport.write(packet) return self._build_response(request.transaction_id) def _handle_response(self, reply): """ Handle the processed response and link to correct deferred :param reply: The reply to process """ if reply is not None: tid = reply.transaction_id handler = self.transaction.get_transaction(tid) if handler: handler.callback(reply) else: _logger.debug('Unrequested message: ' + str(reply)) def _build_response(self, tid): """ Helper method to return a deferred response for the current request. :param tid: The transaction identifier for this response :returns: A defer linked to the latest request """ if not self._connected: return defer.fail(Failure( ConnectionException('Client is not connected'))) d = defer.Deferred() self.transaction.add_transaction(d, tid) return d
class ModbusClientProtocol(protocol.Protocol, ModbusClientMixin): """ This represents the base modbus client protocol. All the application layer code is deferred to a higher level wrapper. """ def __init__(self, framer=None, **kwargs): """ Initializes the framer module :param framer: The framer to use for the protocol """ self._connected = False self.framer = framer or ModbusSocketFramer(ClientDecoder()) if isinstance(self.framer, ModbusSocketFramer): self.transaction = DictTransactionManager(self, **kwargs) else: self.transaction = FifoTransactionManager(self, **kwargs) def connection_made(self): """ Called upon a successful client connection. """ _logger.debug('Client connected to modbus server') self._connected = True def connection_lost(self, reason): """ Called upon a client disconnect :param reason: The reason for the disconnect """ _logger.debug('Client disconnected from modbus server: ' + str(reason)) self._connected = False for tid in list(self.transaction): self.transaction.get_transaction(tid).errback( Failure(ConnectionException('Connection lost during request'))) def data_received(self, data): """ Get response, check for valid message, decode result :param data: The data returned from the server """ self.framer.process_incoming_packet(data, self._handle_response) def execute(self, request): """ Starts the producer to send the next request to consumer.write(Frame(request)) """ request.transaction_id = self.transaction.get_next_tid() packet = self.framer.build_packet(request) self.transport.write(packet) return self._build_response(request.transaction_id) def _handle_response(self, reply): """ Handle the processed response and link to correct deferred :param reply: The reply to process """ if reply is not None: tid = reply.transaction_id handler = self.transaction.get_transaction(tid) if handler: handler.callback(reply) else: _logger.debug('Unrequested message: ' + str(reply)) def _build_response(self, tid): """ Helper method to return a deferred response for the current request. :param tid: The transaction identifier for this response :returns: A defer linked to the latest request """ if not self._connected: return defer.fail( Failure(ConnectionException('Client is not connected'))) d = defer.Deferred() self.transaction.add_transaction(d, tid) return d
class BaseModbusClient(ModbusClientMixin): """ Interface for a modbus synchronous client. Defined here are all the methods for performing the related request methods. Derived classes simply need to implement the transport methods and set the correct framer. """ def __init__(self, framer, **kwargs): """ Initialize a client instance :param framer: The modbus framer implementation to use """ self.framer = framer if isinstance(self.framer, ModbusSocketFramer): self.transaction = DictTransactionManager(self, **kwargs) else: self.transaction = FifoTransactionManager(self, **kwargs) # region Client Interface def connect(self): """ Connect to the modbus remote host :returns: True if connection succeeded, False otherwise """ raise NotImplementedError('Method not implemented by derived class') def close(self): """ Closes the underlying socket connection """ pass def send(self, request): """ Sends data on the underlying socket :param request: The encoded request to send :return: The number of bytes written """ raise NotImplementedError('Method not implemented by derived class') def receive(self, size): """ Reads data from the underlying descriptor :param size: The number of bytes to read :return: The bytes read """ raise NotImplementedError('Method not implemented by derived class') # endregion # region Modbus Client Methods def execute(self, request=None): """ :param request: The request to process :returns: The result of the request execution """ if not self.connect(): raise ConnectionException('Failed to connect[{0}]'.format( self.__str__())) return self.transaction.execute(request) # endregion # region Magic methods def __enter__(self): """ Implement the client with enter block :returns: The current instance of the client """ if not self.connect(): raise ConnectionException('Failed to connect[{0}]'.format( self.__str__())) return self def __exit__(self, cls, value, traceback): """ Implement the client with exit block """ self.close() def __str__(self): """ Builds a string representation of the connection :returns: The string representation """ return 'Null Transport' # endregion pass