def temperature(params): moteSelected = macToMoteId(params[0]) if moteSelected < 0: print 'moteId invalid' return # filter params try: moteId = moteSelected isBcast = False except: isBcast = True tempOn = int(params[1]) pktPeriod = int(params[2]) if moteId > len(AppData().get('operationalmotes')): print 'moteId {0} impossible, there are only {1} motes'.format( moteId, len(AppData().get('operationalmotes')), ) return # send OAP command ... single or all broadcast if not isBcast: AppData().get('oap_clients')[AppData().get('operationalmotes') [moteId]].send( cmd_type=OAPMessage.CmdType.PUT, addr=[5], data_tags=[ OAPMessage.TLVByte(t=0, v=tempOn), OAPMessage.TLVLong(t=1, v=pktPeriod), ], ) else: # build OAP message oap_msg = OAPMessage.build_oap( seq=0, sid=0, cmd=OAPMessage.CmdType.PUT, addr=[5], tags=[ OAPMessage.TLVByte(t=0, v=tempOn), OAPMessage.TLVLong(t=1, v=pktPeriod), ], sync=True, ) oap_msg = [ord(b) for b in oap_msg] # send OAP message broadcast NUM_BCAST_TO_SEND times for i in range(NUM_BCAST_TO_SEND): AppData().get('connector').dn_sendData( macAddress=[0xff] * 8, priority=0, srcPort=OAPMessage.OAP_PORT, dstPort=OAPMessage.OAP_PORT, options=0x00, data=oap_msg, )
def analog_clicb(params): moteSelected = macToMoteId(params[0]) if moteSelected < 0: print 'moteId invalid' return # filter params moteId = moteSelected channel = int(params[1]) enable = int(params[2]) rate = int(params[3]) if (rate == 0): rate = 30000 print 'Setting {0} analog {1} rate to {2} ({3})'.format( moteId, channel, rate, enable) if moteId > len(AppData().get('operationalmotes')): print 'moteId {0} impossible, there are only {1} motes'.format( moteId, len(AppData().get('operationalmotes')), ) return AppData().get('oap_clients')[AppData().get( 'operationalmotes')[moteId]].send( cmd_type=OAPMessage.CmdType.PUT, addr=[4, channel], data_tags=[ OAPMessage.TLVByte(t=0, v=enable), # enable OAPMessage.TLVLong(t=1, v=rate), # rate ], )
def _moteListFrameCb_rateSet(self,mac,val): # send the OAP message try: self.oap_clients[mac].send( OAPMessage.CmdType.PUT, # command [5], # address data_tags=[OAPMessage.TLVByte(t=0,v=1), OAPMessage.TLVLong(t=1,v=val),],# parameters cb=None, # callback ) except APIError as err: self.statusFrame.write("[WARNING] {0}".format(err)) else: # update status self.statusFrame.write( "Publish rate set({0}) request sent successfully to mote {1}.".format( val, FormatUtils.formatMacString(mac), ) )
def analog_clicb(params): # filter params moteId = int(params[0]) channel = int(params[1]) enable = int(params[2]) rate = int(params[3]) if moteId>len(AppData().get('operationalmotes')): print 'moteId {0} impossible, there are only {1} motes'.format( moteId, len(AppData().get('operationalmotes')), ) return AppData().get('oap_clients')[AppData().get('operationalmotes')[moteId]].send( cmd_type = OAPMessage.CmdType.PUT, addr = [4,channel], data_tags = [ OAPMessage.TLVByte(t=0,v=enable), # enable OAPMessage.TLVLong(t=1,v=rate), # rate ], )
class PkGenGui(object): def __init__(self): # log log.debug("Creating PkGenGui") # local variables self.guiLock = threading.Lock() self.apiDef = IpMgrDefinition.IpMgrDefinition() self.notifClientHandler = None self.guiUpdaters = 0 self.oap_clients = {} # create window self.window = dustWindow.dustWindow('PkGen', self._windowCb_close) # add a API selection frame self.apiFrame = dustFrameApi.dustFrameApi( self.window, self.guiLock, self._apiFrameCb_apiLoaded, row=0, column=0, deviceType=dustFrameApi.dustFrameApi.MANAGER) self.apiFrame.show() # add a connection frame self.connectionFrame = dustFrameConnection.dustFrameConnection( self.window, self.guiLock, self._connectionFrameCb_connected, frameName="manager connection", row=1, column=0) # add a mote list frame columnnames = [ # PkGen { 'name': COL_PKGEN_NUM, 'type': dustFrameMoteList.dustFrameMoteList.LABEL, }, { 'name': COL_PKGEN_PPS, 'type': dustFrameMoteList.dustFrameMoteList.LABEL, }, { 'name': COL_PKGEN_CLR, 'type': dustFrameMoteList.dustFrameMoteList.ACTION, }, { 'name': COL_PKGEN_RATE, 'type': dustFrameMoteList.dustFrameMoteList.SETTHREEVAL, }, ] self.moteListFrame = dustFrameMoteList.dustFrameMoteList(self.window, self.guiLock, columnnames, row=2, column=0) self.moteListFrame.show() # add a status (text) frame self.statusFrame = dustFrameText.dustFrameText(self.window, self.guiLock, frameName="status", row=3, column=0) self.statusFrame.show() #======================== public ========================================== def start(self): # log log.debug("Starting PkGenGui") ''' This command instructs the GUI to start executing and reacting to user interactions. It never returns and should therefore be the last command called. ''' try: self.window.mainloop() except SystemExit: sys.exit() #======================== private ========================================= #==== user interactions def _apiFrameCb_apiLoaded(self, apiDefLoaded): ''' \brief Called when an API is selected. ''' # log log.debug("_apiFrameCb_apiLoaded") # record the loaded API self.apiDef = apiDefLoaded # tell other frames about it self.connectionFrame.apiLoaded(self.apiDef) # display frames self.connectionFrame.show() # update status self.statusFrame.write("API {0} loaded successfully.".format( type(apiDefLoaded))) def _connectionFrameCb_connected(self, connector): ''' \brief Called when the connectionFrame has connected. ''' # log log.debug("_connectionFrameCb_connected") # store the connector self.connector = connector # start a notification client self.notifClientHandler = notifClient( self.apiDef, self.connector, self._connectionFrameCb_disconnected, ) # retrieve list of motes from manager macs = self._getOperationalMotesMacAddresses() for mac in macs: self._addNewMote(mac) # schedule the GUI to update itself in GUI_UPDATEPERIOD ms if self.guiUpdaters == 0: self.moteListFrame.after(GUI_UPDATEPERIOD, self._updateMoteList) self.guiUpdaters += 1 # update status self.statusFrame.write("Connection to manager successful.") def _moteListFrameCb_clearPkGen(self, mac, button): # log log.debug("_moteListFrameCb_clearPkGen") # clear the PkGen counters self.notifClientHandler.clearPkGenCounters(mac) # update status self.statusFrame.write( "pkGen counters for mote {0} cleared successfully.".format( FormatUtils.formatMacString(mac), )) def _moteListFrameCb_PkGenSet(self, mac, (val1, val2, val3)): # log log.debug("_moteListFrameCb_PkGenSet") # send the OAP message try: self.oap_clients[mac].send( OAPMessage.CmdType.PUT, # command [254], # address data_tags=[ OAPMessage.TLVLong(t=0, v=1), OAPMessage.TLVLong(t=1, v=val1), OAPMessage.TLVLong(t=2, v=val2), OAPMessage.TLVByte(t=3, v=val3), ], # parameters cb=None, # callback ) except APIError as err: print "[WARNING] {0}".format(err) else: # update status self.statusFrame.write( "PkGen request ({0} packets, to be sent each {1}ms, with a {2} byte payload) sent successfully to mote {3}." .format( val1, val2, val3, FormatUtils.formatMacString(mac), ))
def run(self): try: dld = DustLinkData.DustLinkData() dld._resetScratchpad() dld._addScratchpad("<p class=\"doc-header\">Resetting motes.</p>") for targetMac in dld.getMoteMacs(): dld._addScratchpad( "<p class=\"doc-header\">resetting {0}.</p>".format( DustLinkData.DustLinkData.macToString(targetMac))) moteInfo = dld.getMoteInfo(targetMac) if moteInfo and ('isAP' in moteInfo) and moteInfo['isAP'] == 0: #===== find netname targetNet = None for netname in dld.getNetnames(): if targetMac in dld.getNetworkMotes(netname): targetNet = netname break if targetNet: dld._addScratchpad( "<p>mote is part of network {0}.</p>".format( targetNet)) else: dld._addScratchpad( "<p>mote is not of any network, skipping.</p>". format(targetNet)) continue #===== disabling digital_in for digitalPort in range(4): dld._addScratchpad( "<p>disabling digital_in D{0}.</p>".format( digitalPort + 1)) try: self._sendOapCommand( targetNet=targetNet, targetMac=targetMac, oapAddress=[2, digitalPort], # 2=digital_in oapTags=[OAPMessage.TLVByte(t=0, v=0)], ) except Exception as err: dld._addScratchpad( "<p class=\"doc-warning\">failed: {0}.</p>". format(err)) else: dld._addScratchpad( "<p class=\"doc-success\">success.</p>") #===== digital_out to 0 for pin in range(3): dld._addScratchpad( "<p>digital_out pin {0} to zero.</p>".format(pin)) try: self._sendOapCommand( targetNet=targetNet, targetMac=targetMac, oapAddress=[3, pin], # 3=digital_out oapTags=[OAPMessage.TLVByte(t=0, v=0)], ) except Exception as err: dld._addScratchpad( "<p class=\"doc-warning\">failed: {0}.</p>". format(err)) else: dld._addScratchpad( "<p class=\"doc-success\">success.</p>") #===== disabling analog for analogPort in range(4): dld._addScratchpad( "<p>disabling analog A{0}.</p>".format(analogPort + 1)) try: self._sendOapCommand( targetNet=targetNet, targetMac=targetMac, oapAddress=[4, analogPort], # 4=analog oapTags=[OAPMessage.TLVByte(t=0, v=0)], ) except Exception as err: dld._addScratchpad( "<p class=\"doc-warning\">failed: {0}.</p>". format(err)) else: dld._addScratchpad( "<p class=\"doc-success\">success.</p>") #===== enabling temperature, set rate to default dld._addScratchpad( "<p>enabling temperature, set rate to default.</p>") try: self._sendOapCommand( targetNet=targetNet, targetMac=targetMac, oapAddress=[5], # 5=temperature oapTags=[ OAPMessage.TLVByte(t=0, v=1), OAPMessage.TLVLong(t=1, v=30000), ], ) except Exception as err: dld._addScratchpad( "<p class=\"doc-warning\">failed: {0}.</p>".format( err)) else: dld._addScratchpad( "<p class=\"doc-success\">success.</p>") #===== disabling pkgen dld._addScratchpad("<p>disabling pkgen.</p>") try: self._sendOapCommand( targetNet=targetNet, targetMac=targetMac, oapAddress=[254], # 254=pkgen oapTags=[ OAPMessage.TLVByte(t=1, v=0), ], ) except Exception as err: dld._addScratchpad( "<p class=\"doc-warning\">failed: {0}.</p>".format( err)) else: dld._addScratchpad( "<p class=\"doc-success\">success.</p>") else: dld._addScratchpad("<p>mote is AP, skipping.</p>") 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 finally: dispatcher.disconnect( self._dataIndication, signal='notifData', weak=False, )
def pkgen_clicb(params): # filter params try: moteId = int(params[0]) isBcast = False except: isBcast = True numPkt = int(params[1]) pktPeriod = int(params[2]) pktSize = int(params[3]) pktstartPID = 0 if moteId>len(AppData().get('operationalmotes')): print 'moteId {0} impossible, there are only {1} motes'.format( moteId, len(AppData().get('operationalmotes')), ) return # send OAP command ... single mote, or all unicast, or all broadcast if isBcast == False: AppData().get('oap_clients')[AppData().get('operationalmotes')[moteId]].send( cmd_type = OAPMessage.CmdType.PUT, addr = [254], data_tags = [ OAPMessage.TLVLong(t=0,v=1), OAPMessage.TLVLong(t=1,v=numPkt), OAPMessage.TLVLong(t=2,v=pktPeriod), OAPMessage.TLVByte(t=3,v=pktSize), OAPMessage.TLVByte(t=4,v=pktstartPID), ], ) elif params[0] == "allu": print " Sending Unicast command to all motes\n" for mote_mac in AppData().get('operationalmotes'): AppData().get('oap_clients')[mote_mac].send( cmd_type = OAPMessage.CmdType.PUT, addr = [254], data_tags = [ OAPMessage.TLVLong(t=0,v=1), OAPMessage.TLVLong(t=1,v=numPkt), OAPMessage.TLVLong(t=2,v=pktPeriod), OAPMessage.TLVByte(t=3,v=pktSize), OAPMessage.TLVByte(t=4,v=pktstartPID), ], ) time.sleep(.25) elif params[0] == "allb": print " Sending Broadcast command to all motes\n" # build OAP message oap_msg = OAPMessage.build_oap( seq = 0, sid = 0, cmd = OAPMessage.CmdType.PUT, addr = [254], tags = [ OAPMessage.TLVLong(t=0,v=1), OAPMessage.TLVLong(t=1,v=numPkt), OAPMessage.TLVLong(t=2,v=pktPeriod), OAPMessage.TLVByte(t=3,v=pktSize), OAPMessage.TLVByte(t=4,v=pktstartPID), ], sync = True, ) oap_msg = [ord(b) for b in oap_msg] # send OAP message broadcast NUM_BCAST_TO_SEND times for i in range (NUM_BCAST_TO_SEND): AppData().get('connector').dn_sendData( macAddress = [0xff]*8, priority = 0, srcPort = OAPMessage.OAP_PORT, dstPort = OAPMessage.OAP_PORT, options = 0x00, data = oap_msg, ) else: print (' unknown paramater ... {0}'.format(params[0]))
def _oap_send_and_wait_for_reply(self, mac, method, resource, subresource=None, body={}): # use only lowercase mac = mac.lower() # add an oapClient, if needed self._oap_add_client_if_needed(mac) # create data_tags data_tags = [] if method == OAPMessage.CmdType.PUT: for (i, (n, t, d)) in enumerate(oapdefs.FIELDS[resource]): if d.count('w'): if t == 'INT8U': data_tags += [OAPMessage.TLVByte(t=i, v=body[n])] elif t == 'INT16U': data_tags += [OAPMessage.TLVShort(t=i, v=body[n])] elif t == 'INT32U': data_tags += [OAPMessage.TLVLong(t=i, v=body[n])] elif t == 'INT8U[16]': temp = body[n] temp = ''.join([ chr(int(b, 16)) for b in [ temp[2 * j:2 * j + 2] for j in range(len(temp) / 2) ] ]) data_tags += [OAPMessage.TLVString(t=i, v=temp)] # send OAP request addr = [b for b in oapdefs.ADDRESS[resource]] if subresource != None: addr += [subresource] self.oapClients[mac].send( cmd_type=method, addr=addr, data_tags=data_tags, cb=self._oap_handle_response, ) # wait for and handle OAP response with self.dataLock: if mac in self.outstandingEvents: raise SystemError('busy waiting for response') event = threading.Event() self.outstandingEvents[mac] = event if event.wait(self.OAP_TIMEOUT): # received response with self.dataLock: response = self.responses[mac] del self.responses[mac] return self._oap_format_response(resource, response) else: # timeout with self.dataLock: del self.outstandingEvents[mac] bottle.response.status = 504 # Gateway Timeout bottle.response.content_type = 'application/json' return json.dumps({ 'body': 'timeout!', })
if userinput == "": pktPeriod = DFLT_RATE else: pktPeriod = int(userinput) else: tempOn = 0 pktPeriod = DFLT_RATE oap_msg = OAPMessage.build_oap( seq=0, sid=0, cmd=OAPMessage.CmdType.PUT, addr=[5], tags=[ OAPMessage.TLVByte(t=0, v=tempOn), OAPMessage.TLVLong(t=1, v=pktPeriod), ], sync=True, ) elif userinput == "2": # '2=PKGen ON/OFF or service only userinput = raw_input( '\nEnter the desired PKGen mode;\n' '1=Turn PKGen ON\n' '2=Turn PKGen OFF\n' '3=PKGen service Bandwidth request only - no publishing\n') numPkt = 30000 pktSize = DFLT_SIZE pktPeriod = DFLT_RATE
def _injectData(self, sender, signal, data): try: # log if log.isEnabledFor(logging.DEBUG): log.debug('_injectData {0}'.format(data)) dld = DustLinkData.DustLinkData() with dld.dataLock: (transport, resource) = dld.getAppTransport(self._appName) if transport == DustLinkData.DustLinkData.APP_TRANSPORT_UDP: raise NotImplementedError() elif transport == DustLinkData.DustLinkData.APP_TRANSPORT_OAP: # TODO: handle seq_num and session_id # format data to send if self._appName == 'OAPLED': dataToSend = OAPMessage.build_oap( 0, # seq_num 0, # session_id OAPMessage.CmdType.PUT, # command [3, 2], # address tags=[ OAPMessage.TLVByte(t=0, v=data['fields']['status']) ], sync=True) elif self._appName == 'OAPTemperature': dataToSend = OAPMessage.build_oap( 0, # seq_num 0, # session_id OAPMessage.CmdType.PUT, # command [5], # address tags=[ OAPMessage.TLVByte(t=0, v=1), OAPMessage.TLVLong(t=1, v=data['fields']['rate']), ], # parameters, sync=True) else: raise NotImplementedError() dataToSend = [ord(b) for b in dataToSend] # find netname targetNetname = None for netname in dld.getNetnames(): if data['mac'] in dld.getNetworkMotes(netname): targetNetname = netname break if not targetNetname: raise SystemError( 'no network found which contains {0}'.format( data['mac'])) # dispatch self._dispatch( signal='dataToMesh_{0}'.format(targetNetname), data={ 'mac': data['mac'], 'priority': 0, 'srcPort': DustLinkData.DustLinkData.WKP_OAP, 'dstPort': DustLinkData.DustLinkData.WKP_OAP, 'options': 0, 'data': dataToSend, }, ) elif transport == DustLinkData.DustLinkData.APP_TRANSPORT_COAP: raise NotImplementedError() elif transport == DustLinkData.DustLinkData.APP_TRANSPORT_MOTERUNNER: raise NotImplementedError() else: raise ValueError( 'unexpected transport={0}'.format(transport)) except Exception as err: import traceback traceback.print_exc() print err