-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathmain.py
More file actions
218 lines (186 loc) · 6.11 KB
/
main.py
File metadata and controls
218 lines (186 loc) · 6.11 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
import crypto
import json
import machine
import os
import sys
import ubinascii as binascii
from network import WLAN, LTE
from helpers import *
from ubirch import SimProtocol
print("\n- - - UBIRCH protocol (SIM) - - -\n")
# load some necessary config (request API keys from ubirch)
with open("config.json") as f:
cfg = json.load(f)
UPP_SERVER = 'niomon.{}.ubirch.com'.format(cfg["env"])
KEY_SERVER = 'key.{}.ubirch.com'.format(cfg["env"])
BOOT_SERVER = 'api.console.{}.ubirch.com'.format(cfg["env"])
device_name = "ukey"
cert_id = "ucrt"
lte = LTE()
if machine.reset_cause() != machine.DEEPSLEEP_RESET:
#if we are not coming from deepsleep, the modem is probably in a strange state -> reset
print("Not coming from sleep, resetting modem to be safe...")
reset_modem(lte,debug_print=cfg.get("debug", False))
if 'wifi' in cfg:
nb_iot_connection = False
func_lvl = 4 # disable modem transmit and receive RF circuits
else:
nb_iot_connection = True
func_lvl = 1 # full modem functionality
# set up modem
try:
set_modem_func_lvl(lte, func_lvl)
except Exception as e:
set_led(LED_PURPLE)
sys.print_exception(e)
reset()
# set up network connection
if nb_iot_connection:
# check Network Coverage for UE device (i.e LTE modem)
if not lte.ue_coverage():
print("!! There seems to be no Netwok Coverage !! Try to attach and connect anyway ...")
# initialize LTE and connect to LTE network
try:
lte_setup(lte, nb_iot_connection, cfg.get("apn"))
except Exception as e:
set_led(LED_PURPLE)
sys.print_exception(e)
lte_shutdown(lte)
reset()
else:
# initialize wifi connection
wlan = WLAN(mode=WLAN.STA)
try:
wifi_connect(wlan, cfg["wifi"]["ssid"], cfg["wifi"]["pass"])
except Exception as e:
set_led(LED_PURPLE)
sys.print_exception(e)
reset()
# set time
try:
set_time()
except Exception as e:
set_led(LED_PURPLE)
sys.print_exception(e)
lte_shutdown(lte)
reset()
# initialize the ubirch protocol interface
ubirch = None
try:
ubirch = SimProtocol(lte=lte, at_debug=cfg.get("debug", False))
except Exception as e:
set_led(LED_RED)
sys.print_exception(e)
ubirch.deinit()
lte_shutdown(lte)
reset()
# get IMSI from SIM
imsi = get_imsi(lte)
print("IMSI: {}\n".format(imsi))
# check if PIN is known and bootstrap if unknown
pin_file = imsi + ".bin"
pin = ""
if pin_file in os.listdir('.'):
with open(pin_file, "rb") as f:
pin = f.readline().decode()
else:
try:
pin = bootstrap(imsi, BOOT_SERVER, cfg["password"])
except Exception as e:
set_led(LED_ORANGE)
sys.print_exception(e)
ubirch.deinit()
lte_shutdown(lte)
reset()
with open(pin_file, "wb") as f:
f.write(pin.encode())
# unlock SIM
ubirch.sim_auth(pin)
# get UUID from SIM
device_uuid = ubirch.get_uuid(device_name)
print("UUID: {}\n".format(device_uuid))
# try to get X.509 certificate from SIM
cert = b''
try:
cert = ubirch.get_certificate(cert_id)
print("X.509 certificate [hex] : " + binascii.hexlify(cert).decode())
print("X.509 certificate [base64]: " + binascii.b2a_base64(cert).decode())
except Exception as e:
print("getting X.509 certificate from SIM failed: {}\n".format(e))
# create a self-signed certificate for the public key
print("-- creating self-signed certificate for identity {}".format(device_uuid))
cert = get_certificate(device_name, device_uuid, ubirch)
print("cert: {}\n".format(cert.decode()))
# register public key at ubirch key service
try:
print("resp: {}\n".format(register_key(KEY_SERVER, cfg["password"], cert).decode()))
except Exception as e:
set_led(LED_ORANGE)
sys.print_exception(e)
ubirch.deinit()
lte_shutdown(lte)
reset()
interval = 60
print("-- starting loop (interval = {} sec)\n".format(interval))
while True:
start_time = wake_up() # start timer
# reinitialize LTE and reconnect to LTE network
try:
lte_setup(lte, nb_iot_connection, cfg.get("apn"))
except Exception as e:
set_led(LED_PURPLE)
sys.print_exception(e)
ubirch.deinit()
lte_shutdown(lte)
reset()
# get data
payload_data = binascii.hexlify(crypto.getrandbits(32))
# create message with timestamp, UUID and data to ensure unique hash
message = '{{"ts":{},"id":"{}","data":"{}"}}'.format(
start_time,
device_uuid,
binascii.b2a_base64(payload_data).decode().rstrip('\n'))
print("\nmessage: {}\n".format(message))
# generate UPP with the message hash using the automatic hashing functionality of the SIM card
try:
upp = ubirch.message_chained(device_name, message.encode(), hash_before_sign=True)
except Exception as e:
set_led(LED_RED)
sys.print_exception(e)
time.sleep(3)
continue
print("UPP (msgpack): {}\n".format(binascii.hexlify(upp).decode()))
print("hash (SHA256): {}".format(binascii.b2a_base64(get_upp_payload(upp)).decode()))
# make sure device is still connected before sending data
try:
if nb_iot_connection:
# check NB-IOT connection
if not lte.isconnected():
nb_iot_connect(lte)
else:
# check WIFI connection
wlan = WLAN(mode=WLAN.STA)
if not wlan.isconnected():
wifi_connect(wlan, cfg["wifi"]["ssid"], cfg["wifi"]["pass"])
except Exception as e:
set_led(LED_PURPLE)
sys.print_exception(e)
ubirch.deinit()
lte_shutdown(lte)
reset()
# # # # # # # # # # # # # # # # # # #
# send message to your backend here #
# # # # # # # # # # # # # # # # # # #
# send UPP to ubirch backend
try:
post(UPP_SERVER, device_uuid, cfg["password"], upp)
except Exception as e:
set_led(LED_ORANGE)
sys.print_exception(e)
time.sleep(3)
continue
# if lte.isconnected():
# print(">> disconnecting LTE")
# lte.disconnect()
lte_shutdown(lte, detach=False)
sleep_until_next_interval(start_time, interval)