def _connectSerialMux(self): ''' \brief Connect through the serial Mux. ''' # initialize the connector try: if isinstance(self.apiDef, IpMgrDefinition.IpMgrDefinition): self.connector = IpMgrConnectorMux.IpMgrConnectorMux() else: raise SystemError except NotImplementedError as err: self.guiLock.acquire() self.tipLabel.configure(text=str(err)) self.guiLock.release() return # read connection params from GUI self.guiLock.acquire() connectParams = { 'host': self.serialMuxHostText.get(1.0, Tkinter.END).strip(), 'port': int(self.serialMuxPortText.get(1.0, Tkinter.END).strip()), } self.guiLock.release() # connect try: self.connector.connect(connectParams) except ConnectionError as err: self.guiLock.acquire() self.serialMuxHostText.configure(bg=dustStyle.COLOR_ERROR) self.serialMuxPortText.configure(bg=dustStyle.COLOR_ERROR) self.tipLabel.configure(text=str(err)) self.guiLock.release() return else: self.guiLock.acquire() self.serialMuxHostText.configure(bg=dustStyle.COLOR_NOERROR) self.serialMuxPortText.configure(bg=dustStyle.COLOR_NOERROR) self.tipLabel.configure(text="Connection successful.") self.guiLock.release() # hide other connectFrames self.guiLock.acquire() self.serialFrame.grid_forget() self.xmlFrame.grid_forget() self.guiLock.release() # update the button self.guiLock.acquire() self.serialMuxButton.configure(text='disconnect', command=self._disconnect) self.guiLock.release() # common connect routing self._connect()
def check_device(sm_data): if (sm_data.com_port and sm_data.listener_port and sm_data.status == SerialMuxConfig.STATUS_RUNNING): mgr = IpMgrConnectorMux.IpMgrConnectorMux() try: mgr.connect({'port': int(sm_data.listener_port)}) sys_info = mgr.dn_getSystemInfo() sm_data.device_type = SerialMuxConfig.DEVICE_MANAGER sm_data.identifier = sys_info.macAddress mgr.disconnect() except ApiException.ConnectionError: sm_data.identifier = '' except socket.error: sm_data.identifier = ''
DEFAULT_MUXHOST = '127.0.0.1' DEFAULT_MUXPORT = 9900 #============================ main ============================================ print 'SimpleIPUpstreamMgr (c) Dust Networks' print 'SmartMesh SDK {0}\n'.format('.'.join( [str(b) for b in sdk_version.VERSION])) print 'Note: Use with SimpleIPUpstreamMote\n' #===== muxHost = DEFAULT_MUXHOST muxPort = DEFAULT_MUXPORT print '\n=====\nCreating connector' connector = IpMgrConnectorMux.IpMgrConnectorMux() print 'done.' print '\n=====\nConnecting to IP manager' try: connector.connect({ 'host': muxHost, 'port': muxPort, }) except ConnectionError as err: print err raw_input('\nScript ended. Press Enter to exit.') sys.exit(1) print 'done.' #=== Initializing the Pipe to send Data to C++
def run(self): with self.dataLock: self.isReconnecting = True while (True): try: #==== wait for an order to (re)connect self.reconnectSem.acquire() with self.dataLock: assert self.isReconnecting == True #==== connect to serial port if isinstance(self.connection_details, str): # connecting to a serial port self.connector = IpMgrConnectorSerial.IpMgrConnectorSerial( ) self.connector.connect({ 'port': self.connection_details, }) else: # connecting to the serialMux self.connector = IpMgrConnectorMux.IpMgrConnectorMux() self.connector.connect({ 'host': self.connection_details[0], 'port': self.connection_details[1], }) #==== getTime temp = self.connector.dn_getTime() managerTime = float(temp.utcSecs) + float( temp.utcUsecs / 1000000.0) self.csvLogger.managerTime(managerTime) #==== subscribe self.subscriber = IpMgrSubscribe.IpMgrSubscribe(self.connector) self.subscriber.start() self.subscriber.subscribe( notifTypes=[ IpMgrSubscribe.IpMgrSubscribe.NOTIFDATA, ], fun=self._subs_notifData, isRlbl=False, ) self.subscriber.subscribe( notifTypes=[ IpMgrSubscribe.IpMgrSubscribe.FINISH, IpMgrSubscribe.IpMgrSubscribe.ERROR, ], fun=self._subs_finishOrError, isRlbl=True, ) #==== log self.csvLogger.log(CsvLogger.EVENT_CONNECTED) log.info(CsvLogger.EVENT_CONNECTED) except ConnectionError as err: # log log.warning(err) # schedule reconnection self._reconnect() # wait before attempting to reconnect time.sleep(1) else: with self.dataLock: # remember I'm not connecting anymore self.isReconnecting = False
def _addManagerConnection(self,connectParam): dld = DustLinkData.DustLinkData() with dld.dataLock: assert(connectParam not in self.apiconnectors) assert(connectParam not in self.listeners) assert(connectParam not in self.netstate) assert(connectParam not in self.analyzers) assert(connectParam not in self.publishers) try: #===== self.apiconnectors if isinstance(connectParam,str): # connecting to a serial port newConnector = IpMgrConnectorSerial.IpMgrConnectorSerial() newConnector.connect({ 'port': connectParam, }) else: # connecting to the serialMux newConnector = IpMgrConnectorMux.IpMgrConnectorMux() newConnector.connect({ 'host': connectParam[0], 'port': connectParam[1], }) # log log.info('added apiconnectors {0}'.format(connectParam)) self.apiconnectors[connectParam] = newConnector dld.updateManagerConnectionState( connectParam, DustLinkData.DustLinkData.MANAGERCONNECTION_STATE_ACTIVE ) #===== delete network try: dld.deleteNetwork(FormatUtils.formatConnectionParams(connectParam)) except ValueError: pass # happens if network doesn't exist #===== add network try: dld.addNetwork(FormatUtils.formatConnectionParams(connectParam)) except ValueError: pass # happens if network already exists from previous connection #===== self.listeners assert(connectParam not in self.listeners) self.listeners[connectParam] = GatewayListener.GatewayListener( self.apiconnectors[connectParam], connectParam, ) log.info('added listener {0}'.format(connectParam)) #===== self.netstate assert(connectParam not in self.netstate) self.netstate[connectParam] = NetworkState.NetworkState(connectParam) log.info('added netstate {0}'.format(connectParam)) #===== self.analyzers assert(connectParam not in self.analyzers) self.analyzers[connectParam] = NetworkStateAnalyzer.NetworkStateAnalyzer(connectParam) log.info('added analyzer {0}'.format(connectParam)) #===== self.publishers assert(connectParam not in self.publishers) self.publishers[connectParam] = NetworkStatePublisher.NetworkStatePublisher(connectParam) log.info('added publisher {0}'.format(connectParam)) except Exception as err: # log log.warning('could not add apiconnectors {0}: {1}'.format(connectParam, err)) # update state dld.updateManagerConnectionState( connectParam, DustLinkData.DustLinkData.MANAGERCONNECTION_STATE_FAIL, reason = str(err), ) # detelete the connection to the manager self._deleteManagerConnection(connectParam)
def run(self): try: dld = DustLinkData.DustLinkData() dld._resetScratchpad() dld._addScratchpad( "<p class=\"doc-header\">Resetting manager.</p>") #===== connecting to manager dld._addScratchpad("<p>connecting to manager at {0}.</p>".format( self.connectionParams)) try: if isinstance(self.connectionParams, tuple): # over serialMux connector = IpMgrConnectorMux.IpMgrConnectorMux() connector.connect({ 'host': self.connectionParams[0], 'port': self.connectionParams[1], }) else: # over serial connector = IpMgrConnectorSerial.IpMgrConnectorSerial() connector.connect({ 'port': self.connectionParams, }) except Exception as err: dld._addScratchpad( "<p class=\"doc-warning\">connection failed: {0}.</p>". format(err)) return else: dld._addScratchpad( "<p class=\"doc-success\">connection successful.</p>") try: #===== issuing dn_getNetworkConfig() dld._addScratchpad("<p>issuing dn_getNetworkConfig()</p>") try: oldconf = connector.dn_getNetworkConfig() except Exception as err: dld._addScratchpad( "<p class=\"doc-warning\">failed issuing dn_getNetworkConfig(): {0}.</p>" .format(err)) return else: output = [] output += [ "<p class=\"doc-success\">issued dn_getNetworkConfig() succesfully.</p>" ] output += ["<p>Received the following fields:</p>"] output += ["<table>"] output += [ "<tr><td>{0}</td><td>{1}</td></tr>".format( k, getattr(oldconf, k)) for k in oldconf._fields ] output += ["</table>"] output = ''.join(output) dld._addScratchpad(output) #===== issuing dn_setNetworkConfig() newconf = { 'networkId': oldconf.networkId, 'apTxPower': 8, 'frameProfile': 1, 'maxMotes': 33, 'baseBandwidth': 9000, 'downFrameMultVal': 1, 'numParents': 2, 'ccaMode': 0, 'channelList': 32767, 'autoStartNetwork': 1, 'locMode': 0, 'bbMode': 0, 'bbSize': 1, 'isRadioTest': 0, 'bwMult': 300, 'oneChannel': 255, } output = [] output += [ "<p>issuing dn_setNetworkConfig() with the following parameters</p>" ] output += ["<table>"] output += [ "<tr><td>{0}</td><td>{1}</td></tr>".format(k, v) for (k, v) in newconf.items() ] output += ["</table>"] output = ''.join(output) dld._addScratchpad(output) try: connector.dn_setNetworkConfig(**newconf) except Exception as err: dld._addScratchpad( "<p class=\"doc-warning\">failed issuing dn_setNetworkConfig(): {0}.</p>" .format(err)) return else: dld._addScratchpad( "<p class=\"doc-success\">issued dn_setNetworkConfig() succesfully.</p>" ) #===== issuing dn_reset() dld._addScratchpad("<p>issuing dn_reset()</p>") try: connector.dn_reset( type=0, # 0 = resetSystem macAddress=[0] * 8, # this field is not used when resetting the system ) except Exception as err: pass # happens since receiving no ACK from manager which is resetting finally: #===== disconnect and delete connector dld._addScratchpad( "<p>disconnecting from manager at {0}.</p>".format( self.connectionParams)) try: connector.disconnect() except Exception as err: dld._addScratchpad( "<p class=\"doc-warning\">disconnection failed: {0}.</p>" .format(err)) else: dld._addScratchpad( "<p class=\"doc-success\">disconnection successful.</p>" ) del connector dld._addScratchpad("<p class=\"doc-header\">done.</p>") except Exception as err: output = [] output += ['===== crash in thread {0} ====='.format(self.name)] output += ['\nerror:\n'] output += [str(err)] output += ['\ncall stack:\n'] output += [traceback.format_exc()] output = '\n'.join(output) print output # critical error log.critical(output) raise