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 void printBits(size_t const size, void const * const ptr)
166 unsigned char *b = (unsigned char*) ptr;
170 for (i=0;i<size;i++) {
172 fprintf(stderr,"%2x:",b[i]);
175 byte = b[i] & (1<<j);
177 fprintf(stderr,"%u", byte);
181 fprintf(stderr,"\n");
184 static int wh2_callback(uint8_t bb[BITBUF_ROWS][BITBUF_COLS]) {
188 int received_crc8,payload_crc8;
194 if (bb[0][0] != 0xFE) return 0;
196 payload[0] = bb[0][1]>>1;
197 payload[1] = bb[0][2]>>1 | ((bb[0][1]&1) << 7 );
198 payload[2] = bb[0][3]>>1 | ((bb[0][2]&1) << 7 );
199 payload[3] = bb[0][4]>>1 | ((bb[0][3]&1) << 7 );
201 received_crc8 = (bb[0][5]>>1) | ((bb[0][4]&1) << 7 );
203 payload_crc8 = crc8(payload,4);
205 if (payload_crc8 != received_crc8) {
206 fprintf(stderr,"Bad WH2 payload CRC, skipping...\n");
210 wh2_id = (payload[0] << 4) + (payload[1] >> 4);
211 wh2_temp = ((payload[1] & 0x7) << 8) + payload[2];
212 if (payload[1] & 0x8) {
213 wh2_temp = -wh2_temp;
215 wh2_temp = wh2_temp/10;
217 wh2_humidity = payload[3];
219 fprintf(stdout, "SENSOR:TYPE=WH2,ID=%X,HUMIDITY=%g,TEMPERATURE=%g\n",wh2_id,wh2_humidity,wh2_temp);
225 static int silvercrest_callback(uint8_t bb[BITBUF_ROWS][BITBUF_COLS]) {
226 /* FIXME validate the received message better */
227 if (bb[1][0] == 0xF8 &&
235 /* Pretty sure this is a Silvercrest remote */
236 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]);
246 static int rubicson_callback(uint8_t bb[BITBUF_ROWS][BITBUF_COLS]) {
247 int temperature_before_dec;
248 int temperature_after_dec;
252 /* FIXME validate the received message better, figure out crc */
253 if (bb[1][0] == bb[2][0] && bb[2][0] == bb[3][0] && bb[3][0] == bb[4][0] &&
254 bb[4][0] == bb[5][0] && bb[5][0] == bb[6][0] && bb[6][0] == bb[7][0] && bb[7][0] == bb[8][0] &&
255 bb[8][0] == bb[9][0] && (bb[5][0] != 0 && bb[5][1] != 0 && bb[5][2] != 0)) {
257 /* Nible 3,4,5 contains 12 bits of temperature
258 * The temperature is signed and scaled by 10 */
259 temp = (int16_t)((uint16_t)(bb[0][1] << 12) | (bb[0][2] << 4));
261 ftemp = (float)temp/10;
263 fprintf(stdout, "SENSOR:TYPE=RUBICSON,ID=%X,TEMPERATURE=%f\n",bb[0][0],ftemp);
273 static int prologue_callback(uint8_t bb[BITBUF_ROWS][BITBUF_COLS]) {
279 /* FIXME validate the received message better */
280 if (((bb[1][0]&0xF0) == 0x90 && (bb[2][0]&0xF0) == 0x90 && (bb[3][0]&0xF0) == 0x90 && (bb[4][0]&0xF0) == 0x90 &&
281 (bb[5][0]&0xF0) == 0x90 && (bb[6][0]&0xF0) == 0x90) ||
282 ((bb[1][0]&0xF0) == 0x50 && (bb[2][0]&0xF0) == 0x50 && (bb[3][0]&0xF0) == 0x50 && (bb[4][0]&0xF0) == 0x50)) {
284 /* Prologue sensor */
285 temp2 = (int16_t)((uint16_t)(bb[1][2] << 8) | (bb[1][3]&0xF0));
287 ftemp = (float)temp2/10;
288 rid = ((bb[1][0]&0x0F)<<4)|(bb[1][1]&0xF0)>>4;
290 "SENSOR:TYPE=PROLOGUE,BUTTON=%d,BATTERY=%s,TEMPERATURE=%f,HUMIDITY=%d,CHANNEL=%d,ID=%d,RID=%02x\n",
292 bb[1][1]&0x08?"Ok":"Low",
294 ((bb[1][3]&0x0F)<<4)|(bb[1][4]>>4),
295 (int)((bb[1][1]&0x03)+1),
296 (int)((bb[1][0]&0xF0)>>4),
307 static int waveman_callback(uint8_t bb[BITBUF_ROWS][BITBUF_COLS]) {
308 /* Two bits map to 2 states, 0 1 -> 0 and 1 1 -> 1 */
312 if (((bb[0][0]&0x55)==0x55) && ((bb[0][1]&0x55)==0x55) && ((bb[0][2]&0x55)==0x55) && ((bb[0][3]&0x55)==0x00)) {
313 for (i=0 ; i<3 ; i++) {
314 nb[i] |= ((bb[0][i]&0xC0)==0xC0) ? 0x00 : 0x01;
315 nb[i] |= ((bb[0][i]&0x30)==0x30) ? 0x00 : 0x02;
316 nb[i] |= ((bb[0][i]&0x0C)==0x0C) ? 0x00 : 0x04;
317 nb[i] |= ((bb[0][i]&0x03)==0x03) ? 0x00 : 0x08;
321 "BUTTON:TYPE=WAVEMAN,ID=%c,CHANNEL=%d,BUTTON=%d,STATE=%s\n",
325 ((nb[2]==0xe) ? "on" : "off"));
335 static int steffen_callback(uint8_t bb[BITBUF_ROWS][BITBUF_COLS]) {
337 if (bb[0][0]==0x00 && ((bb[1][0]&0x07)==0x07) && bb[1][0]==bb[2][0] && bb[2][0]==bb[3][0]) {
339 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);
341 if ((bb[1][2]&0x0f)==0x0e)
342 fprintf(stdout, "BUTTON=A,");
343 else if ((bb[1][2]&0x0f)==0x0d)
344 fprintf(stdout, "BUTTON=B,");
345 else if ((bb[1][2]&0x0f)==0x0b)
346 fprintf(stdout, "BUTTON=C,");
347 else if ((bb[1][2]&0x0f)==0x07)
348 fprintf(stdout, "BUTTON=D,");
349 else if ((bb[1][2]&0x0f)==0x0f)
350 fprintf(stdout, "BUTTON=ALL,");
352 fprintf(stdout, "BUTTON=UNKNOWN,");
354 if ((bb[1][2]&0xf0)==0xf0) {
355 fprintf(stdout, "STATE=OFF\n");
357 fprintf(stdout, "STATE=ON\n");
369 uint16_t AD_POP(uint8_t bb[BITBUF_COLS], uint8_t bits, uint8_t bit) {
371 uint8_t i, byte_no, bit_no;
372 for (i=0;i<bits;i++) {
374 bit_no =7-((bit+i)%8);
375 if (bb[byte_no]&(1<<bit_no)) val = val | (1<<i);
380 static int em1000_callback(uint8_t bb[BITBUF_ROWS][BITBUF_COLS]) {
384 uint8_t bit=18; // preamble
386 char* types[] = {"S", "?", "GZ"};
387 uint8_t checksum_calculated = 0;
390 uint8_t checksum_received;
392 // check and combine the 3 repetitions
393 for (i = 0; i < 14; i++) {
394 if(bb[0][i]==bb[1][i] || bb[0][i]==bb[2][i]) bb_p[i]=bb[0][i];
395 else if(bb[1][i]==bb[2][i]) bb_p[i]=bb[1][i];
399 // read 9 bytes with stopbit ...
400 for (i = 0; i < 9; i++) {
401 dec[i] = AD_POP (bb_p, 8, bit); bit+=8;
402 stopbit=AD_POP (bb_p, 1, bit); bit+=1;
404 // fprintf(stderr, "!stopbit: %i\n", i);
407 checksum_calculated ^= dec[i];
412 checksum_received = AD_POP (bb_p, 8, bit); bit+=8;
413 if (checksum_received != checksum_calculated) {
414 // fprintf(stderr, "checksum_received != checksum_calculated: %d %d\n", checksum_received, checksum_calculated);
418 //for (i = 0; i < bytes; i++) fprintf(stderr, "%02X ", dec[i]); fprintf(stderr, "\n");
420 // based on 15_CUL_EM.pm
421 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);
426 static int ws2000_callback(uint8_t bb[BITBUF_ROWS][BITBUF_COLS]) {
427 // based on http://www.dc3yc.privat.t-online.de/protocol.htm
430 uint8_t bit=11; // preamble
431 char* types[]={"!AS3", "AS2000/ASH2000/S2000/S2001A/S2001IA/ASH2200/S300IA", "!S2000R", "!S2000W", "S2001I/S2001ID", "!S2500H", "!Pyrano", "!KS200/KS300"};
432 uint8_t check_calculated=0, sum_calculated=0;
435 uint8_t sum_received;
437 dec[0] = AD_POP (bb[0], 4, bit); bit+=4;
438 stopbit= AD_POP (bb[0], 1, bit); bit+=1;
440 //fprintf(stderr, "!stopbit\n");
443 check_calculated ^= dec[0];
444 sum_calculated += dec[0];
446 // read nibbles with stopbit ...
447 for (i = 1; i <= (dec[0]==4?12:8); i++) {
448 dec[i] = AD_POP (bb[0], 4, bit); bit+=4;
449 stopbit= AD_POP (bb[0], 1, bit); bit+=1;
451 //fprintf(stderr, "!stopbit %i\n", i);
454 check_calculated ^= dec[i];
455 sum_calculated += dec[i];
459 if (check_calculated) {
460 //fprintf(stderr, "check_calculated (%d) != 0\n", check_calculated);
465 sum_received = AD_POP (bb[0], 4, bit); bit+=4;
468 if (sum_received != sum_calculated) {
469 //fprintf(stderr, "sum_received (%d) != sum_calculated (%d) ", sum_received, sum_calculated);
473 //for (i = 0; i < nibbles; i++) fprintf(stderr, "%02X ", dec[i]); fprintf(stderr, "\n");
475 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]);
477 fprintf(stdout, "PRESSURE=%d\n", 200+dec[10]*100+dec[9]*10+dec[8]);
479 fprintf(stdout, "\n");
485 // ** Acurite 5n1 functions **
487 const float acurite_winddirections[] =
488 { 337.5, 315.0, 292.5, 270.0, 247.5, 225.0, 202.5, 180,
489 157.5, 135.0, 112.5, 90.0, 67.5, 45.0, 22.5, 0.0 };
491 static int acurite_raincounter = 0;
493 static int acurite_crc(uint8_t row[BITBUF_COLS], int cols) {
494 // sum of first n-1 bytes modulo 256 should equal nth byte
497 for ( i=0; i < cols; i++)
499 if ( sum % 256 == row[cols] )
505 static int acurite_detect(uint8_t *pRow) {
507 if ( pRow[0] != 0x00 ) {
508 // invert bits due to wierd issue
509 for (i = 0; i < 8; i++)
510 pRow[i] = ~pRow[i] & 0xFF;
511 pRow[0] |= pRow[8]; // fix first byte that has mashed leading bit
513 if (acurite_crc(pRow, 7))
514 return 1; // passes crc check
519 static float acurite_getTemp (uint8_t highbyte, uint8_t lowbyte) {
520 // range -40 to 158 F
521 int highbits = (highbyte & 0x0F) << 7 ;
522 int lowbits = lowbyte & 0x7F;
523 int rawtemp = highbits | lowbits;
524 float temp = (rawtemp - 400) / 10.0;
528 static int acurite_getWindSpeed (uint8_t highbyte, uint8_t lowbyte) {
529 // range: 0 to 159 kph
530 int highbits = ( highbyte & 0x1F) << 3;
531 int lowbits = ( lowbyte & 0x70 ) >> 4;
532 int speed = highbits | lowbits;
536 static float acurite_getWindDirection (uint8_t byte) {
537 // 16 compass points, ccw from (NNW) to 15 (N)
538 int direction = byte & 0x0F;
539 return acurite_winddirections[direction];
542 static int acurite_getHumidity (uint8_t byte) {
543 // range: 1 to 99 %RH
544 int humidity = byte & 0x7F;
548 static int acurite_getRainfallCounter (uint8_t highbyte, uint8_t lowbyte) {
549 // range: 0 to 99.99 in, 0.01 in incr., rolling counter?
550 int highbits = (highbyte & 0x3F) << 7 ;
551 int lowbits = lowbyte & 0x7F;
552 int raincounter = highbits | lowbits;
556 static int acurite5n1_callback(uint8_t bb[BITBUF_ROWS][BITBUF_COLS]) {
557 // acurite 5n1 weather sensor decoding for rtl_433
561 // run through rows til we find one with good crc (brute force)
562 for (i=0; i < BITBUF_ROWS; i++) {
563 if (acurite_detect(bb[i])) {
570 // decode packet here
571 fprintf(stdout, "SENSOR:TYPE=ACURITE");
573 for (i=0; i < 8; i++)
574 fprintf(stderr, "%02X ", buf[i]);
575 fprintf(stderr, "CRC OK\n");
578 if ((buf[2] & 0x0F) == 1) {
579 // wind speed, wind direction, rainfall
581 float rainfall = 0.00;
583 if (acurite_raincounter > 0) {
584 // track rainfall difference after first run
585 raincounter = acurite_getRainfallCounter(buf[5], buf[6]);
586 rainfall = ( raincounter - acurite_raincounter ) * 0.01;
588 // capture starting counter
589 acurite_raincounter = raincounter;
592 fprintf(stdout, ",WINDSPEED=%d",
593 acurite_getWindSpeed(buf[3], buf[4]));
594 fprintf(stdout, ",WINDDIRECTION=%0.1f",
595 acurite_getWindDirection(buf[4]));
596 fprintf(stdout, ",RAINGAUGE: %0.2f\n", rainfall);
598 } else if ((buf[2] & 0x0F) == 8) {
599 // wind speed, temp, RH
600 fprintf(stdout, ",WINDSPEED=%d",
601 acurite_getWindSpeed(buf[3], buf[4]));
602 fprintf(stdout, ",TEMPERATURE=%2.1f",
603 acurite_getTemp(buf[4], buf[5]));
604 fprintf(stdout, ",HUMIDITY=%d\n",
605 acurite_getHumidity(buf[6]));
609 // debug_callback(bb);
614 // timings based on samp_rate=1024000
615 r_device rubicson = {
617 /* .name = */ "Rubicson Temperature Sensor",
618 /* .modulation = */ OOK_PWM_D,
619 /* .short_limit = */ 1744/4,
620 /* .long_limit = */ 3500/4,
621 /* .reset_limit = */ 5000/4,
622 /* .json_callback = */ &rubicson_callback,
625 r_device prologue = {
627 /* .name = */ "Prologue Temperature Sensor",
628 /* .modulation = */ OOK_PWM_D,
629 /* .short_limit = */ 3500/4,
630 /* .long_limit = */ 7000/4,
631 /* .reset_limit = */ 15000/4,
632 /* .json_callback = */ &prologue_callback,
635 r_device silvercrest = {
637 /* .name = */ "Silvercrest Remote Control",
638 /* .modulation = */ OOK_PWM_P,
639 /* .short_limit = */ 600/4,
640 /* .long_limit = */ 5000/4,
641 /* .reset_limit = */ 15000/4,
642 /* .json_callback = */ &silvercrest_callback,
645 r_device tech_line_fws_500 = {
647 /* .name = */ "Tech Line FWS-500 Sensor",
648 /* .modulation = */ OOK_PWM_D,
649 /* .short_limit = */ 3500/4,
650 /* .long_limit = */ 7000/4,
651 /* .reset_limit = */ 15000/4,
652 /* .json_callback = */ &rubicson_callback,
655 r_device generic_hx2262 = {
657 /* .name = */ "Window/Door sensor",
658 /* .modulation = */ OOK_PWM_P,
659 /* .short_limit = */ 1300/4,
660 /* .long_limit = */ 10000/4,
661 /* .reset_limit = */ 40000/4,
662 /* .json_callback = */ &silvercrest_callback,
665 r_device technoline_ws9118 = {
667 /* .name = */ "Technoline WS9118",
668 /* .modulation = */ OOK_PWM_D,
669 /* .short_limit = */ 1800/4,
670 /* .long_limit = */ 3500/4,
671 /* .reset_limit = */ 15000/4,
672 /* .json_callback = */ &debug_callback,
676 r_device elv_em1000 = {
678 /* .name = */ "ELV EM 1000",
679 /* .modulation = */ OOK_PWM_D,
680 /* .short_limit = */ 750/4,
681 /* .long_limit = */ 7250/4,
682 /* .reset_limit = */ 30000/4,
683 /* .json_callback = */ &em1000_callback,
686 r_device elv_ws2000 = {
688 /* .name = */ "ELV WS 2000",
689 /* .modulation = */ OOK_PWM_D,
690 /* .short_limit = */ (602+(1155-602)/2)/4,
691 /* .long_limit = */ ((1755635-1655517)/2)/4, // no repetitions
692 /* .reset_limit = */ ((1755635-1655517)*2)/4,
693 /* .json_callback = */ &ws2000_callback,
698 /* .name = */ "Waveman Switch Transmitter",
699 /* .modulation = */ OOK_PWM_P,
700 /* .short_limit = */ 1000/4,
701 /* .long_limit = */ 8000/4,
702 /* .reset_limit = */ 30000/4,
703 /* .json_callback = */ &waveman_callback,
708 /* .name = */ "Steffen Switch Transmitter",
709 /* .modulation = */ OOK_PWM_D,
710 /* .short_limit = */ 140,
711 /* .long_limit = */ 270,
712 /* .reset_limit = */ 1500,
713 /* .json_callback = */ &steffen_callback,
716 r_device acurite5n1 = {
718 /* .name = */ "Acurite 5n1 Weather Station",
719 /* .modulation = */ OOK_PWM_P,
720 /* .short_limit = */ 75,
721 /* .long_limit = */ 220,
722 /* .reset_limit = */ 20000,
723 /* .json_callback = */ &acurite5n1_callback,
728 /* .name = */ "WH2 Weather Station",
729 /* .modulation = */ OOK_PWM_P,
730 /* .short_limit = */ 150,
731 /* .long_limit = */ 400,
732 /* .reset_limit = */ 20000,
733 /* .json_callback = */ &wh2_callback,
736 struct protocol_state {
737 int (*callback)(uint8_t bits_buffer[BITBUF_ROWS][BITBUF_COLS]);
742 int bits_bit_col_idx;
743 uint8_t bits_buffer[BITBUF_ROWS][BITBUF_COLS];
744 int16_t bits_per_row[BITBUF_ROWS];
746 unsigned int modulation;
772 int32_t decimation_level;
773 int16_t filter_buffer[MAXIMAL_BUF_LENGTH+FILTER_ORDER];
778 /* Signal grabber variables */
785 /* Protocol states */
787 struct protocol_state *r_devs[MAX_PROTOCOLS];
794 "rtl_433, an ISM band generic data receiver for RTL2832 based DVB-T receivers\n\n"
795 "Usage:\t[-d device_index (default: 0)]\n"
796 "\t[-g gain (default: 0 for auto)]\n"
797 "\t[-a analyze mode, print a textual description of the signal]\n"
798 "\t[-t signal auto save, use it together with analyze mode (-a -t)\n"
799 "\t[-l change the detection level used to determine pulses (0-3200) default: %i]\n"
800 "\t[-f [-f...] receive frequency[s], default: %i Hz]\n"
801 "\t[-s samplerate (default: %i Hz)]\n"
802 "\t[-S force sync output (default: async)]\n"
803 "\t[-r read data from file instead of from a receiver]\n"
804 "\t[-p ppm_error (default: 0)]\n"
805 "\t[-r test file name (indata)]\n"
806 "\t[-m test file mode (0 rtl_sdr data, 1 rtl_433 data)]\n"
807 "\t[-D print debug info on event\n"
808 "\t[-z override short value\n"
809 "\t[-x override long value\n"
810 "\tfilename (a '-' dumps samples to stdout)\n\n", DEFAULT_LEVEL_LIMIT, DEFAULT_FREQUENCY, DEFAULT_SAMPLE_RATE);
816 sighandler(int signum)
818 if (CTRL_C_EVENT == signum) {
819 fprintf(stderr, "Signal caught, exiting!\n");
821 rtlsdr_cancel_async(dev);
827 static void sighandler(int signum)
829 fprintf(stderr, "Signal caught, exiting!\n");
831 rtlsdr_cancel_async(dev);
835 /* precalculate lookup table for envelope detection */
836 static void calc_squares() {
838 for (i=0 ; i<256 ; i++)
839 scaled_squares[i] = (128-i) * (128-i);
842 /** This will give a noisy envelope of OOK/ASK signals
843 * Subtract the bias (-128) and get an envelope estimation
844 * The output will be written in the input buffer
845 * @returns pointer to the input buffer
848 static void envelope_detect(unsigned char *buf, uint32_t len, int decimate)
850 uint16_t* sample_buffer = (uint16_t*) buf;
853 unsigned int stride = 1<<decimate;
855 for (i=0 ; i<len/2 ; i+=stride) {
856 sample_buffer[op++] = scaled_squares[buf[2*i ]]+scaled_squares[buf[2*i+1]];
860 static void demod_reset_bits_packet(struct protocol_state* p) {
861 memset(p->bits_buffer, 0 ,BITBUF_ROWS*BITBUF_COLS);
862 memset(p->bits_per_row, 0 ,BITBUF_ROWS);
864 p->bits_bit_col_idx = 7;
869 static void demod_add_bit(struct protocol_state* p, int bit) {
870 p->bits_buffer[p->bits_row_idx][p->bits_col_idx] |= bit<<p->bits_bit_col_idx;
871 p->bits_bit_col_idx--;
872 if (p->bits_bit_col_idx<0) {
873 p->bits_bit_col_idx = 7;
875 if (p->bits_col_idx>BITBUF_COLS-1) {
876 p->bits_col_idx = BITBUF_COLS-1;
877 // fprintf(stderr, "p->bits_col_idx>%i!\n", BITBUF_COLS-1);
880 p->bits_per_row[p->bit_rows]++;
883 static void demod_next_bits_packet(struct protocol_state* p) {
886 p->bits_bit_col_idx = 7;
887 if (p->bits_row_idx>BITBUF_ROWS-1) {
888 p->bits_row_idx = BITBUF_ROWS-1;
889 //fprintf(stderr, "p->bits_row_idx>%i!\n", BITBUF_ROWS-1);
892 if (p->bit_rows > BITBUF_ROWS-1)
896 static void demod_print_bits_packet(struct protocol_state* p) {
899 fprintf(stderr, "\n");
900 for (i=0 ; i<p->bit_rows+1 ; i++) {
901 fprintf(stderr, "[%02d] {%d} ",i, p->bits_per_row[i]);
902 for (j=0 ; j<((p->bits_per_row[i]+8)/8) ; j++) {
903 fprintf(stderr, "%02x ", p->bits_buffer[i][j]);
905 fprintf(stderr, ": ");
906 for (j=0 ; j<((p->bits_per_row[i]+8)/8) ; j++) {
907 for (k=7 ; k>=0 ; k--) {
908 if (p->bits_buffer[i][j] & 1<<k)
909 fprintf(stderr, "1");
911 fprintf(stderr, "0");
913 // fprintf(stderr, "=0x%x ",demod->bits_buffer[i][j]);
914 fprintf(stderr, " ");
916 fprintf(stderr, "\n");
918 fprintf(stderr, "\n");
922 static void register_protocol(struct dm_state *demod, r_device *t_dev) {
923 struct protocol_state *p = calloc(1,sizeof(struct protocol_state));
924 p->short_limit = (float)t_dev->short_limit/((float)DEFAULT_SAMPLE_RATE/(float)samp_rate);
925 p->long_limit = (float)t_dev->long_limit /((float)DEFAULT_SAMPLE_RATE/(float)samp_rate);
926 p->reset_limit = (float)t_dev->reset_limit/((float)DEFAULT_SAMPLE_RATE/(float)samp_rate);
927 p->modulation = t_dev->modulation;
928 p->callback = t_dev->json_callback;
929 demod_reset_bits_packet(p);
931 demod->r_devs[demod->r_dev_num] = p;
934 fprintf(stderr, "Registering protocol[%02d] %s\n",demod->r_dev_num, t_dev->name);
936 if (demod->r_dev_num > MAX_PROTOCOLS)
937 fprintf(stderr, "Max number of protocols reached %d\n",MAX_PROTOCOLS);
941 static unsigned int counter = 0;
942 static unsigned int print = 1;
943 static unsigned int print2 = 0;
944 static unsigned int pulses_found = 0;
945 static unsigned int prev_pulse_start = 0;
946 static unsigned int pulse_start = 0;
947 static unsigned int pulse_end = 0;
948 static unsigned int pulse_avg = 0;
949 static unsigned int signal_start = 0;
950 static unsigned int signal_end = 0;
951 static unsigned int signal_pulse_data[4000][3] = {{0}};
952 static unsigned int signal_pulse_counter = 0;
955 static void classify_signal() {
956 unsigned int i,k, max=0, min=1000000, t;
957 unsigned int delta, count_min, count_max, min_new, max_new, p_limit;
958 unsigned int a[3], b[2], a_cnt[3], a_new[3], b_new[2];
959 unsigned int signal_distance_data[4000] = {0};
960 struct protocol_state p = {0};
961 unsigned int signal_type;
963 if (!signal_pulse_data[0][0])
966 for (i=0 ; i<1000 ; i++) {
967 if (signal_pulse_data[i][0] > 0) {
968 //fprintf(stderr, "[%03d] s: %d\t e:\t %d\t l:%d\n",
969 //i, signal_pulse_data[i][0], signal_pulse_data[i][1],
970 //signal_pulse_data[i][2]);
971 if (signal_pulse_data[i][2] > max)
972 max = signal_pulse_data[i][2];
973 if (signal_pulse_data[i][2] <= min)
974 min = signal_pulse_data[i][2];
978 //fprintf(stderr, "\n\nMax: %d, Min: %d t:%d\n", max, min, t);
980 delta = (max - min)*(max-min);
982 //TODO use Lloyd-Max quantizer instead
984 while((k < 10) && (delta > 0)) {
985 min_new = 0; count_min = 0;
986 max_new = 0; count_max = 0;
988 for (i=0 ; i < 1000 ; i++) {
989 if (signal_pulse_data[i][0] > 0) {
990 if (signal_pulse_data[i][2] < t) {
991 min_new = min_new + signal_pulse_data[i][2];
995 max_new = max_new + signal_pulse_data[i][2];
1000 min_new = min_new / count_min;
1001 max_new = max_new / count_max;
1003 delta = (min - min_new)*(min - min_new) + (max - max_new)*(max - max_new);
1008 fprintf(stderr, "Iteration %d. t: %d min: %d (%d) max: %d (%d) delta %d\n", k,t, min, count_min, max, count_max, delta);
1012 for (i=0 ; i<1000 ; i++) {
1013 if (signal_pulse_data[i][0] > 0) {
1014 //fprintf(stderr, "%d\n", signal_pulse_data[i][1]);
1017 /* 50% decision limit */
1019 fprintf(stderr, "Pulse coding: Short pulse length %d - Long pulse length %d\n", min, max);
1022 fprintf(stderr, "Distance coding: Pulse length %d\n", (min+max)/2);
1025 p_limit = (max+min)/2;
1027 /* Initial guesses */
1030 for (i=1 ; i<1000 ; i++) {
1031 if (signal_pulse_data[i][0] > 0) {
1032 // fprintf(stderr, "[%03d] s: %d\t e:\t %d\t l:%d\t d:%d\n",
1033 // i, signal_pulse_data[i][0], signal_pulse_data[i][1],
1034 // signal_pulse_data[i][2], signal_pulse_data[i][0]-signal_pulse_data[i-1][1]);
1035 signal_distance_data[i-1] = signal_pulse_data[i][0]-signal_pulse_data[i-1][1];
1036 if (signal_distance_data[i-1] > a[2])
1037 a[2] = signal_distance_data[i-1];
1038 if (signal_distance_data[i-1] <= a[0])
1039 a[0] = signal_distance_data[i-1];
1044 a[1] = (a[0]+a[2])/2;
1045 // for (i=0 ; i<1 ; i++) {
1046 // b[i] = (a[i]+a[i+1])/2;
1048 b[0] = (a[0]+a[1])/2;
1049 b[1] = (a[1]+a[2])/2;
1050 // fprintf(stderr, "a[0]: %d\t a[1]: %d\t a[2]: %d\t\n",a[0],a[1],a[2]);
1051 // fprintf(stderr, "b[0]: %d\t b[1]: %d\n",b[0],b[1]);
1055 while((k < 10) && (delta > 0)) {
1056 for (i=0 ; i<3 ; i++) {
1061 for (i=0 ; i < 1000 ; i++) {
1062 if (signal_distance_data[i] > 0) {
1063 if (signal_distance_data[i] < b[0]) {
1064 a_new[0] += signal_distance_data[i];
1066 } else if (signal_distance_data[i] < b[1] && signal_distance_data[i] >= b[0]){
1067 a_new[1] += signal_distance_data[i];
1069 } else if (signal_distance_data[i] >= b[1]) {
1070 a_new[2] += signal_distance_data[i];
1076 // fprintf(stderr, "Iteration %d.", k);
1078 for (i=0 ; i<3 ; i++) {
1080 a_new[i] /= a_cnt[i];
1081 delta += (a[i]-a_new[i])*(a[i]-a_new[i]);
1082 // fprintf(stderr, "\ta[%d]: %d (%d)", i, a_new[i], a[i]);
1085 // fprintf(stderr, " delta %d\n", delta);
1089 // fprintf(stderr, "Fixing a[0] = %d\n", min);
1093 // fprintf(stderr, "Fixing a[2] = %d\n", max);
1096 // a[1] = (a[2]+a[0])/2;
1097 // fprintf(stderr, "Fixing a[1] = %d\n", a[1]);
1100 // fprintf(stderr, "Iteration %d.", k);
1101 for (i=0 ; i<2 ; i++) {
1102 // fprintf(stderr, "\tb[%d]: (%d) ", i, b[i]);
1103 b[i] = (a[i]+a[i+1])/2;
1104 // fprintf(stderr, "%d ", b[i]);
1106 // fprintf(stderr, "\n");
1110 if (override_short) {
1111 p_limit = override_short;
1112 a[0] = override_short;
1115 if (override_long) {
1116 a[1] = override_long;
1127 fprintf(stderr, "\nShort distance: %d, long distance: %d, packet distance: %d\n",a[0],a[1],a[2]);
1128 fprintf(stderr, "\np_limit: %d\n",p_limit);
1130 demod_reset_bits_packet(&p);
1131 if (signal_type == 1) {
1132 for(i=0 ; i<1000 ; i++){
1133 if (signal_distance_data[i] > 0) {
1134 if (signal_distance_data[i] < (a[0]+a[1])/2) {
1135 // fprintf(stderr, "0 [%d] %d < %d\n",i, signal_distance_data[i], (a[0]+a[1])/2);
1136 demod_add_bit(&p, 0);
1137 } else if ((signal_distance_data[i] > (a[0]+a[1])/2) && (signal_distance_data[i] < (a[1]+a[2])/2)) {
1138 // fprintf(stderr, "0 [%d] %d > %d\n",i, signal_distance_data[i], (a[0]+a[1])/2);
1139 demod_add_bit(&p, 1);
1140 } else if (signal_distance_data[i] > (a[1]+a[2])/2) {
1141 // fprintf(stderr, "0 [%d] %d > %d\n",i, signal_distance_data[i], (a[1]+a[2])/2);
1142 demod_next_bits_packet(&p);
1148 demod_print_bits_packet(&p);
1150 if (signal_type == 2) {
1151 for(i=0 ; i<1000 ; i++){
1152 if(signal_pulse_data[i][2] > 0) {
1153 if (signal_pulse_data[i][2] < p_limit) {
1154 // fprintf(stderr, "0 [%d] %d < %d\n",i, signal_pulse_data[i][2], p_limit);
1155 demod_add_bit(&p, 0);
1157 // fprintf(stderr, "1 [%d] %d > %d\n",i, signal_pulse_data[i][2], p_limit);
1158 demod_add_bit(&p, 1);
1160 if ((signal_distance_data[i] >= (a[1]+a[2])/2)) {
1161 // fprintf(stderr, "\\n [%d] %d > %d\n",i, signal_distance_data[i], (a[1]+a[2])/2);
1162 demod_next_bits_packet(&p);
1168 demod_print_bits_packet(&p);
1171 for (i=0 ; i<1000 ; i++) {
1172 signal_pulse_data[i][0] = 0;
1173 signal_pulse_data[i][1] = 0;
1174 signal_pulse_data[i][2] = 0;
1175 signal_distance_data[i] = 0;
1181 static void pwm_analyze(struct dm_state *demod, int16_t *buf, uint32_t len)
1185 for (i=0 ; i<len ; i++) {
1186 if (buf[i] > demod->level_limit) {
1188 signal_start = counter;
1191 pulse_start = counter;
1192 signal_pulse_data[signal_pulse_counter][0] = counter;
1193 signal_pulse_data[signal_pulse_counter][1] = -1;
1194 signal_pulse_data[signal_pulse_counter][2] = -1;
1195 if (debug_output) fprintf(stderr, "pulse_distance %d\n",counter-pulse_end);
1196 if (debug_output) fprintf(stderr, "pulse_start distance %d\n",pulse_start-prev_pulse_start);
1197 if (debug_output) fprintf(stderr, "pulse_start[%d] found at sample %d, value = %d\n",pulses_found, counter, buf[i]);
1198 prev_pulse_start = pulse_start;
1204 if (buf[i] < demod->level_limit) {
1206 pulse_avg += counter-pulse_start;
1207 if (debug_output) fprintf(stderr, "pulse_end [%d] found at sample %d, pulse length = %d, pulse avg length = %d\n",
1208 pulses_found, counter, counter-pulse_start, pulse_avg/pulses_found);
1209 pulse_end = counter;
1211 signal_pulse_data[signal_pulse_counter][1] = counter;
1212 signal_pulse_data[signal_pulse_counter][2] = counter-pulse_start;
1213 signal_pulse_counter++;
1214 if (signal_pulse_counter >= 4000) {
1215 signal_pulse_counter = 0;
1220 if (signal_start && (pulse_end + 50000 < counter)) {
1221 signal_end = counter - 40000;
1222 fprintf(stderr, "*** signal_start = %d, signal_end = %d\n",signal_start-10000, signal_end);
1223 fprintf(stderr, "signal_len = %d, pulses = %d\n", signal_end-(signal_start-10000), pulses_found);
1227 signal_pulse_counter = 0;
1228 if (demod->sg_buf) {
1229 int start_pos, signal_bszie, wlen, wrest=0, sg_idx, idx;
1230 char sgf_name[256] = {0};
1233 sprintf(sgf_name, "gfile%03d.data",demod->signal_grabber);
1234 demod->signal_grabber++;
1235 signal_bszie = 2*(signal_end-(signal_start-10000));
1236 signal_bszie = (131072-(signal_bszie%131072)) + signal_bszie;
1237 sg_idx = demod->sg_index-demod->sg_len;
1239 sg_idx = SIGNAL_GRABBER_BUFFER-demod->sg_len;
1241 start_pos = sg_idx+idx-signal_bszie;
1242 fprintf(stderr, "signal_bszie = %d - sg_index = %d\n", signal_bszie, demod->sg_index);
1243 fprintf(stderr, "start_pos = %d - buffer_size = %d\n", start_pos, SIGNAL_GRABBER_BUFFER);
1244 if (signal_bszie > SIGNAL_GRABBER_BUFFER)
1245 fprintf(stderr, "Signal bigger then buffer, signal = %d > buffer %d !!\n", signal_bszie, SIGNAL_GRABBER_BUFFER);
1247 if (start_pos < 0) {
1248 start_pos = SIGNAL_GRABBER_BUFFER+start_pos;
1249 fprintf(stderr, "restart_pos = %d\n", start_pos);
1252 fprintf(stderr, "*** Saving signal to file %s\n",sgf_name);
1253 sgfp = fopen(sgf_name, "wb");
1255 fprintf(stderr, "Failed to open %s\n", sgf_name);
1257 wlen = signal_bszie;
1258 if (start_pos + signal_bszie > SIGNAL_GRABBER_BUFFER) {
1259 wlen = SIGNAL_GRABBER_BUFFER - start_pos;
1260 wrest = signal_bszie - wlen;
1262 fprintf(stderr, "*** Writing data from %d, len %d\n",start_pos, wlen);
1263 fwrite(&demod->sg_buf[start_pos], 1, wlen, sgfp);
1266 fprintf(stderr, "*** Writing data from %d, len %d\n",0, wrest);
1267 fwrite(&demod->sg_buf[0], 1, wrest, sgfp);
1281 fprintf(stderr, "To many pulses detected, probably bad input data or input parameters\n");
1285 /* The distance between pulses decodes into bits */
1287 static void pwm_d_decode(struct dm_state *demod, struct protocol_state* p, int16_t *buf, uint32_t len) {
1290 for (i=0 ; i<len ; i++) {
1291 if (buf[i] > demod->level_limit) {
1295 if (p->pulse_count && (buf[i] < demod->level_limit)) {
1296 p->pulse_length = 0;
1297 p->pulse_distance = 1;
1298 p->sample_counter = 0;
1301 if (p->start_c) p->sample_counter++;
1302 if (p->pulse_distance && (buf[i] > demod->level_limit)) {
1303 if (p->sample_counter < p->short_limit) {
1304 demod_add_bit(p, 0);
1305 } else if (p->sample_counter < p->long_limit) {
1306 demod_add_bit(p, 1);
1308 demod_next_bits_packet(p);
1310 p->sample_counter = 0;
1312 p->pulse_distance = 0;
1314 if (p->sample_counter > p->reset_limit) {
1316 p->sample_counter = 0;
1317 p->pulse_distance = 0;
1319 events+=p->callback(p->bits_buffer);
1321 demod_print_bits_packet(p);
1323 demod_reset_bits_packet(p);
1328 /* The length of pulses decodes into bits */
1330 static void pwm_p_decode(struct dm_state *demod, struct protocol_state* p, int16_t *buf, uint32_t len) {
1333 for (i=0 ; i<len ; i++) {
1334 if (buf[i] > demod->level_limit && !p->start_bit) {
1335 /* start bit detected */
1338 p->sample_counter = 0;
1340 fprintf(stderr, "start bit pulse start detected\n");
1343 if (!p->real_bits && p->start_bit && (buf[i] < demod->level_limit)) {
1344 /* end of startbit */
1346 p->pulse_length = 0;
1348 fprintf(stderr, "start bit pulse end detected\n");
1350 if (p->start_c) p->sample_counter++;
1353 if (!p->pulse_start && p->real_bits && (buf[i] > demod->level_limit)) {
1354 /* save the pulse start, it will never be zero */
1355 p->pulse_start = p->sample_counter;
1357 fprintf(stderr, "real bit pulse start detected\n");
1361 if (p->real_bits && p->pulse_start && (buf[i] < demod->level_limit)) {
1364 p->pulse_length = p->sample_counter-p->pulse_start;
1366 fprintf(stderr, "real bit pulse end detected %d\n", p->pulse_length);
1367 fprintf(stderr, "space duration %d\n", p->sample_counter);
1370 if (p->pulse_length <= p->short_limit) {
1372 fprintf(stderr, "1 received\n");
1373 demod_add_bit(p, 1);
1376 fprintf(stderr, "0 received\n");
1377 demod_add_bit(p, 0);
1379 p->sample_counter = 0;
1383 if (p->real_bits && (p->pulse_length > p->long_limit)) {
1385 fprintf(stderr, "End of packet\n");
1386 demod_next_bits_packet(p);
1392 if (p->sample_counter > p->reset_limit) {
1394 p->sample_counter = 0;
1396 events+=p->callback(p->bits_buffer);
1398 demod_print_bits_packet(p);
1399 demod_reset_bits_packet(p);
1409 /** Something that might look like a IIR lowpass filter
1411 * [b,a] = butter(1, 0.01) -> quantizes nicely thus suitable for fixed point
1412 * Q1.15*Q15.0 = Q16.15
1413 * Q16.15>>1 = Q15.14
1414 * Q15.14 + Q15.14 + Q15.14 could possibly overflow to 17.14
1415 * but the b coeffs are small so it wont happen
1416 * Q15.14>>14 = Q15.0 \o/
1419 static uint16_t lp_xmem[FILTER_ORDER] = {0};
1422 #define S_CONST (1<<F_SCALE)
1423 #define FIX(x) ((int)(x*S_CONST))
1425 int a[FILTER_ORDER+1] = {FIX(1.00000),FIX(0.96907)};
1426 int b[FILTER_ORDER+1] = {FIX(0.015466),FIX(0.015466)};
1428 static void low_pass_filter(uint16_t *x_buf, int16_t *y_buf, uint32_t len)
1432 /* Calculate first sample */
1433 y_buf[0] = ((a[1]*y_buf[-1]>>1) + (b[0]*x_buf[0]>>1) + (b[1]*lp_xmem[0]>>1)) >> (F_SCALE-1);
1434 for (i=1 ; i<len ; i++) {
1435 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);
1438 /* Save last sample */
1439 memcpy(lp_xmem, &x_buf[len-1-FILTER_ORDER], FILTER_ORDER*sizeof(int16_t));
1440 memcpy(&y_buf[-FILTER_ORDER], &y_buf[len-1-FILTER_ORDER], FILTER_ORDER*sizeof(int16_t));
1441 //fprintf(stderr, "%d\n", y_buf[0]);
1445 static void rtlsdr_callback(unsigned char *buf, uint32_t len, void *ctx)
1447 struct dm_state *demod = ctx;
1448 uint16_t* sbuf = (uint16_t*) buf;
1450 if (demod->file || !demod->save_data) {
1451 if (do_exit || do_exit_async)
1454 if ((bytes_to_read > 0) && (bytes_to_read < len)) {
1455 len = bytes_to_read;
1457 rtlsdr_cancel_async(dev);
1460 if (demod->signal_grabber) {
1461 //fprintf(stderr, "[%d] sg_index - len %d\n", demod->sg_index, len );
1462 memcpy(&demod->sg_buf[demod->sg_index], buf, len);
1464 demod->sg_index +=len;
1465 if (demod->sg_index+len > SIGNAL_GRABBER_BUFFER)
1466 demod->sg_index = 0;
1470 if (demod->debug_mode == 0) {
1471 envelope_detect(buf, len, demod->decimation_level);
1472 low_pass_filter(sbuf, demod->f_buf, len>>(demod->decimation_level+1));
1473 } else if (demod->debug_mode == 1){
1474 memcpy(demod->f_buf, buf, len);
1476 if (demod->analyze) {
1477 pwm_analyze(demod, demod->f_buf, len/2);
1480 for (i=0 ; i<demod->r_dev_num ; i++) {
1481 switch (demod->r_devs[i]->modulation) {
1483 pwm_d_decode(demod, demod->r_devs[i], demod->f_buf, len/2);
1486 pwm_p_decode(demod, demod->r_devs[i], demod->f_buf, len/2);
1489 fprintf(stderr, "Unknown modulation %d in protocol!\n", demod->r_devs[i]->modulation);
1495 if (demod->save_data) {
1496 if (fwrite(demod->f_buf, 1, len>>demod->decimation_level, demod->file) != len>>demod->decimation_level) {
1497 fprintf(stderr, "Short write, samples lost, exiting!\n");
1498 rtlsdr_cancel_async(dev);
1502 if (bytes_to_read > 0)
1503 bytes_to_read -= len;
1508 if(difftime(rawtime, rawtime_old)>DEFAULT_HOP_TIME || events>=DEFAULT_HOP_EVENTS) {
1509 rawtime_old=rawtime;
1512 rtlsdr_cancel_async(dev);
1518 int main(int argc, char **argv)
1521 struct sigaction sigact;
1523 char *filename = NULL;
1524 char *test_mode_file = NULL;
1531 struct dm_state* demod;
1533 uint32_t dev_index = 0;
1534 int frequency_current=0;
1535 uint32_t out_block_size = DEFAULT_BUF_LENGTH;
1537 char vendor[256], product[256], serial[256];
1539 demod = malloc(sizeof(struct dm_state));
1540 memset(demod,0,sizeof(struct dm_state));
1542 /* initialize tables */
1545 demod->f_buf = &demod->filter_buffer[FILTER_ORDER];
1546 demod->decimation_level = DEFAULT_DECIMATION_LEVEL;
1547 demod->level_limit = DEFAULT_LEVEL_LIMIT;
1550 while ((opt = getopt(argc, argv, "x:z:p:Dtam:r:c:l:d:f:g:s:b:n:S::")) != -1) {
1553 dev_index = atoi(optarg);
1556 if(frequencies<MAX_PROTOCOLS) frequency[frequencies++] = (uint32_t)atof(optarg);
1557 else fprintf(stderr, "Max number of frequencies reached %d\n",MAX_PROTOCOLS);
1560 gain = (int)(atof(optarg) * 10); /* tenths of a dB */
1563 ppm_error = atoi(optarg);
1566 samp_rate = (uint32_t)atof(optarg);
1569 out_block_size = (uint32_t)atof(optarg);
1572 demod->level_limit = (uint32_t)atof(optarg);
1575 bytes_to_read = (uint32_t)atof(optarg) * 2;
1578 demod->decimation_level = (uint32_t)atof(optarg);
1584 test_mode_file = optarg;
1587 demod->signal_grabber = 1;
1590 demod->debug_mode = atoi(optarg);
1599 override_short = atoi(optarg);
1602 override_long = atoi(optarg);
1610 /* init protocols somewhat ok */
1611 register_protocol(demod, &rubicson);
1612 register_protocol(demod, &prologue);
1613 register_protocol(demod, &silvercrest);
1614 // register_protocol(demod, &generic_hx2262);
1615 // register_protocol(demod, &technoline_ws9118);
1616 register_protocol(demod, &elv_em1000);
1617 register_protocol(demod, &elv_ws2000);
1618 register_protocol(demod, &waveman);
1619 register_protocol(demod, &steffen);
1620 register_protocol(demod, &acurite5n1);
1621 register_protocol(demod, &wh2);
1623 if (argc <= optind-1) {
1626 filename = argv[optind];
1629 if(out_block_size < MINIMAL_BUF_LENGTH ||
1630 out_block_size > MAXIMAL_BUF_LENGTH ){
1632 "Output block size wrong value, falling back to default\n");
1634 "Minimal length: %u\n", MINIMAL_BUF_LENGTH);
1636 "Maximal length: %u\n", MAXIMAL_BUF_LENGTH);
1637 out_block_size = DEFAULT_BUF_LENGTH;
1640 buffer = malloc(out_block_size * sizeof(uint8_t));
1642 device_count = rtlsdr_get_device_count();
1643 if (!device_count) {
1644 fprintf(stderr, "No supported devices found.\n");
1645 if (!test_mode_file)
1649 fprintf(stderr, "Found %d device(s):\n", device_count);
1650 for (i = 0; i < device_count; i++) {
1651 rtlsdr_get_device_usb_strings(i, vendor, product, serial);
1652 fprintf(stderr, " %d: %s, %s, SN: %s\n", i, vendor, product, serial);
1654 fprintf(stderr, "\n");
1656 fprintf(stderr, "Using device %d: %s\n",
1657 dev_index, rtlsdr_get_device_name(dev_index));
1659 r = rtlsdr_open(&dev, dev_index);
1661 fprintf(stderr, "Failed to open rtlsdr device #%d.\n", dev_index);
1662 if (!test_mode_file)
1666 sigact.sa_handler = sighandler;
1667 sigemptyset(&sigact.sa_mask);
1668 sigact.sa_flags = 0;
1669 sigaction(SIGINT, &sigact, NULL);
1670 sigaction(SIGTERM, &sigact, NULL);
1671 sigaction(SIGQUIT, &sigact, NULL);
1672 sigaction(SIGPIPE, &sigact, NULL);
1674 SetConsoleCtrlHandler( (PHANDLER_ROUTINE) sighandler, TRUE );
1676 /* Set the sample rate */
1677 r = rtlsdr_set_sample_rate(dev, samp_rate);
1679 fprintf(stderr, "WARNING: Failed to set sample rate.\n");
1681 fprintf(stderr, "Sample rate set to %d.\n", rtlsdr_get_sample_rate(dev)); // Unfortunately, doesn't return real rate
1683 fprintf(stderr, "Sample rate decimation set to %d. %d->%d\n",demod->decimation_level, samp_rate, samp_rate>>demod->decimation_level);
1684 fprintf(stderr, "Bit detection level set to %d.\n", demod->level_limit);
1687 /* Enable automatic gain */
1688 r = rtlsdr_set_tuner_gain_mode(dev, 0);
1690 fprintf(stderr, "WARNING: Failed to enable automatic gain.\n");
1692 fprintf(stderr, "Tuner gain set to Auto.\n");
1694 /* Enable manual gain */
1695 r = rtlsdr_set_tuner_gain_mode(dev, 1);
1697 fprintf(stderr, "WARNING: Failed to enable manual gain.\n");
1699 /* Set the tuner gain */
1700 r = rtlsdr_set_tuner_gain(dev, gain);
1702 fprintf(stderr, "WARNING: Failed to set tuner gain.\n");
1704 fprintf(stderr, "Tuner gain set to %f dB.\n", gain/10.0);
1707 r = rtlsdr_set_freq_correction(dev, ppm_error);
1709 demod->save_data = 1;
1711 demod->save_data = 0;
1712 } else if(strcmp(filename, "-") == 0) { /* Write samples to stdout */
1713 demod->file = stdout;
1715 _setmode(_fileno(stdin), _O_BINARY);
1718 demod->file = fopen(filename, "wb");
1720 fprintf(stderr, "Failed to open %s\n", filename);
1725 if (demod->signal_grabber)
1726 demod->sg_buf = malloc(SIGNAL_GRABBER_BUFFER);
1728 if (test_mode_file) {
1730 unsigned char test_mode_buf[DEFAULT_BUF_LENGTH];
1731 fprintf(stderr, "Test mode active. Reading samples from file: %s\n",test_mode_file);
1732 test_mode = fopen(test_mode_file, "r");
1734 fprintf(stderr, "Opening file: %s failed!\n",test_mode_file);
1737 while(fread(test_mode_buf, 131072, 1, test_mode) != 0) {
1738 rtlsdr_callback(test_mode_buf, 131072, demod);
1741 //Always classify a signal at the end of the file
1743 fprintf(stderr, "Test mode file issued %d packets\n", i);
1744 fprintf(stderr, "Filter coeffs used:\n");
1745 fprintf(stderr, "a: %d %d\n", a[0], a[1]);
1746 fprintf(stderr, "b: %d %d\n", b[0], b[1]);
1750 /* Reset endpoint before we start reading from it (mandatory) */
1751 r = rtlsdr_reset_buffer(dev);
1753 fprintf(stderr, "WARNING: Failed to reset buffers.\n");
1756 fprintf(stderr, "Reading samples in sync mode...\n");
1758 r = rtlsdr_read_sync(dev, buffer, out_block_size, &n_read);
1760 fprintf(stderr, "WARNING: sync read failed.\n");
1764 if ((bytes_to_read > 0) && (bytes_to_read < (uint32_t)n_read)) {
1765 n_read = bytes_to_read;
1769 if (fwrite(buffer, 1, n_read, demod->file) != (size_t)n_read) {
1770 fprintf(stderr, "Short write, samples lost, exiting!\n");
1774 if ((uint32_t)n_read < out_block_size) {
1775 fprintf(stderr, "Short read, samples lost, exiting!\n");
1779 if (bytes_to_read > 0)
1780 bytes_to_read -= n_read;
1783 if(frequencies==0) {
1784 frequency[0] = DEFAULT_FREQUENCY;
1789 fprintf(stderr, "Reading samples in async mode...\n");
1791 /* Set the frequency */
1792 r = rtlsdr_set_center_freq(dev, frequency[frequency_current]);
1794 fprintf(stderr, "WARNING: Failed to set center freq.\n");
1796 fprintf(stderr, "Tuned to %u Hz.\n", rtlsdr_get_center_freq(dev));
1797 r = rtlsdr_read_async(dev, rtlsdr_callback, (void *)demod,
1798 DEFAULT_ASYNC_BUF_NUMBER, out_block_size);
1800 frequency_current++;
1801 if(frequency_current>frequencies-1) frequency_current=0;
1806 fprintf(stderr, "\nUser cancel, exiting...\n");
1808 fprintf(stderr, "\nLibrary error %d, exiting...\n", r);
1810 if (demod->file && (demod->file != stdout))
1811 fclose(demod->file);
1813 for (i=0 ; i<demod->r_dev_num ; i++)
1814 free(demod->r_devs[i]);
1816 if (demod->signal_grabber)
1817 free(demod->sg_buf);
1825 return r >= 0 ? r : -r;