Debian Codegraph @

dump1090.c

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