Esempio n. 1
0
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
            ],
        )
Esempio n. 2
0
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,
            )
Esempio n. 3
0
def led_clicb(params):
    
    # filter params
    try:
        moteId    = int(params[0])
        isBcast   = False
    except:
        isBcast   = True
    ledState  = params[1]
    
    if moteId>len(AppData().get('operationalmotes')):
        print 'moteId {0} impossible, there are only {1} motes'.format(
            moteId,
            len(AppData().get('operationalmotes')),
        )
        return
    
    if ledState=="0":
        ledVal = 0
    else:
        ledVal = 1
    
    # 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       = [3,2],
            data_tags  = [OAPMessage.TLVByte(t=0,v=ledVal)],
            cb         = _respPoipoi,
        )
    else:
        # build OAP message
        oap_msg = OAPMessage.build_oap(
            seq          = 0,
            sid          = 0,
            cmd          = OAPMessage.CmdType.PUT,
            addr         = [3,2],
            tags         = [OAPMessage.TLVByte(t=0,v=ledVal)],
            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,
            )
Esempio n. 4
0
    def _moteListFrameCb_toggleLed(self, mac, button):

        if isinstance(self.apiDef, IpMgrDefinition.IpMgrDefinition):
            # find out whether to switch LED on of off
            if button.cget("text") == 'ON':
                val = 1
                button.configure(text="OFF")
            else:
                val = 0
                button.configure(text="ON")

            # send the OAP message
            try:
                self.oap_clients[mac].send(
                    OAPMessage.CmdType.PUT,  # command
                    [3, 2],  # address
                    data_tags=[OAPMessage.TLVByte(t=0, v=val)],  # parameters
                    cb=None,  # callback
                )
            except APIError as err:
                self.statusFrame.write("[WARNING] {0}".format(err))
            else:
                # update status
                self.statusFrame.write(
                    "Toggle LED command sent successfully to mote {0}.".format(
                        FormatUtils.formatMacString(mac), ))
        else:
            button.configure(text="N.A.")
            # update status
            self.statusFrame.write(
                "This feature is only present in SmartMesh IP")
Esempio n. 5
0
 def _moteListFrameCb_Ledoff(self,mac,button):
     
     self.oap_clients[mac].send( OAPMessage.CmdType.PUT,
                                 [3,2],
                                 data_tags=[ OAPMessage.TLVByte(t=0,v=0)],
                                 cb=None,
                                )
     
     self.statusFrame.write("Set led off of mote {0}".format(FormatUtils.formatMacString(mac)))
Esempio n. 6
0
 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),
             )
         )
Esempio n. 7
0
def temp_clicb(params):
    
    # filter params
    try:
        moteId    = int(params[0])
        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,
            )
Esempio n. 8
0
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
        ],
    )
Esempio n. 9
0
    def _led_cb(self, mac, datastream, value):

        # all non-0 values turn LED on
        if value == 0:
            value = 0
        else:
            value = 1

        # send through OAP
        self.oap_clients[mac].send(
            OAPMessage.CmdType.PUT,  # command
            [3, 2],  # address
            data_tags=[OAPMessage.TLVByte(t=0, v=value)],  # parameters
            cb=None,  # callback
        )
Esempio n. 10
0
    def _sendOap(self, macToSendTo):

        with self.dataLock:

            # build OAP message
            oap_msg = OAPMessage.build_oap(
                seq=0,
                sid=0,
                cmd=OAPMessage.CmdType.PUT,
                addr=[3, 2],
                tags=[OAPMessage.TLVByte(t=0, v=self.ledVal)],
                sync=True,
            )
            oap_msg = [ord(b) for b in oap_msg]

            # send OAP message
            connector.dn_sendData(
                macAddress=macToSendTo,
                priority=0,
                srcPort=OAPMessage.OAP_PORT,
                dstPort=OAPMessage.OAP_PORT,
                options=0x00,
                data=oap_msg,
            )
Esempio n. 11
0
    def _toggleLed(self):

        # indicate event
        self.ratecalculator.signalEvent()

        # pick the command to send
        if self.ledOn:
            ledVal = 0x00  # turn LED off
        else:
            ledVal = 0x01  # turn LED on

        # send packet
        self.oap_client.send(
            OAPMessage.CmdType.PUT,  # command
            [3, 2],  # address (digital_out=3,Actuate LED (2))
            data_tags=[OAPMessage.TLVByte(t=0, v=ledVal)],  # parameters
            cb=self._oap_response  # callback
        )

        # update my local view of the LED
        self.ledOn = not self.ledOn
Esempio n. 12
0
 def _sendOap(self,macToSendTo):
     
     with self.dataLock:
         
         # build OAP message
         oap_msg = OAPMessage.build_oap(
             seq          = 0,
             sid          = 0,
             cmd          = OAPMessage.CmdType.PUT,
             addr         = [3,2],
             tags         = [OAPMessage.TLVByte(t=0,v=self.ledVal)],
             sync         = True,
         )
         oap_msg = [ord(b) for b in oap_msg]
         
         # send OAP message
         connector.dn_sendData(
             macAddress   = macToSendTo,
             priority     = 0,
             srcPort      = OAPMessage.OAP_PORT,
             dstPort      = OAPMessage.OAP_PORT,
             options      = 0x00,
             data         = oap_msg,
         )
Esempio n. 13
0
            tempOn = 1
            userinput = raw_input('\nEnter the desired publish rate in ms (e.g. {0} ):'.format(DFLT_RATE))
            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'
        )
Esempio n. 14
0
    def _sendOapCommand(self, targetNet, targetMac, oapAddress, oapTags):

        #===== send

        dataToSend = OAPMessage.build_oap(
            0,  # seq_num
            0,  # session_id
            OAPMessage.CmdType.PUT,  # command
            oapAddress,  # address 254=pkgen
            tags=oapTags,  # parameters,
            sync=True,
        )

        dataToSend = [ord(b) for b in dataToSend]

        # dispatch
        dispatcher.send(
            signal='dataToMesh_{0}'.format(targetNet),
            data={
                'mac': targetMac,
                'priority': 0,
                'srcPort': DustLinkData.DustLinkData.WKP_OAP,
                'dstPort': DustLinkData.DustLinkData.WKP_OAP,
                'options': 0,
                'data': dataToSend,
            },
        )

        #===== compute expected ACK

        expectedAck = [0x02, 0x00, 0xff, len(oapAddress)] + oapAddress

        #===== wait for ACK

        waitStartTime = time.time()
        self.waitForResponseEvent.clear()

        while True:

            # calculate how much time left to wait for response
            timeToWait = self.MAXWAITFOROAPRESPONSE - (time.time() -
                                                       waitStartTime)
            if timeToWait < 0:
                timeToWait = None

            # wait for a response
            if self.waitForResponseEvent.wait(timeToWait):
                # I received a response

                self.waitForResponseEvent.clear()

                with self.responseBufLock:

                    if (self.reponseBuf['mac'] == targetMac and
                            self.reponseBuf['srcPort'] == OAPMessage.OAP_PORT
                            and self.reponseBuf['destPort']
                            == OAPMessage.OAP_PORT
                            and len(self.reponseBuf['payload'])
                            == len(expectedAck) + 2
                            and self.reponseBuf['payload'][-len(expectedAck):]
                            == expectedAck):
                        return

            else:
                # timeout
                raise SystemError(
                    "OAP Timeout: no ACK received after {0}s".format(
                        self.MAXWAITFOROAPRESPONSE))
Esempio n. 15
0
    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,
            )
Esempio n. 16
0
    config.password     = '******'
    config.verify_ssl   = False
    
    if os.path.isfile(certifi.where()):
        config.ssl_ca_cert  = certifi.where()
    else:
        config.ssl_ca_cert = os.path.join(os.path.dirname(sys.executable), "cacert.pem")
    
    # initialize the VManager Python library
    voyager = VManagerApi(host=mgrhost)
    
    # build OAP message
    oap_msg = OAPMessage.build_oap(
        seq             = 0,
        sid             = 0,
        cmd             = OAPMessage.CmdType.PUT,
        addr            = [3,2],
        tags            = [OAPMessage.TLVByte(t=0,v=ledVal)],
        sync           = True,
    )
    oap_msg_b64 = base64.b64encode(oap_msg)   # Convert from bin to base64

    # send the packet, once if to one mote, 4 times if Broadcast
    if macaddr == "FF-FF-FF-FF-FF-FF-FF-FF":
        loop = 3
    else:
        loop = 1
    for x in xrange(loop):
        sendapacket(macaddr, oap_msg_b64)
        time.sleep(2)

    print 'Script ended normally'
Esempio n. 17
0
    def _oap_getd0(self,mac,oap_resp):

        d0=OAPMessage.Temperature()
        d0.parse_response(oap_resp)
        self.moteListFrame.update(mac,COL_D0,d0.value)
        print d0.value
Esempio n. 18
0
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]))
Esempio n. 19
0
 def _oap_getd1(self,mac,oap_resp):
     
     d1=OAPMessage.Temperature()
     d1.parse_response(oap_resp)
     self.moteListFrame.update(mac,COL_D1,d1.value.value)
Esempio n. 20
0
    def _oap_rateGet_resp(self, mac, oap_resp):

        temp = OAPMessage.Temperature()
        temp.parse_response(oap_resp)

        self.moteListFrame.update(mac, COL_TEMP_RATE, temp.rate.value)
Esempio n. 21
0
    def _oap_getd2(self,mac,oap_resp):

        d2=OAPMessage.Temperature()
        d2.parse_response(oap_resp)
        self.moteListFrame.update(mac,COL_D2,d2.value.value)
Esempio n. 22
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!',
            })
Esempio n. 23
0
    def _oap_getd3(self,mac,oap_resp):

        d3=OAPMessage.Temperature()
        d3.parse_response(oap_resp)
        self.moteListFrame.update(mac,COL_D3,d3.value.value)
Esempio n. 24
0
 def _sendOapCommand(self,targetNet,targetMac,oapAddress,oapTags):
     
     #===== send
     
     dataToSend =    OAPMessage.build_oap(
                                         0,                       # seq_num
                                         0,                       # session_id
                                         OAPMessage.CmdType.PUT,  # command
                                         oapAddress,              # address 254=pkgen
                                         tags=oapTags,            # parameters,
                                         sync=True,
                                     )
     
     dataToSend = [ord(b) for b in dataToSend]
                     
     # dispatch
     dispatcher.send (
         signal        = 'dataToMesh_{0}'.format(targetNet),
         data          = {
             'mac':         targetMac,
             'priority':    0,
             'srcPort':     DustLinkData.DustLinkData.WKP_OAP,
             'dstPort':     DustLinkData.DustLinkData.WKP_OAP,
             'options':     0,
             'data':        dataToSend,
         },
     )
     
     #===== compute expected ACK
     
     expectedAck = [0x02,0x00,0xff,len(oapAddress)]+oapAddress
     
     #===== wait for ACK
     
     waitStartTime   = time.time()
     self.waitForResponseEvent.clear()
     
     while True:
         
         # calculate how much time left to wait for response
         timeToWait = self.MAXWAITFOROAPRESPONSE - (time.time()-waitStartTime)
         if timeToWait<0:
             timeToWait = None
         
         # wait for a response
         if self.waitForResponseEvent.wait(timeToWait):
             # I received a response
             
             self.waitForResponseEvent.clear()
             
             with self.responseBufLock:
                 
                 if (self.reponseBuf['mac']==targetMac                      and
                     self.reponseBuf['srcPort']==OAPMessage.OAP_PORT        and 
                     self.reponseBuf['destPort']==OAPMessage.OAP_PORT       and
                     len(self.reponseBuf['payload'])==len(expectedAck)+2    and
                     self.reponseBuf['payload'][-len(expectedAck):]==expectedAck
                     ):
                     return
             
         else:
             # timeout
             raise SystemError("OAP Timeout: no ACK received after {0}s".format(self.MAXWAITFOROAPRESPONSE))
Esempio n. 25
0
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]))
Esempio n. 26
0
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),
                ))
Esempio n. 27
0
 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=='OAPsound':
                     dataToSend =    OAPMessage.build_oap(
                                         0,                                   # seq_num
                                         0,                                   # session_id
                                         OAPMessage.CmdType.PUT,              # command
                                         [3,0],                               # 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
Esempio n. 28
0
                '\nEnter the desired publish rate in ms (e.g. {0} ):'.format(
                    DFLT_RATE))
            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
Esempio n. 29
0
    config.verify_ssl = False

    if os.path.isfile(certifi.where()):
        config.ssl_ca_cert = certifi.where()
    else:
        config.ssl_ca_cert = os.path.join(os.path.dirname(sys.executable),
                                          "cacert.pem")

    # initialize the VManager Python library
    voyager = VManagerApi(host=mgrhost)

    # build OAP message
    oap_msg = OAPMessage.build_oap(
        seq=0,
        sid=0,
        cmd=OAPMessage.CmdType.PUT,
        addr=[3, 2],
        tags=[OAPMessage.TLVByte(t=0, v=ledVal)],
        sync=True,
    )
    oap_msg_b64 = base64.b64encode(oap_msg)  # Convert from bin to base64

    # send the packet, once if to one mote, 4 times if Broadcast
    if macaddr == "FF-FF-FF-FF-FF-FF-FF-FF":
        loop = 3
    else:
        loop = 1
    for x in xrange(loop):
        sendapacket(macaddr, oap_msg_b64)
        time.sleep(2)

    print 'Script ended normally'
Esempio n. 30
0
    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