-
Notifications
You must be signed in to change notification settings - Fork 75
/
modes_reader.c
1480 lines (1257 loc) · 50.4 KB
/
modes_reader.c
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
/*
* Part of mlat-client - an ADS-B multilateration client.
* Copyright 2015, Oliver Jowett <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "_modes.h"
/* decoder modes */
typedef enum {
DECODER_NONE, /* Not configured */
DECODER_BEAST, /* Beast binary, freerunning 48-bit timestamp @ 12MHz */
DECODER_RADARCAPE, /* Beast binary, 1GHz Radarcape timestamp, UTC synchronized from GPS */
DECODER_RADARCAPE_EMULATED, /* Beast binary, 1GHz Radarcape timestamp, not synchronized */
DECODER_AVR, /* AVR, no timestamp */
DECODER_AVRMLAT, /* AVR, freerunning 48-bit timestamp @ 12MHz */
DECODER_SBS, /* Kinetic SBS, freerunning 20MHz 24-bit timestamp, wraps around all the time but we try to widen it */
} decoder_mode;
/* This range of timestamps are treated as synthetic messages (generated by
* mlat, from UAT, etc)
*/
#define SYNTHETIC_TIMESTAMP_START 0xFF004D4C4154ULL
#define SYNTHETIC_TIMESTAMP_END (SYNTHETIC_TIMESTAMP_START + 10)
/* a modesreader object */
typedef struct {
PyObject_HEAD
/* decoder characteristics */
decoder_mode decoder_mode;
const char *decoder_mode_string;
unsigned long long frequency;
const char *epoch;
unsigned long long last_timestamp; /* last seen timestamp */
unsigned int radarcape_utc_bugfix;
/* configurable bits */
char allow_mode_change;
char want_zero_timestamps;
char want_synthetic_messages;
char want_invalid_messages;
char want_events;
/* filtering */
PyObject *seen;
PyObject *default_filter;
PyObject *specific_filter;
PyObject *modeac_filter;
/* stats */
unsigned int received_messages;
unsigned int suppressed_messages;
} modesreader;
/* methods for the modesreader type */
static PyObject *modesreader_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
static int modesreader_init(modesreader *self, PyObject *args, PyObject *kwds);
static void modesreader_dealloc(modesreader *self);
static int modesreader_setmode(modesreader *self, PyObject *mode, void *dummy);
static PyObject *modesreader_getmode(modesreader *self, void *dummy);
static PyObject *modesreader_feed(modesreader *self, PyObject *args, PyObject *kwds);
/* modesreader fields */
static PyMemberDef modesreaderMembers[] = {
/* these two are derived from the current mode always */
{ "frequency", T_ULONGLONG, offsetof(modesreader, frequency), READONLY, "timestamp frequency" },
{ "epoch", T_STRING, offsetof(modesreader, epoch), READONLY, "timestamp epoch" },
{ "last_timestamp", T_ULONGLONG, offsetof(modesreader, last_timestamp), 0, "last timestamp seen" },
{ "allow_mode_change", T_BOOL, offsetof(modesreader, allow_mode_change), 0, "can the decoder change mode based on status messages it receives?" },
{ "want_zero_timestamps", T_BOOL, offsetof(modesreader, want_zero_timestamps), 0, "should the decoder return messages with zero timestamps?" },
{ "want_synthetic_messages", T_BOOL, offsetof(modesreader, want_synthetic_messages), 0, "should the decoder return synthetic messages?" },
{ "want_invalid_messages", T_BOOL, offsetof(modesreader, want_invalid_messages), 0, "should the decoder return invalid messages?" },
{ "want_events", T_BOOL, offsetof(modesreader, want_events), 0, "should the decoder return metadata events?" },
{ "seen", T_OBJECT, offsetof(modesreader, seen), 0, "set of addresses seen by the decoder" },
{ "default_filter", T_OBJECT, offsetof(modesreader, default_filter), 0, "DF accept filter for all aircraft"},
{ "specific_filter", T_OBJECT, offsetof(modesreader, specific_filter), 0, "DF accept filter for specific aircraft"},
{ "modeac_filter", T_OBJECT, offsetof(modesreader, modeac_filter), 0, "Mode A/C accept filter"},
{ "received_messages", T_UINT, offsetof(modesreader, received_messages), 0, "total number of messages decoded"},
{ "suppressed_messages", T_UINT, offsetof(modesreader, suppressed_messages), 0, "number of messages suppressed by filtering"},
{ NULL, 0, 0, 0, NULL }
};
/* .. and the mode field which has a special getter/setter */
static PyGetSetDef modesreaderGetSet[] = {
{ "mode", (getter)modesreader_getmode, (setter)modesreader_setmode, "decoder mode", NULL },
{ NULL, NULL, NULL, NULL, NULL }
};
/* modesreader methods */
static PyMethodDef modesreaderMethods[] = {
{ "feed", (PyCFunction)modesreader_feed, METH_VARARGS|METH_KEYWORDS, "Process and decode some data." },
{ NULL, NULL, 0, NULL }
};
/* modesreader type definition */
static PyTypeObject modesreaderType = {
PyVarObject_HEAD_INIT(NULL, 0)
"_modes.Reader", /* tp_name */
sizeof(modesreader), /* tp_basicsize */
0, /* tp_itemsize */
(destructor)modesreader_dealloc, /* tp_dealloc */
0, /* tp_print */
0, /* tp_getattr */
0, /* tp_setattr */
0, /* tp_reserved */
0, /* tp_repr */
0, /* tp_as_number */
0, /* tp_as_sequence */
0, /* tp_as_mapping */
0, /* tp_hash */
0, /* tp_call */
0, /* tp_str */
PyObject_GenericGetAttr, /* tp_getattro */
PyObject_GenericSetAttr, /* tp_setattro */
0, /* tp_as_buffer */
Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE, /* tp_flags */
"A ModeS stream reader.", /* tp_doc */
0, /* tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_weaklistoffset */
0, /* tp_iter */
0, /* tp_iternext */
modesreaderMethods, /* tp_methods */
modesreaderMembers, /* tp_members */
modesreaderGetSet, /* tp_getset */
0, /* tp_base */
0, /* tp_dict */
0, /* tp_descr_get */
0, /* tp_descr_set */
0, /* tp_dictoffset */
(initproc)modesreader_init, /* tp_init */
0, /* tp_alloc */
modesreader_new, /* tp_new */
};
/* lookup table for decoder_mode <-> python strings */
static struct {
decoder_mode mode;
const char *cstr;
PyObject *pystr;
} modetable[] = {
{ DECODER_BEAST, "BEAST", NULL },
{ DECODER_RADARCAPE, "RADARCAPE", NULL },
{ DECODER_RADARCAPE_EMULATED, "RADARCAPE_EMULATED", NULL },
{ DECODER_AVR, "AVR", NULL },
{ DECODER_AVRMLAT, "AVRMLAT", NULL },
{ DECODER_SBS, "SBS", NULL },
{ DECODER_NONE, NULL, NULL }
};
/* internal helpers */
static PyObject *feed_beast(modesreader *self, Py_buffer *buf, int max_messages);
static PyObject *feed_avr(modesreader *self, Py_buffer *buf, int max_messages);
static PyObject *feed_sbs(modesreader *self, Py_buffer *buf, int max_messages);
static void set_decoder_mode(modesreader *self, decoder_mode newmode);
static PyObject *radarcape_settings_to_list(uint8_t settings);
static PyObject *radarcape_status_to_dict(uint8_t *message);
static int filter_message(modesreader *self, PyObject *message);
/*
* module setup/teardown
*/
int modesreader_module_init(PyObject *m)
{
int i;
if (PyType_Ready(&modesreaderType) < 0)
goto error;
for (i = 0; modetable[i].cstr != NULL; ++i) {
PyObject *pystr = PyUnicode_FromString(modetable[i].cstr);
if (pystr == NULL) {
goto error;
}
Py_INCREF(pystr);
modetable[i].pystr = pystr;
if (PyModule_AddObject(m, modetable[i].cstr, pystr) < 0)
goto error;
}
Py_INCREF(&modesreaderType);
if (PyModule_AddObject(m, "Reader", (PyObject *)&modesreaderType) < 0) {
Py_DECREF(&modesreaderType);
goto error;
}
return 0;
error:
for (i = 0; modetable[i].cstr != NULL; ++i) {
Py_CLEAR(modetable[i].pystr);
}
return -1;
}
void modesreader_module_free(PyObject *m)
{
int i;
for (i = 0; modetable[i].cstr != NULL; ++i) {
Py_CLEAR(modetable[i].pystr);
}
}
static PyObject *modesreader_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
modesreader *self;
self = (modesreader *)type->tp_alloc(type, 0);
if (self == NULL)
return NULL;
/* minimal init */
set_decoder_mode(self, DECODER_NONE);
self->last_timestamp = 0;
self->allow_mode_change = 1;
self->want_zero_timestamps = 0;
self->want_synthetic_messages = 0;
self->want_invalid_messages = 0;
self->want_events = 1;
Py_INCREF(Py_None); self->seen = Py_None;
Py_INCREF(Py_None); self->default_filter = Py_None;
Py_INCREF(Py_None); self->specific_filter = Py_None;
Py_INCREF(Py_None); self->modeac_filter = Py_None;
self->received_messages = self->suppressed_messages = 0;
return (PyObject *)self;
}
static void modesreader_dealloc(modesreader *self)
{
Py_CLEAR(self->seen);
Py_CLEAR(self->default_filter);
Py_CLEAR(self->specific_filter);
Py_CLEAR(self->modeac_filter);
Py_TYPE(self)->tp_free((PyObject*)self);
}
static int modesreader_init(modesreader *self, PyObject *args, PyObject *kwds)
{
static char *kwlist[] = { "mode", NULL };
PyObject *mode = Py_None;
if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O", kwlist, &mode))
return -1;
if (modesreader_setmode(self, mode, NULL) < 0)
return -1;
return 0;
}
static int modesreader_setmode(modesreader *self, PyObject *mode, void *dummy)
{
int i;
if (mode == Py_None) {
set_decoder_mode(self, DECODER_NONE);
return 0;
}
for (i = 0; modetable[i].cstr != NULL; ++i) {
int res = PyObject_RichCompareBool(modetable[i].pystr, mode, Py_EQ);
if (res < 0)
return -1;
if (res == 1) {
set_decoder_mode(self, modetable[i].mode);
break;
}
}
if (modetable[i].cstr == NULL) {
PyErr_SetString(PyExc_ValueError, "unrecognized decoder mode");
return -1;
}
return 0;
}
static PyObject *modesreader_getmode(modesreader *self, void *dummy)
{
int i;
for (i = 0; modetable[i].cstr; ++i) {
if (self->decoder_mode == modetable[i].mode) {
Py_INCREF(modetable[i].pystr);
return modetable[i].pystr;
}
}
Py_INCREF(Py_None);
return Py_None;
}
/* feed some data to the reader and does one of:
* 1) returns a tuple (bytes_consumed, messages, error_pending), or
* 2) throws an exception
*
* If a stream error is seen, but some messages were parsed OK,
* then an exception is not immediately thrown and the parsed
* messages are returned with error_pending = True. The caller
* should call feed again (after consuming the given number of
* bytes) to get the exception.
*
* Internal errors (e.g. out of memory) are thrown immediately.
*/
static PyObject *modesreader_feed(modesreader *self, PyObject *args, PyObject *kwds)
{
Py_buffer buffer;
PyObject *rv = NULL;
int max_messages = 0;
static char *kwlist[] = { "buffer", "max_messages", NULL };
if (!PyArg_ParseTupleAndKeywords(args, kwds, "y*|i", kwlist, &buffer, &max_messages))
return NULL;
if (buffer.itemsize != 1) {
PyErr_SetString(PyExc_ValueError, "buffer itemsize is not 1");
goto out;
}
if (!PyBuffer_IsContiguous(&buffer, 'C')) {
PyErr_SetString(PyExc_ValueError, "buffer is not contiguous");
goto out;
}
switch (self->decoder_mode) {
case DECODER_NONE:
PyErr_SetString(PyExc_NotImplementedError, "decoder mode is None, no decoder type selected");
break;
case DECODER_BEAST:
case DECODER_RADARCAPE:
case DECODER_RADARCAPE_EMULATED:
rv = feed_beast(self, &buffer, max_messages);
break;
case DECODER_AVR:
case DECODER_AVRMLAT:
rv = feed_avr(self, &buffer, max_messages);
break;
case DECODER_SBS:
rv = feed_sbs(self, &buffer, max_messages);
break;
default:
PyErr_Format(PyExc_AssertionError, "decoder somehow got into illegal mode %d", (int)self->decoder_mode);
break;
}
out:
PyBuffer_Release(&buffer);
return rv;
}
static void set_decoder_mode(modesreader *self, decoder_mode newmode)
{
self->decoder_mode = newmode;
switch (newmode) {
case DECODER_BEAST:
self->frequency = 12000000ULL; /* assumed */
self->epoch = NULL;
break;
case DECODER_RADARCAPE:
self->frequency = 1000000000ULL;
self->epoch = "utc_midnight";
break;
case DECODER_RADARCAPE_EMULATED:
self->frequency = 1000000000ULL;
self->epoch = NULL;
break;
case DECODER_AVRMLAT:
self->frequency = 12000000ULL; /* assumed */
self->epoch = NULL;
break;
case DECODER_SBS:
self->frequency = 20000000ULL;
self->epoch = NULL;
break;
case DECODER_AVR:
default:
self->frequency = 0;
self->epoch = NULL;
break;
}
}
/* turn a radarcape DIP switch setting byte into a Python list of settings strings */
static PyObject *radarcape_settings_to_list(uint8_t settings)
{
return Py_BuildValue("[s,s,s,s,s,s,s]",
settings & 0x01 ? "beast" : (settings & 0x04 ? "avrmlat" : "avr"),
settings & 0x02 ? "filtered_frames" : "all_frames",
settings & 0x08 ? "no_crc" : "check_crc",
settings & 0x10 ? "gps_timestamps" : "legacy_timestamps",
settings & 0x20 ? "rtscts" : "no_rtscts",
settings & 0x40 ? "no_fec" : "fec",
settings & 0x80 ? "modeac" : "no_modeac");
}
/* turn a radarcape GPS status byte into a Python dict */
static PyObject *radarcape_gpsstatus_to_dict(uint8_t status)
{
if (!(status & 0x80)) {
return Py_BuildValue("{s:O,s:O}",
"utc_bugfix", Py_False,
"timestamp_ok", Py_True
);
}
return Py_BuildValue("{s:O,s:O,s:O,s:O,s:O,s:O,s:O}",
"utc_bugfix", Py_True,
"timestamp_ok", (status & 0x20 ? Py_False : Py_True),
"sync_ok", (status & 0x10 ? Py_True : Py_False),
"utc_offset_ok", (status & 0x08 ? Py_True : Py_False),
"sats_ok", (status & 0x04 ? Py_True : Py_False),
"tracking_ok", (status & 0x02 ? Py_True : Py_False),
"antenna_ok", (status & 0x01 ? Py_True : Py_False));
}
/* turn a radarcape 0x34 status message into a Python dict */
static PyObject *radarcape_status_to_dict(uint8_t *message)
{
return Py_BuildValue("{s:N,s:i,s:N}",
"settings", radarcape_settings_to_list(message[0]),
"timestamp_pps_delta", (int)(int8_t)message[1],
"gps_status", radarcape_gpsstatus_to_dict(message[2]));
}
/* create an event message for a timestamp jump */
static PyObject *make_timestamp_jump_event(modesreader *self, unsigned long long timestamp)
{
PyObject *eventdata = Py_BuildValue("{s:K}",
"last-timestamp", self->last_timestamp);
if (eventdata == NULL)
return NULL;
return modesmessage_new_eventmessage(DF_EVENT_TIMESTAMP_JUMP, timestamp, eventdata);
}
/* create an event message for a decoder mode change. the new mode should already be set. */
static PyObject *make_mode_change_event(modesreader *self)
{
PyObject *eventdata = Py_BuildValue("{s:N,s:K,s:s}",
"mode", modesreader_getmode(self, NULL),
"frequency", self->frequency,
"epoch", self->epoch);
if (eventdata == NULL)
return NULL;
return modesmessage_new_eventmessage(DF_EVENT_MODE_CHANGE, 0, eventdata);
}
/* create an event message for an epoch rollover (e.g. GPS end of day) */
static PyObject *make_epoch_rollover_event(modesreader *self, unsigned long long timestamp)
{
PyObject *eventdata = PyDict_New();
if (eventdata == NULL)
return NULL;
return modesmessage_new_eventmessage(DF_EVENT_EPOCH_ROLLOVER, timestamp, eventdata);
}
/* create an event message for a radarcape status report */
static PyObject *make_radarcape_status_event(modesreader *self, unsigned long long timestamp, uint8_t *data)
{
PyObject *eventdata = radarcape_status_to_dict(data);
if (eventdata == NULL)
return NULL;
return modesmessage_new_eventmessage(DF_EVENT_RADARCAPE_STATUS, timestamp, eventdata);
}
static double unpack_float4_le(uint8_t *p)
{
/* This API changed in Python 3.11, and the arg types vary a bit */
#if PY_VERSION_HEX < 0x030B0000
return _PyFloat_Unpack4((const unsigned char *)p, 1);
#else
return PyFloat_Unpack4((const char *)p, 1);
#endif
}
/* create an event message for a radarcape position report */
static PyObject *radarcape_position_to_dict(uint8_t *data)
{
float lat, lon, alt;
lat = unpack_float4_le(data + 4);
if (lat == -1.0 && PyErr_Occurred())
return NULL;
lon = unpack_float4_le(data + 8);
if (lon == -1.0 && PyErr_Occurred())
return NULL;
alt = unpack_float4_le(data + 12);
if (alt == -1.0 && PyErr_Occurred())
return NULL;
return Py_BuildValue("{s:f,s:f,s:f}",
"lat", lat,
"lon", lon,
"alt", alt);
}
static PyObject *make_radarcape_position_event(modesreader *self, uint8_t *data)
{
PyObject *eventdata = radarcape_position_to_dict(data);
if (eventdata == NULL)
return NULL;
return modesmessage_new_eventmessage(DF_EVENT_RADARCAPE_POSITION, 0, eventdata);
}
static int is_synthetic_timestamp(unsigned long long timestamp)
{
return (timestamp >= SYNTHETIC_TIMESTAMP_START && timestamp <= SYNTHETIC_TIMESTAMP_END);
}
static int is_synthetic_or_zero_timestamp(unsigned long long timestamp)
{
return (timestamp == 0 || is_synthetic_timestamp(timestamp));
}
/* check if the given timestamp is in range (not a jump), return 1 if it is */
static int timestamp_check(modesreader *self, unsigned long long timestamp)
{
if (is_synthetic_or_zero_timestamp(timestamp))
return 1;
if (self->last_timestamp == 0)
return 1;
if (self->frequency == 0)
return 1;
if (self->last_timestamp > timestamp && (self->last_timestamp - timestamp) > 90 * self->frequency)
return 0;
if (self->last_timestamp < timestamp && (timestamp - self->last_timestamp) > 90 * self->frequency)
return 0;
return 1;
}
/* update self->last_timestamp given that we just saw this timestamp */
static void timestamp_update(modesreader *self, unsigned long long timestamp)
{
if (is_synthetic_or_zero_timestamp(timestamp)) {
/* special timestamps, don't use them */
return;
}
if (self->last_timestamp == 0 || self->frequency == 0) {
/* startup cases, just accept whatever */
self->last_timestamp = timestamp;
return;
}
if (self->last_timestamp > timestamp && (self->last_timestamp - timestamp) < 90 * self->frequency) {
/* ignore small moves backwards */
return;
}
if ((self->decoder_mode == DECODER_RADARCAPE || self->decoder_mode == DECODER_RADARCAPE_EMULATED) &&
timestamp >= (86340 * 1000000000ULL) && self->last_timestamp <= (60 * 1000000000ULL)) {
/* in radarcape mode, don't allow last_timestamp to roll back to the previous day
* as we will have already issued an epoch reset
*/
return;
}
self->last_timestamp = timestamp;
}
/* feed implementation for Beast-format data (including Radarcape) */
static PyObject *feed_beast(modesreader *self, Py_buffer *buffer, int max_messages)
{
PyObject *rv = NULL;
uint8_t *buffer_start, *p, *eod;
int message_count = 0;
PyObject *message_tuple = NULL;
PyObject **messages = NULL;
int error_pending = 0;
buffer_start = buffer->buf;
if (max_messages <= 0) {
/* allocate the maximum size we might need, given a minimal encoding of:
* <1A> <'1'> <6 bytes timestamp> <1 byte signal> <2 bytes message> = 11 bytes total
*/
max_messages = buffer->len / 11 + 2;
}
messages = calloc(max_messages, sizeof(PyObject*));
if (!messages) {
PyErr_NoMemory();
goto out;
}
/* parse messages */
p = buffer_start;
eod = buffer_start + buffer->len;
while (p+2 <= eod && message_count+2 < max_messages) {
int message_len = -1;
uint64_t timestamp;
uint8_t signal;
uint8_t data[14];
uint8_t *m, *eom;
int i;
uint8_t type;
PyObject *message;
int wanted;
int has_timestamp_signal;
if (p[0] != 0x1a) {
error_pending = 1;
if (message_count > 0)
goto nomoredata;
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]);
goto out;
}
has_timestamp_signal = 1;
type = p[1];
switch (type) {
case '1': message_len = 2; break; /* mode A/C */
case '2': message_len = 7; break; /* mode S short */
case '3': message_len = 14; break; /* mode S long */
case '4': message_len = 14; break; /* radarcape status message */
case '5':
/* radarcape position message, no timestamp/signal bytes */
message_len = 21;
has_timestamp_signal = 0;
break;
default:
error_pending = 1;
if (message_count > 0)
goto nomoredata;
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));
goto out;
}
m = p + 2;
eom = m + message_len + (has_timestamp_signal ? 7 : 0);
if (eom > eod)
break;
#define ADVANCE \
do { \
if (*m++ == 0x1a) { \
if (m < eod && *m != 0x1a) { \
error_pending = 1; \
if (message_count > 0) \
goto nomoredata; \
PyErr_SetString(PyExc_ValueError, "Lost sync with input stream: expected 0x1A after 0x1A escape"); \
goto out; \
} \
++m, ++eom; \
if (eom > eod) \
goto nomoredata; \
} \
} while(0)
if (has_timestamp_signal) {
/* timestamp, 6 bytes */
timestamp = *m;
ADVANCE;
timestamp = (timestamp << 8) | *m;
ADVANCE;
timestamp = (timestamp << 8) | *m;
ADVANCE;
timestamp = (timestamp << 8) | *m;
ADVANCE;
timestamp = (timestamp << 8) | *m;
ADVANCE;
timestamp = (timestamp << 8) | *m;
ADVANCE;
/* signal, 1 byte */
signal = *m;
ADVANCE;
} else {
timestamp = 0;
signal = 0;
}
/* message, N bytes */
for (i = 0; i < message_len; ++i) {
data[i] = *m;
ADVANCE;
}
/* do some filtering */
if (type == '4') {
/* radarcape-style status message, use this to switch our decoder type */
self->radarcape_utc_bugfix = (data[2] & 0x80) == 0x80;
if (self->allow_mode_change) {
decoder_mode newmode;
if (data[0] & 0x10) {
/* radarcape in GPS timestamp mode */
if ((data[2] & 0x20) == 0x20) {
newmode = DECODER_RADARCAPE_EMULATED;
} else {
newmode = DECODER_RADARCAPE;
}
} else {
/* radarcape in 12MHz timestamp mode */
newmode = DECODER_BEAST;
}
/* handle mode changes by inserting an event message */
if (newmode != self->decoder_mode) {
set_decoder_mode(self, newmode);
if (self->want_events) {
if (! (messages[message_count++] = make_mode_change_event(self)))
goto out;
}
}
}
}
if (has_timestamp_signal && !is_synthetic_or_zero_timestamp(timestamp)) {
if (self->decoder_mode == DECODER_BEAST) {
/* 12MHz mode */
/* check for very out of range value
* (dump1090 can hold messages for up to 60 seconds! so be conservative here)
* also work around dump1090-mutability issue #47 which can send very stale Mode A/C messages
*/
if (self->want_events && type != '1' && !timestamp_check(self, timestamp)) {
if (! (messages[message_count++] = make_timestamp_jump_event(self, timestamp)))
goto out;
}
/* adjust the timestamps so they always reflect the start of the frame */
uint64_t adjust;
if (type == '1') {
// Mode A/C, timestamp reported at F2 which is 20.3us after F1
// this is 243.6 cycles at 12MHz
adjust = 244;
} else if (type == '2') {
// Mode S short, timestamp reported at end of frame, frame is 8us preamble plus 56us data
// this is 768 cycles at 12MHz
adjust = 768;
} else if (type == '3') {
// Mode S long, timestamp reported halfway through the frame (at bit 56), same offset as Mode S short
adjust = 768;
} else {
// anything else we assume is already correct
adjust = 0;
}
if (timestamp < adjust) {
timestamp = 0;
} else {
timestamp = timestamp - adjust;
}
} else {
/* gps mode */
/* adjust timestamp so that it is a contiguous nanoseconds-since-
* midnight value, rather than the raw form which skips values once
* a second
*/
uint64_t nanos = timestamp & 0x00003FFFFFFF;
uint64_t secs = timestamp >> 30;
if (!self->radarcape_utc_bugfix) {
/* fix up the timestamp so it is UTC, not 1 second ahead */
if (secs == 0) {
secs = 86399;
} else {
--secs;
}
}
timestamp = nanos + secs * 1000000000;
/* adjust the timestamps so they always reflect the start of the frame */
uint64_t adjust;
if (type == '1') {
// Mode A/C, timestamp reported at F2 which is 20.3us after F1
adjust = 20300;
} else if (type == '2') {
// Mode S short, timestamp reported at end of frame, frame is 8us preamble plus 56us data
adjust = 64000;
} else if (type == '3') {
// Mode S long, timestamp reported at end of frame, frame is 8us preamble plus 112us data
adjust = 120000;
} else {
// anything else we assume is already correct
adjust = 0;
}
if (adjust <= timestamp) {
timestamp = timestamp - adjust;
} else {
/* wrap it to the previous day */
timestamp = timestamp + 86400 * 1000000000ULL - adjust;
}
/* check for end of day rollover */
if (self->want_events && self->last_timestamp >= (86340 * 1000000000ULL) && timestamp <= (60 * 1000000000ULL)) {
if (! (messages[message_count++] = make_epoch_rollover_event(self, timestamp)))
goto out;
} else if (self->want_events && type != '1' && !timestamp_check(self, timestamp)) {
if (! (messages[message_count++] = make_timestamp_jump_event(self, timestamp)))
goto out;
}
}
if (type != '1') {
timestamp_update(self, timestamp);
}
}
if (type == '4') {
/* radarcape-style status message, emit the status event if wanted */
if (self->want_events) {
if (! (messages[message_count++] = make_radarcape_status_event(self, timestamp, data)))
goto out;
}
/* don't try to process this as a Mode S message */
p = m;
continue;
}
if (type == '5') {
/* radarcape-style position message, emit the position event if wanted */
if (self->want_events) {
if (! (messages[message_count++] = make_radarcape_position_event(self, data)))
goto out;
}
/* don't try to process this as a Mode S message */
p = m;
continue;
}
/* it's a Mode A/C or Mode S message, parse it */
if (! (message = modesmessage_from_buffer(timestamp, signal, data, message_len)))
goto out;
/* apply filters, update seen-set */
++self->received_messages;
wanted = filter_message(self, message);
if (wanted < 0)
goto out;
else if (wanted)
messages[message_count++] = message;
else {
++self->suppressed_messages;
Py_DECREF(message);
}
p = m;
}
nomoredata:
if (! (message_tuple = PyTuple_New(message_count)))
goto out;
while (--message_count >= 0) {
PyTuple_SET_ITEM(message_tuple, message_count, messages[message_count]); /* steals ref */
}
rv = Py_BuildValue("(l,N,N)", (long) (p - buffer_start), message_tuple, PyBool_FromLong(error_pending));
out:
while (--message_count >= 0) {
Py_XDECREF(messages[message_count]);
}
free(messages);
return rv;
}
/********** SBS INPUT **************/
/*
* Some notes on this format, as it is poorly documented by Kinetic:
*
* The stream can start at an arbitrary point, the first byte might be mid-packet.
* You need to look for a DLE STX to synchronize with the stream.
* This implementation does that in the Python code to keep this bit simpler; the
* C code assumes it is always given bytes starting at the start of a packet.
*
* You might get arbitrary packet types e.g. AIS interleaved with Mode S messages.
* This implementation doesn't try to interpret them at all, it just reads all
* data until DLE ETX regardless of type and skips those types it doesn't
* understand.
*
* The Mode S CRC values are not the raw bytes from the message; they are the
* residual CRC value after XORing the raw bytes with the calculated CRC over
* the body of the message. That is, a DF17 message with a correct CRC will have
* zeros in the CRC bytes; a DF11 with correct CRC will have the IID in the CRC
* bytes; messages that use Address/Parity will have the address in the CRC bytes.
* To recover the original message, calculate the CRC and XOR it back into the CRC
* bytes. Andrew Whewell says this is probably controlled by a Basestation setting.
*
* The timestamps are measured at the _end_ of the frame, not at the start.
* As frames are variable length, if you want a timestamp anchored to the
* start of the frame (as dump1090 / Beast do), you have to compensate for
* the frame length.
*/
static PyObject *feed_sbs(modesreader *self, Py_buffer *buffer, int max_messages)
{
PyObject *rv = NULL;
uint8_t *buffer_start, *p, *eod;
int message_count = 0;
PyObject *message_tuple = NULL;
PyObject **messages = NULL;
int error_pending = 0;
buffer_start = buffer->buf;
if (max_messages <= 0) {
/* allocate the maximum size we might need, given a minimal encoding of:
* <DLE> <STX> <0x09> <n/a> <3 bytes timestamp> <2 bytes message> <DLE> <ETX> <2 bytes CRC> = 13 bytes total
*/
max_messages = buffer->len / 13 + 1;
}
messages = calloc(max_messages, sizeof(PyObject*));
if (!messages) {
PyErr_NoMemory();
goto out;
}
/* parse messages */
p = buffer_start;
eod = buffer_start + buffer->len;
while (p+13 <= eod && message_count < max_messages) {
int message_len = -1;
uint64_t timestamp;
/* largest message we care about is:
* type 1 byte 0x05 = ADS-B
* spare 1 byte
* timestamp 3 bytes
* data 14 bytes
* total 19 bytes
*/
uint8_t data[19];
uint8_t *m;
int i;
uint8_t type;
uint32_t crc;
PyObject *message;
if (p[0] != 0x10 || p[1] != 0x02) {
error_pending = 1;
if (message_count > 0)
goto nomoredata;
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]);
goto out;
}
/* scan for DLE ETX, copy data */
m = p + 2;
i = 0;
while (m < eod) {
if (*m == 0x10) {
/* DLE <something> */
if ((m+1) >= eod)
goto nomoredata;