/
bd_wrapper.py
119 lines (103 loc) · 3.82 KB
/
bd_wrapper.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
from building_depot import DataService, BDError
import authdata
from datetime import datetime, timedelta
from pytz import timezone
import pandas as pd
import numpy as np
from collections import OrderedDict
import operator
#import urllib3
#urllib3.disable_warnings()
# NOTE
# ts=timeseries
#Example of time init
# self.pst.localize(offTime, is_dst=True)
class BDWrapper:
bdDS = None
pst = timezone('US/Pacific')
utc = timezone('UTC')
bdStrFormat = '%Y-%m-%dT%H:%M:%S+00:00'
def __init__(self):
self.bdDS = DataService(authdata.srcUrlBase, authdata.bdApiKey, authdata.bdUserName)
def get_sensor_uuids(self, context):
# context (a series of dictionary) -> uuid (list)
#context is
try:
resp = self.bdDS.list_sensors(context)
uuids = list()
for sensor in resp['sensors']:
uuids.append(sensor['uuid'])
return uuids
except BDError as e:
print e
return []
def get_sensor_names(self, context):
try:
resp = self.bdDS.list_sensors(context)
uuids = list()
for sensor in resp['sensors']:
uuids.append(sensor['source_name'])
return uuids
except BDError as e:
print e
return []
def get_sensor_ts(self, uuid, sensorType, beginTime, endTime):
# uuid(string), sensorType(string), beginTime(datetime), endTime(datetime) -> timeseries (pd.Series)
# Note: beginTime and endtime should not be normalized already. should be a raw format.
isoBegin = self.pst.localize(beginTime)
isoEnd = self.pst.localize(endTime)
try:
rawData = self.bdDS.get_timeseries_datapoints(uuid, sensorType, isoBegin, isoEnd) #return json
pdseries = self.rawts2pdseries(rawData['timeseries'])
#pdts = self.rawts2pdts(rawData['timeseries'])
return pdseries
except BDError as e:
print e
return None
# TODO: Can I do this better? hard to convert list of dict into dataframe
def rawts2pdts(self, rawData):
rawData = OrderedDict([(key,d[key]) for d in rawData for key in d])
sortedData = rawData
#rawData = dict([(key,d[key]) for d in rawData for key in d])
#sortedData = OrderedDict(sorted(rawData.items(), key=operator.itemgetter(0)))
pdts = pd.DataFrame({'timestamp':sortedData.keys(), 'value':sortedData.values()})
g = lambda tp:datetime.strptime(tp, self.bdStrFormat).replace(tzinfo=self.utc).astimezone(self.pst).replace(tzinfo=None)
pdts['timestamp'] = pdts['timestamp'].apply(g)
return pdts
def rawts2pdseries(self,rawData):
rawData = OrderedDict([(key,d[key]) for d in rawData for key in d])
for key in rawData.keys():
newKey = datetime.strptime(key, self.bdStrFormat).replace(tzinfo=self.utc).astimezone(self.pst).replace(tzinfo=None)
rawData[newKey] = rawData.pop(key)
pdseries = pd.Series(data=rawData.values(),index=rawData.keys())
return pdseries
# TODO: Do not make multiple writing (maybe remove this?)
def get_zone_sensor_ts(self, zone, template, sensorType, beginTime, endTime):
# zone(string), template(string), sensorType(string), beginTime(datetime), endTime(datetime) -> ts(pd.Series)
# Note: This is a wrapper for easy use of get sensor time series
context = {'room':zone, 'template':template}
try:
uuids = self.get_sensor_uuids(context)
if len(uuids)>1:
print "ERROR: More than one sensor are found: " + string(len(uuids)) + ' sensors are found'
return None
elif len(uuids)==0:
print "ERROR: No sensor is found"
return None
ts = self.get_sensor_ts(uuids[0], sensorType, beginTime, endTime)
return ts
except BDError as e:
print e
#TODO or just return None?
return pd.Series()
def set_sensor(self, uuid, sensorType, tp, val):
# uuid(string), sensorType(string), ts(list of dict) -> success(boolean)
# An example of ts: [{datetime(2014,1,1,0,0,0):72}]
newts = list()
newts.append({self.pst.localize(tp).isoformat():val})
try:
self.bdDS.put_timeseries_datapoints(uuid, sensorType, newts)
return True
except BDError as e:
print e
return False