rtl_adsb.c 11 KB

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