Exemplo n.º 1
0
def publish_smap(source_name,sourcedef,dev,devdef,feednum,devuuid,time,data):
    if source_name not in smap_instances:
        if not reactor.running:
            print "Starting twistd reactor"
            th = threading.Thread(target=lambda: reactor.run(installSignalHandlers=0))
            th.daemon = True
            th.start()

        inst = core.SmapInstance(SMAP_UUID,reportfile=SMAP_DATAFILE)
        rpt = {
               'ReportDeliveryLocation' : [sourcedef['url']+'/add/'+sourcedef['apikey']],
               'ReportResource' : '/+',
               'uuid' : inst.uuid('report 0')
        }
        if not inst.reports.update_report(rpt):
            inst.reports.add_report(rpt)
        inst.reports.update_subscriptions()
        inst.start()
        smap_instances[source_name] = inst
    else:
        inst = smap_instances[source_name]     
    
    uuido = uuid.UUID(devuuid)
    ts = inst.get_timeseries(uuido)
    if ts == None:
        print "add ts: "+'/'+dev.IDstr+'/'+str(dev.feed_names);
        ts = inst.add_timeseries('/'+dev.IDstr+'/'+str(dev.feed_names[feednum]),uuido,dev.feed_names[feednum],data_type='double',milliseconds=False)
        smapmeta = {'Instrument/ModelName' : devdef['name'],
                    'Instrument/DeviceDefinition' : dev.device_type,
                    'Instrument/ID' : dev.IDstr,
                    'Instrument/FeedIndex' : str(feednum),
                    'Instrument/FeedName' : str(dev.feed_names[feednum]) }
        locmeta = devicedb.get_devicemetas(where="key='LOCATION' and %d=any(devices)"%dev.ID,limit=1)
        if len(locmeta) > 0:
            smapmeta['Location/CurrentLocation'] = locmeta[0].value

        usermeta = devicedb.get_devicemetas(where="key='USER' and %d=any(devices)"%dev.ID,limit=1)
        if len(usermeta) > 0:
            smapmeta['Extra/User'] = usermeta[0].value
            
        inst.set_metadata(uuido, smapmeta)
    
    #print time,data
    if ( isinstance(time,list) ):
        for i in range(len(time)):
            ts.add(time[i],data[i])
    else:
        ts.add(time,data)
        
    mapstate <input CSV> <reverse mapping file> <output CSV> [--rawdata <raw CSV> --invr <input value ratio>]
        Splits an input CSV timeseries (time,aggregate state no) into an output CSV timeseries (time,state1_no,state2_no...)
        Estimates the disaggregated values using rawdata file
"""
    sys.exit(0);
    
op = sys.argv.pop(0)

if (op == 'list'):
    import learningdb,devicedb
    learningdb.connect()
    print "Hidden Markov Model w/ Gaussian Emission Parameters"
    ids = learningdb.getHMMGaussianEmissionIDs()
    for id in ids:
        met = devicedb.get_devicemetas(where="id=%d"%id, limit=1)
        plname = met[0].value
        entries = learningdb.getHMMGaussianEmissions(id);
        gparm = learningdb.computeGlobalHMMGaussianParameters(entries);
        print "\tPlugload \"%s\" Total Learning Sets: %d"%(plname,len(entries))
        for g in gparm:
            print "\t\tState %-3d: N=%-7d mean=%20.10e variance=%20.10e"%(g.state_id,g.counts,g.mean,g.variance)
        print "\n";
    
    
elif (op == 'insert'):
    import devicedb,postgresops
    devicedb.connect();
    fromtime = None
    totime = None
    dtype = "GHMM"
Exemplo n.º 3
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