-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.py
389 lines (326 loc) · 10.9 KB
/
main.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
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
# POLARIS_FORTEBIT
# Created at 2019-07-26 11:34:26.282569
from fortebit.polaris import polaris
from fortebit.polaris import modem
from fortebit.polaris import gnss
import vm
import sfw
vm.set_option(vm.VM_OPT_RESET_ON_EXCEPTION, 1)
vm.set_option(vm.VM_OPT_TRACE_ON_EXCEPTION, 1)
vm.set_option(vm.VM_OPT_RESET_ON_HARDFAULT, 1)
vm.set_option(vm.VM_OPT_TRACE_ON_HARDFAULT, 1)
import streams
s = streams.serial()
import mcu
import timestamp
import timers
import ssl
import requests
import threading
from wireless import gsm
import utils
sleep(1000)
# CONFIG
poll_time = 100 # poll inputs at twice the specified period in ms
gps_period = 10000 # gps lat,lon and speed telemetry period in ms
update_period = 6 * gps_period # other telemetry data period in ms
no_ignition_period = 300000 # no ignition telemetry data period in ms
fw_version = "1.11"
# POLARIS INIT
try:
print("Polaris default app")
polaris.init()
print("MCU UID:", [hex(b) for b in mcu.uid()])
print("VM info:", vm.info())
print("FW version:", fw_version)
print("Watchdog was triggered:", sfw.watchdog_triggered())
polaris.ledRedOn()
polaris.ledGreenOff()
except Exception as e:
print("Failed polaris init with", e)
sleep(500)
mcu.reset()
# INIT HW
try:
print("Initializing Modem...")
modem = modem.init()
print("Initializing GNSS...")
gnss = gnss.init()
# verify preconditions and start utility thread
utils.start()
print("Starting Accelerometer...")
import accel
accel.start()
print("Starting GNSS...")
gnss.start()
gnss.set_rate(2000)
print("Starting Modem...")
modem.startup()
# enable modem/gnss utilities
utils.modem = modem
utils.gnss = gnss
sfw.watchdog(0, 30000)
sfw.kick()
if utils.check_terminal(s):
utils.do_terminal(s)
minfo = gsm.mobile_info()
print("Modem:", minfo)
# enable SMS checking
utils.check_sms = True
except Exception as e:
print("Failed init hw with", e)
sleep(500)
mcu.reset()
# GATHERING SETTINGS
name = None
apn = None
email = None
try:
print("Read settings...")
settings = utils.readSettings()
sfw.kick()
if "apn" in settings:
apn = settings["apn"]
print("APN:", apn)
if "email" in settings:
email = settings["email"]
print("Email:", email)
if "name" in settings:
name = settings["name"]
print("Name:", name)
if apn is not None and not utils.validate_apn(apn):
print("Invalid APN!")
apn = None
if email is not None and not utils.validate_email(email):
print("Invalid email!")
email = None
if name is None:
name = "Polaris"
print("Saving name:", name)
settings["name"] = name
utils.saveSettings(settings)
if apn is None:
print("APN is not defined, can't connect to Internet!")
apn = utils.request_apn(s)
print("Saving APN:", apn)
settings["apn"] = apn
utils.saveSettings(settings)
if email is None:
print("email is not defined, can't register to Cloud!")
email = utils.request_email(s)
print("Saving email:", email)
settings["email"] = email
utils.saveSettings(settings)
except Exception as e:
print("Failed gathering settings with", e)
sleep(500)
mcu.reset()
# GSM ATTACH
try:
print("Waiting for network...",end='')
for _ in range(150):
sfw.kick()
ninfo = gsm.network_info()
if ninfo[6]:
break
sleep(1000)
if (_ % 10) == 9:
print('.',end='')
else:
raise TimeoutError
print("ok!")
print("Attached to network:", ninfo)
print("Activating data connection...")
for _ in range(3):
try:
gsm.attach(apn)
break
except Exception as e:
print("Retrying...", e)
try:
gsm.detach()
sleep(5000 * (_ + 1))
except:
pass
else:
raise TimeoutError
linfo = gsm.link_info()
print("Connection parameters:", linfo)
except Exception as e:
print("Network failure", e)
sleep(500)
mcu.reset()
# FORTEBIT CLOUD
try:
from fortebit.polaris import cloud
# get access token
device_token = cloud.getAccessToken(minfo[0], mcu.uid())
# NOTE! Do not disclose security token in production builds
print("Access Token:", device_token)
print("Connecting to Fortebit Cloud...")
# retrieve the CA certificate used to sign the howsmyssl.com certificate
cacert = __lookup(SSL_CACERT_DST_ROOT_CA_X3)
# create a SSL context to require server certificate verification
ctx = ssl.create_ssl_context(cacert=cacert, options=ssl.CERT_REQUIRED | ssl.SERVER_AUTH)
# NOTE: if the underlying SSL driver does not support certificate validation
# uncomment the following line!
# ctx = None
from fortebit.iot import iot
from fortebit.iot import mqtt_client
# from fortebit.iot import http_client
# let's create a device passing the token and the type of client
device = iot.Device(device_token, mqtt_client.MqttClient, ctx) # use ctx for TLS
# device = iot.Device(device_token, http_client.HttpClient, ctx) # use ctx for TLS
utils.client = device.client
# connect the device
if not device.connect():
for _ in range(5):
sfw.kick()
try:
sleep(3000 * (_ + 1))
print("Retrying...")
if device.connect():
break
except Exception as e:
print("Failed connect...", e)
else:
raise TimeoutError
print("Device is connected")
polaris.ledGreenOn()
# start the device
device.run()
sfw.kick()
print("Device is up and running")
# if not registered, register device to Fortebit Cloud
if not cloud.isRegistered(device, email):
sfw.kick()
retry = timers.now()
print("Device is not registered, register device...")
while timers.now() - retry < 60000:
if cloud.register(device, email):
sfw.kick()
if cloud.isRegistered(device, email):
break
if not device.is_connected():
raise ConnectionError
sleep(5000)
print("Retry device registration...")
else:
raise TimeoutError
sfw.kick()
print("Device is registered")
polaris.ledRedOff()
polaris.ledGreenOff()
print("Publish device attributes")
device.publish_attributes({"name": name,
"target_board": vm.info()[1].upper(),
"vm_version": vm.info()[2],
"fw_version": fw_version})
sfw.kick()
except Exception as e:
print("Failed access to Fortebit cloud", e)
sleep(500)
mcu.reset()
# TELEMETRY LOOP
try:
accel.get_sigma() # reset accumulated value
sleep(500)
last_time = -(no_ignition_period + gps_period) # force sending data immediately
counter = 0
sos = -1
connected = True
ignition = None
sos = None
telemetry = {}
disconn_time = None
while True:
# allow other threads to run while waiting
sleep(poll_time*2)
sfw.kick()
now_time = timers.now()
if utils.check_terminal(s):
utils.do_terminal(s)
# read inputs
old_ign = ignition
ignition = polaris.getIgnitionStatus()
old_sos = sos
sos = polaris.getEmergencyStatus()
extra_send = False
if connected and not device.is_connected():
if disconn_time is None:
disconn_time = now_time + 60000 # add some time to recover
connected = False
elif not connected and device.is_connected():
connected = True
disconn_time = None
if not connected and disconn_time:
if now_time > disconn_time:
raise TimeoutError
pass
# led waiting status
utils.status_led(False, ignition, connected)
if sos != old_sos:
telemetry['sos'] = sos
extra_send = True
if ignition != old_ign:
telemetry['ignition'] = ignition
extra_send = True
if not extra_send:
if ignition == 0:
# sleep as indicated by rate for no ignition
if now_time - last_time < no_ignition_period - poll_time:
continue
extra_send = True
else:
# sleep as indicated by rate
if now_time - last_time < gps_period - poll_time:
continue
ts = modem.rtc()
#print("MODEM RTC =", ts)
if counter % (update_period / gps_period) == 0 or extra_send:
telemetry['ignition'] = ignition
telemetry['sos'] = sos
if polaris.isBatteryBackup():
telemetry['charger'] = -1
else:
telemetry['battery'] = utils.decimal(3, polaris.readMainVoltage())
telemetry['charger'] = polaris.getChargerStatus()
telemetry['backup'] = utils.decimal(3, polaris.readBattVoltage())
telemetry['temperature'] = utils.decimal(2, accel.get_temperature())
telemetry['sigma'] = utils.decimal(3, accel.get_sigma())
pr = accel.get_pitchroll()
telemetry['pitch'] = utils.decimal(1, pr[0])
telemetry['roll'] = utils.decimal(1, pr[1])
if gnss.has_fix():
fix = gnss.fix()
# only transmit position when it's accurate
if fix[6] < 2.5:
telemetry['latitude'] = utils.decimal(6, fix[0])
telemetry['longitude'] = utils.decimal(6, fix[1])
telemetry['speed'] = utils.decimal(1, fix[3])
if counter % (update_period / gps_period) == 0 or extra_send:
telemetry['altitude'] = utils.decimal(1, fix[2])
telemetry['COG'] = utils.decimal(1, fix[4])
if counter % (update_period / gps_period) == 0 or extra_send:
telemetry['nsat'] = fix[5]
telemetry['HDOP'] = utils.decimal(2, fix[6])
# replace timestamp with GPS
ts = fix[9]
elif ts is not None and ts[0] < 2019:
ts = None
if ts is not None:
ts = str(timestamp.to_unix(ts)) + "000"
counter += 1
last_time = now_time
# led sending status
utils.status_led(True, ignition, connected)
print("Publishing:", counter, ts, telemetry)
sfw.kick()
ok = device.publish_telemetry(telemetry, ts)
telemetry = {}
if not ok:
print("Publishing failed") # TODO: retry or store to qspiflash and resend later
except Exception as e:
print("Failed telemetry loop", e)
sleep(500)
mcu.reset()