rtl_power.c 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872
  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. *
  7. * This program is free software: you can redistribute it and/or modify
  8. * it under the terms of the GNU General Public License as published by
  9. * the Free Software Foundation, either version 2 of the License, or
  10. * (at your option) any later version.
  11. *
  12. * This program is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. * GNU 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. /*
  21. * rtl_power: general purpose FFT integrator
  22. * -f low_freq:high_freq:max_bin_size
  23. * -i seconds
  24. * outputs CSV
  25. * time, low, high, step, db, db, db ...
  26. * db optional? raw output might be better for noise correction
  27. * todo:
  28. * threading
  29. * randomized hopping
  30. * noise correction
  31. * continuous IIR
  32. * general astronomy usefulness
  33. * multiple dongles
  34. * multiple FFT workers
  35. * fft bins smaller than 61Hz
  36. * bandwidths smaller than 1MHz
  37. * check edge cropping for off-by-one and rounding errors
  38. */
  39. #include <errno.h>
  40. #include <signal.h>
  41. #include <string.h>
  42. #include <stdio.h>
  43. #include <stdlib.h>
  44. #include <time.h>
  45. #ifndef _WIN32
  46. #include <unistd.h>
  47. #else
  48. #include <windows.h>
  49. #include <fcntl.h>
  50. #include <io.h>
  51. #include "getopt/getopt.h"
  52. #define usleep(x) Sleep(x/1000)
  53. #define round(x) (x > 0.0 ? floor(x + 0.5): ceil(x - 0.5))
  54. #define _USE_MATH_DEFINES
  55. #endif
  56. #include <math.h>
  57. #include <pthread.h>
  58. #include <libusb.h>
  59. #include "rtl-sdr.h"
  60. #define DEFAULT_SAMPLE_RATE 24000
  61. #define DEFAULT_ASYNC_BUF_NUMBER 32
  62. #define DEFAULT_BUF_LENGTH (1 * 16384)
  63. #define MAXIMUM_OVERSAMPLE 16
  64. #define MAXIMUM_BUF_LENGTH (MAXIMUM_OVERSAMPLE * DEFAULT_BUF_LENGTH)
  65. #define AUTO_GAIN -100
  66. #define BUFFER_DUMP (1<<12)
  67. static volatile int do_exit = 0;
  68. static rtlsdr_dev_t *dev = NULL;
  69. FILE *file;
  70. int16_t* Sinewave;
  71. double* power_table;
  72. int N_WAVE, LOG2_N_WAVE;
  73. int next_power;
  74. int16_t *fft_buf;
  75. int *window_coefs;
  76. struct tuning_state
  77. /* one per tuning range */
  78. {
  79. int freq;
  80. int rate;
  81. int bin_e;
  82. long *avg; /* length == 2^bin_e */
  83. int samples;
  84. long mega_samples;
  85. //pthread_rwlock_t avg_lock;
  86. //pthread_mutex_t avg_mutex;
  87. /* having the iq buffer here is wasteful, but will avoid contention */
  88. uint8_t *buf8;
  89. int buf_len;
  90. //pthread_rwlock_t buf_lock;
  91. //pthread_mutex_t buf_mutex;
  92. };
  93. /* 3000 is enough for 3GHz b/w worst case */
  94. #define MAX_TUNES 3000
  95. struct tuning_state tunes[MAX_TUNES];
  96. int tune_count = 0;
  97. void usage(void)
  98. {
  99. fprintf(stderr,
  100. "rtl_power, a simple FFT logger for RTL2832 based DVB-T receivers\n\n"
  101. "Use:\trtl_power -f freq_range [-options] [filename]\n"
  102. "\t-f lower:upper:bin_size [Hz]\n"
  103. "\t (bin size is a maximum, smaller more convenient bins\n"
  104. "\t will be used. valid range 61-2M)\n"
  105. "\t[-i integration_interval (default: 10 seconds)]\n"
  106. "\t (buggy if a full sweep takes longer than the interval)\n"
  107. "\t[-1 enables single-shot mode (default: off)]\n"
  108. "\t[-e exit_timer (default: off/0)]\n"
  109. //"\t[-s avg/iir smoothing (default: avg)]\n"
  110. //"\t[-t threads (default: 1)]\n"
  111. "\t[-d device_index (default: 0)]\n"
  112. "\t[-g tuner_gain (default: automatic)]\n"
  113. "\t[-p ppm_error (default: 0)]\n"
  114. "\tfilename (a '-' dumps samples to stdout)\n"
  115. "\t (omitting the filename also uses stdout)\n"
  116. "\n"
  117. "Experimental options:\n"
  118. "\t[-w window (default: rectangle)]\n"
  119. "\t (hamming, blackman, blackman-harris, hann-poisson, bartlett, youssef)\n"
  120. // kaiser
  121. "\t[-c crop_percent (default: 0%, recommended: 20%%-50%%)]\n"
  122. "\t (discards data at the edges, 100%% discards everything)\n"
  123. "\t (has no effect in rms bin mode)\n"
  124. "\n"
  125. "CSV FFT output columns:\n"
  126. "\tdate, time, Hz low, Hz high, Hz step, samples, dbm, dbm, ...\n\n"
  127. "Examples:\n"
  128. "\trtl_power -f 88M:108M:125k fm_stations.csv\n"
  129. "\t (creates 160 bins across the FM band,\n"
  130. "\t individual stations should be visible)\n"
  131. "\trtl_power -f 100M:1G:1M -i 5m -1 survey.csv\n"
  132. "\t (a five minute low res scan of nearly everything)\n"
  133. "\trtl_power -f ... -i 15m -1 log.csv\n"
  134. "\t (integrate for 15 minutes and exit afterwards)\n"
  135. "\trtl_power -f ... -e 1h | gzip > log.csv.gz\n"
  136. "\t (collect data for one hour and compress it on the fly)\n"
  137. "Convert CSV to a waterfall graphic with\n"
  138. "\thttp://kmkeen.com/tmp/heatmap.py.txt\n"
  139. "");
  140. exit(1);
  141. }
  142. #ifdef _WIN32
  143. BOOL WINAPI
  144. sighandler(int signum)
  145. {
  146. if (CTRL_C_EVENT == signum) {
  147. fprintf(stderr, "Signal caught, exiting!\n");
  148. do_exit = 1;
  149. return TRUE;
  150. }
  151. return FALSE;
  152. }
  153. #else
  154. static void sighandler(int signum)
  155. {
  156. fprintf(stderr, "Signal caught, exiting!\n");
  157. do_exit = 1;
  158. }
  159. #endif
  160. /* more cond dumbness */
  161. #define safe_cond_signal(n, m) pthread_mutex_lock(m); pthread_cond_signal(n); pthread_mutex_unlock(m)
  162. #define safe_cond_wait(n, m) pthread_mutex_lock(m); pthread_cond_wait(n, m); pthread_mutex_unlock(m)
  163. /* FFT based on fix_fft.c by Roberts, Slaney and Bouras
  164. http://www.jjj.de/fft/fftpage.html
  165. 16 bit ints for everything
  166. -32768..+32768 maps to -1.0..+1.0
  167. */
  168. void sine_table(int size)
  169. {
  170. int i;
  171. double d;
  172. LOG2_N_WAVE = size;
  173. N_WAVE = 1 << LOG2_N_WAVE;
  174. Sinewave = malloc(sizeof(int16_t) * N_WAVE*3/4);
  175. power_table = malloc(sizeof(double) * N_WAVE);
  176. for (i=0; i<N_WAVE*3/4; i++)
  177. {
  178. d = (double)i * 2.0 * M_PI / N_WAVE;
  179. Sinewave[i] = (int)round(32767*sin(d));
  180. //printf("%i\n", Sinewave[i]);
  181. }
  182. }
  183. inline int16_t FIX_MPY(int16_t a, int16_t b)
  184. /* fixed point multiply and scale */
  185. {
  186. int c = ((int)a * (int)b) >> 14;
  187. b = c & 0x01;
  188. return (c >> 1) + b;
  189. }
  190. int fix_fft(int16_t iq[], int16_t m)
  191. /* interleaved iq[], 0 <= n < 2**m, changes in place */
  192. {
  193. int mr, nn, i, j, l, k, istep, n, shift;
  194. int16_t qr, qi, tr, ti, wr, wi;
  195. n = 1 << m;
  196. if (n > N_WAVE)
  197. {return -1;}
  198. mr = 0;
  199. nn = n - 1;
  200. /* decimation in time - re-order data */
  201. for (m=1; m<=nn; ++m) {
  202. l = n;
  203. do
  204. {l >>= 1;}
  205. while (mr+l > nn);
  206. mr = (mr & (l-1)) + l;
  207. if (mr <= m)
  208. {continue;}
  209. // real = 2*m, imag = 2*m+1
  210. tr = iq[2*m];
  211. iq[2*m] = iq[2*mr];
  212. iq[2*mr] = tr;
  213. ti = iq[2*m+1];
  214. iq[2*m+1] = iq[2*mr+1];
  215. iq[2*mr+1] = ti;
  216. }
  217. l = 1;
  218. k = LOG2_N_WAVE-1;
  219. while (l < n) {
  220. shift = 1;
  221. istep = l << 1;
  222. for (m=0; m<l; ++m) {
  223. j = m << k;
  224. wr = Sinewave[j+N_WAVE/4];
  225. wi = -Sinewave[j];
  226. if (shift) {
  227. wr >>= 1; wi >>= 1;}
  228. for (i=m; i<n; i+=istep) {
  229. j = i + l;
  230. tr = FIX_MPY(wr,iq[2*j]) - FIX_MPY(wi,iq[2*j+1]);
  231. ti = FIX_MPY(wr,iq[2*j+1]) + FIX_MPY(wi,iq[2*j]);
  232. qr = iq[2*i];
  233. qi = iq[2*i+1];
  234. if (shift) {
  235. qr >>= 1; qi >>= 1;}
  236. iq[2*j] = qr - tr;
  237. iq[2*j+1] = qi - ti;
  238. iq[2*i] = qr + tr;
  239. iq[2*i+1] = qi + ti;
  240. }
  241. }
  242. --k;
  243. l = istep;
  244. }
  245. return 0;
  246. }
  247. double rectangle(int i, int length)
  248. {
  249. return 1.0;
  250. }
  251. double hamming(int i, int length)
  252. {
  253. double a, b, w, N1;
  254. a = 25.0/46.0;
  255. b = 21.0/46.0;
  256. N1 = (double)(length-1);
  257. w = a - b*cos(2*i*M_PI/N1);
  258. return w;
  259. }
  260. double blackman(int i, int length)
  261. {
  262. double a0, a1, a2, w, N1;
  263. a0 = 7938.0/18608.0;
  264. a1 = 9240.0/18608.0;
  265. a2 = 1430.0/18608.0;
  266. N1 = (double)(length-1);
  267. w = a0 - a1*cos(2*i*M_PI/N1) + a2*cos(4*i*M_PI/N1);
  268. return w;
  269. }
  270. double blackman_harris(int i, int length)
  271. {
  272. double a0, a1, a2, a3, w, N1;
  273. a0 = 0.35875;
  274. a1 = 0.48829;
  275. a2 = 0.14128;
  276. a3 = 0.01168;
  277. N1 = (double)(length-1);
  278. w = a0 - a1*cos(2*i*M_PI/N1) + a2*cos(4*i*M_PI/N1) - a3*cos(6*i*M_PI/N1);
  279. return w;
  280. }
  281. double hann_poisson(int i, int length)
  282. {
  283. double a, N1, w;
  284. a = 2.0;
  285. N1 = (double)(length-1);
  286. w = 0.5 * (1 - cos(2*M_PI*i/N1)) * \
  287. pow(M_E, (-a*(double)abs((int)(N1-1-2*i)))/N1);
  288. return w;
  289. }
  290. double youssef(int i, int length)
  291. /* really a blackman-harris-poisson window, but that is a mouthful */
  292. {
  293. double a, a0, a1, a2, a3, w, N1;
  294. a0 = 0.35875;
  295. a1 = 0.48829;
  296. a2 = 0.14128;
  297. a3 = 0.01168;
  298. N1 = (double)(length-1);
  299. w = a0 - a1*cos(2*i*M_PI/N1) + a2*cos(4*i*M_PI/N1) - a3*cos(6*i*M_PI/N1);
  300. a = 0.0025;
  301. w *= pow(M_E, (-a*(double)abs((int)(N1-1-2*i)))/N1);
  302. return w;
  303. }
  304. double kaiser(int i, int length)
  305. // todo, become more smart
  306. {
  307. return 1.0;
  308. }
  309. double bartlett(int i, int length)
  310. {
  311. double N1, L, w;
  312. L = (double)length;
  313. N1 = L - 1;
  314. w = (i - N1/2) / (L/2);
  315. if (w < 0) {
  316. w = -w;}
  317. w = 1 - w;
  318. return w;
  319. }
  320. void rms_power(struct tuning_state *ts)
  321. /* for bins between 1MHz and 2MHz */
  322. {
  323. int i, s;
  324. uint8_t *buf = ts->buf8;
  325. int buf_len = ts->buf_len;
  326. long p, t;
  327. int ln, lp;
  328. double dc, err;
  329. p = t = 0L;
  330. for (i=0; i<buf_len; i++) {
  331. s = (int)buf[i] - 127;
  332. t += (long)s;
  333. p += (long)(s * s);
  334. }
  335. /* correct for dc offset in squares */
  336. dc = (double)t / (double)buf_len;
  337. err = t * 2 * dc - dc * dc * buf_len;
  338. p -= (long)round(err);
  339. ts->avg[0] += p;
  340. ts->samples += 1;
  341. /* complex pairs, half length */
  342. ts->mega_samples += (long)(buf_len/2);
  343. }
  344. double atofs(char *f)
  345. /* standard suffixes */
  346. {
  347. char last;
  348. int len;
  349. double suff = 1.0;
  350. len = strlen(f);
  351. last = f[len-1];
  352. f[len-1] = '\0';
  353. switch (last) {
  354. case 'g':
  355. case 'G':
  356. suff *= 1e3;
  357. case 'm':
  358. case 'M':
  359. suff *= 1e3;
  360. case 'k':
  361. case 'K':
  362. suff *= 1e3;
  363. suff *= atof(f);
  364. f[len-1] = last;
  365. return suff;
  366. }
  367. f[len-1] = last;
  368. return atof(f);
  369. }
  370. double atoft(char *f)
  371. /* time suffixes */
  372. {
  373. char last;
  374. int len;
  375. double suff = 1.0;
  376. len = strlen(f);
  377. last = f[len-1];
  378. f[len-1] = '\0';
  379. switch (last) {
  380. case 'h':
  381. case 'H':
  382. suff *= 60;
  383. case 'm':
  384. case 'M':
  385. suff *= 60;
  386. case 's':
  387. case 'S':
  388. suff *= atof(f);
  389. f[len-1] = last;
  390. return suff;
  391. }
  392. f[len-1] = last;
  393. return atof(f);
  394. }
  395. double atofp(char *f)
  396. /* percent suffixes */
  397. {
  398. char last;
  399. int len;
  400. double suff = 1.0;
  401. len = strlen(f);
  402. last = f[len-1];
  403. f[len-1] = '\0';
  404. switch (last) {
  405. case '%':
  406. suff *= 0.01;
  407. suff *= atof(f);
  408. f[len-1] = last;
  409. return suff;
  410. }
  411. f[len-1] = last;
  412. return atof(f);
  413. }
  414. int nearest_gain(int target_gain)
  415. {
  416. int i, err1, err2, count, close_gain;
  417. int* gains;
  418. count = rtlsdr_get_tuner_gains(dev, NULL);
  419. if (count <= 0) {
  420. return 0;
  421. }
  422. gains = malloc(sizeof(int) * count);
  423. count = rtlsdr_get_tuner_gains(dev, gains);
  424. close_gain = gains[0];
  425. for (i=0; i<count; i++) {
  426. err1 = abs(target_gain - close_gain);
  427. err2 = abs(target_gain - gains[i]);
  428. if (err2 < err1) {
  429. close_gain = gains[i];
  430. }
  431. }
  432. free(gains);
  433. return close_gain;
  434. }
  435. void frequency_range(char *arg, double crop)
  436. /* flesh out the tunes[] for scanning */
  437. // do we want the fewest ranges (easy) or the fewest bins (harder)?
  438. {
  439. char *start, *stop, *step;
  440. int i, j, upper, lower, max_size, bw_seen, bw_used, bin_size, bin_e, buf_len;
  441. struct tuning_state *ts;
  442. /* hacky string parsing */
  443. start = arg;
  444. stop = strchr(start, ':') + 1;
  445. stop[-1] = '\0';
  446. step = strchr(stop, ':') + 1;
  447. step[-1] = '\0';
  448. lower = (int)atofs(start);
  449. upper = (int)atofs(stop);
  450. max_size = (int)atofs(step);
  451. stop[-1] = ':';
  452. step[-1] = ':';
  453. /* evenly sized ranges, as close to 2MHz as possible */
  454. for (i=1; i<1500; i++) {
  455. bw_seen = (upper - lower) / i;
  456. bw_used = (int)((double)(bw_seen) / (1.0 - crop));
  457. if (bw_used > 2000000) {
  458. continue;}
  459. tune_count = i;
  460. break;
  461. }
  462. /* number of bins is power-of-two, bin size is under limit */
  463. for (i=1; i<=21; i++) {
  464. bin_e = i;
  465. bin_size = bw_used / (1<<i);
  466. if (bin_size <= max_size) {
  467. break;}
  468. }
  469. /* unless giant bins */
  470. if (max_size >= 1000000) {
  471. bw_seen = max_size;
  472. bw_used = max_size;
  473. tune_count = (upper - lower) / bw_seen;
  474. bin_e = 0;
  475. }
  476. if (tune_count > MAX_TUNES) {
  477. fprintf(stderr, "Error: bandwidth too wide.\n");
  478. exit(1);
  479. }
  480. buf_len = DEFAULT_BUF_LENGTH;
  481. if ((2<<bin_e) > buf_len) {
  482. buf_len = (2<<bin_e);
  483. }
  484. /* build the array */
  485. for (i=0; i<tune_count; i++) {
  486. ts = &tunes[i];
  487. ts->freq = lower + i*bw_seen + bw_seen/2;
  488. ts->rate = bw_used;
  489. ts->bin_e = bin_e;
  490. ts->samples = 0;
  491. ts->mega_samples = 0L;
  492. ts->avg = (long*)malloc((1<<bin_e) * sizeof(long));
  493. if (!ts->avg) {
  494. fprintf(stderr, "Error: malloc.\n");
  495. exit(1);
  496. }
  497. for (j=0; j<(1<<bin_e); j++) {
  498. ts->avg[j] = 0L;
  499. }
  500. ts->buf8 = (uint8_t*)malloc(buf_len * sizeof(uint8_t));
  501. if (!ts->buf8) {
  502. fprintf(stderr, "Error: malloc.\n");
  503. exit(1);
  504. }
  505. ts->buf_len = buf_len;
  506. }
  507. /* report */
  508. fprintf(stderr, "Number of frequency hops: %i\n", tune_count);
  509. fprintf(stderr, "Dongle bandwidth: %iHz\n", bw_used);
  510. fprintf(stderr, "Total FFT bins: %i\n", tune_count * (1<<bin_e));
  511. fprintf(stderr, "Logged FFT bins: %i\n", \
  512. (int)((double)(tune_count * (1<<bin_e)) * (1.0-crop)));
  513. fprintf(stderr, "FFT bin size: %iHz\n", bin_size);
  514. fprintf(stderr, "Buffer size: %0.2fms\n", 1000 * 0.5 * (float)buf_len / (float)bw_used);
  515. }
  516. void retune(rtlsdr_dev_t *d, int freq)
  517. {
  518. uint8_t dump[BUFFER_DUMP];
  519. int n_read;
  520. rtlsdr_set_center_freq(d, (uint32_t)freq);
  521. /* wait for settling and flush buffer */
  522. usleep(5000);
  523. rtlsdr_read_sync(d, &dump, BUFFER_DUMP, &n_read);
  524. if (n_read != BUFFER_DUMP) {
  525. fprintf(stderr, "Error: bad retune.\n");}
  526. }
  527. void scanner(void)
  528. {
  529. int i, j, f, n_read, offset, bin_e, bin_len, buf_len;
  530. struct tuning_state *ts;
  531. bin_e = tunes[0].bin_e;
  532. bin_len = 1 << bin_e;
  533. buf_len = tunes[0].buf_len;
  534. for (i=0; i<tune_count; i++) {
  535. if (do_exit) {
  536. break;}
  537. ts = &tunes[i];
  538. f = (int)rtlsdr_get_center_freq(dev);
  539. if (f != ts->freq) {
  540. retune(dev, ts->freq);}
  541. rtlsdr_read_sync(dev, ts->buf8, buf_len, &n_read);
  542. if (n_read != buf_len) {
  543. fprintf(stderr, "Error: dropped samples.\n");}
  544. /* rms */
  545. if (bin_len == 1) {
  546. rms_power(ts);
  547. continue;
  548. }
  549. /* fft */
  550. for (j=0; j<buf_len; j++) {
  551. fft_buf[j] = (int16_t)ts->buf8[j] - 127;
  552. }
  553. for (offset=0; offset<buf_len; offset+=(2*bin_len)) {
  554. // todo, let rect skip this
  555. for (j=0; j<bin_len; j++) {
  556. fft_buf[offset+j*2] *= window_coefs[j];
  557. fft_buf[offset+j*2+1] *= window_coefs[j];
  558. }
  559. fix_fft(fft_buf+offset, bin_e);
  560. for (j=0; j<bin_len; j++) {
  561. ts->avg[j] += (long) abs(fft_buf[offset+j*2]);
  562. }
  563. ts->samples += 1;
  564. }
  565. }
  566. }
  567. void csv_dbm(struct tuning_state *ts, double crop)
  568. {
  569. int i, len, i1, i2, bw2;
  570. long tmp;
  571. double dbm;
  572. len = 1 << ts->bin_e;
  573. /* fix FFT stuff quirks */
  574. if (ts->bin_e > 0) {
  575. /* nuke DC component (not effective for all windows) */
  576. ts->avg[0] = ts->avg[1];
  577. /* FFT is translated by 180 degrees */
  578. for (i=0; i<len/2; i++) {
  579. tmp = ts->avg[i];
  580. ts->avg[i] = ts->avg[i+len/2];
  581. ts->avg[i+len/2] = tmp;
  582. }
  583. }
  584. /* Hz low, Hz high, Hz step, samples, dbm, dbm, ... */
  585. bw2 = (int)((double)ts->rate * (1.0-crop) * 0.5);
  586. fprintf(file, "%i, %i, %.2f, %i, ", ts->freq - bw2, ts->freq + bw2,
  587. (double)ts->rate / (double)len, ts->samples);
  588. // something seems off with the dbm math
  589. i1 = 0 + (int)((double)len * crop * 0.5);
  590. i2 = (len-1) - (int)((double)len * crop * 0.5);
  591. for (i=i1; i<i2; i++) {
  592. dbm = (double)ts->avg[i];
  593. dbm /= (double)ts->rate;
  594. dbm /= (double)ts->samples;
  595. dbm = 10 * log10(dbm);
  596. fprintf(file, "%.2f, ", dbm);
  597. }
  598. dbm = (double)ts->avg[i2] / ((double)ts->rate * (double)ts->samples);
  599. if (ts->bin_e == 0) {
  600. dbm = ((double)ts->avg[0] / \
  601. ((double)ts->rate * (double)ts->samples));}
  602. dbm = 10 * log10(dbm);
  603. fprintf(file, "%.2f\n", dbm);
  604. for (i=0; i<len; i++) {
  605. ts->avg[i] = 0L;
  606. }
  607. ts->samples = 0;
  608. ts->mega_samples = 0L;
  609. }
  610. int main(int argc, char **argv)
  611. {
  612. #ifndef _WIN32
  613. struct sigaction sigact;
  614. #endif
  615. char *filename = NULL;
  616. int i, length, n_read, r, opt, wb_mode = 0;
  617. int gain = AUTO_GAIN; // tenths of a dB
  618. uint8_t *buffer;
  619. uint32_t dev_index = 0;
  620. int device_count;
  621. int ppm_error = 0;
  622. int interval = 10;
  623. int fft_threads = 1;
  624. int smoothing = 0;
  625. int single = 0;
  626. double crop = 0.1;
  627. char vendor[256], product[256], serial[256];
  628. char *freq_optarg;
  629. time_t next_tick;
  630. time_t time_now;
  631. time_t exit_time = 0;
  632. char t_str[50];
  633. struct tm *cal_time;
  634. double (*window_fn)(int, int) = rectangle;
  635. while ((opt = getopt(argc, argv, "f:i:s:t:d:g:p:e:w:c:1h")) != -1) {
  636. switch (opt) {
  637. case 'f': // lower:upper:bin_size
  638. freq_optarg = strdup(optarg);
  639. break;
  640. case 'd':
  641. dev_index = atoi(optarg);
  642. break;
  643. case 'g':
  644. gain = (int)(atof(optarg) * 10);
  645. break;
  646. case 'c':
  647. crop = atofp(optarg);
  648. break;
  649. case 'i':
  650. interval = (int)round(atoft(optarg));
  651. break;
  652. case 'e':
  653. exit_time = (time_t)((int)round(atoft(optarg)));
  654. break;
  655. case 's':
  656. if (strcmp("avg", optarg) == 0) {
  657. smoothing = 0;}
  658. if (strcmp("iir", optarg) == 0) {
  659. smoothing = 1;}
  660. break;
  661. case 'w':
  662. if (strcmp("rectangle", optarg) == 0) {
  663. window_fn = rectangle;}
  664. if (strcmp("hamming", optarg) == 0) {
  665. window_fn = hamming;}
  666. if (strcmp("blackman", optarg) == 0) {
  667. window_fn = blackman;}
  668. if (strcmp("blackman-harris", optarg) == 0) {
  669. window_fn = blackman_harris;}
  670. if (strcmp("hann-poisson", optarg) == 0) {
  671. window_fn = hann_poisson;}
  672. if (strcmp("youssef", optarg) == 0) {
  673. window_fn = youssef;}
  674. if (strcmp("kaiser", optarg) == 0) {
  675. window_fn = kaiser;}
  676. if (strcmp("bartlett", optarg) == 0) {
  677. window_fn = bartlett;}
  678. break;
  679. case 't':
  680. fft_threads = atoi(optarg);
  681. break;
  682. case 'p':
  683. ppm_error = atoi(optarg);
  684. break;
  685. case '1':
  686. single = 1;
  687. break;
  688. case 'h':
  689. default:
  690. usage();
  691. break;
  692. }
  693. }
  694. frequency_range(freq_optarg, crop);
  695. if (tune_count == 0) {
  696. usage();}
  697. if (argc <= optind) {
  698. filename = "-";
  699. } else {
  700. filename = argv[optind];
  701. }
  702. if (interval < 1) {
  703. interval = 1;}
  704. fprintf(stderr, "Reporting every %i seconds\n", interval);
  705. device_count = rtlsdr_get_device_count();
  706. if (!device_count) {
  707. fprintf(stderr, "No supported devices found.\n");
  708. exit(1);
  709. }
  710. fprintf(stderr, "Found %d device(s):\n", device_count);
  711. for (i = 0; i < device_count; i++) {
  712. rtlsdr_get_device_usb_strings(i, vendor, product, serial);
  713. fprintf(stderr, " %d: %s, %s, SN: %s\n", i, vendor, product, serial);
  714. }
  715. fprintf(stderr, "\n");
  716. fprintf(stderr, "Using device %d: %s\n",
  717. dev_index, rtlsdr_get_device_name(dev_index));
  718. r = rtlsdr_open(&dev, dev_index);
  719. if (r < 0) {
  720. fprintf(stderr, "Failed to open rtlsdr device #%d.\n", dev_index);
  721. exit(1);
  722. }
  723. #ifndef _WIN32
  724. sigact.sa_handler = sighandler;
  725. sigemptyset(&sigact.sa_mask);
  726. sigact.sa_flags = 0;
  727. sigaction(SIGINT, &sigact, NULL);
  728. sigaction(SIGTERM, &sigact, NULL);
  729. sigaction(SIGQUIT, &sigact, NULL);
  730. sigaction(SIGPIPE, &sigact, NULL);
  731. #else
  732. SetConsoleCtrlHandler( (PHANDLER_ROUTINE) sighandler, TRUE );
  733. #endif
  734. /* Set the tuner gain */
  735. if (gain == AUTO_GAIN) {
  736. r = rtlsdr_set_tuner_gain_mode(dev, 0);
  737. } else {
  738. r = rtlsdr_set_tuner_gain_mode(dev, 1);
  739. gain = nearest_gain(gain);
  740. r = rtlsdr_set_tuner_gain(dev, gain);
  741. }
  742. if (r != 0) {
  743. fprintf(stderr, "WARNING: Failed to set tuner gain.\n");
  744. } else if (gain == AUTO_GAIN) {
  745. fprintf(stderr, "Tuner gain set to automatic.\n");
  746. } else {
  747. fprintf(stderr, "Tuner gain set to %0.2f dB.\n", gain/10.0);
  748. }
  749. r = rtlsdr_set_freq_correction(dev, ppm_error);
  750. if (strcmp(filename, "-") == 0) { /* Write log to stdout */
  751. file = stdout;
  752. #ifdef _WIN32
  753. _setmode(_fileno(file), _O_BINARY);
  754. #endif
  755. } else {
  756. file = fopen(filename, "wb");
  757. if (!file) {
  758. fprintf(stderr, "Failed to open %s\n", filename);
  759. exit(1);
  760. }
  761. }
  762. /* Reset endpoint before we start reading from it (mandatory) */
  763. r = rtlsdr_reset_buffer(dev);
  764. if (r < 0) {
  765. fprintf(stderr, "WARNING: Failed to reset buffers.\n");}
  766. /* actually do stuff */
  767. rtlsdr_set_sample_rate(dev, (uint32_t)tunes[0].rate);
  768. sine_table(tunes[0].bin_e);
  769. next_tick = time(NULL) + interval;
  770. if (exit_time) {
  771. exit_time = time(NULL) + exit_time;}
  772. fft_buf = malloc(tunes[0].buf_len * sizeof(int16_t));
  773. length = 1 << tunes[0].bin_e;
  774. window_coefs = malloc(length * sizeof(int));
  775. for (i=0; i<length; i++) {
  776. window_coefs[i] = (int)(256*window_fn(i, length));
  777. }
  778. while (!do_exit) {
  779. scanner();
  780. time_now = time(NULL);
  781. if (time_now <= next_tick) {
  782. continue;}
  783. // time, Hz low, Hz high, Hz step, samples, dbm, dbm, ...
  784. cal_time = localtime(&time_now);
  785. strftime(t_str, 50, "%Y-%m-%d, %H:%M:%S", cal_time);
  786. for (i=0; i<tune_count; i++) {
  787. fprintf(file, "%s, ", t_str);
  788. csv_dbm(&tunes[i], crop);
  789. }
  790. fflush(file);
  791. while (time(NULL) >= next_tick) {
  792. next_tick += interval;}
  793. if (single) {
  794. do_exit = 1;}
  795. if (exit_time && time(NULL) >= exit_time) {
  796. do_exit = 1;}
  797. }
  798. /* clean up */
  799. if (do_exit) {
  800. fprintf(stderr, "\nUser cancel, exiting...\n");}
  801. else {
  802. fprintf(stderr, "\nLibrary error %d, exiting...\n", r);}
  803. if (file != stdout) {
  804. fclose(file);}
  805. rtlsdr_close(dev);
  806. free(fft_buf);
  807. free(window_coefs);
  808. //for (i=0; i<tune_count; i++) {
  809. // free(tunes[i].avg);
  810. // free(tunes[i].buf8);
  811. //}
  812. return r >= 0 ? r : -r;
  813. }
  814. // vim: tabstop=8:softtabstop=8:shiftwidth=8:noexpandtab