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>
7 * Copyright (C) 2012 by Steve Markgraf <steve@steve-m.de>
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.
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.
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/>.
25 #include "rtl_433_devices.h"
27 static int do_exit = 0;
28 static int do_exit_async = 0, frequencies = 0, events = 0;
29 uint32_t frequency[MAX_PROTOCOLS];
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;
40 int debug_callback(uint8_t bb[BITBUF_ROWS][BITBUF_COLS], int16_t bits_per_row[BITBUF_ROWS]) {
42 int rows_used[BITBUF_ROWS];
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--) {
64 fprintf(stderr, "debug_callback: empty data array\n");
68 fprintf(stderr, "\n");
69 for (i=0 ; i<BITBUF_ROWS ; i++) {
74 fprintf(stderr, "[%02d] ",i);
75 for (j=0 ; j<=col_max ; j++) {
76 fprintf(stderr, "%02x ", bb[i][j]);
78 fprintf(stderr, ": ");
79 for (j=0 ; j<=col_max ; j++) {
80 for (k=7 ; k>=0 ; k--) {
88 fprintf(stderr, "\n");
90 fprintf(stderr, "\n");
95 struct protocol_state {
96 int (*callback)(uint8_t bits_buffer[BITBUF_ROWS][BITBUF_COLS], int16_t bits_per_row[BITBUF_ROWS]);
101 int bits_bit_col_idx;
102 uint8_t bits_buffer[BITBUF_ROWS][BITBUF_COLS];
103 int16_t bits_per_row[BITBUF_ROWS];
105 unsigned int modulation;
130 int32_t decimation_level;
131 int16_t filter_buffer[MAXIMAL_BUF_LENGTH + FILTER_ORDER];
136 /* Signal grabber variables */
143 /* Protocol states */
145 struct protocol_state *r_devs[MAX_PROTOCOLS];
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);
173 sighandler(int signum) {
174 if (CTRL_C_EVENT == signum) {
175 fprintf(stderr, "Signal caught, exiting!\n");
177 rtlsdr_cancel_async(dev);
183 static void sighandler(int signum) {
184 if (signum == SIGPIPE) {
185 signal(SIGPIPE,SIG_IGN);
187 fprintf(stderr, "Signal caught, exiting!\n");
190 rtlsdr_cancel_async(dev);
194 /* precalculate lookup table for envelope detection */
195 static void calc_squares() {
197 for (i = 0; i < 256; i++)
198 scaled_squares[i] = (128 - i) * (128 - i);
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
207 static void envelope_detect(unsigned char *buf, uint32_t len, int decimate) {
208 uint16_t* sample_buffer = (uint16_t*) buf;
211 unsigned int stride = 1 << decimate;
213 for (i = 0; i < len / 2; i += stride) {
214 sample_buffer[op++] = scaled_squares[buf[2 * i ]] + scaled_squares[buf[2 * i + 1]];
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);
222 p->bits_bit_col_idx = 7;
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;
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);
238 p->bits_per_row[p->bit_rows]++;
241 static void demod_next_bits_packet(struct protocol_state* p) {
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);
250 if (p->bit_rows > BITBUF_ROWS - 1)
254 static void demod_print_bits_packet(struct protocol_state* p) {
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]);
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");
269 fprintf(stderr, "0");
271 // fprintf(stderr, "=0x%x ",demod->bits_buffer[i][j]);
272 fprintf(stderr, " ");
274 fprintf(stderr, "\n");
276 fprintf(stderr, "\n");
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);
289 demod->r_devs[demod->r_dev_num] = p;
292 fprintf(stderr, "Registering protocol[%02d] %s\n", demod->r_dev_num, t_dev->name);
294 if (demod->r_dev_num > MAX_PROTOCOLS)
295 fprintf(stderr, "Max number of protocols reached %d\n", MAX_PROTOCOLS);
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] = {
311 static unsigned int signal_pulse_counter = 0;
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;
321 if (!signal_pulse_data[0][0])
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];
336 //fprintf(stderr, "\n\nMax: %d, Min: %d t:%d\n", max, min, t);
338 delta = (max - min)*(max - min);
340 //TODO use Lloyd-Max quantizer instead
342 while ((k < 10) && (delta > 0)) {
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];
354 max_new = max_new + signal_pulse_data[i][2];
359 if (count_min != 0 && count_max != 0) {
360 min_new = min_new / count_min;
361 max_new = max_new / count_max;
364 delta = (min - min_new)*(min - min_new) + (max - max_new)*(max - max_new);
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);
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]);
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);
383 fprintf(stderr, "Distance coding: Pulse length %d\n", (min + max) / 2);
386 p_limit = (max + min) / 2;
388 /* Initial guesses */
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];
405 a[1] = (a[0] + a[2]) / 2;
406 // for (i=0 ; i<1 ; i++) {
407 // b[i] = (a[i]+a[i+1])/2;
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]);
416 while ((k < 10) && (delta > 0)) {
417 for (i = 0; i < 3; i++) {
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];
427 } else if (signal_distance_data[i] < b[1] && signal_distance_data[i] >= b[0]) {
428 a_new[1] += signal_distance_data[i];
430 } else if (signal_distance_data[i] >= b[1]) {
431 a_new[2] += signal_distance_data[i];
437 // fprintf(stderr, "Iteration %d.", k);
439 for (i = 0; i < 3; 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]);
446 // fprintf(stderr, " delta %d\n", delta);
450 // fprintf(stderr, "Fixing a[0] = %d\n", min);
454 // fprintf(stderr, "Fixing a[2] = %d\n", max);
457 // a[1] = (a[2]+a[0])/2;
458 // fprintf(stderr, "Fixing a[1] = %d\n", a[1]);
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]);
467 // fprintf(stderr, "\n");
471 if (override_short) {
472 p_limit = override_short;
473 a[0] = override_short;
477 a[1] = override_long;
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);
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);
509 demod_print_bits_packet(&p);
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);
518 // fprintf(stderr, "1 [%d] %d > %d\n",i, signal_pulse_data[i][2], p_limit);
519 demod_add_bit(&p, 1);
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);
529 demod_print_bits_packet(&p);
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;
541 static void pwm_analyze(struct dm_state *demod, int16_t *buf, uint32_t len) {
544 for (i = 0; i < len; i++) {
545 if (buf[i] > demod->level_limit) {
547 signal_start = counter;
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;
563 if (buf[i] < demod->level_limit) {
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);
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;
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);
586 signal_pulse_counter = 0;
588 int start_pos, signal_bszie, wlen, wrest = 0, sg_idx, idx;
589 char sgf_name[256] = {0};
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;
598 sg_idx = SIGNAL_GRABBER_BUFFER - demod->sg_len;
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);
607 start_pos = SIGNAL_GRABBER_BUFFER + start_pos;
608 fprintf(stderr, "restart_pos = %d\n", start_pos);
611 fprintf(stderr, "*** Saving signal to file %s\n", sgf_name);
612 sgfp = fopen(sgf_name, "wb");
614 fprintf(stderr, "Failed to open %s\n", sgf_name);
617 if (start_pos + signal_bszie > SIGNAL_GRABBER_BUFFER) {
618 wlen = SIGNAL_GRABBER_BUFFER - start_pos;
619 wrest = signal_bszie - wlen;
621 fprintf(stderr, "*** Writing data from %d, len %d\n", start_pos, wlen);
622 fwrite(&demod->sg_buf[start_pos], 1, wlen, sgfp);
625 fprintf(stderr, "*** Writing data from %d, len %d\n", 0, wrest);
626 fwrite(&demod->sg_buf[0], 1, wrest, sgfp);
640 fprintf(stderr, "To many pulses detected, probably bad input data or input parameters\n");
644 /* The distance between pulses decodes into bits */
646 static void pwm_d_decode(struct dm_state *demod, struct protocol_state* p, int16_t *buf, uint32_t len) {
649 for (i = 0; i < len; i++) {
650 if (buf[i] > demod->level_limit) {
654 if (p->pulse_count && (buf[i] < demod->level_limit)) {
656 p->pulse_distance = 1;
657 p->sample_counter = 0;
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) {
664 } else if (p->sample_counter < p->long_limit) {
667 demod_next_bits_packet(p);
669 p->sample_counter = 0;
671 p->pulse_distance = 0;
673 if (p->sample_counter > p->reset_limit) {
675 p->sample_counter = 0;
676 p->pulse_distance = 0;
678 events += p->callback(p->bits_buffer, p->bits_per_row);
680 demod_print_bits_packet(p);
682 demod_reset_bits_packet(p);
687 /* The length of pulses decodes into bits */
689 static void pwm_p_decode(struct dm_state *demod, struct protocol_state* p, int16_t *buf, uint32_t len) {
692 for (i = 0; i < len; i++) {
693 if (buf[i] > demod->level_limit && !p->start_bit) {
694 /* start bit detected */
697 p->sample_counter = 0;
698 // fprintf(stderr, "start bit pulse start detected\n");
701 if (!p->real_bits && p->start_bit && (buf[i] < demod->level_limit)) {
702 /* end of startbit */
705 p->sample_counter = 0;
706 // fprintf(stderr, "start bit pulse end detected\n");
708 if (p->start_c) p->sample_counter++;
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");
718 if (p->real_bits && p->pulse_start && (buf[i] < demod->level_limit)) {
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);
725 if (p->pulse_length <= p->short_limit) {
727 } else if (p->pulse_length > p->short_limit) {
730 p->sample_counter = 0;
734 if (p->real_bits && (p->pulse_length > p->long_limit)) {
735 demod_next_bits_packet(p);
741 if (p->sample_counter > p->reset_limit) {
743 p->sample_counter = 0;
744 //demod_print_bits_packet(p);
746 events += p->callback(p->bits_buffer, p->bits_per_row);
748 demod_print_bits_packet(p);
749 demod_reset_bits_packet(p);
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).
763 static void manchester_decode(struct dm_state *demod, struct protocol_state* p, int16_t *buf, uint32_t len) {
766 if (p->sample_counter == 0)
767 p->sample_counter = p->short_limit*2;
769 for (i=0 ; i<len ; i++) {
772 p->sample_counter++; /* For this decode type, sample counter is count since last data bit recorded */
774 if (!p->pulse_count && (buf[i] > demod->level_limit)) { /* Pulse start (rising edge) */
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) */
781 p->start_c++; // start_c counts number of bits received
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) */
795 if (p->sample_counter > p->reset_limit) {
796 //fprintf(stderr, "manchester_decode number of bits received=%d\n",p->start_c);
798 events+=p->callback(p->bits_buffer, p->bits_per_row);
800 demod_print_bits_packet(p);
801 demod_reset_bits_packet(p);
802 p->sample_counter = p->short_limit*2;
808 /** Something that might look like a IIR lowpass filter
810 * [b,a] = butter(1, 0.01) -> quantizes nicely thus suitable for fixed point
811 * Q1.15*Q15.0 = Q16.15
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/
818 static uint16_t lp_xmem[FILTER_ORDER] = {0};
821 #define S_CONST (1<<F_SCALE)
822 #define FIX(x) ((int)(x*S_CONST))
824 int a[FILTER_ORDER + 1] = {FIX(1.00000), FIX(0.96907)};
825 int b[FILTER_ORDER + 1] = {FIX(0.015466), FIX(0.015466)};
827 static void low_pass_filter(uint16_t *x_buf, int16_t *y_buf, uint32_t len) {
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);
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]);
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;
846 if (demod->file || !demod->save_data) {
847 if (do_exit || do_exit_async)
850 if ((bytes_to_read > 0) && (bytes_to_read < len)) {
853 rtlsdr_cancel_async(dev);
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);
860 demod->sg_index += len;
861 if (demod->sg_index + len > SIGNAL_GRABBER_BUFFER)
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);
872 if (demod->analyze) {
873 pwm_analyze(demod, demod->f_buf, len / 2);
875 for (i = 0; i < demod->r_dev_num; i++) {
876 switch (demod->r_devs[i]->modulation) {
878 pwm_d_decode(demod, demod->r_devs[i], demod->f_buf, len / 2);
881 pwm_p_decode(demod, demod->r_devs[i], demod->f_buf, len / 2);
884 manchester_decode(demod, demod->r_devs[i], demod->f_buf, len/2);
887 fprintf(stderr, "Unknown modulation %d in protocol!\n", demod->r_devs[i]->modulation);
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);
900 if (bytes_to_read > 0)
901 bytes_to_read -= len;
903 if (frequencies > 1) {
906 if (difftime(rawtime, rawtime_old) > DEFAULT_HOP_TIME || events >= DEFAULT_HOP_EVENTS) {
907 rawtime_old = rawtime;
910 rtlsdr_cancel_async(dev);
916 int main(int argc, char **argv) {
918 struct sigaction sigact;
920 char *filename = NULL;
921 char *test_mode_file = NULL;
928 struct dm_state* demod;
930 uint32_t dev_index = 0;
931 int frequency_current = 0;
932 uint32_t out_block_size = DEFAULT_BUF_LENGTH;
934 char vendor[256], product[256], serial[256];
936 demod = malloc(sizeof (struct dm_state));
937 memset(demod, 0, sizeof (struct dm_state));
939 /* initialize tables */
942 demod->f_buf = &demod->filter_buffer[FILTER_ORDER];
943 demod->decimation_level = DEFAULT_DECIMATION_LEVEL;
944 demod->level_limit = DEFAULT_LEVEL_LIMIT;
947 while ((opt = getopt(argc, argv, "x:z:p:Dtam:r:c:l:d:f:g:s:b:n:S::")) != -1) {
950 dev_index = atoi(optarg);
953 if (frequencies < MAX_PROTOCOLS) frequency[frequencies++] = (uint32_t) atof(optarg);
954 else fprintf(stderr, "Max number of frequencies reached %d\n", MAX_PROTOCOLS);
957 gain = (int) (atof(optarg) * 10); /* tenths of a dB */
960 ppm_error = atoi(optarg);
963 samp_rate = (uint32_t) atof(optarg);
966 out_block_size = (uint32_t) atof(optarg);
969 demod->level_limit = (uint32_t) atof(optarg);
972 bytes_to_read = (uint32_t) atof(optarg) * 2;
975 demod->decimation_level = (uint32_t) atof(optarg);
981 test_mode_file = optarg;
984 demod->signal_grabber = 1;
987 demod->debug_mode = atoi(optarg);
996 override_short = atoi(optarg);
999 override_long = atoi(optarg);
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);
1028 if (argc <= optind - 1) {
1031 filename = argv[optind];
1034 if (out_block_size < MINIMAL_BUF_LENGTH ||
1035 out_block_size > MAXIMAL_BUF_LENGTH) {
1037 "Output block size wrong value, falling back to default\n");
1039 "Minimal length: %u\n", MINIMAL_BUF_LENGTH);
1041 "Maximal length: %u\n", MAXIMAL_BUF_LENGTH);
1042 out_block_size = DEFAULT_BUF_LENGTH;
1045 buffer = malloc(out_block_size * sizeof (uint8_t));
1047 device_count = rtlsdr_get_device_count();
1048 if (!device_count) {
1049 fprintf(stderr, "No supported devices found.\n");
1050 if (!test_mode_file)
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);
1059 fprintf(stderr, "\n");
1061 fprintf(stderr, "Using device %d: %s\n",
1062 dev_index, rtlsdr_get_device_name(dev_index));
1064 r = rtlsdr_open(&dev, dev_index);
1066 fprintf(stderr, "Failed to open rtlsdr device #%d.\n", dev_index);
1067 if (!test_mode_file)
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);
1079 SetConsoleCtrlHandler((PHANDLER_ROUTINE) sighandler, TRUE);
1081 /* Set the sample rate */
1082 r = rtlsdr_set_sample_rate(dev, samp_rate);
1084 fprintf(stderr, "WARNING: Failed to set sample rate.\n");
1086 fprintf(stderr, "Sample rate set to %d.\n", rtlsdr_get_sample_rate(dev)); // Unfortunately, doesn't return real rate
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);
1092 /* Enable automatic gain */
1093 r = rtlsdr_set_tuner_gain_mode(dev, 0);
1095 fprintf(stderr, "WARNING: Failed to enable automatic gain.\n");
1097 fprintf(stderr, "Tuner gain set to Auto.\n");
1099 /* Enable manual gain */
1100 r = rtlsdr_set_tuner_gain_mode(dev, 1);
1102 fprintf(stderr, "WARNING: Failed to enable manual gain.\n");
1104 /* Set the tuner gain */
1105 r = rtlsdr_set_tuner_gain(dev, gain);
1107 fprintf(stderr, "WARNING: Failed to set tuner gain.\n");
1109 fprintf(stderr, "Tuner gain set to %f dB.\n", gain / 10.0);
1112 r = rtlsdr_set_freq_correction(dev, ppm_error);
1114 demod->save_data = 1;
1116 demod->save_data = 0;
1117 } else if (strcmp(filename, "-") == 0) { /* Write samples to stdout */
1118 demod->file = stdout;
1120 _setmode(_fileno(stdin), _O_BINARY);
1123 demod->file = fopen(filename, "wb");
1125 fprintf(stderr, "Failed to open %s\n", filename);
1130 if (demod->signal_grabber)
1131 demod->sg_buf = malloc(SIGNAL_GRABBER_BUFFER);
1133 if (test_mode_file) {
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");
1139 fprintf(stderr, "Opening file: %s failed!\n", test_mode_file);
1142 while (fread(test_mode_buf, 131072, 1, test_mode) != 0) {
1143 rtlsdr_callback(test_mode_buf, 131072, demod);
1146 //Always classify a signal at the end of the file
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]);
1155 /* Reset endpoint before we start reading from it (mandatory) */
1156 r = rtlsdr_reset_buffer(dev);
1158 fprintf(stderr, "WARNING: Failed to reset buffers.\n");
1161 fprintf(stderr, "Reading samples in sync mode...\n");
1163 r = rtlsdr_read_sync(dev, buffer, out_block_size, &n_read);
1165 fprintf(stderr, "WARNING: sync read failed.\n");
1169 if ((bytes_to_read > 0) && (bytes_to_read < (uint32_t) n_read)) {
1170 n_read = bytes_to_read;
1174 if (fwrite(buffer, 1, n_read, demod->file) != (size_t) n_read) {
1175 fprintf(stderr, "Short write, samples lost, exiting!\n");
1179 if ((uint32_t) n_read < out_block_size) {
1180 fprintf(stderr, "Short read, samples lost, exiting!\n");
1184 if (bytes_to_read > 0)
1185 bytes_to_read -= n_read;
1188 if (frequencies == 0) {
1189 frequency[0] = DEFAULT_FREQUENCY;
1194 fprintf(stderr, "Reading samples in async mode...\n");
1196 /* Set the frequency */
1197 r = rtlsdr_set_center_freq(dev, frequency[frequency_current]);
1199 fprintf(stderr, "WARNING: Failed to set center freq.\n");
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);
1205 frequency_current++;
1206 if (frequency_current > frequencies - 1) frequency_current = 0;
1211 fprintf(stderr, "\nUser cancel, exiting...\n");
1213 fprintf(stderr, "\nLibrary error %d, exiting...\n", r);
1215 if (demod->file && (demod->file != stdout))
1216 fclose(demod->file);
1218 for (i = 0; i < demod->r_dev_num; i++)
1219 free(demod->r_devs[i]);
1221 if (demod->signal_grabber)
1222 free(demod->sg_buf);
1230 return r >= 0 ? r : -r;