Debian Codegraph @

mlat/client/coordinator.py

raw symbols SCIP
1 # -*- mode: python; indent-tabs-mode: nil -*-
2
3 # Part of mlat-client - an ADS-B multilateration client.
4 # Copyright 2015, Oliver Jowett <[email protected]>
5 #
6 # This program is free software: you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation, either version 3 of the License, or
9 # (at your option) any later version.
10 #
11 # This program is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 # GNU General Public License for more details.
15 #
16 # You should have received a copy of the GNU General Public License
17 # along with this program. If not, see <http://www.gnu.org/licenses/>.
18
19 """
20 Core of the client: track aircraft and send data to the server as needed.
21 """
22
23 import asyncore
24 import time
25
26 import _modes
27 import mlat.profile
28 from mlat.client.util import monotonic_time, log
29 from mlat.client.stats import global_stats
30
31 import random
32 random.seed()
33
34 class Aircraft:
35 """One tracked aircraft."""
36
37 def __init__(self, icao):
38 self.icao = icao
39 self.messages = 0
40 self.last_message_time = 0
41 self.last_even_time = 0
42 self.last_odd_time = 0
43 self.adsb_good = False
44 self.even_message = None
45 self.odd_message = None
46 self.reported = False
47 self.requested = True
48 self.measurement_start = None
49 self.rate_measurement_start = 0
50 self.recent_adsb_positions = 0
51
52
53 class Coordinator:
54 update_interval = 4.5
55 report_interval = 4.0 # in multiples update_interval
56 stats_interval = 900.0
57 position_expiry_age = 30.0
58 expiry_age = 120.0
59
60 def __init__(self, receiver, server, outputs, freq, allow_anon, allow_modeac):
61 self.receiver = receiver
62 self.server = server
63 self.outputs = outputs
64 self.freq = freq
65 self.allow_anon = allow_anon
66 self.allow_modeac = allow_modeac
67
68 self.aircraft = {}
69 self.requested_traffic = set()
70 self.requested_modeac = set()
71 self.reported = set()
72 self.df_handlers = {
73 _modes.DF_EVENT_MODE_CHANGE: self.received_mode_change_event,
74 _modes.DF_EVENT_EPOCH_ROLLOVER: self.received_epoch_rollover_event,
75 _modes.DF_EVENT_TIMESTAMP_JUMP: self.received_timestamp_jump_event,
76 _modes.DF_EVENT_RADARCAPE_POSITION: self.received_radarcape_position_event,
77 0: self.received_df_misc,
78 4: self.received_df_misc,
79 5: self.received_df_misc,
80 16: self.received_df_misc,
81 20: self.received_df_misc,
82 21: self.received_df_misc,
83 11: self.received_df11,
84 17: self.received_df17,
85 _modes.DF_MODEAC: self.received_modeac
86 }
87 self.next_report = None
88 self.next_stats = monotonic_time() + 60
89 self.next_profile = monotonic_time()
90 self.next_aircraft_update = self.last_aircraft_update = monotonic_time()
91 self.recent_jumps = 0
92 self.last_jump_message = 0
93
94 self.server_send = 1
95
96 receiver.coordinator = self
97 server.coordinator = self
98
99 self.print_server_statistics = False
100
101 # internals
102
103 def run_forever(self):
104 self.run_until(lambda: False)
105
106 def run_until(self, termination_condition):
107 try:
108 next_heartbeat = monotonic_time() + 0.5
109 next_server_send = monotonic_time()
110 while not termination_condition():
111 # maybe there are no active sockets and
112 # we're just waiting on a timeout
113 if asyncore.socket_map:
114 asyncore.loop(timeout=0.1, count=5)
115 else:
116 time.sleep(0.5)
117
118 now = monotonic_time()
119 if now >= next_heartbeat:
120 next_heartbeat = now + 0.5
121 self.heartbeat(now)
122
123 if now >= next_server_send:
124 self.server_send = 1
125 next_server_send = now + 0.25
126
127 finally:
128 self.receiver.disconnect('Client shutting down')
129 self.server.disconnect('Client shutting down')
130 for o in self.outputs:
131 o.disconnect('Client shutting down')
132
133 def heartbeat(self, now):
134 self.receiver.heartbeat(now)
135 self.server.heartbeat(now)
136 for o in self.outputs:
137 o.heartbeat(now)
138
139 if now >= self.next_profile:
140 self.next_profile = now + 30.0
141 mlat.profile.dump_cpu_profiles()
142
143 if now >= self.next_aircraft_update:
144 self.next_aircraft_update = now + self.update_interval + random.random()
145 self.update_aircraft(now)
146
147 # piggyback reporting on regular updates
148 # as the reporting uses data produced by the update
149 if self.next_report is not None:
150 self.next_report += 1.0
151 if self.next_report >= self.report_interval:
152 #global_stats.log_and_reset(self)
153 self.next_report = 0.0
154 self.send_aircraft_report()
155 self.send_rate_report(now)
156
157 if now >= self.next_stats:
158 self.next_stats = now + self.stats_interval
159 self.periodic_stats(now)
160
161 def update_aircraft(self, now):
162 # process aircraft the receiver has seen
163 # (we have not necessarily seen any messages,
164 # due to the receiver filter)
165 for icao in self.receiver.recent_aircraft():
166 ac = self.aircraft.get(icao)
167 if not ac:
168 ac = Aircraft(icao)
169 ac.requested = (icao in self.requested_traffic)
170 ac.rate_measurement_start = now
171 self.aircraft[icao] = ac
172
173 if ac.last_message_time <= self.last_aircraft_update:
174 # fudge it a bit, receiver has seen messages
175 # but they were all filtered
176 ac.messages += 1
177 ac.last_message_time = now
178
179 if now - ac.last_even_time < self.position_expiry_age and now - ac.last_odd_time < self.position_expiry_age:
180 ac.adsb_good = True
181 else:
182 ac.adsb_good = False
183
184 # expire aircraft we have not seen for a while
185 for ac in list(self.aircraft.values()):
186 if (now - ac.last_message_time) > self.expiry_age:
187 del self.aircraft[ac.icao]
188
189 self.last_aircraft_update = now
190
191 def send_aircraft_report(self):
192 all_aircraft = {x.icao for x in self.aircraft.values() if x.messages > 1}
193 seen_ac = all_aircraft.difference(self.reported)
194 lost_ac = self.reported.difference(all_aircraft)
195
196 if seen_ac:
197 self.server.send_seen(seen_ac)
198 if lost_ac:
199 self.server.send_lost(lost_ac)
200
201 self.reported = all_aircraft
202
203 def send_rate_report(self, now):
204 # report ADS-B position rate stats
205 rate_report = {}
206 for ac in self.aircraft.values():
207 interval = now - ac.rate_measurement_start
208 if interval > 0 and ac.recent_adsb_positions > 0:
209 rate = 1.0 * ac.recent_adsb_positions / interval
210 ac.rate_measurement_start = now
211 ac.recent_adsb_positions = 0
212 rate_report[ac.icao] = rate
213
214 if rate_report:
215 self.server.send_rate_report(rate_report)
216
217 def periodic_stats(self, now):
218 global_stats.log_and_reset(self)
219
220 adsb_req = adsb_total = modes_req = modes_total = 0
221 now = monotonic_time()
222 for ac in self.aircraft.values():
223 if ac.messages < 2:
224 continue
225
226 if ac.adsb_good:
227 adsb_total += 1
228 if ac.requested:
229 adsb_req += 1
230 else:
231 modes_total += 1
232 if ac.requested:
233 modes_req += 1
234
235 log('Aircraft: {modes_req} of {modes_total} Mode S, {adsb_req} of {adsb_total} ADS-B used',
236 modes_req=modes_req,
237 modes_total=modes_total,
238 adsb_req=adsb_req,
239 adsb_total=adsb_total)
240
241 if self.recent_jumps > 0:
242 log('Out-of-order timestamps: {recent}', recent=self.recent_jumps)
243 self.recent_jumps = 0
244
245 # callbacks from server connection
246
247 def server_connected(self):
248 self.requested_traffic = set()
249 self.requested_modeac = set()
250 self.newly_seen = set()
251 self.aircraft = {}
252 self.reported = set()
253 self.next_report = random.random() * self.report_interval
254 if self.receiver.state != 'ready':
255 self.receiver.reconnect()
256
257 def server_disconnected(self):
258 self.receiver.disconnect('Lost connection to multilateration server, no need for input data')
259 self.next_report = None
260 self.next_rate_report = None
261 self.next_expiry = None
262
263 def server_mlat_result(self, timestamp, addr, lat, lon, alt, nsvel, ewvel, vrate,
264 callsign, squawk, error_est, nstations, anon, modeac):
265 global_stats.mlat_positions += 1
266
267 if anon and not self.allow_anon:
268 return
269
270 if modeac and not self.allow_modeac:
271 return
272
273 for o in self.outputs:
274 o.send_position(timestamp, addr, lat, lon, alt, nsvel, ewvel, vrate,
275 callsign, squawk, error_est, nstations, anon, modeac)
276
277 def server_start_sending(self, icao_set, modeac_set=set()):
278 for icao in icao_set:
279 ac = self.aircraft.get(icao)
280 if ac:
281 ac.requested = True
282 self.requested_traffic.update(icao_set)
283 if self.allow_modeac:
284 self.requested_modeac.update(modeac_set)
285 self.update_receiver_filter()
286
287 def server_stop_sending(self, icao_set, modeac_set=set()):
288 for icao in icao_set:
289 ac = self.aircraft.get(icao)
290 if ac:
291 ac.requested = False
292 self.requested_traffic.difference_update(icao_set)
293 if self.allow_modeac:
294 self.requested_modeac.difference_update(modeac_set)
295 self.update_receiver_filter()
296
297 def update_receiver_filter(self):
298 now = monotonic_time()
299
300 mlat = set()
301 for icao in self.requested_traffic:
302 ac = self.aircraft.get(icao)
303 if not ac or not ac.adsb_good:
304 # requested, and we have not seen a recent ADS-B message from it
305 mlat.add(icao)
306
307 self.receiver.update_filter(mlat)
308 self.receiver.update_modeac_filter(self.requested_modeac)
309
310 # callbacks from receiver input
311
312 def input_connected(self):
313 self.server.send_input_connected()
314
315 def input_disconnected(self):
316 self.server.send_input_disconnected()
317 # expire everything
318 self.aircraft.clear()
319 self.server.send_lost(self.reported)
320 self.reported.clear()
321
322 @mlat.profile.trackcpu
323 def input_received_messages(self, messages):
324 now = monotonic_time()
325 for message in messages:
326 handler = self.df_handlers.get(message.df)
327 if handler:
328 handler(message, now)
329
330 # handlers for input messages
331
332 def received_mode_change_event(self, message, now):
333 # decoder mode changed, clock parameters possibly changed
334 self.freq = message.eventdata['frequency']
335 self.recent_jumps = 0
336 self.server.send_clock_reset(reason='Decoder mode changed to {mode}'.format(mode=message.eventdata['mode']),
337 frequency=message.eventdata['frequency'],
338 epoch=message.eventdata['epoch'],
339 mode=message.eventdata['mode'])
340 log("Input format changed to {mode}, {freq:.0f}MHz clock",
341 mode=message.eventdata['mode'],
342 freq=message.eventdata['frequency']/1e6)
343
344 def received_epoch_rollover_event(self, message, now):
345 # epoch rollover, reset clock
346 self.server.send_clock_reset('Epoch rollover detected')
347
348 def received_timestamp_jump_event(self, message, now):
349 self.recent_jumps += 1
350 self.server.send_clock_jump()
351 #log("clockjump")
352 if self.recent_jumps % 9 == 8 and time.monotonic() > self.last_jump_message + 300.0 :
353 self.last_jump_message = time.monotonic()
354 log("WARNING: the timestamps provided by your receiver do not seem to be self-consistent. "
355 "This can happen if you feed data from multiple receivers to a single mlat-client, which "
356 "is not supported; use a separate mlat-client for each receiver. "
357 "Or you might have the wrong --input-type set, try radarcape_gps and dump1090.")
358
359 def received_radarcape_position_event(self, message, now):
360 lat, lon = message.eventdata['lat'], message.eventdata['lon']
361 if lat >= -90 and lat <= 90 and lon >= -180 and lon <= -180:
362 self.server.send_position_update(lat, lon,
363 message.eventdata['lon'],
364 message.eventdata['alt'],
365 'egm96_meters')
366
367 def received_df_misc(self, message, now):
368 ac = self.aircraft.get(message.address)
369 if not ac:
370 return False # not a known ICAO
371
372 ac.messages += 1
373 ac.last_message_time = now
374
375 if ac.messages < 10:
376 return # wait for more messages
377 if not ac.requested:
378 return
379
380 # Candidate for MLAT
381 if ac.adsb_good:
382 return # reported position recently, no need for mlat
383 self.server.send_mlat(message)
384
385 def received_df11(self, message, now):
386 ac = self.aircraft.get(message.address)
387 if not ac:
388 ac = Aircraft(message.address)
389 ac.requested = (message.address in self.requested_traffic)
390 ac.messages += 1
391 ac.last_message_time = now
392 ac.rate_measurement_start = now
393 self.aircraft[message.address] = ac
394 return # will need some more messages..
395
396 ac.messages += 1
397 ac.last_message_time = now
398
399 if ac.messages < 10:
400 return # wait for more messages
401 if not ac.requested:
402 return
403
404 # Candidate for MLAT
405 if ac.adsb_good:
406 return # reported position recently, no need for mlat
407 self.server.send_mlat(message)
408
409 def received_df17(self, message, now):
410 ac = self.aircraft.get(message.address)
411 if not ac:
412 ac = Aircraft(message.address)
413 ac.requested = (message.address in self.requested_traffic)
414 ac.messages += 1
415 ac.last_message_time = now
416 ac.rate_measurement_start = now
417 self.aircraft[message.address] = ac
418 return # wait for more messages
419
420 ac.messages += 1
421 ac.last_message_time = now
422 if ac.messages < 10:
423 return
424
425 if not message.even_cpr and not message.odd_cpr:
426 # not a position message
427 return
428
429 if not message.valid:
430 # invalid message
431 return
432
433 if message.even_cpr:
434 ac.even_message = message
435 else:
436 ac.odd_message = message
437
438 if not ac.even_message or not ac.odd_message:
439 return
440 if abs(ac.even_message.timestamp - ac.odd_message.timestamp) > 5 * self.freq:
441 return
442
443 if message.altitude is None:
444 return # need an altitude
445
446 if message.nuc < 6:
447 return # need NUCp >= 6
448
449 ac.recent_adsb_positions += 1
450
451 if message.even_cpr:
452 ac.last_even_time = now
453 else:
454 ac.last_odd_time = now
455
456 if now - ac.last_even_time < self.position_expiry_age and now - ac.last_odd_time < self.position_expiry_age:
457 ac.adsb_good = True
458 else:
459 ac.adsb_good = False
460
461 if not ac.requested:
462 return
463
464 if self.server.send_split_sync:
465 # this is a useful reference message
466 self.server.send_split_sync(message)
467 else:
468 # this is a useful reference message pair
469 self.server.send_sync(ac.even_message, ac.odd_message)
470
471 def received_modeac(self, message, now):
472 if message.address not in self.requested_modeac:
473 return
474
475 self.server.send_mlat(message)