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/>.
28 #include "pulse_detect.h"
29 #include "pulse_demod.h"
34 static int do_exit = 0;
35 static int do_exit_async = 0, frequencies = 0, events = 0;
36 uint32_t frequency[MAX_PROTOCOLS];
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
51 int overwrite_mode = 0;
58 static conversion_mode_t conversion_mode = CONVERT_NATIVE;
60 int num_r_devices = 0;
65 int16_t am_buf[MAXIMAL_BUF_LENGTH]; // AM demodulated signal (for OOK decoding)
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..)
71 FilterState lowpass_filter_state;
72 DemodFM_State demod_FM_state;
78 /* Signal grabber variables */
87 struct protocol_state *r_devs[MAX_PROTOCOLS];
89 pulse_data_t pulse_data;
90 pulse_data_t fsk_pulse_data;
93 void usage(r_device *devices) {
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);
137 fprintf(stderr, "Supported device protocols:\n");
138 for (i = 0; i < num_r_devices; i++) {
139 if (devices[i].disabled)
144 fprintf(stderr, " [%02d]%c %s\n", i + 1, disabledc, devices[i].name);
146 fprintf(stderr, "\n* Disabled by default, use -R n or -G\n");
153 sighandler(int signum) {
154 if (CTRL_C_EVENT == signum) {
155 fprintf(stderr, "Signal caught, exiting!\n");
157 rtlsdr_cancel_async(dev);
163 static void sighandler(int signum) {
164 if (signum == SIGPIPE) {
165 signal(SIGPIPE,SIG_IGN);
167 fprintf(stderr, "Signal caught, exiting!\n");
170 rtlsdr_cancel_async(dev);
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);
186 demod->r_devs[demod->r_dev_num] = p;
190 fprintf(stderr, "Registering protocol [%d] \"%s\"\n", demod->r_dev_num, t_dev->name);
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");
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] = {
213 static unsigned int signal_pulse_counter = 0;
215 typedef struct output_handler {
216 /*data_printer_t*/ void *printer;
217 void (*aux_free)(void *aux);
220 struct output_handler *next;
222 static output_handler_t *output_handler = NULL;
223 static output_handler_t **next_output_handler = &output_handler;
225 /* handles incoming structured data by dumping it */
226 void data_acquired_handler(data_t *data)
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);
234 d->key = strdup("temperature_C");
237 (pos = strrchr(d->format, 'F'))) {
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);
249 d->key = strdup("temperature_F");
252 (pos = strrchr(d->format, 'C'))) {
259 for (output_handler_t *output = output_handler; output; output = output->next) {
260 data_print(data, output->file, output->printer, output->aux);
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;
273 if (!signal_pulse_data[0][0])
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];
288 //fprintf(stderr, "\n\nMax: %d, Min: %d t:%d\n", max, min, t);
290 delta = (max - min)*(max - min);
292 //TODO use Lloyd-Max quantizer instead
294 while ((k < 10) && (delta > 0)) {
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];
306 max_new = max_new + signal_pulse_data[i][2];
311 if (count_min != 0 && count_max != 0) {
312 min_new = min_new / count_min;
313 max_new = max_new / count_max;
316 delta = (min - min_new)*(min - min_new) + (max - max_new)*(max - max_new);
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);
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]);
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);
335 fprintf(stderr, "Distance coding: Pulse length %d\n", (min + max) / 2);
338 p_limit = (max + min) / 2;
340 /* Initial guesses */
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];
357 a[1] = (a[0] + a[2]) / 2;
358 // for (i=0 ; i<1 ; i++) {
359 // b[i] = (a[i]+a[i+1])/2;
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]);
368 while ((k < 10) && (delta > 0)) {
369 for (i = 0; i < 3; i++) {
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];
379 } else if (signal_distance_data[i] < b[1] && signal_distance_data[i] >= b[0]) {
380 a_new[1] += signal_distance_data[i];
382 } else if (signal_distance_data[i] >= b[1]) {
383 a_new[2] += signal_distance_data[i];
389 // fprintf(stderr, "Iteration %d.", k);
391 for (i = 0; i < 3; 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]);
398 // fprintf(stderr, " delta %d\n", delta);
402 // fprintf(stderr, "Fixing a[0] = %d\n", min);
406 // fprintf(stderr, "Fixing a[2] = %d\n", max);
409 // a[1] = (a[2]+a[0])/2;
410 // fprintf(stderr, "Fixing a[1] = %d\n", a[1]);
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]);
419 // fprintf(stderr, "\n");
423 if (override_short) {
424 p_limit = override_short;
425 a[0] = override_short;
429 a[1] = override_long;
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);
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);
453 bitbuffer_print(&p.bits);
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);
462 // fprintf(stderr, "1 [%d] %d > %d\n",i, signal_pulse_data[i][2], p_limit);
463 bitbuffer_add_bit(&p.bits, 1);
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);
473 bitbuffer_print(&p.bits);
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;
485 static void pwm_analyze(struct dm_state *demod, int16_t *buf, uint32_t len) {
487 int32_t threshold = (demod->level_limit ? demod->level_limit : 8000); // Does not support auto level. Use old default instead.
489 for (i = 0; i < len; i++) {
490 if (buf[i] > threshold) {
492 signal_start = counter;
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;
508 if (buf[i] < threshold) {
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);
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;
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);
531 signal_pulse_counter = 0;
533 int start_pos, signal_bszie, wlen, wrest = 0, sg_idx, idx;
534 char sgf_name[256] = {0};
538 sprintf(sgf_name, "gfile%03d.data", demod->signal_grabber);
539 demod->signal_grabber++;
540 if (access(sgf_name, F_OK) == -1 || overwrite_mode) {
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;
549 sg_idx = SIGNAL_GRABBER_BUFFER - demod->sg_len;
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);
558 start_pos = SIGNAL_GRABBER_BUFFER + start_pos;
559 fprintf(stderr, "restart_pos = %d\n", start_pos);
562 fprintf(stderr, "*** Saving signal to file %s\n", sgf_name);
563 sgfp = fopen(sgf_name, "wb");
565 fprintf(stderr, "Failed to open %s\n", sgf_name);
568 if (start_pos + signal_bszie > SIGNAL_GRABBER_BUFFER) {
569 wlen = SIGNAL_GRABBER_BUFFER - start_pos;
570 wrest = signal_bszie - wlen;
572 fprintf(stderr, "*** Writing data from %d, len %d\n", start_pos, wlen);
573 fwrite(&demod->sg_buf[start_pos], 1, wlen, sgfp);
576 fprintf(stderr, "*** Writing data from %d, len %d\n", 0, wrest);
577 fwrite(&demod->sg_buf[0], 1, wrest, sgfp);
591 fprintf(stderr, "To many pulses detected, probably bad input data or input parameters\n");
596 static void rtlsdr_callback(unsigned char *iq_buf, uint32_t len, void *ctx) {
597 struct dm_state *demod = ctx;
599 char time_str[LOCAL_TIME_BUFLEN];
601 if (do_exit || do_exit_async)
604 if ((bytes_to_read > 0) && (bytes_to_read < len)) {
607 rtlsdr_cancel_async(dev);
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);
614 demod->sg_index += len;
615 if (demod->sg_index + len > SIGNAL_GRABBER_BUFFER)
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);
624 if (demod->enable_FM_demod) {
625 baseband_demod_FM(iq_buf, demod->fm_buf, len/2, &demod->demod_FM_state);
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");
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);
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]);
652 case OOK_PULSE_PPM_RAW:
653 p_events += pulse_demod_ppm(&demod->pulse_data, demod->r_devs[i]);
655 case OOK_PULSE_PWM_PRECISE:
656 p_events += pulse_demod_pwm_precise(&demod->pulse_data, demod->r_devs[i]);
658 case OOK_PULSE_PWM_RAW:
659 p_events += pulse_demod_pwm(&demod->pulse_data, demod->r_devs[i]);
661 case OOK_PULSE_PWM_TERNARY:
662 p_events += pulse_demod_pwm_ternary(&demod->pulse_data, demod->r_devs[i]);
664 case OOK_PULSE_MANCHESTER_ZEROBIT:
665 p_events += pulse_demod_manchester_zerobit(&demod->pulse_data, demod->r_devs[i]);
667 case OOK_PULSE_CLOCK_BITS:
668 p_events += pulse_demod_clock_bits(&demod->pulse_data, demod->r_devs[i]);
670 case OOK_PULSE_PWM_OSV1:
671 p_events += pulse_demod_osv1(&demod->pulse_data, demod->r_devs[i]);
675 case FSK_PULSE_PWM_RAW:
677 case FSK_PULSE_MANCHESTER_ZEROBIT:
678 p_events += pulse_demod_manchester_zerobit(&demod->pulse_data, demod->r_devs[i]);
681 fprintf(stderr, "Unknown modulation %d in protocol!\n", demod->r_devs[i]->modulation);
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);
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) {
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:
703 p_events += pulse_demod_pcm(&demod->fsk_pulse_data, demod->r_devs[i]);
705 case FSK_PULSE_PWM_RAW:
706 p_events += pulse_demod_pwm(&demod->fsk_pulse_data, demod->r_devs[i]);
708 case FSK_PULSE_MANCHESTER_ZEROBIT:
709 p_events += pulse_demod_manchester_zerobit(&demod->fsk_pulse_data, demod->r_devs[i]);
712 fprintf(stderr, "Unknown modulation %d in protocol!\n", demod->r_devs[i]->modulation);
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);
719 } // if (package_type == ...
720 } // while(package_type)...
721 } // if (demod->analyze...
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;
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);
736 if (bytes_to_read > 0)
737 bytes_to_read -= len;
741 if (frequencies > 1) {
742 if (difftime(rawtime, rawtime_old) > DEFAULT_HOP_TIME || events >= DEFAULT_HOP_EVENTS) {
743 rawtime_old = rawtime;
746 rtlsdr_cancel_async(dev);
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);
756 // find the fields output for CSV
757 void *determine_csv_fields(r_device* devices, int num_devices)
760 int cur_output_fields = 0;
761 int num_output_fields = 0;
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)
770 fprintf(stderr, "rtl_433: warning: %d \"%s\" does not support CSV output\n",
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];
783 csv_aux = data_csv_init(output_fields, num_output_fields);
788 void add_json_output()
790 output_handler_t *output = calloc(1, sizeof(output_handler_t));
792 fprintf(stderr, "rtl_433: failed to allocate memory for output handler\n");
795 output->printer = &data_json_printer;
796 output->file = stdout;
797 *next_output_handler = output;
798 next_output_handler = &output->next;
801 void add_csv_output(void *aux_data)
804 fprintf(stderr, "rtl_433: failed to allocate memory for CSV auxiliary data\n");
807 output_handler_t *output = calloc(1, sizeof(output_handler_t));
809 fprintf(stderr, "rtl_433: failed to allocate memory for output handler\n");
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;
822 output_handler_t *output = calloc(1, sizeof(output_handler_t));
824 fprintf(stderr, "rtl_433: failed to allocate memory for output handler\n");
827 output->printer = &data_kv_printer;
828 output->file = stdout;
829 *next_output_handler = output;
830 next_output_handler = &output->next;
833 int main(int argc, char **argv) {
835 struct sigaction sigact;
837 char *out_filename = NULL;
838 char *in_filename = NULL;
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;
850 char vendor[256], product[256], serial[256];
852 int register_all = 0;
854 setbuf(stdout, NULL);
855 setbuf(stderr, NULL);
857 demod = malloc(sizeof (struct dm_state));
858 memset(demod, 0, sizeof (struct dm_state));
860 /* initialize tables */
863 r_device devices[] = {
864 #define DECL(name) name,
869 num_r_devices = sizeof(devices)/sizeof(*devices);
871 demod->level_limit = DEFAULT_LEVEL_LIMIT;
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) {
876 dev_index = atoi(optarg);
879 if (frequencies < MAX_PROTOCOLS) frequency[frequencies++] = (uint32_t) atof(optarg);
880 else fprintf(stderr, "Max number of frequencies reached %d\n", MAX_PROTOCOLS);
883 gain = (int) (atof(optarg) * 10); /* tenths of a dB */
889 ppm_error = atoi(optarg);
892 samp_rate = (uint32_t) atof(optarg);
895 out_block_size = (uint32_t) atof(optarg);
898 demod->level_limit = (uint32_t) atof(optarg);
901 bytes_to_read = (uint32_t) atof(optarg) * 2;
907 demod->analyze_pulses = 1;
910 include_only = atoi(optarg);
913 in_filename = optarg;
916 demod->signal_grabber = 1;
919 demod->debug_mode = atoi(optarg);
928 override_short = atoi(optarg);
931 override_long = atoi(optarg);
935 for (i = 0; i < num_r_devices; i++) {
936 devices[i].disabled = 1;
942 if (i > num_r_devices) {
943 fprintf(stderr, "Remote device number specified larger than number of devices\n\n");
947 devices[i - 1].disabled = 0;
953 if (strcmp(optarg, "json") == 0) {
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) {
960 fprintf(stderr, "Invalid output format %s\n", optarg);
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;
972 fprintf(stderr, "Invalid conversion mode %s\n", optarg);
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);
987 duration = atoi(optarg);
989 fprintf(stderr, "Duration '%s' was not positive integer; will continue indefinitely\n", optarg);
991 stop_time += duration;
1000 if (argc <= optind - 1) {
1003 out_filename = argv[optind];
1006 if (!output_handler) {
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;
1020 fprintf(stderr,"Registered %d out of %d device decoding protocols\n",
1021 demod->r_dev_num, num_r_devices);
1023 if (out_block_size < MINIMAL_BUF_LENGTH ||
1024 out_block_size > MAXIMAL_BUF_LENGTH) {
1026 "Output block size wrong value, falling back to default\n");
1028 "Minimal length: %u\n", MINIMAL_BUF_LENGTH);
1030 "Maximal length: %u\n", MAXIMAL_BUF_LENGTH);
1031 out_block_size = DEFAULT_BUF_LENGTH;
1035 device_count = rtlsdr_get_device_count();
1036 if (!device_count) {
1037 fprintf(stderr, "No supported devices found.\n");
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);
1048 fprintf(stderr, "\n");
1050 fprintf(stderr, "Using device %d: %s\n",
1051 dev_index, rtlsdr_get_device_name(dev_index));
1054 r = rtlsdr_open(&dev, dev_index);
1056 fprintf(stderr, "Failed to open rtlsdr device #%d.\n", dev_index);
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);
1068 SetConsoleCtrlHandler((PHANDLER_ROUTINE) sighandler, TRUE);
1070 /* Set the sample rate */
1071 r = rtlsdr_set_sample_rate(dev, samp_rate);
1073 fprintf(stderr, "WARNING: Failed to set sample rate.\n");
1075 fprintf(stderr, "Sample rate set to %d.\n", rtlsdr_get_sample_rate(dev)); // Unfortunately, doesn't return real rate
1077 fprintf(stderr, "Bit detection level set to %d%s.\n", demod->level_limit, (demod->level_limit ? "" : " (Auto)"));
1080 /* Enable automatic gain */
1081 r = rtlsdr_set_tuner_gain_mode(dev, 0);
1083 fprintf(stderr, "WARNING: Failed to enable automatic gain.\n");
1085 fprintf(stderr, "Tuner gain set to Auto.\n");
1087 /* Enable manual gain */
1088 r = rtlsdr_set_tuner_gain_mode(dev, 1);
1090 fprintf(stderr, "WARNING: Failed to enable manual gain.\n");
1092 /* Set the tuner gain */
1093 r = rtlsdr_set_tuner_gain(dev, gain);
1095 fprintf(stderr, "WARNING: Failed to set tuner gain.\n");
1097 fprintf(stderr, "Tuner gain set to %f dB.\n", gain / 10.0);
1100 r = rtlsdr_set_freq_correction(dev, ppm_error);
1105 if (strcmp(out_filename, "-") == 0) { /* Write samples to stdout */
1106 demod->out_file = stdout;
1108 _setmode(_fileno(stdin), _O_BINARY);
1111 if (access(out_filename, F_OK) == 0 && !overwrite_mode) {
1112 fprintf(stderr, "Output file %s already exists, exiting\n", out_filename);
1115 demod->out_file = fopen(out_filename, "wb");
1116 if (!demod->out_file) {
1117 fprintf(stderr, "Failed to open %s\n", out_filename);
1123 if (demod->signal_grabber)
1124 demod->sg_buf = malloc(SIGNAL_GRABBER_BUFFER);
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 */
1132 in_filename = "<stdin>";
1134 in_file = fopen(in_filename, "rb");
1136 fprintf(stderr, "Opening file: %s failed!\n", in_filename);
1140 fprintf(stderr, "Test mode active. Reading samples from file: %s\n", in_filename); // Essential information (not quiet)
1142 fprintf(stderr, "Input format: %s\n", (demod->debug_mode == 3) ? "cf32" : "uint8");
1144 sample_file_pos = 0.0;
1146 int n_read, cf32_tmp;
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;
1154 else if (cf32_tmp > 255)
1156 test_mode_buf[n] = (uint8_t)cf32_tmp;
1159 n_read = fread(test_mode_buf, 1, 131072, in_file);
1161 if (n_read == 0) break; // rtlsdr_callback() will Segmentation Fault with len=0
1162 rtlsdr_callback(test_mode_buf, n_read, demod);
1164 sample_file_pos = (float)i * n_read / samp_rate;
1165 } while (n_read != 0);
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?
1171 //Always classify a signal at the end of the file
1174 fprintf(stderr, "Test mode file issued %d packets\n", i);
1179 /* Reset endpoint before we start reading from it (mandatory) */
1180 r = rtlsdr_reset_buffer(dev);
1182 fprintf(stderr, "WARNING: Failed to reset buffers.\n");
1185 if (!demod->out_file) {
1186 fprintf(stderr, "Specify an output file for sync mode.\n");
1190 fprintf(stderr, "Reading samples in sync mode...\n");
1191 uint8_t *buffer = malloc(out_block_size * sizeof (uint8_t));
1195 r = rtlsdr_read_sync(dev, buffer, out_block_size, &n_read);
1197 fprintf(stderr, "WARNING: sync read failed.\n");
1201 if ((bytes_to_read > 0) && (bytes_to_read < (uint32_t) n_read)) {
1202 n_read = bytes_to_read;
1206 if (fwrite(buffer, 1, n_read, demod->out_file) != (size_t) n_read) {
1207 fprintf(stderr, "Short write, samples lost, exiting!\n");
1211 if ((uint32_t) n_read < out_block_size) {
1212 fprintf(stderr, "Short read, samples lost, exiting!\n");
1218 if (timestamp >= stop_time) {
1220 fprintf(stderr, "Time expired, exiting!\n");
1224 if (bytes_to_read > 0)
1225 bytes_to_read -= n_read;
1230 if (frequencies == 0) {
1231 frequency[0] = DEFAULT_FREQUENCY;
1237 fprintf(stderr, "Reading samples in async mode...\n");
1240 /* Set the frequency */
1241 r = rtlsdr_set_center_freq(dev, frequency[frequency_current]);
1243 fprintf(stderr, "WARNING: Failed to set center freq.\n");
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);
1249 frequency_current++;
1250 if (frequency_current > frequencies - 1) frequency_current = 0;
1255 fprintf(stderr, "\nUser cancel, exiting...\n");
1257 fprintf(stderr, "\nLibrary error %d, exiting...\n", r);
1259 if (demod->out_file && (demod->out_file != stdout))
1260 fclose(demod->out_file);
1262 for (i = 0; i < demod->r_dev_num; i++)
1263 free(demod->r_devs[i]);
1265 if (demod->signal_grabber)
1266 free(demod->sg_buf);
1272 for (output_handler_t *output = output_handler; output; output = output->next) {
1273 if (output->aux_free) {
1274 output->aux_free(output->aux);
1277 return r >= 0 ? r : -r;