Bugfixes
[rtl-433.git] / src / rtl_433.c
1 /*
2  * rtl_433, turns your Realtek RTL2832 based DVB dongle into a 433.92MHz generic data receiver
3  * Copyright (C) 2012 by Benjamin Larsson <benjamin@southpole.se>
4  *
5  * Based on rtl_sdr
6  *
7  * Copyright (C) 2012 by Steve Markgraf <steve@steve-m.de>
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
23 #include <stdbool.h>
24
25 #include "rtl-sdr.h"
26 #include "rtl_433.h"
27 #include "baseband.h"
28 #include "pulse_detect.h"
29 #include "pulse_demod.h"
30 #include "data.h"
31 #include "util.h"
32
33
34 static int do_exit = 0;
35 static int do_exit_async = 0, frequencies = 0, events = 0;
36 uint32_t frequency[MAX_PROTOCOLS];
37 time_t rawtime_old;
38 int duration = 0;
39 time_t stop_time;
40 int flag;
41 uint32_t samp_rate = DEFAULT_SAMPLE_RATE;
42 float sample_file_pos = -1;
43 static uint32_t bytes_to_read = 0;
44 static rtlsdr_dev_t *dev = NULL;
45 static int override_short = 0;
46 static int override_long = 0;
47 int include_only = 0;   // Option -I
48 int debug_output = 0;
49 int quiet_mode = 0;
50 int utc_mode = 0;
51 int overwrite_mode = 0;
52
53 typedef enum  {
54     CONVERT_NATIVE,
55     CONVERT_SI,
56     CONVERT_CUSTOMARY
57 } conversion_mode_t;
58 static conversion_mode_t conversion_mode = CONVERT_NATIVE;
59
60 int num_r_devices = 0;
61
62 struct dm_state {
63     FILE *out_file;
64     int32_t level_limit;
65     int16_t am_buf[MAXIMAL_BUF_LENGTH]; // AM demodulated signal (for OOK decoding)
66     union {
67         // These buffers aren't used at the same time, so let's use a union to save some memory
68         int16_t fm_buf[MAXIMAL_BUF_LENGTH];     // FM demodulated signal (for FSK decoding)
69         uint16_t temp_buf[MAXIMAL_BUF_LENGTH];  // Temporary buffer (to be optimized out..)
70     };
71     FilterState lowpass_filter_state;
72     DemodFM_State demod_FM_state;
73     int enable_FM_demod;
74     int analyze;
75     int analyze_pulses;
76     int debug_mode;
77
78     /* Signal grabber variables */
79     int signal_grabber;
80     int8_t* sg_buf;
81     int sg_index;
82     int sg_len;
83
84
85     /* Protocol states */
86     int r_dev_num;
87     struct protocol_state *r_devs[MAX_PROTOCOLS];
88
89         pulse_data_t    pulse_data;
90         pulse_data_t    fsk_pulse_data;
91 };
92
93 void usage(r_device *devices) {
94         int i;
95         char disabledc;
96
97         fprintf(stderr,
98             "rtl_433, an ISM band generic data receiver for RTL2832 based DVB-T receivers\n\n"
99             "Usage:\t= Tuner options =\n"
100             "\t[-d <RTL-SDR USB device index>] (default: 0)\n"
101             "\t[-g <gain>] (default: 0 for auto)\n"
102             "\t[-f <frequency>] [-f...] Receive frequency(s) (default: %i Hz)\n"
103             "\t[-p <ppm_error] Correct rtl-sdr tuner frequency offset error (default: 0)\n"
104             "\t[-s <sample rate>] Set sample rate (default: %i Hz)\n"
105             "\t[-S] Force sync output (default: async)\n"
106             "\t= Demodulator options =\n"
107             "\t[-R <device>] Enable only the specified device decoding protocol (can be used multiple times)\n"
108             "\t[-G] Enable all device protocols, included those disabled by default\n"
109             "\t[-l <level>] Change detection level used to determine pulses [0-16384] (0 = auto) (default: %i)\n"
110             "\t[-z <value>] Override short value in data decoder\n"
111             "\t[-x <value>] Override long value in data decoder\n"
112             "\t[-n <value>] Specify number of samples to take (each sample is 2 bytes: 1 each of I & Q)\n"
113             "\t= Analyze/Debug options =\n"
114             "\t[-a] Analyze mode. Print a textual description of the signal. Disables decoding\n"
115             "\t[-A] Pulse Analyzer. Enable pulse analyzis and decode attempt\n"
116             "\t[-I] Include only: 0 = all (default), 1 = unknown devices, 2 = known devices\n"
117             "\t[-D] Print debug info on event (repeat for more info)\n"
118             "\t[-q] Quiet mode, suppress non-data messages\n"
119             "\t[-W] Overwrite mode, disable checks to prevent files from being overwritten\n"
120             "\t= File I/O options =\n"
121             "\t[-t] Test signal auto save. Use it together with analyze mode (-a -t). Creates one file per signal\n"
122             "\t\t Note: Saves raw I/Q samples (uint8 pcm, 2 channel). Preferred mode for generating test files\n"
123             "\t[-r <filename>] Read data from input file instead of a receiver\n"
124             "\t[-m <mode>] Data file mode for input / output file (default: 0)\n"
125             "\t\t 0 = Raw I/Q samples (uint8, 2 channel)\n"
126             "\t\t 1 = AM demodulated samples (int16 pcm, 1 channel)\n"
127             "\t\t 2 = FM demodulated samples (int16) (experimental)\n"
128             "\t\t 3 = Raw I/Q samples (cf32, 2 channel)\n"
129             "\t\t Note: If output file is specified, input will always be I/Q\n"
130             "\t[-F] kv|json|csv Produce decoded output in given format. Not yet supported by all drivers.\n"
131             "\t[-C] native|si|customary Convert units in decoded output.\n"
132             "\t[-T] specify number of seconds to run\n"
133             "\t[-U] Print timestamps in UTC (this may also be accomplished by invocation with TZ environment variable set).\n"
134             "\t[<filename>] Save data stream to output file (a '-' dumps samples to stdout)\n\n",
135             DEFAULT_FREQUENCY, DEFAULT_SAMPLE_RATE, DEFAULT_LEVEL_LIMIT);
136
137     fprintf(stderr, "Supported device protocols:\n");
138     for (i = 0; i < num_r_devices; i++) {
139         if (devices[i].disabled)
140             disabledc = '*';
141         else
142             disabledc = ' ';
143
144         fprintf(stderr, "    [%02d]%c %s\n", i + 1, disabledc, devices[i].name);
145     }
146     fprintf(stderr, "\n* Disabled by default, use -R n or -G\n");
147
148     exit(1);
149 }
150
151 #ifdef _WIN32
152 BOOL WINAPI
153 sighandler(int signum) {
154     if (CTRL_C_EVENT == signum) {
155         fprintf(stderr, "Signal caught, exiting!\n");
156         do_exit = 1;
157         rtlsdr_cancel_async(dev);
158         return TRUE;
159     }
160     return FALSE;
161 }
162 #else
163 static void sighandler(int signum) {
164     if (signum == SIGPIPE) {
165         signal(SIGPIPE,SIG_IGN);
166     } else {
167         fprintf(stderr, "Signal caught, exiting!\n");
168     }
169     do_exit = 1;
170     rtlsdr_cancel_async(dev);
171 }
172 #endif
173
174
175 static void register_protocol(struct dm_state *demod, r_device *t_dev) {
176     struct protocol_state *p = calloc(1, sizeof (struct protocol_state));
177     p->short_limit = (float) t_dev->short_limit / ((float) 1000000 / (float) samp_rate);
178     p->long_limit = (float) t_dev->long_limit / ((float) 1000000 / (float) samp_rate);
179     p->reset_limit = (float) t_dev->reset_limit / ((float) 1000000 / (float) samp_rate);
180     p->modulation = t_dev->modulation;
181     p->callback = t_dev->json_callback;
182     p->name = t_dev->name;
183     p->demod_arg = t_dev->demod_arg;
184     bitbuffer_clear(&p->bits);
185
186     demod->r_devs[demod->r_dev_num] = p;
187     demod->r_dev_num++;
188
189     if (!quiet_mode) {
190         fprintf(stderr, "Registering protocol [%d] \"%s\"\n", demod->r_dev_num, t_dev->name);
191     }
192
193     if (demod->r_dev_num > MAX_PROTOCOLS) {
194         fprintf(stderr, "\n\nMax number of protocols reached %d\n", MAX_PROTOCOLS);
195         fprintf(stderr, "Increase MAX_PROTOCOLS and recompile\n");
196         exit(-1);
197     }
198 }
199
200
201 static unsigned int counter = 0;
202 static unsigned int print = 1;
203 static unsigned int print2 = 0;
204 static unsigned int pulses_found = 0;
205 static unsigned int prev_pulse_start = 0;
206 static unsigned int pulse_start = 0;
207 static unsigned int pulse_end = 0;
208 static unsigned int pulse_avg = 0;
209 static unsigned int signal_start = 0;
210 static unsigned int signal_end = 0;
211 static unsigned int signal_pulse_data[4000][3] = {
212     {0}};
213 static unsigned int signal_pulse_counter = 0;
214
215 typedef struct output_handler {
216     /*data_printer_t*/ void *printer;
217     void (*aux_free)(void *aux);
218     FILE *file;
219     void *aux;
220     struct output_handler *next;
221 } output_handler_t;
222 static output_handler_t *output_handler = NULL;
223 static output_handler_t **next_output_handler = &output_handler;
224
225 /* handles incoming structured data by dumping it */
226 void data_acquired_handler(data_t *data)
227 {
228     if (conversion_mode == CONVERT_SI) {
229         for (data_t *d = data; d; d = d->next) {
230             if ((d->type == DATA_DOUBLE) &&
231                 !strcmp(d->key, "temperature_F")) {
232                     *(double*)d->value = fahrenheit2celsius(*(double*)d->value);
233                                         free(d->key);
234                     d->key = strdup("temperature_C");
235                     char *pos;
236                     if (d->format &&
237                         (pos = strrchr(d->format, 'F'))) {
238                         *pos = 'C';
239                     }
240             }
241         }
242     }
243     if (conversion_mode == CONVERT_CUSTOMARY) {
244         for (data_t *d = data; d; d = d->next) {
245             if ((d->type == DATA_DOUBLE) &&
246                 !strcmp(d->key, "temperature_C")) {
247                     *(double*)d->value = celsius2fahrenheit(*(double*)d->value);
248                                         free(d->key);
249                     d->key = strdup("temperature_F");
250                     char *pos;
251                     if (d->format &&
252                         (pos = strrchr(d->format, 'C'))) {
253                         *pos = 'F';
254                     }
255             }
256         }
257     }
258
259     for (output_handler_t *output = output_handler; output; output = output->next) {
260         data_print(data, output->file, output->printer, output->aux);
261     }
262     data_free(data);
263 }
264
265 static void classify_signal() {
266     unsigned int i, k, max = 0, min = 1000000, t;
267     unsigned int delta, count_min, count_max, min_new, max_new, p_limit;
268     unsigned int a[3], b[2], a_cnt[3], a_new[3], b_new[2];
269     unsigned int signal_distance_data[4000] = {0};
270     struct protocol_state p = {0};
271     unsigned int signal_type;
272
273     if (!signal_pulse_data[0][0])
274         return;
275
276     for (i = 0; i < 1000; i++) {
277         if (signal_pulse_data[i][0] > 0) {
278             //fprintf(stderr, "[%03d] s: %d\t  e:\t %d\t l:%d\n",
279             //i, signal_pulse_data[i][0], signal_pulse_data[i][1],
280             //signal_pulse_data[i][2]);
281             if (signal_pulse_data[i][2] > max)
282                 max = signal_pulse_data[i][2];
283             if (signal_pulse_data[i][2] <= min)
284                 min = signal_pulse_data[i][2];
285         }
286     }
287     t = (max + min) / 2;
288     //fprintf(stderr, "\n\nMax: %d, Min: %d  t:%d\n", max, min, t);
289
290     delta = (max - min)*(max - min);
291
292     //TODO use Lloyd-Max quantizer instead
293     k = 1;
294     while ((k < 10) && (delta > 0)) {
295         min_new = 0;
296         count_min = 0;
297         max_new = 0;
298         count_max = 0;
299
300         for (i = 0; i < 1000; i++) {
301             if (signal_pulse_data[i][0] > 0) {
302                 if (signal_pulse_data[i][2] < t) {
303                     min_new = min_new + signal_pulse_data[i][2];
304                     count_min++;
305                 } else {
306                     max_new = max_new + signal_pulse_data[i][2];
307                     count_max++;
308                 }
309             }
310         }
311         if (count_min != 0 && count_max != 0) {
312             min_new = min_new / count_min;
313             max_new = max_new / count_max;
314         }
315
316         delta = (min - min_new)*(min - min_new) + (max - max_new)*(max - max_new);
317         min = min_new;
318         max = max_new;
319         t = (min + max) / 2;
320
321         fprintf(stderr, "Iteration %d. t: %d    min: %d (%d)    max: %d (%d)    delta %d\n", k, t, min, count_min, max, count_max, delta);
322         k++;
323     }
324
325     for (i = 0; i < 1000; i++) {
326         if (signal_pulse_data[i][0] > 0) {
327             //fprintf(stderr, "%d\n", signal_pulse_data[i][1]);
328         }
329     }
330     /* 50% decision limit */
331     if (min != 0 && max / min > 1) {
332         fprintf(stderr, "Pulse coding: Short pulse length %d - Long pulse length %d\n", min, max);
333         signal_type = 2;
334     } else {
335         fprintf(stderr, "Distance coding: Pulse length %d\n", (min + max) / 2);
336         signal_type = 1;
337     }
338     p_limit = (max + min) / 2;
339
340     /* Initial guesses */
341     a[0] = 1000000;
342     a[2] = 0;
343     for (i = 1; i < 1000; i++) {
344         if (signal_pulse_data[i][0] > 0) {
345             //               fprintf(stderr, "[%03d] s: %d\t  e:\t %d\t l:%d\t  d:%d\n",
346             //               i, signal_pulse_data[i][0], signal_pulse_data[i][1],
347             //               signal_pulse_data[i][2], signal_pulse_data[i][0]-signal_pulse_data[i-1][1]);
348             signal_distance_data[i - 1] = signal_pulse_data[i][0] - signal_pulse_data[i - 1][1];
349             if (signal_distance_data[i - 1] > a[2])
350                 a[2] = signal_distance_data[i - 1];
351             if (signal_distance_data[i - 1] <= a[0])
352                 a[0] = signal_distance_data[i - 1];
353         }
354     }
355     min = a[0];
356     max = a[2];
357     a[1] = (a[0] + a[2]) / 2;
358     //    for (i=0 ; i<1 ; i++) {
359     //        b[i] = (a[i]+a[i+1])/2;
360     //    }
361     b[0] = (a[0] + a[1]) / 2;
362     b[1] = (a[1] + a[2]) / 2;
363     //     fprintf(stderr, "a[0]: %d\t a[1]: %d\t a[2]: %d\t\n",a[0],a[1],a[2]);
364     //     fprintf(stderr, "b[0]: %d\t b[1]: %d\n",b[0],b[1]);
365
366     k = 1;
367     delta = 10000000;
368     while ((k < 10) && (delta > 0)) {
369         for (i = 0; i < 3; i++) {
370             a_new[i] = 0;
371             a_cnt[i] = 0;
372         }
373
374         for (i = 0; i < 1000; i++) {
375             if (signal_distance_data[i] > 0) {
376                 if (signal_distance_data[i] < b[0]) {
377                     a_new[0] += signal_distance_data[i];
378                     a_cnt[0]++;
379                 } else if (signal_distance_data[i] < b[1] && signal_distance_data[i] >= b[0]) {
380                     a_new[1] += signal_distance_data[i];
381                     a_cnt[1]++;
382                 } else if (signal_distance_data[i] >= b[1]) {
383                     a_new[2] += signal_distance_data[i];
384                     a_cnt[2]++;
385                 }
386             }
387         }
388
389         //         fprintf(stderr, "Iteration %d.", k);
390         delta = 0;
391         for (i = 0; i < 3; i++) {
392             if (a_cnt[i])
393                 a_new[i] /= a_cnt[i];
394             delta += (a[i] - a_new[i])*(a[i] - a_new[i]);
395             //             fprintf(stderr, "\ta[%d]: %d (%d)", i, a_new[i], a[i]);
396             a[i] = a_new[i];
397         }
398         //         fprintf(stderr, " delta %d\n", delta);
399
400         if (a[0] < min) {
401             a[0] = min;
402             //             fprintf(stderr, "Fixing a[0] = %d\n", min);
403         }
404         if (a[2] > max) {
405             a[0] = max;
406             //             fprintf(stderr, "Fixing a[2] = %d\n", max);
407         }
408         //         if (a[1] == 0) {
409         //             a[1] = (a[2]+a[0])/2;
410         //             fprintf(stderr, "Fixing a[1] = %d\n", a[1]);
411         //         }
412
413         //         fprintf(stderr, "Iteration %d.", k);
414         for (i = 0; i < 2; i++) {
415             //             fprintf(stderr, "\tb[%d]: (%d) ", i, b[i]);
416             b[i] = (a[i] + a[i + 1]) / 2;
417             //             fprintf(stderr, "%d  ", b[i]);
418         }
419         //         fprintf(stderr, "\n");
420         k++;
421     }
422
423     if (override_short) {
424         p_limit = override_short;
425         a[0] = override_short;
426     }
427
428     if (override_long) {
429         a[1] = override_long;
430     }
431
432     fprintf(stderr, "\nShort distance: %d, long distance: %d, packet distance: %d\n", a[0], a[1], a[2]);
433     fprintf(stderr, "\np_limit: %d\n", p_limit);
434
435     bitbuffer_clear(&p.bits);
436     if (signal_type == 1) {
437         for (i = 0; i < 1000; i++) {
438             if (signal_distance_data[i] > 0) {
439                 if (signal_distance_data[i] < (a[0] + a[1]) / 2) {
440                     //                     fprintf(stderr, "0 [%d] %d < %d\n",i, signal_distance_data[i], (a[0]+a[1])/2);
441                     bitbuffer_add_bit(&p.bits, 0);
442                 } else if ((signal_distance_data[i] > (a[0] + a[1]) / 2) && (signal_distance_data[i] < (a[1] + a[2]) / 2)) {
443                     //                     fprintf(stderr, "0 [%d] %d > %d\n",i, signal_distance_data[i], (a[0]+a[1])/2);
444                     bitbuffer_add_bit(&p.bits, 1);
445                 } else if (signal_distance_data[i] > (a[1] + a[2]) / 2) {
446                     //                     fprintf(stderr, "0 [%d] %d > %d\n",i, signal_distance_data[i], (a[1]+a[2])/2);
447                     bitbuffer_add_row(&p.bits);
448                 }
449
450             }
451
452         }
453         bitbuffer_print(&p.bits);
454     }
455     if (signal_type == 2) {
456         for (i = 0; i < 1000; i++) {
457             if (signal_pulse_data[i][2] > 0) {
458                 if (signal_pulse_data[i][2] < p_limit) {
459                     //                     fprintf(stderr, "0 [%d] %d < %d\n",i, signal_pulse_data[i][2], p_limit);
460                     bitbuffer_add_bit(&p.bits, 0);
461                 } else {
462                     //                     fprintf(stderr, "1 [%d] %d > %d\n",i, signal_pulse_data[i][2], p_limit);
463                     bitbuffer_add_bit(&p.bits, 1);
464                 }
465                 if ((signal_distance_data[i] >= (a[1] + a[2]) / 2)) {
466                     //                     fprintf(stderr, "\\n [%d] %d > %d\n",i, signal_distance_data[i], (a[1]+a[2])/2);
467                     bitbuffer_add_row(&p.bits);
468                 }
469
470
471             }
472         }
473         bitbuffer_print(&p.bits);
474     }
475
476     for (i = 0; i < 1000; i++) {
477         signal_pulse_data[i][0] = 0;
478         signal_pulse_data[i][1] = 0;
479         signal_pulse_data[i][2] = 0;
480         signal_distance_data[i] = 0;
481     }
482
483 };
484
485 static void pwm_analyze(struct dm_state *demod, int16_t *buf, uint32_t len) {
486     unsigned int i;
487     int32_t threshold = (demod->level_limit ? demod->level_limit : 8000);       // Does not support auto level. Use old default instead.
488
489     for (i = 0; i < len; i++) {
490         if (buf[i] > threshold) {
491             if (!signal_start)
492                 signal_start = counter;
493             if (print) {
494                 pulses_found++;
495                 pulse_start = counter;
496                 signal_pulse_data[signal_pulse_counter][0] = counter;
497                 signal_pulse_data[signal_pulse_counter][1] = -1;
498                 signal_pulse_data[signal_pulse_counter][2] = -1;
499                 if (debug_output) fprintf(stderr, "pulse_distance %d\n", counter - pulse_end);
500                 if (debug_output) fprintf(stderr, "pulse_start distance %d\n", pulse_start - prev_pulse_start);
501                 if (debug_output) fprintf(stderr, "pulse_start[%d] found at sample %d, value = %d\n", pulses_found, counter, buf[i]);
502                 prev_pulse_start = pulse_start;
503                 print = 0;
504                 print2 = 1;
505             }
506         }
507         counter++;
508         if (buf[i] < threshold) {
509             if (print2) {
510                 pulse_avg += counter - pulse_start;
511                 if (debug_output) fprintf(stderr, "pulse_end  [%d] found at sample %d, pulse length = %d, pulse avg length = %d\n",
512                         pulses_found, counter, counter - pulse_start, pulse_avg / pulses_found);
513                 pulse_end = counter;
514                 print2 = 0;
515                 signal_pulse_data[signal_pulse_counter][1] = counter;
516                 signal_pulse_data[signal_pulse_counter][2] = counter - pulse_start;
517                 signal_pulse_counter++;
518                 if (signal_pulse_counter >= 4000) {
519                     signal_pulse_counter = 0;
520                     goto err;
521                 }
522             }
523             print = 1;
524             if (signal_start && (pulse_end + 50000 < counter)) {
525                 signal_end = counter - 40000;
526                 fprintf(stderr, "*** signal_start = %d, signal_end = %d\n", signal_start - 10000, signal_end);
527                 fprintf(stderr, "signal_len = %d,  pulses = %d\n", signal_end - (signal_start - 10000), pulses_found);
528                 pulses_found = 0;
529                 classify_signal();
530
531                 signal_pulse_counter = 0;
532                 if (demod->sg_buf) {
533                     int start_pos, signal_bszie, wlen, wrest = 0, sg_idx, idx;
534                     char sgf_name[256] = {0};
535                     FILE *sgfp;
536
537                     while (1) {
538                         sprintf(sgf_name, "gfile%03d.data", demod->signal_grabber);
539                         demod->signal_grabber++;
540                         if (access(sgf_name, F_OK) == -1 || overwrite_mode) {
541                             break;
542                         }
543                     }
544
545                     signal_bszie = 2 * (signal_end - (signal_start - 10000));
546                     signal_bszie = (131072 - (signal_bszie % 131072)) + signal_bszie;
547                     sg_idx = demod->sg_index - demod->sg_len;
548                     if (sg_idx < 0)
549                         sg_idx = SIGNAL_GRABBER_BUFFER - demod->sg_len;
550                     idx = (i - 40000)*2;
551                     start_pos = sg_idx + idx - signal_bszie;
552                     fprintf(stderr, "signal_bszie = %d  -      sg_index = %d\n", signal_bszie, demod->sg_index);
553                     fprintf(stderr, "start_pos    = %d  -   buffer_size = %d\n", start_pos, SIGNAL_GRABBER_BUFFER);
554                     if (signal_bszie > SIGNAL_GRABBER_BUFFER)
555                         fprintf(stderr, "Signal bigger then buffer, signal = %d > buffer %d !!\n", signal_bszie, SIGNAL_GRABBER_BUFFER);
556
557                     if (start_pos < 0) {
558                         start_pos = SIGNAL_GRABBER_BUFFER + start_pos;
559                         fprintf(stderr, "restart_pos = %d\n", start_pos);
560                     }
561
562                     fprintf(stderr, "*** Saving signal to file %s\n", sgf_name);
563                     sgfp = fopen(sgf_name, "wb");
564                     if (!sgfp) {
565                         fprintf(stderr, "Failed to open %s\n", sgf_name);
566                     }
567                     wlen = signal_bszie;
568                     if (start_pos + signal_bszie > SIGNAL_GRABBER_BUFFER) {
569                         wlen = SIGNAL_GRABBER_BUFFER - start_pos;
570                         wrest = signal_bszie - wlen;
571                     }
572                     fprintf(stderr, "*** Writing data from %d, len %d\n", start_pos, wlen);
573                     fwrite(&demod->sg_buf[start_pos], 1, wlen, sgfp);
574
575                     if (wrest) {
576                         fprintf(stderr, "*** Writing data from %d, len %d\n", 0, wrest);
577                         fwrite(&demod->sg_buf[0], 1, wrest, sgfp);
578                     }
579
580                     fclose(sgfp);
581                 }
582                 signal_start = 0;
583             }
584         }
585
586
587     }
588     return;
589
590 err:
591     fprintf(stderr, "To many pulses detected, probably bad input data or input parameters\n");
592     return;
593 }
594
595
596 static void rtlsdr_callback(unsigned char *iq_buf, uint32_t len, void *ctx) {
597     struct dm_state *demod = ctx;
598     int i;
599     char time_str[LOCAL_TIME_BUFLEN];
600
601         if (do_exit || do_exit_async)
602                 return;
603
604         if ((bytes_to_read > 0) && (bytes_to_read < len)) {
605                 len = bytes_to_read;
606                 do_exit = 1;
607                 rtlsdr_cancel_async(dev);
608         }
609
610         if (demod->signal_grabber) {
611                 //fprintf(stderr, "[%d] sg_index - len %d\n", demod->sg_index, len );
612                 memcpy(&demod->sg_buf[demod->sg_index], iq_buf, len);
613                 demod->sg_len = len;
614                 demod->sg_index += len;
615                 if (demod->sg_index + len > SIGNAL_GRABBER_BUFFER)
616                         demod->sg_index = 0;
617         }
618
619         // AM demodulation
620         envelope_detect(iq_buf, demod->temp_buf, len/2);
621         baseband_low_pass_filter(demod->temp_buf, demod->am_buf, len/2, &demod->lowpass_filter_state);
622
623         // FM demodulation
624         if (demod->enable_FM_demod) {
625                 baseband_demod_FM(iq_buf, demod->fm_buf, len/2, &demod->demod_FM_state);
626         }
627
628         // Handle special input formats
629         if(!demod->out_file) {                          // If output file is specified we always assume I/Q input
630                 if (demod->debug_mode == 1) {   // The IQ buffer is really AM demodulated data
631                         memcpy(demod->am_buf, iq_buf, len);
632                 } else if (demod->debug_mode == 2) {    // The IQ buffer is really FM demodulated data
633                         fprintf(stderr, "Reading FM modulated data not implemented yet!\n");
634                 }
635         }
636
637         if (demod->analyze || (demod->out_file == stdout)) {    // We don't want to decode devices when outputting to stdout
638                 pwm_analyze(demod, demod->am_buf, len / 2);
639         } else {
640                 // Detect a package and loop through demodulators with pulse data
641                 int package_type = 1;   // Just to get us started
642                 while(package_type) {
643                         int p_events = 0;       // Sensor events successfully detected per package
644                         package_type = pulse_detect_package(demod->am_buf, demod->fm_buf, len/2, demod->level_limit, samp_rate, &demod->pulse_data, &demod->fsk_pulse_data);
645                         if (package_type == 1) {
646                                 if(demod->analyze_pulses) fprintf(stderr, "Detected OOK package\t@ %s\n", local_time_str(0, time_str));
647                                 for (i = 0; i < demod->r_dev_num; i++) {
648                                         switch (demod->r_devs[i]->modulation) {
649                                                 case OOK_PULSE_PCM_RZ:
650                                                         p_events += pulse_demod_pcm(&demod->pulse_data, demod->r_devs[i]);
651                                                         break;
652                                                 case OOK_PULSE_PPM_RAW:
653                                                         p_events += pulse_demod_ppm(&demod->pulse_data, demod->r_devs[i]);
654                                                         break;
655                                                 case OOK_PULSE_PWM_PRECISE:
656                                                         p_events += pulse_demod_pwm_precise(&demod->pulse_data, demod->r_devs[i]);
657                                                         break;
658                                                 case OOK_PULSE_PWM_RAW:
659                                                         p_events += pulse_demod_pwm(&demod->pulse_data, demod->r_devs[i]);
660                                                         break;
661                                                 case OOK_PULSE_PWM_TERNARY:
662                                                         p_events += pulse_demod_pwm_ternary(&demod->pulse_data, demod->r_devs[i]);
663                                                         break;
664                                                 case OOK_PULSE_MANCHESTER_ZEROBIT:
665                                                         p_events += pulse_demod_manchester_zerobit(&demod->pulse_data, demod->r_devs[i]);
666                                                         break;
667                                                 case OOK_PULSE_CLOCK_BITS:
668                                                         p_events += pulse_demod_clock_bits(&demod->pulse_data, demod->r_devs[i]);
669                                                         break;
670                                                 case OOK_PULSE_PWM_OSV1:
671                                                         p_events += pulse_demod_osv1(&demod->pulse_data, demod->r_devs[i]);
672                                                         break;
673                                                 // FSK decoders
674                                                 case FSK_PULSE_PCM:
675                                                 case FSK_PULSE_PWM_RAW:
676                                                         break;
677                                                 case FSK_PULSE_MANCHESTER_ZEROBIT:
678                                                         p_events += pulse_demod_manchester_zerobit(&demod->pulse_data, demod->r_devs[i]);
679                                                         break;
680                                                 default:
681                                                         fprintf(stderr, "Unknown modulation %d in protocol!\n", demod->r_devs[i]->modulation);
682                                         }
683                                 } // for demodulators
684                                 if(debug_output > 1) pulse_data_print(&demod->pulse_data);
685                                 if(demod->analyze_pulses && (include_only == 0 || (include_only == 1 && p_events == 0) || (include_only == 2 && p_events > 0)) ) { 
686                                         pulse_analyzer(&demod->pulse_data, samp_rate);
687                                 }
688                         } else if (package_type == 2) {
689                                 if(demod->analyze_pulses) fprintf(stderr, "Detected FSK package\t@ %s\n", local_time_str(0, time_str));
690                                 for (i = 0; i < demod->r_dev_num; i++) {
691                                         switch (demod->r_devs[i]->modulation) {
692                                                 // OOK decoders
693                                                 case OOK_PULSE_PCM_RZ:
694                                                 case OOK_PULSE_PPM_RAW:
695                                                 case OOK_PULSE_PWM_PRECISE:
696                                                 case OOK_PULSE_PWM_RAW:
697                                                 case OOK_PULSE_PWM_TERNARY:
698                                                 case OOK_PULSE_MANCHESTER_ZEROBIT:
699                                                 case OOK_PULSE_CLOCK_BITS:
700                                                 case OOK_PULSE_PWM_OSV1:
701                                                         break;
702                                                 case FSK_PULSE_PCM:
703                                                         p_events += pulse_demod_pcm(&demod->fsk_pulse_data, demod->r_devs[i]);
704                                                         break;
705                                                 case FSK_PULSE_PWM_RAW:
706                                                         p_events += pulse_demod_pwm(&demod->fsk_pulse_data, demod->r_devs[i]);
707                                                         break;
708                                                 case FSK_PULSE_MANCHESTER_ZEROBIT:
709                                                         p_events += pulse_demod_manchester_zerobit(&demod->fsk_pulse_data, demod->r_devs[i]);
710                                                         break;
711                                                 default:
712                                                         fprintf(stderr, "Unknown modulation %d in protocol!\n", demod->r_devs[i]->modulation);
713                                         }
714                                 } // for demodulators
715                                 if(debug_output > 1) pulse_data_print(&demod->fsk_pulse_data);
716                                 if(demod->analyze_pulses && (include_only == 0 || (include_only == 1 && p_events == 0) || (include_only == 2 && p_events > 0)) ) { 
717                                         pulse_analyzer(&demod->fsk_pulse_data, samp_rate);
718                                 }
719                         } // if (package_type == ...
720                 } // while(package_type)...
721         } // if (demod->analyze...
722
723         if (demod->out_file) {
724                 uint8_t* out_buf = iq_buf;                              // Default is to dump IQ samples
725                 if (demod->debug_mode == 1) {                   // AM data
726                         out_buf = (uint8_t*)demod->am_buf;
727                 } else if (demod->debug_mode == 2) {    // FM data
728                         out_buf = (uint8_t*)demod->fm_buf;
729                 }
730                 if (fwrite(out_buf, 1, len, demod->out_file) != len) {
731                         fprintf(stderr, "Short write, samples lost, exiting!\n");
732                         rtlsdr_cancel_async(dev);
733                 }
734         }
735
736         if (bytes_to_read > 0)
737                 bytes_to_read -= len;
738
739         time_t rawtime;
740         time(&rawtime);
741         if (frequencies > 1) {
742                 if (difftime(rawtime, rawtime_old) > DEFAULT_HOP_TIME || events >= DEFAULT_HOP_EVENTS) {
743                         rawtime_old = rawtime;
744                         events = 0;
745                         do_exit_async = 1;
746                         rtlsdr_cancel_async(dev);
747                 }
748         }
749     if (duration > 0 && rawtime >= stop_time) {
750       do_exit_async = do_exit = 1;
751       fprintf(stderr, "Time expired, exiting!\n");
752       rtlsdr_cancel_async(dev);
753     }
754 }
755
756 // find the fields output for CSV
757 void *determine_csv_fields(r_device* devices, int num_devices)
758 {
759     int i, j;
760     int cur_output_fields = 0;
761     int num_output_fields = 0;
762     void *csv_aux;
763     const char **output_fields = NULL;
764     for (i = 0; i < num_devices; i++)
765         if (!devices[i].disabled) {
766             if (devices[i].fields)
767                 for (int c = 0; devices[i].fields[c]; ++c)
768                     ++num_output_fields;
769             else
770                 fprintf(stderr, "rtl_433: warning: %d \"%s\" does not support CSV output\n",
771                         i, devices[i].name);
772         }
773     output_fields = calloc(num_output_fields + 1, sizeof(char*));
774     for (i = 0; i < num_devices; i++) {
775         if (!devices[i].disabled && devices[i].fields) {
776             for (int c = 0; devices[i].fields[c]; ++c) {
777                 output_fields[cur_output_fields] = devices[i].fields[c];
778                 ++cur_output_fields;
779             }
780         }
781     }
782
783     csv_aux = data_csv_init(output_fields, num_output_fields);
784     free(output_fields);
785     return csv_aux;
786 }
787
788 void add_json_output()
789 {
790     output_handler_t *output = calloc(1, sizeof(output_handler_t));
791     if (!output) {
792         fprintf(stderr, "rtl_433: failed to allocate memory for output handler\n");
793         exit(1);
794     }
795     output->printer = &data_json_printer;
796     output->file = stdout;
797     *next_output_handler = output;
798     next_output_handler = &output->next;
799 }
800
801 void add_csv_output(void *aux_data)
802 {
803     if (!aux_data) {
804         fprintf(stderr, "rtl_433: failed to allocate memory for CSV auxiliary data\n");
805         exit(1);
806     }
807     output_handler_t *output = calloc(1, sizeof(output_handler_t));
808     if (!output) {
809         fprintf(stderr, "rtl_433: failed to allocate memory for output handler\n");
810         exit(1);
811     }
812     output->printer = &data_csv_printer;
813     output->aux_free = &data_csv_free;
814     output->file = stdout;
815     output->aux = aux_data;
816     *next_output_handler = output;
817     next_output_handler = &output->next;
818 }
819
820 void add_kv_output()
821 {
822     output_handler_t *output = calloc(1, sizeof(output_handler_t));
823     if (!output) {
824         fprintf(stderr, "rtl_433: failed to allocate memory for output handler\n");
825         exit(1);
826     }
827     output->printer = &data_kv_printer;
828     output->file = stdout;
829     *next_output_handler = output;
830     next_output_handler = &output->next;
831 }
832
833 int main(int argc, char **argv) {
834 #ifndef _WIN32
835     struct sigaction sigact;
836 #endif
837     char *out_filename = NULL;
838     char *in_filename = NULL;
839     FILE *in_file;
840     int n_read;
841     int r = 0, opt;
842     int i, gain = 0;
843     int sync_mode = 0;
844     int ppm_error = 0;
845     struct dm_state* demod;
846     uint32_t dev_index = 0;
847     int frequency_current = 0;
848     uint32_t out_block_size = DEFAULT_BUF_LENGTH;
849     int device_count;
850     char vendor[256], product[256], serial[256];
851     int have_opt_R = 0;
852     int register_all = 0;
853
854     setbuf(stdout, NULL);
855     setbuf(stderr, NULL);
856
857     demod = malloc(sizeof (struct dm_state));
858     memset(demod, 0, sizeof (struct dm_state));
859
860     /* initialize tables */
861     baseband_init();
862
863         r_device devices[] = {
864 #define DECL(name) name,
865                         DEVICES
866 #undef DECL
867                         };
868
869     num_r_devices = sizeof(devices)/sizeof(*devices);
870
871     demod->level_limit = DEFAULT_LEVEL_LIMIT;
872
873     while ((opt = getopt(argc, argv, "x:z:p:DtaAI:qm:r:l:d:f:g:s:b:n:SR:F:C:T:UWG")) != -1) {
874         switch (opt) {
875             case 'd':
876                 dev_index = atoi(optarg);
877                 break;
878             case 'f':
879                 if (frequencies < MAX_PROTOCOLS) frequency[frequencies++] = (uint32_t) atof(optarg);
880                 else fprintf(stderr, "Max number of frequencies reached %d\n", MAX_PROTOCOLS);
881                 break;
882             case 'g':
883                 gain = (int) (atof(optarg) * 10); /* tenths of a dB */
884                 break;
885             case 'G':
886                 register_all = 1;
887                 break;
888             case 'p':
889                 ppm_error = atoi(optarg);
890                 break;
891             case 's':
892                 samp_rate = (uint32_t) atof(optarg);
893                 break;
894             case 'b':
895                 out_block_size = (uint32_t) atof(optarg);
896                 break;
897             case 'l':
898                 demod->level_limit = (uint32_t) atof(optarg);
899                 break;
900             case 'n':
901                 bytes_to_read = (uint32_t) atof(optarg) * 2;
902                 break;
903             case 'a':
904                 demod->analyze = 1;
905                 break;
906             case 'A':
907                 demod->analyze_pulses = 1;
908                 break;
909             case 'I':
910                 include_only = atoi(optarg);
911                 break;
912             case 'r':
913                 in_filename = optarg;
914                 break;
915             case 't':
916                 demod->signal_grabber = 1;
917                 break;
918             case 'm':
919                 demod->debug_mode = atoi(optarg);
920                 break;
921             case 'S':
922                 sync_mode = 1;
923                 break;
924             case 'D':
925                 debug_output++;
926                 break;
927             case 'z':
928                 override_short = atoi(optarg);
929                 break;
930             case 'x':
931                 override_long = atoi(optarg);
932                 break;
933             case 'R':
934                 if (!have_opt_R) {
935                     for (i = 0; i < num_r_devices; i++) {
936                         devices[i].disabled = 1;
937                     }
938                     have_opt_R = 1;
939                 }
940
941                 i = atoi(optarg);
942                 if (i > num_r_devices) {
943                     fprintf(stderr, "Remote device number specified larger than number of devices\n\n");
944                     usage(devices);
945                 }
946
947                 devices[i - 1].disabled = 0;
948                 break;
949             case 'q':
950                 quiet_mode = 1;
951                 break;
952             case 'F':
953                 if (strcmp(optarg, "json") == 0) {
954             add_json_output();
955                 } else if (strcmp(optarg, "csv") == 0) {
956             add_csv_output(determine_csv_fields(devices, num_r_devices));
957                 } else if (strcmp(optarg, "kv") == 0) {
958             add_kv_output();
959                 } else {
960                     fprintf(stderr, "Invalid output format %s\n", optarg);
961                     usage(devices);
962                 }
963                 break;
964         case 'C':
965         if (strcmp(optarg, "native") == 0) {
966             conversion_mode = CONVERT_NATIVE;
967         } else if (strcmp(optarg, "si") == 0) {
968             conversion_mode = CONVERT_SI;
969         } else if (strcmp(optarg, "customary") == 0) {
970             conversion_mode = CONVERT_CUSTOMARY;
971         } else {
972                     fprintf(stderr, "Invalid conversion mode %s\n", optarg);
973                     usage(devices);
974         }
975         break;
976         case 'U':
977         #if !defined(__MINGW32__)
978           utc_mode = setenv("TZ", "UTC", 1);
979           if(utc_mode != 0) fprintf(stderr, "Unable to set TZ to UTC; error code: %d\n", utc_mode);
980         #endif
981         break;
982             case 'W':
983             overwrite_mode = 1;
984         break;
985         case 'T':
986           time(&stop_time);
987           duration = atoi(optarg);
988           if (duration < 1) {
989             fprintf(stderr, "Duration '%s' was not positive integer; will continue indefinitely\n", optarg);
990           } else {
991             stop_time += duration;
992           }
993           break;
994             default:
995                 usage(devices);
996                 break;
997         }
998     }
999
1000     if (argc <= optind - 1) {
1001         usage(devices);
1002     } else {
1003         out_filename = argv[optind];
1004     }
1005
1006     if (!output_handler) {
1007         add_kv_output();
1008     }
1009
1010     for (i = 0; i < num_r_devices; i++) {
1011         if (!devices[i].disabled || register_all) {
1012             register_protocol(demod, &devices[i]);
1013             if(devices[i].modulation >= FSK_DEMOD_MIN_VAL) {
1014               demod->enable_FM_demod = 1;
1015             }
1016         }
1017     }
1018
1019     if (!quiet_mode)
1020         fprintf(stderr,"Registered %d out of %d device decoding protocols\n",
1021                 demod->r_dev_num, num_r_devices);
1022
1023     if (out_block_size < MINIMAL_BUF_LENGTH ||
1024             out_block_size > MAXIMAL_BUF_LENGTH) {
1025         fprintf(stderr,
1026                 "Output block size wrong value, falling back to default\n");
1027         fprintf(stderr,
1028                 "Minimal length: %u\n", MINIMAL_BUF_LENGTH);
1029         fprintf(stderr,
1030                 "Maximal length: %u\n", MAXIMAL_BUF_LENGTH);
1031         out_block_size = DEFAULT_BUF_LENGTH;
1032     }
1033
1034     if (!in_filename) {
1035         device_count = rtlsdr_get_device_count();
1036         if (!device_count) {
1037             fprintf(stderr, "No supported devices found.\n");
1038             if (!in_filename)
1039                 exit(1);
1040         }
1041
1042         if (!quiet_mode) {
1043             fprintf(stderr, "Found %d device(s):\n", device_count);
1044             for (i = 0; i < device_count; i++) {
1045                 rtlsdr_get_device_usb_strings(i, vendor, product, serial);
1046                 fprintf(stderr, "  %d:  %s, %s, SN: %s\n", i, vendor, product, serial);
1047             }
1048             fprintf(stderr, "\n");
1049
1050             fprintf(stderr, "Using device %d: %s\n",
1051                     dev_index, rtlsdr_get_device_name(dev_index));
1052         }
1053
1054         r = rtlsdr_open(&dev, dev_index);
1055         if (r < 0) {
1056             fprintf(stderr, "Failed to open rtlsdr device #%d.\n", dev_index);
1057             exit(1);
1058         }
1059 #ifndef _WIN32
1060         sigact.sa_handler = sighandler;
1061         sigemptyset(&sigact.sa_mask);
1062         sigact.sa_flags = 0;
1063         sigaction(SIGINT, &sigact, NULL);
1064         sigaction(SIGTERM, &sigact, NULL);
1065         sigaction(SIGQUIT, &sigact, NULL);
1066         sigaction(SIGPIPE, &sigact, NULL);
1067 #else
1068         SetConsoleCtrlHandler((PHANDLER_ROUTINE) sighandler, TRUE);
1069 #endif
1070         /* Set the sample rate */
1071         r = rtlsdr_set_sample_rate(dev, samp_rate);
1072         if (r < 0)
1073             fprintf(stderr, "WARNING: Failed to set sample rate.\n");
1074         else
1075             fprintf(stderr, "Sample rate set to %d.\n", rtlsdr_get_sample_rate(dev)); // Unfortunately, doesn't return real rate
1076
1077         fprintf(stderr, "Bit detection level set to %d%s.\n", demod->level_limit, (demod->level_limit ? "" : " (Auto)"));
1078
1079         if (0 == gain) {
1080             /* Enable automatic gain */
1081             r = rtlsdr_set_tuner_gain_mode(dev, 0);
1082             if (r < 0)
1083                 fprintf(stderr, "WARNING: Failed to enable automatic gain.\n");
1084             else
1085                 fprintf(stderr, "Tuner gain set to Auto.\n");
1086         } else {
1087             /* Enable manual gain */
1088             r = rtlsdr_set_tuner_gain_mode(dev, 1);
1089             if (r < 0)
1090                 fprintf(stderr, "WARNING: Failed to enable manual gain.\n");
1091
1092             /* Set the tuner gain */
1093             r = rtlsdr_set_tuner_gain(dev, gain);
1094             if (r < 0)
1095                 fprintf(stderr, "WARNING: Failed to set tuner gain.\n");
1096             else
1097                 fprintf(stderr, "Tuner gain set to %f dB.\n", gain / 10.0);
1098         }
1099
1100         r = rtlsdr_set_freq_correction(dev, ppm_error);
1101
1102     }
1103
1104         if (out_filename) {
1105                 if (strcmp(out_filename, "-") == 0) { /* Write samples to stdout */
1106                         demod->out_file = stdout;
1107 #ifdef _WIN32
1108                         _setmode(_fileno(stdin), _O_BINARY);
1109 #endif
1110                 } else {
1111                         if (access(out_filename, F_OK) == 0 && !overwrite_mode) {
1112                             fprintf(stderr, "Output file %s already exists, exiting\n", out_filename);
1113                             goto out;
1114                         }
1115                         demod->out_file = fopen(out_filename, "wb");
1116                         if (!demod->out_file) {
1117                                 fprintf(stderr, "Failed to open %s\n", out_filename);
1118                                 goto out;
1119                         }
1120                 }
1121         }
1122
1123     if (demod->signal_grabber)
1124         demod->sg_buf = malloc(SIGNAL_GRABBER_BUFFER);
1125
1126     if (in_filename) {
1127         int i = 0;
1128         unsigned char test_mode_buf[DEFAULT_BUF_LENGTH];
1129         float test_mode_float_buf[DEFAULT_BUF_LENGTH];
1130         if (strcmp(in_filename, "-") == 0) { /* read samples from stdin */
1131             in_file = stdin;
1132             in_filename = "<stdin>";
1133         } else {
1134             in_file = fopen(in_filename, "rb");
1135             if (!in_file) {
1136                 fprintf(stderr, "Opening file: %s failed!\n", in_filename);
1137                 goto out;
1138             }
1139         }
1140         fprintf(stderr, "Test mode active. Reading samples from file: %s\n", in_filename);      // Essential information (not quiet)
1141         if (!quiet_mode) {
1142             fprintf(stderr, "Input format: %s\n", (demod->debug_mode == 3) ? "cf32" : "uint8");
1143         }
1144         sample_file_pos = 0.0;
1145
1146         int n_read, cf32_tmp;
1147         do {
1148             if (demod->debug_mode == 3) {
1149                 n_read = fread(test_mode_float_buf, sizeof(float), 131072, in_file);
1150                 for(int n = 0; n < n_read; n++) {
1151                     cf32_tmp = test_mode_float_buf[n]*127 + 127;
1152                         if (cf32_tmp < 0)
1153                             cf32_tmp = 0;
1154                         else if (cf32_tmp > 255)
1155                             cf32_tmp = 255;
1156                         test_mode_buf[n] = (uint8_t)cf32_tmp;
1157                 }
1158             } else {
1159                 n_read = fread(test_mode_buf, 1, 131072, in_file);
1160             }
1161             if (n_read == 0) break;     // rtlsdr_callback() will Segmentation Fault with len=0
1162             rtlsdr_callback(test_mode_buf, n_read, demod);
1163             i++;
1164             sample_file_pos = (float)i * n_read / samp_rate;
1165         } while (n_read != 0);
1166
1167         // Call a last time with cleared samples to ensure EOP detection
1168         memset(test_mode_buf, 128, DEFAULT_BUF_LENGTH);     // 128 is 0 in unsigned data
1169         rtlsdr_callback(test_mode_buf, 131072, demod);      // Why the magic value 131072?
1170
1171         //Always classify a signal at the end of the file
1172         classify_signal();
1173         if (!quiet_mode) {
1174             fprintf(stderr, "Test mode file issued %d packets\n", i);
1175         }
1176         exit(0);
1177     }
1178
1179     /* Reset endpoint before we start reading from it (mandatory) */
1180     r = rtlsdr_reset_buffer(dev);
1181     if (r < 0)
1182         fprintf(stderr, "WARNING: Failed to reset buffers.\n");
1183
1184     if (sync_mode) {
1185         if (!demod->out_file) {
1186             fprintf(stderr, "Specify an output file for sync mode.\n");
1187             exit(0);
1188         }
1189
1190         fprintf(stderr, "Reading samples in sync mode...\n");
1191         uint8_t *buffer = malloc(out_block_size * sizeof (uint8_t));
1192
1193       time_t timestamp;
1194         while (!do_exit) {
1195             r = rtlsdr_read_sync(dev, buffer, out_block_size, &n_read);
1196             if (r < 0) {
1197                 fprintf(stderr, "WARNING: sync read failed.\n");
1198                 break;
1199             }
1200
1201             if ((bytes_to_read > 0) && (bytes_to_read < (uint32_t) n_read)) {
1202                 n_read = bytes_to_read;
1203                 do_exit = 1;
1204             }
1205
1206             if (fwrite(buffer, 1, n_read, demod->out_file) != (size_t) n_read) {
1207                 fprintf(stderr, "Short write, samples lost, exiting!\n");
1208                 break;
1209             }
1210
1211             if ((uint32_t) n_read < out_block_size) {
1212                 fprintf(stderr, "Short read, samples lost, exiting!\n");
1213                 break;
1214             }
1215
1216         if (duration > 0) {
1217           time(&timestamp);
1218           if (timestamp >= stop_time) {
1219             do_exit = 1;
1220             fprintf(stderr, "Time expired, exiting!\n");
1221           }
1222         }
1223
1224             if (bytes_to_read > 0)
1225                 bytes_to_read -= n_read;
1226         }
1227
1228         free(buffer);
1229     } else {
1230         if (frequencies == 0) {
1231             frequency[0] = DEFAULT_FREQUENCY;
1232             frequencies = 1;
1233         } else {
1234             time(&rawtime_old);
1235         }
1236         if (!quiet_mode) {
1237             fprintf(stderr, "Reading samples in async mode...\n");
1238         }
1239         while (!do_exit) {
1240             /* Set the frequency */
1241             r = rtlsdr_set_center_freq(dev, frequency[frequency_current]);
1242             if (r < 0)
1243                 fprintf(stderr, "WARNING: Failed to set center freq.\n");
1244             else
1245                 fprintf(stderr, "Tuned to %u Hz.\n", rtlsdr_get_center_freq(dev));
1246             r = rtlsdr_read_async(dev, rtlsdr_callback, (void *) demod,
1247                     DEFAULT_ASYNC_BUF_NUMBER, out_block_size);
1248             do_exit_async = 0;
1249             frequency_current++;
1250             if (frequency_current > frequencies - 1) frequency_current = 0;
1251         }
1252     }
1253
1254     if (do_exit)
1255         fprintf(stderr, "\nUser cancel, exiting...\n");
1256     else
1257         fprintf(stderr, "\nLibrary error %d, exiting...\n", r);
1258
1259     if (demod->out_file && (demod->out_file != stdout))
1260         fclose(demod->out_file);
1261
1262     for (i = 0; i < demod->r_dev_num; i++)
1263         free(demod->r_devs[i]);
1264
1265     if (demod->signal_grabber)
1266         free(demod->sg_buf);
1267
1268     free(demod);
1269
1270     rtlsdr_close(dev);
1271 out:
1272     for (output_handler_t *output = output_handler; output; output = output->next) {
1273         if (output->aux_free) {
1274             output->aux_free(output->aux);
1275         }
1276     }
1277     return r >= 0 ? r : -r;
1278 }