-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
1640 lines (1131 loc) · 59.2 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
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
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
from importlib.resources import path
import os
import logging
import logging.handlers as handlers
import json
import sys
import sqlite3
import traceback
import pyModeS as pms #pip3 install pyModeS
from pymongo import MongoClient #pip3 install pymongo
import uuid
import time
import datetime
from datetime import datetime, timedelta
import threading
from threading import Thread, current_thread
import requests
import paho.mqtt.client #pip3 install paho-mqtt
import signal
from rulesEngine import rulesEngine as skyFollowerRE
from watchdog.observers import Observer #pip3 install watchdog
from watchdog.events import PatternMatchingEventHandler
import schedule
import queue
import multiprocessing
import socket
import random
import re
def handle_interrupt(signal, frame):
raise sigKill("SIGKILL Requested")
class sigKill(Exception):
pass
class noQueueReaderThreadsAvailable(Exception):
pass
class adsbConnectFailure(Exception):
pass
class StoppableThread(threading.Thread):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._stop_event = threading.Event()
def stop(self):
self._stop_event.set()
def stopped(self):
return self._stop_event.is_set()
class ADSBClient(StoppableThread):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.connected = False
self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
def run(self):
try:
self.socket.connect((settings['adsb']['uri'], settings['adsb']['port']))
self.connected = True
while self.connected == True:
if self.stopped() != False:
break
data = self.socket.recv(4096)
messages = []
msg_stop = False
self.current_msg = ""
for b in data:
if b == 59:
msg_stop = True
ts = time.time()
messages.append([self.current_msg, ts])
if b == 42:
msg_stop = False
self.current_msg = ""
if (not msg_stop) and (48 <= b <= 57 or 65 <= b <= 70 or 97 <= b <= 102):
self.current_msg = self.current_msg + chr(b)
data = []
for msg in messages:
stats.increment_message_count()
messageQueue.put(msg)
stats.set_message_queue_depth(messageQueue.qsize())
self.socket.close()
logger.debug("ADS-B socket closed.")
except ConnectionRefusedError as ex:
logger.error("Connection to ADS-B Receiver " + settings['adsb']['uri'] + ":" + str(settings['adsb']['port']) + " was refused.")
except Exception as ex:
logger.error("Exception in adsbClient of type: " + type(ex).__name__ + ": " + str(ex))
def messageQueueReader():
while threading.current_thread().stopped() == False:
try:
messageProcessor(messageQueue.get())
messageQueue.task_done()
except queue.Empty:
pass
def messageProcessor(objMsg):
try:
handlingWaitTime = int((datetime.now().timestamp() - objMsg[1])*1000)
stats.set_message_handling_high_water_mark(handlingWaitTime)
#Reduce message consumption as the queue gets deeper and the hardware can't keep up
if 1000 < handlingWaitTime >= 850: #Throttle 5%
if random.randint(1, 20) == 1:
stats.increment_throttled_message_count()
return
if 1500 < handlingWaitTime >= 1000: #Throttle 10%
if random.randint(1, 10) == 1:
stats.increment_throttled_message_count()
return
if 2000 < handlingWaitTime >= 1500: #Throttle 20%
if random.randint(1, 5) == 1:
stats.increment_throttled_message_count()
return
if handlingWaitTime >= 2000: #Throttle 33%
if random.randint(1, 3) == 1:
stats.increment_throttled_message_count()
return
#Object to store data
data = {}
#Ensure the message appears to be valid and is not corrupted
if len(objMsg[0]) < 14:
return
#Get the download format
data['downlink_format'] = pms.df(objMsg[0])
if data['downlink_format'] not in [5, 21, 17]:
return
data['icao_hex'] = pms.adsb.icao(objMsg[0])
#Ensure we have an icao_hex
if data['icao_hex'] == None:
return
if data['downlink_format'] in [5, 21]:
data['squawk'] = pms.common.idcode(objMsg[0])
if data['downlink_format'] == 17:
typeCode = pms.adsb.typecode(objMsg[0])
data['messageType'] = typeCode
#Throw away TC 28 and 29...not yet supported
if typeCode in [28, 29]:
return
if 1 <= typeCode <= 4:
data['ident'] = pms.adsb.callsign(objMsg[0]).replace("_","")
data['category'] = pms.adsb.category(objMsg[0])
if 5 <= typeCode <= 18 or 20 <= typeCode <=22:
data['latitude'] = pms.adsb.position_with_ref(objMsg[0], settings['latitude'], settings['longitude'])[0]
data['longitude'] = pms.adsb.position_with_ref(objMsg[0], settings['latitude'], settings['longitude'])[1]
data['altitude'] = pms.adsb.altitude(objMsg[0])
if 5 <= typeCode <= 8:
data['velocity'] = pms.adsb.velocity(objMsg[0])[0]
data['heading'] = pms.adsb.velocity(objMsg[0])[1]
data['vertical_speed'] = pms.adsb.velocity(objMsg[0])[2]
if typeCode == 19:
data['velocity'] = pms.adsb.velocity(objMsg[0])[0]
data['heading'] = pms.adsb.velocity(objMsg[0])[1]
data['vertical_speed'] = pms.adsb.velocity(objMsg[0])[2]
if typeCode == 31:
data['adsb_version'] = pms.adsb.version(objMsg[0])
flight = Flight()
flight.setIcao_hex(data['icao_hex'])
if not flight.exists:
stats.increment_flights_count()
flight.first_message = objMsg[1]
flight.last_message = objMsg[1]
flight.total_messages = flight.total_messages + 1
if "latitude" in data and "longitude" in data and "altitude" in data:
flight.addPosition(Position(objMsg[1], data['latitude'], data['longitude'], data['altitude']))
if "velocity" in data and "heading" in data and "vertical_speed" in data:
flight.addVelocity(Velocity(objMsg[1], data['velocity'], data['heading'], data['vertical_speed']))
if "squawk" in data:
flight.setSquawk(data['squawk'])
if "category" in data:
flight.setCategory(data['category'])
if "ident" in data:
flight.setIdent(data['ident'])
if "adsb_version" in data:
flight.setAdsbVersion(data['adsb_version'])
flight.evaluateRules()
flight.saveLocal()
except Exception as ex:
logger.error("Exception of type: " + type(ex).__name__ + " while processing message [" + str(objMsg[0]) + "] : " + str(ex))
pass
def mqtt_publishNotication(identifier, message):
if settings['mqtt']['enabled'] != True:
return
if mqttClient.is_connected():
mqttClient.publish(settings["mqtt"]["topic_rule"] + identifier, message)
def mqtt_publishOnline():
if settings['mqtt']['enabled'] != True:
return
if mqttClient.is_connected() == True:
mqttClient.publish(settings['mqtt']['topic_status'], "ONLINE", retain=True)
def mqtt_publishAutoDiscovery():
if settings['mqtt']['enabled'] != True:
return
if settings['home_assistant']['enabled'] != True:
return
ad = autoDiscovery()
ad.status()
ad.stats()
ad.rules()
def mqtt_onConnect(client, userdata, flags, rc):
#########################################################
# Handles MQTT Connections
#########################################################
if settings['mqtt']['enabled'] != True:
return
if rc != 0:
logger.warning("Failed to connect to MQTT. Response code: " + str(rc) + ".")
else:
logger.info("MQTT connected to " + settings["mqtt"]["uri"] + ".")
mqtt_publishOnline()
mqtt_publishAutoDiscovery()
stats.publish()
def exitApp(exitCode=None):
if exitCode is None:
exitCode = 0
#Commit the database if it is not memory
if 'local_database_mode' in settings:
if settings['local_database_mode'] == "disk":
logger.info("Committing database to disk.")
localDb.commit()
if exitCode == 0:
logger.info(applicationName + " application finished successfully.")
sys.exit(exitCode)
if exitCode != 0:
logger.info("Error; Exiting with code " + str(exitCode))
os._exit(exitCode)
def setLogLevel(logLevel):
if logLevel == "debug":
logger.setLevel(logging.DEBUG)
logger.debug("Logging set to DEBUG.")
return
if logLevel == "error":
logger.setLevel(logging.ERROR)
logger.error("Logging set to ERROR.")
return
if logLevel == "warning":
logger.setLevel(logging.WARNING)
logger.warning("Logging set to WARNING.")
return
if logLevel == "critical":
logger.setLevel(logging.CRITICAL)
logger.critical("Logging set to CRITICAL.")
return
def setup():
global applicationName
global settings
global logger
global localDb
global mqttClient
global rulesEngine
global stats
global messageQueue
applicationName = "SkyFollower"
settings = {}
stats = statistics()
try:
filePath = os.path.dirname(os.path.realpath(__file__))
logger = logging.getLogger(applicationName)
formatter = logging.Formatter('%(asctime)s [%(levelname)s] - %(message)s')
logHandler = handlers.RotatingFileHandler(os.path.join(filePath, 'events.log'), maxBytes=10485760, backupCount=1)
logHandler.setFormatter(formatter)
logger.addHandler(logHandler)
logger.setLevel(logging.INFO)
if os.path.exists(os.path.join(filePath, 'settings.json')) == False:
raise Exception("Settings file does not exist. Expected file " + os.path.join(filePath, 'settings.json'))
with open(os.path.join(filePath, 'settings.json')) as settingsFile:
settings = json.load(settingsFile)
if "log_level" in settings:
settings['log_level'] = settings['log_level'].lower()
else:
settings['log_level'] = "info"
setLogLevel(settings['log_level'])
logger.info(applicationName + " application started.")
logger.debug("Python Version: " + str(sys.version))
#if sys.version_info.major == 3 and sys.version_info.minor < 10:
# logger.warning("Current Python Version " + str(sys.version_info.major) + "." + str(sys.version_info.minor) + " is below the recommended 3.10. See readme for further information.")
if "files" not in settings:
raise Exception ("files object is missing from settings.json")
rulesEngine = skyFollowerRE(logger)
if "areas" in settings['files']:
settings['files']['areas'] = settings['files']['areas'].replace("./", filePath + "/")
rulesEngine.loadAreas(settings['files']['areas'])
else:
logger.warning("Missing files -> areas in settings.json")
if "rules" in settings['files']:
settings['files']['rules'] = settings['files']['rules'].replace("./", filePath + "/")
rulesEngine.loadRules(settings['files']['rules'])
else:
logger.warning("Missing files -> rules in settings.json")
if "adsb" not in settings:
raise Exception ("adsb object is missing from settings.json")
if "uri" not in settings['adsb']:
raise Exception ("Missing adsb -> uri in settings.json")
if settings['adsb']['uri'] == "":
raise Exception ("Empty adsb -> uri in settings.json")
if "port" not in settings['adsb']:
raise Exception ("Missing adsb -> port in settings.json")
if str(settings['adsb']['port']).isnumeric() != True:
raise Exception ("Invalid adsb -> port in settings.json")
if "type" not in settings['adsb']:
raise Exception ("Missing adsb -> type in settings.json")
if settings['adsb']['type'].lower() not in ['raw']:
raise Exception ("Unknown adsb -> type in settings.json. Valid values are raw")
if "flight_ttl_seconds" not in settings:
logger.debug("Setting 'flight_ttl_seconds' not declared in the settings file; Defaulting to 300 seconds.")
settings['flight_ttl_seconds'] = 300
if str(settings['flight_ttl_seconds']).isnumeric() != True:
raise Exception ("Invalid flight_ttl_seconds in settings.json")
if "latitude" not in settings:
raise Exception ("Missing latitude in settings.json")
if isinstance(settings['latitude'], float) == False:
raise Exception ("Invalid latitude in settings.json")
if "longitude" not in settings:
raise Exception ("Missing longitude in settings.json. Expected float.")
if isinstance(settings['longitude'], float) == False:
raise Exception ("Invalid longitude in settings.json. Expected float.")
if settings['latitude'] == 38.8969137 and settings['longitude'] == -77.0357096:
raise Exception ("Configure your latitude and longitude in settings.json.")
settings['queue_reader_thread_count'] = 1 #Hard-coding for now, because multi-threading causes performances issues
#if "queue_reader_thread_count" not in settings:
# settings['queue_reader_thread_count'] = multiprocessing.cpu_count()
#else:
# if str(settings['queue_reader_thread_count']).isnumeric() != True:
# raise Exception ("Invalid queue_reader_thread_count in settings.json")
# if settings['queue_reader_thread_count'] < 1:
# raise Exception ("Setting 'queue_reader_thread_count' cannot be less than 1.")
# if settings['queue_reader_thread_count'] > multiprocessing.cpu_count():
# logger.warning("Setting 'queue_reader_thread_count' is set to " + str(settings['queue_reader_thread_count']) + ", which is greater than the CPU count of " + str(multiprocessing.cpu_count()))
#logger.debug("Queue Reader Thread Count: " + str(settings['queue_reader_thread_count']) + " CPU Count: " + str(multiprocessing.cpu_count()))
if 'mqtt' not in settings:
logger.info("mqtt is not declared in the settings file; MQTT will be disabled.")
settings['mqtt'] = {}
settings['mqtt']['enabled'] = False
else:
if 'enabled' not in settings['mqtt']:
settings['mqtt']['enabled'] = False
if settings['mqtt']['enabled'] == False:
logger.info("MQTT is disabled in the settings file; MQTT will be disabled.")
if "uri" not in settings['mqtt']:
raise Exception ("Missing mqtt -> uri in settings.json")
if settings['mqtt']['uri'] == "":
raise Exception ("Empty mqtt -> uri in settings.json")
if "port" not in settings['mqtt']:
raise Exception ("Missing mqtt -> port in settings.json")
if str(settings['mqtt']['port']).isnumeric() != True:
raise Exception ("Invalid mqtt -> port in settings.json")
if "username" not in settings['mqtt']:
raise Exception ("Missing mqtt -> username in settings.json")
if settings['mqtt']['username'] == "":
raise Exception ("Empty mqtt -> username in settings.json")
if "password" not in settings['mqtt']:
raise Exception ("Missing mqtt -> password in settings.json")
if settings['mqtt']['password'] == "":
raise Exception ("Empty mqtt -> password in settings.json")
if "topic" not in settings['mqtt']:
raise Exception ("Missing mqtt -> topic in settings.json")
if settings['mqtt']['topic'] == "":
raise Exception ("Empty mqtt -> topic in settings.json")
settings['mqtt']['topic_status'] = str(os.path.join(settings['mqtt']['topic'], "status"))
settings['mqtt']['topic_rule'] = str(os.path.join(settings['mqtt']['topic'], "rule/"))
settings['mqtt']['topic_statistics'] = str(os.path.join(settings['mqtt']['topic'], "statistic/"))
mqttClient = paho.mqtt.client.Client()
if 'local_database_mode' not in settings:
settings['local_database_mode'] = "memory"
if "mongoDb" not in settings:
raise Exception ("mongoDb object is missing from settings.json")
if "enabled" not in settings['mongoDb']:
settings['mongoDb']['enabled'] = False
logger.info("mongoDb -> enabled is missing in the settings file; MongoDB persistence will be disabled.")
if "uri" not in settings['mongoDb']:
raise Exception ("Missing mongoDb -> uri in settings.json")
if "port" not in settings['mongoDb']:
raise Exception ("Missing mongoDb -> port in settings.json")
if str(settings['mongoDb']['port']).isnumeric() != True:
raise Exception ("Invalid mongoDb -> port in settings.json")
if "database" not in settings['mongoDb']:
raise Exception ("Missing mongoDb -> database in settings.json")
if "collection" not in settings['mongoDb']:
raise Exception ("Missing mongoDb -> collection in settings.json")
if 'registration' not in settings:
logger.info("registration is not declared in the settings file; Retrieving registrations will be disabled.")
settings['registration'] = {}
settings['registration']['enabled'] = False
else:
if 'enabled' not in settings['registration']:
settings['registration']['enabled'] = False
if settings['registration']['enabled'] == False:
logger.info("Registration is disabled in the settings file; Retrieving registrations will be disabled.")
if "registration" not in settings:
raise Exception ("registration object is missing from settings.json")
if "uri" not in settings['registration']:
raise Exception ("Missing registration -> uri in settings.json")
if "$ICAO_HEX$" not in settings['registration']['uri']:
raise Exception ("Missing $ICAO_HEX$ text in registration -> uri in settings.json")
if "x-api-key" not in settings['registration']:
raise Exception ("Missing registration -> x-api-key in settings.json")
if 'operators' not in settings:
logger.info("operators is not declared in the settings file; Retrieving operators will be disabled.")
settings['operators'] = {}
settings['operators']['enabled'] = False
else:
if 'enabled' not in settings['operators']:
settings['operators']['enabled'] = False
if settings['operators']['enabled'] == False:
logger.info("Operators is disabled in the settings file; Retrieving operators will be disabled.")
if "uri" not in settings['operators']:
raise Exception ("Missing operators -> uri in settings.json")
if "$IDENT$" not in settings['operators']['uri']:
raise Exception ("Missing $IDENT$ text in operators -> uri in settings.json")
if "x-api-key" not in settings['operators']:
raise Exception ("Missing operators -> x-api-key in settings.json")
if 'flights' not in settings:
logger.info("flights is not declared in the settings file; Retrieving flight info will be disabled.")
settings['flights'] = {}
settings['flights']['enabled'] = False
else:
if 'enabled' not in settings['flights']:
settings['flights']['enabled'] = False
if settings['flights']['enabled'] == False:
logger.info("Flights is disabled in the settings file; Retrieving flight info will be disabled.")
if "uri" not in settings['flights']:
raise Exception ("Missing flights -> uri in settings.json")
if "$IDENT$" not in settings['flights']['uri']:
raise Exception ("Missing $IDENT$ text in flights -> uri in settings.json")
if "x-api-key" not in settings['flights']:
raise Exception ("flights operators -> x-api-key in settings.json")
if 'home_assistant' not in settings:
logger.info("home_assistant is not declared in the settings file; Home Assistant will be disabled.")
settings['home_assistant'] = {}
settings['home_assistant']['enabled'] = False
else:
if 'enabled' not in settings['home_assistant']:
settings['home_assistant']['enabled'] = False
if settings['home_assistant']['enabled'] == False:
logger.info("Home Assistant is disabled in the settings file; Home Assistant operators will be disabled.")
if settings['home_assistant']['enabled'] == True and 'discovery_prefix' not in settings['home_assistant']:
settings['home_assistant']['discovery_prefix'] = "homeassistant"
logger.debug("Setting 'home_assistant -> discovery_prefix' not declared in the settings file; Defaulting to 'homeassistant'.")
settings['mqtt']['topic_home_assistant_autodiscovery'] = str(settings['home_assistant']['discovery_prefix'] + "/").replace("//", "/")
#Default the local database to be memory
if str(settings['local_database_mode']).lower() == "memory":
logger.debug("Using memory for localDb.")
localDb = sqlite3.connect(":memory:", check_same_thread=False)
else:
settings['local_database_mode'] = "disk"
logger.debug("Using disk for localDb.")
settings['database_file'] = os.path.join(filePath, applicationName + ".db")
#Create the localDB tables
if os.path.exists(settings['database_file']):
#Delete the old database
os.remove(settings['database_file'])
if os.path.exists(settings['database_file'] + "-journal"):
#Delete the old database
os.remove(settings['database_file'] + "-journal")
localDb = sqlite3.connect(settings['database_file'], check_same_thread=False)
localDb.row_factory = sqlite3.Row
cursor = localDb.cursor()
#Create the temporary tables
cursor.execute("CREATE TABLE flights (icao_hex text NOT NULL, first_message real NOT NULL, last_message real, total_messages integer, aircraft text, ident text, operator text, squawk text, origin text, destination text, matched_rules text, PRIMARY KEY(icao_hex))")
cursor.execute("CREATE TABLE positions (icao_hex text, timestamp real, latitude real, longitude real, altitude integer)")
cursor.execute("CREATE TABLE velocities (icao_hex text, timestamp real, velocity integer, heading real, vertical_speed integer)")
cursor.execute("CREATE INDEX positions_icao_hex ON positions (icao_hex);")
cursor.execute("CREATE INDEX velocities_icao_hex ON velocities (icao_hex);")
#Setup the message queue
messageQueue = queue.Queue()
stats.message_queue = messageQueue
except Exception as ex:
logger.error(ex)
exitApp(1)
def run_scheduled_tasks():
t = current_thread()
t.alive = True
while t.alive:
schedule.run_pending()
time.sleep(1)
def main():
try:
if settings['mqtt']['enabled'] == True:
#Setup the handlers for connection and messages
mqttClient.on_connect = mqtt_onConnect
#Create the MQTT credentials from the settings file
mqttClient.username_pw_set(settings["mqtt"]["username"], password=settings["mqtt"]["password"])
#Set the last will and testament
mqttClient.will_set(settings["mqtt"]["topic_status"], payload="OFFLINE", qos=0, retain=True)
#Connect to MQTT
mqttClient.connect_async(settings["mqtt"]["uri"], port=settings["mqtt"]["port"], keepalive=60)
threading.excepthook = threadExceptHook
threadsMessageQueueReader = []
for i in range(settings['queue_reader_thread_count']):
queueReaderThread = StoppableThread(target=messageQueueReader, name="MessageQueueReader_" + str(i), daemon=True)
threadsMessageQueueReader.append(queueReaderThread)
queueReaderThread.start()
adsb_client = ADSBClient()
threadADSBClient = Thread(name="ADSB Client", target=adsb_client.run, daemon=True)
threadADSBClient.start()
#Start the threads
if settings['mqtt']['enabled'] == True:
mqttClient.loop_start()
flight = Flight()
schedule.every().hour.at("00:30").do(stats.reset_hour)
schedule.every().day.at("00:00").do(stats.reset_today)
schedule.every(30).seconds.do(stats.publish)
schedule.every(10).seconds.do(flight.persistStaleFlights)
schedule.every(10).seconds.do(checkQueueReaderThreads, threadsMessageQueueReader)
threadScheduler = threading.Thread(name="scheduled_tasks", target=run_scheduled_tasks, daemon=True)
threadScheduler.start()
observer = Observer()
file_changed_event_handler = fileChanged()
observer.schedule(file_changed_event_handler, path=os.path.dirname(settings['files']['areas']))
observer.schedule(file_changed_event_handler, path=os.path.dirname(settings['files']['rules']))
observer.start()
#Run forever
threadADSBClient.join()
#Exit with an error code
exitApp(2)
except adsbConnectFailure as ex:
exitApp(3)
except (sigKill, KeyboardInterrupt) as ex:
logger.debug("Number of active message queue reader threads at exit: " + str(checkQueueReaderThreads(threadsMessageQueueReader)))
logger.info("Shutdown was requested.")
for job in schedule.get_jobs():
schedule.cancel_job(job)
if settings['mqtt']['enabled'] == True:
mqttClient.publish(settings["mqtt"]['topic_status'], "TERMINATING")
if adsb_client.connected == True:
adsb_client.stop()
while checkQueueReaderThreads(threadsMessageQueueReader) > 0 and messageQueue.qsize() > 0:
logger.info("Waiting for the queue readers to empty the message queue. Current queue size is " + str(messageQueue.qsize()))
time.sleep(1)
flight = Flight()
flight.persistStaleFlights(True)
if settings['mqtt']['enabled'] == True and mqttClient.is_connected():
mqttClient.loop_stop()
for messageQueueReaderThread in threadsMessageQueueReader:
if messageQueueReaderThread.is_alive() == True:
messageQueueReaderThread.stop()
exitApp(0)
except Exception as ex:
logger.error("Exception of type: " + type(ex).__name__ + " in main(): " + str(ex))
pass
def threadExceptHook(args):
if args.exc_type == noQueueReaderThreadsAvailable:
logger.critical(str(args.exc_value))
for job in schedule.get_jobs():
schedule.cancel_job(job)
if settings['mqtt']['enabled'] == True:
mqttClient.publish(settings["mqtt"]['topic_status'], "TERMINATING")
flight = Flight()
flight.persistStaleFlights(True)
if settings['mqtt']['enabled'] == True and mqttClient.is_connected():
mqttClient.loop_stop()
exitApp(4)
#Handle all other errors by writing them to the log
logger.critical(traceback.format_tb(args.exc_traceback))
logger.critical(str(args))
def checkQueueReaderThreads(threadsMessageQueueReader):
working_threads = 0
for thread in threadsMessageQueueReader:
if thread.is_alive():
working_threads = working_threads + 1
continue
if working_threads < settings['queue_reader_thread_count']:
logger.critical("A queue reader thread has terminated. Current queue reader thread count is: " + str(working_threads))
settings['queue_reader_thread_count'] = working_threads
if working_threads == 0:
raise noQueueReaderThreadsAvailable("No remaining queue reader threads to process incoming messages.")
return working_threads
class Flight():
"""Flight Record"""
def __init__(self) -> None:
self.exists:bool = False
self.icao_hex:str = ""
self.first_message:int = 0
self.last_message:int = 0
self.total_messages:int = 0
self.aircraft:dict = {}
self.ident:str = ""
self.operator:dict = {}
self.squawk:str = ""
self.origin:dict = {}
self.destination:dict = {}
self.positions:list[Position] = []
self.velocities:list[Velocity] = []
self.matched_rules:list[str] = []
def toDict(self) -> dict:
record = {}
record['icao_hex'] = self.icao_hex
record['first_message'] = datetime.utcfromtimestamp(self.first_message)
record['last_message'] = datetime.utcfromtimestamp(self.last_message)
record['total_messages'] = self.total_messages
if self.aircraft != {}:
record['aircraft'] = self.aircraft
else:
record['aircraft'] = {}
record['aircraft']['icao_hex'] = self.icao_hex
if self.ident != "":
record['ident'] = self.ident
if self.operator != {}:
record['operator'] = self.operator
if self.squawk != "":
record['squawk'] = self.squawk
record['origin'] = self.origin
record['destination'] = self.destination
if len(self.matched_rules) > 0 and settings['log_level'] == "debug":
record['matched_rules'] = self.matched_rules
if len(self.positions) > 0:
record['positions'] = []
for position in self.positions:
record['positions'].append(position.toDict())
if len(self.velocities) > 0:
record['velocities'] = []
for velocity in self.velocities:
record['velocities'].append(velocity.toDict())
return record
def get(self, limit_position:bool = True, limit_velocity:bool = True):
"""Retrieves the given ICAO HEX from the local database.
If no records are found, False is returned.
If records are returned, True is returned and the object is populated from the database.
"""
sqliteCur = localDb.cursor()
sqliteCur.execute("SELECT icao_hex, first_message, last_message, total_messages, aircraft, ident, operator, squawk, origin, destination, matched_rules FROM flights WHERE icao_hex='" + self.icao_hex + "'")
result = sqliteCur.fetchall()
if len(result) == 0:
self.exists = False
logger.debug("ICAO HEX " + self.icao_hex + " will be added to localDb.")
return
self.exists = True
self.icao_hex = result[0]['icao_hex']
self.first_message = result[0]['first_message']
self.last_message = result[0]['last_message']
self.total_messages = result[0]['total_messages']
self.aircraft = json.loads(result[0]['aircraft'])
self.ident = result[0]['ident']
self.operator = json.loads(result[0]['operator'])
self.squawk = result[0]['squawk']
self.origin = json.loads(result[0]['origin'])
self.destination = json.loads(result[0]['destination'])
self.matched_rules = json.loads(result[0]['matched_rules'])
self.positions = []
self.velocities = []
self._getPositions(limit_position)
self._getVelocities(limit_velocity)
return True
def saveLocal(self):
"""Saves the flight data to the localDb."""
sqliteCur = localDb.cursor()
sqlStatement = "REPLACE INTO flights (icao_hex, first_message, last_message, total_messages, aircraft, ident, operator, squawk, origin, destination, matched_rules) VALUES (?,?,?,?,?,?,?,?,?,?,?)"
parameters = (self.icao_hex, self.first_message, self.last_message, self.total_messages, json.dumps(self.aircraft), self.ident, json.dumps(self.operator), self.squawk, json.dumps(self.origin), json.dumps(self.destination), json.dumps(self.matched_rules))
sqliteCur.execute(sqlStatement, parameters)
def persist(self):
"""Persists the data to the remote data store."""
if settings['mongoDb']['enabled'] == False:
return
mongoDBClient = MongoClient(host=settings['mongoDb']['uri'], port=settings['mongoDb']['port'])
adsbDB = mongoDBClient[settings['mongoDb']['database']]
adsbDBCollection = adsbDB[settings['mongoDb']['collection']]
record = self.toDict()
record['_id'] = str(uuid.uuid4())
if "icao_hex" in record:
record.pop("icao_hex")
if "military" in record['aircraft']:
if record['aircraft']['military'] == False:
record['aircraft'].pop("military")
if "icao_code" in self.origin:
record['origin'] = self.origin['icao_code']
else:
record.pop('origin')
if "icao_code" in self.destination:
record['destination'] = self.destination['icao_code']
else:
record.pop('destination')
if "source" in self.operator:
record['operator'].pop("source")
adsbDBCollection.insert_one(record)
logger.debug("Persisted record _id: " + record['_id'] + " ICAO HEX: " + record['aircraft']['icao_hex'])
def delete(self):
"""Deletes the object from the localDb."""
sqliteCur = localDb.cursor()
sqliteCur.execute("DELETE FROM flights WHERE icao_hex ='" + self.icao_hex + "'")
sqliteCur.execute("DELETE FROM positions WHERE icao_hex ='" + self.icao_hex + "'")
sqliteCur.execute("DELETE FROM velocities WHERE icao_hex ='" + self.icao_hex + "'")
def _getPositions(self, limit:bool=True):
"""Retrieves position reports for the current aircraft.
If limit is True, only the last message is returned."""
sql = "SELECT timestamp, latitude, longitude, altitude FROM positions WHERE icao_hex='" + self.icao_hex + "' ORDER BY timestamp"
if limit == True:
sql = sql + " DESC LIMIT 1"
sqliteCur = localDb.cursor()
sqliteCur.execute(sql)
results = sqliteCur.fetchall()
if results == None or len(results) < 1: