rtl_adsb.c 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518
  1. /*
  2. * rtl-sdr, turns your Realtek RTL2832 based DVB dongle into a SDR receiver
  3. * Copyright (C) 2012 by Steve Markgraf <steve@steve-m.de>
  4. * Copyright (C) 2012 by Hoernchen <la@tfc-server.de>
  5. * Copyright (C) 2012 by Kyle Keen <keenerd@gmail.com>
  6. * Copyright (C) 2012 by Youssef Touil <youssef@sdrsharp.com>
  7. * Copyright (C) 2012 by Ian Gilmour <ian@sdrsharp.com>
  8. *
  9. * This program is free software: you can redistribute it and/or modify
  10. * it under the terms of the GNU General Public License as published by
  11. * the Free Software Foundation, either version 2 of the License, or
  12. * (at your option) any later version.
  13. *
  14. * This program is distributed in the hope that it will be useful,
  15. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  16. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  17. * GNU General Public License for more details.
  18. *
  19. * You should have received a copy of the GNU General Public License
  20. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  21. */
  22. #include <errno.h>
  23. #include <signal.h>
  24. #include <string.h>
  25. #include <stdio.h>
  26. #include <stdlib.h>
  27. #include <math.h>
  28. #ifndef _WIN32
  29. #include <unistd.h>
  30. #else
  31. #include <windows.h>
  32. #include <fcntl.h>
  33. #include <io.h>
  34. #include "getopt/getopt.h"
  35. #endif
  36. #include <pthread.h>
  37. #include <libusb.h>
  38. #include "rtl-sdr.h"
  39. #ifdef _WIN32
  40. #define sleep Sleep
  41. #define round(x) (x > 0.0 ? floor(x + 0.5): ceil(x - 0.5))
  42. #endif
  43. #define ADSB_RATE 2000000
  44. #define ADSB_FREQ 1090000000
  45. #define DEFAULT_ASYNC_BUF_NUMBER 12
  46. #define DEFAULT_BUF_LENGTH (16 * 16384)
  47. #define AUTO_GAIN -100
  48. #define MESSAGEGO 253
  49. #define OVERWRITE 254
  50. #define BADSAMPLE 255
  51. static pthread_t demod_thread;
  52. static pthread_mutex_t data_ready; /* locked when no data available */
  53. static volatile int do_exit = 0;
  54. static rtlsdr_dev_t *dev = NULL;
  55. uint16_t squares[256];
  56. /* todo, bundle these up in a struct */
  57. uint8_t *buffer; /* also abused for uint16_t */
  58. int verbose_output = 0;
  59. int short_output = 0;
  60. int quality = 10;
  61. int allowed_errors = 5;
  62. FILE *file;
  63. int adsb_frame[14];
  64. #define preamble_len 16
  65. #define long_frame 112
  66. #define short_frame 56
  67. void usage(void)
  68. {
  69. fprintf(stderr,
  70. "rtl_adsb, a simple ADS-B decoder\n\n"
  71. "Use:\trtl_adsb [-R] [-g gain] [-p ppm] [output file]\n"
  72. "\t[-d device_index (default: 0)]\n"
  73. "\t[-V verbove output (default: off)]\n"
  74. "\t[-S show short frames (default: off)]\n"
  75. "\t[-Q quality (0: no sanity checks, 0.5: half bit, 1: one bit (default), 2: two bits)]\n"
  76. "\t[-e allowed_errors (default: 5)]\n"
  77. "\t[-g tuner_gain (default: automatic)]\n"
  78. "\t[-p ppm_error (default: 0)]\n"
  79. "\tfilename (a '-' dumps samples to stdout)\n"
  80. "\t (omitting the filename also uses stdout)\n\n"
  81. "Streaming with netcat:\n"
  82. "\trtl_adsb | netcat -lp 8080\n"
  83. "\twhile true; do rtl_adsb | nc -lp 8080; done\n"
  84. "Streaming with socat:\n"
  85. "\trtl_adsb | socat -u - TCP4:sdrsharp.com:47806\n"
  86. "\n");
  87. exit(1);
  88. }
  89. #ifdef _WIN32
  90. BOOL WINAPI
  91. sighandler(int signum)
  92. {
  93. if (CTRL_C_EVENT == signum) {
  94. fprintf(stderr, "Signal caught, exiting!\n");
  95. do_exit = 1;
  96. rtlsdr_cancel_async(dev);
  97. return TRUE;
  98. }
  99. return FALSE;
  100. }
  101. #else
  102. static void sighandler(int signum)
  103. {
  104. fprintf(stderr, "Signal caught, exiting!\n");
  105. do_exit = 1;
  106. rtlsdr_cancel_async(dev);
  107. }
  108. #endif
  109. void display(int *frame, int len)
  110. {
  111. int i, df;
  112. if (!short_output && len <= short_frame) {
  113. return;}
  114. df = (frame[0] >> 3) & 0x1f;
  115. if (quality == 0 && !(df==11 || df==17 || df==18 || df==19)) {
  116. return;}
  117. fprintf(file, "*");
  118. for (i=0; i<((len+7)/8); i++) {
  119. fprintf(file, "%02x", frame[i]);}
  120. fprintf(file, ";\r\n");
  121. if (!verbose_output) {
  122. return;}
  123. fprintf(file, "DF=%i CA=%i\n", df, frame[0] & 0x07);
  124. fprintf(file, "ICAO Address=%06x\n", frame[1] << 16 | frame[2] << 8 | frame[3]);
  125. if (len <= short_frame) {
  126. return;}
  127. fprintf(file, "PI=0x%06x\n", frame[11] << 16 | frame[12] << 8 | frame[13]);
  128. fprintf(file, "Type Code=%i S.Type/Ant.=%x\n", (frame[4] >> 3) & 0x1f, frame[4] & 0x07);
  129. fprintf(file, "--------------\n");
  130. }
  131. int abs8(int x)
  132. /* do not subtract 128 from the raw iq, this handles it */
  133. {
  134. if (x >= 128) {
  135. return x - 128;}
  136. return 128 - x;
  137. }
  138. void squares_precompute(void)
  139. /* equiv to abs(x-128) ^ 2 */
  140. {
  141. int i, j;
  142. // todo, check if this LUT is actually any faster
  143. for (i=0; i<256; i++) {
  144. j = abs8(i);
  145. squares[i] = (uint16_t)(j*j);
  146. }
  147. }
  148. int magnitute(uint8_t *buf, int len)
  149. /* takes i/q, changes buf in place (16 bit), returns new len (16 bit) */
  150. {
  151. int i;
  152. uint16_t *m;
  153. for (i=0; i<len; i+=2) {
  154. m = (uint16_t*)(&buf[i]);
  155. *m = squares[buf[i]] + squares[buf[i+1]];
  156. }
  157. return len/2;
  158. }
  159. inline uint16_t single_manchester(uint16_t a, uint16_t b, uint16_t c, uint16_t d)
  160. /* takes 4 consecutive real samples, return 0 or 1, BADSAMPLE on error */
  161. {
  162. int bit, bit_p;
  163. bit_p = a > b;
  164. bit = c > d;
  165. if (quality == 0) {
  166. return bit;}
  167. if (quality == 5) {
  168. if ( bit && bit_p && b > c) {
  169. return BADSAMPLE;}
  170. if (!bit && !bit_p && b < c) {
  171. return BADSAMPLE;}
  172. return bit;
  173. }
  174. if (quality == 10) {
  175. if ( bit && bit_p && c > b) {
  176. return 1;}
  177. if ( bit && !bit_p && d < b) {
  178. return 1;}
  179. if (!bit && bit_p && d > b) {
  180. return 0;}
  181. if (!bit && !bit_p && c < b) {
  182. return 0;}
  183. return BADSAMPLE;
  184. }
  185. if ( bit && bit_p && c > b && d < a) {
  186. return 1;}
  187. if ( bit && !bit_p && c > a && d < b) {
  188. return 1;}
  189. if (!bit && bit_p && c < a && d > b) {
  190. return 0;}
  191. if (!bit && !bit_p && c < b && d > a) {
  192. return 0;}
  193. return BADSAMPLE;
  194. }
  195. inline uint16_t min16(uint16_t a, uint16_t b)
  196. {
  197. return a<b ? a : b;
  198. }
  199. inline uint16_t max16(uint16_t a, uint16_t b)
  200. {
  201. return a>b ? a : b;
  202. }
  203. inline int preamble(uint16_t *buf, int i)
  204. /* returns 0/1 for preamble at index i */
  205. {
  206. int i2;
  207. uint16_t low = 0;
  208. uint16_t high = 65535;
  209. for (i2=0; i2<preamble_len; i2++) {
  210. switch (i2) {
  211. case 0:
  212. case 2:
  213. case 7:
  214. case 9:
  215. //high = min16(high, buf[i+i2]);
  216. high = buf[i+i2];
  217. break;
  218. default:
  219. //low = max16(low, buf[i+i2]);
  220. low = buf[i+i2];
  221. break;
  222. }
  223. if (high <= low) {
  224. return 0;}
  225. }
  226. return 1;
  227. }
  228. void manchester(uint16_t *buf, int len)
  229. /* overwrites magnitude buffer with valid bits (BADSAMPLE on errors) */
  230. {
  231. /* a and b hold old values to verify local manchester */
  232. uint16_t a=0, b=0;
  233. uint16_t bit;
  234. int i, i2, start, errors;
  235. int maximum_i = len - 1; // len-1 since we look at i and i+1
  236. // todo, allow wrap across buffers
  237. i = 0;
  238. while (i < maximum_i) {
  239. /* find preamble */
  240. for ( ; i < (len - preamble_len); i++) {
  241. if (!preamble(buf, i)) {
  242. continue;}
  243. a = buf[i];
  244. b = buf[i+1];
  245. for (i2=0; i2<preamble_len; i2++) {
  246. buf[i+i2] = MESSAGEGO;}
  247. i += preamble_len;
  248. break;
  249. }
  250. i2 = start = i;
  251. errors = 0;
  252. /* mark bits until encoding breaks */
  253. for ( ; i < maximum_i; i+=2, i2++) {
  254. bit = single_manchester(a, b, buf[i], buf[i+1]);
  255. a = buf[i];
  256. b = buf[i+1];
  257. if (bit == BADSAMPLE) {
  258. errors += 1;
  259. if (errors > allowed_errors) {
  260. buf[i2] = BADSAMPLE;
  261. break;
  262. } else {
  263. bit = a > b;
  264. /* these don't have to match the bit */
  265. a = 0;
  266. b = 65535;
  267. }
  268. }
  269. buf[i] = buf[i+1] = OVERWRITE;
  270. buf[i2] = bit;
  271. }
  272. }
  273. }
  274. void messages(uint16_t *buf, int len)
  275. {
  276. int i, i2, start, preamble_found;
  277. int data_i, index, shift, frame_len;
  278. // todo, allow wrap across buffers
  279. for (i=0; i<len; i++) {
  280. if (buf[i] > 1) {
  281. continue;}
  282. frame_len = long_frame;
  283. data_i = 0;
  284. for (index=0; index<14; index++) {
  285. adsb_frame[index] = 0;}
  286. for(; i<len && buf[i]<=1 && data_i<frame_len; i++, data_i++) {
  287. if (buf[i]) {
  288. index = data_i / 8;
  289. shift = 7 - (data_i % 8);
  290. adsb_frame[index] |= (uint8_t)(1<<shift);
  291. }
  292. if (data_i == 7) {
  293. if (adsb_frame[0] == 0) {
  294. break;}
  295. if (adsb_frame[0] & 0x80) {
  296. frame_len = long_frame;}
  297. else {
  298. frame_len = short_frame;}
  299. }
  300. }
  301. if (data_i < (frame_len-1)) {
  302. continue;}
  303. display(adsb_frame, frame_len);
  304. fflush(file);
  305. }
  306. }
  307. static void rtlsdr_callback(unsigned char *buf, uint32_t len, void *ctx)
  308. {
  309. if (do_exit) {
  310. return;}
  311. memcpy(buffer, buf, len);
  312. pthread_mutex_trylock(&data_ready);
  313. pthread_mutex_unlock(&data_ready);
  314. }
  315. static void *demod_thread_fn(void *arg)
  316. {
  317. int len;
  318. while (!do_exit) {
  319. pthread_mutex_lock(&data_ready);
  320. len = magnitute(buffer, DEFAULT_BUF_LENGTH);
  321. manchester((uint16_t*)buffer, len);
  322. messages((uint16_t*)buffer, len);
  323. }
  324. rtlsdr_cancel_async(dev);
  325. return 0;
  326. }
  327. int main(int argc, char **argv)
  328. {
  329. #ifndef _WIN32
  330. struct sigaction sigact;
  331. #endif
  332. char *filename = NULL;
  333. int n_read, r, opt;
  334. int i, gain = AUTO_GAIN; /* tenths of a dB */
  335. uint32_t dev_index = 0;
  336. int device_count;
  337. int ppm_error = 0;
  338. char vendor[256], product[256], serial[256];
  339. pthread_mutex_init(&data_ready, NULL);
  340. squares_precompute();
  341. while ((opt = getopt(argc, argv, "d:g:p:e:Q:VS")) != -1)
  342. {
  343. switch (opt) {
  344. case 'd':
  345. dev_index = atoi(optarg);
  346. break;
  347. case 'g':
  348. gain = (int)(atof(optarg) * 10);
  349. break;
  350. case 'p':
  351. ppm_error = atoi(optarg);
  352. break;
  353. case 'V':
  354. verbose_output = 1;
  355. break;
  356. case 'S':
  357. short_output = 1;
  358. break;
  359. case 'e':
  360. allowed_errors = atoi(optarg);
  361. break;
  362. case 'Q':
  363. quality = (int)(atof(optarg) * 10);
  364. break;
  365. default:
  366. usage();
  367. return 0;
  368. }
  369. }
  370. if (argc <= optind) {
  371. filename = "-";
  372. } else {
  373. filename = argv[optind];
  374. }
  375. buffer = malloc(DEFAULT_BUF_LENGTH * sizeof(uint8_t));
  376. device_count = rtlsdr_get_device_count();
  377. if (!device_count) {
  378. fprintf(stderr, "No supported devices found.\n");
  379. exit(1);
  380. }
  381. fprintf(stderr, "Found %d device(s):\n", device_count);
  382. for (i = 0; i < device_count; i++) {
  383. rtlsdr_get_device_usb_strings(i, vendor, product, serial);
  384. fprintf(stderr, " %d: %s, %s, SN: %s\n", i, vendor, product, serial);
  385. }
  386. fprintf(stderr, "\n");
  387. fprintf(stderr, "Using device %d: %s\n",
  388. dev_index, rtlsdr_get_device_name(dev_index));
  389. r = rtlsdr_open(&dev, dev_index);
  390. if (r < 0) {
  391. fprintf(stderr, "Failed to open rtlsdr device #%d.\n", dev_index);
  392. exit(1);
  393. }
  394. #ifndef _WIN32
  395. sigact.sa_handler = sighandler;
  396. sigemptyset(&sigact.sa_mask);
  397. sigact.sa_flags = 0;
  398. sigaction(SIGINT, &sigact, NULL);
  399. sigaction(SIGTERM, &sigact, NULL);
  400. sigaction(SIGQUIT, &sigact, NULL);
  401. sigaction(SIGPIPE, &sigact, NULL);
  402. #else
  403. SetConsoleCtrlHandler( (PHANDLER_ROUTINE) sighandler, TRUE );
  404. #endif
  405. if (strcmp(filename, "-") == 0) { /* Write samples to stdout */
  406. file = stdout;
  407. setvbuf(stdout, NULL, _IONBF, 0);
  408. #ifdef _WIN32
  409. _setmode(_fileno(file), _O_BINARY);
  410. #endif
  411. } else {
  412. file = fopen(filename, "wb");
  413. if (!file) {
  414. fprintf(stderr, "Failed to open %s\n", filename);
  415. exit(1);
  416. }
  417. }
  418. /* Set the tuner gain */
  419. if (gain == AUTO_GAIN) {
  420. r = rtlsdr_set_tuner_gain_mode(dev, 0);
  421. } else {
  422. r = rtlsdr_set_tuner_gain_mode(dev, 1);
  423. r = rtlsdr_set_tuner_gain(dev, gain);
  424. }
  425. if (r != 0) {
  426. fprintf(stderr, "WARNING: Failed to set tuner gain.\n");
  427. } else if (gain == AUTO_GAIN) {
  428. fprintf(stderr, "Tuner gain set to automatic.\n");
  429. } else {
  430. fprintf(stderr, "Tuner gain set to %0.2f dB.\n", gain/10.0);
  431. }
  432. r = rtlsdr_set_freq_correction(dev, ppm_error);
  433. r = rtlsdr_set_agc_mode(dev, 1);
  434. /* Set the tuner frequency */
  435. r = rtlsdr_set_center_freq(dev, ADSB_FREQ);
  436. if (r < 0) {
  437. fprintf(stderr, "WARNING: Failed to set center freq.\n");}
  438. else {
  439. fprintf(stderr, "Tuned to %u Hz.\n", ADSB_FREQ);}
  440. /* Set the sample rate */
  441. fprintf(stderr, "Sampling at %u Hz.\n", ADSB_RATE);
  442. r = rtlsdr_set_sample_rate(dev, ADSB_RATE);
  443. if (r < 0) {
  444. fprintf(stderr, "WARNING: Failed to set sample rate.\n");}
  445. /* Reset endpoint before we start reading from it (mandatory) */
  446. r = rtlsdr_reset_buffer(dev);
  447. if (r < 0) {
  448. fprintf(stderr, "WARNING: Failed to reset buffers.\n");}
  449. /* flush old junk */
  450. sleep(1);
  451. rtlsdr_read_sync(dev, NULL, 4096, NULL);
  452. pthread_create(&demod_thread, NULL, demod_thread_fn, (void *)(NULL));
  453. rtlsdr_read_async(dev, rtlsdr_callback, (void *)(NULL),
  454. DEFAULT_ASYNC_BUF_NUMBER,
  455. DEFAULT_BUF_LENGTH);
  456. if (do_exit) {
  457. fprintf(stderr, "\nUser cancel, exiting...\n");}
  458. else {
  459. fprintf(stderr, "\nLibrary error %d, exiting...\n", r);}
  460. rtlsdr_cancel_async(dev);
  461. pthread_mutex_destroy(&data_ready);
  462. if (file != stdout) {
  463. fclose(file);}
  464. rtlsdr_close(dev);
  465. free(buffer);
  466. return r >= 0 ? r : -r;
  467. }