- Merged with upstream version
[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 "rtl-sdr.h"
24 #include "rtl_433.h"
25 #include "rtl_433_devices.h"
26
27 static int do_exit = 0;
28 static int do_exit_async = 0, frequencies = 0, events = 0;
29 uint32_t frequency[MAX_PROTOCOLS];
30 time_t rawtime_old;
31 int flag;
32 uint32_t samp_rate = DEFAULT_SAMPLE_RATE;
33 static uint32_t bytes_to_read = 0;
34 static rtlsdr_dev_t *dev = NULL;
35 static uint16_t scaled_squares[256];
36 static int override_short = 0;
37 static int override_long = 0;
38 int debug_output = 0;
39
40 int debug_callback(uint8_t bb[BITBUF_ROWS][BITBUF_COLS], int16_t bits_per_row[BITBUF_ROWS]) {
41     int i,j,k;
42     int rows_used[BITBUF_ROWS];
43     int col_max = 0;
44     int row_cnt = 0;
45
46     // determine what part of bb[][] has non-zero data to avoid
47     // outputting lots of empty rows
48     for (i=0 ; i<BITBUF_ROWS ; i++) {
49         for (j=BITBUF_COLS - 1 ; j > 0 ; j--) {
50             if (bb[i][j] != 0)
51                 break;
52         }
53         if (j != 0) {
54             rows_used[i] = 1;
55             row_cnt++;
56             if (j > col_max)
57                 col_max = j;
58         } else {
59             rows_used[i] = 0;
60         }
61     }
62
63     if (!row_cnt) {
64         fprintf(stderr, "debug_callback: empty data array\n");
65         return 0;
66     }
67
68     fprintf(stderr, "\n");
69     for (i=0 ; i<BITBUF_ROWS ; i++) {
70         if (!rows_used[i]) {
71             continue;
72         }
73
74         fprintf(stderr, "[%02d] ",i);
75         for (j=0 ; j<=col_max ; j++) {
76             fprintf(stderr, "%02x ", bb[i][j]);
77         }
78         fprintf(stderr, ": ");
79         for (j=0 ; j<=col_max ; j++) {
80             for (k=7 ; k>=0 ; k--) {
81                 if (bb[i][j] & 1<<k)
82                     fprintf(stderr, "1");
83                 else
84                     fprintf(stderr, "0");
85             }
86             fprintf(stderr, " ");
87         }
88         fprintf(stderr, "\n");
89     }
90     fprintf(stderr, "\n");
91
92     return 0;
93 }
94
95 struct protocol_state {
96     int (*callback)(uint8_t bits_buffer[BITBUF_ROWS][BITBUF_COLS], int16_t bits_per_row[BITBUF_ROWS]);
97
98     /* bits state */
99     int bits_col_idx;
100     int bits_row_idx;
101     int bits_bit_col_idx;
102     uint8_t bits_buffer[BITBUF_ROWS][BITBUF_COLS];
103     int16_t bits_per_row[BITBUF_ROWS];
104     int bit_rows;
105     unsigned int modulation;
106
107     /* demod state */
108     int pulse_length;
109     int pulse_count;
110     int pulse_distance;
111     int sample_counter;
112     int start_c;
113
114     int packet_present;
115     int pulse_start;
116     int real_bits;
117     int start_bit;
118     /* pwm limits */
119     int short_limit;
120     int long_limit;
121     int reset_limit;
122
123
124 };
125
126 struct dm_state {
127     FILE *file;
128     int save_data;
129     int32_t level_limit;
130     int32_t decimation_level;
131     int16_t filter_buffer[MAXIMAL_BUF_LENGTH + FILTER_ORDER];
132     int16_t* f_buf;
133     int analyze;
134     int debug_mode;
135
136     /* Signal grabber variables */
137     int signal_grabber;
138     int8_t* sg_buf;
139     int sg_index;
140     int sg_len;
141
142
143     /* Protocol states */
144     int r_dev_num;
145     struct protocol_state *r_devs[MAX_PROTOCOLS];
146
147 };
148
149 void usage(void) {
150     fprintf(stderr,
151             "rtl_433, an ISM band generic data receiver for RTL2832 based DVB-T receivers\n\n"
152             "Usage:\t[-d device_index (default: 0)]\n"
153             "\t[-g gain (default: 0 for auto)]\n"
154             "\t[-a analyze mode, print a textual description of the signal]\n"
155             "\t[-t signal auto save, use it together with analyze mode (-a -t)\n"
156             "\t[-l change the detection level used to determine pulses (0-3200) default: %i]\n"
157             "\t[-f [-f...] receive frequency[s], default: %i Hz]\n"
158             "\t[-s samplerate (default: %i Hz)]\n"
159             "\t[-S force sync output (default: async)]\n"
160             "\t[-r read data from file instead of from a receiver]\n"
161             "\t[-p ppm_error (default: 0)]\n"
162             "\t[-r test file name (indata)]\n"
163             "\t[-m test file mode (0 rtl_sdr data, 1 rtl_433 data)]\n"
164             "\t[-D print debug info on event\n"
165             "\t[-z override short value\n"
166             "\t[-x override long value\n"
167             "\tfilename (a '-' dumps samples to stdout)\n\n", DEFAULT_LEVEL_LIMIT, DEFAULT_FREQUENCY, DEFAULT_SAMPLE_RATE);
168     exit(1);
169 }
170
171 #ifdef _WIN32
172 BOOL WINAPI
173 sighandler(int signum) {
174     if (CTRL_C_EVENT == signum) {
175         fprintf(stderr, "Signal caught, exiting!\n");
176         do_exit = 1;
177         rtlsdr_cancel_async(dev);
178         return TRUE;
179     }
180     return FALSE;
181 }
182 #else
183 static void sighandler(int signum) {
184     if (signum == SIGPIPE) {
185         signal(SIGPIPE,SIG_IGN);
186     } else {
187         fprintf(stderr, "Signal caught, exiting!\n");
188     }
189     do_exit = 1;
190     rtlsdr_cancel_async(dev);
191 }
192 #endif
193
194 /* precalculate lookup table for envelope detection */
195 static void calc_squares() {
196     int i;
197     for (i = 0; i < 256; i++)
198         scaled_squares[i] = (128 - i) * (128 - i);
199 }
200
201 /** This will give a noisy envelope of OOK/ASK signals
202  *  Subtract the bias (-128) and get an envelope estimation
203  *  The output will be written in the input buffer
204  *  @returns   pointer to the input buffer
205  */
206
207 static void envelope_detect(unsigned char *buf, uint32_t len, int decimate) {
208     uint16_t* sample_buffer = (uint16_t*) buf;
209     unsigned int i;
210     unsigned op = 0;
211     unsigned int stride = 1 << decimate;
212
213     for (i = 0; i < len / 2; i += stride) {
214         sample_buffer[op++] = scaled_squares[buf[2 * i ]] + scaled_squares[buf[2 * i + 1]];
215     }
216 }
217
218 static void demod_reset_bits_packet(struct protocol_state* p) {
219     memset(p->bits_buffer, 0, BITBUF_ROWS * BITBUF_COLS);
220     memset(p->bits_per_row, 0, BITBUF_ROWS);
221     p->bits_col_idx = 0;
222     p->bits_bit_col_idx = 7;
223     p->bits_row_idx = 0;
224     p->bit_rows = 0;
225 }
226
227 static void demod_add_bit(struct protocol_state* p, int bit) {
228     p->bits_buffer[p->bits_row_idx][p->bits_col_idx] |= bit << p->bits_bit_col_idx;
229     p->bits_bit_col_idx--;
230     if (p->bits_bit_col_idx < 0) {
231         p->bits_bit_col_idx = 7;
232         p->bits_col_idx++;
233         if (p->bits_col_idx > BITBUF_COLS - 1) {
234             p->bits_col_idx = BITBUF_COLS - 1;
235             //            fprintf(stderr, "p->bits_col_idx>%i!\n", BITBUF_COLS-1);
236         }
237     }
238     p->bits_per_row[p->bit_rows]++;
239 }
240
241 static void demod_next_bits_packet(struct protocol_state* p) {
242     p->bits_col_idx = 0;
243     p->bits_row_idx++;
244     p->bits_bit_col_idx = 7;
245     if (p->bits_row_idx > BITBUF_ROWS - 1) {
246         p->bits_row_idx = BITBUF_ROWS - 1;
247         //fprintf(stderr, "p->bits_row_idx>%i!\n", BITBUF_ROWS-1);
248     }
249     p->bit_rows++;
250     if (p->bit_rows > BITBUF_ROWS - 1)
251         p->bit_rows -= 1;
252 }
253
254 static void demod_print_bits_packet(struct protocol_state* p) {
255     int i, j, k;
256
257     fprintf(stderr, "\n");
258     for (i = 0; i < p->bit_rows + 1; i++) {
259         fprintf(stderr, "[%02d] {%d} ", i, p->bits_per_row[i]);
260         for (j = 0; j < ((p->bits_per_row[i] + 8) / 8); j++) {
261             fprintf(stderr, "%02x ", p->bits_buffer[i][j]);
262         }
263         fprintf(stderr, ": ");
264         for (j = 0; j < ((p->bits_per_row[i] + 8) / 8); j++) {
265             for (k = 7; k >= 0; k--) {
266                 if (p->bits_buffer[i][j] & 1 << k)
267                     fprintf(stderr, "1");
268                 else
269                     fprintf(stderr, "0");
270             }
271             //            fprintf(stderr, "=0x%x ",demod->bits_buffer[i][j]);
272             fprintf(stderr, " ");
273         }
274         fprintf(stderr, "\n");
275     }
276     fprintf(stderr, "\n");
277     return;
278 }
279
280 static void register_protocol(struct dm_state *demod, r_device *t_dev) {
281     struct protocol_state *p = calloc(1, sizeof (struct protocol_state));
282     p->short_limit = (float) t_dev->short_limit / ((float) DEFAULT_SAMPLE_RATE / (float) samp_rate);
283     p->long_limit = (float) t_dev->long_limit / ((float) DEFAULT_SAMPLE_RATE / (float) samp_rate);
284     p->reset_limit = (float) t_dev->reset_limit / ((float) DEFAULT_SAMPLE_RATE / (float) samp_rate);
285     p->modulation = t_dev->modulation;
286     p->callback = t_dev->json_callback;
287     demod_reset_bits_packet(p);
288
289     demod->r_devs[demod->r_dev_num] = p;
290     demod->r_dev_num++;
291
292     fprintf(stderr, "Registering protocol[%02d] %s\n", demod->r_dev_num, t_dev->name);
293
294     if (demod->r_dev_num > MAX_PROTOCOLS)
295         fprintf(stderr, "Max number of protocols reached %d\n", MAX_PROTOCOLS);
296 }
297
298
299 static unsigned int counter = 0;
300 static unsigned int print = 1;
301 static unsigned int print2 = 0;
302 static unsigned int pulses_found = 0;
303 static unsigned int prev_pulse_start = 0;
304 static unsigned int pulse_start = 0;
305 static unsigned int pulse_end = 0;
306 static unsigned int pulse_avg = 0;
307 static unsigned int signal_start = 0;
308 static unsigned int signal_end = 0;
309 static unsigned int signal_pulse_data[4000][3] = {
310     {0}};
311 static unsigned int signal_pulse_counter = 0;
312
313 static void classify_signal() {
314     unsigned int i, k, max = 0, min = 1000000, t;
315     unsigned int delta, count_min, count_max, min_new, max_new, p_limit;
316     unsigned int a[3], b[2], a_cnt[3], a_new[3], b_new[2];
317     unsigned int signal_distance_data[4000] = {0};
318     struct protocol_state p = {0};
319     unsigned int signal_type;
320
321     if (!signal_pulse_data[0][0])
322         return;
323
324     for (i = 0; i < 1000; i++) {
325         if (signal_pulse_data[i][0] > 0) {
326             //fprintf(stderr, "[%03d] s: %d\t  e:\t %d\t l:%d\n",
327             //i, signal_pulse_data[i][0], signal_pulse_data[i][1],
328             //signal_pulse_data[i][2]);
329             if (signal_pulse_data[i][2] > max)
330                 max = signal_pulse_data[i][2];
331             if (signal_pulse_data[i][2] <= min)
332                 min = signal_pulse_data[i][2];
333         }
334     }
335     t = (max + min) / 2;
336     //fprintf(stderr, "\n\nMax: %d, Min: %d  t:%d\n", max, min, t);
337
338     delta = (max - min)*(max - min);
339
340     //TODO use Lloyd-Max quantizer instead
341     k = 1;
342     while ((k < 10) && (delta > 0)) {
343         min_new = 0;
344         count_min = 0;
345         max_new = 0;
346         count_max = 0;
347
348         for (i = 0; i < 1000; i++) {
349             if (signal_pulse_data[i][0] > 0) {
350                 if (signal_pulse_data[i][2] < t) {
351                     min_new = min_new + signal_pulse_data[i][2];
352                     count_min++;
353                 } else {
354                     max_new = max_new + signal_pulse_data[i][2];
355                     count_max++;
356                 }
357             }
358         }
359         if (count_min != 0 && count_max != 0) {
360             min_new = min_new / count_min;
361             max_new = max_new / count_max;
362         }
363
364         delta = (min - min_new)*(min - min_new) + (max - max_new)*(max - max_new);
365         min = min_new;
366         max = max_new;
367         t = (min + max) / 2;
368
369         fprintf(stderr, "Iteration %d. t: %d    min: %d (%d)    max: %d (%d)    delta %d\n", k, t, min, count_min, max, count_max, delta);
370         k++;
371     }
372
373     for (i = 0; i < 1000; i++) {
374         if (signal_pulse_data[i][0] > 0) {
375             //fprintf(stderr, "%d\n", signal_pulse_data[i][1]);
376         }
377     }
378     /* 50% decision limit */
379     if (min != 0 && max / min > 1) {
380         fprintf(stderr, "Pulse coding: Short pulse length %d - Long pulse length %d\n", min, max);
381         signal_type = 2;
382     } else {
383         fprintf(stderr, "Distance coding: Pulse length %d\n", (min + max) / 2);
384         signal_type = 1;
385     }
386     p_limit = (max + min) / 2;
387
388     /* Initial guesses */
389     a[0] = 1000000;
390     a[2] = 0;
391     for (i = 1; i < 1000; i++) {
392         if (signal_pulse_data[i][0] > 0) {
393             //               fprintf(stderr, "[%03d] s: %d\t  e:\t %d\t l:%d\t  d:%d\n",
394             //               i, signal_pulse_data[i][0], signal_pulse_data[i][1],
395             //               signal_pulse_data[i][2], signal_pulse_data[i][0]-signal_pulse_data[i-1][1]);
396             signal_distance_data[i - 1] = signal_pulse_data[i][0] - signal_pulse_data[i - 1][1];
397             if (signal_distance_data[i - 1] > a[2])
398                 a[2] = signal_distance_data[i - 1];
399             if (signal_distance_data[i - 1] <= a[0])
400                 a[0] = signal_distance_data[i - 1];
401         }
402     }
403     min = a[0];
404     max = a[2];
405     a[1] = (a[0] + a[2]) / 2;
406     //    for (i=0 ; i<1 ; i++) {
407     //        b[i] = (a[i]+a[i+1])/2;
408     //    }
409     b[0] = (a[0] + a[1]) / 2;
410     b[1] = (a[1] + a[2]) / 2;
411     //     fprintf(stderr, "a[0]: %d\t a[1]: %d\t a[2]: %d\t\n",a[0],a[1],a[2]);
412     //     fprintf(stderr, "b[0]: %d\t b[1]: %d\n",b[0],b[1]);
413
414     k = 1;
415     delta = 10000000;
416     while ((k < 10) && (delta > 0)) {
417         for (i = 0; i < 3; i++) {
418             a_new[i] = 0;
419             a_cnt[i] = 0;
420         }
421
422         for (i = 0; i < 1000; i++) {
423             if (signal_distance_data[i] > 0) {
424                 if (signal_distance_data[i] < b[0]) {
425                     a_new[0] += signal_distance_data[i];
426                     a_cnt[0]++;
427                 } else if (signal_distance_data[i] < b[1] && signal_distance_data[i] >= b[0]) {
428                     a_new[1] += signal_distance_data[i];
429                     a_cnt[1]++;
430                 } else if (signal_distance_data[i] >= b[1]) {
431                     a_new[2] += signal_distance_data[i];
432                     a_cnt[2]++;
433                 }
434             }
435         }
436
437         //         fprintf(stderr, "Iteration %d.", k);
438         delta = 0;
439         for (i = 0; i < 3; i++) {
440             if (a_cnt[i])
441                 a_new[i] /= a_cnt[i];
442             delta += (a[i] - a_new[i])*(a[i] - a_new[i]);
443             //             fprintf(stderr, "\ta[%d]: %d (%d)", i, a_new[i], a[i]);
444             a[i] = a_new[i];
445         }
446         //         fprintf(stderr, " delta %d\n", delta);
447
448         if (a[0] < min) {
449             a[0] = min;
450             //             fprintf(stderr, "Fixing a[0] = %d\n", min);
451         }
452         if (a[2] > max) {
453             a[0] = max;
454             //             fprintf(stderr, "Fixing a[2] = %d\n", max);
455         }
456         //         if (a[1] == 0) {
457         //             a[1] = (a[2]+a[0])/2;
458         //             fprintf(stderr, "Fixing a[1] = %d\n", a[1]);
459         //         }
460
461         //         fprintf(stderr, "Iteration %d.", k);
462         for (i = 0; i < 2; i++) {
463             //             fprintf(stderr, "\tb[%d]: (%d) ", i, b[i]);
464             b[i] = (a[i] + a[i + 1]) / 2;
465             //             fprintf(stderr, "%d  ", b[i]);
466         }
467         //         fprintf(stderr, "\n");
468         k++;
469     }
470
471     if (override_short) {
472         p_limit = override_short;
473         a[0] = override_short;
474     }
475
476     if (override_long) {
477         a[1] = override_long;
478     }
479
480     if (a[1]<a[0]) {
481         a[1]=a[0]+1;
482     }
483                                   
484     if (a[2]<a[1]*2) {
485         a[2] = a[1]*2;
486     }
487                                                                      
488     fprintf(stderr, "\nShort distance: %d, long distance: %d, packet distance: %d\n", a[0], a[1], a[2]);
489     fprintf(stderr, "\np_limit: %d\n", p_limit);
490
491     demod_reset_bits_packet(&p);
492     if (signal_type == 1) {
493         for (i = 0; i < 1000; i++) {
494             if (signal_distance_data[i] > 0) {
495                 if (signal_distance_data[i] < (a[0] + a[1]) / 2) {
496                     //                     fprintf(stderr, "0 [%d] %d < %d\n",i, signal_distance_data[i], (a[0]+a[1])/2);
497                     demod_add_bit(&p, 0);
498                 } else if ((signal_distance_data[i] > (a[0] + a[1]) / 2) && (signal_distance_data[i] < (a[1] + a[2]) / 2)) {
499                     //                     fprintf(stderr, "0 [%d] %d > %d\n",i, signal_distance_data[i], (a[0]+a[1])/2);
500                     demod_add_bit(&p, 1);
501                 } else if (signal_distance_data[i] > (a[1] + a[2]) / 2) {
502                     //                     fprintf(stderr, "0 [%d] %d > %d\n",i, signal_distance_data[i], (a[1]+a[2])/2);
503                     demod_next_bits_packet(&p);
504                 }
505
506             }
507
508         }
509         demod_print_bits_packet(&p);
510     }
511     if (signal_type == 2) {
512         for (i = 0; i < 1000; i++) {
513             if (signal_pulse_data[i][2] > 0) {
514                 if (signal_pulse_data[i][2] < p_limit) {
515                     //                     fprintf(stderr, "0 [%d] %d < %d\n",i, signal_pulse_data[i][2], p_limit);
516                     demod_add_bit(&p, 0);
517                 } else {
518                     //                     fprintf(stderr, "1 [%d] %d > %d\n",i, signal_pulse_data[i][2], p_limit);
519                     demod_add_bit(&p, 1);
520                 }
521                 if ((signal_distance_data[i] >= (a[1] + a[2]) / 2)) {
522                     //                     fprintf(stderr, "\\n [%d] %d > %d\n",i, signal_distance_data[i], (a[1]+a[2])/2);
523                     demod_next_bits_packet(&p);
524                 }
525
526
527             }
528         }
529         demod_print_bits_packet(&p);
530     }
531
532     for (i = 0; i < 1000; i++) {
533         signal_pulse_data[i][0] = 0;
534         signal_pulse_data[i][1] = 0;
535         signal_pulse_data[i][2] = 0;
536         signal_distance_data[i] = 0;
537     }
538
539 };
540
541 static void pwm_analyze(struct dm_state *demod, int16_t *buf, uint32_t len) {
542     unsigned int i;
543
544     for (i = 0; i < len; i++) {
545         if (buf[i] > demod->level_limit) {
546             if (!signal_start)
547                 signal_start = counter;
548             if (print) {
549                 pulses_found++;
550                 pulse_start = counter;
551                 signal_pulse_data[signal_pulse_counter][0] = counter;
552                 signal_pulse_data[signal_pulse_counter][1] = -1;
553                 signal_pulse_data[signal_pulse_counter][2] = -1;
554                 if (debug_output) fprintf(stderr, "pulse_distance %d\n", counter - pulse_end);
555                 if (debug_output) fprintf(stderr, "pulse_start distance %d\n", pulse_start - prev_pulse_start);
556                 if (debug_output) fprintf(stderr, "pulse_start[%d] found at sample %d, value = %d\n", pulses_found, counter, buf[i]);
557                 prev_pulse_start = pulse_start;
558                 print = 0;
559                 print2 = 1;
560             }
561         }
562         counter++;
563         if (buf[i] < demod->level_limit) {
564             if (print2) {
565                 pulse_avg += counter - pulse_start;
566                 if (debug_output) fprintf(stderr, "pulse_end  [%d] found at sample %d, pulse length = %d, pulse avg length = %d\n",
567                         pulses_found, counter, counter - pulse_start, pulse_avg / pulses_found);
568                 pulse_end = counter;
569                 print2 = 0;
570                 signal_pulse_data[signal_pulse_counter][1] = counter;
571                 signal_pulse_data[signal_pulse_counter][2] = counter - pulse_start;
572                 signal_pulse_counter++;
573                 if (signal_pulse_counter >= 4000) {
574                     signal_pulse_counter = 0;
575                     goto err;
576                 }
577             }
578             print = 1;
579             if (signal_start && (pulse_end + 50000 < counter)) {
580                 signal_end = counter - 40000;
581                 fprintf(stderr, "*** signal_start = %d, signal_end = %d\n", signal_start - 10000, signal_end);
582                 fprintf(stderr, "signal_len = %d,  pulses = %d\n", signal_end - (signal_start - 10000), pulses_found);
583                 pulses_found = 0;
584                 classify_signal();
585
586                 signal_pulse_counter = 0;
587                 if (demod->sg_buf) {
588                     int start_pos, signal_bszie, wlen, wrest = 0, sg_idx, idx;
589                     char sgf_name[256] = {0};
590                     FILE *sgfp;
591
592                     sprintf(sgf_name, "gfile%03d.data", demod->signal_grabber);
593                     demod->signal_grabber++;
594                     signal_bszie = 2 * (signal_end - (signal_start - 10000));
595                     signal_bszie = (131072 - (signal_bszie % 131072)) + signal_bszie;
596                     sg_idx = demod->sg_index - demod->sg_len;
597                     if (sg_idx < 0)
598                         sg_idx = SIGNAL_GRABBER_BUFFER - demod->sg_len;
599                     idx = (i - 40000)*2;
600                     start_pos = sg_idx + idx - signal_bszie;
601                     fprintf(stderr, "signal_bszie = %d  -      sg_index = %d\n", signal_bszie, demod->sg_index);
602                     fprintf(stderr, "start_pos    = %d  -   buffer_size = %d\n", start_pos, SIGNAL_GRABBER_BUFFER);
603                     if (signal_bszie > SIGNAL_GRABBER_BUFFER)
604                         fprintf(stderr, "Signal bigger then buffer, signal = %d > buffer %d !!\n", signal_bszie, SIGNAL_GRABBER_BUFFER);
605
606                     if (start_pos < 0) {
607                         start_pos = SIGNAL_GRABBER_BUFFER + start_pos;
608                         fprintf(stderr, "restart_pos = %d\n", start_pos);
609                     }
610
611                     fprintf(stderr, "*** Saving signal to file %s\n", sgf_name);
612                     sgfp = fopen(sgf_name, "wb");
613                     if (!sgfp) {
614                         fprintf(stderr, "Failed to open %s\n", sgf_name);
615                     }
616                     wlen = signal_bszie;
617                     if (start_pos + signal_bszie > SIGNAL_GRABBER_BUFFER) {
618                         wlen = SIGNAL_GRABBER_BUFFER - start_pos;
619                         wrest = signal_bszie - wlen;
620                     }
621                     fprintf(stderr, "*** Writing data from %d, len %d\n", start_pos, wlen);
622                     fwrite(&demod->sg_buf[start_pos], 1, wlen, sgfp);
623
624                     if (wrest) {
625                         fprintf(stderr, "*** Writing data from %d, len %d\n", 0, wrest);
626                         fwrite(&demod->sg_buf[0], 1, wrest, sgfp);
627                     }
628
629                     fclose(sgfp);
630                 }
631                 signal_start = 0;
632             }
633         }
634
635
636     }
637     return;
638
639 err:
640     fprintf(stderr, "To many pulses detected, probably bad input data or input parameters\n");
641     return;
642 }
643
644 /* The distance between pulses decodes into bits */
645
646 static void pwm_d_decode(struct dm_state *demod, struct protocol_state* p, int16_t *buf, uint32_t len) {
647     unsigned int i;
648
649     for (i = 0; i < len; i++) {
650         if (buf[i] > demod->level_limit) {
651             p->pulse_count = 1;
652             p->start_c = 1;
653         }
654         if (p->pulse_count && (buf[i] < demod->level_limit)) {
655             p->pulse_length = 0;
656             p->pulse_distance = 1;
657             p->sample_counter = 0;
658             p->pulse_count = 0;
659         }
660         if (p->start_c) p->sample_counter++;
661         if (p->pulse_distance && (buf[i] > demod->level_limit)) {
662             if (p->sample_counter < p->short_limit) {
663                 demod_add_bit(p, 0);
664             } else if (p->sample_counter < p->long_limit) {
665                 demod_add_bit(p, 1);
666             } else {
667                 demod_next_bits_packet(p);
668                 p->pulse_count = 0;
669                 p->sample_counter = 0;
670             }
671             p->pulse_distance = 0;
672         }
673         if (p->sample_counter > p->reset_limit) {
674             p->start_c = 0;
675             p->sample_counter = 0;
676             p->pulse_distance = 0;
677             if (p->callback)
678                 events += p->callback(p->bits_buffer, p->bits_per_row);
679             else
680                 demod_print_bits_packet(p);
681
682             demod_reset_bits_packet(p);
683         }
684     }
685 }
686
687 /* The length of pulses decodes into bits */
688
689 static void pwm_p_decode(struct dm_state *demod, struct protocol_state* p, int16_t *buf, uint32_t len) {
690     unsigned int i;
691
692     for (i = 0; i < len; i++) {
693         if (buf[i] > demod->level_limit && !p->start_bit) {
694             /* start bit detected */
695             p->start_bit = 1;
696             p->start_c = 1;
697             p->sample_counter = 0;
698             //            fprintf(stderr, "start bit pulse start detected\n");
699         }
700
701         if (!p->real_bits && p->start_bit && (buf[i] < demod->level_limit)) {
702             /* end of startbit */
703             p->real_bits = 1;
704             p->pulse_length = 0;
705             p->sample_counter = 0;
706             //            fprintf(stderr, "start bit pulse end detected\n");
707         }
708         if (p->start_c) p->sample_counter++;
709
710
711         if (!p->pulse_start && p->real_bits && (buf[i] > demod->level_limit)) {
712             /* save the pulse start, it will never be zero */
713             p->pulse_start = p->sample_counter;
714             //           fprintf(stderr, "real bit pulse start detected\n");
715
716         }
717
718         if (p->real_bits && p->pulse_start && (buf[i] < demod->level_limit)) {
719             /* end of pulse */
720
721             p->pulse_length = p->sample_counter - p->pulse_start;
722             //           fprintf(stderr, "real bit pulse end detected %d\n", p->pulse_length);
723             //           fprintf(stderr, "space duration %d\n", p->sample_counter);
724
725             if (p->pulse_length <= p->short_limit) {
726                 demod_add_bit(p, 1);
727             } else if (p->pulse_length > p->short_limit) {
728                 demod_add_bit(p, 0);
729             }
730             p->sample_counter = 0;
731             p->pulse_start = 0;
732         }
733
734         if (p->real_bits && (p->pulse_length > p->long_limit)) {
735             demod_next_bits_packet(p);
736
737             p->start_bit = 0;
738             p->real_bits = 0;
739         }
740
741         if (p->sample_counter > p->reset_limit) {
742             p->start_c = 0;
743             p->sample_counter = 0;
744             //demod_print_bits_packet(p);
745             if (p->callback)
746                 events += p->callback(p->bits_buffer, p->bits_per_row);
747             else
748                 demod_print_bits_packet(p);
749             demod_reset_bits_packet(p);
750
751             p->start_bit = 0;
752             p->real_bits = 0;
753         }
754     }
755 }
756
757 /*  Machester Decode for Oregon Scientific Weather Sensors
758    Decode data streams sent by Oregon Scientific v2.1, and v3 weather sensors.
759    With manchester encoding, both the pulse width and pulse distance vary.  Clock sync
760    is recovered from the data stream based on pulse widths and distances exceeding a
761    minimum threashold (short limit* 1.5).
762  */
763 static void manchester_decode(struct dm_state *demod, struct protocol_state* p, int16_t *buf, uint32_t len) {
764     unsigned int i;
765
766         if (p->sample_counter == 0)
767             p->sample_counter = p->short_limit*2;
768
769     for (i=0 ; i<len ; i++) {
770
771             if (p->start_c)
772                     p->sample_counter++; /* For this decode type, sample counter is count since last data bit recorded */
773
774         if (!p->pulse_count && (buf[i] > demod->level_limit)) { /* Pulse start (rising edge) */
775             p->pulse_count = 1;
776                         if (p->sample_counter  > (p->short_limit + (p->short_limit>>1))) {
777                            /* Last bit was recorded more than short_limit*1.5 samples ago */
778                            /* so this pulse start must be a data edge (rising data edge means bit = 0) */
779                demod_add_bit(p, 0);
780                            p->sample_counter=1;
781                            p->start_c++; // start_c counts number of bits received
782                         }
783         }
784         if (p->pulse_count && (buf[i] <= demod->level_limit)) { /* Pulse end (falling edge) */
785                     if (p->sample_counter > (p->short_limit + (p->short_limit>>1))) {
786                        /* Last bit was recorded more than "short_limit*1.5" samples ago */
787                            /* so this pulse end is a data edge (falling data edge means bit = 1) */
788                demod_add_bit(p, 1);
789                            p->sample_counter=1;
790                            p->start_c++;
791                         }
792             p->pulse_count = 0;
793         }
794
795         if (p->sample_counter > p->reset_limit) {
796         //fprintf(stderr, "manchester_decode number of bits received=%d\n",p->start_c);
797                    if (p->callback)
798               events+=p->callback(p->bits_buffer, p->bits_per_row);
799            else
800               demod_print_bits_packet(p);
801                         demod_reset_bits_packet(p);
802                 p->sample_counter = p->short_limit*2;
803                         p->start_c = 0;
804         }
805     }
806 }
807
808 /** Something that might look like a IIR lowpass filter
809  *
810  *  [b,a] = butter(1, 0.01) ->  quantizes nicely thus suitable for fixed point
811  *  Q1.15*Q15.0 = Q16.15
812  *  Q16.15>>1 = Q15.14
813  *  Q15.14 + Q15.14 + Q15.14 could possibly overflow to 17.14
814  *  but the b coeffs are small so it wont happen
815  *  Q15.14>>14 = Q15.0 \o/
816  */
817
818 static uint16_t lp_xmem[FILTER_ORDER] = {0};
819
820 #define F_SCALE 15
821 #define S_CONST (1<<F_SCALE)
822 #define FIX(x) ((int)(x*S_CONST))
823
824 int a[FILTER_ORDER + 1] = {FIX(1.00000), FIX(0.96907)};
825 int b[FILTER_ORDER + 1] = {FIX(0.015466), FIX(0.015466)};
826
827 static void low_pass_filter(uint16_t *x_buf, int16_t *y_buf, uint32_t len) {
828     unsigned int i;
829
830     /* Calculate first sample */
831     y_buf[0] = ((a[1] * y_buf[-1] >> 1) + (b[0] * x_buf[0] >> 1) + (b[1] * lp_xmem[0] >> 1)) >> (F_SCALE - 1);
832     for (i = 1; i < len; i++) {
833         y_buf[i] = ((a[1] * y_buf[i - 1] >> 1) + (b[0] * x_buf[i] >> 1) + (b[1] * x_buf[i - 1] >> 1)) >> (F_SCALE - 1);
834     }
835
836     /* Save last sample */
837     memcpy(lp_xmem, &x_buf[len - 1 - FILTER_ORDER], FILTER_ORDER * sizeof (int16_t));
838     memcpy(&y_buf[-FILTER_ORDER], &y_buf[len - 1 - FILTER_ORDER], FILTER_ORDER * sizeof (int16_t));
839     //fprintf(stderr, "%d\n", y_buf[0]);
840 }
841
842 static void rtlsdr_callback(unsigned char *buf, uint32_t len, void *ctx) {
843     struct dm_state *demod = ctx;
844     uint16_t* sbuf = (uint16_t*) buf;
845     int i;
846     if (demod->file || !demod->save_data) {
847         if (do_exit || do_exit_async)
848             return;
849
850         if ((bytes_to_read > 0) && (bytes_to_read < len)) {
851             len = bytes_to_read;
852             do_exit = 1;
853             rtlsdr_cancel_async(dev);
854         }
855
856         if (demod->signal_grabber) {
857             //fprintf(stderr, "[%d] sg_index - len %d\n", demod->sg_index, len );
858             memcpy(&demod->sg_buf[demod->sg_index], buf, len);
859             demod->sg_len = len;
860             demod->sg_index += len;
861             if (demod->sg_index + len > SIGNAL_GRABBER_BUFFER)
862                 demod->sg_index = 0;
863         }
864
865
866         if (demod->debug_mode == 0) {
867             envelope_detect(buf, len, demod->decimation_level);
868             low_pass_filter(sbuf, demod->f_buf, len >> (demod->decimation_level + 1));
869         } else if (demod->debug_mode == 1) {
870             memcpy(demod->f_buf, buf, len);
871         }
872         if (demod->analyze) {
873             pwm_analyze(demod, demod->f_buf, len / 2);
874         } else {
875             for (i = 0; i < demod->r_dev_num; i++) {
876                 switch (demod->r_devs[i]->modulation) {
877                     case OOK_PWM_D:
878                         pwm_d_decode(demod, demod->r_devs[i], demod->f_buf, len / 2);
879                         break;
880                     case OOK_PWM_P:
881                         pwm_p_decode(demod, demod->r_devs[i], demod->f_buf, len / 2);
882                         break;
883                     case OOK_MANCHESTER:
884                         manchester_decode(demod, demod->r_devs[i], demod->f_buf, len/2);
885                         break;
886                     default:
887                         fprintf(stderr, "Unknown modulation %d in protocol!\n", demod->r_devs[i]->modulation);
888                 }
889             }
890             fflush(stdout);
891         }
892
893         if (demod->save_data) {
894             if (fwrite(demod->f_buf, 1, len >> demod->decimation_level, demod->file) != len >> demod->decimation_level) {
895                 fprintf(stderr, "Short write, samples lost, exiting!\n");
896                 rtlsdr_cancel_async(dev);
897             }
898         }
899
900         if (bytes_to_read > 0)
901             bytes_to_read -= len;
902
903         if (frequencies > 1) {
904             time_t rawtime;
905             time(&rawtime);
906             if (difftime(rawtime, rawtime_old) > DEFAULT_HOP_TIME || events >= DEFAULT_HOP_EVENTS) {
907                 rawtime_old = rawtime;
908                 events = 0;
909                 do_exit_async = 1;
910                 rtlsdr_cancel_async(dev);
911             }
912         }
913     }
914 }
915
916 int main(int argc, char **argv) {
917 #ifndef _WIN32
918     struct sigaction sigact;
919 #endif
920     char *filename = NULL;
921     char *test_mode_file = NULL;
922     FILE *test_mode;
923     int n_read;
924     int r, opt;
925     int i, gain = 0;
926     int sync_mode = 0;
927     int ppm_error = 0;
928     struct dm_state* demod;
929     uint8_t *buffer;
930     uint32_t dev_index = 0;
931     int frequency_current = 0;
932     uint32_t out_block_size = DEFAULT_BUF_LENGTH;
933     int device_count;
934     char vendor[256], product[256], serial[256];
935
936     demod = malloc(sizeof (struct dm_state));
937     memset(demod, 0, sizeof (struct dm_state));
938
939     /* initialize tables */
940     calc_squares();
941
942     demod->f_buf = &demod->filter_buffer[FILTER_ORDER];
943     demod->decimation_level = DEFAULT_DECIMATION_LEVEL;
944     demod->level_limit = DEFAULT_LEVEL_LIMIT;
945
946
947     while ((opt = getopt(argc, argv, "x:z:p:Dtam:r:c:l:d:f:g:s:b:n:S::")) != -1) {
948         switch (opt) {
949             case 'd':
950                 dev_index = atoi(optarg);
951                 break;
952             case 'f':
953                 if (frequencies < MAX_PROTOCOLS) frequency[frequencies++] = (uint32_t) atof(optarg);
954                 else fprintf(stderr, "Max number of frequencies reached %d\n", MAX_PROTOCOLS);
955                 break;
956             case 'g':
957                 gain = (int) (atof(optarg) * 10); /* tenths of a dB */
958                 break;
959             case 'p':
960                 ppm_error = atoi(optarg);
961                 break;
962             case 's':
963                 samp_rate = (uint32_t) atof(optarg);
964                 break;
965             case 'b':
966                 out_block_size = (uint32_t) atof(optarg);
967                 break;
968             case 'l':
969                 demod->level_limit = (uint32_t) atof(optarg);
970                 break;
971             case 'n':
972                 bytes_to_read = (uint32_t) atof(optarg) * 2;
973                 break;
974             case 'c':
975                 demod->decimation_level = (uint32_t) atof(optarg);
976                 break;
977             case 'a':
978                 demod->analyze = 1;
979                 break;
980             case 'r':
981                 test_mode_file = optarg;
982                 break;
983             case 't':
984                 demod->signal_grabber = 1;
985                 break;
986             case 'm':
987                 demod->debug_mode = atoi(optarg);
988                 break;
989             case 'S':
990                 sync_mode = 1;
991                 break;
992             case 'D':
993                 debug_output = 1;
994                 break;
995             case 'z':
996                 override_short = atoi(optarg);
997                 break;
998             case 'x':
999                 override_long = atoi(optarg);
1000                 break;
1001             default:
1002                 usage();
1003                 break;
1004         }
1005     }
1006
1007     /* init protocols somewhat ok */
1008     register_protocol(demod, &rubicson);
1009     register_protocol(demod, &prologue);
1010     register_protocol(demod, &silvercrest);
1011     //    register_protocol(demod, &generic_hx2262);
1012     //    register_protocol(demod, &technoline_ws9118);
1013     register_protocol(demod, &elv_em1000);
1014     register_protocol(demod, &elv_ws2000);
1015     register_protocol(demod, &waveman);
1016     register_protocol(demod, &steffen);
1017     register_protocol(demod, &acurite5n1);
1018     register_protocol(demod, &acurite_th);
1019     register_protocol(demod, &acurite_rain_gauge);
1020     register_protocol(demod, &lacrossetx);
1021     register_protocol(demod, &oregon_scientific);
1022     register_protocol(demod, &newkaku);
1023     register_protocol(demod, &alectov1);
1024     register_protocol(demod, &intertechno);
1025     register_protocol(demod, &mebus433);
1026     register_protocol(demod, &wh2);
1027
1028     if (argc <= optind - 1) {
1029         usage();
1030     } else {
1031         filename = argv[optind];
1032     }
1033
1034     if (out_block_size < MINIMAL_BUF_LENGTH ||
1035             out_block_size > MAXIMAL_BUF_LENGTH) {
1036         fprintf(stderr,
1037                 "Output block size wrong value, falling back to default\n");
1038         fprintf(stderr,
1039                 "Minimal length: %u\n", MINIMAL_BUF_LENGTH);
1040         fprintf(stderr,
1041                 "Maximal length: %u\n", MAXIMAL_BUF_LENGTH);
1042         out_block_size = DEFAULT_BUF_LENGTH;
1043     }
1044
1045     buffer = malloc(out_block_size * sizeof (uint8_t));
1046
1047     device_count = rtlsdr_get_device_count();
1048     if (!device_count) {
1049         fprintf(stderr, "No supported devices found.\n");
1050         if (!test_mode_file)
1051             exit(1);
1052     }
1053
1054     fprintf(stderr, "Found %d device(s):\n", device_count);
1055     for (i = 0; i < device_count; i++) {
1056         rtlsdr_get_device_usb_strings(i, vendor, product, serial);
1057         fprintf(stderr, "  %d:  %s, %s, SN: %s\n", i, vendor, product, serial);
1058     }
1059     fprintf(stderr, "\n");
1060
1061     fprintf(stderr, "Using device %d: %s\n",
1062             dev_index, rtlsdr_get_device_name(dev_index));
1063
1064     r = rtlsdr_open(&dev, dev_index);
1065     if (r < 0) {
1066         fprintf(stderr, "Failed to open rtlsdr device #%d.\n", dev_index);
1067         if (!test_mode_file)
1068             exit(1);
1069     }
1070 #ifndef _WIN32
1071     sigact.sa_handler = sighandler;
1072     sigemptyset(&sigact.sa_mask);
1073     sigact.sa_flags = 0;
1074     sigaction(SIGINT, &sigact, NULL);
1075     sigaction(SIGTERM, &sigact, NULL);
1076     sigaction(SIGQUIT, &sigact, NULL);
1077     sigaction(SIGPIPE, &sigact, NULL);
1078 #else
1079     SetConsoleCtrlHandler((PHANDLER_ROUTINE) sighandler, TRUE);
1080 #endif
1081     /* Set the sample rate */
1082     r = rtlsdr_set_sample_rate(dev, samp_rate);
1083     if (r < 0)
1084         fprintf(stderr, "WARNING: Failed to set sample rate.\n");
1085     else
1086         fprintf(stderr, "Sample rate set to %d.\n", rtlsdr_get_sample_rate(dev)); // Unfortunately, doesn't return real rate
1087
1088     fprintf(stderr, "Sample rate decimation set to %d. %d->%d\n", demod->decimation_level, samp_rate, samp_rate >> demod->decimation_level);
1089     fprintf(stderr, "Bit detection level set to %d.\n", demod->level_limit);
1090
1091     if (0 == gain) {
1092         /* Enable automatic gain */
1093         r = rtlsdr_set_tuner_gain_mode(dev, 0);
1094         if (r < 0)
1095             fprintf(stderr, "WARNING: Failed to enable automatic gain.\n");
1096         else
1097             fprintf(stderr, "Tuner gain set to Auto.\n");
1098     } else {
1099         /* Enable manual gain */
1100         r = rtlsdr_set_tuner_gain_mode(dev, 1);
1101         if (r < 0)
1102             fprintf(stderr, "WARNING: Failed to enable manual gain.\n");
1103
1104         /* Set the tuner gain */
1105         r = rtlsdr_set_tuner_gain(dev, gain);
1106         if (r < 0)
1107             fprintf(stderr, "WARNING: Failed to set tuner gain.\n");
1108         else
1109             fprintf(stderr, "Tuner gain set to %f dB.\n", gain / 10.0);
1110     }
1111
1112     r = rtlsdr_set_freq_correction(dev, ppm_error);
1113
1114     demod->save_data = 1;
1115     if (!filename) {
1116         demod->save_data = 0;
1117     } else if (strcmp(filename, "-") == 0) { /* Write samples to stdout */
1118         demod->file = stdout;
1119 #ifdef _WIN32
1120         _setmode(_fileno(stdin), _O_BINARY);
1121 #endif
1122     } else {
1123         demod->file = fopen(filename, "wb");
1124         if (!demod->file) {
1125             fprintf(stderr, "Failed to open %s\n", filename);
1126             goto out;
1127         }
1128     }
1129
1130     if (demod->signal_grabber)
1131         demod->sg_buf = malloc(SIGNAL_GRABBER_BUFFER);
1132
1133     if (test_mode_file) {
1134         int i = 0;
1135         unsigned char test_mode_buf[DEFAULT_BUF_LENGTH];
1136         fprintf(stderr, "Test mode active. Reading samples from file: %s\n", test_mode_file);
1137         test_mode = fopen(test_mode_file, "r");
1138         if (!test_mode) {
1139             fprintf(stderr, "Opening file: %s failed!\n", test_mode_file);
1140             goto out;
1141         }
1142         while (fread(test_mode_buf, 131072, 1, test_mode) != 0) {
1143             rtlsdr_callback(test_mode_buf, 131072, demod);
1144             i++;
1145         }
1146         //Always classify a signal at the end of the file
1147         classify_signal();
1148         fprintf(stderr, "Test mode file issued %d packets\n", i);
1149         fprintf(stderr, "Filter coeffs used:\n");
1150         fprintf(stderr, "a: %d %d\n", a[0], a[1]);
1151         fprintf(stderr, "b: %d %d\n", b[0], b[1]);
1152         exit(0);
1153     }
1154
1155     /* Reset endpoint before we start reading from it (mandatory) */
1156     r = rtlsdr_reset_buffer(dev);
1157     if (r < 0)
1158         fprintf(stderr, "WARNING: Failed to reset buffers.\n");
1159
1160     if (sync_mode) {
1161         fprintf(stderr, "Reading samples in sync mode...\n");
1162         while (!do_exit) {
1163             r = rtlsdr_read_sync(dev, buffer, out_block_size, &n_read);
1164             if (r < 0) {
1165                 fprintf(stderr, "WARNING: sync read failed.\n");
1166                 break;
1167             }
1168
1169             if ((bytes_to_read > 0) && (bytes_to_read < (uint32_t) n_read)) {
1170                 n_read = bytes_to_read;
1171                 do_exit = 1;
1172             }
1173
1174             if (fwrite(buffer, 1, n_read, demod->file) != (size_t) n_read) {
1175                 fprintf(stderr, "Short write, samples lost, exiting!\n");
1176                 break;
1177             }
1178
1179             if ((uint32_t) n_read < out_block_size) {
1180                 fprintf(stderr, "Short read, samples lost, exiting!\n");
1181                 break;
1182             }
1183
1184             if (bytes_to_read > 0)
1185                 bytes_to_read -= n_read;
1186         }
1187     } else {
1188         if (frequencies == 0) {
1189             frequency[0] = DEFAULT_FREQUENCY;
1190             frequencies = 1;
1191         } else {
1192             time(&rawtime_old);
1193         }
1194         fprintf(stderr, "Reading samples in async mode...\n");
1195         while (!do_exit) {
1196             /* Set the frequency */
1197             r = rtlsdr_set_center_freq(dev, frequency[frequency_current]);
1198             if (r < 0)
1199                 fprintf(stderr, "WARNING: Failed to set center freq.\n");
1200             else
1201                 fprintf(stderr, "Tuned to %u Hz.\n", rtlsdr_get_center_freq(dev));
1202             r = rtlsdr_read_async(dev, rtlsdr_callback, (void *) demod,
1203                     DEFAULT_ASYNC_BUF_NUMBER, out_block_size);
1204             do_exit_async = 0;
1205             frequency_current++;
1206             if (frequency_current > frequencies - 1) frequency_current = 0;
1207         }
1208     }
1209
1210     if (do_exit)
1211         fprintf(stderr, "\nUser cancel, exiting...\n");
1212     else
1213         fprintf(stderr, "\nLibrary error %d, exiting...\n", r);
1214
1215     if (demod->file && (demod->file != stdout))
1216         fclose(demod->file);
1217
1218     for (i = 0; i < demod->r_dev_num; i++)
1219         free(demod->r_devs[i]);
1220
1221     if (demod->signal_grabber)
1222         free(demod->sg_buf);
1223
1224     if (demod)
1225         free(demod);
1226
1227     rtlsdr_close(dev);
1228     free(buffer);
1229 out:
1230     return r >= 0 ? r : -r;
1231 }