Exemplo n.º 1
0
def find_plugload(sourcename,sourceid):
    device_rows = get_devices(where="source_name='%s' and '%s'=any(source_ids)"%(sourcename,sourceid),limit=1)
    if ( len(device_rows) == 0 ):
        return None,None,None
    
    dev = device_rows[0]
    chan_index = dev.source_ids.index(sourceid)
    
    devdef = utils.read_device(dev.device_type)
    if 'plugload_groups' in devdef:
        plgroups = [int(s) for s in devdef['plugload_groups'].split(',')]
        
        tchan = chan_index;
        pl_index = 0;
        while ( pl_index < len(plgroups) and tchan >= plgroups[pl_index] ):
            tchan -= plgroups[pl_index];
            pl_index += 1;
    else:
        pl_index = 0;
        
    plugload_row = get_devicemetas(where="key='PLUGLOAD%d'and %d=any(devices)"%(pl_index,dev.ID), limit=1)
    if( len(plugload_row)==0):
        return None,dev,pl_index
        
    return plugload_row[0],dev,pl_index
Exemplo n.º 2
0
def publish_data( keyvals, msg_dbg=''):    
    if keyvals != None  and 'driver' in keyvals and 'device_id' in keyvals:
        driver = keyvals['driver']
        device_id = keyvals['device_id']
        devdef = utils.read_device(driver)
        if devdef == None:
            print "Device definition for %s not found"%driver
            return

        ## Custom device drivers here
        if driver == 'custom!@#!@$!$#':
            pass
        else: # generic driver: try to match keys to feeds
            if 'timestamp' in keyvals:
                dev = publisher.find_device( device_id, create_new=True, device_type=driver, devdef=devdef )
                
                ts = utils.date_to_unix(utils.str_to_date(keyvals['timestamp']))
                datapoints = []
                feednums = []
                
                for key,val in keyvals.iteritems():
                    if key in ['driver','device_id','timestamp']:
                        continue
                        
                    try:
                        f = float(val);
                    except:
                        print "Skipping Key-Value pair",key,"/",val,"as it is non-numeric"
                        continue;
                        
                    if key in dev.feed_names:
                        idx = dev.feed_names.index(key)
                        feednums.append(idx)
                        datapoints.append(f)
                    else:
                        feednums.append(len(dev.feed_names))
                        datapoints.append(f)
                        dev.feed_names.append(key)
                try:
                    if (len(datapoints) > 0):
                        publisher.publish_data( device_id, ts, datapoints, feednum=feednums, devdef=devdef, device_type=driver, dev=dev)
                except:
                    import traceback
                    traceback.print_exc();
            else:
                print "Data Line '%s' did not have a timestamp field (for generic driver)"%msg_dbg
        
        
    else:
        print "Data Line '%s' did not contain a key for driver and/or device_id"%msg_dbg
Exemplo n.º 3
0
def populate_BT_cache():
    global dev_BT_cache
    dev_BT_cache = {}
    print "Scanning for MT values"
    devs = utils.list_devicedefs()
    for devf in devs:
        dev = utils.read_device(devf)
        
        if ( 'SPF_BT' in dev ):
            btstr = dev['SPF_BT']
            if not 'SPF_field_bitmask' in dev:
                print "Warning: SPF_field_bitmask not present for devdef "+devf
                continue;
            if not 'SPF_field_types' in dev:
                print "Warning: SPF_field_bitmask not present for devdef "+devf
                continue;
            
            dev['_SPFbm'] = [int(a) for a in dev['SPF_field_bitmask'].split(',')];
            dev['_SPFft'] = dev['SPF_field_types'].split(',');
            
            if ( len(dev['_SPFbm']) != len(dev['feeds']) ):
                print "Warning: SPF_field_bitmask not the same length as the number of feeds"
                continue;
            
            if ( len(dev['_SPFft']) != len(dev['feeds']) ):
                print "Warning: SPF_field_types not the same length as the number of feeds"
                continue;
            
            if len(btstr) > 2 and btstr[0:2] == '0x':
                bt = int(btstr[2:],16)
            else:
                bt = int(btstr);
            
            dev['_type'] = devf
            dev_BT_cache[bt] = dev
            print "\t0x%02X : "%bt+dev['name']
Exemplo n.º 4
0
def timesync_packet():
    #0000004F056B5200
    return '\x00\x00'+struct.pack('<I',time.time())
    
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))

    if SPF_result != None:
        if SPF_result[1] == MT_SENSOR_DATA:
            (devname,packet_type,time,feedidxfound,feedvalsfound) = SPF_result
            devdef = utils.read_device(devname);
            dev = publisher.find_device(source, create_new=True, device_type=devname, devdef=devdef )
            dev.feed_names = devdef['feeds']
            publisher.publish_data(source, time, feedvalsfound, feednum=feedidxfound, device_type=devname, dev=dev)
        elif SPF_result[1] == MT_RFID_TAG_DETECTED:
            (devname,packet_type,time,uidstr) = SPF_result
            devdef = utils.read_device(devname);
            dev = publisher.find_device(uidstr, create_new=True, device_type=devname, devdef=devdef )
            sourcestr = "RFID Reader %s"%source
            if ( sourcestr in dev.feed_names ):
                idx = dev.feed_names.index(sourcestr)
                feedidxfound = idx
            else:
                dev.feed_names.append(sourcestr)
                feedidxfound = len(dev.feed_names)-1
                
Exemplo n.º 5
0
def lookupstuff():
    global lookedstuffup, CODE_LINES
    if lookedstuffup:
        return 
        
    import config
    import utils
    import devicedb
    import postgresops
    devicedb.connect()
    
    for code,dat in CODES.iteritems():
        if dat[0] == "P":
            dev = devicedb.get_devices(where="idstr='%s'"%dat[1],limit=1);
            if len(dev) != 1:
                CODE_LINES[code] = lambda:"ERROR: Can't find device";
                return;
            dev = dev[0]
            # get plug load names
            metas = devicedb.get_devicemetas(where="key like 'PLUGLOAD%d' and %d=any(devices)"%(dat[2],dev.ID),limit=1);
            if len(metas) != 1 or metas[0].parent == 0:
                loadstr = "UNKNOWN";
            else:
                meta = metas[0]
                if meta.parent == 1:
                    loads = [int(s) for s in meta.value.split(',')]
                else:
                    loads = [meta.parent]
                
                loadstr = ""
                for lid in loads:
                    loadnamemeta = devicedb.get_devicemetas(where="id=%d"%lid,limit=1)[0]
                    loadstr += loadnamemeta.value;
                    if lid != loads[-1]:
                        loadstr += " + "
                        
            # get uuid of power and current
            devdef = utils.read_device(dev.device_type)
            poweruuid = None
            currentuuid = None
            for feednameidx in range(len(dev.feed_names)):
                feedname = dev.feed_names[feednameidx]
                if 'power %d'%(dat[2]+1) in feedname.lower():
                    poweruuid = dev.source_ids[feednameidx]
                elif 'current %d'%(dat[2]+1) in feedname.lower():
                    currentuuid = dev.source_ids[feednameidx]
        
            CODE_LINES[code] = lambda loadstr=loadstr,poweruuid=poweruuid,currentuuid=currentuuid,dat=dat:  ("http://sensezilla.berkeley.edu:7500/showliveplot?title=%s&source=sensezilla&sourceid=%s"%(urllib.quote("Wattage of Device(s): %s (Instrument:%s Port:%d)"%(loadstr,dat[1],dat[2]+1)),poweruuid)+";Device(s): "+loadstr + "\n" +
                                        "Wattage: %.2f W"%(get_smap_data(poweruuid)) + "\n" + 
                                        "Amperage: %.2f A"%(get_smap_data(currentuuid)));
                
        elif dat[0] == "R":
            devs = {}
            for t,v in dat[1].iteritems():
                dev = devicedb.get_devices(where="idstr='%s'"%v,limit=1);
                if len(dev) != 1:
                    CODE_LINES[code] = lambda:"ERROR: Can't find device %s"%v;
                    return;
                devs[t] = dev[0]
            
            occuuid   = devs['occupancy'].source_ids[2];
            humiduuid = devs['humidity'].source_ids[0];
            tempuuid  = devs['temperature'].source_ids[1];
            lightuuid = devs['light'].source_ids[3];
            
            CODE_LINES[code] = lambda occuuid=occuuid,humiduuid=humiduuid,tempuuid=tempuuid,lightuuid=lightuuid:  ("http://sensezilla.berkeley.edu:7500/showliveplot?title=%s&source=sensezilla&sourceid=%s"%(urllib.quote("Occupancy of room"),occuuid)+";"+
                                        "Occupancy: %.1f %%"%(get_smap_data(occuuid)) + "\n" +
                                        "Humidity: %.1f %%RH"%(get_smap_data(humiduuid)) + "\n" + 
                                        "Temperature: %.1f C"%(get_smap_data(tempuuid))  + "\n" +
                                        "Light Level: %.1f ulux"%(1.0e6*get_smap_data(lightuuid)));
                
        else:
            CODE_LINES[code] = lambda:"NOT IMPLEMENTED"
    
    lookedstuffup = True
Exemplo n.º 6
0
def publish_data(id_str, time, data, feednum=None, devdef=None, device_type=None, source=None, dev=None):    
    # Usage 1: time and data are scalars - one data point, feed # = feednum or 0 if feednum=None
    # Usage 2: time and data are lists of scalars (time could also be scalar) - one data point per feed, feed #s = feednum (list) or range(total feeds) if feednum=None
    # Usage 3: time and data are lists of scalars, feednum is a scalar - multiple data points for one feed
    # Usage 4: time and data are lists of lists of scalars (time could also be list of scalar) - multiple data points per feed, feed #s = feednum(list) or range(total feeds) if feednum=None
    if not isinstance(data, list): # Usage 1
        data = [data]
        if feednum == None:
            feednum = [0]
        else:
            feednum = [feednum]
    else:  # Usage 2,3,4
        if feednum == None: # Usage 2,4
            feednum = range(len(data))
        elif not isinstance(feednum,list): # usage 3
            feednum = [feednum]
            time = [time]
            data = [data]
    
    if not isinstance(time,list) or (not isinstance(time[0],list) and isinstance(data[0],list)): # Usage 1,2,4
        time = [time]*len(feednum)
        
    if not devicedb.connected():
        devicedb.connect()
    
    id_str = id_str.replace('/','_');
    postgresops.check_evil(id_str);
    
    dev = find_device(id_str, create_new = True, device_type=device_type, source=source, devdef=devdef, dev=dev)
    
    if dev == None:
        return;
    
    source_struct = utils.read_source(dev.source_name)
    if devdef == None:
        devdef = utils.read_device(dev.device_type)
        
    driver = source_struct['driver']
    for i in range(len(feednum)):
        if feednum[i] >= len(dev.feed_names):
            print "ERROR cannot publish data for feed %d because it is not defined in the definition for %s"%(feednum[i],dev.device_type)
        elif feednum[i] >= len(dev.source_ids) or dev.source_ids[feednum[i]] == None or dev.source_ids[feednum[i]] == '':
            print "ERROR cannot publish data for feed %d of device %s because it is not defined"%(feednum[i],dev.IDstr)
        else:
            source_id = dev.source_ids[feednum[i]]
            if driver == 'SMAP':
                publish_smap(dev.source_name,source_struct,dev,devdef,feednum[i],source_id,time[i],data[i])
            elif driver == 'CSV':
                fname = source_id
                if fname[0] != '/':
                    fname = source_struct['path'] + '/' + fname
                try:
                    parentdir = fname[:fname.rfind('/')]
                    
                    try:
                        os.makedirs(parentdir)
                    except: pass
                    
                    csvfile = open(fname, "ab")
                    #print "\t",time[i],data[i]
                    if isinstance(time[i],list):
                        for j in range(len(time[i])):
                            csvfile.write("%.12f,%.12f\n"%(time[i][j],data[i][j]))
                    else:
                        csvfile.write("%.12f,%.12f\n"%(time[i],data[i]))
                    csvfile.close()
                except OSError,e:
                    print "ERROR Cannot publish data to %s because "%(fname),e
                    
            else:
                print "ERROR Cannot publish data for %s b/c no %s driver"%(dev.source_name,driver)
                return []