示例#1
0
 def run(self):
     power_hex = hexify(self.power, 2)
     ad_hex = hexify(self.advertisement)
     self.__print(ad_hex, power_hex)
     length = hexify(len(hex_split(ad_hex).split(" ")) + 1)
     content = f"{length} 09 {hex_split(ad_hex)} 02 0A F4 0A 16 0D D0 61 62 63 64 04 02 06 00 00"
     self._run_command(content)
def verify_at(atcmd, value):
    val = read_at(atcmd)
    if val != None and val != value and utils.strip0s(value) != utils.strip0s(val):
        print "%s Command expected %s got %s"%(atcmd,utils.hexify(value),utils.hexify(val))
        xbee.send('at',command=atcmd,parameter=value)
        return False
    return True
示例#3
0
    def run(self):
        power_hex = hexify(self.power, 2)
        major_hex = hexify(self.major, 4)
        minor_hex = hexify(self.minor, 4)
        self.__print(major_hex, minor_hex, power_hex)

        content = f"{self.__uuid()} {hex_split(major_hex)} {hex_split(minor_hex)} {power_hex} 00"
        manufacturer = "4C 00 02 15"
        ibeacon = f"02 01 06 1A FF {manufacturer}"
        self._run_command(f"{ibeacon} {content}")
示例#4
0
    def run(self):
        power_hex = hexify(self.power, 2)
        namespace_hex = hexify(self.namespace, 20)
        instance_hex = hexify(self.instance, 12)
        self.__print(namespace_hex, instance_hex, power_hex)

        frame_type = "00"
        eddystone = f"02 01 06 03 03 AA FE 15 16 AA FE {frame_type}"
        content = f"{hex_split(namespace_hex)} {hex_split(instance_hex)}"
        rfu = "00 00"
        self._run_command(f"{eddystone} {power_hex} {content} {rfu}")
def process_cmd(cmd):
    global sock_connected,s
    if ( len(cmd) < 3 ):
        print "Command is too short"
        return
        
    tag_reading_recieved = False
    tag_reading_map = {} # primary key = tag addr, secondary key = sensor addr, value = rssi value
    
    #print "Recieved: "+utils.hexify(cmd)
    reader_addr_str = cmd[0:2]
    unknown_str = cmd[2]
    pos = 3
    while pos < len(cmd):
        length = ord(cmd[pos])
        subcmd = cmd[pos+1]
        if subcmd == '\x02':
            sensor_addr_str = cmd[pos+2:pos+4]
           # print "Reading from sensor "+utils.hexify(sensor_addr_str),
            pos2 = pos+4;
            while pos2 < pos+1+length:
                if len(cmd) < 4+pos2:
                    print "Warning: Unexpected end of data (len given was %d, but actual length was %d)"%(length,len(cmd)-pos-1)
                    break
                tag_addr_str = cmd[pos2:pos2+2]
                tag_rssi_str = cmd[pos2+2:pos2+4]
                (tag_rssi,) = struct.unpack(">h",tag_rssi_str)
                tag_reading_recieved = True
                if tag_addr_str not in tag_reading_map:
                    tag_reading_map[tag_addr_str] = {}
                
                tag_reading_map[tag_addr_str][sensor_addr_str] = tag_rssi
                
                #print " tag "+utils.hexify(tag_addr_str)+":%3ddbM"%tag_rssi,
                pos2 = pos2+4
                
            #print ""
            
        pos += length + 1
                

    if tag_reading_recieved:
        tlvstr = ''
        for key,val in tag_reading_map.iteritems():
            tlvstr += 'timestamp/%d'%int(time.time()+0.5)+'/driver/rfidloc_sinbb/device_id/%s/'%utils.hexify(key)
            for subkey,rssival in val.iteritems():
                tlvstr += 'Sensor %s RSSI(dBm)/%d/'%(utils.hexify(subkey),rssival)
            tlvstr += '\n'

#        print tlvstr,
        if sock_connected:
            try:
                s.sendall(tlvstr);
            except:
                traceback.print_exc();
                try:
                    s.close()
                except:pass
                sock_connected = False
示例#6
0
 def format_decompressed(self, index = 0):
     data = self.datas[index]
     pattern = "  ".join([" ".join(["%s"] * 4)] * 4)
     s = ""
     h = lambda n: hexify(n, pad=2)
     while data:
         current, data = data[:16], data[16:]
         current += [0] * (16 - len(current))
         s = "\n".join([s, pattern % tuple(h(current))])
     return s.strip()
示例#7
0
    def write(self, outfile, data):
        outfile.seek(self.baseaddr + BLOCK_HEADER_SIZE)
        blocks = 0
        while data:
            blocks += 1
            chunk, data = data[:BLOCK_SIZE], data[BLOCK_SIZE:]
            length = len(chunk)
            chunk += [0] * (BLOCK_SIZE - len(chunk))
            assert len(chunk) == BLOCK_SIZE
            chunk = map(lambda x: x & 0xff, chunk)
            outfile.write("".join(map(chr, chunk)))
            outfile.seek(outfile.tell() + BLOCK_HEADER_SIZE)

        if blocks > self.blocks:
            print "FATAL ERROR at %s; Data too big." % hexify(self.baseaddr)
            print "Using %s and %s/2048, available: %s" % (blocks - 1, length, self.blocks)
            assert False
def read_packet(data):
    global last_scan
    BT = ord(data[0])
    MT = ord(data[1])
    data = data[2:]
    
    if not BT in dev_BT_cache:
        if time.time() - last_scan > 10:
            populate_BT_cache()
            if not BT in dev_BT_cache:
                return None;
            last_scan = time.time()
        else:
            return None
            
    feedidxfound = []
    feedvalsfound = []
    dev = dev_BT_cache[BT]
    devf = dev['_type']
    if MT == MT_SENSOR_DATA:
        (ptime,fields) = struct.unpack('<IH',data[0:6])
        data = data[6:]
        feedidx = 0;
       # print "Fields:%04X data:%s"%(fields,utils.hexify(data))
        # check each bit in <fields> and unpack from <data>
        for b in range(16): 
            if ( fields & (1<<b) != 0):
                while feedidx < len(dev['_SPFbm']):
                    #print "b=%d feedidx=%d"%(b,feedidx)
                    if dev['_SPFbm'][feedidx] > b:
                        print "Error: bitmask algorithm failed (is SPF_field_bitmask specified correctly? and in order?)"
                        print "\tb=%d (0x%02X), feedidx=%d [%s] SPFbm=%d"%(b,(1<<b),feedidx,dev['feeds'][feedidx],dev['_SPFbm'][feedidx])
                        break;
                    elif dev['_SPFbm'][feedidx] == b:
                        while feedidx < len(dev['_SPFbm']) and dev['_SPFbm'][feedidx] == b:
                            feedidxfound += [feedidx]
                            type = dev['_SPFft'][feedidx]
                            tsize = struct.calcsize(type);
                            (val,) = struct.unpack('<'+type,data[0:tsize])
                            data = data[tsize:]
                            feedvalsfound += [float(val)]
                           # print "\t[%s] : %.2f"%(dev['feeds'][feedidx],float(val))
                            feedidx += 1
                            
                        break
                        
                    feedidx += 1
        
        # debugging
        #print "Data found: t=%10d fields=%04X"%(ptime,fields)
        #for fi in feedidxfound:
        #    print "\tFeed %d : %s => %8.2e"%(fi,dev['feeds'][feedidxfound[fi]],feedvalsfound[fi])
            
        return (devf,MT_SENSOR_DATA,ptime,feedidxfound,feedvalsfound)
    elif MT == MT_RFID_TAG_DETECTED:
        (ptime,) = struct.unpack('<I',data[0:4])
        uidstr = utils.hexify(data[4:])
        
        return ('mifare_rfid',MT_RFID_TAG_DETECTED,ptime,uidstr)
    elif MT == MT_RECORDSTORE_DATA:
        records = []
        record_types = {}
        i = 0;
        while i < len(data):
            chb = ord(data[i])
            if chb & 0x80 != 0:
                plen = chb & 0x7F;
                record_types[plen] = data[i+1:i+1+plen]
                records.append(record_types[plen])
                i = i+1+plen
                #print "New %d byte record: %s"%(plen,utils.hexify(record_types[plen]))
            else:
                plen = chb;
                if plen not in record_types:
                    print "Error decompressing recordstore, no record type for len=%d"%plen
                    
                record = ''
                nDiff = int((plen+7)/8);
                db = i + 1 + nDiff;
                for i2 in range(plen):
                    if ord(data[i + 1 + int(i2)/8]) & (1<<(i2%8)) != 0:
                        record += data[db]
                        db += 1;
                    else:
                        if plen in record_types:
                            record += record_types[plen][i2]
                        else:
                            record += chr(0xFF)
                        
                if plen in record_types:
                    #print "Record: "+utils.hexify(record)
                    records.append(record)

                    
                i = db    
                    
    
        return (devf,MT_RECORDSTORE_DATA,records)
    elif MT == MT_DEVICE_IDENTIFIER:
        idtype = ord(data[0])
        if idtype >= 0x00 and idtype <= 0x3F:
            if idtype == ID_TYPE_BIN_MAC_80211:
                idstr = ':'.join(['%02x'%ord(c) for c in data[1:]])
            else:
                idstr = utils.hexify(data[1:])
        elif idtype >= 0x40 and idtype <= 0x7F:
            idstr = data[1:]        
        
        return (devf,MT_DEVICE_IDENTIFIER,idtype,idstr)
def publish(source, data):
    import publisher
    #print "Publish from %s data %s"%(source,utils.hexify(data))
    try:
        SPF_result = read_packet(data)
    except struct.error, emsg:
            print "Error parsing SPF packet from %s device (%s): %s"%(source,str(emsg),utils.hexify(data))
     xbee_relay_IF.reconnect();
     if xbee_relay_IF.connected():
         xbee_relay_IF.register_as_relay();
     
 # process connection w/ XBee
 while len(xbee_frames) > 0:
     frame = xbee_frames.pop();
     #print "FRAME "+frame['id']
     if frame['id'] == 'at_response':
         pass
     elif frame['id'] == 'status':
         print "Modem Status is now %02X"%ord(frame['status'][0])
     elif frame['id'] == 'tx_status':
         pass
     elif frame['id'] == 'rx_long_addr' or frame['id'] == 'rx_io_data_long_addr':
         source_addr = utils.hexify(frame['source_addr'])
         if frame['id'] == 'rx_long_addr':
             data = frame['rf_data']
         else:
             tdata = frame['samples']
             data = "DIGI/"
             for delem in tdata:
                 print delem
                 for key,val in delem.iteritems():
                     data += str(key)+"/"+str(val)+"/"
             print "Digi data: "+data
             ts_noupdate.add(source_addr)
         
         #print "<"+source_addr+" : "+utils.hexify(data)
         children_cache.add(source_addr)
         
        b = ser.read(size=1)
        if len(b) == 0:
            break;
        
        last_serial_msg = time.time()
        b = b[0]
#        print utils.hexify(b),
        if b == '\x7E':
            cmdbuf = ''
            recieving_cmd = True
        elif recieving_cmd and b == '\x7B':
            print ''
            try:
                process_cmd(cmdbuf)
            except:
                print "Error processing "+utils.hexify(cmdbuf)
                import traceback
                traceback.print_exc()
            recieving_cmd = False
        elif len(cmdbuf) >= MAX_CMD_SIZE:
            print "Buffer overflow!"
            cmdbuf = ''
            reciving_cmd = False
        elif recieving_cmd:
            cmdbuf += b
    
    if not sock_connected:
        try:
            s = socket.socket(socket.AF_INET, socket.SOCK_STREAM);
            s.connect((HOST_NAME,HOST_PORT))
            sock_connected = True