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]));
607 fprintf(stdout,",DATA=UNKNOWN\n");
611 // debug_callback(bb);
616 // timings based on samp_rate=1024000
617 r_device rubicson = {
619 /* .name = */ "Rubicson Temperature Sensor",
620 /* .modulation = */ OOK_PWM_D,
621 /* .short_limit = */ 1744/4,
622 /* .long_limit = */ 3500/4,
623 /* .reset_limit = */ 5000/4,
624 /* .json_callback = */ &rubicson_callback,
627 r_device prologue = {
629 /* .name = */ "Prologue Temperature Sensor",
630 /* .modulation = */ OOK_PWM_D,
631 /* .short_limit = */ 3500/4,
632 /* .long_limit = */ 7000/4,
633 /* .reset_limit = */ 15000/4,
634 /* .json_callback = */ &prologue_callback,
637 r_device silvercrest = {
639 /* .name = */ "Silvercrest Remote Control",
640 /* .modulation = */ OOK_PWM_P,
641 /* .short_limit = */ 600/4,
642 /* .long_limit = */ 5000/4,
643 /* .reset_limit = */ 15000/4,
644 /* .json_callback = */ &silvercrest_callback,
647 r_device tech_line_fws_500 = {
649 /* .name = */ "Tech Line FWS-500 Sensor",
650 /* .modulation = */ OOK_PWM_D,
651 /* .short_limit = */ 3500/4,
652 /* .long_limit = */ 7000/4,
653 /* .reset_limit = */ 15000/4,
654 /* .json_callback = */ &rubicson_callback,
657 r_device generic_hx2262 = {
659 /* .name = */ "Window/Door sensor",
660 /* .modulation = */ OOK_PWM_P,
661 /* .short_limit = */ 1300/4,
662 /* .long_limit = */ 10000/4,
663 /* .reset_limit = */ 40000/4,
664 /* .json_callback = */ &silvercrest_callback,
667 r_device technoline_ws9118 = {
669 /* .name = */ "Technoline WS9118",
670 /* .modulation = */ OOK_PWM_D,
671 /* .short_limit = */ 1800/4,
672 /* .long_limit = */ 3500/4,
673 /* .reset_limit = */ 15000/4,
674 /* .json_callback = */ &debug_callback,
678 r_device elv_em1000 = {
680 /* .name = */ "ELV EM 1000",
681 /* .modulation = */ OOK_PWM_D,
682 /* .short_limit = */ 750/4,
683 /* .long_limit = */ 7250/4,
684 /* .reset_limit = */ 30000/4,
685 /* .json_callback = */ &em1000_callback,
688 r_device elv_ws2000 = {
690 /* .name = */ "ELV WS 2000",
691 /* .modulation = */ OOK_PWM_D,
692 /* .short_limit = */ (602+(1155-602)/2)/4,
693 /* .long_limit = */ ((1755635-1655517)/2)/4, // no repetitions
694 /* .reset_limit = */ ((1755635-1655517)*2)/4,
695 /* .json_callback = */ &ws2000_callback,
700 /* .name = */ "Waveman Switch Transmitter",
701 /* .modulation = */ OOK_PWM_P,
702 /* .short_limit = */ 1000/4,
703 /* .long_limit = */ 8000/4,
704 /* .reset_limit = */ 30000/4,
705 /* .json_callback = */ &waveman_callback,
710 /* .name = */ "Steffen Switch Transmitter",
711 /* .modulation = */ OOK_PWM_D,
712 /* .short_limit = */ 140,
713 /* .long_limit = */ 270,
714 /* .reset_limit = */ 1500,
715 /* .json_callback = */ &steffen_callback,
718 r_device acurite5n1 = {
720 /* .name = */ "Acurite 5n1 Weather Station",
721 /* .modulation = */ OOK_PWM_P,
722 /* .short_limit = */ 75,
723 /* .long_limit = */ 220,
724 /* .reset_limit = */ 20000,
725 /* .json_callback = */ &acurite5n1_callback,
730 /* .name = */ "WH2 Weather Station",
731 /* .modulation = */ OOK_PWM_P,
732 /* .short_limit = */ 150,
733 /* .long_limit = */ 400,
734 /* .reset_limit = */ 20000,
735 /* .json_callback = */ &wh2_callback,
738 struct protocol_state {
739 int (*callback)(uint8_t bits_buffer[BITBUF_ROWS][BITBUF_COLS]);
744 int bits_bit_col_idx;
745 uint8_t bits_buffer[BITBUF_ROWS][BITBUF_COLS];
746 int16_t bits_per_row[BITBUF_ROWS];
748 unsigned int modulation;
774 int32_t decimation_level;
775 int16_t filter_buffer[MAXIMAL_BUF_LENGTH+FILTER_ORDER];
780 /* Signal grabber variables */
787 /* Protocol states */
789 struct protocol_state *r_devs[MAX_PROTOCOLS];
796 "rtl_433, an ISM band generic data receiver for RTL2832 based DVB-T receivers\n\n"
797 "Usage:\t[-d device_index (default: 0)]\n"
798 "\t[-g gain (default: 0 for auto)]\n"
799 "\t[-a analyze mode, print a textual description of the signal]\n"
800 "\t[-t signal auto save, use it together with analyze mode (-a -t)\n"
801 "\t[-l change the detection level used to determine pulses (0-3200) default: %i]\n"
802 "\t[-f [-f...] receive frequency[s], default: %i Hz]\n"
803 "\t[-s samplerate (default: %i Hz)]\n"
804 "\t[-S force sync output (default: async)]\n"
805 "\t[-r read data from file instead of from a receiver]\n"
806 "\t[-p ppm_error (default: 0)]\n"
807 "\t[-r test file name (indata)]\n"
808 "\t[-m test file mode (0 rtl_sdr data, 1 rtl_433 data)]\n"
809 "\t[-D print debug info on event\n"
810 "\t[-z override short value\n"
811 "\t[-x override long value\n"
812 "\tfilename (a '-' dumps samples to stdout)\n\n", DEFAULT_LEVEL_LIMIT, DEFAULT_FREQUENCY, DEFAULT_SAMPLE_RATE);
818 sighandler(int signum)
820 if (CTRL_C_EVENT == signum) {
821 fprintf(stderr, "Signal caught, exiting!\n");
823 rtlsdr_cancel_async(dev);
829 static void sighandler(int signum)
831 fprintf(stderr, "Signal caught, exiting!\n");
833 rtlsdr_cancel_async(dev);
837 /* precalculate lookup table for envelope detection */
838 static void calc_squares() {
840 for (i=0 ; i<256 ; i++)
841 scaled_squares[i] = (128-i) * (128-i);
844 /** This will give a noisy envelope of OOK/ASK signals
845 * Subtract the bias (-128) and get an envelope estimation
846 * The output will be written in the input buffer
847 * @returns pointer to the input buffer
850 static void envelope_detect(unsigned char *buf, uint32_t len, int decimate)
852 uint16_t* sample_buffer = (uint16_t*) buf;
855 unsigned int stride = 1<<decimate;
857 for (i=0 ; i<len/2 ; i+=stride) {
858 sample_buffer[op++] = scaled_squares[buf[2*i ]]+scaled_squares[buf[2*i+1]];
862 static void demod_reset_bits_packet(struct protocol_state* p) {
863 memset(p->bits_buffer, 0 ,BITBUF_ROWS*BITBUF_COLS);
864 memset(p->bits_per_row, 0 ,BITBUF_ROWS);
866 p->bits_bit_col_idx = 7;
871 static void demod_add_bit(struct protocol_state* p, int bit) {
872 p->bits_buffer[p->bits_row_idx][p->bits_col_idx] |= bit<<p->bits_bit_col_idx;
873 p->bits_bit_col_idx--;
874 if (p->bits_bit_col_idx<0) {
875 p->bits_bit_col_idx = 7;
877 if (p->bits_col_idx>BITBUF_COLS-1) {
878 p->bits_col_idx = BITBUF_COLS-1;
879 // fprintf(stderr, "p->bits_col_idx>%i!\n", BITBUF_COLS-1);
882 p->bits_per_row[p->bit_rows]++;
885 static void demod_next_bits_packet(struct protocol_state* p) {
888 p->bits_bit_col_idx = 7;
889 if (p->bits_row_idx>BITBUF_ROWS-1) {
890 p->bits_row_idx = BITBUF_ROWS-1;
891 //fprintf(stderr, "p->bits_row_idx>%i!\n", BITBUF_ROWS-1);
894 if (p->bit_rows > BITBUF_ROWS-1)
898 static void demod_print_bits_packet(struct protocol_state* p) {
901 fprintf(stderr, "\n");
902 for (i=0 ; i<p->bit_rows+1 ; i++) {
903 fprintf(stderr, "[%02d] {%d} ",i, p->bits_per_row[i]);
904 for (j=0 ; j<((p->bits_per_row[i]+8)/8) ; j++) {
905 fprintf(stderr, "%02x ", p->bits_buffer[i][j]);
907 fprintf(stderr, ": ");
908 for (j=0 ; j<((p->bits_per_row[i]+8)/8) ; j++) {
909 for (k=7 ; k>=0 ; k--) {
910 if (p->bits_buffer[i][j] & 1<<k)
911 fprintf(stderr, "1");
913 fprintf(stderr, "0");
915 // fprintf(stderr, "=0x%x ",demod->bits_buffer[i][j]);
916 fprintf(stderr, " ");
918 fprintf(stderr, "\n");
920 fprintf(stderr, "\n");
924 static void register_protocol(struct dm_state *demod, r_device *t_dev) {
925 struct protocol_state *p = calloc(1,sizeof(struct protocol_state));
926 p->short_limit = (float)t_dev->short_limit/((float)DEFAULT_SAMPLE_RATE/(float)samp_rate);
927 p->long_limit = (float)t_dev->long_limit /((float)DEFAULT_SAMPLE_RATE/(float)samp_rate);
928 p->reset_limit = (float)t_dev->reset_limit/((float)DEFAULT_SAMPLE_RATE/(float)samp_rate);
929 p->modulation = t_dev->modulation;
930 p->callback = t_dev->json_callback;
931 demod_reset_bits_packet(p);
933 demod->r_devs[demod->r_dev_num] = p;
936 fprintf(stderr, "Registering protocol[%02d] %s\n",demod->r_dev_num, t_dev->name);
938 if (demod->r_dev_num > MAX_PROTOCOLS)
939 fprintf(stderr, "Max number of protocols reached %d\n",MAX_PROTOCOLS);
943 static unsigned int counter = 0;
944 static unsigned int print = 1;
945 static unsigned int print2 = 0;
946 static unsigned int pulses_found = 0;
947 static unsigned int prev_pulse_start = 0;
948 static unsigned int pulse_start = 0;
949 static unsigned int pulse_end = 0;
950 static unsigned int pulse_avg = 0;
951 static unsigned int signal_start = 0;
952 static unsigned int signal_end = 0;
953 static unsigned int signal_pulse_data[4000][3] = {{0}};
954 static unsigned int signal_pulse_counter = 0;
957 static void classify_signal() {
958 unsigned int i,k, max=0, min=1000000, t;
959 unsigned int delta, count_min, count_max, min_new, max_new, p_limit;
960 unsigned int a[3], b[2], a_cnt[3], a_new[3], b_new[2];
961 unsigned int signal_distance_data[4000] = {0};
962 struct protocol_state p = {0};
963 unsigned int signal_type;
965 if (!signal_pulse_data[0][0])
968 for (i=0 ; i<1000 ; i++) {
969 if (signal_pulse_data[i][0] > 0) {
970 //fprintf(stderr, "[%03d] s: %d\t e:\t %d\t l:%d\n",
971 //i, signal_pulse_data[i][0], signal_pulse_data[i][1],
972 //signal_pulse_data[i][2]);
973 if (signal_pulse_data[i][2] > max)
974 max = signal_pulse_data[i][2];
975 if (signal_pulse_data[i][2] <= min)
976 min = signal_pulse_data[i][2];
980 //fprintf(stderr, "\n\nMax: %d, Min: %d t:%d\n", max, min, t);
982 delta = (max - min)*(max-min);
984 //TODO use Lloyd-Max quantizer instead
986 while((k < 10) && (delta > 0)) {
987 min_new = 0; count_min = 0;
988 max_new = 0; count_max = 0;
990 for (i=0 ; i < 1000 ; i++) {
991 if (signal_pulse_data[i][0] > 0) {
992 if (signal_pulse_data[i][2] < t) {
993 min_new = min_new + signal_pulse_data[i][2];
997 max_new = max_new + signal_pulse_data[i][2];
1002 min_new = min_new / count_min;
1003 max_new = max_new / count_max;
1005 delta = (min - min_new)*(min - min_new) + (max - max_new)*(max - max_new);
1010 fprintf(stderr, "Iteration %d. t: %d min: %d (%d) max: %d (%d) delta %d\n", k,t, min, count_min, max, count_max, delta);
1014 for (i=0 ; i<1000 ; i++) {
1015 if (signal_pulse_data[i][0] > 0) {
1016 //fprintf(stderr, "%d\n", signal_pulse_data[i][1]);
1019 /* 50% decision limit */
1021 fprintf(stderr, "Pulse coding: Short pulse length %d - Long pulse length %d\n", min, max);
1024 fprintf(stderr, "Distance coding: Pulse length %d\n", (min+max)/2);
1027 p_limit = (max+min)/2;
1029 /* Initial guesses */
1032 for (i=1 ; i<1000 ; i++) {
1033 if (signal_pulse_data[i][0] > 0) {
1034 // fprintf(stderr, "[%03d] s: %d\t e:\t %d\t l:%d\t d:%d\n",
1035 // i, signal_pulse_data[i][0], signal_pulse_data[i][1],
1036 // signal_pulse_data[i][2], signal_pulse_data[i][0]-signal_pulse_data[i-1][1]);
1037 signal_distance_data[i-1] = signal_pulse_data[i][0]-signal_pulse_data[i-1][1];
1038 if (signal_distance_data[i-1] > a[2])
1039 a[2] = signal_distance_data[i-1];
1040 if (signal_distance_data[i-1] <= a[0])
1041 a[0] = signal_distance_data[i-1];
1046 a[1] = (a[0]+a[2])/2;
1047 // for (i=0 ; i<1 ; i++) {
1048 // b[i] = (a[i]+a[i+1])/2;
1050 b[0] = (a[0]+a[1])/2;
1051 b[1] = (a[1]+a[2])/2;
1052 // fprintf(stderr, "a[0]: %d\t a[1]: %d\t a[2]: %d\t\n",a[0],a[1],a[2]);
1053 // fprintf(stderr, "b[0]: %d\t b[1]: %d\n",b[0],b[1]);
1057 while((k < 10) && (delta > 0)) {
1058 for (i=0 ; i<3 ; i++) {
1063 for (i=0 ; i < 1000 ; i++) {
1064 if (signal_distance_data[i] > 0) {
1065 if (signal_distance_data[i] < b[0]) {
1066 a_new[0] += signal_distance_data[i];
1068 } else if (signal_distance_data[i] < b[1] && signal_distance_data[i] >= b[0]){
1069 a_new[1] += signal_distance_data[i];
1071 } else if (signal_distance_data[i] >= b[1]) {
1072 a_new[2] += signal_distance_data[i];
1078 // fprintf(stderr, "Iteration %d.", k);
1080 for (i=0 ; i<3 ; i++) {
1082 a_new[i] /= a_cnt[i];
1083 delta += (a[i]-a_new[i])*(a[i]-a_new[i]);
1084 // fprintf(stderr, "\ta[%d]: %d (%d)", i, a_new[i], a[i]);
1087 // fprintf(stderr, " delta %d\n", delta);
1091 // fprintf(stderr, "Fixing a[0] = %d\n", min);
1095 // fprintf(stderr, "Fixing a[2] = %d\n", max);
1098 // a[1] = (a[2]+a[0])/2;
1099 // fprintf(stderr, "Fixing a[1] = %d\n", a[1]);
1102 // fprintf(stderr, "Iteration %d.", k);
1103 for (i=0 ; i<2 ; i++) {
1104 // fprintf(stderr, "\tb[%d]: (%d) ", i, b[i]);
1105 b[i] = (a[i]+a[i+1])/2;
1106 // fprintf(stderr, "%d ", b[i]);
1108 // fprintf(stderr, "\n");
1112 if (override_short) {
1113 p_limit = override_short;
1114 a[0] = override_short;
1117 if (override_long) {
1118 a[1] = override_long;
1129 fprintf(stderr, "\nShort distance: %d, long distance: %d, packet distance: %d\n",a[0],a[1],a[2]);
1130 fprintf(stderr, "\np_limit: %d\n",p_limit);
1132 demod_reset_bits_packet(&p);
1133 if (signal_type == 1) {
1134 for(i=0 ; i<1000 ; i++){
1135 if (signal_distance_data[i] > 0) {
1136 if (signal_distance_data[i] < (a[0]+a[1])/2) {
1137 // fprintf(stderr, "0 [%d] %d < %d\n",i, signal_distance_data[i], (a[0]+a[1])/2);
1138 demod_add_bit(&p, 0);
1139 } else if ((signal_distance_data[i] > (a[0]+a[1])/2) && (signal_distance_data[i] < (a[1]+a[2])/2)) {
1140 // fprintf(stderr, "0 [%d] %d > %d\n",i, signal_distance_data[i], (a[0]+a[1])/2);
1141 demod_add_bit(&p, 1);
1142 } else if (signal_distance_data[i] > (a[1]+a[2])/2) {
1143 // fprintf(stderr, "0 [%d] %d > %d\n",i, signal_distance_data[i], (a[1]+a[2])/2);
1144 demod_next_bits_packet(&p);
1150 demod_print_bits_packet(&p);
1152 if (signal_type == 2) {
1153 for(i=0 ; i<1000 ; i++){
1154 if(signal_pulse_data[i][2] > 0) {
1155 if (signal_pulse_data[i][2] < p_limit) {
1156 // fprintf(stderr, "0 [%d] %d < %d\n",i, signal_pulse_data[i][2], p_limit);
1157 demod_add_bit(&p, 0);
1159 // fprintf(stderr, "1 [%d] %d > %d\n",i, signal_pulse_data[i][2], p_limit);
1160 demod_add_bit(&p, 1);
1162 if ((signal_distance_data[i] >= (a[1]+a[2])/2)) {
1163 // fprintf(stderr, "\\n [%d] %d > %d\n",i, signal_distance_data[i], (a[1]+a[2])/2);
1164 demod_next_bits_packet(&p);
1170 demod_print_bits_packet(&p);
1173 for (i=0 ; i<1000 ; i++) {
1174 signal_pulse_data[i][0] = 0;
1175 signal_pulse_data[i][1] = 0;
1176 signal_pulse_data[i][2] = 0;
1177 signal_distance_data[i] = 0;
1183 static void pwm_analyze(struct dm_state *demod, int16_t *buf, uint32_t len)
1187 for (i=0 ; i<len ; i++) {
1188 if (buf[i] > demod->level_limit) {
1190 signal_start = counter;
1193 pulse_start = counter;
1194 signal_pulse_data[signal_pulse_counter][0] = counter;
1195 signal_pulse_data[signal_pulse_counter][1] = -1;
1196 signal_pulse_data[signal_pulse_counter][2] = -1;
1197 if (debug_output) fprintf(stderr, "pulse_distance %d\n",counter-pulse_end);
1198 if (debug_output) fprintf(stderr, "pulse_start distance %d\n",pulse_start-prev_pulse_start);
1199 if (debug_output) fprintf(stderr, "pulse_start[%d] found at sample %d, value = %d\n",pulses_found, counter, buf[i]);
1200 prev_pulse_start = pulse_start;
1206 if (buf[i] < demod->level_limit) {
1208 pulse_avg += counter-pulse_start;
1209 if (debug_output) fprintf(stderr, "pulse_end [%d] found at sample %d, pulse length = %d, pulse avg length = %d\n",
1210 pulses_found, counter, counter-pulse_start, pulse_avg/pulses_found);
1211 pulse_end = counter;
1213 signal_pulse_data[signal_pulse_counter][1] = counter;
1214 signal_pulse_data[signal_pulse_counter][2] = counter-pulse_start;
1215 signal_pulse_counter++;
1216 if (signal_pulse_counter >= 4000) {
1217 signal_pulse_counter = 0;
1222 if (signal_start && (pulse_end + 50000 < counter)) {
1223 signal_end = counter - 40000;
1224 fprintf(stderr, "*** signal_start = %d, signal_end = %d\n",signal_start-10000, signal_end);
1225 fprintf(stderr, "signal_len = %d, pulses = %d\n", signal_end-(signal_start-10000), pulses_found);
1229 signal_pulse_counter = 0;
1230 if (demod->sg_buf) {
1231 int start_pos, signal_bszie, wlen, wrest=0, sg_idx, idx;
1232 char sgf_name[256] = {0};
1235 sprintf(sgf_name, "gfile%03d.data",demod->signal_grabber);
1236 demod->signal_grabber++;
1237 signal_bszie = 2*(signal_end-(signal_start-10000));
1238 signal_bszie = (131072-(signal_bszie%131072)) + signal_bszie;
1239 sg_idx = demod->sg_index-demod->sg_len;
1241 sg_idx = SIGNAL_GRABBER_BUFFER-demod->sg_len;
1243 start_pos = sg_idx+idx-signal_bszie;
1244 fprintf(stderr, "signal_bszie = %d - sg_index = %d\n", signal_bszie, demod->sg_index);
1245 fprintf(stderr, "start_pos = %d - buffer_size = %d\n", start_pos, SIGNAL_GRABBER_BUFFER);
1246 if (signal_bszie > SIGNAL_GRABBER_BUFFER)
1247 fprintf(stderr, "Signal bigger then buffer, signal = %d > buffer %d !!\n", signal_bszie, SIGNAL_GRABBER_BUFFER);
1249 if (start_pos < 0) {
1250 start_pos = SIGNAL_GRABBER_BUFFER+start_pos;
1251 fprintf(stderr, "restart_pos = %d\n", start_pos);
1254 fprintf(stderr, "*** Saving signal to file %s\n",sgf_name);
1255 sgfp = fopen(sgf_name, "wb");
1257 fprintf(stderr, "Failed to open %s\n", sgf_name);
1259 wlen = signal_bszie;
1260 if (start_pos + signal_bszie > SIGNAL_GRABBER_BUFFER) {
1261 wlen = SIGNAL_GRABBER_BUFFER - start_pos;
1262 wrest = signal_bszie - wlen;
1264 fprintf(stderr, "*** Writing data from %d, len %d\n",start_pos, wlen);
1265 fwrite(&demod->sg_buf[start_pos], 1, wlen, sgfp);
1268 fprintf(stderr, "*** Writing data from %d, len %d\n",0, wrest);
1269 fwrite(&demod->sg_buf[0], 1, wrest, sgfp);
1283 fprintf(stderr, "To many pulses detected, probably bad input data or input parameters\n");
1287 /* The distance between pulses decodes into bits */
1289 static void pwm_d_decode(struct dm_state *demod, struct protocol_state* p, int16_t *buf, uint32_t len) {
1292 for (i=0 ; i<len ; i++) {
1293 if (buf[i] > demod->level_limit) {
1297 if (p->pulse_count && (buf[i] < demod->level_limit)) {
1298 p->pulse_length = 0;
1299 p->pulse_distance = 1;
1300 p->sample_counter = 0;
1303 if (p->start_c) p->sample_counter++;
1304 if (p->pulse_distance && (buf[i] > demod->level_limit)) {
1305 if (p->sample_counter < p->short_limit) {
1306 demod_add_bit(p, 0);
1307 } else if (p->sample_counter < p->long_limit) {
1308 demod_add_bit(p, 1);
1310 demod_next_bits_packet(p);
1312 p->sample_counter = 0;
1314 p->pulse_distance = 0;
1316 if (p->sample_counter > p->reset_limit) {
1318 p->sample_counter = 0;
1319 p->pulse_distance = 0;
1321 events+=p->callback(p->bits_buffer);
1323 demod_print_bits_packet(p);
1325 demod_reset_bits_packet(p);
1330 /* The length of pulses decodes into bits */
1332 static void pwm_p_decode(struct dm_state *demod, struct protocol_state* p, int16_t *buf, uint32_t len) {
1335 for (i=0 ; i<len ; i++) {
1336 if (buf[i] > demod->level_limit && !p->start_bit) {
1337 /* start bit detected */
1340 p->sample_counter = 0;
1342 fprintf(stderr, "start bit pulse start detected\n");
1345 if (!p->real_bits && p->start_bit && (buf[i] < demod->level_limit)) {
1346 /* end of startbit */
1348 p->pulse_length = 0;
1350 fprintf(stderr, "start bit pulse end detected\n");
1352 if (p->start_c) p->sample_counter++;
1355 if (!p->pulse_start && p->real_bits && (buf[i] > demod->level_limit)) {
1356 /* save the pulse start, it will never be zero */
1357 p->pulse_start = p->sample_counter;
1359 fprintf(stderr, "real bit pulse start detected\n");
1363 if (p->real_bits && p->pulse_start && (buf[i] < demod->level_limit)) {
1366 p->pulse_length = p->sample_counter-p->pulse_start;
1368 fprintf(stderr, "real bit pulse end detected %d\n", p->pulse_length);
1369 fprintf(stderr, "space duration %d\n", p->sample_counter);
1372 if (p->pulse_length <= p->short_limit) {
1374 fprintf(stderr, "1 received\n");
1375 demod_add_bit(p, 1);
1378 fprintf(stderr, "0 received\n");
1379 demod_add_bit(p, 0);
1381 p->sample_counter = 0;
1385 if (p->real_bits && (p->pulse_length > p->long_limit)) {
1387 fprintf(stderr, "End of packet\n");
1388 demod_next_bits_packet(p);
1394 if (p->sample_counter > p->reset_limit) {
1396 p->sample_counter = 0;
1398 events+=p->callback(p->bits_buffer);
1400 demod_print_bits_packet(p);
1401 demod_reset_bits_packet(p);
1411 /** Something that might look like a IIR lowpass filter
1413 * [b,a] = butter(1, 0.01) -> quantizes nicely thus suitable for fixed point
1414 * Q1.15*Q15.0 = Q16.15
1415 * Q16.15>>1 = Q15.14
1416 * Q15.14 + Q15.14 + Q15.14 could possibly overflow to 17.14
1417 * but the b coeffs are small so it wont happen
1418 * Q15.14>>14 = Q15.0 \o/
1421 static uint16_t lp_xmem[FILTER_ORDER] = {0};
1424 #define S_CONST (1<<F_SCALE)
1425 #define FIX(x) ((int)(x*S_CONST))
1427 int a[FILTER_ORDER+1] = {FIX(1.00000),FIX(0.96907)};
1428 int b[FILTER_ORDER+1] = {FIX(0.015466),FIX(0.015466)};
1430 static void low_pass_filter(uint16_t *x_buf, int16_t *y_buf, uint32_t len)
1434 /* Calculate first sample */
1435 y_buf[0] = ((a[1]*y_buf[-1]>>1) + (b[0]*x_buf[0]>>1) + (b[1]*lp_xmem[0]>>1)) >> (F_SCALE-1);
1436 for (i=1 ; i<len ; i++) {
1437 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);
1440 /* Save last sample */
1441 memcpy(lp_xmem, &x_buf[len-1-FILTER_ORDER], FILTER_ORDER*sizeof(int16_t));
1442 memcpy(&y_buf[-FILTER_ORDER], &y_buf[len-1-FILTER_ORDER], FILTER_ORDER*sizeof(int16_t));
1443 //fprintf(stderr, "%d\n", y_buf[0]);
1447 static void rtlsdr_callback(unsigned char *buf, uint32_t len, void *ctx)
1449 struct dm_state *demod = ctx;
1450 uint16_t* sbuf = (uint16_t*) buf;
1452 if (demod->file || !demod->save_data) {
1453 if (do_exit || do_exit_async)
1456 if ((bytes_to_read > 0) && (bytes_to_read < len)) {
1457 len = bytes_to_read;
1459 rtlsdr_cancel_async(dev);
1462 if (demod->signal_grabber) {
1463 //fprintf(stderr, "[%d] sg_index - len %d\n", demod->sg_index, len );
1464 memcpy(&demod->sg_buf[demod->sg_index], buf, len);
1466 demod->sg_index +=len;
1467 if (demod->sg_index+len > SIGNAL_GRABBER_BUFFER)
1468 demod->sg_index = 0;
1472 if (demod->debug_mode == 0) {
1473 envelope_detect(buf, len, demod->decimation_level);
1474 low_pass_filter(sbuf, demod->f_buf, len>>(demod->decimation_level+1));
1475 } else if (demod->debug_mode == 1){
1476 memcpy(demod->f_buf, buf, len);
1478 if (demod->analyze) {
1479 pwm_analyze(demod, demod->f_buf, len/2);
1482 for (i=0 ; i<demod->r_dev_num ; i++) {
1483 switch (demod->r_devs[i]->modulation) {
1485 pwm_d_decode(demod, demod->r_devs[i], demod->f_buf, len/2);
1488 pwm_p_decode(demod, demod->r_devs[i], demod->f_buf, len/2);
1491 fprintf(stderr, "Unknown modulation %d in protocol!\n", demod->r_devs[i]->modulation);
1497 if (demod->save_data) {
1498 if (fwrite(demod->f_buf, 1, len>>demod->decimation_level, demod->file) != len>>demod->decimation_level) {
1499 fprintf(stderr, "Short write, samples lost, exiting!\n");
1500 rtlsdr_cancel_async(dev);
1504 if (bytes_to_read > 0)
1505 bytes_to_read -= len;
1510 if(difftime(rawtime, rawtime_old)>DEFAULT_HOP_TIME || events>=DEFAULT_HOP_EVENTS) {
1511 rawtime_old=rawtime;
1514 rtlsdr_cancel_async(dev);
1520 int main(int argc, char **argv)
1523 struct sigaction sigact;
1525 char *filename = NULL;
1526 char *test_mode_file = NULL;
1533 struct dm_state* demod;
1535 uint32_t dev_index = 0;
1536 int frequency_current=0;
1537 uint32_t out_block_size = DEFAULT_BUF_LENGTH;
1539 char vendor[256], product[256], serial[256];
1541 demod = malloc(sizeof(struct dm_state));
1542 memset(demod,0,sizeof(struct dm_state));
1544 /* initialize tables */
1547 demod->f_buf = &demod->filter_buffer[FILTER_ORDER];
1548 demod->decimation_level = DEFAULT_DECIMATION_LEVEL;
1549 demod->level_limit = DEFAULT_LEVEL_LIMIT;
1552 while ((opt = getopt(argc, argv, "x:z:p:Dtam:r:c:l:d:f:g:s:b:n:S::")) != -1) {
1555 dev_index = atoi(optarg);
1558 if(frequencies<MAX_PROTOCOLS) frequency[frequencies++] = (uint32_t)atof(optarg);
1559 else fprintf(stderr, "Max number of frequencies reached %d\n",MAX_PROTOCOLS);
1562 gain = (int)(atof(optarg) * 10); /* tenths of a dB */
1565 ppm_error = atoi(optarg);
1568 samp_rate = (uint32_t)atof(optarg);
1571 out_block_size = (uint32_t)atof(optarg);
1574 demod->level_limit = (uint32_t)atof(optarg);
1577 bytes_to_read = (uint32_t)atof(optarg) * 2;
1580 demod->decimation_level = (uint32_t)atof(optarg);
1586 test_mode_file = optarg;
1589 demod->signal_grabber = 1;
1592 demod->debug_mode = atoi(optarg);
1601 override_short = atoi(optarg);
1604 override_long = atoi(optarg);
1612 /* init protocols somewhat ok */
1613 register_protocol(demod, &rubicson);
1614 register_protocol(demod, &prologue);
1615 register_protocol(demod, &silvercrest);
1616 // register_protocol(demod, &generic_hx2262);
1617 // register_protocol(demod, &technoline_ws9118);
1618 register_protocol(demod, &elv_em1000);
1619 register_protocol(demod, &elv_ws2000);
1620 register_protocol(demod, &waveman);
1621 register_protocol(demod, &steffen);
1622 register_protocol(demod, &acurite5n1);
1623 register_protocol(demod, &wh2);
1625 if (argc <= optind-1) {
1628 filename = argv[optind];
1631 if(out_block_size < MINIMAL_BUF_LENGTH ||
1632 out_block_size > MAXIMAL_BUF_LENGTH ){
1634 "Output block size wrong value, falling back to default\n");
1636 "Minimal length: %u\n", MINIMAL_BUF_LENGTH);
1638 "Maximal length: %u\n", MAXIMAL_BUF_LENGTH);
1639 out_block_size = DEFAULT_BUF_LENGTH;
1642 buffer = malloc(out_block_size * sizeof(uint8_t));
1644 device_count = rtlsdr_get_device_count();
1645 if (!device_count) {
1646 fprintf(stderr, "No supported devices found.\n");
1647 if (!test_mode_file)
1651 fprintf(stderr, "Found %d device(s):\n", device_count);
1652 for (i = 0; i < device_count; i++) {
1653 rtlsdr_get_device_usb_strings(i, vendor, product, serial);
1654 fprintf(stderr, " %d: %s, %s, SN: %s\n", i, vendor, product, serial);
1656 fprintf(stderr, "\n");
1658 fprintf(stderr, "Using device %d: %s\n",
1659 dev_index, rtlsdr_get_device_name(dev_index));
1661 r = rtlsdr_open(&dev, dev_index);
1663 fprintf(stderr, "Failed to open rtlsdr device #%d.\n", dev_index);
1664 if (!test_mode_file)
1668 sigact.sa_handler = sighandler;
1669 sigemptyset(&sigact.sa_mask);
1670 sigact.sa_flags = 0;
1671 sigaction(SIGINT, &sigact, NULL);
1672 sigaction(SIGTERM, &sigact, NULL);
1673 sigaction(SIGQUIT, &sigact, NULL);
1674 sigaction(SIGPIPE, &sigact, NULL);
1676 SetConsoleCtrlHandler( (PHANDLER_ROUTINE) sighandler, TRUE );
1678 /* Set the sample rate */
1679 r = rtlsdr_set_sample_rate(dev, samp_rate);
1681 fprintf(stderr, "WARNING: Failed to set sample rate.\n");
1683 fprintf(stderr, "Sample rate set to %d.\n", rtlsdr_get_sample_rate(dev)); // Unfortunately, doesn't return real rate
1685 fprintf(stderr, "Sample rate decimation set to %d. %d->%d\n",demod->decimation_level, samp_rate, samp_rate>>demod->decimation_level);
1686 fprintf(stderr, "Bit detection level set to %d.\n", demod->level_limit);
1689 /* Enable automatic gain */
1690 r = rtlsdr_set_tuner_gain_mode(dev, 0);
1692 fprintf(stderr, "WARNING: Failed to enable automatic gain.\n");
1694 fprintf(stderr, "Tuner gain set to Auto.\n");
1696 /* Enable manual gain */
1697 r = rtlsdr_set_tuner_gain_mode(dev, 1);
1699 fprintf(stderr, "WARNING: Failed to enable manual gain.\n");
1701 /* Set the tuner gain */
1702 r = rtlsdr_set_tuner_gain(dev, gain);
1704 fprintf(stderr, "WARNING: Failed to set tuner gain.\n");
1706 fprintf(stderr, "Tuner gain set to %f dB.\n", gain/10.0);
1709 r = rtlsdr_set_freq_correction(dev, ppm_error);
1711 demod->save_data = 1;
1713 demod->save_data = 0;
1714 } else if(strcmp(filename, "-") == 0) { /* Write samples to stdout */
1715 demod->file = stdout;
1717 _setmode(_fileno(stdin), _O_BINARY);
1720 demod->file = fopen(filename, "wb");
1722 fprintf(stderr, "Failed to open %s\n", filename);
1727 if (demod->signal_grabber)
1728 demod->sg_buf = malloc(SIGNAL_GRABBER_BUFFER);
1730 if (test_mode_file) {
1732 unsigned char test_mode_buf[DEFAULT_BUF_LENGTH];
1733 fprintf(stderr, "Test mode active. Reading samples from file: %s\n",test_mode_file);
1734 test_mode = fopen(test_mode_file, "r");
1736 fprintf(stderr, "Opening file: %s failed!\n",test_mode_file);
1739 while(fread(test_mode_buf, 131072, 1, test_mode) != 0) {
1740 rtlsdr_callback(test_mode_buf, 131072, demod);
1743 //Always classify a signal at the end of the file
1745 fprintf(stderr, "Test mode file issued %d packets\n", i);
1746 fprintf(stderr, "Filter coeffs used:\n");
1747 fprintf(stderr, "a: %d %d\n", a[0], a[1]);
1748 fprintf(stderr, "b: %d %d\n", b[0], b[1]);
1752 /* Reset endpoint before we start reading from it (mandatory) */
1753 r = rtlsdr_reset_buffer(dev);
1755 fprintf(stderr, "WARNING: Failed to reset buffers.\n");
1758 fprintf(stderr, "Reading samples in sync mode...\n");
1760 r = rtlsdr_read_sync(dev, buffer, out_block_size, &n_read);
1762 fprintf(stderr, "WARNING: sync read failed.\n");
1766 if ((bytes_to_read > 0) && (bytes_to_read < (uint32_t)n_read)) {
1767 n_read = bytes_to_read;
1771 if (fwrite(buffer, 1, n_read, demod->file) != (size_t)n_read) {
1772 fprintf(stderr, "Short write, samples lost, exiting!\n");
1776 if ((uint32_t)n_read < out_block_size) {
1777 fprintf(stderr, "Short read, samples lost, exiting!\n");
1781 if (bytes_to_read > 0)
1782 bytes_to_read -= n_read;
1785 if(frequencies==0) {
1786 frequency[0] = DEFAULT_FREQUENCY;
1791 fprintf(stderr, "Reading samples in async mode...\n");
1793 /* Set the frequency */
1794 r = rtlsdr_set_center_freq(dev, frequency[frequency_current]);
1796 fprintf(stderr, "WARNING: Failed to set center freq.\n");
1798 fprintf(stderr, "Tuned to %u Hz.\n", rtlsdr_get_center_freq(dev));
1799 r = rtlsdr_read_async(dev, rtlsdr_callback, (void *)demod,
1800 DEFAULT_ASYNC_BUF_NUMBER, out_block_size);
1802 frequency_current++;
1803 if(frequency_current>frequencies-1) frequency_current=0;
1808 fprintf(stderr, "\nUser cancel, exiting...\n");
1810 fprintf(stderr, "\nLibrary error %d, exiting...\n", r);
1812 if (demod->file && (demod->file != stdout))
1813 fclose(demod->file);
1815 for (i=0 ; i<demod->r_dev_num ; i++)
1816 free(demod->r_devs[i]);
1818 if (demod->signal_grabber)
1819 free(demod->sg_buf);
1827 return r >= 0 ? r : -r;