Exemplo n.º 1
0
 def _parseData(self,byteArray):
     
     returnVal = {}
     
     # log
     log.debug("_parseData with byteArray {0}".format(FormatUtils.formatBuffer(byteArray)))
     
     # command ID
     try:
         (returnVal['cmdId'],) = struct.unpack('>H', self._toString(byteArray[:2]))
     except struct.error as err:
         raise ValueError(err)
     
     if   returnVal['cmdId']==CMDID_CONFIGURATION:
         
         try:
             (
                 returnVal['reportPeriod'],
                 returnVal['bridgeSettlingTime'],
                 returnVal['ldoOnTime'],
             ) = struct.unpack('>III', self._toString(byteArray[2:]))
         except struct.error as err:
             raise ValueError(err)
     
     elif returnVal['cmdId']==CMDID_REPORT:
         
         try:
             (
                 returnVal['temperature'],
                 returnVal['adcValue'],
             ) = struct.unpack('>IH', self._toString(byteArray[2:]))
         except struct.error as err:
             raise ValueError(err)
     
     elif returnVal['cmdId']==ERR_NO_SERVICE:
         pass
     
     elif returnVal['cmdId'] in [ERR_NOT_ENOUGH_BW,ERR_INVALID]:
         try:
             (
                 returnVal['val'],
             ) = struct.unpack('>I', self._toString(byteArray[2:]))
         except struct.error as err:
             raise ValueError(err)
     
     else:
         raise ValueError("unexpected command ID {0}".format(returnVal['cmdId']))
     
     return returnVal
Exemplo n.º 2
0
    def calculate(self, data):

        if log.isEnabledFor(logging.DEBUG):
            log.debug('calculating for data={0}'.format(
                FormatUtils.formatBuffer(data)))

        ptr = 0
        tempfcs = 0xffff
        while ptr < len(data):
            tempfcs = (tempfcs >> 8) ^ self._fcstab[(tempfcs ^ data[ptr])
                                                    & 0xff]
            ptr += 1
        tempfcs ^= 0xffff
        fcs = []
        fcs.append((tempfcs >> 0) & 0xff)
        fcs.append((tempfcs >> 8) & 0xff)

        if log.isEnabledFor(logging.DEBUG):
            log.debug('fcs=0x%2x%2x', fcs[0], fcs[1])

        return fcs
Exemplo n.º 3
0
 def calculate(self,data):
     
     if log.isEnabledFor(logging.DEBUG):
         log.debug('calculating for data={0}'.format(FormatUtils.formatBuffer(data)))
     
     ptr = 0
     tempfcs = 0xffff
     while ptr<len(data):
         tempfcs = (tempfcs >> 8) ^ self._fcstab[(tempfcs ^ data[ptr]) & 0xff];
         ptr += 1
     tempfcs ^= 0xffff
     fcs  = []
     fcs.append( (tempfcs>>0) & 0xff )
     fcs.append( (tempfcs>>8) & 0xff )
     
     if log.isEnabledFor(logging.DEBUG):
         log.debug('fcs=0x%2x%2x',fcs[0],fcs[1])
     
     return fcs
 
 #======================== private =========================================
Exemplo n.º 4
0
    def deserialize(self, type, id, byteArray):
        notRcOk = False
        returnFields = {}
        nameArray = [self.ApiDef.idToName(type, id)]
        index = 0

        # log
        if log.isEnabledFor(logging.DEBUG):
            output = []
            output += ["deserialize ..."]
            output += ["- type:             {0}".format(type)]
            output += ["- id:               {0}".format(id)]
            output += [
                "- byteArray:        {0}".format(
                    FormatUtils.formatBuffer(byteArray))
            ]
            output = '\n'.join(output)
            log.debug(output)

        continueParsing = True
        while continueParsing:

            fieldDefs = self.ApiDef.getResponseFields(type, nameArray)

            for fieldDef in fieldDefs:

                fieldMissing = False

                # isolate the piece of the byteArray corresponding to this field
                if fieldDef.length:
                    # this field has an expected length

                    thisFieldArray = byteArray[index:index + fieldDef.length]
                    index += fieldDef.length

                    if len(thisFieldArray) == 0:
                        # field missing: allowed
                        fieldMissing = True
                    elif len(thisFieldArray) < fieldDef.length:
                        # incomplete field: not allowed
                        raise CommandError(
                            CommandError.TOO_FEW_BYTES,
                            "incomplete field {0}".format(fieldDef.name),
                        )

                else:
                    thisFieldArray = byteArray[index:]
                    index = len(byteArray)

                    if len(thisFieldArray) < 1:
                        # too few bytes
                        fieldMissing = True

                # find thisFieldValue
                if fieldMissing:
                    thisFieldValue = None
                else:
                    if fieldDef.format == ApiDefinition.FieldFormats.STRING:
                        thisFieldValue = ''
                        for byte in thisFieldArray:
                            thisFieldValue += chr(byte)

                    elif fieldDef.format == ApiDefinition.FieldFormats.BOOL:
                        if len(thisFieldArray
                               ) == 1 and thisFieldArray[0] == 0x00:
                            thisFieldValue = False
                        elif len(thisFieldArray
                                 ) == 1 and thisFieldArray[0] == 0x01:
                            thisFieldValue = True
                        else:
                            raise CommandError(
                                CommandError.VALUE_NOT_IN_OPTIONS,
                                "field=" + fieldDef.name + " value=" +
                                str(thisFieldValue))

                    elif fieldDef.format == ApiDefinition.FieldFormats.INT:
                        thisFieldValue = 0
                        for i in range(len(thisFieldArray)):
                            thisFieldValue += thisFieldArray[i] * pow(
                                2, 8 * (len(thisFieldArray) - i - 1))

                    elif fieldDef.format == ApiDefinition.FieldFormats.INTS:
                        tempList = [chr(i) for i in thisFieldArray]
                        tempString = ''.join(tempList)
                        if len(thisFieldArray) == 1:
                            (thisFieldValue, ) = struct.unpack_from(
                                '>b', tempString)
                        elif len(thisFieldArray) == 2:
                            (thisFieldValue, ) = struct.unpack_from(
                                '>h', tempString)
                        elif len(thisFieldArray) == 4:
                            (thisFieldValue, ) = struct.unpack_from(
                                '>i', tempString)
                        else:
                            raise SystemError('field with format=' +
                                              fieldDef.format +
                                              ' and length=' +
                                              str(fieldDef.length) +
                                              ' unsupported.')

                    elif fieldDef.format == ApiDefinition.FieldFormats.HEXDATA:
                        thisFieldValue = thisFieldArray

                    else:
                        raise SystemError('unknown field format=' +
                                          fieldDef.format)

                    # make sure thisFieldValue in fieldDef.options
                    if fieldDef.options.validOptions:
                        if thisFieldValue not in fieldDef.options.validOptions:
                            raise CommandError(
                                CommandError.VALUE_NOT_IN_OPTIONS,
                                "field=" + fieldDef.name + " value=" +
                                str(thisFieldValue))

                if fieldDef.name in ApiDefinition.ApiDefinition.RESERVED:
                    # the subcommand specifier cannot be missing
                    if thisFieldValue == None:
                        raise CommandError(
                            CommandError.TOO_FEW_BYTES,
                            "reserved field missing {0}".format(fieldDef.name),
                        )
                    idNextCommand = thisFieldValue
                else:
                    returnFields[fieldDef.name] = thisFieldValue

                # stop if not RC_OK
                if  (
                        (ApiDefinition.ApiDefinition.RC in returnFields) and
                        (
                            returnFields[ApiDefinition.ApiDefinition.RC]!= \
                                ApiDefinition.ApiDefinition.RC_OK
                        )
                   ):
                    notRcOk = True
                    break

            # continue if subCommand
            if ((not notRcOk) and continueParsing
                    and self.ApiDef.hasSubcommands(type, nameArray)):
                # find name of subCommand
                nameArray.append(
                    self.ApiDef.subcommandIdToName(type, nameArray,
                                                   idNextCommand))
                continueParsing = True
            else:
                continueParsing = False

            # stop if not RC_OK
            if (continueParsing and notRcOk):
                continueParsing = False

            # stop if end of packet reached
            if (continueParsing and index >= len(byteArray)):
                continueParsing = False

        if log.isEnabledFor(logging.DEBUG):
            output = []
            output += ["... deserialized into"]
            output += ["- nameArray:        {0}".format(nameArray)]
            output += ["- returnFields:     {0}".format(returnFields)]
            output = '\n'.join(output)
            log.debug(output)

        return nameArray, returnFields
Exemplo n.º 5
0
 def serialize(self,commandArray,fieldsToFill):
     
     # log
     if log.isEnabledFor(logging.DEBUG):
         output  = []
         output += ["serialize ..."]
         output += ["- commandArray:     {0}".format(commandArray)]
         output += ["- fieldsToFill:     {0}".format(fieldsToFill)]
         output  = '\n'.join(output)
         log.debug(output)
     
     # validate input
     if type(commandArray)!=types.ListType and type(commandArray)!=types.TupleType:
         raise TypeError("First parameter should be a list or tuple, not "+str(type(commandArray)))
     
     # initialize the output
     byteArray  = []
     
     for cmdCounter in range(len(commandArray)):
     
         # packet payload
         definition = self.ApiDef.getDefinition(
             ApiDefinition.ApiDefinition.COMMAND,
             commandArray[:cmdCounter+1]
         )
         
         fields = [ApiDefinition.Field(fieldRaw,self.ApiDef.fieldOptions)
                      for fieldRaw in definition['request']]
         
         for field in fields:
             thisFieldByteArray = []
             if field.name in ApiDefinition.ApiDefinition.RESERVED:
                 thisFieldByteArray.append(
                     self.ApiDef.subcommandNameToId(
                         ApiDefinition.ApiDefinition.COMMAND,
                         commandArray[:cmdCounter+1],
                         commandArray[cmdCounter+1]
                     )
                 )
             else:
                 val                          = fieldsToFill[field.name]
                 
                 if   field.format==ApiDefinition.FieldFormats.STRING:
                     thisFieldByteArray      += [ord(car) for car in val]
                 
                 elif field.format==ApiDefinition.FieldFormats.BOOL:
                     thisFieldByteArray.append(val)
                 
                 elif field.format==ApiDefinition.FieldFormats.INT:
                     thisFieldByteArray      += [operator.mod(int(val>>(8*i)), 0x100) for i in xrange(field.length-1, -1, -1)]
                 
                 elif field.format==ApiDefinition.FieldFormats.INTS:
                     if   field.length==1:
                         temp = struct.pack('>b',int(val))
                     elif field.length==2:
                         temp = struct.pack('>h',int(val))
                     elif field.length==4:
                         temp = struct.pack('>i',int(val))
                     else:
                         raise SystemError('field with format='+field.format+' and length='+str(field.length)+' unsupported.')
                     for i in range(len(temp)):
                         thisFieldByteArray.append(ord(temp[i]))
                 
                 elif field.format==ApiDefinition.FieldFormats.HEXDATA:
                     thisFieldByteArray    += val
                 
                 else:
                     raise SystemError('unknown field format='+field.format)
                 
                 # padding
                 while len(thisFieldByteArray)<field.length:
                     thisFieldByteArray  = [0x00]+thisFieldByteArray
             
             byteArray = byteArray+thisFieldByteArray
     
     cmdId = self.ApiDef.nameToId(ApiDefinition.ApiDefinition.COMMAND,commandArray)
     
     if log.isEnabledFor(logging.DEBUG):
         output  = []
         output += ["... serialize into"]
         output += ["- cmdId:            {0}".format(cmdId)]
         output += ["- byteArray:        {0}".format(FormatUtils.formatBuffer(byteArray))]
         output  = '\n'.join(output)
         log.debug(output)
     
     return cmdId,byteArray
Exemplo n.º 6
0
 def deserialize(self,type,id,byteArray):
     notRcOk         = False
     returnFields    = {}
     nameArray       = [self.ApiDef.idToName(type,id)]
     index           = 0
     
     # log
     if log.isEnabledFor(logging.DEBUG):
         output  = []
         output += ["deserialize ..."]
         output += ["- type:             {0}".format(type)]
         output += ["- id:               {0}".format(id)]
         output += ["- byteArray:        {0}".format(FormatUtils.formatBuffer(byteArray))]
         output  = '\n'.join(output)
         log.debug(output)
     
     continueParsing  = True
     while continueParsing:
         
         fieldDefs   = self.ApiDef.getResponseFields(type,nameArray)
         
         for fieldDef in fieldDefs:
             
             fieldMissing = False
             
             # isolate the piece of the byteArray corresponding to this field
             if fieldDef.length:
                 # this field has an expected length
                 
                 thisFieldArray = byteArray[index:index+fieldDef.length]
                 index         += fieldDef.length
                 
                 if   len(thisFieldArray)==0:
                     # field missing: allowed
                     fieldMissing   = True
                 elif len(thisFieldArray)<fieldDef.length:
                     # incomplete field: not allowed
                     raise CommandError(
                         CommandError.TOO_FEW_BYTES,
                         "incomplete field {0}".format(fieldDef.name),
                     )
                 
             else:
                 thisFieldArray = byteArray[index:]
                 index          = len(byteArray)
                 
                 if len(thisFieldArray)<1:
                     # too few bytes
                     fieldMissing    = True
             
             # find thisFieldValue
             if fieldMissing:
                 thisFieldValue = None
             else:
                 if   fieldDef.format==ApiDefinition.FieldFormats.STRING:
                     thisFieldValue = ''
                     for byte in thisFieldArray:
                         thisFieldValue += chr(byte)
                 
                 elif fieldDef.format==ApiDefinition.FieldFormats.BOOL:
                     if    len(thisFieldArray)==1 and thisFieldArray[0]==0x00:
                         thisFieldValue = False
                     elif  len(thisFieldArray)==1 and thisFieldArray[0]==0x01:
                         thisFieldValue = True
                     else:
                         raise CommandError(CommandError.VALUE_NOT_IN_OPTIONS,
                                            "field="+fieldDef.name+" value="+str(thisFieldValue))
                 
                 elif fieldDef.format==ApiDefinition.FieldFormats.INT:
                     thisFieldValue = 0
                     for i in range(len(thisFieldArray)):
                         thisFieldValue += thisFieldArray[i]*pow(2,8*(len(thisFieldArray)-i-1))
                 
                 elif fieldDef.format==ApiDefinition.FieldFormats.INTS:
                     tempList = [chr(i) for i in thisFieldArray]
                     tempString = ''.join(tempList)
                     if   len(thisFieldArray)==1:
                         (thisFieldValue,) = struct.unpack_from('>b',tempString)
                     elif len(thisFieldArray)==2:
                         (thisFieldValue,) = struct.unpack_from('>h',tempString)
                     elif len(thisFieldArray)==4:
                         (thisFieldValue,) = struct.unpack_from('>i',tempString)
                     else:
                         raise SystemError('field with format='+fieldDef.format+' and length='+str(fieldDef.length)+' unsupported.')
                 
                 elif fieldDef.format==ApiDefinition.FieldFormats.HEXDATA:
                     thisFieldValue = thisFieldArray
                 
                 else:
                     raise SystemError('unknown field format='+fieldDef.format)
                 
                 # make sure thisFieldValue in fieldDef.options
                 if fieldDef.options.validOptions:
                     if thisFieldValue not in fieldDef.options.validOptions:
                         raise CommandError(CommandError.VALUE_NOT_IN_OPTIONS,
                                            "field="+fieldDef.name+" value="+str(thisFieldValue))
             
             if fieldDef.name in ApiDefinition.ApiDefinition.RESERVED:
                 # the subcommand specifier cannot be missing
                 if thisFieldValue==None:
                     raise CommandError(
                         CommandError.TOO_FEW_BYTES,
                         "reserved field missing {0}".format(fieldDef.name),
                     )
                 idNextCommand = thisFieldValue
             else:
                 returnFields[fieldDef.name] = thisFieldValue
                 
             # stop if not RC_OK
             if  (
                     (ApiDefinition.ApiDefinition.RC in returnFields) and
                     (
                         returnFields[ApiDefinition.ApiDefinition.RC]!= \
                             ApiDefinition.ApiDefinition.RC_OK
                     )
                ):
                notRcOk = True
                break
         
         # continue if subCommand
         if  (
                 (not notRcOk)           and
                 continueParsing         and
                 self.ApiDef.hasSubcommands(type,nameArray)
             ):
             # find name of subCommand
             nameArray.append(self.ApiDef.subcommandIdToName(type,
                                                             nameArray,
                                                             idNextCommand))
             continueParsing = True
         else:
             continueParsing = False
         
         # stop if not RC_OK
         if  (
                 continueParsing         and
                 notRcOk
             ):
             continueParsing = False
         
         # stop if end of packet reached
         if  (
                 continueParsing         and
                 index>=len(byteArray)
             ):
             continueParsing = False
     
     if log.isEnabledFor(logging.DEBUG):
         output  = []
         output += ["... deserialized into"]
         output += ["- nameArray:        {0}".format(nameArray)]
         output += ["- returnFields:     {0}".format(returnFields)]
         output  = '\n'.join(output)
         log.debug(output)
     
     return nameArray,returnFields
Exemplo n.º 7
0
    def _ipmt_notif(self, cmdId, subcmdId):
        '''
        \brief Called by C library when a notification is received.
        '''
        log.debug('_ipmt_notif cmdId={0} subcmdId={1} notifBuf={2}'.format(
            cmdId,
            subcmdId,
            FormatUtils.formatBuffer([ord(b) for b in self.notifBuf]),
        ))

        #===== cast notification buffer to correct type

        # find apiNotif
        apiNotifFields = []
        nameArray = []
        for notif in IpMoteDefinition.IpMoteDefinition.notifications:
            if notif['id'] == cmdId:
                nameArray += [notif['name']]
                for f in notif['response']['FIELDS']:
                    if f[0] not in [SUBID1, SUBID2]:
                        apiNotifFields += [f]

        # create returned fields on the fly
        theseFields = []
        lengthField = None
        for [name, type, length, _] in apiNotifFields:
            if length == None:
                theseFields += [('{0}Len'.format(name), c_uint8)]
                theseFields += [(name, c_uint8 * self.MAX_FRAME_LENGTH)]
                lengthField = name
            else:
                theseFields += [(name, _getResponseType(type, length))]

        # Structure to hold the response
        class reply_t(Structure):
            _fields_ = theseFields

        # cast response to that structure
        c_notif = cast(self.notifBuf, POINTER(reply_t))

        #===== convert C notification to Python dictionary

        # convert structure to dictionary
        py_notif = {}
        for (f, _) in theseFields:
            rawVal = getattr(c_notif.contents, f)
            if isinstance(rawVal, int):
                py_notif[f] = rawVal
            elif isinstance(rawVal, long):
                py_notif[f] = int(rawVal)
            else:
                py_notif[f] = [int(b) for b in rawVal]

        # trim lengthField
        if lengthField != None:
            py_notif[lengthField] = py_notif[
                lengthField][:py_notif['{0}Len'.format(lengthField)]]
            del py_notif['{0}Len'.format(lengthField)]

        #===== put received packet in notification buffer

        self.putNotification((nameArray, py_notif))
Exemplo n.º 8
0
    def _notifDataCallback(self,notifName,notifParams):
        
        # only accept data from mote selected in the optionbox
        selectedMote = dc2126aData().get('selectedMote')
        
        if not selectedMote:
            return

        if tuple(notifParams.macAddress) != tuple(selectedMote):
            return
        
        if notifParams.dstPort!=WKP_DC2126A:
            return
        
        # parse data
        try:
            parsedData = self._parseData(notifParams.data)
        except ValueError as err:
            output  = []
            output += ["Could not parse received data {0}".format(
                FormatUtils.formatBuffer(notifParams.data)
            )]
            output += ['Error: {0}'.format(type(err))]
            output += ['{0}'.format(err)]
            output  = '\n'.join(output)
            print output
            log.error(output)
            return
        
        # log
        output  = []
        output += ["Received data:"]
        for (k,v) in parsedData.items():
            output += ["- {0:<15}: 0x{1:x} ({1})".format(k,v)]
        output  = '\n'.join(output)
        log.debug(output)
        
        # handle data
        if   parsedData['cmdId']==CMDID_REPORT:
            
            # record temperature
            temperature = self.converters.convertTemperature(parsedData['temperature'])
            dc2126aData().set('temperature',temperature)
            
            # record adcValue
            adcValue = self.converters.convertAdcValue(parsedData['adcValue'])
            dc2126aData().set('adcValue',adcValue)
            
            # record energysource
            energysource = self.converters.convertEnergySource(notifParams.macAddress,adcValue)
            dc2126aData().set('energysource',energysource)
        
        elif parsedData['cmdId']==CMDID_CONFIGURATION:
            
            # show new CFG values 
            self.displayConfigurationCB(parsedData)
            
        elif parsedData['cmdId']==ERR_NO_SERVICE:
            
            # display message
            output  = []
            output += ['This configuration was NOT accepted by the mote.']
            output += ['The mote indicated it cannot change its configuration']
            output += ['at this point since no network service has been']
            output += ['installed yet. Retry sending this command later.']
            output  = '\n'.join(output)
            self.displayErrorCB(output)
        
        elif parsedData['cmdId']==ERR_NOT_ENOUGH_BW:
            
            # display message
            output  = []
            output += ['This configuration was NOT accepted by the mote.']
            output += ['The mote indicated its current service is {}ms,'.format(parsedData['val'])]
            output += ['which is not sufficient for this configuration.']
            output  = '\n'.join(output)
            self.displayErrorCB(output)
        
        elif parsedData['cmdId']==ERR_INVALID:
            
            # display message
            output  = []
            output += ['This configuration was NOT accepted by the mote.']
            output += ['The mote indicated value {0} is invalid.'.format(parsedData['val'])]
            output  = '\n'.join(output)
            self.displayErrorCB(output)
        
        else:
            
            # display error
            self.displayErrorCB("received unexpected cmdId {0}".format(parsedData['cmdId']))
Exemplo n.º 9
0
def connect(params):
    # filter params
    #port = params[0]
    port = params

    try:
        AppData().get('connector')
    except KeyError:
        pass
    else:
        print 'already connected.'
        return

    # create a connector
    AppData().set('connector', IpMgrConnectorSerial.IpMgrConnectorSerial())

    # connect to the manager
    try:
        AppData().get('connector').connect({
            'port': port,
        })
    except ConnectionError as err:
        print 'Could not connect to {0}: {1}'.format(
            port,
            err,
        )
        AppData().delete('connector')
        return

    # Set ACL's
    joinKey = [
        0x44, 0x55, 0x53, 0x54, 0x4E, 0x45, 0x54, 0x57, 0x4F, 0x52, 0x4B, 0x53,
        0x52, 0x4F, 0x43, 0x4B
    ]
    mac = [0x00, 0x17, 0x0d, 0x00, 0x00, 0x30, 0xb3, 0x5c]
    print "Setting ACL for {0} to {1}".format(FormatUtils.formatBuffer(mac),
                                              joinKey)
    AppData().get('connector').dn_setACLEntry(macAddress=mac, joinKey=joinKey)

    joinKey = [
        0x44, 0x55, 0x53, 0x54, 0x4E, 0x45, 0x54, 0x57, 0x4F, 0x52, 0x4B, 0x53,
        0x52, 0x4F, 0x43, 0x4B
    ]
    mac = [0x00, 0x17, 0x0d, 0x00, 0x00, 0x30, 0xb6, 0x81]
    print "Setting ACL for {0} to {1}".format(FormatUtils.formatBuffer(mac),
                                              joinKey)
    AppData().get('connector').dn_setACLEntry(macAddress=mac, joinKey=joinKey)

    joinKey = [
        0x44, 0x55, 0x53, 0x54, 0x4E, 0x45, 0x54, 0x57, 0x4F, 0x52, 0x4B, 0x53,
        0x52, 0x4F, 0x43, 0x4B
    ]
    print "Setting common join key to {0}".format(
        FormatUtils.formatBuffer(joinKey))
    AppData().get('connector').dn_setCommonJoinKey(joinKey)

    networkId = 1337
    apTxPower = 8  # TX power 8
    frameProfile = 1  # Frame profile 1
    maxMotes = 33
    baseBandwidth = 9000
    downFrameMultVal = 1
    numParents = 2
    ccaMode = 0  # off
    channelList = 32767
    autoStartNetwork = True
    locMode = 0
    bbMode = 0  # off
    bbSize = 1
    isRadioTest = 0
    bwMult = 300
    oneChannel = 255

    print "Setting network ID to {0}".format(networkId)
    AppData().get('connector').dn_setNetworkConfig(
        networkId=networkId,
        apTxPower=apTxPower,
        frameProfile=frameProfile,
        maxMotes=maxMotes,
        baseBandwidth=baseBandwidth,
        downFrameMultVal=downFrameMultVal,
        numParents=numParents,
        ccaMode=ccaMode,
        channelList=channelList,
        autoStartNetwork=autoStartNetwork,
        locMode=locMode,
        bbMode=bbMode,
        bbSize=bbSize,
        isRadioTest=isRadioTest,
        bwMult=bwMult,
        oneChannel=oneChannel)

    print "Resetting manager"
    mac = [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]
    AppData().get('connector').dn_reset(0, mac)  # System Reset

    # start threads
    AppData().set('manager', Manager())
            print '==== Connect mote {0} to your computer (or Ctrl+C to quit)'.format(
                motecount)

            serialport = raw_input(
                "    Serial port of SmartMesh IP Mote (e.g. {0}): ".format(
                    DEFAULT_MOTESERIALPORT))
            serialport = serialport.strip()
            if not serialport:
                serialport = DEFAULT_MOTESERIALPORT
            mote.connect({'port': serialport})
            print '    Connected to mote at {0}.'.format(serialport)

            joinKey = [random.randint(0x00, 0xff) for _ in range(16)]
            #joinKey = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15] # default key
            print '    Random join key: {0}'.format(
                FormatUtils.formatBuffer(joinKey))

            macAddress = mote.dn_getParameter_macAddress().macAddress
            print '    mote\'s MAC address: {0}'.format(
                FormatUtils.formatBuffer(macAddress))

            print '    Writing joinKey in mote...',
            mote.dn_setParameter_joinKey(joinKey=joinKey)
            print 'done.'

            print '    Configuring joinKey in manager...',
            manager.dn_setACLEntry(
                macAddress=macAddress,
                joinKey=joinKey,
            )
            print 'done.'
Exemplo n.º 11
0
    serialport = raw_input(
        "Serial port of SmartMesh IP Manager (e.g. {0}): ".format(
            DEFAULT_MGRSERIALPORT))
    serialport = serialport.strip()
    if not serialport:
        serialport = DEFAULT_MGRSERIALPORT
    manager.connect({'port': serialport})
    print 'Connected to manager at {0}.\n'.format(serialport)

    # Create ACL until the final of file

    print '    Detele ACL on the manager... \n',
    with open('decFile.json', 'r') as MacFile:
        for line in MacFile:
            data = json.loads(line)
            print('MAC address:{}'.format(FormatUtils.formatBuffer(
                data['MAC'])))
            manager.dn_deleteACLEntry(macAddress=data['MAC'], )
    print 'done.'

    # Reset whole system to apply new ACL

    print '\n\n==== disconnect from manager'
    manager.disconnect()
    print 'Bye bye.\n'

except Exception as err:
    output = []
    output += ['=============']
    output += ['CRASH']
    output += [str(err)]
    output += [traceback.format_exc()]
Exemplo n.º 12
0
 def write(self, stringToWrite):
     self.hdlcBytes = [ord(b) for b in stringToWrite]
     print 'HdlcConverter.write {0}'.format(
         FormatUtils.formatBuffer(self.hdlcBytes))
     self.doneSem.release()
     return len(stringToWrite)
Exemplo n.º 13
0
 def write(self,stringToWrite):
     self.hdlcBytes = [ord(b) for b in stringToWrite]
     print 'HdlcConverter.write {0}'.format(FormatUtils.formatBuffer(self.hdlcBytes))
     self.doneSem.release()
     return len(stringToWrite)
Exemplo n.º 14
0
try:
    manager        = IpMgrConnectorSerial.IpMgrConnectorSerial()
    
    print 'ACL Commissioning (c) Dust Networks'
    print 'SmartMesh SDK {0}\n'.format('.'.join([str(b) for b in sdk_version.VERSION]))
    
    print '==== Connect to manager'
    serialport     = ""
    if not serialport:
        serialport = DEFAULT_MGRSERIALPORT
	manager.connect({'port': serialport})
	print 'Connected to manager at {0}.\n'.format(serialport)
	
	joinKey = [0x44, 0x55, 0x53, 0x54, 0x4E, 0x45, 0x54, 0x57, 0x4F, 0x52, 0x4B, 0x53, 0x52, 0x4F, 0x43, 0x4B]
	mac = [0x00, 0x17, 0x0d, 0x00, 0x00, 0x30, 0xb3, 0x5c]
	print "Setting ACL for {0} to {1}".format(FormatUtils.formatBuffer(mac), joinKey)
	manager.dn_setACLEntry(macAddress = mac, joinKey = joinKey)
	
	joinKey = [0x44, 0x55, 0x53, 0x54, 0x4E, 0x45, 0x54, 0x57, 0x4F, 0x52, 0x4B, 0x53, 0x52, 0x4F, 0x43, 0x4B]
	mac = [0x00, 0x17, 0x0d, 0x00, 0x00, 0x30, 0xb6, 0x81]
	print "Setting ACL for {0} to {1}".format(FormatUtils.formatBuffer(mac), joinKey)
	manager.dn_setACLEntry(macAddress = mac, joinKey = joinKey)
	
	joinKey = [0x44, 0x55, 0x53, 0x54, 0x4E, 0x45, 0x54, 0x57, 0x4F, 0x52, 0x4B, 0x53, 0x52, 0x4F, 0x43, 0x4B]
	print "Setting common join key to {0}".format(FormatUtils.formatBuffer(joinKey))
	manager.dn_setCommonJoinKey(joinKey)
    
	networkId = 1337
	apTxPower = 8 # TX power 8
	frameProfile = 1 # Frame profile 1
	maxMotes = 33
Exemplo n.º 15
0
    def json_to_influxdb(self, sol_json, tags):
        """
        Convert a JSON SOL object into a InfluxDB point

        :param list sol_json: JSON SOL object
        :return: InfluxDB point
        :rtpe: list
        """

        # fields
        if sol_json['type'] == SolDefines.SOL_TYPE_DUST_NOTIF_HRNEIGHBORS:
            fields = {}
            for n in sol_json["value"]['neighbors']:
                fields["neighbors:" + str(n['neighborId'])] = n
            fields['numItems'] = sol_json["value"]['numItems']
        elif sol_json['type'] == SolDefines.SOL_TYPE_DUST_NOTIF_HRDISCOVERED:
            fields = sol_json["value"]
        elif sol_json['type'] == SolDefines.SOL_TYPE_DUST_SNAPSHOT:
            fields = {}
            fields["mote"] = []
            for mote in sol_json["value"]:
                mote["macAddress"] = FormatUtils.formatBuffer(
                    mote["macAddress"])
                for path in mote["paths"]:
                    path["macAddress"] = FormatUtils.formatBuffer(
                        path["macAddress"])
                fields["mote"].append(mote)
        elif sol_json['type'] == SolDefines.SOL_TYPE_DUST_EVENTNETWORKRESET:
            fields = {'value': 'dummy'}
        else:
            fields = sol_json["value"]
            for (k, v) in fields.items():
                if type(v) == list:  # mac
                    if k in ['macAddress', 'source', 'dest']:
                        fields[k] = FormatUtils.formatBuffer(v)
                    elif k in [
                            'sol_version', 'sdk_version', 'solmanager_version'
                    ]:
                        fields[k] = ".".join(str(i) for i in v)

        f = flatdict.FlatDict(fields)
        fields = {}
        for (k, v) in f.items():
            fields[k] = v

        # add additionnal fiel if apply_function exists
        try:
            obj_struct = SolDefines.solStructure(sol_json['type'])
            if 'apply' in obj_struct:
                for ap in obj_struct['apply']:
                    arg_list = [fields[arg] for arg in ap["args"]]
                    fields[ap["name"]] = ap["function"](*arg_list)
        except ValueError:
            pass

        # get SOL type
        measurement = SolDefines.solTypeToTypeName(SolDefines,
                                                   sol_json['type'])

        # convert SOL timestamp to UTC
        utc_time = sol_json["timestamp"] * 1000000000

        sol_influxdb = {
            "time": utc_time,
            "tags": tags,
            "measurement": measurement,
            "fields": fields,
        }

        return sol_influxdb
Exemplo n.º 16
0
    def serialize(self, commandArray, fieldsToFill):

        # log
        if log.isEnabledFor(logging.DEBUG):
            output = []
            output += ["serialize ..."]
            output += ["- commandArray:     {0}".format(commandArray)]
            output += ["- fieldsToFill:     {0}".format(fieldsToFill)]
            output = '\n'.join(output)
            log.debug(output)

        # validate input
        if type(commandArray) != types.ListType and type(
                commandArray) != types.TupleType:
            raise TypeError("First parameter should be a list or tuple, not " +
                            str(type(commandArray)))

        # initialize the output
        byteArray = []

        for cmdCounter in range(len(commandArray)):

            # packet payload
            definition = self.ApiDef.getDefinition(
                ApiDefinition.ApiDefinition.COMMAND,
                commandArray[:cmdCounter + 1])

            fields = [
                ApiDefinition.Field(fieldRaw, self.ApiDef.fieldOptions)
                for fieldRaw in definition['request']
            ]

            for field in fields:
                thisFieldByteArray = []
                if field.name in ApiDefinition.ApiDefinition.RESERVED:
                    thisFieldByteArray.append(
                        self.ApiDef.subcommandNameToId(
                            ApiDefinition.ApiDefinition.COMMAND,
                            commandArray[:cmdCounter + 1],
                            commandArray[cmdCounter + 1]))
                else:
                    val = fieldsToFill[field.name]

                    if field.format == ApiDefinition.FieldFormats.STRING:
                        thisFieldByteArray += [ord(car) for car in val]

                    elif field.format == ApiDefinition.FieldFormats.BOOL:
                        thisFieldByteArray.append(val)

                    elif field.format == ApiDefinition.FieldFormats.INT:
                        thisFieldByteArray += [
                            operator.mod(int(val >> (8 * i)), 0x100)
                            for i in xrange(field.length - 1, -1, -1)
                        ]

                    elif field.format == ApiDefinition.FieldFormats.INTS:
                        if field.length == 1:
                            temp = struct.pack('>b', int(val))
                        elif field.length == 2:
                            temp = struct.pack('>h', int(val))
                        elif field.length == 4:
                            temp = struct.pack('>i', int(val))
                        else:
                            raise SystemError('field with format=' +
                                              field.format + ' and length=' +
                                              str(field.length) +
                                              ' unsupported.')
                        for i in range(len(temp)):
                            thisFieldByteArray.append(ord(temp[i]))

                    elif field.format == ApiDefinition.FieldFormats.HEXDATA:
                        thisFieldByteArray += val

                    else:
                        raise SystemError('unknown field format=' +
                                          field.format)

                    # padding
                    while len(thisFieldByteArray) < field.length:
                        thisFieldByteArray = [0x00] + thisFieldByteArray

                byteArray = byteArray + thisFieldByteArray

        cmdId = self.ApiDef.nameToId(ApiDefinition.ApiDefinition.COMMAND,
                                     commandArray)

        if log.isEnabledFor(logging.DEBUG):
            output = []
            output += ["... serialize into"]
            output += ["- cmdId:            {0}".format(cmdId)]
            output += [
                "- byteArray:        {0}".format(
                    FormatUtils.formatBuffer(byteArray))
            ]
            output = '\n'.join(output)
            log.debug(output)

        return cmdId, byteArray
Exemplo n.º 17
0
 def _whmt_notif(self,cmdId,subcmdId):
     '''
     \brief Called by C library when a notification is received.
     '''
     log.debug(
         '_whmt_notif cmdId={0} subcmdId={1} notifBuf={2}'.format(
             cmdId,
             subcmdId,
             FormatUtils.formatBuffer([ord(b) for b in self.notifBuf]),
         )
     )
     
     #===== cast notification buffer to correct type
     
     # find apiNotif
     apiNotifFields  = []
     nameArray       = []
     for notif in HartMoteDefinition.HartMoteDefinition.notifications:
         if notif['id']==cmdId:
             nameArray += [notif['name']]
             for f in notif['response']['FIELDS']:
                 if f[0] not in [SUBID1,SUBID2]:
                     apiNotifFields += [f]
     
     # create returned fields on the fly
     theseFields = []
     lengthField = None
     for [name,type,length,_] in apiNotifFields:
         if length==None:
             theseFields += [('{0}Len'.format(name), c_uint8)]
             theseFields += [(name,                  c_uint8*self.MAX_FRAME_LENGTH)]
             lengthField  = name
         else:
             theseFields += [(name, _getResponseType(type,length))]
     
     # Structure to hold the response
     class reply_t(Structure):
         _fields_    = theseFields
     
     # cast response to that structure
     c_notif         = cast(self.notifBuf, POINTER(reply_t))
     
     #===== convert C notification to Python dictionary
     
     # convert structure to dictionary
     py_notif = {}
     for (f,_) in theseFields:
         rawVal = getattr(c_notif.contents,f)
         if  isinstance(rawVal,int):
             py_notif[f] = rawVal
         elif isinstance(rawVal,long):
             py_notif[f] = int(rawVal)
         else:
             py_notif[f] = [int(b) for b in rawVal]
     
     # trim lengthField
     if lengthField!=None:
         py_notif[lengthField] = py_notif[lengthField][:py_notif['{0}Len'.format(lengthField)]]
         del py_notif['{0}Len'.format(lengthField)]
     
     #===== put received packet in notification buffer
     
     self.putNotification((nameArray, py_notif))
Exemplo n.º 18
0
    def json_to_influxdb(self,sol_json,tags):
        """
        Convert a JSON SOL object into a InfluxDB point

        :param list sol_json: JSON SOL object
        :return: InfluxDB point
        :rtpe: list
        """
        # tags
        obj_tags = copy.deepcopy(tags)

        # fields
        if   sol_json['type']==SolDefines.SOL_TYPE_DUST_NOTIF_HRNEIGHBORS:
            fields = {}
            for n in sol_json["value"]['neighbors']:
                fields["neighbors:" + str(n['neighborId'])] = n
            fields['numItems'] = sol_json["value"]['numItems']
        elif sol_json['type']==SolDefines.SOL_TYPE_DUST_NOTIF_HRDISCOVERED:
            fields = sol_json["value"]
        elif sol_json['type']==SolDefines.SOL_TYPE_DUST_SNAPSHOT:
            fields = {}
            fields["mote"] = []
            for mote in sol_json["value"]:
                mote["macAddress"] = FormatUtils.formatBuffer(mote["macAddress"])
                for path in mote["paths"]:
                    path["macAddress"] = FormatUtils.formatBuffer(path["macAddress"])
                fields["mote"].append(mote)
        elif sol_json['type']==SolDefines.SOL_TYPE_DUST_EVENTNETWORKRESET:
            fields = {'value':'dummy'}
        else:
            fields = sol_json["value"]
            for (k,v) in fields.items():
                if type(v)==list: # mac
                    if k in ['macAddress','source','dest']:
                        fields[k] = FormatUtils.formatBuffer(v)
                    elif k in ['sol_version','sdk_version','solmanager_version']:
                        fields[k] = ".".join(str(i) for i in v)

        f = flatdict.FlatDict(fields)
        fields = {}
        for (k,v) in f.items():
            fields[k] = v

        # add additionnal field or tag if apply_function exists
        try:
            obj_struct = SolDefines.solStructure(sol_json['type'])
            if 'apply' in obj_struct:
                for ap in obj_struct['apply']:
                    arg_list = [fields[arg] for arg in ap["args"]]
                    if "field" in ap:
                        fields[ap["field"]] = ap["function"](*arg_list)
                    if "tag" in ap:
                        obj_tags[ap["tag"]] = ap["function"](*arg_list)
        except ValueError:
            pass

        # get SOL type
        measurement = SolDefines.solTypeToTypeName(SolDefines,sol_json['type'])

        # convert SOL timestamp to UTC
        utc_time = sol_json["timestamp"]*1000000000

        sol_influxdb = {
                "time"          : utc_time,
                "tags"          : obj_tags,
                "measurement"   : measurement,
                "fields"        : fields,
                }

        return sol_influxdb