-
Notifications
You must be signed in to change notification settings - Fork 20
/
dump1090.c
2046 lines (1783 loc) · 78.7 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
// Part of dump1090, a Mode S message decoder for RTLSDR devices.
//
// dump1090.c: main program & miscellany
//
// Copyright (c) 2014-2016 Oliver Jowett <[email protected]>
//
// This file is free software: you may copy, redistribute and/or modify it
// under the terms of the GNU General Public License as published by the
// Free Software Foundation, either version 2 of the License, or (at your
// option) any later version.
//
// This file 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/>.
// This file incorporates work covered by the following copyright and
// permission notice:
//
// Copyright (C) 2012 by Salvatore Sanfilippo <[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 "dump1090.h"
#include <rtl-sdr.h>
#include <stdarg.h>
#define MAX_RSP_DEVS 16
static int verbose_device_search(char *s);
sdrplay_api_DeviceT devs[MAX_RSP_DEVS];
//
// ============================= Utility functions ==========================
//
static void log_with_timestamp(const char *format, ...) __attribute__((format (printf, 1, 2) ));
static void log_with_timestamp(const char *format, ...)
{
char timebuf[128];
char msg[1024];
time_t now;
struct tm local;
va_list ap;
now = time(NULL);
localtime_r(&now, &local);
strftime(timebuf, 128, "%c %Z", &local);
timebuf[127] = 0;
va_start(ap, format);
vsnprintf(msg, 1024, format, ap);
va_end(ap);
msg[1023] = 0;
fprintf(stderr, "%s %s\n", timebuf, msg);
}
static void sigintHandler(int dummy) {
MODES_NOTUSED(dummy);
sdrplay_api_ErrT err;
int reint = 0;
if(slaveAttached == 1) {
if (Modes.interactive) {
Modes.interactive = 0;
reint = 1;
}
fprintf(stderr, "\nUnable to close this application.\n\nAnother application is currently using the slave tuner.\nPlease close the application that is currently using the slave tuner\nbefore attempting to close this application.\nPress ENTER key to continue\n");
getchar();
if (reint == 1) {
Modes.interactive = 1;
reint = 0;
}
return;
}
signal(SIGINT, SIG_DFL); // reset signal handler - bit extra safety
Modes.exit = 1; // Signal to threads that we are done
pthread_cond_signal(&Modes.exit_cond); // tell reader thread to exit (only needed for sdrplay)
log_with_timestamp("Caught SIGINT, shutting down..\n");
err = sdrplay_api_Uninit(chosenDev->dev);
if (err != sdrplay_api_Success) {
if (Modes.interactive) {
Modes.interactive = 0;
}
fprintf(stderr, "sdrplay_api_Uninit error: %s\n", sdrplay_api_GetErrorString(err));
}
err = sdrplay_api_ReleaseDevice(chosenDev);
if (err != sdrplay_api_Success) {
if (Modes.interactive) {
Modes.interactive = 0;
}
fprintf(stderr, "sdrplay_api_ReleaseDevice error: %s\n", sdrplay_api_GetErrorString(err));
}
err = sdrplay_api_Close();
if (err != sdrplay_api_Success) {
if (Modes.interactive) {
Modes.interactive = 0;
}
fprintf(stderr, "sdrplay_api_Close error: %s\n", sdrplay_api_GetErrorString(err));
}
}
static void sigtermHandler(int dummy) {
MODES_NOTUSED(dummy);
signal(SIGTERM, SIG_DFL); // reset signal handler - bit extra safety
Modes.exit = 1; // Signal to threads that we are done
pthread_cond_signal(&Modes.exit_cond); // tell reader thread to exit (only needed for sdrplay)
log_with_timestamp("Caught SIGTERM, shutting down..\n");
}
//
// =============================== Terminal handling ========================
//
#ifndef _WIN32
// Get the number of rows after the terminal changes size.
int getTermRows() {
struct winsize w;
ioctl(STDOUT_FILENO, TIOCGWINSZ, &w);
return w.ws_row;
}
// Handle resizing terminal
void sigWinchCallback() {
signal(SIGWINCH, SIG_IGN);
Modes.interactive_rows = getTermRows();
interactiveShowData();
signal(SIGWINCH, sigWinchCallback);
}
#else
int getTermRows() { return MODES_INTERACTIVE_ROWS;}
#endif
static void start_cpu_timing(struct timespec *start_time)
{
clock_gettime(CLOCK_THREAD_CPUTIME_ID, start_time);
}
static void end_cpu_timing(const struct timespec *start_time, struct timespec *add_to)
{
struct timespec end_time;
clock_gettime(CLOCK_THREAD_CPUTIME_ID, &end_time);
add_to->tv_sec += (end_time.tv_sec - start_time->tv_sec - 1);
add_to->tv_nsec += (1000000000L + end_time.tv_nsec - start_time->tv_nsec);
add_to->tv_sec += add_to->tv_nsec / 1000000000L;
add_to->tv_nsec = add_to->tv_nsec % 1000000000L;
}
//
// =============================== Initialization ===========================
//
void modesInitConfig(void) {
// Default everything to zero/NULL
memset(&Modes, 0, sizeof(Modes));
// Now initialise things that should not be 0/NULL to their defaults
Modes.use_rtlsdr = 1;
Modes.gr = MODES_RSP_INITIAL_GR;
Modes.max_sig = RSP_MIN_GAIN_THRESH << RSP_ACC_SHIFT;
Modes.gain = MODES_MAX_GAIN;
Modes.freq = MODES_DEFAULT_FREQ;
Modes.ppm_error = MODES_DEFAULT_PPM;
Modes.check_crc = 1;
Modes.net_heartbeat_interval = MODES_NET_HEARTBEAT_INTERVAL;
Modes.net_input_raw_ports = strdup("30001");
Modes.net_output_raw_ports = strdup("30002");
Modes.net_output_sbs_ports = strdup("30003");
Modes.net_input_beast_ports = strdup("30004,30104");
Modes.net_output_beast_ports = strdup("30005");
Modes.net_http_ports = strdup("8080");
Modes.interactive_rows = getTermRows();
Modes.interactive_display_ttl = MODES_INTERACTIVE_DISPLAY_TTL;
Modes.html_dir = HTMLPATH;
Modes.json_interval = 1000;
Modes.json_location_accuracy = 1;
Modes.maxRange = 1852 * 300; // 300NM default max range
#ifdef SDRPLAY
Modes.antenna_port = sdrplay_api_Rsp2_ANTENNA_B;
Modes.Dxantenna_port = sdrplay_api_RspDx_ANTENNA_B;
Modes.tuner = sdrplay_api_Tuner_B; // RSPduo default
Modes.mode = sdrplay_api_RspDuoMode_Master; // RSPduo default
Modes.bwMode = 1; // 5 MHz
Modes.adsbMode = 1; // for ZIF
#endif
}
//
//=========================================================================
//
void modesInit(void) {
int i, q;
pthread_mutex_init(&Modes.data_mutex,NULL);
pthread_cond_init(&Modes.data_cond,NULL);
pthread_mutex_init(&Modes.exit_mutex,NULL);
pthread_cond_init(&Modes.exit_cond,NULL);
if (Modes.oversample)
Modes.sample_rate = (Modes.use_rtlsdr) ? 2400000 : 8000000;
else
Modes.sample_rate = 2000000.0;
// arrays for demod_8000 if used.
if (Modes.sample_rate == 8000000)
{
Modes.d8m_match_ar = malloc(D8M_WIN_LEN * sizeof(int));
Modes.d8m_phase_ar = malloc(D8M_WIN_LEN * sizeof(int));
Modes.d8m_dbuf = malloc((D8M_BUF_OVERLAP + MODES_MAG_BUF_SAMPLES) * sizeof(int));
if ((Modes.d8m_match_ar==NULL) || (Modes.d8m_phase_ar==NULL) ||(Modes.d8m_dbuf==NULL))
{
fprintf(stderr, "Out of memory allocating data buffer.\n");
exit(1);
}
memset (Modes.d8m_dbuf, 0, (D8M_BUF_OVERLAP + MODES_MAG_BUF_SAMPLES) * sizeof(int));
}
// Allocate the various buffers used by Modes
Modes.trailing_samples = (MODES_PREAMBLE_US + MODES_LONG_MSG_BITS + 16) * 1e-6 * Modes.sample_rate;
if ( ((Modes.maglut = (uint16_t *) malloc(sizeof(uint16_t) * 256 * 256) ) == NULL) ||
((Modes.log10lut = (uint16_t *) malloc(sizeof(uint16_t) * 256 * 256) ) == NULL) )
{
fprintf(stderr, "Out of memory allocating data buffer.\n");
exit(1);
}
for (i = 0; i < MODES_MAG_BUFFERS; ++i) {
if ( (Modes.mag_buffers[i].data = calloc(MODES_MAG_BUF_SAMPLES+Modes.trailing_samples, sizeof(uint16_t))) == NULL ) {
fprintf(stderr, "Out of memory allocating magnitude buffer.\n");
exit(1);
}
Modes.mag_buffers[i].length = 0;
Modes.mag_buffers[i].dropped = 0;
Modes.mag_buffers[i].sampleTimestamp = 0;
}
// Validate the users Lat/Lon home location inputs
if ( (Modes.fUserLat > 90.0) // Latitude must be -90 to +90
|| (Modes.fUserLat < -90.0) // and
|| (Modes.fUserLon > 360.0) // Longitude must be -180 to +360
|| (Modes.fUserLon < -180.0) ) {
Modes.fUserLat = Modes.fUserLon = 0.0;
} else if (Modes.fUserLon > 180.0) { // If Longitude is +180 to +360, make it -180 to 0
Modes.fUserLon -= 360.0;
}
// If both Lat and Lon are 0.0 then the users location is either invalid/not-set, or (s)he's in the
// Atlantic ocean off the west coast of Africa. This is unlikely to be correct.
// Set the user LatLon valid flag only if either Lat or Lon are non zero. Note the Greenwich meridian
// is at 0.0 Lon,so we must check for either fLat or fLon being non zero not both.
// Testing the flag at runtime will be much quicker than ((fLon != 0.0) || (fLat != 0.0))
Modes.bUserFlags &= ~MODES_USER_LATLON_VALID;
if ((Modes.fUserLat != 0.0) || (Modes.fUserLon != 0.0)) {
Modes.bUserFlags |= MODES_USER_LATLON_VALID;
}
// Limit the maximum requested raw output size to less than one Ethernet Block
if (Modes.net_output_flush_size > (MODES_OUT_FLUSH_SIZE))
{Modes.net_output_flush_size = MODES_OUT_FLUSH_SIZE;}
if (Modes.net_output_flush_interval > (MODES_OUT_FLUSH_INTERVAL))
{Modes.net_output_flush_interval = MODES_OUT_FLUSH_INTERVAL;}
if (Modes.net_sndbuf_size > (MODES_NET_SNDBUF_MAX))
{Modes.net_sndbuf_size = MODES_NET_SNDBUF_MAX;}
// compute UC8 magnitude lookup table
for (i = 0; i <= 255; i++) {
for (q = 0; q <= 255; q++) {
float fI, fQ, magsq;
fI = (i - 127.5) / 127.5;
fQ = (q - 127.5) / 127.5;
magsq = fI * fI + fQ * fQ;
if (magsq > 1)
magsq = 1;
Modes.maglut[le16toh((i*256)+q)] = (uint16_t) round(sqrtf(magsq) * 65535.0);
}
}
// Prepare the log10 lookup table: 100log10(x)
Modes.log10lut[0] = 0; // poorly defined..
for (i = 1; i <= 65535; i++) {
Modes.log10lut[i] = (uint16_t) round(100.0 * log10(i));
}
// Prepare error correction tables
modesChecksumInit(Modes.nfix_crc);
icaoFilterInit();
if (Modes.show_only)
icaoFilterAdd(Modes.show_only);
// Prepare sample conversion
if (!Modes.net_only) {
if (Modes.filename == NULL) {
if (Modes.use_sdrplay)
Modes.input_format = INPUT_SC16;
else
// using a real RTLSDR, use UC8 input always
Modes.input_format = INPUT_UC8;
}
Modes.converter_function = init_converter(Modes.input_format,
Modes.sample_rate,
Modes.dc_filter,
Modes.measure_noise, /* total power is interesting if we want noise */
&Modes.converter_state);
if (!Modes.converter_function) {
fprintf(stderr, "Can't initialize sample converter, giving up.\n");
exit(1);
}
}
}
static void convert_samples(void *iq,
uint16_t *mag,
unsigned nsamples,
double *power)
{
Modes.converter_function(iq, mag, nsamples, Modes.converter_state, power);
}
//
// =============================== RTLSDR handling ==========================
//
int modesInitRTLSDR(void) {
int j;
int device_count, dev_index = 0;
char vendor[256], product[256], serial[256];
if (Modes.dev_name) {
if ( (dev_index = verbose_device_search(Modes.dev_name)) < 0 )
return -1;
}
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 == dev_index) ? "(currently selected)" : "");
}
if (rtlsdr_open(&Modes.dev, 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) {
int *gains;
int numgains;
numgains = rtlsdr_get_tuner_gains(Modes.dev, NULL);
if (numgains <= 0) {
fprintf(stderr, "Error getting tuner gains\n");
return -1;
}
gains = malloc(numgains * sizeof(int));
if (rtlsdr_get_tuner_gains(Modes.dev, gains) != numgains) {
fprintf(stderr, "Error getting tuner gains\n");
free(gains);
return -1;
}
if (Modes.gain == MODES_MAX_GAIN) {
int highest = -1;
int i;
for (i = 0; i < numgains; ++i) {
if (gains[i] > highest)
highest = gains[i];
}
Modes.gain = highest;
fprintf(stderr, "Max available gain is: %.2f dB\n", Modes.gain/10.0);
} else {
int closest = -1;
int i;
for (i = 0; i < numgains; ++i) {
if (closest == -1 || abs(gains[i] - Modes.gain) < abs(closest - Modes.gain))
closest = gains[i];
}
if (closest != Modes.gain) {
Modes.gain = closest;
fprintf(stderr, "Closest available gain: %.2f dB\n", Modes.gain/10.0);
}
}
free(gains);
fprintf(stderr, "Setting gain to: %.2f dB\n", Modes.gain/10.0);
if (rtlsdr_set_tuner_gain(Modes.dev, Modes.gain) < 0) {
fprintf(stderr, "Error setting tuner gains\n");
return -1;
}
} else {
fprintf(stderr, "Using automatic gain control.\n");
}
rtlsdr_set_freq_correction(Modes.dev, Modes.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, (unsigned)Modes.sample_rate);
rtlsdr_reset_buffer(Modes.dev);
fprintf(stderr, "Gain reported by device: %.2f dB\n",
rtlsdr_get_tuner_gain(Modes.dev)/10.0);
return 0;
}
/* =============================== SDRplay handling ========================== */
#ifdef SDRPLAY
#define LNA_STATE_FOR_MAX_GAIN 0
void sdrplayCallbackA(short *xi, short *xq, sdrplay_api_StreamCbParamsT *params, unsigned int numSamples, unsigned int reset, void *cbContext);
void sdrplayCallbackB(short *xi, short *xq, sdrplay_api_StreamCbParamsT *params, unsigned int numSamples, unsigned int reset, void *cbContext);
void sdrplayEventCallback(sdrplay_api_EventT eventId, sdrplay_api_TunerSelectT tuner, sdrplay_api_EventParamsT *params, void *cbContext);
int modesInitSDRplay(void) {
sdrplay_api_ErrT err;
float ver;
unsigned int ndevs = 0;
unsigned int i;
unsigned int devIdx;
int reint = 0;
slaveAttached = 0;
/* Allocate data buffers */
Modes.sdrplay_data = malloc(MODES_RSP_BUF_SIZE * MODES_RSP_BUFFERS * sizeof(short));
if (Modes.sdrplay_data == NULL){
if(Modes.interactive) {
Modes.interactive = 0;
}
fprintf(stderr, "Insufficient memory for buffers\n");
return 1;
}
err = sdrplay_api_Open();
if(err != sdrplay_api_Success) {
if(Modes.interactive) {
Modes.interactive = 0;
}
fprintf(stderr, "dump1090: Open error (%s)\n", sdrplay_api_GetErrorString(err));
return 1;
}
#if 0
err = sdrplay_api_DebugEnable(NULL, 1);
if (err != sdrplay_api_Success) {
if(Modes.interactive) {
Modes.interactive = 0;
}
fprintf(stderr, "dump1090: DebugEnable error (%s)\n", sdrplay_api_GetErrorString(err));
return 1;
}
#endif
/* Check API version */
sdrplay_api_ApiVersion(&ver);
if (ver < (float)(3.06)) {
if(Modes.interactive) {
Modes.interactive = 0;
}
fprintf(stderr, "Incorrect API version %.2f\n", ver);
return 1;
}
err = sdrplay_api_LockDeviceApi();
if (err != sdrplay_api_Success) {
if(Modes.interactive) {
Modes.interactive = 0;
}
fprintf(stderr, "dump1090: LockDeviceApi error (%s)\n", sdrplay_api_GetErrorString(err));
return 1;
}
err = sdrplay_api_GetDevices(devs, &ndevs, MAX_RSP_DEVS);
if (err != sdrplay_api_Success) {
if(Modes.interactive) {
Modes.interactive = 0;
}
fprintf(stderr, "dump1090: GetDevices error (%s)\n", sdrplay_api_GetErrorString(err));
sdrplay_api_UnlockDeviceApi();
return 1;
}
if (ndevs == 1)
{
// only 1 device found, so use it
chosenDev = &devs[0];
if (chosenDev->hwVer == SDRPLAY_RSPduo_ID) {
if (chosenDev->rspDuoMode & sdrplay_api_RspDuoMode_Master) {
chosenDev->tuner = Modes.tuner;
chosenDev->rspDuoMode = Modes.mode;
chosenDev->rspDuoSampleFreq = 8000000.0;
}
else
{
if(chosenDev->rspDuoMode != sdrplay_api_RspDuoMode_Single_Tuner) {
chosenDev->rspDuoMode = sdrplay_api_RspDuoMode_Slave;
}
}
}
#if 0
err = sdrplay_api_DebugEnable(chosenDev->dev, 1);
if (err != sdrplay_api_Success) {
if(Modes.interactive) {
Modes.interactive = 0;
}
fprintf(stderr, "dump1090: DebugEnable error (%s)\n", sdrplay_api_GetErrorString(err));
return 1;
}
#endif
if (chosenDev->hwVer != SDRPLAY_RSPduo_ID) {
chosenDev->tuner = sdrplay_api_Tuner_A;
}
err = sdrplay_api_SelectDevice(chosenDev);
if (err != sdrplay_api_Success) {
if(Modes.interactive) {
Modes.interactive = 0;
}
fprintf(stderr, "dump1090: SelectDevice-1 error (%s)\n", sdrplay_api_GetErrorString(err));
sdrplay_api_UnlockDeviceApi();
return 1;
}
}
else if ((ndevs > 1) && (Modes.device_serno == NULL))
{
if(Modes.interactive) {
Modes.interactive = 0;
reint = 1;
}
/* List RSP devices if device serial number not specfied */
fprintf(stdout, "Please select a RSP device from the following list:\n\n");
for (i = 0; i < ndevs; i++)
{
if(devs[i].hwVer == SDRPLAY_RSP1A_ID)
fprintf(stdout, "Device Index %d: RSP1A - SerialNumber = %s\n", i, devs[i].SerNo);
else if(devs[i].hwVer == SDRPLAY_RSPduo_ID)
fprintf(stdout, "Device Index %d: RSPduo - SerialNumber = %s\n", i, devs[i].SerNo);
else
fprintf(stdout, "Device Index %d: RSP%d - SerialNumber = %s\n", i, devs[i].hwVer, devs[i].SerNo);
}
fprintf(stdout, "\nEnter Device Index number [0:%d] >> ", ndevs - 1);
int xx = fscanf(stdin, "%d", &devIdx);
i = i + (xx - xx);
if (devIdx < ndevs)
{
chosenDev = &devs[devIdx];
}
else
{
fprintf(stderr, "Device index %d is out of range [0:%d]\n", devIdx, ndevs - 1);
return 1;
}
if (reint == 1) {
Modes.interactive = 1;
reint = 0;
}
if (chosenDev->hwVer == SDRPLAY_RSPduo_ID) {
if (chosenDev->rspDuoMode & sdrplay_api_RspDuoMode_Master) {
chosenDev->tuner = Modes.tuner;
chosenDev->rspDuoMode = Modes.mode;
chosenDev->rspDuoSampleFreq = 8000000.0;
}
}
if (chosenDev->hwVer != SDRPLAY_RSPduo_ID) {
chosenDev->tuner = sdrplay_api_Tuner_A;
}
err = sdrplay_api_SelectDevice(chosenDev);
if (err != sdrplay_api_Success) {
if(Modes.interactive) {
Modes.interactive = 0;
}
fprintf(stderr, "dump1090: SelectDevice-2 error (%s)\n", sdrplay_api_GetErrorString(err));
sdrplay_api_UnlockDeviceApi();
return 1;
}
}
else if (ndevs > 1)
{
/* Otherwise find corresponding device and use that */
for (i = 0; i < ndevs; i++)
{
if (!strcasecmp(Modes.device_serno, devs[i].SerNo))
{
chosenDev = &devs[i];
if (chosenDev->hwVer == SDRPLAY_RSPduo_ID) {
if (chosenDev->rspDuoMode & sdrplay_api_RspDuoMode_Master) {
chosenDev->tuner = Modes.tuner;
chosenDev->rspDuoMode = Modes.mode;
chosenDev->rspDuoSampleFreq = 8000000.0;
}
}
if (chosenDev->hwVer != SDRPLAY_RSPduo_ID) {
chosenDev->tuner = sdrplay_api_Tuner_A;
}
err = sdrplay_api_SelectDevice(chosenDev);
if (err != sdrplay_api_Success) {
sdrplay_api_UnlockDeviceApi();
if(Modes.interactive) {
Modes.interactive = 0;
}
fprintf(stderr, "dump1090: SelectDevice-3 error (%s)\n", sdrplay_api_GetErrorString(err));
return 1;
}
break;
}
}
if (i == ndevs)
{
if(Modes.interactive) {
Modes.interactive = 0;
}
fprintf(stderr, "Couldn't find a RSP with serial number %s\n", Modes.device_serno);
return 1;
}
}
else if (ndevs == 0)
{
if(Modes.interactive) {
Modes.interactive = 0;
}
fprintf(stderr, "Couldn't find a RSP\n");
sdrplay_api_UnlockDeviceApi();
return 1;
}
err = sdrplay_api_UnlockDeviceApi();
if (err != sdrplay_api_Success) {
if(Modes.interactive) {
Modes.interactive = 0;
}
fprintf(stderr, "dump1090: UnlockDeviceApi error (%s)\n", sdrplay_api_GetErrorString(err));
return 1;
}
err = sdrplay_api_GetDeviceParams(chosenDev->dev, &deviceParams);
if (err != sdrplay_api_Success) {
if(Modes.interactive) {
Modes.interactive = 0;
}
fprintf(stderr, "dump1090: GetDeviceParams error (%s)\n", sdrplay_api_GetErrorString(err));
return 1;
}
if (deviceParams == NULL) {
if(Modes.interactive) {
Modes.interactive = 0;
}
fprintf(stderr, "dump1090: deviceParams == NULL\n");
return 1;
}
chParams = (chosenDev->tuner == sdrplay_api_Tuner_A)? deviceParams->rxChannelA: deviceParams->rxChannelB;
chParams->ctrlParams.dcOffset.IQenable = 0;
chParams->ctrlParams.dcOffset.DCenable = 1;
//#if defined(__arm__) || defined(__aarch64__)
// deviceParams->devParams->mode = 1; // Bulk mode
//#else
// deviceParams->devParams->mode = 0; // Isochronous mode
//#endif
sdrplay_api_If_kHzT ifType = (Modes.ifMode == 0) ? sdrplay_api_IF_Zero : sdrplay_api_IF_2_048;
sdrplay_api_Bw_MHzT bwType = (Modes.bwMode == 0) ? sdrplay_api_BW_1_536 : sdrplay_api_BW_5_000;
if (chosenDev->hwVer == SDRPLAY_RSPduo_ID) {
if (chosenDev->rspDuoMode == sdrplay_api_RspDuoMode_Master || chosenDev->rspDuoMode == sdrplay_api_RspDuoMode_Slave) {
Modes.ifMode = 1;
if (Modes.oversample) {
Modes.adsbMode = 2;
}
else
{
Modes.adsbMode = 0;
}
ifType = sdrplay_api_IF_2_048;
bwType = sdrplay_api_BW_5_000;
}
else
{
Modes.ifMode = 0;
Modes.adsbMode = 1;
ifType = sdrplay_api_IF_Zero;
bwType = sdrplay_api_BW_5_000;
}
}
chParams->tunerParams.ifType = ifType;
chParams->tunerParams.bwType = bwType;
chParams->tunerParams.rfFreq.rfHz = 1090.0 * 1e6;
if (chosenDev->hwVer != SDRPLAY_RSP1_ID) {
chParams->tunerParams.gain.minGr = sdrplay_api_EXTENDED_MIN_GR;
}
chParams->tunerParams.gain.gRdB = Modes.gr;
chParams->tunerParams.gain.LNAstate = LNA_STATE_FOR_MAX_GAIN;
chParams->ctrlParams.agc.enable = 0;
chParams->tunerParams.dcOffsetTuner.dcCal = 4;
chParams->tunerParams.dcOffsetTuner.speedUp = 0;
chParams->tunerParams.dcOffsetTuner.trackTime = 63;
if((chosenDev->hwVer != SDRPLAY_RSPduo_ID) || (chosenDev->rspDuoMode != sdrplay_api_RspDuoMode_Slave)) {
deviceParams->devParams->fsFreq.fsHz = 8.0 * 1e6;
}
if((chosenDev->hwVer == SDRPLAY_RSPduo_ID) && (chosenDev->rspDuoMode & sdrplay_api_RspDuoMode_Slave)) {
if(chosenDev->rspDuoSampleFreq != 8000000.0) {
if(Modes.interactive) {
Modes.interactive = 0;
}
fprintf(stderr, "\nError: RSPduo Master tuner in use and is not running in ADS-B compatible mode.\nSet the Master tuner to ADS-B compatible mode and restart dump1090\n\n");
return 1;
}
}
if(chosenDev->hwVer == SDRPLAY_RSP1A_ID) {
chParams->rsp1aTunerParams.biasTEnable = Modes.enable_biasT;
deviceParams->devParams->rsp1aParams.rfNotchEnable = (1 - Modes.disableBroadcastNotch);
deviceParams->devParams->rsp1aParams.rfDabNotchEnable = (1 - Modes.disableDabNotch);
}
else if(chosenDev->hwVer == SDRPLAY_RSP2_ID) {
chParams->rsp2TunerParams.biasTEnable = Modes.enable_biasT;
chParams->rsp2TunerParams.rfNotchEnable = (1 - Modes.disableBroadcastNotch);
chParams->rsp2TunerParams.amPortSel = sdrplay_api_Rsp2_AMPORT_2;
chParams->rsp2TunerParams.antennaSel = Modes.antenna_port;
}
else if(chosenDev->hwVer == SDRPLAY_RSPdx_ID) {
deviceParams->devParams->rspDxParams.biasTEnable = Modes.enable_biasT;
deviceParams->devParams->rspDxParams.rfNotchEnable = (1 - Modes.disableBroadcastNotch);
deviceParams->devParams->rspDxParams.antennaSel = Modes.Dxantenna_port;
deviceParams->devParams->rspDxParams.rfDabNotchEnable = (1 - Modes.disableDabNotch);
}
else if(chosenDev->hwVer == SDRPLAY_RSPduo_ID) {
chParams->rspDuoTunerParams.biasTEnable = Modes.enable_biasT;
chParams->rspDuoTunerParams.rfNotchEnable = (1 - Modes.disableBroadcastNotch);
chParams->rspDuoTunerParams.rfDabNotchEnable = (1 - Modes.disableDabNotch);
}
switch (Modes.adsbMode) {
case 0: chParams->ctrlParams.adsbMode = sdrplay_api_ADSB_DECIMATION; break;
case 1: chParams->ctrlParams.adsbMode = sdrplay_api_ADSB_NO_DECIMATION_LOWPASS; break;
case 2: chParams->ctrlParams.adsbMode = sdrplay_api_ADSB_NO_DECIMATION_BANDPASS_2MHZ; break;
case 3: chParams->ctrlParams.adsbMode = sdrplay_api_ADSB_NO_DECIMATION_BANDPASS_3MHZ; break;
}
if (Modes.ifMode == 0)
{
if (Modes.oversample == 0) {
chParams->ctrlParams.decimation.enable = 1;
chParams->ctrlParams.decimation.decimationFactor = 4;
}
else
{
chParams->ctrlParams.adsbMode = sdrplay_api_ADSB_DECIMATION;
}
}
err = sdrplay_api_Init(chosenDev->dev, &cbFns, NULL);
if (err) {
if(Modes.interactive) {
Modes.interactive = 0;
}
if(err == sdrplay_api_StartPending) {
fprintf(stderr, "\ndump1090 run as a slave will only begin to receive data when the master\nstream is running. Please start the master stream (e.g. press PLAY in SDRuno)\nand then restart dump1090.\n\n");
return 1;
}
fprintf(stderr, "dump1090: Init error (%s)\n", sdrplay_api_GetErrorString(err));
return 1;
}
chParams->tunerParams.rfFreq.rfHz = 1090.0 * 1e6;
err = sdrplay_api_Update(chosenDev->dev, chosenDev->tuner, sdrplay_api_Update_Tuner_Frf, sdrplay_api_Update_Ext1_None);
if (err != sdrplay_api_Success) {
if(Modes.interactive) {
Modes.interactive = 0;
}
fprintf(stderr, "dump1090: Frf update error (%s)\n", sdrplay_api_GetErrorString(err));
return 1;
}
return 0;
}
#endif
//
//=========================================================================
//
// 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.
//
static struct timespec reader_thread_start;
void rtlsdrCallback(unsigned char *buf, uint32_t len, void *ctx) {
struct mag_buf *outbuf;
struct mag_buf *lastbuf;
uint32_t slen;
unsigned next_free_buffer;
unsigned free_bufs;
unsigned block_duration;
static int was_odd = 0; // paranoia!!
static int dropping = 0;
MODES_NOTUSED(ctx);
// Lock the data buffer variables before accessing them
pthread_mutex_lock(&Modes.data_mutex);
if (Modes.exit) {
if (Modes.use_rtlsdr)
rtlsdr_cancel_async(Modes.dev); // ask our caller to exit
}
next_free_buffer = (Modes.first_free_buffer + 1) % MODES_MAG_BUFFERS;
outbuf = &Modes.mag_buffers[Modes.first_free_buffer];
lastbuf = &Modes.mag_buffers[(Modes.first_free_buffer + MODES_MAG_BUFFERS - 1) % MODES_MAG_BUFFERS];
free_bufs = (Modes.first_filled_buffer - next_free_buffer + MODES_MAG_BUFFERS) % MODES_MAG_BUFFERS;
// Paranoia! Unlikely, but let's go for belt and suspenders here
if (len != MODES_RTL_BUF_SIZE) {
fprintf(stderr, "weirdness: rtlsdr gave us a block with an unusual size (got %u bytes, expected %u bytes)\n",
(unsigned)len, (unsigned)MODES_RTL_BUF_SIZE);
if (len > MODES_RTL_BUF_SIZE) {
// wat?! Discard the start.
unsigned discard = (len - MODES_RTL_BUF_SIZE + 1) / 2;
outbuf->dropped += discard;
buf += discard*2;
len -= discard*2;
}
}
if (was_odd) {
// Drop a sample so we are in sync with I/Q samples again (hopefully)
++buf;
--len;
++outbuf->dropped;
}
was_odd = (len & 1);
slen = len/2;
if (free_bufs == 0 || (dropping && free_bufs < MODES_MAG_BUFFERS/2)) {
// FIFO is full. Drop this block.
dropping = 1;
outbuf->dropped += slen;
pthread_mutex_unlock(&Modes.data_mutex);
return;
}
dropping = 0;
pthread_mutex_unlock(&Modes.data_mutex);
// Compute the sample timestamp and system timestamp for the start of the block
outbuf->sampleTimestamp = lastbuf->sampleTimestamp + 12e6 * (lastbuf->length + outbuf->dropped) / Modes.sample_rate;
block_duration = 1e9 * slen / Modes.sample_rate;
// Get the approx system time for the start of this block
clock_gettime(CLOCK_REALTIME, &outbuf->sysTimestamp);
outbuf->sysTimestamp.tv_nsec -= block_duration;
normalize_timespec(&outbuf->sysTimestamp);
// Copy trailing data from last block (or reset if not valid)
if (outbuf->dropped == 0 && lastbuf->length >= Modes.trailing_samples) {
memcpy(outbuf->data, lastbuf->data + lastbuf->length - Modes.trailing_samples, Modes.trailing_samples * sizeof(uint16_t));
} else {
memset(outbuf->data, 0, Modes.trailing_samples * sizeof(uint16_t));
}
// Convert the new data
outbuf->length = slen;
convert_samples(buf, &outbuf->data[Modes.trailing_samples], slen, &outbuf->total_power);
// Push the new data to the demodulation thread
pthread_mutex_lock(&Modes.data_mutex);
Modes.mag_buffers[next_free_buffer].dropped = 0;
Modes.mag_buffers[next_free_buffer].length = 0; // just in case
Modes.first_free_buffer = next_free_buffer;
// accumulate CPU while holding the mutex, and restart measurement
end_cpu_timing(&reader_thread_start, &Modes.reader_cpu_accumulator);
start_cpu_timing(&reader_thread_start);
pthread_cond_signal(&Modes.data_cond);
pthread_mutex_unlock(&Modes.data_mutex);
}
//
//=========================================================================
//
// This is used when --ifile is specified in order to read data from file
// instead of using an RTLSDR device
//
void readDataFromFile(void) {
int eof = 0;
struct timespec next_buffer_delivery;
void *readbuf;
int bytes_per_sample = 0;
switch (Modes.input_format) {
case INPUT_UC8:
bytes_per_sample = 2;
break;
case INPUT_SC16:
case INPUT_SC16Q11:
bytes_per_sample = 4;
break;
}
if (!(readbuf = malloc(MODES_MAG_BUF_SAMPLES * bytes_per_sample))) {
fprintf(stderr, "failed to allocate read buffer\n");
exit(1);
}
clock_gettime(CLOCK_MONOTONIC, &next_buffer_delivery);
pthread_mutex_lock(&Modes.data_mutex);
while (!Modes.exit && !eof) {
ssize_t nread, toread;
void *r;
struct mag_buf *outbuf, *lastbuf;
unsigned next_free_buffer;
unsigned slen;
next_free_buffer = (Modes.first_free_buffer + 1) % MODES_MAG_BUFFERS;
if (next_free_buffer == Modes.first_filled_buffer) {
// no space for output yet