def __init__(self, client, timeout=2): self.client = client self.decoder = ClientDecoder() self.framer = ModbusSocketFramer(self.decoder, client=self) self._ack_waiter: Optional[asyncio.Future[None]] = None self.transaction = DictTransactionManager(self) self.timeout = timeout
def __init__(self, framer, **kwargs): """ Initialize a client instance :param framer: The modbus framer implementation to use """ self.framer = framer self.transaction = DictTransactionManager(self, **kwargs) self._debug = False self._debugfd = None self.broadcast_enable = kwargs.get('broadcast_enable', Defaults.broadcast_enable)
class ModbusOverQuicClientProtocol(ModbusClientMixin): def __init__(self, client, timeout=2): self.client = client self.decoder = ClientDecoder() self.framer = ModbusSocketFramer(self.decoder, client=self) self._ack_waiter: Optional[asyncio.Future[None]] = None self.transaction = DictTransactionManager(self) self.timeout = timeout # BaseModbusAsyncClientProtocol::execute async def execute(self, request=None): req = self._execute(request) resp = await asyncio.wait_for(req, timeout=self.timeout) return resp # BaseModbusAsyncClientProtocol::_execute def _execute(self, request): # Build Framer Packet request.transaction_id = self.transaction.getNextTID() packet = self.framer.buildPacket(message=request) logger.debug("send: " + hexlify_packets(packet)) # Send packet through QUIC self.send(packet) # Get response waiter = self.client._loop.create_future() self.transaction.addTransaction(waiter, request.transaction_id) self._ack_waiter = waiter self.client.transmit() return waiter def send(self, data): self.client.send(data) def dataReceived(self, data): logger.debug("recv: " + hexlify_packets(data)) unit = self.framer.decode_data(data=data).get("unit", 0) self.framer.processIncomingPacket(data, self._handleResponse, unit=unit) def _handleResponse(self, reply): if reply is not None: tid = reply.transaction_id handler = self.transaction.getTransaction(tid) if handler: self.resolve_future(handler, reply) else: logger.debug("Unrequested message: " + str(reply)) def resolve_future(self, f, result): if not f.done(): f.set_result(result)
def __init__(self, framer=None, **kwargs): self._connected = False self.framer = framer or ModbusSocketFramer(ClientDecoder()) if isinstance(self.framer, type): # Framer class not instance self.framer = self.framer(ClientDecoder(), client=None) 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)
def __init__(self, framer=None): ''' 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) else: self.transaction = FifoTransactionManager(self)
def __init__(self, framer=None, **kwargs): """ Initializes the framer module :param framer: The framer to use for the protocol """ deprecated(self.__class__.__name__) 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) self._debug = False self._debugfd = None
def connectionMade(self): # 初始化Framer self.framer = self.factory.framer # 初始化TransactionT if isinstance(self.framer, ModbusSocketFramer): self.transaction = DictTransactionManager(self) else: self.transaction = FifoTransactionManager(self) self._addr = '%s:%d' % (self.transport.getPeer().host, self.transport.getPeer().port) self.factory.addClient(self._addr, self, None) log.debug("Client Connected [%s]" % self._addr) self._connected = True
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, type): # Framer class not instance self.framer = self.framer(ClientDecoder(), client=None) if isinstance(self.framer, ModbusSocketFramer): self.transaction = DictTransactionManager(self, **kwargs) else: self.transaction = FifoTransactionManager(self, **kwargs)
class BaseModbusClient(ModbusClientMixin): """ Inteface 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 self.transaction = DictTransactionManager(self, **kwargs) self._debug = False self._debugfd = None self.broadcast_enable = kwargs.get('broadcast_enable', Defaults.broadcast_enable) # ----------------------------------------------------------------------- # # Client interface # ----------------------------------------------------------------------- # def connect(self): """ Connect to the modbus remote host :returns: True if connection succeeded, False otherwise """ raise NotImplementedException( "Method not implemented by derived class") def close(self): """ Closes the underlying socket connection """ pass def is_socket_open(self): """ Check whether the underlying socket/serial is open or not. :returns: True if socket/serial is open, False otherwise """ raise NotImplementedException( "is_socket_open() not implemented by {}".format(self.__str__())) def send(self, request): _logger.debug("New Transaction state 'SENDING'") self.state = ModbusTransactionState.SENDING return self._send(request) def _send(self, request): """ Sends data on the underlying socket :param request: The encoded request to send :return: The number of bytes written """ raise NotImplementedException( "Method not implemented by derived class") def recv(self, size): return self._recv(size) def _recv(self, size): """ Reads data from the underlying descriptor :param size: The number of bytes to read :return: The bytes read """ raise NotImplementedException( "Method not implemented by derived class") # ----------------------------------------------------------------------- # # 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[%s]" % (self.__str__())) return self.transaction.execute(request) # ----------------------------------------------------------------------- # # The 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[%s]" % (self.__str__())) return self def __exit__(self, klass, value, traceback): """ Implement the client with exit block """ self.close() def idle_time(self): """ Bus Idle Time to initiate next transaction :return: time stamp """ if self.last_frame_end is None or self.silent_interval is None: return 0 return self.last_frame_end + self.silent_interval def debug_enabled(self): """ Returns a boolean indicating if debug is enabled. """ return self._debug def set_debug(self, debug): """ Sets the current debug flag. """ self._debug = debug def trace(self, writeable): if writeable: self.set_debug(True) self._debugfd = writeable def _dump(self, data, direction): fd = self._debugfd if self._debugfd else sys.stdout try: fd.write(hexlify_packets(data)) except Exception as e: self._logger.debug(hexlify_packets(data)) self._logger.exception(e) def register(self, function): """ Registers a function and sub function class with the decoder :param function: Custom function class to register :return: """ self.framer.decoder.register(function) def __str__(self): """ Builds a string representation of the connection :returns: The string representation """ return "Null Transport"
class BaseModbusClient(ModbusClientMixin): """ Inteface 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 self.transaction = DictTransactionManager(self, **kwargs) self._debug = False self._debugfd = None self.broadcast_enable = kwargs.get('broadcast_enable', Defaults.broadcast_enable) # ----------------------------------------------------------------------- # # Client interface # ----------------------------------------------------------------------- # def connect(self): """ Connect to the modbus remote host :returns: True if connection succeeded, False otherwise """ raise NotImplementedException("Method not implemented by derived class") def close(self): """ Closes the underlying socket connection """ pass def is_socket_open(self): """ Check whether the underlying socket/serial is open or not. :returns: True if socket/serial is open, False otherwise """ raise NotImplementedException( "is_socket_open() not implemented by {}".format(self.__str__()) ) def send(self, request): _logger.debug("New Transaction state 'SENDING'") self.state = ModbusTransactionState.SENDING return self._send(request) def _send(self, request): """ Sends data on the underlying socket :param request: The encoded request to send :return: The number of bytes written """ raise NotImplementedException("Method not implemented by derived class") def recv(self, size): return self._recv(size) def _recv(self, size): """ Reads data from the underlying descriptor :param size: The number of bytes to read :return: The bytes read """ raise NotImplementedException("Method not implemented by derived class") # ----------------------------------------------------------------------- # # 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[%s]" % (self.__str__())) return self.transaction.execute(request) # ----------------------------------------------------------------------- # # The 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[%s]" % (self.__str__())) return self def __exit__(self, klass, value, traceback): """ Implement the client with exit block """ self.close() def idle_time(self): """ Bus Idle Time to initiate next transaction :return: time stamp """ if self.last_frame_end is None or self.silent_interval is None: return 0 return self.last_frame_end + self.silent_interval def debug_enabled(self): """ Returns a boolean indicating if debug is enabled. """ return self._debug def set_debug(self, debug): """ Sets the current debug flag. """ self._debug = debug def trace(self, writeable): if writeable: self.set_debug(True) self._debugfd = writeable def _dump(self, data, direction): fd = self._debugfd if self._debugfd else sys.stdout try: fd.write(hexlify_packets(data)) except Exception as e: self._logger.debug(hexlify_packets(data)) self._logger.exception(e) def register(self, function): """ Registers a function and sub function class with the decoder :param function: Custom function class to register :return: """ self.framer.decoder.register(function) def __str__(self): """ Builds a string representation of the connection :returns: The string representation """ return "Null Transport"