-
Notifications
You must be signed in to change notification settings - Fork 0
/
code.py
529 lines (464 loc) · 17.6 KB
/
code.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
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
import asyncio
import binascii
import random
import time
import adafruit_connection_manager
import adafruit_requests
import adafruit_rfm9x
import adafruit_rgbled
import board
import busio
import microcontroller
import rtc
import storage
import supervisor
import usyslog
from adafruit_esp32spi import PWMOut, adafruit_esp32spi, adafruit_esp32spi_wifimanager
from APRS import APRS
from digitalio import DigitalInOut, Direction, Pull
from microcontroller import watchdog as w
from watchdog import WatchDogMode
import config
# software release
RELEASE = "1.0"
# stop autoreloading
supervisor.runtime.autoreload = False
# gateway or igate detect via pin state
versionPin = DigitalInOut(board.GP9)
versionPin.direction = Direction.INPUT
versionPin.pull = Pull.UP
# 1/2W Pa
pa = DigitalInOut(board.GP2)
pa.direction = Direction.OUTPUT
pa.value = False
# 5v biasT
biast = DigitalInOut(board.GP1)
biast.direction = Direction.OUTPUT
biast.value = False
igate = False
if versionPin.value is True:
igate = True
loraTimeout = 900
biast = DigitalInOut(board.GP0)
biast.direction = Direction.OUTPUT
biast.value = False
else:
loraTimeout = 30
transmit = DigitalInOut(board.GP0)
transmit.direction = Direction.OUTPUT
transmit.value = False
if config.biast is True:
biast.value = True
# board version
if igate is True:
VERSION = "APRSiGate"
else:
VERSION = "APRSGateway"
def _format_datetime(datetime):
return "{:02}/{:02}/{} {:02}:{:02}:{:02}".format(
datetime.tm_mon,
datetime.tm_mday,
datetime.tm_year,
datetime.tm_hour,
datetime.tm_min,
datetime.tm_sec,
)
def purple(data):
stamp = "{}".format(_format_datetime(time.localtime()))
return "\x1b[38;5;104m[" + str(stamp) + "] " + config.call + " " + data + "\x1b[0m"
def green(data):
stamp = "{}".format(_format_datetime(time.localtime()))
return (
"\r\x1b[38;5;112m[" + str(stamp) + "] " + config.call + " " + data + "\x1b[0m"
)
def blue(data):
stamp = "{}".format(_format_datetime(time.localtime()))
return "\x1b[38;5;14m[" + str(stamp) + "] " + config.call + " " + data + "\x1b[0m"
def yellow(data):
return "\x1b[38;5;220m" + data + "\x1b[0m"
def red(data):
stamp = "{}".format(_format_datetime(time.localtime()))
return "\x1b[1;5;31m[" + str(stamp) + "] " + config.call + " " + data + "\x1b[0m"
def bgred(data):
stamp = "{}".format(_format_datetime(time.localtime()))
return "\x1b[41m[" + str(stamp) + "] " + config.call + data + "\x1b[0m"
# wait for console
time.sleep(2)
print("\x1b[1;5;31m -- " + f"{config.call} -=- {VERSION} {RELEASE}" + "\x1b[0m\n")
try:
from secrets import secrets
except ImportError:
print(red("WiFi secrets are kept in secrets.py, please add them there!"))
raise
esp32_cs = DigitalInOut(board.GP17)
esp32_ready = DigitalInOut(board.GP14)
esp32_reset = DigitalInOut(board.GP13)
# Clock MOSI(TX) MISO(RX)
spi = busio.SPI(board.GP18, board.GP19, board.GP16)
esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset)
if esp.status == adafruit_esp32spi.WL_IDLE_STATUS:
print(yellow("ESP32 found and in idle mode"))
print(yellow("Firmware version: " + (esp.firmware_version).decode("utf-8")))
print(yellow("MAC addr: " + str([hex(i) for i in esp.MAC_address])))
RED_LED = PWMOut.PWMOut(esp, 25)
GREEN_LED = PWMOut.PWMOut(esp, 26)
BLUE_LED = PWMOut.PWMOut(esp, 27)
status_light = adafruit_rgbled.RGBLED(RED_LED, GREEN_LED, BLUE_LED)
esp.set_hostname(config.call + "-APRS-iGate")
wifi = adafruit_esp32spi_wifimanager.ESPSPI_WiFiManager(esp, secrets, status_light)
## Connect to WiFi
print(yellow("Connecting to WiFi..."))
wifi.connect()
print(yellow("Connected!"))
print(yellow("Connected to: [" + str(esp.ssid, "utf-8") + "]\tRSSI:" + str(esp.rssi)))
print()
# Initialize a requests object with a socket and esp32spi interface
pool = adafruit_connection_manager.get_radio_socketpool(esp)
ssl_context = adafruit_connection_manager.get_radio_ssl_context(esp)
requests = adafruit_requests.Session(pool, ssl_context)
# aprs auth packet
rawauthpacket = f"user {config.call} pass {config.passcode} vers {VERSION} {RELEASE} filter t/m/{config.call}/{config.msgDistance}\n"
now = None
while now is None:
try:
now = time.localtime(esp.get_time()[0])
except OSError:
pass
rtc.RTC().datetime = now
# configure watchdog
w.timeout = 5
w.mode = WatchDogMode.RESET
w.feed()
if storage.getmount("/").readonly is False:
try:
UPDATE_URL = (
"https://raw.githubusercontent.com/Guru-RF/LoRa433APRSGatewayWiFi/main/ota"
)
response = requests.get(UPDATE_URL)
if response.status_code == 200:
OTARELEASE = response.content.decode("utf-8")
if OTARELEASE != RELEASE:
print(
yellow(
f"OTA update available old:{RELEASE} new:{OTARELEASE}, updating..."
)
)
# OTA update simplified
UPDATE_URL = "https://raw.githubusercontent.com/Guru-RF/LoRa433APRSGatewayWiFi/main/code.py"
response = requests.get(UPDATE_URL)
if response.status_code == 200:
print(yellow("OTA update available, downloading..."))
with open("ota.py", "wb") as f:
for chunk in response.iter_content(chunk_size=32):
f.write(chunk)
w.feed()
print(yellow("OTA update complete, restarting..."))
microcontroller.reset()
else:
print(yellow("no OTA update available"))
print()
except TimeoutError as error:
print(yellow(f"OTA unavailable {error}"))
print()
# usyslog
# until we cannot have multiple sockets open
# this can be used for debugging and reporting software updates
syslog = usyslog.UDPClient(
pool,
esp,
hostname=config.call,
host=config.syslogHost,
port=config.syslogPort,
process=VERSION + RELEASE,
)
if config.call == "":
syslog.send("callsign missing!")
print()
print(red("callsign is empty, please set callsign in config.py"))
while True:
w.feed()
time.sleep(1)
if config.passcode == "":
syslog.send("callsign missing!")
print()
print(red("callsign is empty, please set passcode in config.py"))
while True:
w.feed()
time.sleep(1)
syslog.send("Alive and kicking!")
# aprs
aprs = APRS()
# tx msg buffer
txmsgs = []
# configure tcp socket
s = pool.socket(type=pool.SOCK_STREAM)
s.settimeout(4)
socketaddr = pool.getaddrinfo(config.aprs_host, config.aprs_port)[0][4]
async def iGateAnnounce():
# Periodically sends status packets and position packets to the APRS-IS server over TCP.
# Handles reconnecting if the send fails.
global w, s, rawauthpacket
try:
s.connect(socketaddr)
s.settimeout(4)
s.send(bytes(rawauthpacket, "utf-8"))
w.feed()
except Exception as error:
print(bgred(f"init: An exception occurred: {error}"))
print(
purple(
f"init: Connect to ARPS {config.aprs_host} {config.aprs_port} Failed ! Lost Packet ! Restarting System !"
)
)
microcontroller.reset()
while True:
await asyncio.sleep(0)
w.feed()
temp = microcontroller.cpus[0].temperature
freq = microcontroller.cpus[1].frequency / 1000000
rawpacket = (
f"{config.call}>APRFGI,TCPIP*:>Running on RP2040 t:{temp}C f:{freq}Mhz\n"
)
try:
s.send(bytes(rawpacket, "utf-8"))
except Exception as error:
print(bgred(f"iGateStatus: An exception occurred: {error}"))
print(
purple(
f"iGateStatus: Reconnecting to ARPS {config.aprs_host} {config.aprs_port}"
)
)
s.close()
try:
s.connect(socketaddr)
w.feed()
s.settimeout(4)
s.send(bytes(rawauthpacket, "utf-8"))
s.send(bytes(rawpacket, "utf-8"))
except Exception as error:
print(bgred(f"iGateStatus: An exception occurred: {error}"))
syslog.send(f"iGateStatus: An exception occurred: {error}")
print(
purple(
f"Connect to ARPS {config.aprs_host} {config.aprs_port} Failed ! Lost Packet ! Restarting system !"
)
)
microcontroller.reset()
print(purple(f"iGateStatus: {rawpacket}"), end="")
pos = aprs.makePosition(
config.latitude, config.longitude, -1, -1, config.symbol
)
altitude = "/A={:06d}".format(int(config.altitude * 3.2808399))
comment = VERSION + "." + RELEASE + " " + config.comment + altitude
ts = aprs.makeTimestamp("z", now.tm_mday, now.tm_hour, now.tm_min, now.tm_sec)
message = f"{config.call}>APRFGI,TCPIP*:@{ts}{pos}{comment}\n"
try:
w.feed()
s.settimeout(4)
s.send(bytes(message, "utf-8"))
except Exception as error:
print(bgred(f"iGateStatus: An exception occurred: {error}"))
print(
purple(
f"iGateStatus: Reconnecting to ARPS {config.aprs_host} {config.aprs_port}"
)
)
s.close()
try:
s.connect(socketaddr)
w.feed()
s.settimeout(4)
s.send(bytes(rawauthpacket, "utf-8"))
s.send(bytes(message, "utf-8"))
except Exception as error:
print(bgred(f"iGateStatus: An exception occurred: {error}"))
syslog.send(f"iGateStatus: An exception occurred: {error}")
print(
purple(
f"iGateStatus: Connect to ARPS {config.aprs_host} {config.aprs_port} Failed ! Lost Packet ! Restarting system !"
)
)
microcontroller.reset()
print(purple(f"iGatePossition: {message}"), end="")
await asyncio.sleep(15 * 60)
async def tcpPost(packet):
# Sends an APRS packet over TCP to the APRS-IS server.
# Handles reconnecting if the send fails.
global w, s, rawauthpacket
w.feed()
rawpacket = f"{packet}\n"
try:
await asyncio.sleep(0)
s.settimeout(4)
s.send(bytes(rawpacket, "utf-8"))
except Exception as error:
print(bgred(f"aprsTCPSend: An exception occurred: {error}"))
print(
purple(
f"aprsTCPSend: Reconnecting to ARPS {config.aprs_host} {config.aprs_port}"
)
)
s.close()
try:
s.connect(socketaddr)
w.feed()
s.settimeout(4)
s.send(bytes(rawauthpacket, "utf-8"))
s.send(bytes(rawpacket, "utf-8"))
except Exception as error:
print(bgred(f"aprsTCPSend: An exception occurred: {error}"))
syslog.send(f"aprsTCPSend: An exception occurred: {error}")
print(
purple(
f"aprsTCPSend: Reconnecting to ARPS {config.aprs_host} {config.aprs_port} Failed ! Lost Packet ! Restarting system !"
)
)
microcontroller.reset()
print(blue(f"aprsTCPSend: {packet}"))
await asyncio.sleep(0)
async def aprsMsgFeed():
# read the ARPS feed for text messages and queues them for transmit
await asyncio.sleep(2)
print(purple("aprsMsgFeed: receiving APRS messages"))
global w, s, rawauthpacket, txmsgs
while True:
try:
while True:
await asyncio.sleep(0)
w.feed()
s.settimeout(0.01)
buff = s.recv(1024)
raw = buff.decode("utf-8")
for line in raw.splitlines():
if not line.startswith("#"):
if line[0].isupper():
station = (line.split(">", 1))[0]
tmpdata = (line.split("::", 1))[1]
destination = (tmpdata.split(":", 1))[0]
data = (tmpdata.split(":", 1))[1]
packet = f"{config.call}>APRFGD,RFONLY,WIDE1-1::{station}:{destination}:{data}"
if station not in config.filtersrc:
if config.allowdst is True:
if destination[:2] in config.filterdst:
txmsgs.append(packet)
else:
txmsgs.append(packet)
await asyncio.sleep(0)
except TimeoutError:
continue
# we ignore the timeout
except UnicodeError:
continue
# we ignore decode errors
except IndexError:
continue
# we ignore wrongly formated msgs
async def loraRunner(loop):
await asyncio.sleep(5)
global w, txmsgs
# Continuously receives LoRa packets and forwards valid APRS packets
# via WiFi. Configures LoRa radio, prints status messages, handles
# exceptions, creates asyncio tasks to process packets.
# LoRa APRS frequency
RADIO_FREQ_MHZ = 433.775
CS = DigitalInOut(board.GP21)
RESET = DigitalInOut(board.GP20)
spi = busio.SPI(board.GP10, MOSI=board.GP11, MISO=board.GP8)
rfm9x = adafruit_rfm9x.RFM9x(
spi, CS, RESET, RADIO_FREQ_MHZ, baudrate=1000000, agc=False, crc=True
)
if igate is False:
rfm9x.tx_power = 23
lastBeacon = time.monotonic() - 900
while True:
await asyncio.sleep(0)
# reboot weekly
if time.monotonic() > 604800:
microcontroller.reset()
w.feed()
timeout = int(loraTimeout) + random.randint(1, 9)
print(
purple(f"loraRunner: Waiting for lora APRS packet timeout:{timeout} ...\r"),
end="",
)
# packet = rfm9x.receive(w, with_header=True, timeout=timeout)
packet = await rfm9x.areceive(w, with_header=True, timeout=timeout)
if packet is not None:
if packet[:3] == (b"<\xff\x01"):
try:
rawdata = bytes(packet[3:]).decode("utf-8")
print(
green(
f"loraRunner: RX: RSSI:{rfm9x.last_rssi} SNR:{rfm9x.last_snr} Data:{rawdata}"
)
)
# syslog.send(
# f"loraRunner: RX: RSSI:{rfm9x.last_rssi} SNR:{rfm9x.last_snr} Data:{rawdata}"
# )
wifi.pixel_status((100, 100, 0))
loop.create_task(tcpPost(rawdata))
await asyncio.sleep(0)
wifi.pixel_status((0, 100, 0))
except Exception as error:
print(bgred(f"loraRunner: An exception occurred: {error}"))
syslog.send(f"loraRunner: An exception occurred: {error}")
print(purple("loraRunner: Lost Packet, unable to decode, skipping"))
continue
if igate is False:
# send a beacon every 15 minutes
if lastBeacon + 900 < time.monotonic():
lastBeacon = time.monotonic()
timestamp = str(time.time())
packet = f"{config.call}>APRFGD,RFONLY,WIDE1-1::APRFGD:{timestamp}|{config.latitude}|{config.longitude}"
biast.value = False
transmit.value = True
pa.value = True
await asyncio.sleep(int(config.paDelay))
print(red(f"loraRunner: TX: {packet}"))
# syslog.send(f"loraRunner: TX: {packet}")
await rfm9x.asend(
bytes("{}".format("<"), "UTF-8")
+ binascii.unhexlify("FF")
+ binascii.unhexlify("01")
+ bytes("{}".format(packet), "UTF-8"),
)
w.feed()
pa.value = False
transmit.value = False
if config.biast is True:
biast.value = True
if len(txmsgs) != 0:
print()
biast.value = False
transmit.value = True
pa.value = True
await asyncio.sleep(int(config.paDelay))
while len(txmsgs) != 0:
w.feed()
packet = txmsgs.pop(0)
print(red(f"loraRunner: TX: {packet}"))
# syslog.send(f"loraRunner: TX: {packet}")
await rfm9x.asend(
bytes("{}".format("<"), "UTF-8")
+ binascii.unhexlify("FF")
+ binascii.unhexlify("01")
+ bytes("{}".format(packet), "UTF-8"),
)
w.feed()
pa.value = False
transmit.value = False
if config.biast is True:
biast.value = True
async def main():
# Create asyncio tasks to run the LoRa receiver, APRS message feed,
# and iGate announcement in parallel. Gather the tasks and wait for
# them to complete wich will never happen ;)
loop = asyncio.get_event_loop()
loraR = asyncio.create_task(loraRunner(loop))
loraA = asyncio.create_task(iGateAnnounce())
if igate is False:
loraM = asyncio.create_task(aprsMsgFeed())
await asyncio.gather(loraA, loraM, loraR)
else:
await asyncio.gather(loraA, loraR)
asyncio.run(main())