-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsensor_rw.py
286 lines (263 loc) · 7.62 KB
/
sensor_rw.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
#!/usr/bin/python
# Copyright (C) 2021 IST-SUPSI (www.supsi.ch/ist)
#
# Author: Daniele Strigaro
#
# This file is part of station_configurator.
#
# station_configurator is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# station_configurator is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with station_configurator. If not, see <http://www.gnu.org/licenses/>.
import configparser
import os
from datetime import datetime, timezone
import time
import json
import sys
import statistics
# external lib
import requests
import yaml
# supported devices
from drivers.ponsel import Ponsel
from drivers.lufft import WS_UMB
from drivers.unilux import Unilux
from drivers.trilux import Trilux
from drivers.ina219 import read_ina219
___dir___ = os.path.abspath(os.getcwd())
num = len(sys.argv)
if num > 1:
for i in range(1, num):
if sys.argv[i] == "-h" or sys.argv[i] == "?": # debug mode
print('-s = sensor/section name')
quit()
if sys.argv[i] == "-s": # debug mode
section_name = sys.argv[i+1]
if sys.argv[i] == "-c": # debug mode
config_file_path = sys.argv[i+1]
# read config file
config = configparser.ConfigParser()
config.read(config_file_path)
usb_log = config['DEFAULT']['usb_log']
# read variables for sensor/section
section = config[section_name]
# set variables
sensor_type = section['type']
sensor_driver = section['driver']
# initialize and read data from sensor
if sensor_driver == 'ponsel':
try:
sensor = Ponsel(
"{}".format(section['port']),
int(section['addr'])
)
sensor.set_run_measurement(0x001f)
time.sleep(0.25)
values = sensor.get_values()
status = sensor.get_status()
except:
values = [-999.99, -999.99, -999.99 , -999.99]
status = [-100, -100, -100, -100]
print("Can\'t find sensor")
elif sensor_driver == 'unilux':
try:
s = Unilux("{}".format(section['port']))
s.start()
data = s.get_values()
print(data)
filtered_data=[]
for d in data:
if d >=0:
filtered_data.append(d)
#v = round(statistics.mean(data), 2)
values = [
round(statistics.mean(filtered_data), 2)
]
status = [100]
if data:
s.stop()
except:
values = [-999.99]
status = [-100]
if data:
s.stop()
print("Can\'t find sensor")
elif sensor_driver == 'trilux':
try:
s = Trilux("{}".format(section['port']))
s.start()
data = s.get_values()
print(data)
filtered_data=[]
p1 = []
p2 = []
p3 = []
for i in range(len(data)):
if data[i][0]>=0:
p1.append(data[i][0])
if data[i][1]>=0:
p2.append(data[i][1])
if data[i][2]>=0:
p3.append(data[i][2])
values = [-999.99, -999.99, -999.99]
status = [-100, -100, -100]
if len(p1) > 0:
values[0] = round(statistics.mean(p1), 2)
status[0] = 100
if len(p2) > 0:
values[1] = round(statistics.mean(p2), 2)
status[1] = 100
if len(p3) > 0:
values[2] = round(statistics.mean(p3), 2)
status[2] = 100
if data:
s.stop()
except:
values = [-999.99, -999.99, -999.99]
status = [-100, -100, -100]
if data:
s.stop()
print("Can\'t find sensor")
elif sensor_driver == 'lufft':
values = []
status = []
value_UMB = [
200, 305, 500,
900, 100, 400, 440
]
try:
with WS_UMB("{}".format(section['port'])) as umb:
for v in value_UMB:
value, st = umb.onlineDataQuery(v, int(section['addr']))
values.append(
round(value, 2)
)
status.append(st)
except:
values = [-999.99, -999.99, -999.99 , -999.99, -999.99, -999.99, -999.99]
status = [-100, -100, -100, -100, -100, -100, -100]
if not values:
raise Exception('Sensor driver is not supported yet.')
elif sensor_driver == 'ina219':
values = []
status = []
try:
values = read_ina219()
status = [100, 100]
except:
values = [-999.99, -999.99]
status = [-100, -100]
print("Can\'t find sensor")
if not values:
raise Exception('Sensor driver is not supported yet.')
else:
raise Exception('Sensor driver is not supported yet.')
data = None
outputs = []
separator = os.sep
with open(
os.path.join(
separator.join(config_file_path.split('/')[0:-1]),
'support',
section['driver'],
f'{sensor_type}.yaml'
)
) as f:
rs = yaml.safe_load(f)
outputs = rs['outputs'][1:]
go_values = []
for i in range(len(outputs)):
go_values.append(round(values[i], 2))
if data:
data = data + ',' + str(round(values[i], 2))
else:
data = str(round(values[i], 2))
bp = datetime.now(timezone.utc).replace(second=0, microsecond=0).isoformat()
data_post = '{};{},{}'.format(
section['assigned_id'],
bp,
data
)
print(data_post)
#### Using InsertObservation #####
go = requests.get(
(
"{}/wa/istsos/services/{}/operations/getobservation"
"/offerings/temporary/procedures/{}/observedproperties/:/eventtime/last"
).format(
config['DEFAULT']['istsos'],
config['DEFAULT']['service'],
section_name
),
auth=(
config['DEFAULT']['user'],
config['DEFAULT']['password']
)
)
go = go.json()
go = go['data'][0]
go["samplingTime"] = {
"beginPosition": bp,
"endPosition": bp
}
go['result']['DataArray']['values'] = [
[bp] + go_values
]
go['result']['DataArray']['elementCount'] = str(len(outputs)+1)
go['result']['DataArray']['field'] = list(
filter(
lambda x: 'qualityIndex' not in x['definition'], go['result']['DataArray']['field']
)
)
res = requests.post(
"%s/wa/istsos/services/%s/operations/"
"insertobservation" % (
config['DEFAULT']['istsos'],
config['DEFAULT']['service'],
),
auth=(
config['DEFAULT']['user'], config['DEFAULT']['password']
),
data=json.dumps({
"ForceInsert": "true",
"AssignedSensorId": section['assigned_id'],
"Observation": go
})
)
res.raise_for_status()
print(" > Insert observation success: %s" % (
res.json()['success']))
# req = requests.post(
# '{}/wa/istsos/services/{}/operations/fastinsert'.format(
# config['DEFAULT']['istsos'],
# config['DEFAULT']['service'],
# ),
# data=data_post,
# auth=(config['DEFAULT']['user'], config['DEFAULT']['password'])
# )
# if req.status_code == 200:
# print(req.text)
# else:
# print(False)
try:
if usb_log:
mode = 'w'
file_name = 'LOG.txt'
for item in os.listdir('/media/usb0'):
if item == file_name:
mode = 'a'
# try some standard file operations
with open('/media/usb0/LOG.txt', mode) as f:
f.write(section_name + "," + data_post + "\n")
f.close()
except Exception as e:
print(str(e))