Debian Codegraph @

modes_reader.c

raw symbols SCIP
1 /*
2 * Part of mlat-client - an ADS-B multilateration client.
3 * Copyright 2015, Oliver Jowett <[email protected]>
4 *
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation, either version 3 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * along with this program. If not, see <http://www.gnu.org/licenses/>.
17 */
18
19 #include "_modes.h"
20 #include <stdlib.h>
21 #include <sys/time.h>
22
23 static unsigned long long monotic_ms(void) {
24 struct timespec ts;
25 unsigned long long mst;
26
27 clock_gettime(CLOCK_MONOTONIC, &ts);
28 mst = ((unsigned long long) ts.tv_sec) * 1000;
29 mst += ts.tv_nsec / (1000 * 1000);
30 return mst;
31 }
32
33
34 /* decoder modes */
35 typedef enum {
36 DECODER_NONE, /* Not configured */
37 DECODER_BEAST, /* Beast binary, freerunning 48-bit timestamp @ 12MHz */
38 DECODER_RADARCAPE, /* Beast binary, 1GHz Radarcape timestamp, UTC synchronized from GPS */
39 DECODER_RADARCAPE_EMULATED, /* Beast binary, 1GHz Radarcape timestamp, not synchronized */
40 DECODER_AVR, /* AVR, no timestamp */
41 DECODER_AVRMLAT, /* AVR, freerunning 48-bit timestamp @ 12MHz */
42 DECODER_SBS, /* Kinetic SBS, freerunning 20MHz 24-bit timestamp, wraps around all the time but we try to widen it */
43 } decoder_mode;
44
45 /* A timestamp that indicates the data is synthetic, created from a
46 * multilateration result. (FF 00 "MLAT")
47 */
48 #define MAGIC_MLAT_TIMESTAMP 0xFF004D4C4154ULL
49 #define MAGIC_UAT_TIMESTAMP 0xFF004D4C4155ULL
50 #define OUTLIER_LIMIT 1
51
52 /* a modesreader object */
53 typedef struct {
54 PyObject_HEAD
55
56 /* decoder characteristics */
57 decoder_mode decoder_mode;
58 const char *decoder_mode_string;
59 unsigned long long frequency;
60 const char *epoch;
61
62 unsigned long long last_timestamp; /* last seen timestamp */
63 unsigned long long last_ts_mono; /* system time associated with last timestamp */
64 unsigned long long monotonic; /* current monotonic time */
65 unsigned int radarcape_utc_bugfix;
66
67 /* count timestamp outliers, first one is ignored / message discarded / last_timestamp not updated */
68 /* two consecutive outliers will result in sending a clock_reset message to the mlat-server (all sync dropped) */
69 /* a non outlier message will outliers to zero */
70 unsigned int outliers;
71 unsigned long long outlierNoSpam;
72 unsigned int outlier_accumulator;
73 int try_toggle_freq;
74
75 /* configurable bits */
76 char allow_mode_change;
77 char want_zero_timestamps;
78 char want_mlat_messages;
79 char want_invalid_messages;
80 char want_events;
81
82 /* filtering */
83 PyObject *seen;
84 PyObject *default_filter;
85 PyObject *specific_filter;
86 PyObject *modeac_filter;
87
88 /* stats */
89 unsigned int received_messages;
90 unsigned int suppressed_messages;
91 unsigned int mlat_messages;
92 } modesreader;
93
94 /* methods for the modesreader type */
95 static PyObject *modesreader_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
96 static int modesreader_init(modesreader *self, PyObject *args, PyObject *kwds);
97 static void modesreader_dealloc(modesreader *self);
98 static int modesreader_setmode(modesreader *self, PyObject *mode, void *dummy);
99 static PyObject *modesreader_getmode(modesreader *self, void *dummy);
100 static PyObject *modesreader_feed(modesreader *self, PyObject *args, PyObject *kwds);
101
102 /* modesreader fields */
103 static PyMemberDef modesreaderMembers[] = {
104 /* these two are derived from the current mode always */
105 { "frequency", T_ULONGLONG, offsetof(modesreader, frequency), READONLY, "timestamp frequency" },
106 { "epoch", T_STRING, offsetof(modesreader, epoch), READONLY, "timestamp epoch" },
107
108 { "last_timestamp", T_ULONGLONG, offsetof(modesreader, last_timestamp), 0, "last timestamp seen" },
109 { "allow_mode_change", T_BOOL, offsetof(modesreader, allow_mode_change), 0, "can the decoder change mode based on status messages it receives?" },
110 { "want_zero_timestamps", T_BOOL, offsetof(modesreader, want_zero_timestamps), 0, "should the decoder return messages with zero timestamps?" },
111 { "want_mlat_messages", T_BOOL, offsetof(modesreader, want_mlat_messages), 0, "should the decoder return synthetic mlat messages?" },
112 { "want_invalid_messages", T_BOOL, offsetof(modesreader, want_invalid_messages), 0, "should the decoder return invalid messages?" },
113 { "want_events", T_BOOL, offsetof(modesreader, want_events), 0, "should the decoder return metadata events?" },
114 { "seen", T_OBJECT, offsetof(modesreader, seen), 0, "set of addresses seen by the decoder" },
115 { "default_filter", T_OBJECT, offsetof(modesreader, default_filter), 0, "DF accept filter for all aircraft"},
116 { "specific_filter", T_OBJECT, offsetof(modesreader, specific_filter), 0, "DF accept filter for specific aircraft"},
117 { "modeac_filter", T_OBJECT, offsetof(modesreader, modeac_filter), 0, "Mode A/C accept filter"},
118 { "received_messages", T_UINT, offsetof(modesreader, received_messages), 0, "total number of messages decoded"},
119 { "suppressed_messages", T_UINT, offsetof(modesreader, suppressed_messages), 0, "number of messages suppressed by filtering"},
120 { "mlat_messages", T_UINT, offsetof(modesreader, mlat_messages), 0, "number of incoming MLAT messages received (and ignored)"},
121 { NULL, 0, 0, 0, NULL }
122 };
123
124 /* .. and the mode field which has a special getter/setter */
125 static PyGetSetDef modesreaderGetSet[] = {
126 { "mode", (getter)modesreader_getmode, (setter)modesreader_setmode, "decoder mode", NULL },
127 { NULL, NULL, NULL, NULL, NULL }
128 };
129
130 /* modesreader methods */
131 static PyMethodDef modesreaderMethods[] = {
132 { "feed", (PyCFunction)modesreader_feed, METH_VARARGS|METH_KEYWORDS, "Process and decode some data." },
133 { NULL, NULL, 0, NULL }
134 };
135
136 /* modesreader type definition */
137 static PyTypeObject modesreaderType = {
138 PyVarObject_HEAD_INIT(NULL, 0)
139 "_modes.Reader", /* tp_name */
140 sizeof(modesreader), /* tp_basicsize */
141 0, /* tp_itemsize */
142 (destructor)modesreader_dealloc, /* tp_dealloc */
143 0, /* tp_print */
144 0, /* tp_getattr */
145 0, /* tp_setattr */
146 0, /* tp_reserved */
147 0, /* tp_repr */
148 0, /* tp_as_number */
149 0, /* tp_as_sequence */
150 0, /* tp_as_mapping */
151 0, /* tp_hash */
152 0, /* tp_call */
153 0, /* tp_str */
154 PyObject_GenericGetAttr, /* tp_getattro */
155 PyObject_GenericSetAttr, /* tp_setattro */
156 0, /* tp_as_buffer */
157 Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE, /* tp_flags */
158 "A ModeS stream reader.", /* tp_doc */
159 0, /* tp_traverse */
160 0, /* tp_clear */
161 0, /* tp_richcompare */
162 0, /* tp_weaklistoffset */
163 0, /* tp_iter */
164 0, /* tp_iternext */
165 modesreaderMethods, /* tp_methods */
166 modesreaderMembers, /* tp_members */
167 modesreaderGetSet, /* tp_getset */
168 0, /* tp_base */
169 0, /* tp_dict */
170 0, /* tp_descr_get */
171 0, /* tp_descr_set */
172 0, /* tp_dictoffset */
173 (initproc)modesreader_init, /* tp_init */
174 0, /* tp_alloc */
175 modesreader_new, /* tp_new */
176 };
177
178 /* lookup table for decoder_mode <-> python strings */
179 static struct {
180 decoder_mode mode;
181 const char *cstr;
182 PyObject *pystr;
183 } modetable[] = {
184 { DECODER_BEAST, "BEAST", NULL },
185 { DECODER_RADARCAPE, "RADARCAPE", NULL },
186 { DECODER_RADARCAPE_EMULATED, "RADARCAPE_EMULATED", NULL },
187 { DECODER_AVR, "AVR", NULL },
188 { DECODER_AVRMLAT, "AVRMLAT", NULL },
189 { DECODER_SBS, "SBS", NULL },
190 { DECODER_NONE, NULL, NULL }
191 };
192
193 /* internal helpers */
194 static PyObject *feed_beast(modesreader *self, Py_buffer *buf, int max_messages);
195 static PyObject *feed_avr(modesreader *self, Py_buffer *buf, int max_messages);
196 static PyObject *feed_sbs(modesreader *self, Py_buffer *buf, int max_messages);
197 static void set_decoder_mode(modesreader *self, decoder_mode newmode);
198 static PyObject *radarcape_settings_to_list(uint8_t settings);
199 static PyObject *radarcape_status_to_dict(uint8_t *message);
200 static int filter_message(modesreader *self, PyObject *message);
201
202 /*
203 * module setup/teardown
204 */
205 int modesreader_module_init(PyObject *m)
206 {
207 int i;
208
209 if (PyType_Ready(&modesreaderType) < 0)
210 goto error;
211
212 for (i = 0; modetable[i].cstr != NULL; ++i) {
213 PyObject *pystr = PyUnicode_FromString(modetable[i].cstr);
214 if (pystr == NULL) {
215 goto error;
216 }
217
218 Py_INCREF(pystr);
219 modetable[i].pystr = pystr;
220 if (PyModule_AddObject(m, modetable[i].cstr, pystr) < 0)
221 goto error;
222 }
223
224 Py_INCREF(&modesreaderType);
225 if (PyModule_AddObject(m, "Reader", (PyObject *)&modesreaderType) < 0) {
226 Py_DECREF(&modesreaderType);
227 goto error;
228 }
229
230 return 0;
231
232 error:
233 for (i = 0; modetable[i].cstr != NULL; ++i) {
234 Py_CLEAR(modetable[i].pystr);
235 }
236 return -1;
237 }
238
239 void modesreader_module_free(PyObject *m)
240 {
241 int i;
242
243 for (i = 0; modetable[i].cstr != NULL; ++i) {
244 Py_CLEAR(modetable[i].pystr);
245 }
246 }
247
248 static PyObject *modesreader_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
249 {
250 modesreader *self;
251
252 self = (modesreader *)type->tp_alloc(type, 0);
253 if (self == NULL)
254 return NULL;
255
256 /* minimal init */
257 set_decoder_mode(self, DECODER_NONE);
258 self->last_timestamp = 0;
259 self->last_ts_mono = 0;
260 self->monotonic = 0;
261 self->outliers = 0;
262 self->allow_mode_change = 1;
263 self->want_zero_timestamps = 0;
264 self->want_mlat_messages = 0;
265 self->want_invalid_messages = 0;
266 self->want_events = 1;
267
268 Py_INCREF(Py_None); self->seen = Py_None;
269 Py_INCREF(Py_None); self->default_filter = Py_None;
270 Py_INCREF(Py_None); self->specific_filter = Py_None;
271 Py_INCREF(Py_None); self->modeac_filter = Py_None;
272
273 self->received_messages = self->suppressed_messages = self->mlat_messages = 0;
274
275 return (PyObject *)self;
276 }
277
278 static void modesreader_dealloc(modesreader *self)
279 {
280 Py_CLEAR(self->seen);
281 Py_CLEAR(self->default_filter);
282 Py_CLEAR(self->specific_filter);
283 Py_CLEAR(self->modeac_filter);
284
285 Py_TYPE(self)->tp_free((PyObject*)self);
286 }
287
288 static int modesreader_init(modesreader *self, PyObject *args, PyObject *kwds)
289 {
290 static char *kwlist[] = { "mode", NULL };
291 PyObject *mode = Py_None;
292
293 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O", kwlist, &mode))
294 return -1;
295
296 if (modesreader_setmode(self, mode, NULL) < 0)
297 return -1;
298
299 return 0;
300 }
301
302 static int modesreader_setmode(modesreader *self, PyObject *mode, void *dummy)
303 {
304 int i;
305
306 if (mode == Py_None) {
307 set_decoder_mode(self, DECODER_NONE);
308 return 0;
309 }
310
311 for (i = 0; modetable[i].cstr != NULL; ++i) {
312 int res = PyObject_RichCompareBool(modetable[i].pystr, mode, Py_EQ);
313 if (res < 0)
314 return -1;
315
316 if (res == 1) {
317 set_decoder_mode(self, modetable[i].mode);
318 break;
319 }
320 }
321
322 if (modetable[i].cstr == NULL) {
323 PyErr_SetString(PyExc_ValueError, "unrecognized decoder mode");
324 return -1;
325 }
326
327 return 0;
328 }
329
330 static PyObject *modesreader_getmode(modesreader *self, void *dummy)
331 {
332 int i;
333
334 for (i = 0; modetable[i].cstr; ++i) {
335 if (self->decoder_mode == modetable[i].mode) {
336 Py_INCREF(modetable[i].pystr);
337 return modetable[i].pystr;
338 }
339 }
340
341 Py_INCREF(Py_None);
342 return Py_None;
343 }
344
345 /* feed some data to the reader and does one of:
346 * 1) returns a tuple (bytes_consumed, messages, error_pending), or
347 * 2) throws an exception
348 *
349 * If a stream error is seen, but some messages were parsed OK,
350 * then an exception is not immediately thrown and the parsed
351 * messages are returned with error_pending = True. The caller
352 * should call feed again (after consuming the given number of
353 * bytes) to get the exception.
354 *
355 * Internal errors (e.g. out of memory) are thrown immediately.
356 */
357 static PyObject *modesreader_feed(modesreader *self, PyObject *args, PyObject *kwds)
358 {
359 Py_buffer buffer;
360 PyObject *rv = NULL;
361 int max_messages = 0;
362 static char *kwlist[] = { "buffer", "max_messages", NULL };
363
364 if (!PyArg_ParseTupleAndKeywords(args, kwds, "y*|i", kwlist, &buffer, &max_messages))
365 return NULL;
366
367 if (buffer.itemsize != 1) {
368 PyErr_SetString(PyExc_ValueError, "buffer itemsize is not 1");
369 goto out;
370 }
371
372 if (!PyBuffer_IsContiguous(&buffer, 'C')) {
373 PyErr_SetString(PyExc_ValueError, "buffer is not contiguous");
374 goto out;
375 }
376
377 switch (self->decoder_mode) {
378 case DECODER_NONE:
379 PyErr_SetString(PyExc_NotImplementedError, "decoder mode is None, no decoder type selected");
380 break;
381
382 case DECODER_BEAST:
383 case DECODER_RADARCAPE:
384 case DECODER_RADARCAPE_EMULATED:
385 rv = feed_beast(self, &buffer, max_messages);
386 break;
387
388 case DECODER_AVR:
389 case DECODER_AVRMLAT:
390 rv = feed_avr(self, &buffer, max_messages);
391 break;
392
393 case DECODER_SBS:
394 rv = feed_sbs(self, &buffer, max_messages);
395 break;
396
397 default:
398 PyErr_Format(PyExc_AssertionError, "decoder somehow got into illegal mode %d", (int)self->decoder_mode);
399 break;
400 }
401
402 out:
403 PyBuffer_Release(&buffer);
404 return rv;
405 }
406
407 static void set_decoder_mode(modesreader *self, decoder_mode newmode)
408 {
409 self->decoder_mode = newmode;
410 switch (newmode) {
411 case DECODER_BEAST:
412 self->frequency = 12000000ULL; /* assumed */
413 self->epoch = NULL;
414 break;
415
416 case DECODER_RADARCAPE:
417 self->frequency = 1000000000ULL;
418 self->epoch = "utc_midnight";
419 break;
420
421 case DECODER_RADARCAPE_EMULATED:
422 self->frequency = 1000000000ULL;
423 self->epoch = NULL;
424 break;
425
426 case DECODER_AVRMLAT:
427 self->frequency = 12000000ULL; /* assumed */
428 self->epoch = NULL;
429 break;
430
431 case DECODER_SBS:
432 self->frequency = 20000000ULL;
433 self->epoch = NULL;
434 break;
435
436 case DECODER_AVR:
437 default:
438 self->frequency = 0;
439 self->epoch = NULL;
440 break;
441 }
442 }
443
444 /* turn a radarcape DIP switch setting byte into a Python list of settings strings */
445 static PyObject *radarcape_settings_to_list(uint8_t settings)
446 {
447 return Py_BuildValue("[s,s,s,s,s,s,s]",
448 settings & 0x01 ? "beast" : (settings & 0x04 ? "avrmlat" : "avr"),
449 settings & 0x02 ? "filtered_frames" : "all_frames",
450 settings & 0x08 ? "no_crc" : "check_crc",
451 settings & 0x10 ? "gps_timestamps" : "legacy_timestamps",
452 settings & 0x20 ? "rtscts" : "no_rtscts",
453 settings & 0x40 ? "no_fec" : "fec",
454 settings & 0x80 ? "modeac" : "no_modeac");
455 }
456
457 /* turn a radarcape GPS status byte into a Python dict */
458 static PyObject *radarcape_gpsstatus_to_dict(uint8_t status)
459 {
460 if (!(status & 0x80)) {
461 return Py_BuildValue("{s:O,s:O}",
462 "utc_bugfix", Py_False,
463 "timestamp_ok", Py_True
464 );
465 }
466
467 return Py_BuildValue("{s:O,s:O,s:O,s:O,s:O,s:O,s:O}",
468 "utc_bugfix", Py_True,
469 "timestamp_ok", (status & 0x20 ? Py_False : Py_True),
470 "sync_ok", (status & 0x10 ? Py_True : Py_False),
471 "utc_offset_ok", (status & 0x08 ? Py_True : Py_False),
472 "sats_ok", (status & 0x04 ? Py_True : Py_False),
473 "tracking_ok", (status & 0x02 ? Py_True : Py_False),
474 "antenna_ok", (status & 0x01 ? Py_True : Py_False));
475 }
476
477 /* turn a radarcape 0x34 status message into a Python dict */
478 static PyObject *radarcape_status_to_dict(uint8_t *message)
479 {
480 return Py_BuildValue("{s:N,s:i,s:N}",
481 "settings", radarcape_settings_to_list(message[0]),
482 "timestamp_pps_delta", (int)(int8_t)message[1],
483 "gps_status", radarcape_gpsstatus_to_dict(message[2]));
484 }
485
486 /* create an event message for a timestamp jump */
487 static PyObject *make_timestamp_jump_event(modesreader *self, unsigned long long timestamp)
488 {
489 PyObject *eventdata = Py_BuildValue("{s:K}",
490 "last-timestamp", self->last_timestamp);
491 if (eventdata == NULL)
492 return NULL;
493
494 return modesmessage_new_eventmessage(DF_EVENT_TIMESTAMP_JUMP, timestamp, eventdata);
495 }
496
497 /* create an event message for a decoder mode change. the new mode should already be set. */
498 static PyObject *make_mode_change_event(modesreader *self)
499 {
500 PyObject *eventdata = Py_BuildValue("{s:N,s:K,s:s}",
501 "mode", modesreader_getmode(self, NULL),
502 "frequency", self->frequency,
503 "epoch", self->epoch);
504 if (eventdata == NULL)
505 return NULL;
506
507 return modesmessage_new_eventmessage(DF_EVENT_MODE_CHANGE, 0, eventdata);
508 }
509
510 /* create an event message for an epoch rollover (e.g. GPS end of day) */
511 static PyObject *make_epoch_rollover_event(modesreader *self, unsigned long long timestamp)
512 {
513 PyObject *eventdata = PyDict_New();
514 if (eventdata == NULL)
515 return NULL;
516
517 return modesmessage_new_eventmessage(DF_EVENT_EPOCH_ROLLOVER, timestamp, eventdata);
518 }
519
520 /* create an event message for a radarcape status report */
521 static PyObject *make_radarcape_status_event(modesreader *self, unsigned long long timestamp, uint8_t *data)
522 {
523 PyObject *eventdata = radarcape_status_to_dict(data);
524 if (eventdata == NULL)
525 return NULL;
526
527 return modesmessage_new_eventmessage(DF_EVENT_RADARCAPE_STATUS, timestamp, eventdata);
528 }
529
530 /* create an event message for a radarcape position report */
531 static PyObject *radarcape_position_to_dict(uint8_t *data)
532 {
533 float lat, lon, alt;
534
535 #if PY_MAJOR_VERSION >= 3 && PY_MINOR_VERSION >=11
536 lat = PyFloat_Unpack4(data + 4, 1);
537 if (lat == -1.0 && PyErr_Occurred())
538 return NULL;
539
540 lon = PyFloat_Unpack4(data + 8, 1);
541 if (lon == -1.0 && PyErr_Occurred())
542 return NULL;
543
544 alt = PyFloat_Unpack4(data + 12, 1);
545 if (alt == -1.0 && PyErr_Occurred())
546 return NULL;
547 #else
548 lat = _PyFloat_Unpack4(data + 4, 1);
549 if (lat == -1.0 && PyErr_Occurred())
550 return NULL;
551
552 lon = _PyFloat_Unpack4(data + 8, 1);
553 if (lon == -1.0 && PyErr_Occurred())
554 return NULL;
555
556 alt = _PyFloat_Unpack4(data + 12, 1);
557 if (alt == -1.0 && PyErr_Occurred())
558 return NULL;
559 #endif
560
561 return Py_BuildValue("{s:f,s:f,s:f}",
562 "lat", lat,
563 "lon", lon,
564 "alt", alt);
565 }
566
567 static PyObject *make_radarcape_position_event(modesreader *self, uint8_t *data)
568 {
569 PyObject *eventdata = radarcape_position_to_dict(data);
570 if (eventdata == NULL)
571 return NULL;
572
573 return modesmessage_new_eventmessage(DF_EVENT_RADARCAPE_POSITION, 0, eventdata);
574 }
575
576 static int is_synthetic_timestamp(unsigned long long timestamp)
577 {
578 return (timestamp == 0 || (timestamp >= MAGIC_MLAT_TIMESTAMP && timestamp <= MAGIC_MLAT_TIMESTAMP + 10));
579 }
580
581 /* check if the given timestamp is in range (not a jump), return 1 if it is */
582 static int timestamp_check(modesreader *self, unsigned long long timestamp)
583 {
584 if (is_synthetic_timestamp(timestamp))
585 return 1;
586
587 if (self->frequency == 0)
588 return 1;
589
590 self->monotonic = monotic_ms(); // update system time
591
592 if (self->last_timestamp == 0)
593 return 1;
594
595
596 long long ts_elapsed = (long long) timestamp - (long long) self->last_timestamp;
597 long long sys_elapsed = (self->monotonic - self->last_ts_mono) * (self->frequency / 1000);
598 long long max_offset = 1.25 * self->frequency; // 1.25 seconds
599
600 if (ts_elapsed > sys_elapsed + max_offset || ts_elapsed < sys_elapsed - max_offset) {
601 self->outliers++;
602 if (self->outliers > OUTLIER_LIMIT) {
603 if (self->monotonic > self->outlierNoSpam) {
604 double tosec = 1.0 / self->frequency;
605 fprintf(stderr, "outlier detected with ts: %.3f, last_ts: %.3f, ts_elapsed: %.3f, sys_elapsed: %.3f (values in seconds)\n", timestamp * tosec, self->last_timestamp * tosec, ts_elapsed * tosec, sys_elapsed * tosec);
606
607 self->outlier_accumulator = 0;
608 self->outlierNoSpam = self->monotonic + 5000;
609 } else {
610 self->outlier_accumulator++;
611 if (self->outlier_accumulator > 100) {
612 // try switching to another input type
613
614 // disable frequency toggling ... bad idea
615 //self->try_toggle_freq++;
616
617 self->outlier_accumulator = 0;
618 }
619 }
620 }
621 return 0;
622 }
623 self->outliers = 0;
624
625 return 1;
626 }
627
628 /* update self->last_timestamp given that we just saw this timestamp */
629 static void timestamp_update(modesreader *self, unsigned long long timestamp)
630 {
631 if (is_synthetic_timestamp(timestamp)) {
632 /* special timestamps, don't use them */
633 return;
634 }
635
636 if (self->last_timestamp == 0 || self->frequency == 0) {
637 /* startup cases, just accept whatever */
638 self->last_ts_mono = self->monotonic;
639 self->last_timestamp = timestamp;
640 return;
641 }
642
643 if (self->last_timestamp > timestamp && (self->last_timestamp - timestamp) < 90 * self->frequency) {
644 /* ignore small moves backwards */
645 return;
646 }
647
648 if ((self->decoder_mode == DECODER_RADARCAPE || self->decoder_mode == DECODER_RADARCAPE_EMULATED) &&
649 timestamp >= (86340 * 1000000000ULL) && self->last_timestamp <= (60 * 1000000000ULL)) {
650 /* in radarcape mode, don't allow last_timestamp to roll back to the previous day
651 * as we will have already issued an epoch reset
652 */
653 return;
654 }
655
656 // don't update the timestamp for outliers until we exceed OUTLIER_LIMIT
657 if (self->outliers && self->outliers <= OUTLIER_LIMIT)
658 return;
659
660 self->last_timestamp = timestamp;
661 self->last_ts_mono = self->monotonic;
662 }
663
664 /* feed implementation for Beast-format data (including Radarcape) */
665 static PyObject *feed_beast(modesreader *self, Py_buffer *buffer, int max_messages)
666 {
667 PyObject *rv = NULL;
668 uint8_t *buffer_start, *p, *eod;
669 int message_count = 0;
670 PyObject *message_tuple = NULL;
671 PyObject **messages = NULL;
672 int error_pending = 0;
673
674 buffer_start = buffer->buf;
675
676 if (max_messages <= 0) {
677 /* allocate the maximum size we might need, given a minimal encoding of:
678 * <1A> <'1'> <6 bytes timestamp> <1 byte signal> <2 bytes message> = 11 bytes total
679 */
680 max_messages = buffer->len / 11 + 2;
681 }
682
683 messages = calloc(max_messages, sizeof(PyObject*));
684 if (!messages) {
685 PyErr_NoMemory();
686 goto out;
687 }
688
689 /* parse messages */
690 p = buffer_start;
691 eod = buffer_start + buffer->len;
692 while (p+2 <= eod && message_count+2 < max_messages) {
693 int message_len = -1;
694 uint64_t timestamp;
695 uint8_t signal;
696 uint8_t data[14];
697 uint8_t *m, *eom;
698 int i;
699 uint8_t type;
700 PyObject *message;
701 int wanted;
702 int has_timestamp_signal;
703
704 if (p[0] != 0x1a) {
705 error_pending = 1;
706 if (message_count > 0)
707 goto nomoredata;
708 PyErr_Format(PyExc_ValueError, "Lost sync with input stream: expected a 0x1A marker at offset %d but found 0x%02x instead", (int) (p - buffer_start), (int)p[0]);
709 goto out;
710 }
711
712 has_timestamp_signal = 1;
713 type = p[1];
714 switch (type) {
715 case '1': message_len = 2; break; /* mode A/C */
716 case '2': message_len = 7; break; /* mode S short */
717 case '3': message_len = 14; break; /* mode S long */
718 case '4': message_len = 14; break; /* radarcape status message */
719 case '5':
720 /* radarcape position message, no timestamp/signal bytes */
721 message_len = 21;
722 has_timestamp_signal = 0;
723 break;
724 default:
725 error_pending = 1;
726 if (message_count > 0)
727 goto nomoredata;
728 PyErr_Format(PyExc_ValueError, "Lost sync with input stream: unexpected message type 0x%02x after 0x1A marker at offset %d", (int)p[1], (int) (p - buffer_start));
729 goto out;
730 }
731
732 m = p + 2;
733 eom = m + message_len + (has_timestamp_signal ? 7 : 0);
734 if (eom > eod)
735 break;
736
737 #define ADVANCE \
738 do { \
739 if (*m++ == 0x1a) { \
740 if (m < eod && *m != 0x1a) { \
741 error_pending = 1; \
742 if (message_count > 0) \
743 goto nomoredata; \
744 PyErr_SetString(PyExc_ValueError, "Lost sync with input stream: expected 0x1A after 0x1A escape"); \
745 goto out; \
746 } \
747 ++m, ++eom; \
748 if (eom > eod) \
749 goto nomoredata; \
750 } \
751 } while(0)
752
753 if (has_timestamp_signal) {
754 /* timestamp, 6 bytes */
755 timestamp = *m;
756 ADVANCE;
757 timestamp = (timestamp << 8) | *m;
758 ADVANCE;
759 timestamp = (timestamp << 8) | *m;
760 ADVANCE;
761 timestamp = (timestamp << 8) | *m;
762 ADVANCE;
763 timestamp = (timestamp << 8) | *m;
764 ADVANCE;
765 timestamp = (timestamp << 8) | *m;
766 ADVANCE;
767
768 /* signal, 1 byte */
769 signal = *m;
770 ADVANCE;
771 } else {
772 timestamp = 0;
773 signal = 0;
774 }
775
776 /* message, N bytes */
777 for (i = 0; i < message_len; ++i) {
778 data[i] = *m;
779 ADVANCE;
780 }
781
782 /* do some filtering */
783
784 if (type == '4') {
785 /* radarcape-style status message, use this to switch our decoder type */
786
787 self->radarcape_utc_bugfix = (data[2] & 0x80) == 0x80;
788
789 if (self->allow_mode_change) {
790 decoder_mode newmode;
791 if (data[0] & 0x10) {
792 /* radarcape in GPS timestamp mode */
793 if ((data[2] & 0x20) == 0x20) {
794 newmode = DECODER_RADARCAPE_EMULATED;
795 } else {
796 newmode = DECODER_RADARCAPE;
797 }
798 } else {
799 /* radarcape in 12MHz timestamp mode */
800 newmode = DECODER_BEAST;
801 }
802
803 /* handle mode changes by inserting an event message */
804 if (newmode != self->decoder_mode) {
805 set_decoder_mode(self, newmode);
806 if (self->want_events) {
807 if (! (messages[message_count++] = make_mode_change_event(self)))
808 goto out;
809 }
810 }
811 }
812 }
813
814 // hacky: toggle mode if self->try_toggle_freq was set in a function
815 if (self->try_toggle_freq > 0) {
816 self->try_toggle_freq = -5;
817
818 decoder_mode newmode = DECODER_NONE;
819
820 if (self->decoder_mode == DECODER_BEAST) {
821 newmode = DECODER_RADARCAPE;
822 }
823 if (self->decoder_mode == DECODER_RADARCAPE) {
824 newmode = DECODER_BEAST;
825 }
826
827 if (newmode != DECODER_NONE) {
828 set_decoder_mode(self, newmode);
829 if (self->want_events) {
830 if (! (messages[message_count++] = make_mode_change_event(self)))
831 goto out;
832 }
833 }
834 }
835
836 // ignore ModeAC messages
837 if (type == '1') {
838 /* don't try to process this as a Mode S message */
839 p = m;
840 continue;
841 }
842
843 if (has_timestamp_signal && !is_synthetic_timestamp(timestamp)) {
844 if (self->decoder_mode == DECODER_BEAST) {
845 /* 12MHz mode */
846
847 /* check for very out of range value
848 * (dump1090 can hold messages for up to 60 seconds! so be conservative here)
849 * also work around dump1090-mutability issue #47 which can send very stale Mode A/C messages
850 */
851 if (self->want_events && type != '1' && !timestamp_check(self, timestamp)) {
852 if (self->outliers > OUTLIER_LIMIT &&
853 ! (messages[message_count++] = make_timestamp_jump_event(self, timestamp)))
854 goto out;
855 }
856
857 /* adjust the timestamps so they always reflect the start of the frame */
858 uint64_t adjust;
859 if (type == '1') {
860 // Mode A/C, timestamp reported at F2 which is 20.3us after F1
861 // this is 243.6 cycles at 12MHz
862 adjust = 244;
863 } else if (type == '2') {
864 // Mode S short, timestamp reported at end of frame, frame is 8us preamble plus 56us data
865 // this is 768 cycles at 12MHz
866 adjust = 768;
867 } else if (type == '3') {
868 // Mode S long, timestamp reported halfway through the frame (at bit 56), same offset as Mode S short
869 adjust = 768;
870 } else {
871 // anything else we assume is already correct
872 adjust = 0;
873 }
874
875 if (timestamp < adjust) {
876 timestamp = 0;
877 } else {
878 timestamp = timestamp - adjust;
879 }
880 } else {
881 /* gps mode */
882
883 /* adjust timestamp so that it is a contiguous nanoseconds-since-
884 * midnight value, rather than the raw form which skips values once
885 * a second
886 */
887 uint64_t nanos = timestamp & 0x00003FFFFFFF;
888 uint64_t secs = timestamp >> 30;
889
890 if (!self->radarcape_utc_bugfix) {
891 /* fix up the timestamp so it is UTC, not 1 second ahead */
892 if (secs == 0) {
893 secs = 86399;
894 } else {
895 --secs;
896 }
897 }
898
899 timestamp = nanos + secs * 1000000000;
900
901 /* adjust the timestamps so they always reflect the start of the frame */
902 uint64_t adjust;
903 if (type == '1') {
904 // Mode A/C, timestamp reported at F2 which is 20.3us after F1
905 adjust = 20300;
906 } else if (type == '2') {
907 // Mode S short, timestamp reported at end of frame, frame is 8us preamble plus 56us data
908 adjust = 64000;
909 } else if (type == '3') {
910 // Mode S long, timestamp reported at end of frame, frame is 8us preamble plus 112us data
911 adjust = 120000;
912 } else {
913 // anything else we assume is already correct
914 adjust = 0;
915 }
916
917 if (adjust <= timestamp) {
918 timestamp = timestamp - adjust;
919 } else {
920 /* wrap it to the previous day */
921 timestamp = timestamp + 86400 * 1000000000ULL - adjust;
922 }
923
924 /* check for end of day rollover */
925 if (self->want_events && self->last_timestamp >= (86340 * 1000000000ULL) && timestamp <= (60 * 1000000000ULL)) {
926 if (! (messages[message_count++] = make_epoch_rollover_event(self, timestamp)))
927 goto out;
928 } else if (self->want_events && type != '1' && !timestamp_check(self, timestamp)) {
929 if (! (messages[message_count++] = make_timestamp_jump_event(self, timestamp)))
930 goto out;
931 }
932 }
933
934 if (type != '1') {
935 timestamp_update(self, timestamp);
936 }
937 }
938
939 if (type == '4') {
940 /* radarcape-style status message, emit the status event if wanted */
941 if (self->want_events) {
942 if (! (messages[message_count++] = make_radarcape_status_event(self, timestamp, data)))
943 goto out;
944 }
945
946 /* don't try to process this as a Mode S message */
947 p = m;
948 continue;
949 }
950
951 if (type == '5') {
952 /* radarcape-style position message, emit the position event if wanted */
953
954 if (self->want_events) {
955 if (! (messages[message_count++] = make_radarcape_position_event(self, data)))
956 goto out;
957 }
958
959 /* don't try to process this as a Mode S message */
960 p = m;
961 continue;
962 }
963
964 /* it's a Mode A/C or Mode S message, parse it */
965 if (! (message = modesmessage_from_buffer(timestamp, signal, data, message_len)))
966 goto out;
967
968 /* apply filters, update seen-set */
969 ++self->received_messages;
970 wanted = filter_message(self, message);
971 if (wanted < 0)
972 goto out;
973 else if (wanted)
974 messages[message_count++] = message;
975 else {
976 ++self->suppressed_messages;
977 Py_DECREF(message);
978 }
979
980 p = m;
981 }
982
983 nomoredata:
984 if (! (message_tuple = PyTuple_New(message_count)))
985 goto out;
986
987 while (--message_count >= 0) {
988 PyTuple_SET_ITEM(message_tuple, message_count, messages[message_count]); /* steals ref */
989 }
990
991 rv = Py_BuildValue("(l,N,N)", (long) (p - buffer_start), message_tuple, PyBool_FromLong(error_pending));
992
993 out:
994 while (--message_count >= 0) {
995 Py_XDECREF(messages[message_count]);
996 }
997 free(messages);
998 return rv;
999 }
1000
1001 /********** SBS INPUT **************/
1002
1003 /*
1004 * Some notes on this format, as it is poorly documented by Kinetic:
1005 *
1006 * The stream can start at an arbitrary point, the first byte might be mid-packet.
1007 * You need to look for a DLE STX to synchronize with the stream.
1008 * This implementation does that in the Python code to keep this bit simpler; the
1009 * C code assumes it is always given bytes starting at the start of a packet.
1010 *
1011 * You might get arbitrary packet types e.g. AIS interleaved with Mode S messages.
1012 * This implementation doesn't try to interpret them at all, it just reads all
1013 * data until DLE ETX regardless of type and skips those types it doesn't
1014 * understand.
1015 *
1016 * The Mode S CRC values are not the raw bytes from the message; they are the
1017 * residual CRC value after XORing the raw bytes with the calculated CRC over
1018 * the body of the message. That is, a DF17 message with a correct CRC will have
1019 * zeros in the CRC bytes; a DF11 with correct CRC will have the IID in the CRC
1020 * bytes; messages that use Address/Parity will have the address in the CRC bytes.
1021 * To recover the original message, calculate the CRC and XOR it back into the CRC
1022 * bytes. Andrew Whewell says this is probably controlled by a Basestation setting.
1023 *
1024 * The timestamps are measured at the _end_ of the frame, not at the start.
1025 * As frames are variable length, if you want a timestamp anchored to the
1026 * start of the frame (as dump1090 / Beast do), you have to compensate for
1027 * the frame length.
1028 */
1029 static PyObject *feed_sbs(modesreader *self, Py_buffer *buffer, int max_messages)
1030 {
1031 PyObject *rv = NULL;
1032 uint8_t *buffer_start, *p, *eod;
1033 int message_count = 0;
1034 PyObject *message_tuple = NULL;
1035 PyObject **messages = NULL;
1036 int error_pending = 0;
1037
1038 buffer_start = buffer->buf;
1039
1040 if (max_messages <= 0) {
1041 /* allocate the maximum size we might need, given a minimal encoding of:
1042 * <DLE> <STX> <0x09> <n/a> <3 bytes timestamp> <2 bytes message> <DLE> <ETX> <2 bytes CRC> = 13 bytes total
1043 */
1044 max_messages = buffer->len / 13 + 1;
1045 }
1046
1047 messages = calloc(max_messages, sizeof(PyObject*));
1048 if (!messages) {
1049 PyErr_NoMemory();
1050 goto out;
1051 }
1052
1053 /* parse messages */
1054 p = buffer_start;
1055 eod = buffer_start + buffer->len;
1056 while (p+13 <= eod && message_count < max_messages) {
1057 int message_len = -1;
1058 uint64_t timestamp;
1059 /* largest message we care about is:
1060 * type 1 byte 0x05 = ADS-B
1061 * spare 1 byte
1062 * timestamp 3 bytes
1063 * data 14 bytes
1064 * total 19 bytes
1065 */
1066 uint8_t data[19];
1067 uint8_t *m;
1068 int i;
1069 uint8_t type;
1070 uint32_t crc;
1071 PyObject *message;
1072
1073 if (p[0] != 0x10 || p[1] != 0x02) {
1074 error_pending = 1;
1075 if (message_count > 0)
1076 goto nomoredata;
1077 PyErr_Format(PyExc_ValueError, "Lost sync with input stream: expected DLE STX at offset %d but found 0x%02x 0x%02x instead", (int) (p - buffer_start), (int)p[0], (int)p[1]);
1078 goto out;
1079 }
1080
1081 /* scan for DLE ETX, copy data */
1082 m = p + 2;
1083 i = 0;
1084 while (m < eod) {
1085 if (*m == 0x10) {
1086 /* DLE <something> */
1087
1088 if ((m+1) >= eod)
1089 goto nomoredata;
1090
1091 if (m[1] == 0x03) {
1092 /* DLE ETX */
1093 break;
1094 }
1095
1096 if (m[1] != 0x10) {
1097 /* DLE <something we don't understand> */
1098 error_pending = 1;
1099 if (message_count > 0)
1100 goto nomoredata;
1101 PyErr_Format(PyExc_ValueError, "Lost sync with input stream: unexpected DLE 0x%02x at offset %d", (int) (m - buffer_start), (int)m[1]);
1102 goto out;
1103 }
1104
1105 /* DLE DLE */
1106 ++m;
1107 }
1108
1109 if (i < 19)
1110 data[i++] = *m;
1111
1112 ++m;
1113 }
1114
1115 /* now pointing at DLE of DLE ETX */
1116 m += 2;
1117
1118 /* first CRC byte */
1119 if (m >= eod)
1120 goto nomoredata;
1121 if (*m++ == 0x10) {
1122 if (m >= eod)
1123 goto nomoredata;
1124 if (m[0] != 0x10) {
1125 error_pending = 1;
1126 if (message_count > 0)
1127 goto nomoredata;
1128 PyErr_Format(PyExc_ValueError, "Lost sync with input stream: unexpected DLE 0x%02x at offset %d", (int) (m - buffer_start), (int)*m);
1129 goto out;
1130 }
1131 ++m;
1132 }
1133
1134 /* second CRC byte */
1135 if (m >= eod)
1136 goto nomoredata;
1137 if (*m++ == 0x10) {
1138 if (m >= eod)
1139 goto nomoredata;
1140 if (m[0] != 0x10) {
1141 error_pending = 1;
1142 if (message_count > 0)
1143 goto nomoredata;
1144 PyErr_Format(PyExc_ValueError, "Lost sync with input stream: unexpected DLE 0x%02x at offset %d", (int) (m - buffer_start), (int)*m);
1145 goto out;
1146 }
1147 ++m;
1148 }
1149
1150 /* try to make sense of the message */
1151 type = data[0];
1152 switch (type) {
1153 case 0x01:
1154 /* ADS-B or TIS-B */
1155 message_len = 14;
1156 break;
1157
1158 case 0x05:
1159 /* Mode S, long */
1160 message_len = 14;
1161 break;
1162
1163 case 0x07:
1164 /* Mode S, short */
1165 message_len = 7;
1166 break;
1167
1168 case 0x09:
1169 /* Mode A/C */
1170 message_len = 2;
1171 break;
1172
1173 default:
1174 /* something else, skip it */
1175 p = m;
1176 continue;
1177 }
1178
1179 if ((5 + message_len) > i) {
1180 /* not enough data */
1181 p = m;
1182 continue;
1183 }
1184
1185 /* regenerate message CRC */
1186 crc = modescrc_buffer_crc(&data[5], message_len - 3);
1187 data[5 + message_len - 3] ^= crc >> 16;
1188 data[5 + message_len - 2] ^= crc >> 8;
1189 data[5 + message_len - 1] ^= crc;
1190
1191 /* little-endian, apparently */
1192 timestamp = (data[4] << 16) | (data[3] << 8) | (data[2]);
1193
1194 /* Baseless speculation! Let's assume that it's like the Radarcape
1195 * and measures at the end of the frame.
1196 *
1197 * It's easier to add to the timestamp than subtract from it, so
1198 * add on enough of an offset so that the timestamps we report are
1199 * consistently (start of frame + 112us) regardless of the actual
1200 * frame length.
1201 */
1202 timestamp = (timestamp + ((14-message_len) * 160)) & 0xFFFFFF;
1203
1204 /* we don't use timestamp_update or timestamp_check here because SBS is "special" */
1205
1206 /* The SBS timestamp is only 24 bits wide; at 20MHz this overflows more than once
1207 * a second (about every 839ms). To get a useful timestamp for mlat synchronization,
1208 * we have to widen the timestamp.
1209 *
1210 * It wasn't reliable to do this based on the system clock, there are enough
1211 * unpredictable delays between the SBS and mlat-client that it didn't work well.
1212 * Instead, we assume that we will be receiving at least one message per 839ms.
1213 * so if we ever see a timestamp that has gone backwards, it must be due to
1214 * exactly one overflow of the timestamp counter.
1215 *
1216 * This is usually true in cases where we see enough traffic for mlat/sync. When it
1217 * isn't true, you will get synchronization jumps that are a multiple of 839ms.
1218 */
1219
1220 /* merge in top bits of the current widened counter */
1221 timestamp = timestamp | (self->last_timestamp & 0xFFFFFFFFFF000000ULL);
1222
1223 /* check for rollover, if it happened then increase the widened part */
1224 if (timestamp < self->last_timestamp)
1225 timestamp += (1 << 24);
1226
1227 self->last_timestamp = timestamp;
1228
1229 /* decode it */
1230 if (! (message = modesmessage_from_buffer(timestamp, 0, &data[5], message_len)))
1231 goto out;
1232
1233 /* apply filters, update seen-set */
1234 ++self->received_messages;
1235 int wanted = filter_message(self, message);
1236 if (wanted < 0)
1237 goto out;
1238 else if (wanted)
1239 messages[message_count++] = message;
1240 else {
1241 ++self->suppressed_messages;
1242 Py_DECREF(message);
1243 }
1244
1245 p = m;
1246 }
1247
1248 nomoredata:
1249 if (! (message_tuple = PyTuple_New(message_count)))
1250 goto out;
1251
1252 while (--message_count >= 0) {
1253 PyTuple_SET_ITEM(message_tuple, message_count, messages[message_count]); /* steals ref */
1254 }
1255
1256 rv = Py_BuildValue("(l,N,N)", (long) (p - buffer_start), message_tuple, PyBool_FromLong(error_pending));
1257
1258 out:
1259 while (--message_count >= 0) {
1260 Py_XDECREF(messages[message_count]);
1261 }
1262 free(messages);
1263 return rv;
1264 }
1265
1266 /********** AVR INPUT **************/
1267
1268 static int hexvalue(char c)
1269 {
1270 if (c >= '0' && c <= '9')
1271 return c - '0';
1272 else if (c >= 'a' && c <= 'f')
1273 return c - 'a' + 10;
1274 else if (c >= 'A' && c <= 'F')
1275 return c - 'A' + 10;
1276 else
1277 return -1;
1278 }
1279
1280 static PyObject *feed_avr(modesreader *self, Py_buffer *buffer, int max_messages)
1281 {
1282 PyObject *rv = NULL;
1283 uint8_t *buffer_start, *p, *eod;
1284 int message_count = 0;
1285 PyObject *message_tuple = NULL;
1286 PyObject **messages = NULL;
1287 int error_pending = 0;
1288
1289 buffer_start = buffer->buf;
1290
1291 if (max_messages <= 0) {
1292 /* allocate the maximum size we might need, given a minimal encoding of:
1293 * '*' <2 bytes message> ';' LF
1294 */
1295 max_messages = buffer->len / 5 + 1;
1296 }
1297
1298 messages = calloc(max_messages, sizeof(PyObject*));
1299 if (!messages) {
1300 PyErr_NoMemory();
1301 goto out;
1302 }
1303
1304 p = buffer_start;
1305 eod = buffer_start + buffer->len;
1306 while (p+17 <= eod && message_count+1 < max_messages) {
1307 int message_len = -1;
1308 uint64_t timestamp;
1309 uint8_t data[14];
1310 uint8_t message_format;
1311 int i;
1312 uint8_t *m;
1313 PyObject *message;
1314
1315 message_format = p[0];
1316 if (message_format != '@' &&
1317 message_format != '%' &&
1318 message_format != '<' &&
1319 message_format != '*' &&
1320 message_format != ':') {
1321 error_pending = 1;
1322 if (message_count > 0)
1323 goto nomoredata;
1324 PyErr_Format(PyExc_ValueError, "Lost sync with input stream: expected '@'/'%%'/'<'/'*'/':' at offset %d but found 0x%02x instead",
1325 (int) (p - buffer_start), (int)p[0]);
1326 goto out;
1327 }
1328
1329 m = p + 1;
1330 if (message_format == '@' ||
1331 message_format == '%' ||
1332 message_format == '<') {
1333 /* read 6 bytes of timestamp */
1334 timestamp = 0;
1335 for (i = 0; i < 12; ++i, ++m) {
1336 int c;
1337
1338 if (m >= eod) {
1339 goto nomoredata;
1340 }
1341
1342 timestamp <<= 4;
1343 c = hexvalue(*m);
1344 if (c >= 0) {
1345 timestamp |= c;
1346 } else {
1347 error_pending = 1;
1348 if (message_count > 0)
1349 goto nomoredata;
1350 PyErr_Format(PyExc_ValueError, "Lost sync with input stream: expected a hex digit at offset %d but found 0x%02x instead",
1351 (int) (m - buffer_start), (int)*m);
1352 goto out;
1353 }
1354 }
1355 } else {
1356 /* AVR format with no timestamp */
1357 timestamp = 0;
1358 }
1359
1360 if (message_format == '<') {
1361 /* in format '<', skip 1 byte of signal */
1362 m += 2;
1363 if (m >= eod)
1364 goto nomoredata;
1365 }
1366
1367 /* read 2-14 bytes of data */
1368 message_len = 0;
1369 while (message_len < 14) {
1370 int c0, c1;
1371
1372 if (m+1 >= eod) {
1373 goto nomoredata;
1374 }
1375
1376 if (m[0] == ';') {
1377 break; /* end of message marker */
1378 } else {
1379 c0 = hexvalue(m[0]);
1380 if (c0 < 0) {
1381 error_pending = 1;
1382 if (message_count > 0)
1383 goto nomoredata;
1384
1385 PyErr_Format(PyExc_ValueError, "Lost sync with input stream: expected a hex digit at offset %d but found 0x%02x instead",
1386 (int) (m - buffer_start), (int)m[0]);
1387 goto out;
1388 }
1389 }
1390
1391 c1 = hexvalue(m[1]);
1392 if (c1 < 0) {
1393 error_pending = 1;
1394 if (message_count > 0)
1395 goto nomoredata;
1396
1397 PyErr_Format(PyExc_ValueError, "Lost sync with input stream: expected a hex digit at offset %d but found 0x%02x instead",
1398 (int) (m - buffer_start), (int)m[1]);
1399 goto out;
1400 }
1401
1402 if (message_len < 14) {
1403 data[message_len] = (c0 << 4) | c1;
1404 }
1405 ++message_len;
1406 m += 2;
1407 }
1408
1409 /* consume ';' */
1410 if (m >= eod)
1411 goto nomoredata;
1412 if (*m != ';') {
1413 error_pending = 1;
1414 if (message_count > 0)
1415 goto nomoredata;
1416
1417 PyErr_Format(PyExc_ValueError, "Lost sync with input stream: expected ';' at offset %d but found 0x%02x instead",
1418 (int) (m - buffer_start), (int)*m);
1419 goto out;
1420 }
1421
1422 /* CR LF, LF CR, LF all seen! ugh. */
1423
1424 /* skip until CR or LF */
1425 while (m < eod && *m != '\r' && *m != '\n')
1426 ++m;
1427
1428 /* consume however many CRs and LFs */
1429 while (m < eod && (*m == '\r' || *m == '\n'))
1430 ++m;
1431
1432 /* check length */
1433 if (message_len != 2 && message_len != 7 && message_len != 14) {
1434 error_pending = 1;
1435 if (message_count > 0)
1436 goto nomoredata;
1437
1438 PyErr_Format(PyExc_ValueError, "Lost sync with input stream: unexpected %d-byte message starting at offset %d",
1439 message_len, (int) (p - buffer_start));
1440 goto out;
1441 }
1442
1443 /* check for very out of range value
1444 * (dump1090 can hold messages for up to 60 seconds! so be conservative here)
1445 * also work around dump1090-mutability issue #47 which can send very stale Mode A/C messages
1446 */
1447 if (self->want_events && message_len != 2 && !timestamp_check(self, timestamp)) {
1448 if (! (messages[message_count++] = make_timestamp_jump_event(self, timestamp)))
1449 goto out;
1450 }
1451
1452 timestamp_update(self, timestamp);
1453
1454 /* decode it */
1455 if (! (message = modesmessage_from_buffer(timestamp, 0, data, message_len)))
1456 goto out;
1457
1458 /* apply filters, update seen-set */
1459 ++self->received_messages;
1460 int wanted = filter_message(self, message);
1461 if (wanted < 0)
1462 goto out;
1463 else if (wanted)
1464 messages[message_count++] = message;
1465 else {
1466 ++self->suppressed_messages;
1467 Py_DECREF(message);
1468 }
1469
1470 /* next message */
1471 p = m;
1472 }
1473
1474 nomoredata:
1475 if (! (message_tuple = PyTuple_New(message_count)))
1476 goto out;
1477
1478 while (--message_count >= 0) {
1479 PyTuple_SET_ITEM(message_tuple, message_count, messages[message_count]); /* steals ref */
1480 }
1481
1482 rv = Py_BuildValue("(l,N,N)", (long) (p - buffer_start), message_tuple, PyBool_FromLong(error_pending));
1483
1484 out:
1485 while (--message_count >= 0) {
1486 Py_XDECREF(messages[message_count]);
1487 }
1488 free(messages);
1489 return rv;
1490 }
1491
1492 /* inspect a message, update the seen set
1493 * return 1 if we should pass this message on to the caller
1494 * return 0 if we should drop it
1495 * return -1 on internal error (exception has been raised)
1496 */
1497 static int filter_message(modesreader *self, PyObject *o)
1498 {
1499 modesmessage *message = (modesmessage *)o;
1500
1501 // Check this, first. We don't really want to use MLAT msgs...
1502 if (message->timestamp == MAGIC_MLAT_TIMESTAMP && !self->want_mlat_messages) {
1503 ++self->mlat_messages;
1504 return 0;
1505 }
1506
1507 // Drop messages as long as timestamps are jumping.
1508 if (self->outliers > 0)
1509 return 0;
1510
1511 // Ignore messages that jump backwards
1512 if (self->last_timestamp > message->timestamp)
1513 return 0;
1514
1515 if (message->df == DF_MODEAC) {
1516 if (self->modeac_filter != NULL && self->modeac_filter != Py_None) {
1517 return PySequence_Contains(self->modeac_filter, message->address);
1518 }
1519
1520 return 1;
1521 }
1522
1523 if (!message->valid) {
1524 return self->want_invalid_messages; /* don't process further, contents are dubious */
1525 }
1526
1527 if (self->seen != NULL && self->seen != Py_None) {
1528 if (message->df == 11 || message->df == 17 || message->df == 18) {
1529 /* note that we saw this aircraft, even if the message is filtered.
1530 * only do this for CRC-checked messages as we get a lot of noise
1531 * otherwise.
1532 */
1533 if (PySet_Add(self->seen, message->address) < 0) {
1534 return -1;
1535 }
1536 }
1537 }
1538
1539 if (message->timestamp == 0 && !self->want_zero_timestamps) {
1540 return 0;
1541 }
1542
1543 if ((self->default_filter == NULL || self->default_filter == Py_None) &&
1544 (self->specific_filter == NULL || self->specific_filter == Py_None)) {
1545 /* no filters installed, match everything */
1546 return 1;
1547 }
1548
1549 /* check per-type filters */
1550 if (self->default_filter != NULL && self->default_filter != Py_None) {
1551 int rv;
1552 PyObject *entry = PySequence_GetItem(self->default_filter, message->df);
1553 if (entry == NULL)
1554 return -1;
1555
1556 rv = PyObject_IsTrue(entry);
1557 Py_DECREF(entry);
1558 if (rv != 0)
1559 return rv;
1560 }
1561
1562 if (self->specific_filter != NULL && self->specific_filter != Py_None) {
1563 int rv;
1564 PyObject *entry = PySequence_GetItem(self->specific_filter, message->df);
1565 if (entry == NULL)
1566 return -1;
1567
1568 if (entry == Py_None) {
1569 rv = 0;
1570 } else {
1571 rv = PySequence_Contains(entry, message->address);
1572 }
1573
1574 Py_DECREF(entry);
1575 if (rv != 0)
1576 return rv;
1577 }
1578
1579 return 0;
1580 }