def disconnect(self): # close serial port self.pyserialHandler.close() # disconnect the parent class ApiConnector.disconnect(self, reason="")
def __init__(self, api_def, maxQSize=100): # log log.info("creating object") # store params self.api_def = api_def # initialize parent class ApiConnector.__init__(self, maxQSize) # local variables self.waitForResp = False ##< flag to indicate whether we are waiting for an ACK self.waitForRespEvent = threading.Event( ) ##< semaphore used when waiting for a command to be acknowledged self.paramLock = threading.Lock( ) ##< lock to ensure atomic access to parameters self.RxPacketId = None ##< running id for packets received from device self.TxPacketId = 0 ##< running id for packets sent to device self.hdlcLock = threading.Lock() ##< lock for the HDLC module self.hdlc = None ##< HDLC module (includes CRC) self.syncNeeded = True ##< True iff we need to sync to the device self.requestSendLock = threading.Lock( ) ##< lock to prevent concurrent requests to be sent self.tsDataSent = 0 ##< timestamp when sent data self.tsDataReceived = 0 ##< timestamp when received data
def __init__(self): # TODO: init super? ApiConnector.__init__(self) # TODO: maxQSize self.apidef = HartMgrDefinition.HartMgrDefinition() self.manager = None self.login_token = None self.notif_token = None self.notif_thread = None
def __init__(self): # local variables self.waitForResponse = threading.Event() # initialize parent classes ApiConnector.__init__(self) threading.Thread.__init__(self) self.name = 'IpMoteConnector'
def disconnect(self, reason=""): with self.hdlcLock: # disconnect the parent class ApiConnector.disconnect(self, reason) # disconnect hdlc module if self.hdlc: self.hdlc.disconnect() # delete the hdlc module self.hdlc = None
def __init__(self): # local variables self.waitForResponse = threading.Event() # initialize parent classes ApiConnector.__init__(self) threading.Thread.__init__(self) self.name = 'HartMoteConnector'
def __init__(self, maxQSize=100): log.debug("creating object") # init the parent ApiConnector.__init__(self,maxQSize) # variables self.varLock = threading.Lock() self._updateStatus(self.STATUS_DISCONNECTED) self.prefix = None # reset stats self._resetStats()
def connect(self, connectParams): if 'port' not in connectParams: output = "'port' entry required in connection parameters" log.error(output) raise ValueError(output) with self.hdlcLock: # create and start HDLC module (includes CRC) self.hdlc = Hdlc.Hdlc(self._hdlcRxCb, self._hdlcConnectCb) # connect HDLC module to serial Port self.hdlc.connect(connectParams) # connect the parent class ApiConnector.connect(self)
def connect(self, resource): # set up the connection parameters self.connect_params = copy.copy(self.DEFAULT_CONNECT_PARAMS) self.connect_params.update(resource) # TODO: allow HTTPS try: self.manager = self._init_xmlrpc(self.connect_params['host'], int(self.connect_params['port']), bool(self.connect_params['use_ssl'])) self.login(self.connect_params['user'], self.connect_params['password']) except xmlrpclib.Fault as ex: log.error(str(ex)) raise ApiException.ConnectionError(str(ex)) log.info('Connected to %s' % self.connect_params['host']) ApiConnector.connect(self)
def connect(self, resource): # set up the connection parameters self.connect_params = copy.copy(self.DEFAULT_CONNECT_PARAMS) self.connect_params.update(resource) # TODO: allow HTTPS try: self.manager = self._init_xmlrpc( self.connect_params['host'], int(self.connect_params['port']), bool(self.connect_params['use_ssl'])) self.login(self.connect_params['user'], self.connect_params['password']) except xmlrpclib.Fault as ex: log.error(str(ex)) raise ApiException.ConnectionError(str(ex)) log.info('Connected to %s' % self.connect_params['host']) ApiConnector.connect(self)
def __init__(self, api_def, maxQSize=100) : # log log.info("creating object") # store params self.api_def = api_def # initialize parent class ApiConnector.__init__(self, maxQSize) # local variables self.waitForResp = False ##< flag to indicate whether we are waiting for an ACK self.waitForRespEvent = threading.Event() ##< semaphore used when waiting for a command to be acknowledged self.paramLock = threading.Lock() ##< lock to ensure atomic access to parameters self.RxPacketId = None ##< running id for packets received from device self.TxPacketId = 0 ##< running id for packets sent to device self.hdlcLock = threading.Lock() ##< lock for the HDLC module self.hdlc = None ##< HDLC module (includes CRC) self.syncNeeded = True ##< True iff we need to sync to the device self.requestSendLock = threading.Lock() ##< lock to prevent concurrent requests to be sent self.tsDataSent = 0 ##< timestamp when sent data self.tsDataReceived = 0 ##< timestamp when received data
def connect(self,connectParams): ''' \brief Connect to the LBR. ''' # filter error if self.getStatus() not in [self.STATUS_DISCONNECTED]: self._abortConnectionWithError(connectParams,'is at wrong status to connect '+str(self.getStatus())) # record variables try: self.varLock.acquire() self.lbrAddr = connectParams['lbrAddr'] self.lbrPort = connectParams['lbrPort'] self.username = connectParams['username'] self.seclevel = connectParams['seclevel'] if self.seclevel==LbrProtocol.SECLEVEL_PASSWORD: self.password = connectParams['password'] elif self.seclevel==LbrProtocol.SECLEVEL_SSL: self.clientprivatekey = connectParams['clientprivatekey'] self.clientpublickey = connectParams['clientpublickey'] self.lbrpublickey = connectParams['lbrpublickey'] except KeyError as err: raise ConnectionError('Missing connection parameter: '+str(err)) finally: self.varLock.release() # connect the parent ApiConnector.connect(self) # update status self._updateStatus(self.STATUS_INIT_CONNECTION) # create TCP socket to connect to LBR try: self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.socket.connect((self.lbrAddr,self.lbrPort)) except socket.error: self._abortConnectionWithError(connectParams,'could not open socket to LBR@'+self.lbrAddr+':'+str(self.lbrPort)+'.') # listen for at most AUTHTIMEOUT seconds during connection self.socket.settimeout(AUTHTIMEOUT) #=== Step 1. Send my security capability to LBR self._updateStatus(self.STATUS_TX_SECURITY) try: self.socket.send(LbrProtocol.CMD_SECURITY+chr(self.seclevel)) except socket.error: self._abortConnectionWithError(connectParams,'could not send security capability.') #=== Step 2. Receive security capabilities from LBR self._updateStatus(self.STATUS_RX_SECURITY) try: input = self.socket.recv(TCPRXBUFSIZE) except socket.timeout: self._abortConnectionWithError(connectParams,'waited too long for security reply.') if ( len(input)!=2 or input[0] !=LbrProtocol.CMD_SECURITY or ord(input[1]) !=self.seclevel): self._abortConnectionWithError(connectParams,'received incorrect security reply.') #=== Step 3. Send username self._updateStatus(self.STATUS_TX_USERNAME) try: self.socket.send(LbrProtocol.CMD_USERNAME+self.username) except socket.error: self._abortConnectionWithError(connectParams,'could not send username.') #=== Step 4. Receive username self._updateStatus(self.STATUS_RX_USERNAME) try: input = self.socket.recv(TCPRXBUFSIZE) except socket.timeout: self._abortConnectionWithError(connectParams,'waited too long for username echo.') if ( len(input)<=1 or input[0] !=LbrProtocol.CMD_USERNAME or input[1:] !=self.username): self._abortConnectionWithError(connectParams,'received incorrect echoed username.') #=== Step 5. Secure TCP session if self.seclevel==LbrProtocol.SECLEVEL_NONE: log.debug('TCP session securing: none') elif self.seclevel==LbrProtocol.SECLEVEL_PASSWORD: log.debug('TCP session securing: password') self._updateStatus(self.STATUS_TX_PASSWORD) try: self.socket.send(LbrProtocol.CMD_PASSWORD+self.password) except socket.error: self._abortConnectionWithError(connectParams,'could not send password.') elif self.seclevel==LbrProtocol.SECLEVEL_SSL: log.debug('TCP session securing: SSL') self._updateStatus(self.STATUS_SLL_WRAPPING) try: clientPrivateKeyPem = self._privatekeyToPem(self.clientprivatekey) clientPrivateKeyFileName = self.username+'.tempprivatekey' clientPrivateKeyFile = open(clientPrivateKeyFileName,'w') clientPrivateKeyFile.write(clientPrivateKeyPem) clientPrivateKeyFile.close() clientPublicKeyPem = self._publickeyToPem(self.clientpublickey) clientPublicKeyFileName = self.username+'.temppublickey' clientPublicKeyFile = open(clientPublicKeyFileName,'w') clientPublicKeyFile.write(clientPublicKeyPem) clientPublicKeyFile.close() lbrpublickeyPem = self._publickeyToPem(self.lbrpublickey) lbrpublickeyFileName = self.username+'.templbrpublickey' lbrpublickeyFile = open(lbrpublickeyFileName,'w') lbrpublickeyFile.write(lbrpublickeyPem) lbrpublickeyFile.close() self.socket = ssl.wrap_socket( self.socket, keyfile=clientPrivateKeyFileName, # client's private key certfile=clientPublicKeyFileName, # client's public key ca_certs=lbrpublickeyFileName, # server's public key cert_reqs=ssl.CERT_REQUIRED) except ssl.SSLError as err: self._abortConnectionWithError(connectParams,'SSL wrapping failed.') except Exception as err: print err else: output = '' output += 'Peer validated:\n' output += '- name: '+str(self.socket.getpeername())+'\n' output += '- cipher: '+str(self.socket.cipher())+'\n' output += '- cartificate: '+str(self.socket.getpeercert()) log.debug(output) finally: os.remove(clientPrivateKeyFileName) os.remove(clientPublicKeyFileName) os.remove(lbrpublickeyFileName) #=== Step 6. Receive assigned prefix from LBR self._updateStatus(self.STATUS_RX_PREFIX) try: input = self.socket.recv(TCPRXBUFSIZE) except (socket.timeout,ssl.SSLError): self._abortConnectionWithError(connectParams,'waited too long for prefix.') if (len(input)!=20 or input[0]!=LbrProtocol.CMD_PREFIX): self._abortConnectionWithError(connectParams,'received malformatted prefix.') # record the prefix self.prefix = input[1:] # if you get here, connection is succesfully established with LBR # update status self._updateStatus(self.STATUS_CONNECTED) # no socket timeout from now on self.socket.settimeout(None) # start an LbrListener thread temp = LbrListener(self.socket,self._rxCb,self._disconnectedCb) temp.start()
def connect(self,connectParams): log.debug("connect connectParams={0}".format(connectParams)) if 'port' not in connectParams: output = "'port' entry required in connection parameters" log.error(output) raise ValueError(output) #==== connect to serial port self.comPort = connectParams['port'] try: self.pyserialHandler = serial.Serial(self.comPort,baudrate=self._BAUDRATE) self.pyserialHandler.setRTS(False) self.pyserialHandler.setDTR(True) except serial.serialutil.SerialException as err: output = "could not open " + self.comPort + ", reason: " + str(err) log.warning(output) raise ConnectionError(output) else: log.info("opened port "+self.comPort) #==== import and initialize the C library global uart_txByte global whmt_notif global whmt_reply global whmt_status # local variables uart_txByte = uart_txByte_cbt(self._uart_txByte) whmt_notif = whmt_notif_cbt(self._whmt_notif) whmt_reply = whmt_reply_cbt(self._whmt_reply) whmt_status = whmt_status_cbt(self._whmt_status) # configure the callback function self.notifBuf = create_string_buffer(self.MAX_FRAME_LENGTH) # open the library under test self.smwhmt = CDLL(CLIB_PATH) self.smwhmt.dn_whmt_init( whmt_notif, # notifCb self.notifBuf, # notifBuf len(self.notifBuf), # notifBufLen whmt_reply, # replyCb whmt_status, # statusCb ) # install callbacks self.smwhmt.dn_uart_register_txByte(uart_txByte) # initial thread threading.Thread.__init__(self) self.name = 'hartMoteConnectorSerial' # start myself self.start() #==== connect administratively # connect the parent class ApiConnector.connect(self)
def disconnect(self, reason=None): self.unsubscribe_override(['unsubscribe'], {}) self.logout() log.info('Disconnected from %s' % self.connect_params['host']) ApiConnector.disconnect(self, reason)
def connect(self,connectParams): log.debug("connect connectParams={0}".format(connectParams)) if 'port' not in connectParams: output = "'port' entry required in connection parameters" log.error(output) raise ValueError(output) #==== connect to serial port self.comPort = connectParams['port'] try: self.pyserialHandler = serial.Serial(self.comPort,baudrate=self._BAUDRATE) self.pyserialHandler.setRTS(False) self.pyserialHandler.setDTR(True) except serial.serialutil.SerialException as err: output = "could not open " + self.comPort + ", reason: " + str(err) log.warning(output) raise ConnectionError(output) else: log.info("opened port "+self.comPort) #==== import and initialize the C library global uart_txByte global ipmg_notif global ipmg_reply global ipmg_status # local variables uart_txByte = uart_txByte_cbt(self._uart_txByte) ipmg_notif = ipmg_notif_cbt(self._ipmg_notif) ipmg_reply = ipmg_reply_cbt(self._ipmg_reply) ipmg_status = ipmg_status_cbt(self._ipmg_status) # configure the callback function self.notifBuf = create_string_buffer(self.MAX_FRAME_LENGTH) # open the library under test self.smipmg = CDLL(CLIB_PATH) self.smipmg.dn_ipmg_init( ipmg_notif, # notifCb self.notifBuf, # notifBuf len(self.notifBuf), # notifBufLen ipmg_reply, # replyCb ipmg_status, # statusCb ) # install callbacks self.smipmg.dn_uart_register_txByte(uart_txByte) # initial thread threading.Thread.__init__(self) self.name = 'IpMgrConnectorSerial' # start myself self.start() #==== connect to manager rcApi = self.smipmg.dn_ipmg_initiateConnect() assert rcApi == DN_ERR_NONE # wait for C library to connect if self.waitForConnected.wait(self.CONNECT_TIMEOUT): self.waitForConnected.clear() # connect the parent class ApiConnector.connect(self) else: raise ConnectionError("timeout connecting")
def disconnect(self, reason = None): self.unsubscribe_override(['unsubscribe'], {}) self.logout() log.info('Disconnected from %s' % self.connect_params['host']) ApiConnector.disconnect(self, reason)
def connect(self, connectParams): log.debug("connect connectParams={0}".format(connectParams)) if 'port' not in connectParams: output = "'port' entry required in connection parameters" log.error(output) raise ValueError(output) #==== connect to serial port self.comPort = connectParams['port'] try: self.pyserialHandler = serial.Serial(self.comPort, baudrate=self._BAUDRATE) self.pyserialHandler.setRTS(False) self.pyserialHandler.setDTR(True) except serial.serialutil.SerialException as err: output = "could not open " + self.comPort + ", reason: " + str(err) log.warning(output) raise ConnectionError(output) else: log.info("opened port " + self.comPort) #==== import and initialize the C library global uart_txByte global ipmt_notif global ipmt_reply global ipmt_status # local variables uart_txByte = uart_txByte_cbt(self._uart_txByte) ipmt_notif = ipmt_notif_cbt(self._ipmt_notif) ipmt_reply = ipmt_reply_cbt(self._ipmt_reply) ipmt_status = ipmt_status_cbt(self._ipmt_status) # configure the callback function self.notifBuf = create_string_buffer(self.MAX_FRAME_LENGTH) # open the library under test self.smipmt = CDLL(CLIB_PATH) self.smipmt.dn_ipmt_init( ipmt_notif, # notifCb self.notifBuf, # notifBuf len(self.notifBuf), # notifBufLen ipmt_reply, # replyCb ipmt_status, # statusCb ) # install callbacks self.smipmt.dn_uart_register_txByte(uart_txByte) # initial thread threading.Thread.__init__(self) self.name = 'IpMoteConnectorSerial' # start myself self.start() #==== connect administratively # connect the parent class ApiConnector.connect(self)
def _disconnectedCb(self): # disconnect the parent ApiConnector.disconnect(self,'') # update status self._updateStatus(self.STATUS_DISCONNECTED)