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/>.
24 /* Currently this can decode the temperature and id from Rubicson sensors
26 * the sensor sends 36 bits 12 times pwm modulated
27 * the data is grouped into 9 nibles
28 * [id0] [id1], [unk0] [temp0], [temp1] [temp2], [unk1] [unk2], [unk3]
30 * The id changes when the battery is changed in the sensor.
31 * unk0 is always 1 0 0 0, most likely 2 channel bits as the sensor can recevice 3 channels
32 * unk1-3 changes and the meaning is unknown
33 * temp is 12 bit signed scaled by 10
35 * The sensor can be bought at Kjell&Co
38 /* Prologue sensor protocol
40 * the sensor sends 36 bits 7 times, before the first packet there is a pulse sent
41 * the packets are pwm modulated
43 * the data is grouped in 9 nibles
44 * [id0] [rid0] [rid1] [data0] [temp0] [temp1] [temp2] [humi0] [humi1]
46 * id0 is always 1001,9
47 * rid is a random id that is generated when the sensor starts, could include battery status
48 * the same batteries often generate the same id
49 * data(3) is 0 the battery status, 1 ok, 0 low, first reading always say low
50 * data(2) is 1 when the sensor sends a reading when pressing the button on the sensor
51 * data(1,0)+1 forms the channel number that can be set by the sensor (1-3)
52 * temp is 12 bit signed scaled by 10
53 * humi0 is always 1100,c if no humidity sensor is available
54 * humi1 is always 1100,c if no humidity sensor is available
56 * The sensor can be bought at Clas Ohlson
72 #include "getopt/getopt.h"
77 #define DEFAULT_SAMPLE_RATE 250000
78 #define DEFAULT_FREQUENCY 433920000
79 #define DEFAULT_HOP_TIME (60*10)
80 #define DEFAULT_HOP_EVENTS 2
81 #define DEFAULT_ASYNC_BUF_NUMBER 32
82 #define DEFAULT_BUF_LENGTH (16 * 16384)
83 #define DEFAULT_LEVEL_LIMIT 10000
84 #define DEFAULT_DECIMATION_LEVEL 0
85 #define MINIMAL_BUF_LENGTH 512
86 #define MAXIMAL_BUF_LENGTH (256 * 16384)
87 #define FILTER_ORDER 1
88 #define MAX_PROTOCOLS 10
89 #define SIGNAL_GRABBER_BUFFER (12 * DEFAULT_BUF_LENGTH)
90 #define BITBUF_COLS 34
91 #define BITBUF_ROWS 50
93 static int do_exit = 0;
94 static int do_exit_async=0, frequencies=0, events=0;
95 uint32_t frequency[MAX_PROTOCOLS];
98 uint32_t samp_rate=DEFAULT_SAMPLE_RATE;
99 static uint32_t bytes_to_read = 0;
100 static rtlsdr_dev_t *dev = NULL;
101 static uint16_t scaled_squares[256];
102 static int debug_output = 0;
103 static int override_short = 0;
104 static int override_long = 0;
106 /* Supported modulation types */
107 #define OOK_PWM_D 1 /* Pulses are of the same length, the distance varies */
108 #define OOK_PWM_P 2 /* The length of the pulses varies */
114 unsigned int modulation;
115 unsigned int short_limit;
116 unsigned int long_limit;
117 unsigned int reset_limit;
118 int (*json_callback)(uint8_t bits_buffer[BITBUF_ROWS][BITBUF_COLS]) ;
121 static int debug_callback(uint8_t bb[BITBUF_ROWS][BITBUF_COLS]) {
123 fprintf(stderr, "\n");
124 for (i=0 ; i<BITBUF_ROWS ; i++) {
125 fprintf(stderr, "[%02d] ",i);
126 for (j=0 ; j<BITBUF_COLS ; j++) {
127 fprintf(stderr, "%02x ", bb[i][j]);
129 fprintf(stderr, ": ");
130 for (j=0 ; j<BITBUF_COLS ; j++) {
131 for (k=7 ; k>=0 ; k--) {
133 fprintf(stderr, "1");
135 fprintf(stderr, "0");
137 fprintf(stderr, " ");
139 fprintf(stderr, "\n");
141 fprintf(stderr, "\n");
146 uint8_t crc8( uint8_t *addr, uint8_t len)
150 // Indicated changes are from reference CRC-8 function in OneWire library
152 uint8_t inbyte = *addr++;
154 for (i = 8; i; i--) {
155 uint8_t mix = (crc ^ inbyte) & 0x80; // changed from & 0x01
156 crc <<= 1; // changed from right shift
157 if (mix) crc ^= 0x31;// changed from 0x8C;
158 inbyte <<= 1; // changed from right shift
164 static int wh2_callback(uint8_t bb[BITBUF_ROWS][BITBUF_COLS]) {
168 uint8_t received_crc8,payload_crc8;
174 if (bb[0][0] != 0xFE) return 0;
176 payload[0] = bb[0][1]>>1;
177 payload[1] = bb[0][2]>>1 | ((bb[0][1]&1) << 7 );
178 payload[2] = bb[0][3]>>1 | ((bb[0][2]&1) << 7 );
179 payload[3] = bb[0][4]>>1 | ((bb[0][3]&1) << 7 );
181 received_crc8 = (bb[0][5]>>1) | ((bb[0][4]&1) << 7 );
183 payload_crc8 = crc8(payload,4);
185 if (payload_crc8 != received_crc8) return 0;
187 wh2_id = (payload[0] << 4) + (payload[1] >> 4);
188 wh2_temp = ((payload[1] & 0x7) << 8) + payload[2];
189 if (payload[1] & 0x8) {
190 wh2_temp = -wh2_temp;
192 wh2_temp = wh2_temp/10;
194 wh2_humidity = payload[3];
196 fprintf(stdout, "SENSOR:TYPE=WH2,ID=%x,HUMIDITY=%g,TEMPERATURE=%g\n",wh2_id,wh2_humidity,wh2_temp);
201 static int silvercrest_callback(uint8_t bb[BITBUF_ROWS][BITBUF_COLS]) {
202 /* FIXME validate the received message better */
203 if (bb[1][0] == 0xF8 &&
211 /* Pretty sure this is a Silvercrest remote */
212 fprintf(stdout, "BUTTON:TYPE=SILVERCREST,CODE=%02x-%02x-%02x-%02x-%02x\n",bb[1][0],bb[0][1],bb[0][2],bb[0][3],bb[0][4]);
222 static int rubicson_callback(uint8_t bb[BITBUF_ROWS][BITBUF_COLS]) {
223 int temperature_before_dec;
224 int temperature_after_dec;
228 /* FIXME validate the received message better, figure out crc */
229 if (bb[1][0] == bb[2][0] && bb[2][0] == bb[3][0] && bb[3][0] == bb[4][0] &&
230 bb[4][0] == bb[5][0] && bb[5][0] == bb[6][0] && bb[6][0] == bb[7][0] && bb[7][0] == bb[8][0] &&
231 bb[8][0] == bb[9][0] && (bb[5][0] != 0 && bb[5][1] != 0 && bb[5][2] != 0)) {
233 /* Nible 3,4,5 contains 12 bits of temperature
234 * The temperature is signed and scaled by 10 */
235 temp = (int16_t)((uint16_t)(bb[0][1] << 12) | (bb[0][2] << 4));
237 ftemp = (float)temp/10;
239 fprintf(stdout, "SENSOR:TYPE=RUBICSON,ID=%x,TEMPERATURE=%f\n",bb[0][0],ftemp);
249 static int prologue_callback(uint8_t bb[BITBUF_ROWS][BITBUF_COLS]) {
255 /* FIXME validate the received message better */
256 if (((bb[1][0]&0xF0) == 0x90 && (bb[2][0]&0xF0) == 0x90 && (bb[3][0]&0xF0) == 0x90 && (bb[4][0]&0xF0) == 0x90 &&
257 (bb[5][0]&0xF0) == 0x90 && (bb[6][0]&0xF0) == 0x90) ||
258 ((bb[1][0]&0xF0) == 0x50 && (bb[2][0]&0xF0) == 0x50 && (bb[3][0]&0xF0) == 0x50 && (bb[4][0]&0xF0) == 0x50)) {
260 /* Prologue sensor */
261 temp2 = (int16_t)((uint16_t)(bb[1][2] << 8) | (bb[1][3]&0xF0));
263 ftemp = (float)temp2/10;
264 rid = ((bb[1][0]&0x0F)<<4)|(bb[1][1]&0xF0)>>4;
266 "SENSOR:TYPE=PROLOGUE,BUTTON=%d,BATTERY=%s,TEMPERATURE=%f,HUMIDITY=%d,CHANNEL=%d,ID=%d,RID=%02x\n",
268 bb[1][1]&0x08?"Ok":"Low",
270 ((bb[1][3]&0x0F)<<4)|(bb[1][4]>>4),
271 (int)((bb[1][1]&0x03)+1),
272 (int)((bb[1][0]&0xF0)>>4),
283 static int waveman_callback(uint8_t bb[BITBUF_ROWS][BITBUF_COLS]) {
284 /* Two bits map to 2 states, 0 1 -> 0 and 1 1 -> 1 */
288 if (((bb[0][0]&0x55)==0x55) && ((bb[0][1]&0x55)==0x55) && ((bb[0][2]&0x55)==0x55) && ((bb[0][3]&0x55)==0x00)) {
289 for (i=0 ; i<3 ; i++) {
290 nb[i] |= ((bb[0][i]&0xC0)==0xC0) ? 0x00 : 0x01;
291 nb[i] |= ((bb[0][i]&0x30)==0x30) ? 0x00 : 0x02;
292 nb[i] |= ((bb[0][i]&0x0C)==0x0C) ? 0x00 : 0x04;
293 nb[i] |= ((bb[0][i]&0x03)==0x03) ? 0x00 : 0x08;
297 "BUTTON:TYPE=WAVEMAN,ID=%c,CHANNEL=%d,BUTTON=%d,STATE=%s\n",
301 ((nb[2]==0xe) ? "on" : "off"));
311 static int steffen_callback(uint8_t bb[BITBUF_ROWS][BITBUF_COLS]) {
313 if (bb[0][0]==0x00 && ((bb[1][0]&0x07)==0x07) && bb[1][0]==bb[2][0] && bb[2][0]==bb[3][0]) {
315 fprintf(stdout, "BUTTON:TYPE=STEFFAN,CODE=%d%d%d%d%d,",(bb[1][0]&0x80)>>7, (bb[1][0]&0x40)>>6, (bb[1][0]&0x20)>>5, (bb[1][0]&0x10)>>4, (bb[1][0]&0x08)>>3);
317 if ((bb[1][2]&0x0f)==0x0e)
318 fprintf(stdout, "BUTTON=A,");
319 else if ((bb[1][2]&0x0f)==0x0d)
320 fprintf(stdout, "BUTTON=B,");
321 else if ((bb[1][2]&0x0f)==0x0b)
322 fprintf(stdout, "BUTTON=C,");
323 else if ((bb[1][2]&0x0f)==0x07)
324 fprintf(stdout, "BUTTON=D,");
325 else if ((bb[1][2]&0x0f)==0x0f)
326 fprintf(stdout, "BUTTON=ALL,");
328 fprintf(stdout, "BUTTON=UNKNOWN,");
330 if ((bb[1][2]&0xf0)==0xf0) {
331 fprintf(stdout, "STATE=OFF\n");
333 fprintf(stdout, "STATE=ON\n");
345 uint16_t AD_POP(uint8_t bb[BITBUF_COLS], uint8_t bits, uint8_t bit) {
347 uint8_t i, byte_no, bit_no;
348 for (i=0;i<bits;i++) {
350 bit_no =7-((bit+i)%8);
351 if (bb[byte_no]&(1<<bit_no)) val = val | (1<<i);
356 static int em1000_callback(uint8_t bb[BITBUF_ROWS][BITBUF_COLS]) {
360 uint8_t bit=18; // preamble
362 char* types[] = {"S", "?", "GZ"};
363 uint8_t checksum_calculated = 0;
366 uint8_t checksum_received;
368 // check and combine the 3 repetitions
369 for (i = 0; i < 14; i++) {
370 if(bb[0][i]==bb[1][i] || bb[0][i]==bb[2][i]) bb_p[i]=bb[0][i];
371 else if(bb[1][i]==bb[2][i]) bb_p[i]=bb[1][i];
375 // read 9 bytes with stopbit ...
376 for (i = 0; i < 9; i++) {
377 dec[i] = AD_POP (bb_p, 8, bit); bit+=8;
378 stopbit=AD_POP (bb_p, 1, bit); bit+=1;
380 // fprintf(stderr, "!stopbit: %i\n", i);
383 checksum_calculated ^= dec[i];
388 checksum_received = AD_POP (bb_p, 8, bit); bit+=8;
389 if (checksum_received != checksum_calculated) {
390 // fprintf(stderr, "checksum_received != checksum_calculated: %d %d\n", checksum_received, checksum_calculated);
394 //for (i = 0; i < bytes; i++) fprintf(stderr, "%02X ", dec[i]); fprintf(stderr, "\n");
396 // based on 15_CUL_EM.pm
397 fprintf(stdout, "SENSOR:TYPE=ELV-EM-1000,MODEL=%s,CODE=%d,SEQNO=%d,TOTAL=%d,CURRENT=%d,PEAK=%d\n",dec[0]>=1&&dec[0]<=3?types[dec[0]-1]:"?",dec[1],dec[2],dec[3]|dec[4]<<8,dec[5]|dec[6]<<8,dec[7]|dec[8]<<8);
402 static int ws2000_callback(uint8_t bb[BITBUF_ROWS][BITBUF_COLS]) {
403 // based on http://www.dc3yc.privat.t-online.de/protocol.htm
406 uint8_t bit=11; // preamble
407 char* types[]={"!AS3", "AS2000/ASH2000/S2000/S2001A/S2001IA/ASH2200/S300IA", "!S2000R", "!S2000W", "S2001I/S2001ID", "!S2500H", "!Pyrano", "!KS200/KS300"};
408 uint8_t check_calculated=0, sum_calculated=0;
411 uint8_t sum_received;
413 dec[0] = AD_POP (bb[0], 4, bit); bit+=4;
414 stopbit= AD_POP (bb[0], 1, bit); bit+=1;
416 //fprintf(stderr, "!stopbit\n");
419 check_calculated ^= dec[0];
420 sum_calculated += dec[0];
422 // read nibbles with stopbit ...
423 for (i = 1; i <= (dec[0]==4?12:8); i++) {
424 dec[i] = AD_POP (bb[0], 4, bit); bit+=4;
425 stopbit= AD_POP (bb[0], 1, bit); bit+=1;
427 //fprintf(stderr, "!stopbit %i\n", i);
430 check_calculated ^= dec[i];
431 sum_calculated += dec[i];
435 if (check_calculated) {
436 //fprintf(stderr, "check_calculated (%d) != 0\n", check_calculated);
441 sum_received = AD_POP (bb[0], 4, bit); bit+=4;
444 if (sum_received != sum_calculated) {
445 //fprintf(stderr, "sum_received (%d) != sum_calculated (%d) ", sum_received, sum_calculated);
449 //for (i = 0; i < nibbles; i++) fprintf(stderr, "%02X ", dec[i]); fprintf(stderr, "\n");
451 fprintf(stdout, "SENSOR:TYPE=ELV-WS-2000,MODEL=%s,CODE=%d,TEMPERATURE=%s%d.%d,HUMIDITY=%d.%d",dec[0]<=7?types[dec[0]]:"?",dec[1]&7,dec[1]&8?"-":"",dec[4]*10+dec[3],dec[2],dec[7]*10+dec[6], dec[5]);
453 fprintf(stdout, "PRESSURE=%d\n", 200+dec[10]*100+dec[9]*10+dec[8]);
455 fprintf(stdout, "\n");
461 // ** Acurite 5n1 functions **
463 const float acurite_winddirections[] =
464 { 337.5, 315.0, 292.5, 270.0, 247.5, 225.0, 202.5, 180,
465 157.5, 135.0, 112.5, 90.0, 67.5, 45.0, 22.5, 0.0 };
467 static int acurite_raincounter = 0;
469 static int acurite_crc(uint8_t row[BITBUF_COLS], int cols) {
470 // sum of first n-1 bytes modulo 256 should equal nth byte
473 for ( i=0; i < cols; i++)
475 if ( sum % 256 == row[cols] )
481 static int acurite_detect(uint8_t *pRow) {
483 if ( pRow[0] != 0x00 ) {
484 // invert bits due to wierd issue
485 for (i = 0; i < 8; i++)
486 pRow[i] = ~pRow[i] & 0xFF;
487 pRow[0] |= pRow[8]; // fix first byte that has mashed leading bit
489 if (acurite_crc(pRow, 7))
490 return 1; // passes crc check
495 static float acurite_getTemp (uint8_t highbyte, uint8_t lowbyte) {
496 // range -40 to 158 F
497 int highbits = (highbyte & 0x0F) << 7 ;
498 int lowbits = lowbyte & 0x7F;
499 int rawtemp = highbits | lowbits;
500 float temp = (rawtemp - 400) / 10.0;
504 static int acurite_getWindSpeed (uint8_t highbyte, uint8_t lowbyte) {
505 // range: 0 to 159 kph
506 int highbits = ( highbyte & 0x1F) << 3;
507 int lowbits = ( lowbyte & 0x70 ) >> 4;
508 int speed = highbits | lowbits;
512 static float acurite_getWindDirection (uint8_t byte) {
513 // 16 compass points, ccw from (NNW) to 15 (N)
514 int direction = byte & 0x0F;
515 return acurite_winddirections[direction];
518 static int acurite_getHumidity (uint8_t byte) {
519 // range: 1 to 99 %RH
520 int humidity = byte & 0x7F;
524 static int acurite_getRainfallCounter (uint8_t highbyte, uint8_t lowbyte) {
525 // range: 0 to 99.99 in, 0.01 in incr., rolling counter?
526 int highbits = (highbyte & 0x3F) << 7 ;
527 int lowbits = lowbyte & 0x7F;
528 int raincounter = highbits | lowbits;
532 static int acurite5n1_callback(uint8_t bb[BITBUF_ROWS][BITBUF_COLS]) {
533 // acurite 5n1 weather sensor decoding for rtl_433
537 // run through rows til we find one with good crc (brute force)
538 for (i=0; i < BITBUF_ROWS; i++) {
539 if (acurite_detect(bb[i])) {
546 // decode packet here
547 fprintf(stdout, "SENSOR:TYPE=ACURITE");
549 for (i=0; i < 8; i++)
550 fprintf(stderr, "%02X ", buf[i]);
551 fprintf(stderr, "CRC OK\n");
554 if ((buf[2] & 0x0F) == 1) {
555 // wind speed, wind direction, rainfall
557 float rainfall = 0.00;
559 if (acurite_raincounter > 0) {
560 // track rainfall difference after first run
561 raincounter = acurite_getRainfallCounter(buf[5], buf[6]);
562 rainfall = ( raincounter - acurite_raincounter ) * 0.01;
564 // capture starting counter
565 acurite_raincounter = raincounter;
568 fprintf(stdout, ",WINDSPEED=%d",
569 acurite_getWindSpeed(buf[3], buf[4]));
570 fprintf(stdout, ",WINDDIRECTION=%0.1f",
571 acurite_getWindDirection(buf[4]));
572 fprintf(stdout, ",RAINGAUGE: %0.2f\n", rainfall);
574 } else if ((buf[2] & 0x0F) == 8) {
575 // wind speed, temp, RH
576 fprintf(stdout, ",WINDSPEED=%d",
577 acurite_getWindSpeed(buf[3], buf[4]));
578 fprintf(stdout, ",TEMPERATURE=%2.1f",
579 acurite_getTemp(buf[4], buf[5]));
580 fprintf(stdout, ",HUMIDITY=%d\n",
581 acurite_getHumidity(buf[6]));
585 // debug_callback(bb);
590 // timings based on samp_rate=1024000
591 r_device rubicson = {
593 /* .name = */ "Rubicson Temperature Sensor",
594 /* .modulation = */ OOK_PWM_D,
595 /* .short_limit = */ 1744/4,
596 /* .long_limit = */ 3500/4,
597 /* .reset_limit = */ 5000/4,
598 /* .json_callback = */ &rubicson_callback,
601 r_device prologue = {
603 /* .name = */ "Prologue Temperature Sensor",
604 /* .modulation = */ OOK_PWM_D,
605 /* .short_limit = */ 3500/4,
606 /* .long_limit = */ 7000/4,
607 /* .reset_limit = */ 15000/4,
608 /* .json_callback = */ &prologue_callback,
611 r_device silvercrest = {
613 /* .name = */ "Silvercrest Remote Control",
614 /* .modulation = */ OOK_PWM_P,
615 /* .short_limit = */ 600/4,
616 /* .long_limit = */ 5000/4,
617 /* .reset_limit = */ 15000/4,
618 /* .json_callback = */ &silvercrest_callback,
621 r_device tech_line_fws_500 = {
623 /* .name = */ "Tech Line FWS-500 Sensor",
624 /* .modulation = */ OOK_PWM_D,
625 /* .short_limit = */ 3500/4,
626 /* .long_limit = */ 7000/4,
627 /* .reset_limit = */ 15000/4,
628 // /* .json_callback = */ &rubicson_callback,
631 r_device generic_hx2262 = {
633 /* .name = */ "Window/Door sensor",
634 /* .modulation = */ OOK_PWM_P,
635 /* .short_limit = */ 1300/4,
636 /* .long_limit = */ 10000/4,
637 /* .reset_limit = */ 40000/4,
638 // /* .json_callback = */ &silvercrest_callback,
641 r_device technoline_ws9118 = {
643 /* .name = */ "Technoline WS9118",
644 /* .modulation = */ OOK_PWM_D,
645 /* .short_limit = */ 1800/4,
646 /* .long_limit = */ 3500/4,
647 /* .reset_limit = */ 15000/4,
648 /* .json_callback = */ &debug_callback,
652 r_device elv_em1000 = {
654 /* .name = */ "ELV EM 1000",
655 /* .modulation = */ OOK_PWM_D,
656 /* .short_limit = */ 750/4,
657 /* .long_limit = */ 7250/4,
658 /* .reset_limit = */ 30000/4,
659 /* .json_callback = */ &em1000_callback,
662 r_device elv_ws2000 = {
664 /* .name = */ "ELV WS 2000",
665 /* .modulation = */ OOK_PWM_D,
666 /* .short_limit = */ (602+(1155-602)/2)/4,
667 /* .long_limit = */ ((1755635-1655517)/2)/4, // no repetitions
668 /* .reset_limit = */ ((1755635-1655517)*2)/4,
669 /* .json_callback = */ &ws2000_callback,
674 /* .name = */ "Waveman Switch Transmitter",
675 /* .modulation = */ OOK_PWM_P,
676 /* .short_limit = */ 1000/4,
677 /* .long_limit = */ 8000/4,
678 /* .reset_limit = */ 30000/4,
679 /* .json_callback = */ &waveman_callback,
684 /* .name = */ "Steffen Switch Transmitter",
685 /* .modulation = */ OOK_PWM_D,
686 /* .short_limit = */ 140,
687 /* .long_limit = */ 270,
688 /* .reset_limit = */ 1500,
689 /* .json_callback = */ &steffen_callback,
692 r_device acurite5n1 = {
694 /* .name = */ "Acurite 5n1 Weather Station",
695 /* .modulation = */ OOK_PWM_P,
696 /* .short_limit = */ 75,
697 /* .long_limit = */ 220,
698 /* .reset_limit = */ 20000,
699 /* .json_callback = */ &acurite5n1_callback,
704 /* .name = */ "WH2 Weather Station",
705 /* .modulation = */ OOK_PWM_P,
706 /* .short_limit = */ 150,
707 /* .long_limit = */ 400,
708 /* .reset_limit = */ 20000,
709 /* .json_callback = */ &wh2_callback,
712 struct protocol_state {
713 int (*callback)(uint8_t bits_buffer[BITBUF_ROWS][BITBUF_COLS]);
718 int bits_bit_col_idx;
719 uint8_t bits_buffer[BITBUF_ROWS][BITBUF_COLS];
720 int16_t bits_per_row[BITBUF_ROWS];
722 unsigned int modulation;
748 int32_t decimation_level;
749 int16_t filter_buffer[MAXIMAL_BUF_LENGTH+FILTER_ORDER];
754 /* Signal grabber variables */
761 /* Protocol states */
763 struct protocol_state *r_devs[MAX_PROTOCOLS];
770 "rtl_433, an ISM band generic data receiver for RTL2832 based DVB-T receivers\n\n"
771 "Usage:\t[-d device_index (default: 0)]\n"
772 "\t[-g gain (default: 0 for auto)]\n"
773 "\t[-a analyze mode, print a textual description of the signal]\n"
774 "\t[-t signal auto save, use it together with analyze mode (-a -t)\n"
775 "\t[-l change the detection level used to determine pulses (0-3200) default: %i]\n"
776 "\t[-f [-f...] receive frequency[s], default: %i Hz]\n"
777 "\t[-s samplerate (default: %i Hz)]\n"
778 "\t[-S force sync output (default: async)]\n"
779 "\t[-r read data from file instead of from a receiver]\n"
780 "\t[-p ppm_error (default: 0)]\n"
781 "\t[-r test file name (indata)]\n"
782 "\t[-m test file mode (0 rtl_sdr data, 1 rtl_433 data)]\n"
783 "\t[-D print debug info on event\n"
784 "\t[-z override short value\n"
785 "\t[-x override long value\n"
786 "\tfilename (a '-' dumps samples to stdout)\n\n", DEFAULT_LEVEL_LIMIT, DEFAULT_FREQUENCY, DEFAULT_SAMPLE_RATE);
792 sighandler(int signum)
794 if (CTRL_C_EVENT == signum) {
795 fprintf(stderr, "Signal caught, exiting!\n");
797 rtlsdr_cancel_async(dev);
803 static void sighandler(int signum)
805 fprintf(stderr, "Signal caught, exiting!\n");
807 rtlsdr_cancel_async(dev);
811 /* precalculate lookup table for envelope detection */
812 static void calc_squares() {
814 for (i=0 ; i<256 ; i++)
815 scaled_squares[i] = (128-i) * (128-i);
818 /** This will give a noisy envelope of OOK/ASK signals
819 * Subtract the bias (-128) and get an envelope estimation
820 * The output will be written in the input buffer
821 * @returns pointer to the input buffer
824 static void envelope_detect(unsigned char *buf, uint32_t len, int decimate)
826 uint16_t* sample_buffer = (uint16_t*) buf;
829 unsigned int stride = 1<<decimate;
831 for (i=0 ; i<len/2 ; i+=stride) {
832 sample_buffer[op++] = scaled_squares[buf[2*i ]]+scaled_squares[buf[2*i+1]];
836 static void demod_reset_bits_packet(struct protocol_state* p) {
837 memset(p->bits_buffer, 0 ,BITBUF_ROWS*BITBUF_COLS);
838 memset(p->bits_per_row, 0 ,BITBUF_ROWS);
840 p->bits_bit_col_idx = 7;
845 static void demod_add_bit(struct protocol_state* p, int bit) {
846 p->bits_buffer[p->bits_row_idx][p->bits_col_idx] |= bit<<p->bits_bit_col_idx;
847 p->bits_bit_col_idx--;
848 if (p->bits_bit_col_idx<0) {
849 p->bits_bit_col_idx = 7;
851 if (p->bits_col_idx>BITBUF_COLS-1) {
852 p->bits_col_idx = BITBUF_COLS-1;
853 // fprintf(stderr, "p->bits_col_idx>%i!\n", BITBUF_COLS-1);
856 p->bits_per_row[p->bit_rows]++;
859 static void demod_next_bits_packet(struct protocol_state* p) {
862 p->bits_bit_col_idx = 7;
863 if (p->bits_row_idx>BITBUF_ROWS-1) {
864 p->bits_row_idx = BITBUF_ROWS-1;
865 //fprintf(stderr, "p->bits_row_idx>%i!\n", BITBUF_ROWS-1);
868 if (p->bit_rows > BITBUF_ROWS-1)
872 static void demod_print_bits_packet(struct protocol_state* p) {
875 fprintf(stderr, "\n");
876 for (i=0 ; i<p->bit_rows+1 ; i++) {
877 fprintf(stderr, "[%02d] {%d} ",i, p->bits_per_row[i]);
878 for (j=0 ; j<((p->bits_per_row[i]+8)/8) ; j++) {
879 fprintf(stderr, "%02x ", p->bits_buffer[i][j]);
881 fprintf(stderr, ": ");
882 for (j=0 ; j<((p->bits_per_row[i]+8)/8) ; j++) {
883 for (k=7 ; k>=0 ; k--) {
884 if (p->bits_buffer[i][j] & 1<<k)
885 fprintf(stderr, "1");
887 fprintf(stderr, "0");
889 // fprintf(stderr, "=0x%x ",demod->bits_buffer[i][j]);
890 fprintf(stderr, " ");
892 fprintf(stderr, "\n");
894 fprintf(stderr, "\n");
898 static void register_protocol(struct dm_state *demod, r_device *t_dev) {
899 struct protocol_state *p = calloc(1,sizeof(struct protocol_state));
900 p->short_limit = (float)t_dev->short_limit/((float)DEFAULT_SAMPLE_RATE/(float)samp_rate);
901 p->long_limit = (float)t_dev->long_limit /((float)DEFAULT_SAMPLE_RATE/(float)samp_rate);
902 p->reset_limit = (float)t_dev->reset_limit/((float)DEFAULT_SAMPLE_RATE/(float)samp_rate);
903 p->modulation = t_dev->modulation;
904 p->callback = t_dev->json_callback;
905 demod_reset_bits_packet(p);
907 demod->r_devs[demod->r_dev_num] = p;
910 fprintf(stderr, "Registering protocol[%02d] %s\n",demod->r_dev_num, t_dev->name);
912 if (demod->r_dev_num > MAX_PROTOCOLS)
913 fprintf(stderr, "Max number of protocols reached %d\n",MAX_PROTOCOLS);
917 static unsigned int counter = 0;
918 static unsigned int print = 1;
919 static unsigned int print2 = 0;
920 static unsigned int pulses_found = 0;
921 static unsigned int prev_pulse_start = 0;
922 static unsigned int pulse_start = 0;
923 static unsigned int pulse_end = 0;
924 static unsigned int pulse_avg = 0;
925 static unsigned int signal_start = 0;
926 static unsigned int signal_end = 0;
927 static unsigned int signal_pulse_data[4000][3] = {{0}};
928 static unsigned int signal_pulse_counter = 0;
931 static void classify_signal() {
932 unsigned int i,k, max=0, min=1000000, t;
933 unsigned int delta, count_min, count_max, min_new, max_new, p_limit;
934 unsigned int a[3], b[2], a_cnt[3], a_new[3], b_new[2];
935 unsigned int signal_distance_data[4000] = {0};
936 struct protocol_state p = {0};
937 unsigned int signal_type;
939 if (!signal_pulse_data[0][0])
942 for (i=0 ; i<1000 ; i++) {
943 if (signal_pulse_data[i][0] > 0) {
944 //fprintf(stderr, "[%03d] s: %d\t e:\t %d\t l:%d\n",
945 //i, signal_pulse_data[i][0], signal_pulse_data[i][1],
946 //signal_pulse_data[i][2]);
947 if (signal_pulse_data[i][2] > max)
948 max = signal_pulse_data[i][2];
949 if (signal_pulse_data[i][2] <= min)
950 min = signal_pulse_data[i][2];
954 //fprintf(stderr, "\n\nMax: %d, Min: %d t:%d\n", max, min, t);
956 delta = (max - min)*(max-min);
958 //TODO use Lloyd-Max quantizer instead
960 while((k < 10) && (delta > 0)) {
961 min_new = 0; count_min = 0;
962 max_new = 0; count_max = 0;
964 for (i=0 ; i < 1000 ; i++) {
965 if (signal_pulse_data[i][0] > 0) {
966 if (signal_pulse_data[i][2] < t) {
967 min_new = min_new + signal_pulse_data[i][2];
971 max_new = max_new + signal_pulse_data[i][2];
976 min_new = min_new / count_min;
977 max_new = max_new / count_max;
979 delta = (min - min_new)*(min - min_new) + (max - max_new)*(max - max_new);
984 fprintf(stderr, "Iteration %d. t: %d min: %d (%d) max: %d (%d) delta %d\n", k,t, min, count_min, max, count_max, delta);
988 for (i=0 ; i<1000 ; i++) {
989 if (signal_pulse_data[i][0] > 0) {
990 //fprintf(stderr, "%d\n", signal_pulse_data[i][1]);
993 /* 50% decision limit */
995 fprintf(stderr, "Pulse coding: Short pulse length %d - Long pulse length %d\n", min, max);
998 fprintf(stderr, "Distance coding: Pulse length %d\n", (min+max)/2);
1001 p_limit = (max+min)/2;
1003 /* Initial guesses */
1006 for (i=1 ; i<1000 ; i++) {
1007 if (signal_pulse_data[i][0] > 0) {
1008 // fprintf(stderr, "[%03d] s: %d\t e:\t %d\t l:%d\t d:%d\n",
1009 // i, signal_pulse_data[i][0], signal_pulse_data[i][1],
1010 // signal_pulse_data[i][2], signal_pulse_data[i][0]-signal_pulse_data[i-1][1]);
1011 signal_distance_data[i-1] = signal_pulse_data[i][0]-signal_pulse_data[i-1][1];
1012 if (signal_distance_data[i-1] > a[2])
1013 a[2] = signal_distance_data[i-1];
1014 if (signal_distance_data[i-1] <= a[0])
1015 a[0] = signal_distance_data[i-1];
1020 a[1] = (a[0]+a[2])/2;
1021 // for (i=0 ; i<1 ; i++) {
1022 // b[i] = (a[i]+a[i+1])/2;
1024 b[0] = (a[0]+a[1])/2;
1025 b[1] = (a[1]+a[2])/2;
1026 // fprintf(stderr, "a[0]: %d\t a[1]: %d\t a[2]: %d\t\n",a[0],a[1],a[2]);
1027 // fprintf(stderr, "b[0]: %d\t b[1]: %d\n",b[0],b[1]);
1031 while((k < 10) && (delta > 0)) {
1032 for (i=0 ; i<3 ; i++) {
1037 for (i=0 ; i < 1000 ; i++) {
1038 if (signal_distance_data[i] > 0) {
1039 if (signal_distance_data[i] < b[0]) {
1040 a_new[0] += signal_distance_data[i];
1042 } else if (signal_distance_data[i] < b[1] && signal_distance_data[i] >= b[0]){
1043 a_new[1] += signal_distance_data[i];
1045 } else if (signal_distance_data[i] >= b[1]) {
1046 a_new[2] += signal_distance_data[i];
1052 // fprintf(stderr, "Iteration %d.", k);
1054 for (i=0 ; i<3 ; i++) {
1056 a_new[i] /= a_cnt[i];
1057 delta += (a[i]-a_new[i])*(a[i]-a_new[i]);
1058 // fprintf(stderr, "\ta[%d]: %d (%d)", i, a_new[i], a[i]);
1061 // fprintf(stderr, " delta %d\n", delta);
1065 // fprintf(stderr, "Fixing a[0] = %d\n", min);
1069 // fprintf(stderr, "Fixing a[2] = %d\n", max);
1072 // a[1] = (a[2]+a[0])/2;
1073 // fprintf(stderr, "Fixing a[1] = %d\n", a[1]);
1076 // fprintf(stderr, "Iteration %d.", k);
1077 for (i=0 ; i<2 ; i++) {
1078 // fprintf(stderr, "\tb[%d]: (%d) ", i, b[i]);
1079 b[i] = (a[i]+a[i+1])/2;
1080 // fprintf(stderr, "%d ", b[i]);
1082 // fprintf(stderr, "\n");
1086 if (override_short) {
1087 p_limit = override_short;
1088 a[0] = override_short;
1091 if (override_long) {
1092 a[1] = override_long;
1103 fprintf(stderr, "\nShort distance: %d, long distance: %d, packet distance: %d\n",a[0],a[1],a[2]);
1104 fprintf(stderr, "\np_limit: %d\n",p_limit);
1106 demod_reset_bits_packet(&p);
1107 if (signal_type == 1) {
1108 for(i=0 ; i<1000 ; i++){
1109 if (signal_distance_data[i] > 0) {
1110 if (signal_distance_data[i] < (a[0]+a[1])/2) {
1111 // fprintf(stderr, "0 [%d] %d < %d\n",i, signal_distance_data[i], (a[0]+a[1])/2);
1112 demod_add_bit(&p, 0);
1113 } else if ((signal_distance_data[i] > (a[0]+a[1])/2) && (signal_distance_data[i] < (a[1]+a[2])/2)) {
1114 // fprintf(stderr, "0 [%d] %d > %d\n",i, signal_distance_data[i], (a[0]+a[1])/2);
1115 demod_add_bit(&p, 1);
1116 } else if (signal_distance_data[i] > (a[1]+a[2])/2) {
1117 // fprintf(stderr, "0 [%d] %d > %d\n",i, signal_distance_data[i], (a[1]+a[2])/2);
1118 demod_next_bits_packet(&p);
1124 demod_print_bits_packet(&p);
1126 if (signal_type == 2) {
1127 for(i=0 ; i<1000 ; i++){
1128 if(signal_pulse_data[i][2] > 0) {
1129 if (signal_pulse_data[i][2] < p_limit) {
1130 // fprintf(stderr, "0 [%d] %d < %d\n",i, signal_pulse_data[i][2], p_limit);
1131 demod_add_bit(&p, 0);
1133 // fprintf(stderr, "1 [%d] %d > %d\n",i, signal_pulse_data[i][2], p_limit);
1134 demod_add_bit(&p, 1);
1136 if ((signal_distance_data[i] >= (a[1]+a[2])/2)) {
1137 // fprintf(stderr, "\\n [%d] %d > %d\n",i, signal_distance_data[i], (a[1]+a[2])/2);
1138 demod_next_bits_packet(&p);
1144 demod_print_bits_packet(&p);
1147 for (i=0 ; i<1000 ; i++) {
1148 signal_pulse_data[i][0] = 0;
1149 signal_pulse_data[i][1] = 0;
1150 signal_pulse_data[i][2] = 0;
1151 signal_distance_data[i] = 0;
1157 static void pwm_analyze(struct dm_state *demod, int16_t *buf, uint32_t len)
1161 for (i=0 ; i<len ; i++) {
1162 if (buf[i] > demod->level_limit) {
1164 signal_start = counter;
1167 pulse_start = counter;
1168 signal_pulse_data[signal_pulse_counter][0] = counter;
1169 signal_pulse_data[signal_pulse_counter][1] = -1;
1170 signal_pulse_data[signal_pulse_counter][2] = -1;
1171 if (debug_output) fprintf(stderr, "pulse_distance %d\n",counter-pulse_end);
1172 if (debug_output) fprintf(stderr, "pulse_start distance %d\n",pulse_start-prev_pulse_start);
1173 if (debug_output) fprintf(stderr, "pulse_start[%d] found at sample %d, value = %d\n",pulses_found, counter, buf[i]);
1174 prev_pulse_start = pulse_start;
1180 if (buf[i] < demod->level_limit) {
1182 pulse_avg += counter-pulse_start;
1183 if (debug_output) fprintf(stderr, "pulse_end [%d] found at sample %d, pulse length = %d, pulse avg length = %d\n",
1184 pulses_found, counter, counter-pulse_start, pulse_avg/pulses_found);
1185 pulse_end = counter;
1187 signal_pulse_data[signal_pulse_counter][1] = counter;
1188 signal_pulse_data[signal_pulse_counter][2] = counter-pulse_start;
1189 signal_pulse_counter++;
1190 if (signal_pulse_counter >= 4000) {
1191 signal_pulse_counter = 0;
1196 if (signal_start && (pulse_end + 50000 < counter)) {
1197 signal_end = counter - 40000;
1198 fprintf(stderr, "*** signal_start = %d, signal_end = %d\n",signal_start-10000, signal_end);
1199 fprintf(stderr, "signal_len = %d, pulses = %d\n", signal_end-(signal_start-10000), pulses_found);
1203 signal_pulse_counter = 0;
1204 if (demod->sg_buf) {
1205 int start_pos, signal_bszie, wlen, wrest=0, sg_idx, idx;
1206 char sgf_name[256] = {0};
1209 sprintf(sgf_name, "gfile%03d.data",demod->signal_grabber);
1210 demod->signal_grabber++;
1211 signal_bszie = 2*(signal_end-(signal_start-10000));
1212 signal_bszie = (131072-(signal_bszie%131072)) + signal_bszie;
1213 sg_idx = demod->sg_index-demod->sg_len;
1215 sg_idx = SIGNAL_GRABBER_BUFFER-demod->sg_len;
1217 start_pos = sg_idx+idx-signal_bszie;
1218 fprintf(stderr, "signal_bszie = %d - sg_index = %d\n", signal_bszie, demod->sg_index);
1219 fprintf(stderr, "start_pos = %d - buffer_size = %d\n", start_pos, SIGNAL_GRABBER_BUFFER);
1220 if (signal_bszie > SIGNAL_GRABBER_BUFFER)
1221 fprintf(stderr, "Signal bigger then buffer, signal = %d > buffer %d !!\n", signal_bszie, SIGNAL_GRABBER_BUFFER);
1223 if (start_pos < 0) {
1224 start_pos = SIGNAL_GRABBER_BUFFER+start_pos;
1225 fprintf(stderr, "restart_pos = %d\n", start_pos);
1228 fprintf(stderr, "*** Saving signal to file %s\n",sgf_name);
1229 sgfp = fopen(sgf_name, "wb");
1231 fprintf(stderr, "Failed to open %s\n", sgf_name);
1233 wlen = signal_bszie;
1234 if (start_pos + signal_bszie > SIGNAL_GRABBER_BUFFER) {
1235 wlen = SIGNAL_GRABBER_BUFFER - start_pos;
1236 wrest = signal_bszie - wlen;
1238 fprintf(stderr, "*** Writing data from %d, len %d\n",start_pos, wlen);
1239 fwrite(&demod->sg_buf[start_pos], 1, wlen, sgfp);
1242 fprintf(stderr, "*** Writing data from %d, len %d\n",0, wrest);
1243 fwrite(&demod->sg_buf[0], 1, wrest, sgfp);
1257 fprintf(stderr, "To many pulses detected, probably bad input data or input parameters\n");
1261 /* The distance between pulses decodes into bits */
1263 static void pwm_d_decode(struct dm_state *demod, struct protocol_state* p, int16_t *buf, uint32_t len) {
1266 for (i=0 ; i<len ; i++) {
1267 if (buf[i] > demod->level_limit) {
1271 if (p->pulse_count && (buf[i] < demod->level_limit)) {
1272 p->pulse_length = 0;
1273 p->pulse_distance = 1;
1274 p->sample_counter = 0;
1277 if (p->start_c) p->sample_counter++;
1278 if (p->pulse_distance && (buf[i] > demod->level_limit)) {
1279 if (p->sample_counter < p->short_limit) {
1280 demod_add_bit(p, 0);
1281 } else if (p->sample_counter < p->long_limit) {
1282 demod_add_bit(p, 1);
1284 demod_next_bits_packet(p);
1286 p->sample_counter = 0;
1288 p->pulse_distance = 0;
1290 if (p->sample_counter > p->reset_limit) {
1292 p->sample_counter = 0;
1293 p->pulse_distance = 0;
1295 events+=p->callback(p->bits_buffer);
1297 demod_print_bits_packet(p);
1299 demod_reset_bits_packet(p);
1304 /* The length of pulses decodes into bits */
1306 static void pwm_p_decode(struct dm_state *demod, struct protocol_state* p, int16_t *buf, uint32_t len) {
1309 for (i=0 ; i<len ; i++) {
1310 if (buf[i] > demod->level_limit && !p->start_bit) {
1311 /* start bit detected */
1314 p->sample_counter = 0;
1315 // fprintf(stderr, "start bit pulse start detected\n");
1318 if (!p->real_bits && p->start_bit && (buf[i] < demod->level_limit)) {
1319 /* end of startbit */
1321 // fprintf(stderr, "start bit pulse end detected\n");
1323 if (p->start_c) p->sample_counter++;
1326 if (!p->pulse_start && p->real_bits && (buf[i] > demod->level_limit)) {
1327 /* save the pulse start, it will never be zero */
1328 p->pulse_start = p->sample_counter;
1329 // fprintf(stderr, "real bit pulse start detected\n");
1333 if (p->real_bits && p->pulse_start && (buf[i] < demod->level_limit)) {
1336 p->pulse_length = p->sample_counter-p->pulse_start;
1337 // fprintf(stderr, "real bit pulse end detected %d\n", p->pulse_length);
1338 // fprintf(stderr, "space duration %d\n", p->sample_counter);
1340 if (p->pulse_length <= p->short_limit) {
1341 demod_add_bit(p, 1);
1342 } else if (p->pulse_length > p->short_limit) {
1343 demod_add_bit(p, 0);
1345 p->sample_counter = 0;
1349 if (p->real_bits && p->pulse_length > p->long_limit) {
1350 demod_next_bits_packet(p);
1356 if (p->sample_counter > p->reset_limit) {
1358 p->sample_counter = 0;
1360 events+=p->callback(p->bits_buffer);
1362 demod_print_bits_packet(p);
1363 demod_reset_bits_packet(p);
1373 /** Something that might look like a IIR lowpass filter
1375 * [b,a] = butter(1, 0.01) -> quantizes nicely thus suitable for fixed point
1376 * Q1.15*Q15.0 = Q16.15
1377 * Q16.15>>1 = Q15.14
1378 * Q15.14 + Q15.14 + Q15.14 could possibly overflow to 17.14
1379 * but the b coeffs are small so it wont happen
1380 * Q15.14>>14 = Q15.0 \o/
1383 static uint16_t lp_xmem[FILTER_ORDER] = {0};
1386 #define S_CONST (1<<F_SCALE)
1387 #define FIX(x) ((int)(x*S_CONST))
1389 int a[FILTER_ORDER+1] = {FIX(1.00000),FIX(0.96907)};
1390 int b[FILTER_ORDER+1] = {FIX(0.015466),FIX(0.015466)};
1392 static void low_pass_filter(uint16_t *x_buf, int16_t *y_buf, uint32_t len)
1396 /* Calculate first sample */
1397 y_buf[0] = ((a[1]*y_buf[-1]>>1) + (b[0]*x_buf[0]>>1) + (b[1]*lp_xmem[0]>>1)) >> (F_SCALE-1);
1398 for (i=1 ; i<len ; i++) {
1399 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);
1402 /* Save last sample */
1403 memcpy(lp_xmem, &x_buf[len-1-FILTER_ORDER], FILTER_ORDER*sizeof(int16_t));
1404 memcpy(&y_buf[-FILTER_ORDER], &y_buf[len-1-FILTER_ORDER], FILTER_ORDER*sizeof(int16_t));
1405 //fprintf(stderr, "%d\n", y_buf[0]);
1409 static void rtlsdr_callback(unsigned char *buf, uint32_t len, void *ctx)
1411 struct dm_state *demod = ctx;
1412 uint16_t* sbuf = (uint16_t*) buf;
1414 if (demod->file || !demod->save_data) {
1415 if (do_exit || do_exit_async)
1418 if ((bytes_to_read > 0) && (bytes_to_read < len)) {
1419 len = bytes_to_read;
1421 rtlsdr_cancel_async(dev);
1424 if (demod->signal_grabber) {
1425 //fprintf(stderr, "[%d] sg_index - len %d\n", demod->sg_index, len );
1426 memcpy(&demod->sg_buf[demod->sg_index], buf, len);
1428 demod->sg_index +=len;
1429 if (demod->sg_index+len > SIGNAL_GRABBER_BUFFER)
1430 demod->sg_index = 0;
1434 if (demod->debug_mode == 0) {
1435 envelope_detect(buf, len, demod->decimation_level);
1436 low_pass_filter(sbuf, demod->f_buf, len>>(demod->decimation_level+1));
1437 } else if (demod->debug_mode == 1){
1438 memcpy(demod->f_buf, buf, len);
1440 if (demod->analyze) {
1441 pwm_analyze(demod, demod->f_buf, len/2);
1444 for (i=0 ; i<demod->r_dev_num ; i++) {
1445 switch (demod->r_devs[i]->modulation) {
1447 pwm_d_decode(demod, demod->r_devs[i], demod->f_buf, len/2);
1450 pwm_p_decode(demod, demod->r_devs[i], demod->f_buf, len/2);
1453 fprintf(stderr, "Unknown modulation %d in protocol!\n", demod->r_devs[i]->modulation);
1458 if (demod->save_data) {
1459 if (fwrite(demod->f_buf, 1, len>>demod->decimation_level, demod->file) != len>>demod->decimation_level) {
1460 fprintf(stderr, "Short write, samples lost, exiting!\n");
1461 rtlsdr_cancel_async(dev);
1465 if (bytes_to_read > 0)
1466 bytes_to_read -= len;
1471 if(difftime(rawtime, rawtime_old)>DEFAULT_HOP_TIME || events>=DEFAULT_HOP_EVENTS) {
1472 rawtime_old=rawtime;
1475 rtlsdr_cancel_async(dev);
1481 int main(int argc, char **argv)
1484 struct sigaction sigact;
1486 char *filename = NULL;
1487 char *test_mode_file = NULL;
1494 struct dm_state* demod;
1496 uint32_t dev_index = 0;
1497 int frequency_current=0;
1498 uint32_t out_block_size = DEFAULT_BUF_LENGTH;
1500 char vendor[256], product[256], serial[256];
1502 demod = malloc(sizeof(struct dm_state));
1503 memset(demod,0,sizeof(struct dm_state));
1505 /* initialize tables */
1508 demod->f_buf = &demod->filter_buffer[FILTER_ORDER];
1509 demod->decimation_level = DEFAULT_DECIMATION_LEVEL;
1510 demod->level_limit = DEFAULT_LEVEL_LIMIT;
1513 while ((opt = getopt(argc, argv, "x:z:p:Dtam:r:c:l:d:f:g:s:b:n:S::")) != -1) {
1516 dev_index = atoi(optarg);
1519 if(frequencies<MAX_PROTOCOLS) frequency[frequencies++] = (uint32_t)atof(optarg);
1520 else fprintf(stderr, "Max number of frequencies reached %d\n",MAX_PROTOCOLS);
1523 gain = (int)(atof(optarg) * 10); /* tenths of a dB */
1526 ppm_error = atoi(optarg);
1529 samp_rate = (uint32_t)atof(optarg);
1532 out_block_size = (uint32_t)atof(optarg);
1535 demod->level_limit = (uint32_t)atof(optarg);
1538 bytes_to_read = (uint32_t)atof(optarg) * 2;
1541 demod->decimation_level = (uint32_t)atof(optarg);
1547 test_mode_file = optarg;
1550 demod->signal_grabber = 1;
1553 demod->debug_mode = atoi(optarg);
1562 override_short = atoi(optarg);
1565 override_long = atoi(optarg);
1573 /* init protocols somewhat ok */
1574 register_protocol(demod, &rubicson);
1575 register_protocol(demod, &prologue);
1576 register_protocol(demod, &silvercrest);
1577 // register_protocol(demod, &generic_hx2262);
1578 // register_protocol(demod, &technoline_ws9118);
1579 register_protocol(demod, &elv_em1000);
1580 register_protocol(demod, &elv_ws2000);
1581 register_protocol(demod, &waveman);
1582 register_protocol(demod, &steffen);
1583 register_protocol(demod, &acurite5n1);
1584 register_protocol(demod, &wh2);
1586 if (argc <= optind-1) {
1589 filename = argv[optind];
1592 if(out_block_size < MINIMAL_BUF_LENGTH ||
1593 out_block_size > MAXIMAL_BUF_LENGTH ){
1595 "Output block size wrong value, falling back to default\n");
1597 "Minimal length: %u\n", MINIMAL_BUF_LENGTH);
1599 "Maximal length: %u\n", MAXIMAL_BUF_LENGTH);
1600 out_block_size = DEFAULT_BUF_LENGTH;
1603 buffer = malloc(out_block_size * sizeof(uint8_t));
1605 device_count = rtlsdr_get_device_count();
1606 if (!device_count) {
1607 fprintf(stderr, "No supported devices found.\n");
1608 if (!test_mode_file)
1612 fprintf(stderr, "Found %d device(s):\n", device_count);
1613 for (i = 0; i < device_count; i++) {
1614 rtlsdr_get_device_usb_strings(i, vendor, product, serial);
1615 fprintf(stderr, " %d: %s, %s, SN: %s\n", i, vendor, product, serial);
1617 fprintf(stderr, "\n");
1619 fprintf(stderr, "Using device %d: %s\n",
1620 dev_index, rtlsdr_get_device_name(dev_index));
1622 r = rtlsdr_open(&dev, dev_index);
1624 fprintf(stderr, "Failed to open rtlsdr device #%d.\n", dev_index);
1625 if (!test_mode_file)
1629 sigact.sa_handler = sighandler;
1630 sigemptyset(&sigact.sa_mask);
1631 sigact.sa_flags = 0;
1632 sigaction(SIGINT, &sigact, NULL);
1633 sigaction(SIGTERM, &sigact, NULL);
1634 sigaction(SIGQUIT, &sigact, NULL);
1635 sigaction(SIGPIPE, &sigact, NULL);
1637 SetConsoleCtrlHandler( (PHANDLER_ROUTINE) sighandler, TRUE );
1639 /* Set the sample rate */
1640 r = rtlsdr_set_sample_rate(dev, samp_rate);
1642 fprintf(stderr, "WARNING: Failed to set sample rate.\n");
1644 fprintf(stderr, "Sample rate set to %d.\n", rtlsdr_get_sample_rate(dev)); // Unfortunately, doesn't return real rate
1646 fprintf(stderr, "Sample rate decimation set to %d. %d->%d\n",demod->decimation_level, samp_rate, samp_rate>>demod->decimation_level);
1647 fprintf(stderr, "Bit detection level set to %d.\n", demod->level_limit);
1650 /* Enable automatic gain */
1651 r = rtlsdr_set_tuner_gain_mode(dev, 0);
1653 fprintf(stderr, "WARNING: Failed to enable automatic gain.\n");
1655 fprintf(stderr, "Tuner gain set to Auto.\n");
1657 /* Enable manual gain */
1658 r = rtlsdr_set_tuner_gain_mode(dev, 1);
1660 fprintf(stderr, "WARNING: Failed to enable manual gain.\n");
1662 /* Set the tuner gain */
1663 r = rtlsdr_set_tuner_gain(dev, gain);
1665 fprintf(stderr, "WARNING: Failed to set tuner gain.\n");
1667 fprintf(stderr, "Tuner gain set to %f dB.\n", gain/10.0);
1670 r = rtlsdr_set_freq_correction(dev, ppm_error);
1672 demod->save_data = 1;
1674 demod->save_data = 0;
1675 } else if(strcmp(filename, "-") == 0) { /* Write samples to stdout */
1676 demod->file = stdout;
1678 _setmode(_fileno(stdin), _O_BINARY);
1681 demod->file = fopen(filename, "wb");
1683 fprintf(stderr, "Failed to open %s\n", filename);
1688 if (demod->signal_grabber)
1689 demod->sg_buf = malloc(SIGNAL_GRABBER_BUFFER);
1691 if (test_mode_file) {
1693 unsigned char test_mode_buf[DEFAULT_BUF_LENGTH];
1694 fprintf(stderr, "Test mode active. Reading samples from file: %s\n",test_mode_file);
1695 test_mode = fopen(test_mode_file, "r");
1697 fprintf(stderr, "Opening file: %s failed!\n",test_mode_file);
1700 while(fread(test_mode_buf, 131072, 1, test_mode) != 0) {
1701 rtlsdr_callback(test_mode_buf, 131072, demod);
1704 //Always classify a signal at the end of the file
1706 fprintf(stderr, "Test mode file issued %d packets\n", i);
1707 fprintf(stderr, "Filter coeffs used:\n");
1708 fprintf(stderr, "a: %d %d\n", a[0], a[1]);
1709 fprintf(stderr, "b: %d %d\n", b[0], b[1]);
1713 /* Reset endpoint before we start reading from it (mandatory) */
1714 r = rtlsdr_reset_buffer(dev);
1716 fprintf(stderr, "WARNING: Failed to reset buffers.\n");
1719 fprintf(stderr, "Reading samples in sync mode...\n");
1721 r = rtlsdr_read_sync(dev, buffer, out_block_size, &n_read);
1723 fprintf(stderr, "WARNING: sync read failed.\n");
1727 if ((bytes_to_read > 0) && (bytes_to_read < (uint32_t)n_read)) {
1728 n_read = bytes_to_read;
1732 if (fwrite(buffer, 1, n_read, demod->file) != (size_t)n_read) {
1733 fprintf(stderr, "Short write, samples lost, exiting!\n");
1737 if ((uint32_t)n_read < out_block_size) {
1738 fprintf(stderr, "Short read, samples lost, exiting!\n");
1742 if (bytes_to_read > 0)
1743 bytes_to_read -= n_read;
1746 if(frequencies==0) {
1747 frequency[0] = DEFAULT_FREQUENCY;
1752 fprintf(stderr, "Reading samples in async mode...\n");
1754 /* Set the frequency */
1755 r = rtlsdr_set_center_freq(dev, frequency[frequency_current]);
1757 fprintf(stderr, "WARNING: Failed to set center freq.\n");
1759 fprintf(stderr, "Tuned to %u Hz.\n", rtlsdr_get_center_freq(dev));
1760 r = rtlsdr_read_async(dev, rtlsdr_callback, (void *)demod,
1761 DEFAULT_ASYNC_BUF_NUMBER, out_block_size);
1763 frequency_current++;
1764 if(frequency_current>frequencies-1) frequency_current=0;
1769 fprintf(stderr, "\nUser cancel, exiting...\n");
1771 fprintf(stderr, "\nLibrary error %d, exiting...\n", r);
1773 if (demod->file && (demod->file != stdout))
1774 fclose(demod->file);
1776 for (i=0 ; i<demod->r_dev_num ; i++)
1777 free(demod->r_devs[i]);
1779 if (demod->signal_grabber)
1780 free(demod->sg_buf);
1788 return r >= 0 ? r : -r;