rtl_adsb.c 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490
  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. #include "convenience/convenience.h"
  40. #ifdef _WIN32
  41. #define sleep Sleep
  42. #define round(x) (x > 0.0 ? floor(x + 0.5): ceil(x - 0.5))
  43. #endif
  44. #define ADSB_RATE 2000000
  45. #define ADSB_FREQ 1090000000
  46. #define DEFAULT_ASYNC_BUF_NUMBER 12
  47. #define DEFAULT_BUF_LENGTH (16 * 16384)
  48. #define AUTO_GAIN -100
  49. #define MESSAGEGO 253
  50. #define OVERWRITE 254
  51. #define BADSAMPLE 255
  52. static pthread_t demod_thread;
  53. static pthread_mutex_t data_ready; /* locked when no data available */
  54. static volatile int do_exit = 0;
  55. static rtlsdr_dev_t *dev = NULL;
  56. uint16_t squares[256];
  57. /* todo, bundle these up in a struct */
  58. uint8_t *buffer; /* also abused for uint16_t */
  59. int verbose_output = 0;
  60. int short_output = 0;
  61. int quality = 10;
  62. int allowed_errors = 5;
  63. FILE *file;
  64. int adsb_frame[14];
  65. #define preamble_len 16
  66. #define long_frame 112
  67. #define short_frame 56
  68. void usage(void)
  69. {
  70. fprintf(stderr,
  71. "rtl_adsb, a simple ADS-B decoder\n\n"
  72. "Use:\trtl_adsb [-R] [-g gain] [-p ppm] [output file]\n"
  73. "\t[-d device_index (default: 0)]\n"
  74. "\t[-V verbove output (default: off)]\n"
  75. "\t[-S show short frames (default: off)]\n"
  76. "\t[-Q quality (0: no sanity checks, 0.5: half bit, 1: one bit (default), 2: two bits)]\n"
  77. "\t[-e allowed_errors (default: 5)]\n"
  78. "\t[-g tuner_gain (default: automatic)]\n"
  79. "\t[-p ppm_error (default: 0)]\n"
  80. "\tfilename (a '-' dumps samples to stdout)\n"
  81. "\t (omitting the filename also uses stdout)\n\n"
  82. "Streaming with netcat:\n"
  83. "\trtl_adsb | netcat -lp 8080\n"
  84. "\twhile true; do rtl_adsb | nc -lp 8080; done\n"
  85. "Streaming with socat:\n"
  86. "\trtl_adsb | socat -u - TCP4:sdrsharp.com:47806\n"
  87. "\n");
  88. exit(1);
  89. }
  90. #ifdef _WIN32
  91. BOOL WINAPI
  92. sighandler(int signum)
  93. {
  94. if (CTRL_C_EVENT == signum) {
  95. fprintf(stderr, "Signal caught, exiting!\n");
  96. do_exit = 1;
  97. rtlsdr_cancel_async(dev);
  98. return TRUE;
  99. }
  100. return FALSE;
  101. }
  102. #else
  103. static void sighandler(int signum)
  104. {
  105. fprintf(stderr, "Signal caught, exiting!\n");
  106. do_exit = 1;
  107. rtlsdr_cancel_async(dev);
  108. }
  109. #endif
  110. void display(int *frame, int len)
  111. {
  112. int i, df;
  113. if (!short_output && len <= short_frame) {
  114. return;}
  115. df = (frame[0] >> 3) & 0x1f;
  116. if (quality == 0 && !(df==11 || df==17 || df==18 || df==19)) {
  117. return;}
  118. fprintf(file, "*");
  119. for (i=0; i<((len+7)/8); i++) {
  120. fprintf(file, "%02x", frame[i]);}
  121. fprintf(file, ";\r\n");
  122. if (!verbose_output) {
  123. return;}
  124. fprintf(file, "DF=%i CA=%i\n", df, frame[0] & 0x07);
  125. fprintf(file, "ICAO Address=%06x\n", frame[1] << 16 | frame[2] << 8 | frame[3]);
  126. if (len <= short_frame) {
  127. return;}
  128. fprintf(file, "PI=0x%06x\n", frame[11] << 16 | frame[12] << 8 | frame[13]);
  129. fprintf(file, "Type Code=%i S.Type/Ant.=%x\n", (frame[4] >> 3) & 0x1f, frame[4] & 0x07);
  130. fprintf(file, "--------------\n");
  131. }
  132. int abs8(int x)
  133. /* do not subtract 128 from the raw iq, this handles it */
  134. {
  135. if (x >= 128) {
  136. return x - 128;}
  137. return 128 - x;
  138. }
  139. void squares_precompute(void)
  140. /* equiv to abs(x-128) ^ 2 */
  141. {
  142. int i, j;
  143. // todo, check if this LUT is actually any faster
  144. for (i=0; i<256; i++) {
  145. j = abs8(i);
  146. squares[i] = (uint16_t)(j*j);
  147. }
  148. }
  149. int magnitute(uint8_t *buf, int len)
  150. /* takes i/q, changes buf in place (16 bit), returns new len (16 bit) */
  151. {
  152. int i;
  153. uint16_t *m;
  154. for (i=0; i<len; i+=2) {
  155. m = (uint16_t*)(&buf[i]);
  156. *m = squares[buf[i]] + squares[buf[i+1]];
  157. }
  158. return len/2;
  159. }
  160. inline uint16_t single_manchester(uint16_t a, uint16_t b, uint16_t c, uint16_t d)
  161. /* takes 4 consecutive real samples, return 0 or 1, BADSAMPLE on error */
  162. {
  163. int bit, bit_p;
  164. bit_p = a > b;
  165. bit = c > d;
  166. if (quality == 0) {
  167. return bit;}
  168. if (quality == 5) {
  169. if ( bit && bit_p && b > c) {
  170. return BADSAMPLE;}
  171. if (!bit && !bit_p && b < c) {
  172. return BADSAMPLE;}
  173. return bit;
  174. }
  175. if (quality == 10) {
  176. if ( bit && bit_p && c > b) {
  177. return 1;}
  178. if ( bit && !bit_p && d < b) {
  179. return 1;}
  180. if (!bit && bit_p && d > b) {
  181. return 0;}
  182. if (!bit && !bit_p && c < b) {
  183. return 0;}
  184. return BADSAMPLE;
  185. }
  186. if ( bit && bit_p && c > b && d < a) {
  187. return 1;}
  188. if ( bit && !bit_p && c > a && d < b) {
  189. return 1;}
  190. if (!bit && bit_p && c < a && d > b) {
  191. return 0;}
  192. if (!bit && !bit_p && c < b && d > a) {
  193. return 0;}
  194. return BADSAMPLE;
  195. }
  196. inline uint16_t min16(uint16_t a, uint16_t b)
  197. {
  198. return a<b ? a : b;
  199. }
  200. inline uint16_t max16(uint16_t a, uint16_t b)
  201. {
  202. return a>b ? a : b;
  203. }
  204. inline int preamble(uint16_t *buf, int i)
  205. /* returns 0/1 for preamble at index i */
  206. {
  207. int i2;
  208. uint16_t low = 0;
  209. uint16_t high = 65535;
  210. for (i2=0; i2<preamble_len; i2++) {
  211. switch (i2) {
  212. case 0:
  213. case 2:
  214. case 7:
  215. case 9:
  216. //high = min16(high, buf[i+i2]);
  217. high = buf[i+i2];
  218. break;
  219. default:
  220. //low = max16(low, buf[i+i2]);
  221. low = buf[i+i2];
  222. break;
  223. }
  224. if (high <= low) {
  225. return 0;}
  226. }
  227. return 1;
  228. }
  229. void manchester(uint16_t *buf, int len)
  230. /* overwrites magnitude buffer with valid bits (BADSAMPLE on errors) */
  231. {
  232. /* a and b hold old values to verify local manchester */
  233. uint16_t a=0, b=0;
  234. uint16_t bit;
  235. int i, i2, start, errors;
  236. int maximum_i = len - 1; // len-1 since we look at i and i+1
  237. // todo, allow wrap across buffers
  238. i = 0;
  239. while (i < maximum_i) {
  240. /* find preamble */
  241. for ( ; i < (len - preamble_len); i++) {
  242. if (!preamble(buf, i)) {
  243. continue;}
  244. a = buf[i];
  245. b = buf[i+1];
  246. for (i2=0; i2<preamble_len; i2++) {
  247. buf[i+i2] = MESSAGEGO;}
  248. i += preamble_len;
  249. break;
  250. }
  251. i2 = start = i;
  252. errors = 0;
  253. /* mark bits until encoding breaks */
  254. for ( ; i < maximum_i; i+=2, i2++) {
  255. bit = single_manchester(a, b, buf[i], buf[i+1]);
  256. a = buf[i];
  257. b = buf[i+1];
  258. if (bit == BADSAMPLE) {
  259. errors += 1;
  260. if (errors > allowed_errors) {
  261. buf[i2] = BADSAMPLE;
  262. break;
  263. } else {
  264. bit = a > b;
  265. /* these don't have to match the bit */
  266. a = 0;
  267. b = 65535;
  268. }
  269. }
  270. buf[i] = buf[i+1] = OVERWRITE;
  271. buf[i2] = bit;
  272. }
  273. }
  274. }
  275. void messages(uint16_t *buf, int len)
  276. {
  277. int i, i2, start, preamble_found;
  278. int data_i, index, shift, frame_len;
  279. // todo, allow wrap across buffers
  280. for (i=0; i<len; i++) {
  281. if (buf[i] > 1) {
  282. continue;}
  283. frame_len = long_frame;
  284. data_i = 0;
  285. for (index=0; index<14; index++) {
  286. adsb_frame[index] = 0;}
  287. for(; i<len && buf[i]<=1 && data_i<frame_len; i++, data_i++) {
  288. if (buf[i]) {
  289. index = data_i / 8;
  290. shift = 7 - (data_i % 8);
  291. adsb_frame[index] |= (uint8_t)(1<<shift);
  292. }
  293. if (data_i == 7) {
  294. if (adsb_frame[0] == 0) {
  295. break;}
  296. if (adsb_frame[0] & 0x80) {
  297. frame_len = long_frame;}
  298. else {
  299. frame_len = short_frame;}
  300. }
  301. }
  302. if (data_i < (frame_len-1)) {
  303. continue;}
  304. display(adsb_frame, frame_len);
  305. fflush(file);
  306. }
  307. }
  308. static void rtlsdr_callback(unsigned char *buf, uint32_t len, void *ctx)
  309. {
  310. if (do_exit) {
  311. return;}
  312. memcpy(buffer, buf, len);
  313. pthread_mutex_trylock(&data_ready);
  314. pthread_mutex_unlock(&data_ready);
  315. }
  316. static void *demod_thread_fn(void *arg)
  317. {
  318. int len;
  319. while (!do_exit) {
  320. pthread_mutex_lock(&data_ready);
  321. len = magnitute(buffer, DEFAULT_BUF_LENGTH);
  322. manchester((uint16_t*)buffer, len);
  323. messages((uint16_t*)buffer, len);
  324. }
  325. rtlsdr_cancel_async(dev);
  326. return 0;
  327. }
  328. int main(int argc, char **argv)
  329. {
  330. #ifndef _WIN32
  331. struct sigaction sigact;
  332. #endif
  333. char *filename = NULL;
  334. int n_read, r, opt;
  335. int i, gain = AUTO_GAIN; /* tenths of a dB */
  336. int dev_index = 0;
  337. int dev_given = 0;
  338. int ppm_error = 0;
  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 = verbose_device_search(optarg);
  346. dev_given = 1;
  347. break;
  348. case 'g':
  349. gain = (int)(atof(optarg) * 10);
  350. break;
  351. case 'p':
  352. ppm_error = atoi(optarg);
  353. break;
  354. case 'V':
  355. verbose_output = 1;
  356. break;
  357. case 'S':
  358. short_output = 1;
  359. break;
  360. case 'e':
  361. allowed_errors = atoi(optarg);
  362. break;
  363. case 'Q':
  364. quality = (int)(atof(optarg) * 10);
  365. break;
  366. default:
  367. usage();
  368. return 0;
  369. }
  370. }
  371. if (argc <= optind) {
  372. filename = "-";
  373. } else {
  374. filename = argv[optind];
  375. }
  376. buffer = malloc(DEFAULT_BUF_LENGTH * sizeof(uint8_t));
  377. if (!dev_given) {
  378. dev_index = verbose_device_search("0");
  379. }
  380. if (dev_index < 0) {
  381. exit(1);
  382. }
  383. r = rtlsdr_open(&dev, (uint32_t)dev_index);
  384. if (r < 0) {
  385. fprintf(stderr, "Failed to open rtlsdr device #%d.\n", dev_index);
  386. exit(1);
  387. }
  388. #ifndef _WIN32
  389. sigact.sa_handler = sighandler;
  390. sigemptyset(&sigact.sa_mask);
  391. sigact.sa_flags = 0;
  392. sigaction(SIGINT, &sigact, NULL);
  393. sigaction(SIGTERM, &sigact, NULL);
  394. sigaction(SIGQUIT, &sigact, NULL);
  395. sigaction(SIGPIPE, &sigact, NULL);
  396. #else
  397. SetConsoleCtrlHandler( (PHANDLER_ROUTINE) sighandler, TRUE );
  398. #endif
  399. if (strcmp(filename, "-") == 0) { /* Write samples to stdout */
  400. file = stdout;
  401. setvbuf(stdout, NULL, _IONBF, 0);
  402. #ifdef _WIN32
  403. _setmode(_fileno(file), _O_BINARY);
  404. #endif
  405. } else {
  406. file = fopen(filename, "wb");
  407. if (!file) {
  408. fprintf(stderr, "Failed to open %s\n", filename);
  409. exit(1);
  410. }
  411. }
  412. /* Set the tuner gain */
  413. if (gain == AUTO_GAIN) {
  414. verbose_auto_gain(dev);
  415. } else {
  416. gain = nearest_gain(dev, gain);
  417. verbose_gain_set(dev, gain);
  418. }
  419. verbose_ppm_set(dev, ppm_error);
  420. r = rtlsdr_set_agc_mode(dev, 1);
  421. /* Set the tuner frequency */
  422. verbose_set_frequency(dev, ADSB_FREQ);
  423. /* Set the sample rate */
  424. verbose_set_sample_rate(dev, ADSB_RATE);
  425. /* Reset endpoint before we start reading from it (mandatory) */
  426. verbose_reset_buffer(dev);
  427. pthread_create(&demod_thread, NULL, demod_thread_fn, (void *)(NULL));
  428. rtlsdr_read_async(dev, rtlsdr_callback, (void *)(NULL),
  429. DEFAULT_ASYNC_BUF_NUMBER,
  430. DEFAULT_BUF_LENGTH);
  431. if (do_exit) {
  432. fprintf(stderr, "\nUser cancel, exiting...\n");}
  433. else {
  434. fprintf(stderr, "\nLibrary error %d, exiting...\n", r);}
  435. rtlsdr_cancel_async(dev);
  436. pthread_mutex_destroy(&data_ready);
  437. if (file != stdout) {
  438. fclose(file);}
  439. rtlsdr_close(dev);
  440. free(buffer);
  441. return r >= 0 ? r : -r;
  442. }