Debian Codegraph @

dump1090.c

raw symbols ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 // Part of dump1090, a Mode S message decoder for RTLSDR devices.
2 //
3 // dump1090.c: main program & miscellany
4 //
5 // Copyright (c) 2014-2016 Oliver Jowett <[email protected]>
6 //
7 // This file is free software: you may copy, redistribute and/or modify it
8 // under the terms of the GNU General Public License as published by the
9 // Free Software Foundation, either version 2 of the License, or (at your
10 // option) any later version.
11 //
12 // This file is distributed in the hope that it will be useful, but
13 // WITHOUT ANY WARRANTY; without even the implied warranty of
14 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 // General Public License for more details.
16 //
17 // You should have received a copy of the GNU General Public License
18 // along with this program. If not, see <http://www.gnu.org/licenses/>.
19
20 // This file incorporates work covered by the following copyright and
21 // permission notice:
22 //
23 // Copyright (C) 2012 by Salvatore Sanfilippo <[email protected]>
24 //
25 // All rights reserved.
26 //
27 // Redistribution and use in source and binary forms, with or without
28 // modification, are permitted provided that the following conditions are
29 // met:
30 //
31 // * Redistributions of source code must retain the above copyright
32 // notice, this list of conditions and the following disclaimer.
33 //
34 // * Redistributions in binary form must reproduce the above copyright
35 // notice, this list of conditions and the following disclaimer in the
36 // documentation and/or other materials provided with the distribution.
37 //
38 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
39 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
40 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
41 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
42 // HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
43 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
44 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
45 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
46 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
47 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
48 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
49
50 #include "dump1090.h"
51
52 #include <rtl-sdr.h>
53
54 #include <stdarg.h>
55
56 static int verbose_device_search(char *s);
57
58 //
59 // ============================= Utility functions ==========================
60 //
61
62 static void log_with_timestamp(const char *format, ...) __attribute__((format (printf, 1, 2) ));
63
64 static void log_with_timestamp(const char *format, ...)
65 {
66 char timebuf[128];
67 char msg[1024];
68 time_t now;
69 struct tm local;
70 va_list ap;
71
72 now = time(NULL);
73 localtime_r(&now, &local);
74 strftime(timebuf, 128, "%c %Z", &local);
75 timebuf[127] = 0;
76
77 va_start(ap, format);
78 vsnprintf(msg, 1024, format, ap);
79 va_end(ap);
80 msg[1023] = 0;
81
82 fprintf(stderr, "%s %s\n", timebuf, msg);
83 }
84
85 static void sigintHandler(int dummy) {
86 MODES_NOTUSED(dummy);
87 signal(SIGINT, SIG_DFL); // reset signal handler - bit extra safety
88 Modes.exit = 1; // Signal to threads that we are done
89 log_with_timestamp("Caught SIGINT, shutting down..\n");
90 }
91
92 static void sigtermHandler(int dummy) {
93 MODES_NOTUSED(dummy);
94 signal(SIGTERM, SIG_DFL); // reset signal handler - bit extra safety
95 Modes.exit = 1; // Signal to threads that we are done
96 log_with_timestamp("Caught SIGTERM, shutting down..\n");
97 }
98 //
99 // =============================== Terminal handling ========================
100 //
101 #ifndef _WIN32
102 // Get the number of rows after the terminal changes size.
103 int getTermRows() {
104 struct winsize w;
105 ioctl(STDOUT_FILENO, TIOCGWINSZ, &w);
106 return (w.ws_row);
107 }
108
109 // Handle resizing terminal
110 void sigWinchCallback() {
111 signal(SIGWINCH, SIG_IGN);
112 Modes.interactive_rows = getTermRows();
113 interactiveShowData();
114 signal(SIGWINCH, sigWinchCallback);
115 }
116 #else
117 int getTermRows() { return MODES_INTERACTIVE_ROWS;}
118 #endif
119
120 static void start_cpu_timing(struct timespec *start_time)
121 {
122 clock_gettime(CLOCK_THREAD_CPUTIME_ID, start_time);
123 }
124
125 static void end_cpu_timing(const struct timespec *start_time, struct timespec *add_to)
126 {
127 struct timespec end_time;
128 clock_gettime(CLOCK_THREAD_CPUTIME_ID, &end_time);
129 add_to->tv_sec += (end_time.tv_sec - start_time->tv_sec - 1);
130 add_to->tv_nsec += (1000000000L + end_time.tv_nsec - start_time->tv_nsec);
131 add_to->tv_sec += add_to->tv_nsec / 1000000000L;
132 add_to->tv_nsec = add_to->tv_nsec % 1000000000L;
133 }
134
135 //
136 // =============================== Initialization ===========================
137 //
138 void modesInitConfig(void) {
139 // Default everything to zero/NULL
140 memset(&Modes, 0, sizeof(Modes));
141
142 // Now initialise things that should not be 0/NULL to their defaults
143 Modes.gain = MODES_MAX_GAIN;
144 Modes.freq = MODES_DEFAULT_FREQ;
145 Modes.ppm_error = MODES_DEFAULT_PPM;
146 Modes.check_crc = 1;
147 Modes.net_heartbeat_interval = MODES_NET_HEARTBEAT_INTERVAL;
148 Modes.net_input_raw_ports = strdup("30001");
149 Modes.net_output_raw_ports = strdup("30002");
150 Modes.net_output_sbs_ports = strdup("30003");
151 Modes.net_input_beast_ports = strdup("30004,30104");
152 Modes.net_output_beast_ports = strdup("30005");
153 #ifdef ENABLE_WEBSERVER
154 Modes.net_http_ports = strdup("8080");
155 #endif
156 Modes.interactive_rows = getTermRows();
157 Modes.interactive_display_ttl = MODES_INTERACTIVE_DISPLAY_TTL;
158 Modes.html_dir = HTMLPATH;
159 Modes.json_interval = 1000;
160 Modes.json_location_accuracy = 1;
161 Modes.maxRange = 1852 * 300; // 300NM default max range
162 }
163 //
164 //=========================================================================
165 //
166 void modesInit(void) {
167 int i, q;
168
169 pthread_mutex_init(&Modes.data_mutex,NULL);
170 pthread_cond_init(&Modes.data_cond,NULL);
171
172 Modes.sample_rate = 2400000.0;
173
174 // Allocate the various buffers used by Modes
175 Modes.trailing_samples = (MODES_PREAMBLE_US + MODES_LONG_MSG_BITS + 16) * 1e-6 * Modes.sample_rate;
176
177 if ( ((Modes.maglut = (uint16_t *) malloc(sizeof(uint16_t) * 256 * 256) ) == NULL) ||
178 ((Modes.log10lut = (uint16_t *) malloc(sizeof(uint16_t) * 256 * 256) ) == NULL) )
179 {
180 fprintf(stderr, "Out of memory allocating data buffer.\n");
181 exit(1);
182 }
183
184 for (i = 0; i < MODES_MAG_BUFFERS; ++i) {
185 if ( (Modes.mag_buffers[i].data = calloc(MODES_MAG_BUF_SAMPLES+Modes.trailing_samples, sizeof(uint16_t))) == NULL ) {
186 fprintf(stderr, "Out of memory allocating magnitude buffer.\n");
187 exit(1);
188 }
189
190 Modes.mag_buffers[i].length = 0;
191 Modes.mag_buffers[i].dropped = 0;
192 Modes.mag_buffers[i].sampleTimestamp = 0;
193 }
194
195 // Validate the users Lat/Lon home location inputs
196 if ( (Modes.fUserLat > 90.0) // Latitude must be -90 to +90
197 || (Modes.fUserLat < -90.0) // and
198 || (Modes.fUserLon > 360.0) // Longitude must be -180 to +360
199 || (Modes.fUserLon < -180.0) ) {
200 Modes.fUserLat = Modes.fUserLon = 0.0;
201 } else if (Modes.fUserLon > 180.0) { // If Longitude is +180 to +360, make it -180 to 0
202 Modes.fUserLon -= 360.0;
203 }
204 // If both Lat and Lon are 0.0 then the users location is either invalid/not-set, or (s)he's in the
205 // Atlantic ocean off the west coast of Africa. This is unlikely to be correct.
206 // Set the user LatLon valid flag only if either Lat or Lon are non zero. Note the Greenwich meridian
207 // is at 0.0 Lon,so we must check for either fLat or fLon being non zero not both.
208 // Testing the flag at runtime will be much quicker than ((fLon != 0.0) || (fLat != 0.0))
209 Modes.bUserFlags &= ~MODES_USER_LATLON_VALID;
210 if ((Modes.fUserLat != 0.0) || (Modes.fUserLon != 0.0)) {
211 Modes.bUserFlags |= MODES_USER_LATLON_VALID;
212 }
213
214 // Limit the maximum requested raw output size to less than one Ethernet Block
215 if (Modes.net_output_flush_size > (MODES_OUT_FLUSH_SIZE))
216 {Modes.net_output_flush_size = MODES_OUT_FLUSH_SIZE;}
217 if (Modes.net_output_flush_interval > (MODES_OUT_FLUSH_INTERVAL))
218 {Modes.net_output_flush_interval = MODES_OUT_FLUSH_INTERVAL;}
219 if (Modes.net_sndbuf_size > (MODES_NET_SNDBUF_MAX))
220 {Modes.net_sndbuf_size = MODES_NET_SNDBUF_MAX;}
221
222 // compute UC8 magnitude lookup table
223 for (i = 0; i <= 255; i++) {
224 for (q = 0; q <= 255; q++) {
225 float fI, fQ, magsq;
226
227 fI = (i - 127.5) / 127.5;
228 fQ = (q - 127.5) / 127.5;
229 magsq = fI * fI + fQ * fQ;
230 if (magsq > 1)
231 magsq = 1;
232
233 Modes.maglut[le16toh((i*256)+q)] = (uint16_t) round(sqrtf(magsq) * 65535.0);
234 }
235 }
236
237 // Prepare the log10 lookup table: 100log10(x)
238 Modes.log10lut[0] = 0; // poorly defined..
239 for (i = 1; i <= 65535; i++) {
240 Modes.log10lut[i] = (uint16_t) round(100.0 * log10(i));
241 }
242
243 // Prepare error correction tables
244 modesChecksumInit(Modes.nfix_crc);
245 icaoFilterInit();
246
247 if (Modes.show_only)
248 icaoFilterAdd(Modes.show_only);
249
250 // Prepare sample conversion
251 if (!Modes.net_only) {
252 if (Modes.filename == NULL) // using a real RTLSDR, use UC8 input always
253 Modes.input_format = INPUT_UC8;
254
255 Modes.converter_function = init_converter(Modes.input_format,
256 Modes.sample_rate,
257 Modes.dc_filter,
258 &Modes.converter_state);
259 if (!Modes.converter_function) {
260 fprintf(stderr, "Can't initialize sample converter, giving up.\n");
261 exit(1);
262 }
263 }
264 }
265
266 static void convert_samples(void *iq,
267 uint16_t *mag,
268 unsigned nsamples,
269 double *power)
270 {
271 Modes.converter_function(iq, mag, nsamples, Modes.converter_state, power);
272 }
273
274 //
275 // =============================== RTLSDR handling ==========================
276 //
277 int modesInitRTLSDR(void) {
278 int j;
279 int device_count, dev_index = 0;
280 char vendor[256], product[256], serial[256];
281
282 if (Modes.dev_name) {
283 if ( (dev_index = verbose_device_search(Modes.dev_name)) < 0 )
284 return -1;
285 }
286
287 device_count = rtlsdr_get_device_count();
288 if (!device_count) {
289 fprintf(stderr, "No supported RTLSDR devices found.\n");
290 return -1;
291 }
292
293 fprintf(stderr, "Found %d device(s):\n", device_count);
294 for (j = 0; j < device_count; j++) {
295 if (rtlsdr_get_device_usb_strings(j, vendor, product, serial) != 0) {
296 fprintf(stderr, "%d: unable to read device details\n", j);
297 } else {
298 fprintf(stderr, "%d: %s, %s, SN: %s %s\n", j, vendor, product, serial,
299 (j == dev_index) ? "(currently selected)" : "");
300 }
301 }
302
303 if (rtlsdr_open(&Modes.dev, dev_index) < 0) {
304 fprintf(stderr, "Error opening the RTLSDR device: %s\n",
305 strerror(errno));
306 return -1;
307 }
308
309 // Set gain, frequency, sample rate, and reset the device
310 rtlsdr_set_tuner_gain_mode(Modes.dev,
311 (Modes.gain == MODES_AUTO_GAIN) ? 0 : 1);
312 if (Modes.gain != MODES_AUTO_GAIN) {
313 int *gains;
314 int numgains;
315
316 numgains = rtlsdr_get_tuner_gains(Modes.dev, NULL);
317 if (numgains <= 0) {
318 fprintf(stderr, "Error getting tuner gains\n");
319 return -1;
320 }
321
322 gains = malloc(numgains * sizeof(int));
323 if (rtlsdr_get_tuner_gains(Modes.dev, gains) != numgains) {
324 fprintf(stderr, "Error getting tuner gains\n");
325 free(gains);
326 return -1;
327 }
328
329 if (Modes.gain == MODES_MAX_GAIN) {
330 int highest = -1;
331 int i;
332
333 for (i = 0; i < numgains; ++i) {
334 if (gains[i] > highest)
335 highest = gains[i];
336 }
337
338 Modes.gain = highest;
339 fprintf(stderr, "Max available gain is: %.2f dB\n", Modes.gain/10.0);
340 } else {
341 int closest = -1;
342 int i;
343
344 for (i = 0; i < numgains; ++i) {
345 if (closest == -1 || abs(gains[i] - Modes.gain) < abs(closest - Modes.gain))
346 closest = gains[i];
347 }
348
349 if (closest != Modes.gain) {
350 Modes.gain = closest;
351 fprintf(stderr, "Closest available gain: %.2f dB\n", Modes.gain/10.0);
352 }
353 }
354
355 free(gains);
356
357 fprintf(stderr, "Setting gain to: %.2f dB\n", Modes.gain/10.0);
358 if (rtlsdr_set_tuner_gain(Modes.dev, Modes.gain) < 0) {
359 fprintf(stderr, "Error setting tuner gains\n");
360 return -1;
361 }
362 } else {
363 fprintf(stderr, "Using automatic gain control.\n");
364 }
365 rtlsdr_set_freq_correction(Modes.dev, Modes.ppm_error);
366 if (Modes.enable_agc) rtlsdr_set_agc_mode(Modes.dev, 1);
367 rtlsdr_set_center_freq(Modes.dev, Modes.freq);
368 rtlsdr_set_sample_rate(Modes.dev, (unsigned)Modes.sample_rate);
369
370 rtlsdr_reset_buffer(Modes.dev);
371 fprintf(stderr, "Gain reported by device: %.2f dB\n",
372 rtlsdr_get_tuner_gain(Modes.dev)/10.0);
373
374 #ifdef HAVE_RTL_BIAST
375 if (Modes.enable_rtlsdr_biast) {
376 rtlsdr_set_bias_tee(Modes.dev, 1);
377 } else {
378 rtlsdr_set_bias_tee(Modes.dev, 0);
379 }
380 #endif
381
382 return 0;
383 }
384 //
385 //=========================================================================
386 //
387 // We use a thread reading data in background, while the main thread
388 // handles decoding and visualization of data to the user.
389 //
390 // The reading thread calls the RTLSDR API to read data asynchronously, and
391 // uses a callback to populate the data buffer.
392 //
393 // A Mutex is used to avoid races with the decoding thread.
394 //
395
396 static struct timespec reader_thread_start;
397
398 void rtlsdrCallback(unsigned char *buf, uint32_t len, void *ctx) {
399 struct mag_buf *outbuf;
400 struct mag_buf *lastbuf;
401 uint32_t slen;
402 unsigned next_free_buffer;
403 unsigned free_bufs;
404 unsigned block_duration;
405
406 static int was_odd = 0; // paranoia!!
407 static int dropping = 0;
408
409 MODES_NOTUSED(ctx);
410
411 // Lock the data buffer variables before accessing them
412 pthread_mutex_lock(&Modes.data_mutex);
413 if (Modes.exit) {
414 rtlsdr_cancel_async(Modes.dev); // ask our caller to exit
415 }
416
417 next_free_buffer = (Modes.first_free_buffer + 1) % MODES_MAG_BUFFERS;
418 outbuf = &Modes.mag_buffers[Modes.first_free_buffer];
419 lastbuf = &Modes.mag_buffers[(Modes.first_free_buffer + MODES_MAG_BUFFERS - 1) % MODES_MAG_BUFFERS];
420 free_bufs = (Modes.first_filled_buffer - next_free_buffer + MODES_MAG_BUFFERS) % MODES_MAG_BUFFERS;
421
422 // Paranoia! Unlikely, but let's go for belt and suspenders here
423
424 if (len != MODES_RTL_BUF_SIZE) {
425 fprintf(stderr, "weirdness: rtlsdr gave us a block with an unusual size (got %u bytes, expected %u bytes)\n",
426 (unsigned)len, (unsigned)MODES_RTL_BUF_SIZE);
427
428 if (len > MODES_RTL_BUF_SIZE) {
429 // wat?! Discard the start.
430 unsigned discard = (len - MODES_RTL_BUF_SIZE + 1) / 2;
431 outbuf->dropped += discard;
432 buf += discard*2;
433 len -= discard*2;
434 }
435 }
436
437 if (was_odd) {
438 // Drop a sample so we are in sync with I/Q samples again (hopefully)
439 ++buf;
440 --len;
441 ++outbuf->dropped;
442 }
443
444 was_odd = (len & 1);
445 slen = len/2;
446
447 if (free_bufs == 0 || (dropping && free_bufs < MODES_MAG_BUFFERS/2)) {
448 // FIFO is full. Drop this block.
449 dropping = 1;
450 outbuf->dropped += slen;
451 pthread_mutex_unlock(&Modes.data_mutex);
452 return;
453 }
454
455 dropping = 0;
456 pthread_mutex_unlock(&Modes.data_mutex);
457
458 // Compute the sample timestamp and system timestamp for the start of the block
459 outbuf->sampleTimestamp = lastbuf->sampleTimestamp + 12e6 * (lastbuf->length + outbuf->dropped) / Modes.sample_rate;
460 block_duration = 1e9 * slen / Modes.sample_rate;
461
462 // Get the approx system time for the start of this block
463 clock_gettime(CLOCK_REALTIME, &outbuf->sysTimestamp);
464 outbuf->sysTimestamp.tv_nsec -= block_duration;
465 normalize_timespec(&outbuf->sysTimestamp);
466
467 // Copy trailing data from last block (or reset if not valid)
468 if (outbuf->dropped == 0 && lastbuf->length >= Modes.trailing_samples) {
469 memcpy(outbuf->data, lastbuf->data + lastbuf->length - Modes.trailing_samples, Modes.trailing_samples * sizeof(uint16_t));
470 } else {
471 memset(outbuf->data, 0, Modes.trailing_samples * sizeof(uint16_t));
472 }
473
474 // Convert the new data
475 outbuf->length = slen;
476 convert_samples(buf, &outbuf->data[Modes.trailing_samples], slen, &outbuf->total_power);
477
478 // Push the new data to the demodulation thread
479 pthread_mutex_lock(&Modes.data_mutex);
480
481 Modes.mag_buffers[next_free_buffer].dropped = 0;
482 Modes.mag_buffers[next_free_buffer].length = 0; // just in case
483 Modes.first_free_buffer = next_free_buffer;
484
485 // accumulate CPU while holding the mutex, and restart measurement
486 end_cpu_timing(&reader_thread_start, &Modes.reader_cpu_accumulator);
487 start_cpu_timing(&reader_thread_start);
488
489 pthread_cond_signal(&Modes.data_cond);
490 pthread_mutex_unlock(&Modes.data_mutex);
491 }
492 //
493 //=========================================================================
494 //
495 // This is used when --ifile is specified in order to read data from file
496 // instead of using an RTLSDR device
497 //
498 void readDataFromFile(void) {
499 int eof = 0;
500 struct timespec next_buffer_delivery;
501 void *readbuf;
502 int bytes_per_sample = 0;
503
504 switch (Modes.input_format) {
505 case INPUT_UC8:
506 bytes_per_sample = 2;
507 break;
508 case INPUT_SC16:
509 case INPUT_SC16Q11:
510 bytes_per_sample = 4;
511 break;
512 }
513
514 if (!(readbuf = malloc(MODES_MAG_BUF_SAMPLES * bytes_per_sample))) {
515 fprintf(stderr, "failed to allocate read buffer\n");
516 exit(1);
517 }
518
519 clock_gettime(CLOCK_MONOTONIC, &next_buffer_delivery);
520
521 pthread_mutex_lock(&Modes.data_mutex);
522 while (!Modes.exit && !eof) {
523 ssize_t nread, toread;
524 void *r;
525 struct mag_buf *outbuf, *lastbuf;
526 unsigned next_free_buffer;
527 unsigned slen;
528
529 next_free_buffer = (Modes.first_free_buffer + 1) % MODES_MAG_BUFFERS;
530 if (next_free_buffer == Modes.first_filled_buffer) {
531 // no space for output yet
532 pthread_cond_wait(&Modes.data_cond, &Modes.data_mutex);
533 continue;
534 }
535
536 outbuf = &Modes.mag_buffers[Modes.first_free_buffer];
537 lastbuf = &Modes.mag_buffers[(Modes.first_free_buffer + MODES_MAG_BUFFERS - 1) % MODES_MAG_BUFFERS];
538 pthread_mutex_unlock(&Modes.data_mutex);
539
540 // Compute the sample timestamp and system timestamp for the start of the block
541 outbuf->sampleTimestamp = lastbuf->sampleTimestamp + 12e6 * lastbuf->length / Modes.sample_rate;
542
543 // Copy trailing data from last block (or reset if not valid)
544 if (lastbuf->length >= Modes.trailing_samples) {
545 memcpy(outbuf->data, lastbuf->data + lastbuf->length - Modes.trailing_samples, Modes.trailing_samples * sizeof(uint16_t));
546 } else {
547 memset(outbuf->data, 0, Modes.trailing_samples * sizeof(uint16_t));
548 }
549
550 // Get the system time for the start of this block
551 clock_gettime(CLOCK_REALTIME, &outbuf->sysTimestamp);
552
553 toread = MODES_MAG_BUF_SAMPLES * bytes_per_sample;
554 r = readbuf;
555 while (toread) {
556 nread = read(Modes.fd, r, toread);
557 if (nread <= 0) {
558 // Done.
559 eof = 1;
560 break;
561 }
562 r += nread;
563 toread -= nread;
564 }
565
566 slen = outbuf->length = MODES_MAG_BUF_SAMPLES - toread/bytes_per_sample;
567
568 // Convert the new data
569 convert_samples(readbuf, &outbuf->data[Modes.trailing_samples], slen, &outbuf->total_power);
570
571 if (Modes.throttle) {
572 // Wait until we are allowed to release this buffer to the main thread
573 while (clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, &next_buffer_delivery, NULL) == EINTR)
574 ;
575
576 // compute the time we can deliver the next buffer.
577 next_buffer_delivery.tv_nsec += outbuf->length * 1e9 / Modes.sample_rate;
578 normalize_timespec(&next_buffer_delivery);
579 }
580
581 // Push the new data to the main thread
582 pthread_mutex_lock(&Modes.data_mutex);
583 Modes.first_free_buffer = next_free_buffer;
584 // accumulate CPU while holding the mutex, and restart measurement
585 end_cpu_timing(&reader_thread_start, &Modes.reader_cpu_accumulator);
586 start_cpu_timing(&reader_thread_start);
587 pthread_cond_signal(&Modes.data_cond);
588 }
589
590 free(readbuf);
591
592 // Wait for the main thread to consume all data
593 while (!Modes.exit && Modes.first_filled_buffer != Modes.first_free_buffer)
594 pthread_cond_wait(&Modes.data_cond, &Modes.data_mutex);
595
596 pthread_mutex_unlock(&Modes.data_mutex);
597 }
598 //
599 //=========================================================================
600 //
601 // We read data using a thread, so the main thread only handles decoding
602 // without caring about data acquisition
603 //
604
605 void *readerThreadEntryPoint(void *arg) {
606 MODES_NOTUSED(arg);
607
608 start_cpu_timing(&reader_thread_start); // we accumulate in rtlsdrCallback() or readDataFromFile()
609
610 if (Modes.filename == NULL) {
611 while (!Modes.exit) {
612 rtlsdr_read_async(Modes.dev, rtlsdrCallback, NULL,
613 MODES_RTL_BUFFERS,
614 MODES_RTL_BUF_SIZE);
615
616 if (!Modes.exit) {
617 log_with_timestamp("Warning: lost the connection to the RTLSDR device.");
618 rtlsdr_close(Modes.dev);
619 Modes.dev = NULL;
620
621 do {
622 sleep(5);
623 log_with_timestamp("Trying to reconnect to the RTLSDR device..");
624 } while (!Modes.exit && modesInitRTLSDR() < 0);
625 }
626 }
627
628 if (Modes.dev != NULL) {
629 rtlsdr_close(Modes.dev);
630 Modes.dev = NULL;
631 }
632 } else {
633 readDataFromFile();
634 }
635
636 // Wake the main thread (if it's still waiting)
637 pthread_mutex_lock(&Modes.data_mutex);
638 Modes.exit = 1; // just in case
639 pthread_cond_signal(&Modes.data_cond);
640 pthread_mutex_unlock(&Modes.data_mutex);
641
642 #ifndef _WIN32
643 pthread_exit(NULL);
644 #else
645 return NULL;
646 #endif
647 }
648 //
649 // ============================== Snip mode =================================
650 //
651 // Get raw IQ samples and filter everything is < than the specified level
652 // for more than 256 samples in order to reduce example file size
653 //
654 void snipMode(int level) {
655 int i, q;
656 uint64_t c = 0;
657
658 while ((i = getchar()) != EOF && (q = getchar()) != EOF) {
659 if (abs(i-127) < level && abs(q-127) < level) {
660 c++;
661 if (c > MODES_PREAMBLE_SIZE) continue;
662 } else {
663 c = 0;
664 }
665 putchar(i);
666 putchar(q);
667 }
668 }
669 //
670 // ================================ Main ====================================
671 //
672 void showHelp(void) {
673 printf(
674 "-----------------------------------------------------------------------------\n"
675 "| dump1090 ModeS Receiver %45s |\n"
676 "-----------------------------------------------------------------------------\n"
677 "--device-index <index> Select RTL device (default: 0)\n"
678 "--gain <db> Set gain (default: max gain. Use -10 for auto-gain)\n"
679 "--enable-agc Enable the Automatic Gain Control (default: off)\n"
680 "--freq <hz> Set frequency (default: 1090 Mhz)\n"
681 "--ifile <filename> Read data from file (use '-' for stdin)\n"
682 "--iformat <format> Sample format for --ifile: UC8 (default), SC16, or SC16Q11\n"
683 "--throttle When reading from a file, play back in realtime, not at max speed\n"
684 "--interactive Interactive mode refreshing data on screen. Implies --throttle\n"
685 "--interactive-rows <num> Max number of rows in interactive mode (default: 22)\n"
686 "--interactive-ttl <sec> Remove from list if idle for <sec> (default: 60)\n"
687 "--interactive-rtl1090 Display flight table in RTL1090 format\n"
688 "--raw Show only messages hex values\n"
689 "--net Enable networking\n"
690 "--modeac Enable decoding of SSR Modes 3/A & 3/C\n"
691 "--net-only Enable just networking, no RTL device or file used\n"
692 "--net-bind-address <ip> IP address to bind to (default: Any; Use 127.0.0.1 for private)\n"
693 #ifdef ENABLE_WEBSERVER
694 "--net-http-port <ports> HTTP server ports (default: 8080)\n"
695 #endif
696 "--net-ri-port <ports> TCP raw input listen ports (default: 30001)\n"
697 "--net-ro-port <ports> TCP raw output listen ports (default: 30002)\n"
698 "--net-sbs-port <ports> TCP BaseStation output listen ports (default: 30003)\n"
699 "--net-bi-port <ports> TCP Beast input listen ports (default: 30004,30104)\n"
700 "--net-bo-port <ports> TCP Beast output listen ports (default: 30005)\n"
701 "--net-ro-size <size> TCP output minimum size (default: 0)\n"
702 "--net-ro-interval <rate> TCP output memory flush rate in seconds (default: 0)\n"
703 "--net-heartbeat <rate> TCP heartbeat rate in seconds (default: 60 sec; 0 to disable)\n"
704 "--net-buffer <n> TCP buffer size 64Kb * (2^n) (default: n=0, 64Kb)\n"
705 "--net-verbatim Do not apply CRC corrections to messages we forward; send unchanged\n"
706 "--forward-mlat Allow forwarding of received mlat results to output ports\n"
707 "--lat <latitude> Reference/receiver latitude for surface posn (opt)\n"
708 "--lon <longitude> Reference/receiver longitude for surface posn (opt)\n"
709 "--max-range <distance> Absolute maximum range for position decoding (in nm, default: 300)\n"
710 "--fix Enable single-bits error correction using CRC\n"
711 "--no-fix Disable single-bits error correction using CRC\n"
712 "--no-crc-check Disable messages with broken CRC (discouraged)\n"
713 #ifdef ALLOW_AGGRESSIVE
714 "--aggressive More CPU for more messages (two bits fixes, ...)\n"
715 #endif
716 "--mlat display raw messages in Beast ascii mode\n"
717 "--stats Print stats at exit\n"
718 "--stats-range Collect/show range histogram\n"
719 "--stats-every <seconds> Show and reset stats every <seconds> seconds\n"
720 "--onlyaddr Show only ICAO addresses (testing purposes)\n"
721 "--metric Use metric units (meters, km/h, ...)\n"
722 "--gnss Show altitudes as HAE/GNSS (with H suffix) when available\n"
723 "--snip <level> Strip IQ file removing samples < level\n"
724 "--debug <flags> Debug mode (verbose), see README for details\n"
725 "--quiet Disable output to stdout. Use for daemon applications\n"
726 "--show-only <addr> Show only messages from the given ICAO on stdout\n"
727 "--ppm <error> Set receiver error in parts per million (default 0)\n"
728 #ifdef HAVE_RTL_BIAST
729 "--enable-rtlsdr-biast Set bias tee supply on (default off)\n"
730 #endif
731 "--html-dir <dir> Use <dir> as base directory for the internal HTTP server. Defaults to " HTMLPATH "\n"
732 "--write-json <dir> Periodically write json output to <dir> (for serving by a separate webserver)\n"
733 "--write-json-every <t> Write json output every t seconds (default 1)\n"
734 "--json-location-accuracy <n> Accuracy of receiver location in json metadata: 0=no location, 1=approximate, 2=exact\n"
735 "--dcfilter Apply a 1Hz DC filter to input data (requires lots more CPU)\n"
736 "--help Show this help\n"
737 "\n"
738 "Debug mode flags: d = Log frames decoded with errors\n"
739 " D = Log frames decoded with zero errors\n"
740 " c = Log frames with bad CRC\n"
741 " C = Log frames with good CRC\n"
742 " p = Log frames with bad preamble\n"
743 " n = Log network debugging info\n"
744 " j = Log frames to frames.js, loadable by debug.html\n",
745 MODES_DUMP1090_VARIANT " " MODES_DUMP1090_VERSION
746 );
747 }
748
749 static void display_total_stats(void)
750 {
751 struct stats added;
752 add_stats(&Modes.stats_alltime, &Modes.stats_current, &added);
753 display_stats(&added);
754 }
755
756 //
757 //=========================================================================
758 //
759 // This function is called a few times every second by main in order to
760 // perform tasks we need to do continuously, like accepting new clients
761 // from the net, refreshing the screen in interactive mode, and so forth
762 //
763 void backgroundTasks(void) {
764 static uint64_t next_stats_display;
765 static uint64_t next_stats_update;
766 static uint64_t next_json, next_history;
767
768 uint64_t now = mstime();
769
770 icaoFilterExpire();
771 trackPeriodicUpdate();
772
773 if (Modes.net) {
774 modesNetPeriodicWork();
775 }
776
777
778 // Refresh screen when in interactive mode
779 if (Modes.interactive) {
780 interactiveShowData();
781 }
782
783 // always update end time so it is current when requests arrive
784 Modes.stats_current.end = now;
785
786 if (now >= next_stats_update) {
787 int i;
788
789 if (next_stats_update == 0) {
790 next_stats_update = now + 60000;
791 } else {
792 Modes.stats_latest_1min = (Modes.stats_latest_1min + 1) % 15;
793 Modes.stats_1min[Modes.stats_latest_1min] = Modes.stats_current;
794
795 add_stats(&Modes.stats_current, &Modes.stats_alltime, &Modes.stats_alltime);
796 add_stats(&Modes.stats_current, &Modes.stats_periodic, &Modes.stats_periodic);
797
798 reset_stats(&Modes.stats_5min);
799 for (i = 0; i < 5; ++i)
800 add_stats(&Modes.stats_1min[(Modes.stats_latest_1min - i + 15) % 15], &Modes.stats_5min, &Modes.stats_5min);
801
802 reset_stats(&Modes.stats_15min);
803 for (i = 0; i < 15; ++i)
804 add_stats(&Modes.stats_1min[i], &Modes.stats_15min, &Modes.stats_15min);
805
806 reset_stats(&Modes.stats_current);
807 Modes.stats_current.start = Modes.stats_current.end = now;
808
809 if (Modes.json_dir)
810 writeJsonToFile("stats.json", generateStatsJson);
811
812 next_stats_update += 60000;
813 }
814 }
815
816 if (Modes.stats && now >= next_stats_display) {
817 if (next_stats_display == 0) {
818 next_stats_display = now + Modes.stats;
819 } else {
820 add_stats(&Modes.stats_periodic, &Modes.stats_current, &Modes.stats_periodic);
821 display_stats(&Modes.stats_periodic);
822 reset_stats(&Modes.stats_periodic);
823
824 next_stats_display += Modes.stats;
825 if (next_stats_display <= now) {
826 /* something has gone wrong, perhaps the system clock jumped */
827 next_stats_display = now + Modes.stats;
828 }
829 }
830 }
831
832 if (Modes.json_dir && now >= next_json) {
833 writeJsonToFile("aircraft.json", generateAircraftJson);
834 next_json = now + Modes.json_interval;
835 }
836
837 if (now >= next_history) {
838 int rewrite_receiver_json = (Modes.json_dir && Modes.json_aircraft_history[HISTORY_SIZE-1].content == NULL);
839
840 free(Modes.json_aircraft_history[Modes.json_aircraft_history_next].content); // might be NULL, that's OK.
841 Modes.json_aircraft_history[Modes.json_aircraft_history_next].content =
842 generateAircraftJson("/data/aircraft.json", &Modes.json_aircraft_history[Modes.json_aircraft_history_next].clen);
843
844 if (Modes.json_dir) {
845 char filebuf[PATH_MAX];
846 snprintf(filebuf, PATH_MAX, "history_%d.json", Modes.json_aircraft_history_next);
847 writeJsonToFile(filebuf, generateHistoryJson);
848 }
849
850 Modes.json_aircraft_history_next = (Modes.json_aircraft_history_next+1) % HISTORY_SIZE;
851
852 if (rewrite_receiver_json)
853 writeJsonToFile("receiver.json", generateReceiverJson); // number of history entries changed
854
855 next_history = now + HISTORY_INTERVAL;
856 }
857 }
858
859 //
860 //=========================================================================
861 //
862 int verbose_device_search(char *s)
863 {
864 int i, device_count, device, offset;
865 char *s2;
866 char vendor[256], product[256], serial[256];
867 device_count = rtlsdr_get_device_count();
868 if (!device_count) {
869 fprintf(stderr, "No supported devices found.\n");
870 return -1;
871 }
872 fprintf(stderr, "Found %d device(s):\n", device_count);
873 for (i = 0; i < device_count; i++) {
874 if (rtlsdr_get_device_usb_strings(i, vendor, product, serial) != 0) {
875 fprintf(stderr, " %d: unable to read device details\n", i);
876 } else {
877 fprintf(stderr, " %d: %s, %s, SN: %s\n", i, vendor, product, serial);
878 }
879 }
880 fprintf(stderr, "\n");
881 /* does string look like raw id number */
882 device = (int)strtol(s, &s2, 0);
883 if (s2[0] == '\0' && device >= 0 && device < device_count) {
884 fprintf(stderr, "Using device %d: %s\n",
885 device, rtlsdr_get_device_name((uint32_t)device));
886 return device;
887 }
888 /* does string exact match a serial */
889 for (i = 0; i < device_count; i++) {
890 rtlsdr_get_device_usb_strings(i, vendor, product, serial);
891 if (strcmp(s, serial) != 0) {
892 continue;}
893 device = i;
894 fprintf(stderr, "Using device %d: %s\n",
895 device, rtlsdr_get_device_name((uint32_t)device));
896 return device;
897 }
898 /* does string prefix match a serial */
899 for (i = 0; i < device_count; i++) {
900 rtlsdr_get_device_usb_strings(i, vendor, product, serial);
901 if (strncmp(s, serial, strlen(s)) != 0) {
902 continue;}
903 device = i;
904 fprintf(stderr, "Using device %d: %s\n",
905 device, rtlsdr_get_device_name((uint32_t)device));
906 return device;
907 }
908 /* does string suffix match a serial */
909 for (i = 0; i < device_count; i++) {
910 rtlsdr_get_device_usb_strings(i, vendor, product, serial);
911 offset = strlen(serial) - strlen(s);
912 if (offset < 0) {
913 continue;}
914 if (strncmp(s, serial+offset, strlen(s)) != 0) {
915 continue;}
916 device = i;
917 fprintf(stderr, "Using device %d: %s\n",
918 device, rtlsdr_get_device_name((uint32_t)device));
919 return device;
920 }
921 fprintf(stderr, "No matching devices found.\n");
922 return -1;
923 }
924 //
925 //=========================================================================
926 //
927 int main(int argc, char **argv) {
928 int j;
929
930 // Set sane defaults
931 modesInitConfig();
932
933 // signal handlers:
934 signal(SIGINT, sigintHandler);
935 signal(SIGTERM, sigtermHandler);
936
937 // Parse the command line options
938 for (j = 1; j < argc; j++) {
939 int more = j+1 < argc; // There are more arguments
940
941 if (!strcmp(argv[j],"--device-index") && more) {
942 Modes.dev_name = strdup(argv[++j]);
943 } else if (!strcmp(argv[j],"--gain") && more) {
944 Modes.gain = (int) (atof(argv[++j])*10); // Gain is in tens of DBs
945 } else if (!strcmp(argv[j],"--enable-agc")) {
946 Modes.enable_agc++;
947 } else if (!strcmp(argv[j],"--freq") && more) {
948 Modes.freq = (int) strtoll(argv[++j],NULL,10);
949 } else if (!strcmp(argv[j],"--ifile") && more) {
950 Modes.filename = strdup(argv[++j]);
951 } else if (!strcmp(argv[j],"--iformat") && more) {
952 ++j;
953 if (!strcasecmp(argv[j], "uc8")) {
954 Modes.input_format = INPUT_UC8;
955 } else if (!strcasecmp(argv[j], "sc16")) {
956 Modes.input_format = INPUT_SC16;
957 } else if (!strcasecmp(argv[j], "sc16q11")) {
958 Modes.input_format = INPUT_SC16Q11;
959 } else {
960 fprintf(stderr, "Input format '%s' not understood (supported values: UC8, SC16, SC16Q11)\n",
961 argv[j]);
962 exit(1);
963 }
964 } else if (!strcmp(argv[j],"--dcfilter")) {
965 Modes.dc_filter = 1;
966 } else if (!strcmp(argv[j],"--measure-noise")) {
967 // Ignored
968 } else if (!strcmp(argv[j],"--fix")) {
969 Modes.nfix_crc = 1;
970 } else if (!strcmp(argv[j],"--no-fix")) {
971 Modes.nfix_crc = 0;
972 } else if (!strcmp(argv[j],"--no-crc-check")) {
973 Modes.check_crc = 0;
974 } else if (!strcmp(argv[j],"--phase-enhance")) {
975 // Ignored, always enabled
976 } else if (!strcmp(argv[j],"--raw")) {
977 Modes.raw = 1;
978 } else if (!strcmp(argv[j],"--net")) {
979 Modes.net = 1;
980 } else if (!strcmp(argv[j],"--modeac")) {
981 Modes.mode_ac = 1;
982 } else if (!strcmp(argv[j],"--net-beast")) {
983 fprintf(stderr, "--net-beast ignored, use --net-bo-port to control where Beast output is generated\n");
984 } else if (!strcmp(argv[j],"--net-only")) {
985 Modes.net = 1;
986 Modes.net_only = 1;
987 } else if (!strcmp(argv[j],"--net-heartbeat") && more) {
988 Modes.net_heartbeat_interval = (uint64_t)(1000 * atof(argv[++j]));
989 } else if (!strcmp(argv[j],"--net-ro-size") && more) {
990 Modes.net_output_flush_size = atoi(argv[++j]);
991 } else if (!strcmp(argv[j],"--net-ro-rate") && more) {
992 Modes.net_output_flush_interval = 1000 * atoi(argv[++j]) / 15; // backwards compatibility
993 } else if (!strcmp(argv[j],"--net-ro-interval") && more) {
994 Modes.net_output_flush_interval = (uint64_t)(1000 * atof(argv[++j]));
995 } else if (!strcmp(argv[j],"--net-ro-port") && more) {
996 free(Modes.net_output_raw_ports);
997 Modes.net_output_raw_ports = strdup(argv[++j]);
998 } else if (!strcmp(argv[j],"--net-ri-port") && more) {
999 free(Modes.net_input_raw_ports);
1000 Modes.net_input_raw_ports = strdup(argv[++j]);
1001 } else if (!strcmp(argv[j],"--net-bo-port") && more) {
1002 free(Modes.net_output_beast_ports);
1003 Modes.net_output_beast_ports = strdup(argv[++j]);
1004 } else if (!strcmp(argv[j],"--net-bi-port") && more) {
1005 free(Modes.net_input_beast_ports);
1006 Modes.net_input_beast_ports = strdup(argv[++j]);
1007 } else if (!strcmp(argv[j],"--net-bind-address") && more) {
1008 free(Modes.net_bind_address);
1009 Modes.net_bind_address = strdup(argv[++j]);
1010 } else if (!strcmp(argv[j],"--net-http-port") && more) {
1011 #ifdef ENABLE_WEBSERVER
1012 free(Modes.net_http_ports);
1013 Modes.net_http_ports = strdup(argv[++j]);
1014 #else
1015 if (strcmp(argv[++j], "0")) {
1016 fprintf(stderr, "warning: --net-http-port not supported in this build, option ignored.\n");
1017 }
1018 #endif
1019 } else if (!strcmp(argv[j],"--net-sbs-port") && more) {
1020 free(Modes.net_output_sbs_ports);
1021 Modes.net_output_sbs_ports = strdup(argv[++j]);
1022 } else if (!strcmp(argv[j],"--net-buffer") && more) {
1023 Modes.net_sndbuf_size = atoi(argv[++j]);
1024 } else if (!strcmp(argv[j],"--net-verbatim")) {
1025 Modes.net_verbatim = 1;
1026 } else if (!strcmp(argv[j],"--forward-mlat")) {
1027 Modes.forward_mlat = 1;
1028 } else if (!strcmp(argv[j],"--onlyaddr")) {
1029 Modes.onlyaddr = 1;
1030 } else if (!strcmp(argv[j],"--metric")) {
1031 Modes.metric = 1;
1032 } else if (!strcmp(argv[j],"--hae") || !strcmp(argv[j],"--gnss")) {
1033 Modes.use_gnss = 1;
1034 } else if (!strcmp(argv[j],"--aggressive")) {
1035 #ifdef ALLOW_AGGRESSIVE
1036 Modes.nfix_crc = MODES_MAX_BITERRORS;
1037 #else
1038 fprintf(stderr, "warning: --aggressive not supported in this build, option ignored.\n");
1039 #endif
1040 } else if (!strcmp(argv[j],"--interactive")) {
1041 Modes.interactive = Modes.throttle = 1;
1042 } else if (!strcmp(argv[j],"--throttle")) {
1043 Modes.throttle = 1;
1044 } else if (!strcmp(argv[j],"--interactive-rows") && more) {
1045 Modes.interactive_rows = atoi(argv[++j]);
1046 } else if (!strcmp(argv[j],"--interactive-ttl") && more) {
1047 Modes.interactive_display_ttl = (uint64_t)(1000 * atof(argv[++j]));
1048 } else if (!strcmp(argv[j],"--lat") && more) {
1049 Modes.fUserLat = atof(argv[++j]);
1050 } else if (!strcmp(argv[j],"--lon") && more) {
1051 Modes.fUserLon = atof(argv[++j]);
1052 } else if (!strcmp(argv[j],"--max-range") && more) {
1053 Modes.maxRange = atof(argv[++j]) * 1852.0; // convert to metres
1054 } else if (!strcmp(argv[j],"--debug") && more) {
1055 char *f = argv[++j];
1056 while(*f) {
1057 switch(*f) {
1058 case 'D': Modes.debug |= MODES_DEBUG_DEMOD; break;
1059 case 'd': Modes.debug |= MODES_DEBUG_DEMODERR; break;
1060 case 'C': Modes.debug |= MODES_DEBUG_GOODCRC; break;
1061 case 'c': Modes.debug |= MODES_DEBUG_BADCRC; break;
1062 case 'p': Modes.debug |= MODES_DEBUG_NOPREAMBLE; break;
1063 case 'n': Modes.debug |= MODES_DEBUG_NET; break;
1064 case 'j': Modes.debug |= MODES_DEBUG_JS; break;
1065 default:
1066 fprintf(stderr, "Unknown debugging flag: %c\n", *f);
1067 exit(1);
1068 break;
1069 }
1070 f++;
1071 }
1072 } else if (!strcmp(argv[j],"--stats")) {
1073 if (!Modes.stats)
1074 Modes.stats = (uint64_t)1 << 60; // "never"
1075 } else if (!strcmp(argv[j],"--stats-range")) {
1076 Modes.stats_range_histo = 1;
1077 } else if (!strcmp(argv[j],"--stats-every") && more) {
1078 Modes.stats = (uint64_t) (1000 * atof(argv[++j]));
1079 } else if (!strcmp(argv[j],"--snip") && more) {
1080 snipMode(atoi(argv[++j]));
1081 exit(0);
1082 } else if (!strcmp(argv[j],"--help")) {
1083 showHelp();
1084 exit(0);
1085 } else if (!strcmp(argv[j],"--ppm") && more) {
1086 Modes.ppm_error = atoi(argv[++j]);
1087 #ifdef HAVE_RTL_BIAST
1088 } else if (!strcmp(argv[j], "--enable-rtlsdr-biast")) {
1089 Modes.enable_rtlsdr_biast = 1;
1090 #endif
1091 } else if (!strcmp(argv[j],"--quiet")) {
1092 Modes.quiet = 1;
1093 } else if (!strcmp(argv[j],"--show-only") && more) {
1094 Modes.show_only = (uint32_t) strtoul(argv[++j], NULL, 16);
1095 } else if (!strcmp(argv[j],"--mlat")) {
1096 Modes.mlat = 1;
1097 } else if (!strcmp(argv[j],"--interactive-rtl1090")) {
1098 Modes.interactive = 1;
1099 Modes.interactive_rtl1090 = 1;
1100 } else if (!strcmp(argv[j],"--oversample")) {
1101 // Ignored
1102 } else if (!strcmp(argv[j], "--html-dir") && more) {
1103 Modes.html_dir = strdup(argv[++j]);
1104 #ifndef _WIN32
1105 } else if (!strcmp(argv[j], "--write-json") && more) {
1106 Modes.json_dir = strdup(argv[++j]);
1107 } else if (!strcmp(argv[j], "--write-json-every") && more) {
1108 Modes.json_interval = (uint64_t)(1000 * atof(argv[++j]));
1109 if (Modes.json_interval < 100) // 0.1s
1110 Modes.json_interval = 100;
1111 } else if (!strcmp(argv[j], "--json-location-accuracy") && more) {
1112 Modes.json_location_accuracy = atoi(argv[++j]);
1113 #endif
1114 } else {
1115 fprintf(stderr,
1116 "Unknown or not enough arguments for option '%s'.\n\n",
1117 argv[j]);
1118 showHelp();
1119 exit(1);
1120 }
1121 }
1122
1123 #ifdef _WIN32
1124 // Try to comply with the Copyright license conditions for binary distribution
1125 if (!Modes.quiet) {showCopyright();}
1126 #endif
1127
1128 #ifndef _WIN32
1129 // Setup for SIGWINCH for handling lines
1130 if (Modes.interactive) {signal(SIGWINCH, sigWinchCallback);}
1131 #endif
1132
1133 // Initialization
1134 log_with_timestamp("%s %s starting up.", MODES_DUMP1090_VARIANT, MODES_DUMP1090_VERSION);
1135 modesInit();
1136
1137 if (Modes.net_only) {
1138 fprintf(stderr,"Net-only mode, no RTL device or file open.\n");
1139 } else if (Modes.filename == NULL) {
1140 if (modesInitRTLSDR() < 0) {
1141 exit(1);
1142 }
1143 } else {
1144 if (Modes.filename[0] == '-' && Modes.filename[1] == '\0') {
1145 Modes.fd = STDIN_FILENO;
1146 } else if ((Modes.fd = open(Modes.filename,
1147 #ifdef _WIN32
1148 (O_RDONLY | O_BINARY)
1149 #else
1150 (O_RDONLY)
1151 #endif
1152 )) == -1) {
1153 perror("Opening data file");
1154 exit(1);
1155 }
1156 }
1157 if (Modes.net) modesInitNet();
1158
1159 // init stats:
1160 Modes.stats_current.start = Modes.stats_current.end =
1161 Modes.stats_alltime.start = Modes.stats_alltime.end =
1162 Modes.stats_periodic.start = Modes.stats_periodic.end =
1163 Modes.stats_5min.start = Modes.stats_5min.end =
1164 Modes.stats_15min.start = Modes.stats_15min.end = mstime();
1165
1166 for (j = 0; j < 15; ++j)
1167 Modes.stats_1min[j].start = Modes.stats_1min[j].end = Modes.stats_current.start;
1168
1169 // write initial json files so they're not missing
1170 writeJsonToFile("receiver.json", generateReceiverJson);
1171 writeJsonToFile("stats.json", generateStatsJson);
1172 writeJsonToFile("aircraft.json", generateAircraftJson);
1173
1174 // If the user specifies --net-only, just run in order to serve network
1175 // clients without reading data from the RTL device
1176 if (Modes.net_only) {
1177 while (!Modes.exit) {
1178 struct timespec start_time;
1179
1180 start_cpu_timing(&start_time);
1181 backgroundTasks();
1182 end_cpu_timing(&start_time, &Modes.stats_current.background_cpu);
1183
1184 usleep(100000);
1185 }
1186 } else {
1187 int watchdogCounter = 10; // about 1 second
1188
1189 // Create the thread that will read the data from the device.
1190 pthread_mutex_lock(&Modes.data_mutex);
1191 pthread_create(&Modes.reader_thread, NULL, readerThreadEntryPoint, NULL);
1192
1193 while (Modes.exit == 0) {
1194 struct timespec start_time;
1195
1196 if (Modes.first_free_buffer == Modes.first_filled_buffer) {
1197 /* wait for more data.
1198 * we should be getting data every 50-60ms. wait for max 100ms before we give up and do some background work.
1199 * this is fairly aggressive as all our network I/O runs out of the background work!
1200 */
1201
1202 struct timespec ts;
1203 clock_gettime(CLOCK_REALTIME, &ts);
1204 ts.tv_nsec += 100000000;
1205 normalize_timespec(&ts);
1206
1207 pthread_cond_timedwait(&Modes.data_cond, &Modes.data_mutex, &ts); // This unlocks Modes.data_mutex, and waits for Modes.data_cond
1208 }
1209
1210 // Modes.data_mutex is locked, and possibly we have data.
1211
1212 // copy out reader CPU time and reset it
1213 add_timespecs(&Modes.reader_cpu_accumulator, &Modes.stats_current.reader_cpu, &Modes.stats_current.reader_cpu);
1214 Modes.reader_cpu_accumulator.tv_sec = 0;
1215 Modes.reader_cpu_accumulator.tv_nsec = 0;
1216
1217 if (Modes.first_free_buffer != Modes.first_filled_buffer) {
1218 // FIFO is not empty, process one buffer.
1219
1220 struct mag_buf *buf;
1221
1222 start_cpu_timing(&start_time);
1223 buf = &Modes.mag_buffers[Modes.first_filled_buffer];
1224
1225 // Process data after releasing the lock, so that the capturing
1226 // thread can read data while we perform computationally expensive
1227 // stuff at the same time.
1228 pthread_mutex_unlock(&Modes.data_mutex);
1229
1230 demodulate2400(buf);
1231 if (Modes.mode_ac) {
1232 demodulate2400AC(buf);
1233 }
1234
1235 Modes.stats_current.samples_processed += buf->length;
1236 Modes.stats_current.samples_dropped += buf->dropped;
1237 end_cpu_timing(&start_time, &Modes.stats_current.demod_cpu);
1238
1239 // Mark the buffer we just processed as completed.
1240 pthread_mutex_lock(&Modes.data_mutex);
1241 Modes.first_filled_buffer = (Modes.first_filled_buffer + 1) % MODES_MAG_BUFFERS;
1242 pthread_cond_signal(&Modes.data_cond);
1243 pthread_mutex_unlock(&Modes.data_mutex);
1244 watchdogCounter = 10;
1245 } else {
1246 // Nothing to process this time around.
1247 pthread_mutex_unlock(&Modes.data_mutex);
1248 if (--watchdogCounter <= 0) {
1249 log_with_timestamp("No data received from the dongle for a long time, it may have wedged");
1250 watchdogCounter = 600;
1251 }
1252 }
1253
1254 start_cpu_timing(&start_time);
1255 backgroundTasks();
1256 end_cpu_timing(&start_time, &Modes.stats_current.background_cpu);
1257
1258 pthread_mutex_lock(&Modes.data_mutex);
1259 }
1260
1261 pthread_mutex_unlock(&Modes.data_mutex);
1262
1263 log_with_timestamp("Waiting for receive thread termination");
1264 pthread_join(Modes.reader_thread,NULL); // Wait on reader thread exit
1265 pthread_cond_destroy(&Modes.data_cond); // Thread cleanup - only after the reader thread is dead!
1266 pthread_mutex_destroy(&Modes.data_mutex);
1267 }
1268
1269 // If --stats were given, print statistics
1270 if (Modes.stats) {
1271 display_total_stats();
1272 }
1273
1274 cleanup_converter(Modes.converter_state);
1275 log_with_timestamp("Normal exit.");
1276
1277 #ifndef _WIN32
1278 pthread_exit(0);
1279 #else
1280 return (0);
1281 #endif
1282 }
1283 //
1284 //=========================================================================
1285 //