forked from itemir/dump1090_sdrplus
-
Notifications
You must be signed in to change notification settings - Fork 4
/
dump1090.c
3079 lines (2746 loc) · 111 KB
/
dump1090.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
/* Mode1090, a Mode S messages decoder for RTLSDR devices.
*
* Copyright (C) 2012 by Salvatore Sanfilippo <[email protected]>
*
* HackRF One support added by Ilker Temir <[email protected]>
* AirSpy support added by Chris Kuethe <[email protected]>
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <pthread.h>
#include <stdint.h>
#include <err.h>
#include <errno.h>
#include <unistd.h>
#include <math.h>
#include <sys/time.h>
#include <signal.h>
#include <fcntl.h>
#include <ctype.h>
#include <sys/stat.h>
#include <sys/ioctl.h>
#include <sys/select.h>
#include "rtl-sdr.h"
#include "libhackrf/hackrf.h"
#include "libairspy/airspy.h"
#include "mirsdrapi-rsp.h"
#include "soxr.h"
#include "anet.h"
#define MODES_DEFAULT_RATE 2000000
#define MODES_DEFAULT_FREQ 1090000000
#define MODES_DEFAULT_WIDTH 1000
#define MODES_DEFAULT_HEIGHT 700
#define MODES_ASYNC_BUF_NUMBER 12
#define MODES_DATA_LEN (16*16384) /* 256k */
#define MODES_AUTO_GAIN -100 /* Use automatic gain. */
#define MODES_MAX_GAIN 999999 /* Use max available gain. */
/* HackRF One Defaults */
#define HACKRF_RF_GAIN 0
#define HACKRF_LNA_GAIN 32
#define HACKRF_VGA_GAIN 48
/* AirSpy defaults */
#define AIRSPY_RF_GAIN 11
#define AIRSPY_LNA_GAIN 11
#define AIRSPY_VGA_GAIN 11
#define MODES_PREAMBLE_US 8 /* microseconds */
#define MODES_LONG_MSG_BITS 112
#define MODES_SHORT_MSG_BITS 56
#define MODES_FULL_LEN (MODES_PREAMBLE_US+MODES_LONG_MSG_BITS)
#define MODES_LONG_MSG_BYTES (112/8)
#define MODES_SHORT_MSG_BYTES (56/8)
#define MODES_ICAO_CACHE_LEN 1024 /* Power of two required. */
#define MODES_ICAO_CACHE_TTL 60 /* Time to live of cached addresses. */
#define MODES_UNIT_FEET 0
#define MODES_UNIT_METERS 1
#define MODES_DEBUG_DEMOD (1<<0)
#define MODES_DEBUG_DEMODERR (1<<1)
#define MODES_DEBUG_BADCRC (1<<2)
#define MODES_DEBUG_GOODCRC (1<<3)
#define MODES_DEBUG_NOPREAMBLE (1<<4)
#define MODES_DEBUG_NET (1<<5)
#define MODES_DEBUG_JS (1<<6)
/* When debug is set to MODES_DEBUG_NOPREAMBLE, the first sample must be
* at least greater than a given level for us to dump the signal. */
#define MODES_DEBUG_NOPREAMBLE_LEVEL 25
#define MODES_INTERACTIVE_REFRESH_TIME 250 /* Milliseconds */
#define MODES_INTERACTIVE_ROWS 15 /* Rows on screen */
#define MODES_INTERACTIVE_TTL 60 /* TTL before being removed */
#define MODES_NET_MAX_FD 1024
#define MODES_NET_OUTPUT_SBS_PORT 30003
#define MODES_NET_OUTPUT_RAW_PORT 30002
#define MODES_NET_INPUT_RAW_PORT 30001
#define MODES_NET_HTTP_PORT 8080
#define MODES_CLIENT_BUF_SIZE 1024
#define MODES_NET_SNDBUF_SIZE (1024*64)
#define MODES_NOTUSED(V) ((void) V)
/* Structure used to describe a networking client. */
struct client {
int fd; /* File descriptor. */
int service; /* TCP port the client is connected to. */
char buf[MODES_CLIENT_BUF_SIZE+1]; /* Read buffer. */
int buflen; /* Amount of data on buffer. */
};
/* Structure used to describe an aircraft in iteractive mode. */
struct aircraft {
uint32_t addr; /* ICAO address */
char hexaddr[7]; /* Printable ICAO address */
char flight[9]; /* Flight number */
int altitude; /* Altitude */
int speed; /* Velocity computed from EW and NS components. */
int track; /* Angle of flight. */
time_t seen; /* Time at which the last packet was received. */
long messages; /* Number of Mode S messages received. */
/* Encoded latitude and longitude as extracted by odd and even
* CPR encoded messages. */
int odd_cprlat;
int odd_cprlon;
int even_cprlat;
int even_cprlon;
double lat, lon; /* Coordinated obtained from CPR encoded data. */
long long odd_cprtime, even_cprtime;
struct aircraft *next; /* Next aircraft in our linked list. */
};
/* Program global state. */
struct {
/* Internal state */
pthread_t reader_thread;
pthread_mutex_t data_mutex; /* Mutex to synchronize buffer access. */
pthread_cond_t data_cond; /* Conditional variable associated. */
unsigned char *data; /* Raw IQ samples buffer */
uint16_t *magnitude; /* Magnitude vector */
uint32_t data_len; /* Buffer length. */
int fd; /* --ifile option file descriptor. */
int data_ready; /* Data ready to be processed. */
uint32_t *icao_cache; /* Recently seen ICAO addresses cache. */
uint16_t *maglut; /* I/Q -> Magnitude lookup table. */
int exit; /* Exit from the main loop when true. */
/* Drivers */
int prefer_airspy;
int prefer_hackrf;
int prefer_rtlsdr;
int prefer_sdrplay;
/* RTLSDR */
int rtl_enabled;
int dev_index;
int gain;
int enable_agc;
rtlsdr_dev_t *dev;
/* HackRF One and Airspy are very similar... */
int hackrf_enabled;
int rf_gain;
int lna_gain;
int vga_gain;
hackrf_device *hackrf;
/* ... but AirSpy needs to be resampled */
int airspy_enabled;
struct airspy_device *airspy;
soxr_t resampler;
char *airspy_bytes, *airspy_scratch;
/* SDRplay */
int sdrplay_enabled;
int sdrplaySamplesPerPacket;
short *sdrplay_i;
short *sdrplay_q;
/* SDR Common */
int freq;
/* Networking */
char aneterr[ANET_ERR_LEN];
struct client *clients[MODES_NET_MAX_FD]; /* Our clients. */
int maxfd; /* Greatest fd currently active. */
int sbsos; /* SBS output listening socket. */
int ros; /* Raw output listening socket. */
int ris; /* Raw input listening socket. */
int https; /* HTTP listening socket. */
/* Configuration */
char *filename; /* Input form file, --ifile option. */
int fix_errors; /* Single bit error correction if true. */
int check_crc; /* Only display messages with good CRC. */
int raw; /* Raw output format. */
int debug; /* Debugging mode. */
int net; /* Enable networking. */
int net_only; /* Enable just networking. */
int interactive; /* Interactive mode */
int interactive_rows; /* Interactive mode: max number of rows. */
int interactive_ttl; /* Interactive mode: TTL before deletion. */
int stats; /* Print stats at exit in --ifile mode. */
int onlyaddr; /* Print only ICAO addresses. */
int metric; /* Use metric units. */
int aggressive; /* Aggressive detection algorithm. */
/* Interactive mode */
struct aircraft *aircrafts;
long long interactive_last_update; /* Last screen update in milliseconds */
/* Statistics */
long long stat_valid_preamble;
long long stat_demodulated;
long long stat_goodcrc;
long long stat_badcrc;
long long stat_fixed;
long long stat_single_bit_fix;
long long stat_two_bits_fix;
long long stat_http_requests;
long long stat_sbs_connections;
long long stat_out_of_phase;
} Modes;
/* The struct we use to store information about a decoded message. */
struct modesMessage {
/* Generic fields */
unsigned char msg[MODES_LONG_MSG_BYTES]; /* Binary message. */
int msgbits; /* Number of bits in message */
int msgtype; /* Downlink format # */
int crcok; /* True if CRC was valid */
uint32_t crc; /* Message CRC */
int errorbit; /* Bit corrected. -1 if no bit corrected. */
int aa1, aa2, aa3; /* ICAO Address bytes 1 2 and 3 */
int phase_corrected; /* True if phase correction was applied. */
/* DF 11 */
int ca; /* Responder capabilities. */
/* DF 17 */
int metype; /* Extended squitter message type. */
int mesub; /* Extended squitter message subtype. */
int heading_is_valid;
int heading;
int aircraft_type;
int fflag; /* 1 = Odd, 0 = Even CPR message. */
int tflag; /* UTC synchronized? */
int raw_latitude; /* Non decoded latitude */
int raw_longitude; /* Non decoded longitude */
char flight[9]; /* 8 chars flight number. */
int ew_dir; /* 0 = East, 1 = West. */
int ew_velocity; /* E/W velocity. */
int ns_dir; /* 0 = North, 1 = South. */
int ns_velocity; /* N/S velocity. */
int vert_rate_source; /* Vertical rate source. */
int vert_rate_sign; /* Vertical rate sign. */
int vert_rate; /* Vertical rate. */
int velocity; /* Computed from EW and NS velocity. */
/* DF4, DF5, DF20, DF21 */
int fs; /* Flight status for DF4,5,20,21 */
int dr; /* Request extraction of downlink request. */
int um; /* Request extraction of downlink request. */
int identity; /* 13 bits identity (Squawk). */
/* Fields used by multiple message types. */
int altitude, unit;
};
void interactiveShowData(void);
struct aircraft* interactiveReceiveData(struct modesMessage *mm);
void modesSendRawOutput(struct modesMessage *mm);
void modesSendSBSOutput(struct modesMessage *mm, struct aircraft *a);
void useModesMessage(struct modesMessage *mm);
int fixSingleBitErrors(unsigned char *msg, int bits);
int fixTwoBitsErrors(unsigned char *msg, int bits);
int modesMessageLenByType(int type);
void sigWinchCallback();
int getTermRows();
/* ============================= Utility functions ========================== */
static long long mstime(void) {
struct timeval tv;
long long mst;
gettimeofday(&tv, NULL);
mst = ((long long)tv.tv_sec)*1000;
mst += tv.tv_usec/1000;
return mst;
}
/* =============================== Initialization =========================== */
void modesInitConfig(void) {
Modes.gain = MODES_MAX_GAIN;
Modes.dev_index = 0;
Modes.enable_agc = 0;
Modes.rf_gain = 0;
Modes.lna_gain = 0;
Modes.vga_gain = 0;
Modes.freq = MODES_DEFAULT_FREQ;
Modes.filename = NULL;
Modes.fix_errors = 1;
Modes.check_crc = 1;
Modes.raw = 0;
Modes.net = 0;
Modes.net_only = 0;
Modes.onlyaddr = 0;
Modes.debug = 0;
Modes.interactive = 0;
Modes.interactive_rows = MODES_INTERACTIVE_ROWS;
Modes.interactive_ttl = MODES_INTERACTIVE_TTL;
Modes.aggressive = 0;
Modes.interactive_rows = getTermRows();
}
void modesInit(void) {
int i, q;
pthread_mutex_init(&Modes.data_mutex,NULL);
pthread_cond_init(&Modes.data_cond,NULL);
/* We add a full message minus a final bit to the length, so that we
* can carry the remaining part of the buffer that we can't process
* in the message detection loop, back at the start of the next data
* to process. This way we are able to also detect messages crossing
* two reads. */
Modes.data_len = MODES_DATA_LEN + (MODES_FULL_LEN-1)*4;
Modes.data_ready = 0;
/* Allocate the ICAO address cache. We use two uint32_t for every
* entry because it's a addr / timestamp pair for every entry. */
Modes.icao_cache = malloc(sizeof(uint32_t)*MODES_ICAO_CACHE_LEN*2);
memset(Modes.icao_cache,0,sizeof(uint32_t)*MODES_ICAO_CACHE_LEN*2);
Modes.aircrafts = NULL;
Modes.interactive_last_update = 0;
if ((Modes.data = malloc(Modes.data_len)) == NULL ||
(Modes.magnitude = malloc(Modes.data_len*2)) == NULL) {
fprintf(stderr, "Out of memory allocating data buffer.\n");
exit(1);
}
memset(Modes.data,127,Modes.data_len);
/* Populate the I/Q -> Magnitude lookup table. It is used because
* sqrt or round may be expensive and may vary a lot depending on
* the libc used.
*
* We scale to 0-255 range multiplying by 1.4 in order to ensure that
* every different I/Q pair will result in a different magnitude value,
* not losing any resolution. */
Modes.maglut = malloc(129*129*2);
for (i = 0; i <= 128; i++) {
for (q = 0; q <= 128; q++) {
Modes.maglut[i*129+q] = round(sqrt(i*i+q*q)*360);
}
}
/* Statistics */
Modes.stat_valid_preamble = 0;
Modes.stat_demodulated = 0;
Modes.stat_goodcrc = 0;
Modes.stat_badcrc = 0;
Modes.stat_fixed = 0;
Modes.stat_single_bit_fix = 0;
Modes.stat_two_bits_fix = 0;
Modes.stat_http_requests = 0;
Modes.stat_sbs_connections = 0;
Modes.stat_out_of_phase = 0;
Modes.exit = 0;
}
/* =============================== RTLSDR handling ========================== */
int modesInitRTLSDR(void) {
int j;
int device_count;
int ppm_error = 0;
char vendor[256], product[256], serial[256];
device_count = rtlsdr_get_device_count();
if (!device_count) {
fprintf(stderr, "No supported RTLSDR devices found.\n");
return(1);
}
fprintf(stderr, "Found %d device(s):\n", device_count);
for (j = 0; j < device_count; j++) {
rtlsdr_get_device_usb_strings(j, vendor, product, serial);
fprintf(stderr, "%d: %s, %s, SN: %s %s\n", j, vendor, product, serial,
(j == Modes.dev_index) ? "(currently selected)" : "");
}
if (rtlsdr_open(&Modes.dev, Modes.dev_index) < 0) {
fprintf(stderr, "Error opening the RTLSDR device: %s\n",
strerror(errno));
return(1);
}
/* Set gain, frequency, sample rate, and reset the device. */
rtlsdr_set_tuner_gain_mode(Modes.dev,
(Modes.gain == MODES_AUTO_GAIN) ? 0 : 1);
if (Modes.gain != MODES_AUTO_GAIN) {
if (Modes.gain == MODES_MAX_GAIN) {
/* Find the maximum gain available. */
int numgains;
int gains[100];
numgains = rtlsdr_get_tuner_gains(Modes.dev, gains);
Modes.gain = gains[numgains-1];
fprintf(stderr, "Max available gain is: %.2f\n", Modes.gain/10.0);
}
rtlsdr_set_tuner_gain(Modes.dev, Modes.gain);
fprintf(stderr, "Setting gain to: %.2f\n", Modes.gain/10.0);
} else {
fprintf(stderr, "Using automatic gain control.\n");
}
rtlsdr_set_freq_correction(Modes.dev, ppm_error);
if (Modes.enable_agc) rtlsdr_set_agc_mode(Modes.dev, 1);
rtlsdr_set_center_freq(Modes.dev, Modes.freq);
rtlsdr_set_sample_rate(Modes.dev, MODES_DEFAULT_RATE);
rtlsdr_reset_buffer(Modes.dev);
fprintf(stderr, "Gain reported by device: %.2f\n",
rtlsdr_get_tuner_gain(Modes.dev)/10.0);
Modes.rtl_enabled = 1;
Modes.hackrf_enabled = 0;
Modes.airspy_enabled = 0;
Modes.sdrplay_enabled = 0;
return (0);
}
/* =============================== AirSpy handling ========================== */
int modesInitAirSpy(void) {
#define AIRSPY_STATUS(status, message) \
if (status != 0) { \
fprintf(stderr, "%s\n", message); \
airspy_close(Modes.airspy); \
airspy_exit(); \
return (1); \
} \
int status;
soxr_error_t sox_err = NULL;
soxr_io_spec_t ios;
soxr_quality_spec_t qts;
soxr_runtime_spec_t rts;
Modes.airspy_scratch = calloc(2*MODES_DATA_LEN, sizeof(int16_t));
Modes.airspy_bytes = malloc(2*MODES_DATA_LEN);
if ((Modes.airspy_bytes == NULL) || (Modes.airspy_scratch == NULL))
err(1, NULL);
ios = soxr_io_spec(SOXR_INT16_I, SOXR_INT16_I);
qts = soxr_quality_spec(SOXR_MQ, 0);
rts = soxr_runtime_spec(2);
Modes.resampler = soxr_create(10, 2, 2, &sox_err, &ios, &qts, &rts);
if (sox_err) {
int e = errno;
fprintf(stderr, "soxr_create: %s; %s\n", soxr_strerror(sox_err), strerror(errno));
return e;
}
status = airspy_init();
AIRSPY_STATUS(status, "airspy_init failed.");
status = airspy_open(&Modes.airspy);
AIRSPY_STATUS(status, "No AirSpy compatible devices found.");
if ((Modes.rf_gain + Modes.lna_gain + Modes.vga_gain) == 0) {
Modes.rf_gain = AIRSPY_RF_GAIN;
Modes.lna_gain = AIRSPY_LNA_GAIN;
Modes.vga_gain = AIRSPY_VGA_GAIN;
}
status = airspy_set_freq(Modes.airspy, Modes.freq);
AIRSPY_STATUS(status, "airspy_set_freq failed.");
status = airspy_set_sample_type(Modes.airspy, AIRSPY_SAMPLE_INT16_IQ);
AIRSPY_STATUS(status, "airspy_set_sample_type failed.");
status = airspy_set_samplerate(Modes.airspy, AIRSPY_SAMPLERATE_10MSPS);
AIRSPY_STATUS(status, "airspy_set_samplerate failed.");
status = airspy_set_mixer_gain(Modes.airspy, Modes.rf_gain != 0);
AIRSPY_STATUS(status, "airspy_set_mixer_gain failed.");
status = airspy_set_lna_gain(Modes.airspy, Modes.lna_gain);
AIRSPY_STATUS(status, "airspy_set_lna_gain failed.");
status = airspy_set_vga_gain(Modes.airspy, Modes.vga_gain);
AIRSPY_STATUS(status, "airspy_set_vga_gain failed");
if (Modes.enable_agc) {
airspy_set_mixer_agc(Modes.airspy, 1);
AIRSPY_STATUS(status, "airspy_set_mixer_agc failed");
airspy_set_lna_agc(Modes.airspy, 1);
AIRSPY_STATUS(status, "airspy_set_lna_agc failed");
}
fprintf (stderr, "AirSpy successfully initialized "
"(RF Gain: %i, LNA Gain: %i, VGA Gain: %i, AGC: %i).\n",
Modes.rf_gain, Modes.lna_gain, Modes.vga_gain, Modes.enable_agc);
Modes.airspy_enabled = 1;
Modes.rtl_enabled = 0;
Modes.hackrf_enabled = 0;
Modes.sdrplay_enabled = 0;
return (0);
}
/* =============================== HackRF One handling ========================== */
int modesInitHackRF(void) {
#define HACKRF_STATUS(status, message) \
if (status != 0) { \
fprintf(stderr, "%s\n", message); \
hackrf_close(Modes.hackrf); \
hackrf_exit(); \
return (1); \
} \
int status;
status = hackrf_init();
HACKRF_STATUS(status, "hackrf_init failed.");
status = hackrf_open(&Modes.hackrf);
HACKRF_STATUS(status, "No HackRF compatible devices found.");
if ((Modes.lna_gain + Modes.vga_gain) == 0) {
Modes.lna_gain = HACKRF_LNA_GAIN;
Modes.vga_gain = HACKRF_VGA_GAIN;
}
status = hackrf_set_freq(Modes.hackrf, Modes.freq);
HACKRF_STATUS(status, "hackrf_set_freq failed.");
status = hackrf_set_sample_rate(Modes.hackrf, MODES_DEFAULT_RATE);
HACKRF_STATUS(status, "hackrf_set_sample_rate failed.");
status = hackrf_set_amp_enable(Modes.hackrf, Modes.rf_gain != 0);
HACKRF_STATUS(status, "hackrf_set_amp_enable failed.");
status = hackrf_set_lna_gain(Modes.hackrf, Modes.lna_gain);
HACKRF_STATUS(status, "hackrf_set_lna_gain failed.");
status = hackrf_set_vga_gain(Modes.hackrf, Modes.vga_gain);
HACKRF_STATUS(status, "hackrf_set_vga_gain failed");
fprintf (stderr, "HackRF successfully initialized "
"(AMP Enable: %i, LNA Gain: %i, VGA Gain: %i).\n",
Modes.rf_gain, Modes.lna_gain, Modes.vga_gain);
Modes.hackrf_enabled = 1;
Modes.airspy_enabled = 0;
Modes.rtl_enabled = 0;
Modes.sdrplay_enabled = 0;
return (0);
}
/* =============================== SDRplay handling ========================== */
int modesInitSDRplay(void) {
mir_sdr_ErrT err;
float ver;
/* Check API version */
err = mir_sdr_ApiVersion(&ver);
if (err || (ver != MIR_SDR_API_VERSION)) {
fprintf(stderr, "Incorrect API version %f\n", ver);
return (1);
}
mir_sdr_SetParam(201,1);
mir_sdr_SetParam(202,0);
/* Initialize SDRplay device */
err = mir_sdr_Init (9, 8.000, 1090.048, mir_sdr_BW_1_536, mir_sdr_IF_2_048, &Modes.sdrplaySamplesPerPacket);
if (err){
fprintf(stderr, "Unable to initialize RSP\n");
return (1);
}
/* Allocate 16-bit I and Q buffers */
Modes.sdrplay_i = malloc (Modes.sdrplaySamplesPerPacket * sizeof(short));
Modes.sdrplay_q = malloc (Modes.sdrplaySamplesPerPacket * sizeof(short));
if ((Modes.sdrplay_i == NULL) || (Modes.sdrplay_q == NULL)){
fprintf(stderr, "Insufficient memory for buffers\n");
return (1);
}
/* Configure DC tracking in tuner */
err = mir_sdr_SetDcMode(4,0);
err |= mir_sdr_SetDcTrackTime(63);
if (err){
fprintf(stderr, "Set DC tracking failed, %d\n", err);
return (1);
}
Modes.sdrplay_enabled = 1;
Modes.hackrf_enabled = 0;
Modes.airspy_enabled = 0;
Modes.rtl_enabled = 0;
return (0);
}
/* We use a thread reading data in background, while the main thread
* handles decoding and visualization of data to the user.
*
* The reading thread calls the RTLSDR API to read data asynchronously, and
* uses a callback to populate the data buffer.
* A Mutex is used to avoid races with the decoding thread. */
void rtlsdrCallback(unsigned char *buf, uint32_t len, void *ctx) {
MODES_NOTUSED(ctx);
pthread_mutex_lock(&Modes.data_mutex);
if (len > MODES_DATA_LEN) len = MODES_DATA_LEN;
/* Move the last part of the previous buffer, that was not processed,
* on the start of the new buffer. */
memcpy(Modes.data, Modes.data+MODES_DATA_LEN, (MODES_FULL_LEN-1)*4);
/* Read the new data. */
memcpy(Modes.data+(MODES_FULL_LEN-1)*4, buf, len);
Modes.data_ready = 1;
/* Signal to the other thread that new data is ready */
pthread_cond_signal(&Modes.data_cond);
pthread_mutex_unlock(&Modes.data_mutex);
}
int hackrfCallback (hackrf_transfer *transfer) {
uint32_t i;
pthread_mutex_lock(&Modes.data_mutex);
uint32_t len = transfer-> buffer_length;
/* HackRF One returns signed IQ values, convert them to unsigned */
for (i = 0; i < len; i++) {
transfer->buffer[i] ^= (uint8_t)0x80;
}
if (len > MODES_DATA_LEN) len = MODES_DATA_LEN;
/* Move the last part of the previous buffer, that was not processed,
* on the start of the new buffer. */
memcpy(Modes.data, Modes.data+MODES_DATA_LEN, (MODES_FULL_LEN-1)*4);
/* Read the new data. */
memcpy(Modes.data+(MODES_FULL_LEN-1)*4, transfer->buffer, len);
Modes.data_ready = 1;
/* Signal to the other thread that new data is ready */
pthread_cond_signal(&Modes.data_cond);
pthread_mutex_unlock(&Modes.data_mutex);
return (0);
}
int airspyCallback (airspy_transfer *transfer) {
pthread_mutex_lock(&Modes.data_mutex);
int16_t *inptr = (int16_t *)transfer->samples;
int16_t *outptr = (int16_t *)Modes.airspy_scratch;
size_t i, i_done, o_done, i_len, len;
i_len = transfer->sample_count;
len = 4 * i_len / 5; // downsample from 2.5Msps to 2Msps
soxr_process(Modes.resampler, inptr, i_len, &i_done, outptr, len, &o_done);
for(i = 0; i < o_done; i++)
Modes.airspy_bytes[i] = (int8_t)(outptr[i]>>4)+127;
len = o_done;
if (len > MODES_DATA_LEN) len = MODES_DATA_LEN;
/* Move the last part of the previous buffer, that was not processed,
* on the start of the new buffer. */
memcpy(Modes.data, Modes.data+MODES_DATA_LEN, (MODES_FULL_LEN-1)*4);
/* Read the new data. */
memcpy(Modes.data+(MODES_FULL_LEN-1)*4, Modes.airspy_bytes, len);
Modes.data_ready = 1;
/* Signal to the other thread that new data is ready */
pthread_cond_signal(&Modes.data_cond);
pthread_mutex_unlock(&Modes.data_mutex);
return (0);
}
/* This is used when --ifile is specified in order to read data from file
* instead of using an RTLSDR device. */
void readDataFromFile(void) {
pthread_mutex_lock(&Modes.data_mutex);
while(1) {
ssize_t nread, toread;
unsigned char *p;
if (Modes.data_ready) {
pthread_cond_wait(&Modes.data_cond,&Modes.data_mutex);
continue;
}
if (Modes.interactive) {
/* When --ifile and --interactive are used together, slow down
* playing at the natural rate of the RTLSDR received. */
pthread_mutex_unlock(&Modes.data_mutex);
usleep(5000);
pthread_mutex_lock(&Modes.data_mutex);
}
/* Move the last part of the previous buffer, that was not processed,
* on the start of the new buffer. */
memcpy(Modes.data, Modes.data+MODES_DATA_LEN, (MODES_FULL_LEN-1)*4);
toread = MODES_DATA_LEN;
p = Modes.data+(MODES_FULL_LEN-1)*4;
while(toread) {
nread = read(Modes.fd, p, toread);
if (nread <= 0) {
Modes.exit = 1; /* Signal the other thread to exit. */
break;
}
p += nread;
toread -= nread;
}
if (toread) {
/* Not enough data on file to fill the buffer? Pad with
* no signal. */
memset(p,127,toread);
}
Modes.data_ready = 1;
/* Signal to the other thread that new data is ready */
pthread_cond_signal(&Modes.data_cond);
}
}
int sdrplay_start_rx(void) {
unsigned int data_index, firstSampleNum;
int grChanged, rfChanged, fsChanged;
int input_index = Modes.sdrplaySamplesPerPacket;
mir_sdr_ErrT err = 0;
pthread_mutex_lock(&Modes.data_mutex);
while(1)
{
if (Modes.data_ready) {
pthread_cond_wait(&Modes.data_cond,&Modes.data_mutex);
continue;
}
/* Move the last part of the previous buffer, that was not processed,
* on the start of the new buffer. */
memcpy(Modes.magnitude, Modes.magnitude+MODES_DATA_LEN, (MODES_FULL_LEN-1)*4);
/* now read new data buffer */
data_index = (MODES_FULL_LEN-1)*2;
while (data_index < ((MODES_DATA_LEN/2) + (MODES_FULL_LEN-1)*2))
{
/* copy available data into buffer */
while ((data_index < (MODES_DATA_LEN/2 + (MODES_FULL_LEN-1)*2)) && (input_index < Modes.sdrplaySamplesPerPacket))
{
int sum = abs(Modes.sdrplay_i[input_index++]);
sum += abs(Modes.sdrplay_i[input_index++]);
sum += abs(Modes.sdrplay_i[input_index++]);
sum += abs(Modes.sdrplay_i[input_index++]);
sum = sum >> 2;
if (sum > 32767) sum = 32767;
Modes.magnitude[data_index++] = sum;
}
if (input_index > Modes.sdrplaySamplesPerPacket) {
fprintf(stderr, "ERROR packet size not divisible by 4\n");
Modes.exit = 1; /* Signal the other thread to exit. */
break;
}
if (input_index == Modes.sdrplaySamplesPerPacket)
{
input_index = 0;
err = mir_sdr_ReadPacket (Modes.sdrplay_i, Modes.sdrplay_q,
&firstSampleNum, &grChanged, &rfChanged, &fsChanged);
if (err){
fprintf(stderr, "sdrplay data read failed\n");
Modes.exit = 1; /* Signal the other thread to exit. */
break;
}
}
}
Modes.data_ready = 1;
/* Signal to the other thread that new data is ready */
pthread_cond_signal(&Modes.data_cond);
}
return (err)? 1 : 0;
}
/* We read data using a thread, so the main thread only handles decoding
* without caring about data acquisition. */
void *readerThreadEntryPoint(void *arg) {
MODES_NOTUSED(arg);
if (Modes.filename == NULL) {
if (Modes.rtl_enabled) {
rtlsdr_read_async(Modes.dev, rtlsdrCallback, NULL,
MODES_ASYNC_BUF_NUMBER,
MODES_DATA_LEN);
} else if (Modes.hackrf_enabled) {
int status = hackrf_start_rx(Modes.hackrf, hackrfCallback, NULL);
if (status != 0) {
fprintf(stderr, "hackrf_start_rx failed");
hackrf_close(Modes.hackrf);
hackrf_exit();
exit (1);
}
} else if (Modes.airspy_enabled) {
int status = airspy_start_rx(Modes.airspy, airspyCallback, NULL);
if (status != 0) {
fprintf(stderr, "airspy_start_rx failed");
airspy_close(Modes.airspy);
airspy_exit();
exit (1);
}
} else if (Modes.sdrplay_enabled) {
int status = sdrplay_start_rx();
if (status != 0) {
fprintf(stderr, "sdrplay_start_rx failed");
mir_sdr_Uninit();
exit (1);
}
}
} else {
readDataFromFile();
}
return NULL;
}
/* ============================== Debugging ================================= */
/* Helper function for dumpMagnitudeVector().
* It prints a single bar used to display raw signals.
*
* Since every magnitude sample is between 0-255, the function uses
* up to 63 characters for every bar. Every character represents
* a length of 4, 3, 2, 1, specifically:
*
* "O" is 4
* "o" is 3
* "-" is 2
* "." is 1
*/
void dumpMagnitudeBar(int index, int magnitude) {
char *set = " .-o";
char buf[256];
int div = magnitude / 256 / 4;
int rem = magnitude / 256 % 4;
memset(buf,'O',div);
buf[div] = set[rem];
buf[div+1] = '\0';
if (index >= 0)
printf("[%.3d] |%-66s %d\n", index, buf, magnitude);
else
printf("[%.2d] |%-66s %d\n", index, buf, magnitude);
}
/* Display an ASCII-art alike graphical representation of the undecoded
* message as a magnitude signal.
*
* The message starts at the specified offset in the "m" buffer.
* The function will display enough data to cover a short 56 bit message.
*
* If possible a few samples before the start of the messsage are included
* for context. */
void dumpMagnitudeVector(uint16_t *m, uint32_t offset) {
uint32_t padding = 5; /* Show a few samples before the actual start. */
uint32_t start = (offset < padding) ? 0 : offset-padding;
uint32_t end = offset + (MODES_PREAMBLE_US*2)+(MODES_SHORT_MSG_BITS*2) - 1;
uint32_t j;
for (j = start; j <= end; j++) {
dumpMagnitudeBar(j-offset, m[j]);
}
}
/* Produce a raw representation of the message as a Javascript file
* loadable by debug.html. */
void dumpRawMessageJS(char *descr, unsigned char *msg,
uint16_t *m, uint32_t offset, int fixable)
{
int padding = 5; /* Show a few samples before the actual start. */
int start = offset - padding;
int end = offset + (MODES_PREAMBLE_US*2)+(MODES_LONG_MSG_BITS*2) - 1;
FILE *fp;
int j, fix1 = -1, fix2 = -1;
if (fixable != -1) {
fix1 = fixable & 0xff;
if (fixable > 255) fix2 = fixable >> 8;
}
if ((fp = fopen("frames.js","a")) == NULL) {
fprintf(stderr, "Error opening frames.js: %s\n", strerror(errno));
exit(1);
}
fprintf(fp,"frames.push({\"descr\": \"%s\", \"mag\": [", descr);
for (j = start; j <= end; j++) {
fprintf(fp,"%d", j < 0 ? 0 : m[j]);
if (j != end) fprintf(fp,",");
}
fprintf(fp,"], \"fix1\": %d, \"fix2\": %d, \"bits\": %d, \"hex\": \"",
fix1, fix2, modesMessageLenByType(msg[0]>>3));
for (j = 0; j < MODES_LONG_MSG_BYTES; j++)
fprintf(fp,"\\x%02x",msg[j]);
fprintf(fp,"\"});\n");
fclose(fp);
}
/* This is a wrapper for dumpMagnitudeVector() that also show the message
* in hex format with an additional description.
*
* descr is the additional message to show to describe the dump.
* msg points to the decoded message
* m is the original magnitude vector
* offset is the offset where the message starts
*
* The function also produces the Javascript file used by debug.html to
* display packets in a graphical format if the Javascript output was
* enabled.
*/
void dumpRawMessage(char *descr, unsigned char *msg,
uint16_t *m, uint32_t offset)
{
int j;
int msgtype = msg[0]>>3;
int fixable = -1;
if (msgtype == 11 || msgtype == 17) {
int msgbits = (msgtype == 11) ? MODES_SHORT_MSG_BITS :
MODES_LONG_MSG_BITS;
fixable = fixSingleBitErrors(msg,msgbits);
if (fixable == -1)
fixable = fixTwoBitsErrors(msg,msgbits);
}
if (Modes.debug & MODES_DEBUG_JS) {
dumpRawMessageJS(descr, msg, m, offset, fixable);
return;
}
printf("\n--- %s\n ", descr);
for (j = 0; j < MODES_LONG_MSG_BYTES; j++) {
printf("%02x",msg[j]);
if (j == MODES_SHORT_MSG_BYTES-1) printf(" ... ");
}
printf(" (DF %d, Fixable: %d)\n", msgtype, fixable);
dumpMagnitudeVector(m,offset);
printf("---\n\n");
}
/* ===================== Mode S detection and decoding ===================== */
/* Parity table for MODE S Messages.
* The table contains 112 elements, every element corresponds to a bit set
* in the message, starting from the first bit of actual data after the
* preamble.
*
* For messages of 112 bit, the whole table is used.
* For messages of 56 bits only the last 56 elements are used.
*
* The algorithm is as simple as xoring all the elements in this table
* for which the corresponding bit on the message is set to 1.
*
* The latest 24 elements in this table are set to 0 as the checksum at the
* end of the message should not affect the computation.
*
* Note: this function can be used with DF11 and DF17, other modes have
* the CRC xored with the sender address as they are reply to interrogations,
* but a casual listener can't split the address from the checksum.
*/
uint32_t modes_checksum_table[112] = {
0x3935ea, 0x1c9af5, 0xf1b77e, 0x78dbbf, 0xc397db, 0x9e31e9, 0xb0e2f0, 0x587178,
0x2c38bc, 0x161c5e, 0x0b0e2f, 0xfa7d13, 0x82c48d, 0xbe9842, 0x5f4c21, 0xd05c14,
0x682e0a, 0x341705, 0xe5f186, 0x72f8c3, 0xc68665, 0x9cb936, 0x4e5c9b, 0xd8d449,
0x939020, 0x49c810, 0x24e408, 0x127204, 0x093902, 0x049c81, 0xfdb444, 0x7eda22,
0x3f6d11, 0xe04c8c, 0x702646, 0x381323, 0xe3f395, 0x8e03ce, 0x4701e7, 0xdc7af7,
0x91c77f, 0xb719bb, 0xa476d9, 0xadc168, 0x56e0b4, 0x2b705a, 0x15b82d, 0xf52612,
0x7a9309, 0xc2b380, 0x6159c0, 0x30ace0, 0x185670, 0x0c2b38, 0x06159c, 0x030ace,
0x018567, 0xff38b7, 0x80665f, 0xbfc92b, 0xa01e91, 0xaff54c, 0x57faa6, 0x2bfd53,
0xea04ad, 0x8af852, 0x457c29, 0xdd4410, 0x6ea208, 0x375104, 0x1ba882, 0x0dd441,
0xf91024, 0x7c8812, 0x3e4409, 0xe0d800, 0x706c00, 0x383600, 0x1c1b00, 0x0e0d80,
0x0706c0, 0x038360, 0x01c1b0, 0x00e0d8, 0x00706c, 0x003836, 0x001c1b, 0xfff409,
0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000,
0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000,
0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000
};
uint32_t modesChecksum(unsigned char *msg, int bits) {