-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
248 lines (195 loc) · 6.71 KB
/
main.py
File metadata and controls
248 lines (195 loc) · 6.71 KB
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
from PiicoDev_Unified import sleep_ms # cross-platform compatible sleep function
from PiicoDev_BME280 import PiicoDev_BME280
from PiicoDev_ENS160 import PiicoDev_ENS160
from nbiot import NBIoT
from config import Config
# from ota_update import OTAUpdate
import asyncio
import machine
import sys
import utils
import time
import io
# import json
def wait_for_startup_interrupt():
count = 5
print(f"Wait for user interrupt ({count}) secs")
while count:
sleep_ms(1000)
count -= 1
async def wdt_task():
print('WDT task started')
interval = 1000
wdt = machine.WDT(timeout = 8388) # Start the watchdog 8.388 seconds
while True:
wdt.feed()
await asyncio.sleep_ms(interval)
#############################
# main
#############################
# Slow down the clock to save power
machine.freq(48_000_000)
debug = False
if utils.console_connected():
debug = True
net = NBIoT()
uid = utils.uid() # The id sent to the mqtt server
env = PiicoDev_BME280() # initialise the env sensor
air = PiicoDev_ENS160() # initialise the aqi sensor
config = Config()
rc_map = {
machine.PWRON_RESET: "PowerOn",
machine.WDT_RESET: "WatchDog"
}
mqtt_base_topic = "sensors/circulait"
mqtt_server = "mqtt.at.martin.cc"
rails_server = "accelerate-advantage-b6d76071507e.herokuapp.com"
rc = machine.reset_cause()
rc_reason = rc_map[rc] or "Unknown"
print(f"Debug: {debug}")
print(f"Reset Code: {rc}")
print(f"Reset Reason: {rc_reason}")
print(f"uid: {uid}")
try:
# Depending on the reset reason, there is an opportunity
# to do stuff that we need only for that particular startup case
if rc == machine.PWRON_RESET:
if debug:
wait_for_startup_interrupt()
net.factory_reset()
net.disable()
time.sleep(3)
# if ota_update.update_available():
# print('OTA Update available')
# ota_update.pull_all()
# print('OTA Update Completed')
# else:
# print('No OTA update')
elif rc == machine.WDT_RESET:
if debug:
wait_for_startup_interrupt()
# send wdt packet to server
# attempt a firmware update
else:
pass
# do stuff that we only do once-off at startup
if net.enable():
# get the configuration from the server and update the config object
# net.dns_lookup(rails_server) # this will force a wait for the dns
# content = net.get_http(f"https://{rails_server}/", f"/api/sensors/{uid}")
# if debug:
# print(f"content: {content}")
# if content:
# config.update(json.loads(content))
# config.save()
# get the date and time
net.set_time()
# send a start message
ip = net.dns_lookup(mqtt_server)
if ip:
t = time.gmtime()
topic = f"{mqtt_base_topic}/start"
msg = {
"u": uid,
"v": config.get_version(),
"b": utils.get_vsys(),
"r": rc_reason,
"utc": "{}-{:02d}-{:02d}T{:02d}:{:02d}:{:02d}".format(t[0], t[1], t[2], t[3], t[4], t[5]),
}
net.send_mqtt(ip, topic, msg)
net.disable()
print("Polling task started")
total_count = 0
env_count = 0
env_data = []
while True:
# default temp and humidity is case the env sensor is not present, required for the aqi sensor
temp = 25
humidity = 101300
if env._device_present:
print("taking an THP sample")
temp, pressure, humidity = env.values() # read all data from the sensor
t = time.gmtime()
data = {
"t": temp,
"p": pressure,
"h": humidity,
"utc": "{}-{:02d}-{:02d}T{:02d}:{:02d}:{:02d}".format(t[0], t[1], t[2], t[3], t[4], t[5]),
"i": env_count
}
env_data.append(data)
print(f"env: {data}")
env_count += 1
total_count += 1
if env_count >= config.getVal('sample_count'):
env_count = 0
tvoc = {}
if air._device_present:
print("Wait for sensor to be ready...")
air.wakeup()
time.sleep(config.getVal('tvoc_wait') * 60)
print("taking a tvoc sample")
air.temperature = temp
air.humidity = humidity
tvoc = air.tvoc
eco2 = air.eco2
aqi = air.aqi
t = time.gmtime() # we had to wait for the heater to heat up
print("deepsleep air")
air.deepsleep()
tvoc = {
"a": aqi.value,
"t": tvoc,
"e": eco2.value,
"utc": "{}-{:02d}-{:02d}T{:02d}:{:02d}:{:02d}".format(t[0], t[1], t[2], t[3], t[4], t[5])
}
print("Build message")
t = time.gmtime()
msg = {
"u": uid,
"i": total_count,
"b": utils.get_vsys(),
"e": env_data,
"t": tvoc,
"utc": "{}-{:02d}-{:02d}T{:02d}:{:02d}:{:02d}".format(t[0], t[1], t[2], t[3], t[4], t[5])
}
topic = f"{mqtt_base_topic}/data"
retry = 3
while retry:
if net.enable():
ip = net.dns_lookup(mqtt_server)
msg["rssi"] = net.rssi()
if ip:
if net.send_mqtt(ip, topic, msg):
break
retry -= 1
net.disable()
time.sleep(60)
net.disable()
env_data = []
tvoc = {}
print(f"sleeping for next sample. count: {total_count}")
time.sleep(config.getVal('sample_interval') * 60)
except Exception as e:
if net:
buf = io.StringIO()
sys.print_exception(e, buf)
traceback_str = buf.getvalue()
traceback_array = traceback_str.splitlines()
t = time.gmtime()
msg = {
"u": uid,
"v": config.get_version(),
"t": type(e).__name__,
"a": e.args,
"tb": traceback_array,
"utc": "{}-{:02d}-{:02d}T{:02d}:{:02d}:{:02d}".format(t[0], t[1], t[2], t[3], t[4], t[5]),
}
topic = f"{mqtt_base_topic}/exception"
net.disable()
if net.enable():
ip = net.dns_lookup(mqtt_server)
if ip:
net.send_mqtt(ip, topic, msg)
net.disable()
machine.reset()