-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpushExcelData.py
executable file
·344 lines (280 loc) · 11.3 KB
/
pushExcelData.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
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
#!/usr/bin/python
'''
take json data from learnAirV1 Sensor (mounted on EPA Sensor) in CSV format,
turn into json, and push to Chain.
generalize to EPA data in xls format (push to Site->Device->Sensor)
generalize to API data (find a device object, look at timestamp of data and location,
call api, push api data. Find a site object, do the same thing)
'''
import itertools
import zmq
import json
import xlrd
import csv
from chainTraversal import ChainTraversal
from datetime import datetime
from tzlocal import get_localzone
from dateutil import parser
import pandas as pd
import os
#pull file (XLSX from EPA, CSV from arduino, CSV from SmartCitizen)
#form it into correct dictionary form
#separate scripts that will call changeTimeStamps (and walk through pre-process)
#and then ask to pull the file, form the data, and put it into the correct place
#(one of a couple of predetermined paths to push data to)
def get_file_recurse_dir_prompt(types=['csv','xlsx'], \
default_folder = '/Users/davidramsay/Documents/thesis/arduinoDataSafe'):
'''
asks the user for a search path, recursively finds all files matching
type in search path, asks users which one they want, returns that filename.
If no files of type 'type' exit, exits.
'''
types = [type.lower() for type in types]
#get folder of search path
folder = raw_input('Search Path: [%s] ' % default_folder)
folder = folder or default_folder
#get all .csv files in search path
print '---'
csv_filenames = []
for root, dirnames, filenames in os.walk(folder):
for filename in filenames:
for type in types:
if filename.lower().endswith('.'+ type):
csv_filenames.append(os.path.join(root, filename))
if (len(csv_filenames) == 0):
print 'no files detected'
exit()
for i, fn in enumerate(csv_filenames):
print ('[%d] ' % i + fn)
print '---'
#get file to edit
while 1:
default_file_index = 0
file_index = raw_input('File Choice: [0] ')
try:
file_index = int(file_index)
except:
file_index = default_file_index
try:
file = csv_filenames[file_index]
print '-- SELECTED ' + file
return file
except:
print '- invalid option, try again -'
def pull_file_values(file_path):
if file_path.lower().endswith('.csv'):
return pull_csv_values(file_path)
elif file_path.lower().endswith('.xlsx'):
return pull_xlsx_values(file_path)
else:
raise 'this is not a known filetype'
def pull_csv_values(file_path):
file_dict = {}
#open and read file
df = pd.read_csv(file_path)
keys = df.keys()
#get the key for timestamps, and all other keys
timekey = [key for key in keys if any(s in key.lower() for s in ['utc', 'timestamp'])][0]
keys = [key for key in keys if not any(s in key.lower() for s in ['utc', 'timestamp'])]
#add local system timezone to timestamps, and format properly for chain
timestamps = [parser.parse(time).replace(tzinfo=get_localzone()) \
for time in df[timekey]]
timestamps = [datetime.strftime(time, '%Y-%m-%d %H:%M:%S.%f%z') \
for time in timestamps]
#for each column, make an array of dicts with 'value' and 'timestamps'
#the key for each array is the key for the column stripped of leading and
#trailing whitespace. Values are assumed to be ints or floats.
for key in keys:
new_key = key.strip()
file_dict[new_key] = []
for time, val in itertools.izip(timestamps,df[key]):
try:
file_dict[new_key].append({'value':int(val),'timestamp':time})
except:
try:
file_dict[new_key].append({'value':float(val),'timestamp':time})
except:
print 'could not add value : %s' % val
return file_dict
def pull_xlsx_values(file_path):
#step 1. pull in XLSX data
with open(tempPath) as file:
reader = csv.DictReader(file)
out = json.dumps( [ row for row in reader ], ensure_ascii=False, encoding="utf-8")
print out
def smart_upload(upload_array):
#look at keys, figure out where these values should be stored in chain,
#call upload and actually upload values
def switch(x):
return {
'temperature ( c raw)': {
'device':{
'unique_name':'learnAirFixedV1',
'device_type':'learnAirFixedV1'},
'sensor': {
'sensor_type':'SHT21',
'metric':'temperature_raw',
'unit':'raw'},
},
'humidity ( % raw)':{
'device':{
'unique_name':'learnAirFixedV1',
'device_type':'learnAirFixedV1'},
'sensor': {
'sensor_type':'SHT21',
'metric':'humidity_raw',
'unit':'raw'},
},
'light ( lx)':{
'device':{
'unique_name':'learnAirFixedV1',
'device_type':'learnAirFixedV1'},
'sensor': {
'sensor_type':'BH1730FVC',
'metric':'light',
'unit':'lux'},
},
'battery ( %)':{
'device':{
'unique_name':'learnAirFixedV1',
'device_type':'learnAirFixedV1'},
'sensor': {
'sensor_type':'generic_battery',
'metric':'charge',
'unit':'%'},
},
'carbon monxide ( kohm)': { #misspelled by smartcitizen
'device':{
'unique_name':'learnAirFixedV1',
'device_type':'learnAirFixedV1'},
'sensor': {
'sensor_type':'MICS4514',
'metric':'CO_raw',
'unit':'kOhm'},
},
'nitrogen dioxide ( kohm)': {
'device':{
'unique_name':'learnAirFixedV1',
'device_type':'learnAirFixedV1'},
'sensor': {
'sensor_type':'MICS4514',
'metric':'NO2_raw',
'unit':'kOhm'},
},
'noise ( mv)': {
'device':{
'unique_name':'learnAirFixedV1',
'device_type':'learnAirFixedV1'},
'sensor': {
'sensor_type':'POM-3044P-R',
'metric':'noise_raw',
'unit':'mV'},
},
'alphas1_aux': {
'device':{
'unique_name':'learnAirFixedV1',
'device_type':'learnAirFixedV1'},
'sensor': {
'sensor_type':'AlphasenseO3-A4',
'metric':'O3_raw_aux',
'unit':'raw'},
},
'alphas1_work': {
'device':{
'unique_name':'learnAirFixedV1',
'device_type':'learnAirFixedV1'},
'sensor': {
'sensor_type':'AlphasenseO3-A4',
'metric':'O3_raw_work',
'unit':'raw'},
},
'alphas2_aux': {
'device':{
'unique_name':'learnAirFixedV1',
'device_type':'learnAirFixedV1'},
'sensor': {
'sensor_type':'AlphasenseCO-A4',
'metric':'CO_raw_aux',
'unit':'raw'},
},
'alphas2_work': {
'device':{
'unique_name':'learnAirFixedV1',
'device_type':'learnAirFixedV1'},
'sensor': {
'sensor_type':'AlphasenseCO-A4',
'metric':'CO_raw_work',
'unit':'raw'},
},
'alphas3_aux': {
'device':{
'unique_name':'learnAirFixedV1',
'device_type':'learnAirFixedV1'},
'sensor': {
'sensor_type':'AlphasenseH2S-A4',
'metric':'H2S_raw_aux',
'unit':'raw'},
},
'alphas3_work': {
'device':{
'unique_name':'learnAirFixedV1',
'device_type':'learnAirFixedV1'},
'sensor': {
'sensor_type':'AlphasenseH2S-A4',
'metric':'H2S_raw_work',
'unit':'raw'},
},
'alphatemp': {
'device':{
'unique_name':'learnAirFixedV1',
'device_type':'learnAirFixedV1'},
'sensor': {
'sensor_type':'AlphasenseAFEtemp',
'metric':'temperature_raw',
'unit':'raw'},
},
'sharpdust': {
'device':{
'unique_name':'learnAirFixedV1',
'device_type':'learnAirFixedV1'},
'sensor': {
'sensor_type':'GP2Y1010AU0F',
'metric':'PM25_raw',
'unit':'raw'},
},
'pressurewind': {
'device':{
'unique_name':'learnAirFixedV1',
'device_type':'learnAirFixedV1'},
'sensor': {
'sensor_type':'D6F-PH',
'metric':'pressure_raw_lrnairv1',
'unit':'raw'},
},
}.get(x.lower(), None)
for key in upload_array.keys():
learnair_data_upload(
[{'type':'organization', 'name':'MIT Media Lab'},
{'type':'deployment', 'post_data':{'name':'LearnAirTestDev'}},
{'type':'site', 'post_data':{'name':'RoxburyEPA'}}],
switch(key),
upload_array[key])
def learnair_data_upload(loc_path, loc_info, values):
#open traverser, move to location safely (create path if necessary),
#add data safely (don't overwrite timestamp)
if loc_info is not None:
traverser = ChainTraversal()
traverser.find_and_move_path_create(loc_path)
if loc_info['device'] is not None:
traverser.add_and_move_to_resource('device', loc_info['device'])
if loc_info['sensor'] is not None:
traverser.add_and_move_to_resource('sensor', loc_info['sensor'])
traverser.safe_add_data(values)
if __name__ == '__main__':
excelMainPath ='/Users/davidramsay/Documents/thesis/arduinoDataSafe'
#locate excel sheet folders
print 'make sure to select a file that has been preprocessed so' + \
' timestamps are correct and the data is well-formed'
file_to_upload = get_file_recurse_dir_prompt()
values_to_upload = pull_file_values(file_to_upload)
smart_upload(values_to_upload)