-
Notifications
You must be signed in to change notification settings - Fork 36
/
adsb-mqtt.py
executable file
·525 lines (443 loc) · 20.4 KB
/
adsb-mqtt.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
#!/usr/bin/env python3
#
# Copyright (c) 2020 Johan Kanflo (github.com/kanflo)
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
from typing import *
import socket, select
import argparse
import threading
import json
import sys
import os
import logging
import logging
import coloredlogs
import calendar
from datetime import datetime, timedelta
import signal
import random
import time
import re
import errno
import sbs1
import utils
import mqtt_wrapper
import pandas as pd
ID = str(random.randint(1,100001))
# Clean out observations this often
OBSERVATION_CLEAN_INTERVAL = 30
# Socket read timeout
DUMP1090_SOCKET_TIMEOUT = 60
args = None
# http:https://stackoverflow.com/questions/1165352/fast-comparison-between-two-python-dictionary
class DictDiffer(object):
"""
Calculate the difference between two dictionaries as:
(1) items added
(2) items removed
(3) keys same in both but changed values
(4) keys same in both and unchanged values
"""
def __init__(self, current_dict, past_dict):
self.current_dict, self.past_dict = current_dict, past_dict
self.set_current, self.set_past = set(current_dict.keys()), set(past_dict.keys())
self.intersect = self.set_current.intersection(self.set_past)
def added(self):
return self.set_current - self.intersect
def removed(self):
return self.set_past - self.intersect
def changed(self):
return set(o for o in self.intersect if self.past_dict[o] != self.current_dict[o])
def unchanged(self):
return set(o for o in self.intersect if self.past_dict[o] == self.current_dict[o])
class Observation(object):
"""
This class keeps track of the observed flights around us.
"""
__icao24 = None
__loggedDate = None
__callsign = None
__altitude = None
__altitudeTime = None
__groundSpeed = None
__track = None
__lat = None
__lon = None
__latLonTime = None
__verticalRate = None
__operator = None
__registration = None
__type = None
__manufacturer = None
__model = None
__updated = None
__route = None
__image_url = None
__planedb_nagged = False # Used in case the icao24 is unknown and we only want to log this once
def __init__(self, sbs1msg):
logging.info("%s appeared" % sbs1msg["icao24"])
self.__icao24 = sbs1msg["icao24"]
self.__loggedDate = datetime.utcnow() # sbs1msg["loggedDate"]
self.__callsign = sbs1msg["callsign"]
self.__altitude = sbs1msg["altitude"]
self.__altitudeTime = datetime.utcnow()
self.__groundSpeed = sbs1msg["groundSpeed"]
self.__track = sbs1msg["track"]
self.__lat = sbs1msg["lat"]
self.__lon = sbs1msg["lon"]
self.__latLonTime = datetime.utcnow()
self.__verticalRate = sbs1msg["verticalRate"]
self.__operator = None
self.__registration = None
self.__type = None
self.__model = None
self.__manufacturer = None
self.__updated = True
plane = planes.loc[planes['icao24'] == self.__icao24.lower()]
if plane.size == 27:
logging.info("{} {} {} {} {}".format(plane["registration"].values[0],plane["manufacturername"].values[0], plane["model"].values[0], plane["operator"].values[0], plane["owner"].values[0]))
self.__registration = plane['registration'].values[0]
self.__type = str(plane['manufacturername'].values[0]) + " " + str(plane['model'].values[0])
self.__manufacturer = plane['manufacturername'].values[0]
self.__model = plane['model'].values[0]
self.__operator = plane['operator'].values[0]
else:
if not self.__planedb_nagged:
self.__planedb_nagged = True
logging.error("icao24 %s not found in the database" % (self.__icao24))
logging.error(plane)
def update(self, sbs1msg):
oldData = dict(self.__dict__)
if sbs1msg["icao24"]:
self.__icao24 = sbs1msg["icao24"]
if sbs1msg["callsign"] and self.__callsign != sbs1msg["callsign"]:
self.__callsign = sbs1msg["callsign"].rstrip()
if sbs1msg["altitude"]:
self.__altitude = sbs1msg["altitude"]
self.__altitudeTime = datetime.utcnow()
if sbs1msg["groundSpeed"]:
self.__groundSpeed = sbs1msg["groundSpeed"]
if sbs1msg["track"]:
self.__track = sbs1msg["track"]
if sbs1msg["lat"]:
self.__lat = sbs1msg["lat"]
self.__latLonTime = datetime.utcnow()
if sbs1msg["lon"]:
self.__lon = sbs1msg["lon"]
self.__latLonTime = datetime.utcnow()
if sbs1msg["verticalRate"]:
self.__verticalRate = sbs1msg["verticalRate"]
if not self.__verticalRate:
self.__verticalRate = 0
if sbs1msg["generatedDate"]:
self.__generatedDate = sbs1msg["generatedDate"]
#if sbs1msg["loggedDate"]:
# self.__loggedDate = sbs1msg["loggedDate"]
if oldData["_Observation__lat"] != self.__lat:
self.__loggedDate = datetime.utcnow()
if self.__planedb_nagged == False and self.__registration == None:
plane = planes.loc[planes['icao24'] == self.__icao24.lower()]
if plane.size == 27:
logging.info("{} {} {} {} {}".format(plane["registration"].values[0],plane["manufacturername"].values[0], plane["model"].values[0], plane["operator"].values[0], plane["owner"].values[0]))
self.__registration = plane['registration'].values[0]
self.__type = str(plane['manufacturername'].values[0]) + " " + str(plane['model'].values[0])
self.__manufacturer = plane['manufacturername'].values[0]
self.__model = plane['model'].values[0]
self.__operator = plane['operator'].values[0]
else:
if not self.__planedb_nagged:
self.__planedb_nagged = True
logging.error("icao24 %s not found in the database" % (self.__icao24))
# Check if observation was updated
newData = dict(self.__dict__)
del oldData["_Observation__loggedDate"]
del newData["_Observation__loggedDate"]
d = DictDiffer(oldData, newData)
self.__updated = len(d.changed()) > 0
def getIcao24(self) -> str:
return self.__icao24
def getLat(self) -> float:
return self.__lat
def getLon(self) -> float:
return self.__lon
def isUpdated(self) -> bool:
return self.__updated
def clearUpdated(self):
self.__updated = False
def getLoggedDate(self) -> datetime:
return self.__loggedDate
def getGroundSpeed(self) -> float:
return self.__groundSpeed
def getHeading(self) -> float:
return self.__track
def getAltitude(self) -> float:
return self.__altitude
def getType(self) -> str:
return self.__type
def getManufacturer(self) -> str:
return self.__manufacturer
def getModel(self) -> str:
return self.__model
def getRegistration(self) -> str:
return self.__registration
def getOperator(self) -> str:
return self.__operator
def getRoute(self) -> str:
return self.__route
def getImageUrl(self) -> str:
return self.__image_url
def isPresentable(self) -> bool:
return self.__altitude and self.__groundSpeed and self.__track and self.__lat and self.__lon # and self.__operator and self.__registration and self.__image_url
def dump(self):
"""Dump this observation on the console
"""
now = datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')
logging.debug("> %s %s %-7s - trk:%3d spd:%3d alt:%5d (%5d) %.4f, %.4f" % (now, self.__icao24, self.__callsign, self.__track, self.__groundSpeed, self.__altitude, self.__verticalRate, self.__lat, self.__lon))
def json(self) -> str:
"""Return JSON representation of this observation
Arguments:
bearing {int} -- bearing to observation in degrees
distance {int} -- distance to observation in meters
Returns:
str -- JSON string
"""
if self.__route is None:
route = "None"
else:
route = "%s" % self.__route
route = route.replace("'", "\"")
if self.__callsign is None:
callsign = "None"
else:
callsign = "\"%s\"" % self.__callsign
planeDict = {"verticalRate": self.__verticalRate, "time": time.time(), "lat": self.__lat, "lon": self.__lon, "altitude": self.__altitude, "groundSpeed": self.__groundSpeed, "icao24": self.__icao24, "registration": self.__registration, "track": self.__track, "operator": self.__operator, "loggedDate": self.__loggedDate, "type": self.__type, "manufacturer": self.__manufacturer, "model": self.__model, "callsign": callsign}
jsonString = json.dumps(planeDict, indent=4, sort_keys=True, default=str)
return jsonString
def dict(self):
d = dict(self.__dict__)
if d["_Observation__verticalRate"] == None:
d["verticalRate"] = 0
if "_Observation__lastAlt" in d:
del d["lastAlt"]
if "_Observation__lastLat" in d:
del d["lastLat"]
if "_Observation__lastLon" in d:
del d["lastLon"]
#d["loggedDate"] = "%s" % (d["_Observation__loggedDate"])
return d
class FlightTracker(object):
__dump1090_host: str = ""
__dump1090_port: int = 0
__mqtt_broker: str = ""
__mqtt_port: int = 0
__dump1090_sock: socket.socket = None
__mqtt_bridge = None
__observations: Dict[str, str] = {}
__next_clean: datetime = None
__has_nagged: bool = False
def __init__(self, dump1090_host: str, mqtt_broker: str, mqtt_topic: str, dump1090_port: int = 30003, mqtt_port: int = 1883, ):
"""Initialize the flight tracker
Arguments:
dump1090_host {str} -- Name or IP of dump1090 host
mqtt_broker {str} -- Name or IP of dump1090 MQTT broker
mqtt_topic {str} -- MQTT topic for plane reports
Keyword Arguments:
dump1090_port {int} -- Override the dump1090 raw port (default: {30003})
mqtt_port {int} -- Override the MQTT default port (default: {1883})
"""
self.__dump1090_host = dump1090_host
self.__dump1090_port = dump1090_port
self.__mqtt_broker = mqtt_broker
self.__mqtt_port = mqtt_port
self.__sock = None
self.__observations = {}
self.__next_clean = datetime.utcnow() + timedelta(seconds=OBSERVATION_CLEAN_INTERVAL)
self.__mqtt_topic = mqtt_topic
def dump1090Connect(self) -> bool:
"""If not connected, connect to the dump1090 host
Returns:
bool -- True if we are connected
"""
if self.__dump1090_sock == None:
try:
if not self.__has_nagged:
logging.info("Connecting to dump1090")
self.__dump1090_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.__dump1090_sock.connect((self.__dump1090_host, self.__dump1090_port))
logging.info("ADSB connected")
self.__dump1090_sock.settimeout(DUMP1090_SOCKET_TIMEOUT)
self.__has_nagged = False
return True
except socket.error as e:
if not self.__has_nagged:
logging.critical("Failed to connect to ADSB receiver on %s:%s, retrying : %s" % (self.__dump1090_host, self.__dump1090_port, e))
self.__has_nagged = True
self.__dump1090_sock = None
time.sleep(5)
return False
else:
return True
def dump1090Close(self):
"""Close connection to dump1090 host.
"""
try:
self.__dump1090_sock.close()
except socket.error:
pass
self.__dump1090_sock = None
self.__has_nagged = False
logging.critical("Closing dump1090 connection")
def dump1090Read(self) -> str:
"""Read a line from the dump1090 host. If the host went down, close the socket and return None
Returns:
str -- An SBS1 message or None if disconnected or timeout
Yields:
str -- An SBS1 message or None if disconnected or timeout
"""
try:
try:
buffer = self.__dump1090_sock.recv(4096)
except ConnectionResetError:
logging.critical("Connection Reset Error")
self.dump1090Close()
yield None
except socket.error:
logging.critical("Socket Error")
self.dump1090Close()
yield None
buffer = buffer.decode("utf-8")
buffering = True
if buffer == "":
logging.critical("Buffer Empty")
self.dump1090Close()
return None
while buffering:
if "\n" in buffer:
(line, buffer) = buffer.split("\r\n", 1)
yield line
else:
try:
more = self.__dump1090_sock.recv(4096)
except ConnectionResetError:
logging.critical("Connection Reset Error")
self.dump1090Close()
yield None
except socket.error:
logging.critical("Socket Error")
self.dump1090Close()
yield None
if not more:
buffering = False
else:
if not isinstance(more, str):
more = more.decode("utf-8")
if more == "":
logging.critical("Receive Empty")
self.dump1090Close()
return None
buffer += more
if buffer:
yield buffer
except socket.timeout:
yield None
def run(self):
"""Run the flight tracker.
"""
timeHeartbeat = 0
self.__mqtt_bridge = mqtt_wrapper.bridge(host = self.__mqtt_broker, port = self.__mqtt_port, client_id = "skyscan-adsb-mqtt-%s" % (ID)) # TOOD: , user_id = args.mqtt_user, password = args.mqtt_password)
#threading.Thread(target = self.__publish_thread, daemon = True).start()
self.__mqtt_bridge.publish("skyscan/registration", "skyscan-adsb-mqtt-"+ID+" Registration", 0, False)
while True:
if timeHeartbeat < time.mktime(time.gmtime()):
timeHeartbeat = time.mktime(time.gmtime()) + 10
self.__mqtt_bridge.publish("skyscan/heartbeat", "skyscan-adsb-mqtt-"+ID+" Heartbeat", 0, False)
if not self.dump1090Connect():
continue
for data in self.dump1090Read():
if data is None:
continue
self.cleanObservations()
m = sbs1.parse(data)
if m:
icao24 = m["icao24"]
if icao24 in self.__observations:
self.__observations[icao24].update(m)
else:
self.__observations[icao24] = Observation(m)
if self.__observations[icao24].isPresentable() and self.__observations[icao24].isUpdated():
retain = False
self.__mqtt_bridge.publish(self.__mqtt_topic, self.__observations[icao24].json(), 0, retain)
#logging.info("%s alt %5d trk %3d spd %3d %s" % (self.__observations[icao24].getIcao24(), self.__observations[icao24].getAltitude(), self.__observations[icao24].getHeading(), self.__observations[icao24].getGroundSpeed(), self.__observations[icao24].getType()))
time.sleep(0.01)
def cleanObservations(self):
"""Clean observations for planes not seen in a while
"""
now = datetime.utcnow()
if now > self.__next_clean:
cleaned = []
for icao24 in self.__observations:
# logging.info("[%s] %s -> %s : %s" % (icao24, self.__observations[icao24].getLoggedDate(), self.__observations[icao24].getLoggedDate() + timedelta(seconds=OBSERVATION_CLEAN_INTERVAL), now))
if self.__observations[icao24].getLoggedDate() + timedelta(seconds=OBSERVATION_CLEAN_INTERVAL) < now:
logging.info("%s disappeared" % (icao24))
cleaned.append(icao24)
for icao24 in cleaned:
del self.__observations[icao24]
self.__next_clean = now + timedelta(seconds=OBSERVATION_CLEAN_INTERVAL)
def main():
global args
global logging
global planes
parser = argparse.ArgumentParser(description='A Dump 1090 to MQTT bridge')
parser.add_argument('-r', '--radar-name', help="name of radar, used as topic string /adsb/<radar>/json", default='radar')
parser.add_argument('-m', '--mqtt-host', help="MQTT broker hostname", default='127.0.0.1')
parser.add_argument('-p', '--mqtt-port', type=int, help="MQTT broker port number (default 1883)", default=1883)
parser.add_argument('-H', '--dump1090-host', help="dump1090 hostname", default='127.0.0.1')
parser.add_argument('-P', '--dump1090-port', type=int, help="dump1090 port number (default 30003)", default=30003)
parser.add_argument('-t', '--mqtt-topic', dest='mqtt_topic', help="MQTT topic", default="skyscan/planes/json")
parser.add_argument('-v', '--verbose', action="store_true", help="Verbose output")
args = parser.parse_args()
level = logging.DEBUG if args.verbose else logging.INFO
styles = {'critical': {'bold': True, 'color': 'red'}, 'debug': {'color': 'green'}, 'error': {'color': 'red'}, 'info': {'color': 'white'}, 'notice': {'color': 'magenta'}, 'spam': {'color': 'green', 'faint': True}, 'success': {'bold': True, 'color': 'green'}, 'verbose': {'color': 'blue'}, 'warning': {'color': 'yellow'}}
level = logging.DEBUG if '-v' in sys.argv or '--verbose' in sys.argv else logging.INFO
if 1:
coloredlogs.install(level=level, fmt='%(asctime)s.%(msecs)03d \033[0;90m%(levelname)-8s '
''
'\033[0;36m%(filename)-18s%(lineno)3d\033[00m '
'%(message)s',
level_styles = styles)
else:
# Show process name
coloredlogs.install(level=level, fmt='%(asctime)s.%(msecs)03d \033[0;90m%(levelname)-8s '
'\033[0;90m[\033[00m \033[0;35m%(processName)-15s\033[00m\033[0;90m]\033[00m '
'\033[0;36m%(filename)s:%(lineno)d\033[00m '
'%(message)s')
logging.info("---[ Starting %s ]---------------------------------------------" % sys.argv[0])
planes = pd.read_csv("/app/data/aircraftDatabase.csv") #,index_col='icao24')
logging.info("Printing table")
logging.info(planes)
tracker = FlightTracker(args.dump1090_host, args.mqtt_host, args.mqtt_topic, dump1090_port = args.dump1090_port, mqtt_port = args.mqtt_port)
tracker.run() # Never returns
# Ye ol main
if __name__ == "__main__":
try:
main()
except Exception as e:
logging.critical(e, exc_info=True)