Forked from git://github.com/merbanan/rtl_433.git
[rtl-433.git] / src / rtl_433.c
1 /*
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>
4  *
5  * Based on rtl_sdr
6  *
7  * Copyright (C) 2012 by Steve Markgraf <steve@steve-m.de>
8  *
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.
13  *
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.
18  *
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/>.
21  */
22
23
24 /* Currently this can decode the temperature and id from Rubicson sensors
25  *
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]
29  *
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
34  *
35  * The sensor can be bought at Kjell&Co
36  */
37
38 /* Prologue sensor protocol
39  *
40  * the sensor sends 36 bits 7 times, before the first packet there is a pulse sent
41  * the packets are pwm modulated
42  *
43  * the data is grouped in 9 nibles
44  * [id0] [rid0] [rid1] [data0] [temp0] [temp1] [temp2] [humi0] [humi1]
45  *
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
55  *
56  * The sensor can be bought at Clas Ohlson
57  */
58
59 #include <errno.h>
60 #include <signal.h>
61 #include <string.h>
62 #include <stdio.h>
63 #include <stdlib.h>
64 #include <time.h>
65
66 #ifndef _WIN32
67 #include <unistd.h>
68 #else
69 #include <Windows.h>
70 #include <io.h>
71 #include <fcntl.h>
72 #include "getopt/getopt.h"
73 #endif
74
75 #include "rtl-sdr.h"
76
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
92
93 static int do_exit = 0;
94 static int do_exit_async=0, frequencies=0, events=0;
95 uint32_t frequency[MAX_PROTOCOLS];
96 time_t rawtime_old;
97 int flag;
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;
105
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 */
109
110
111 typedef struct {
112     unsigned int    id;
113     char            name[256];
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]) ;
119 } r_device;
120
121 static int debug_callback(uint8_t bb[BITBUF_ROWS][BITBUF_COLS]) {
122     int i,j,k;
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]);
128         }
129         fprintf(stderr, ": ");
130         for (j=0 ; j<BITBUF_COLS ; j++) {
131             for (k=7 ; k>=0 ; k--) {
132                 if (bb[i][j] & 1<<k)
133                     fprintf(stderr, "1");
134                 else
135                     fprintf(stderr, "0");
136             }
137             fprintf(stderr, " ");
138         }
139         fprintf(stderr, "\n");
140     }
141     fprintf(stderr, "\n");
142
143     return 0;
144 }
145
146 uint8_t crc8( uint8_t *addr, uint8_t len)
147 {
148   uint8_t crc = 0;
149   
150   // Indicated changes are from reference CRC-8 function in OneWire library
151   while (len--) {
152     uint8_t inbyte = *addr++;
153     int i;
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
159     }
160   }
161   return crc;
162 }
163
164 static int wh2_callback(uint8_t bb[BITBUF_ROWS][BITBUF_COLS]) {
165     int j,k;
166
167     uint8_t payload[4];
168     uint8_t received_crc8,payload_crc8;
169
170     int wh2_id;
171     float wh2_temp;
172     float wh2_humidity;
173     
174     if (bb[0][0] != 0xFE) return 0;
175
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 );
180     
181     received_crc8 = (bb[0][5]>>1) | ((bb[0][4]&1) << 7 );
182
183     payload_crc8 = crc8(payload,4);
184     
185     if (payload_crc8 != received_crc8) return 0;
186     
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;
191     }
192     wh2_temp = wh2_temp/10;
193     
194     wh2_humidity = payload[3];
195     
196     fprintf(stdout, "SENSOR:TYPE=WH2,ID=%X,HUMIDITY=%g,TEMPERATURE=%g\n",wh2_id,wh2_humidity,wh2_temp);
197
198     return 1;
199 }
200
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 &&
204         bb[2][0] == 0xF8 &&
205         bb[3][0] == 0xF8 &&
206         bb[4][0] == 0xF8 &&
207         bb[1][1] == 0x4d &&
208         bb[2][1] == 0x4d &&
209         bb[3][1] == 0x4d &&
210         bb[4][1] == 0x4d) {
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]);
213
214         if (debug_output)
215             debug_callback(bb);
216
217         return 1;
218     }
219     return 0;
220 }
221
222 static int rubicson_callback(uint8_t bb[BITBUF_ROWS][BITBUF_COLS]) {
223     int temperature_before_dec;
224     int temperature_after_dec;
225     int16_t temp;
226     float ftemp;
227
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)) {
232
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));
236         temp = temp >> 4;
237         ftemp = (float)temp/10;
238
239         fprintf(stdout, "SENSOR:TYPE=RUBICSON,ID=%X,TEMPERATURE=%f\n",bb[0][0],ftemp);
240
241         if (debug_output)
242             debug_callback(bb);
243
244         return 1;
245     }
246     return 0;
247 }
248
249 static int prologue_callback(uint8_t bb[BITBUF_ROWS][BITBUF_COLS]) {
250     int rid;
251
252     int16_t temp2;
253     float ftemp;
254
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)) {
259
260         /* Prologue sensor */
261         temp2 = (int16_t)((uint16_t)(bb[1][2] << 8) | (bb[1][3]&0xF0));
262         temp2 = temp2 >> 4;
263         ftemp = (float)temp2/10;
264         rid = ((bb[1][0]&0x0F)<<4)|(bb[1][1]&0xF0)>>4;
265         fprintf(stdout, 
266           "SENSOR:TYPE=PROLOGUE,BUTTON=%d,BATTERY=%s,TEMPERATURE=%f,HUMIDITY=%d,CHANNEL=%d,ID=%d,RID=%02x\n",
267             bb[1][1]&0x04?1:0,
268             bb[1][1]&0x08?"Ok":"Low",
269             ftemp,
270             ((bb[1][3]&0x0F)<<4)|(bb[1][4]>>4),
271             (int)((bb[1][1]&0x03)+1),
272             (int)((bb[1][0]&0xF0)>>4),
273             rid);
274
275         if (debug_output)
276             debug_callback(bb);
277
278         return 1;
279     }
280     return 0;
281 }
282
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 */
285     int i;
286     uint8_t nb[3] = {0};
287
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;
294         }
295
296         fprintf(stdout, 
297           "BUTTON:TYPE=WAVEMAN,ID=%c,CHANNEL=%d,BUTTON=%d,STATE=%s\n",
298           'A'+nb[0],
299           (int)((nb[1]>>2)+1),
300           (int)((nb[1]&3)+1),
301           ((nb[2]==0xe) ? "on" : "off"));
302
303         if (debug_output)
304             debug_callback(bb);
305
306         return 1;
307     }
308     return 0;
309 }
310
311 static int steffen_callback(uint8_t bb[BITBUF_ROWS][BITBUF_COLS]) {
312
313     if (bb[0][0]==0x00 && ((bb[1][0]&0x07)==0x07) && bb[1][0]==bb[2][0] && bb[2][0]==bb[3][0]) {
314         
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);
316
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,");
327         else
328             fprintf(stdout, "BUTTON=UNKNOWN,");
329
330         if ((bb[1][2]&0xf0)==0xf0) {
331             fprintf(stdout, "STATE=OFF\n");
332         } else {
333             fprintf(stdout, "STATE=ON\n");
334         }
335
336         if (debug_output)
337             debug_callback(bb);
338
339         return 1;
340     }
341     return 0;
342 }
343
344
345 uint16_t AD_POP(uint8_t bb[BITBUF_COLS], uint8_t bits, uint8_t bit) {
346     uint16_t val = 0;
347     uint8_t i, byte_no, bit_no;
348     for (i=0;i<bits;i++) {
349         byte_no=   (bit+i)/8 ;
350         bit_no =7-((bit+i)%8);
351         if (bb[byte_no]&(1<<bit_no)) val = val | (1<<i);
352     }
353     return val;
354 }
355
356 static int em1000_callback(uint8_t bb[BITBUF_ROWS][BITBUF_COLS]) {
357     // based on fs20.c
358     uint8_t dec[10];
359     uint8_t bytes=0;
360     uint8_t bit=18; // preamble
361     uint8_t bb_p[14];
362     char* types[] = {"S", "?", "GZ"};
363     uint8_t checksum_calculated = 0;
364     uint8_t i;
365         uint8_t stopbit;
366         uint8_t checksum_received;
367
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];
372         else return 0;
373     }
374
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;
379         if (!stopbit) {
380 //            fprintf(stderr, "!stopbit: %i\n", i);
381             return 0;
382         }
383         checksum_calculated ^= dec[i];
384         bytes++;
385     }
386
387     // Read checksum
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);
391         return 0;
392     }
393
394 //for (i = 0; i < bytes; i++) fprintf(stderr, "%02X ", dec[i]); fprintf(stderr, "\n");
395
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);
398
399     return 1;
400 }
401
402 static int ws2000_callback(uint8_t bb[BITBUF_ROWS][BITBUF_COLS]) {
403     // based on http://www.dc3yc.privat.t-online.de/protocol.htm
404     uint8_t dec[13];
405     uint8_t nibbles=0;
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;
409     uint8_t i;
410     uint8_t stopbit;
411         uint8_t sum_received;
412
413     dec[0] = AD_POP (bb[0], 4, bit); bit+=4;
414     stopbit= AD_POP (bb[0], 1, bit); bit+=1;
415     if (!stopbit) {
416 //fprintf(stderr, "!stopbit\n");
417         return 0;
418     }
419     check_calculated ^= dec[0];
420     sum_calculated   += dec[0];
421
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;
426         if (!stopbit) {
427 //fprintf(stderr, "!stopbit %i\n", i);
428             return 0;
429         }
430         check_calculated ^= dec[i];
431         sum_calculated   += dec[i];
432         nibbles++;
433     }
434
435     if (check_calculated) {
436 //fprintf(stderr, "check_calculated (%d) != 0\n", check_calculated);
437         return 0;
438     }
439
440     // Read sum
441     sum_received = AD_POP (bb[0], 4, bit); bit+=4;
442     sum_calculated+=5;
443     sum_calculated&=0xF;
444     if (sum_received != sum_calculated) {
445 //fprintf(stderr, "sum_received (%d) != sum_calculated (%d) ", sum_received, sum_calculated);
446         return 0;
447     }
448
449 //for (i = 0; i < nibbles; i++) fprintf(stderr, "%02X ", dec[i]); fprintf(stderr, "\n");
450
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]);
452     if(dec[0]==4) {
453         fprintf(stdout, "PRESSURE=%d\n", 200+dec[10]*100+dec[9]*10+dec[8]);
454     } else {
455         fprintf(stdout, "\n");
456     }
457
458     return 1;
459 }
460
461 // ** Acurite 5n1 functions **
462
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 };
466
467 static int acurite_raincounter = 0;
468
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
471     int i;
472     int sum = 0;
473     for ( i=0; i < cols; i++) 
474         sum += row[i]; 
475     if ( sum % 256 == row[cols] ) 
476         return 1;
477     else 
478         return 0;
479 }
480
481 static int acurite_detect(uint8_t *pRow) {
482     int i;
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
488
489         if (acurite_crc(pRow, 7)) 
490             return 1;  // passes crc check
491     }
492     return 0;   
493 }
494
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;
501     return temp;
502 }
503
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;
509     return speed;
510 }
511
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];
516 }
517
518 static int acurite_getHumidity (uint8_t byte) {
519     // range: 1 to 99 %RH
520     int humidity = byte & 0x7F;
521     return humidity;
522 }
523
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;
529     return raincounter;
530 }
531
532 static int acurite5n1_callback(uint8_t bb[BITBUF_ROWS][BITBUF_COLS]) {
533     // acurite 5n1 weather sensor decoding for rtl_433
534     // Jens Jensen 2014
535     int i;
536     uint8_t *buf = NULL;
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])) {
540             buf = bb[i];
541             break; // done
542         }
543     }
544
545     if (buf) {
546         // decode packet here
547         fprintf(stdout, "SENSOR:TYPE=ACURITE");
548         if (debug_output) { 
549             for (i=0; i < 8; i++)
550                 fprintf(stderr, "%02X ", buf[i]);
551             fprintf(stderr, "CRC OK\n");
552         }
553
554         if ((buf[2] & 0x0F) == 1) {
555             // wind speed, wind direction, rainfall
556
557             float rainfall = 0.00;
558             int raincounter = 0;
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;
563             } else {
564                 // capture starting counter
565                 acurite_raincounter = raincounter;
566             }
567
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);
573
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]));
582         }
583     }
584     //if (debug_output)
585     //   debug_callback(bb);
586     return 1;
587 }
588
589
590 // timings based on samp_rate=1024000
591 r_device rubicson = {
592     /* .id             = */ 1,
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,
599 };
600
601 r_device prologue = {
602     /* .id             = */ 2,
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,
609 };
610
611 r_device silvercrest = {
612     /* .id             = */ 3,
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,
619 };
620
621 r_device tech_line_fws_500 = {
622     /* .id             = */ 4,
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,
629 };
630
631 r_device generic_hx2262 = {
632     /* .id             = */ 5,
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,
639 };
640
641 r_device technoline_ws9118 = {
642     /* .id             = */ 6,
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,
649 };
650
651
652 r_device elv_em1000 = {
653     /* .id             = */ 7,
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,
660 };
661
662 r_device elv_ws2000 = {
663     /* .id             = */ 8,
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,
670 };
671
672 r_device waveman = {
673     /* .id             = */ 6,
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,
680 };
681
682 r_device steffen = {
683     /* .id             = */ 9,
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,
690 };
691
692 r_device acurite5n1 = {
693     /* .id             = */ 10,
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,
700 };
701
702 r_device wh2 = {
703     /* .id             = */ 11,
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,
710 };
711
712 struct protocol_state {
713     int (*callback)(uint8_t bits_buffer[BITBUF_ROWS][BITBUF_COLS]);
714
715     /* bits state */
716     int bits_col_idx;
717     int bits_row_idx;
718     int bits_bit_col_idx;
719     uint8_t bits_buffer[BITBUF_ROWS][BITBUF_COLS];
720     int16_t bits_per_row[BITBUF_ROWS];
721     int     bit_rows;
722     unsigned int modulation;
723
724     /* demod state */
725     int pulse_length;
726     int pulse_count;
727     int pulse_distance;
728     int sample_counter;
729     int start_c;
730
731     int packet_present;
732     int pulse_start;
733     int real_bits;
734     int start_bit;
735     /* pwm limits */
736     int short_limit;
737     int long_limit;
738     int reset_limit;
739
740
741 };
742
743
744 struct dm_state {
745     FILE *file;
746     int save_data;
747     int32_t level_limit;
748     int32_t decimation_level;
749     int16_t filter_buffer[MAXIMAL_BUF_LENGTH+FILTER_ORDER];
750     int16_t* f_buf;
751     int analyze;
752     int debug_mode;
753
754     /* Signal grabber variables */
755     int signal_grabber;
756     int8_t* sg_buf;
757     int sg_index;
758     int sg_len;
759
760
761     /* Protocol states */
762     int r_dev_num;
763     struct protocol_state *r_devs[MAX_PROTOCOLS];
764
765 };
766
767 void usage(void)
768 {
769     fprintf(stderr,
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);
787     exit(1);
788 }
789
790 #ifdef _WIN32
791 BOOL WINAPI
792 sighandler(int signum)
793 {
794     if (CTRL_C_EVENT == signum) {
795         fprintf(stderr, "Signal caught, exiting!\n");
796         do_exit = 1;
797         rtlsdr_cancel_async(dev);
798         return TRUE;
799     }
800     return FALSE;
801 }
802 #else
803 static void sighandler(int signum)
804 {
805     fprintf(stderr, "Signal caught, exiting!\n");
806     do_exit = 1;
807     rtlsdr_cancel_async(dev);
808 }
809 #endif
810
811 /* precalculate lookup table for envelope detection */
812 static void calc_squares() {
813     int i;
814     for (i=0 ; i<256 ; i++)
815         scaled_squares[i] = (128-i) * (128-i);
816 }
817
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
822  */
823
824 static void envelope_detect(unsigned char *buf, uint32_t len, int decimate)
825 {
826     uint16_t* sample_buffer = (uint16_t*) buf;
827     unsigned int i;
828     unsigned op = 0;
829     unsigned int stride = 1<<decimate;
830
831     for (i=0 ; i<len/2 ; i+=stride) {
832         sample_buffer[op++] = scaled_squares[buf[2*i  ]]+scaled_squares[buf[2*i+1]];
833     }
834 }
835
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);
839     p->bits_col_idx = 0;
840     p->bits_bit_col_idx = 7;
841     p->bits_row_idx = 0;
842     p->bit_rows = 0;
843 }
844
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;
850         p->bits_col_idx++;
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);
854         }
855     }
856     p->bits_per_row[p->bit_rows]++;
857 }
858
859 static void demod_next_bits_packet(struct protocol_state* p) {
860     p->bits_col_idx = 0;
861     p->bits_row_idx++;
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);
866     }
867     p->bit_rows++;
868     if (p->bit_rows > BITBUF_ROWS-1)
869         p->bit_rows -=1;
870 }
871
872 static void demod_print_bits_packet(struct protocol_state* p) {
873     int i,j,k;
874
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]);
880         }
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");
886                 else
887                     fprintf(stderr, "0");
888             }
889 //            fprintf(stderr, "=0x%x ",demod->bits_buffer[i][j]);
890             fprintf(stderr, " ");
891         }
892         fprintf(stderr, "\n");
893     }
894     fprintf(stderr, "\n");
895     return;
896 }
897
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);
906
907     demod->r_devs[demod->r_dev_num] = p;
908     demod->r_dev_num++;
909
910     fprintf(stderr, "Registering protocol[%02d] %s\n",demod->r_dev_num, t_dev->name);
911
912     if (demod->r_dev_num > MAX_PROTOCOLS)
913         fprintf(stderr, "Max number of protocols reached %d\n",MAX_PROTOCOLS);
914 }
915
916
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;
929
930
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;
938
939     if (!signal_pulse_data[0][0])
940         return;
941
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];
951         }
952     }
953     t=(max+min)/2;
954     //fprintf(stderr, "\n\nMax: %d, Min: %d  t:%d\n", max, min, t);
955
956     delta = (max - min)*(max-min);
957
958     //TODO use Lloyd-Max quantizer instead
959     k=1;
960     while((k < 10) && (delta > 0)) {
961         min_new = 0; count_min = 0;
962         max_new = 0; count_max = 0;
963
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];
968                     count_min++;
969                 }
970                 else {
971                     max_new = max_new + signal_pulse_data[i][2];
972                     count_max++;
973                 }
974             }
975         }
976         min_new = min_new / count_min;
977         max_new = max_new / count_max;
978
979         delta = (min - min_new)*(min - min_new) + (max - max_new)*(max - max_new);
980         min = min_new;
981         max = max_new;
982         t = (min + max)/2;
983
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);
985         k++;
986     }
987
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]);
991         }
992     }
993     /* 50% decision limit */
994     if (max/min > 1) {
995         fprintf(stderr, "Pulse coding: Short pulse length %d - Long pulse length %d\n", min, max);
996         signal_type = 2;
997     } else {
998         fprintf(stderr, "Distance coding: Pulse length %d\n", (min+max)/2);
999         signal_type = 1;
1000     }
1001     p_limit = (max+min)/2;
1002
1003     /* Initial guesses */
1004     a[0] = 1000000;
1005     a[2] = 0;
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];
1016         }
1017     }
1018     min = a[0];
1019     max = a[2];
1020     a[1] = (a[0]+a[2])/2;
1021 //    for (i=0 ; i<1 ; i++) {
1022 //        b[i] = (a[i]+a[i+1])/2;
1023 //    }
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]);
1028
1029     k=1;
1030     delta = 10000000;
1031     while((k < 10) && (delta > 0)) {
1032         for (i=0 ; i<3 ; i++) {
1033             a_new[i] = 0;
1034             a_cnt[i] = 0;
1035         }
1036
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];
1041                     a_cnt[0]++;
1042                 } else if (signal_distance_data[i] < b[1] && signal_distance_data[i] >= b[0]){
1043                     a_new[1] += signal_distance_data[i];
1044                     a_cnt[1]++;
1045                 } else if (signal_distance_data[i] >= b[1]) {
1046                     a_new[2] += signal_distance_data[i];
1047                     a_cnt[2]++;
1048                 }
1049             }
1050         }
1051
1052 //         fprintf(stderr, "Iteration %d.", k);
1053         delta = 0;
1054         for (i=0 ; i<3 ; i++) {
1055             if (a_cnt[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]);
1059             a[i] = a_new[i];
1060         }
1061 //         fprintf(stderr, " delta %d\n", delta);
1062
1063         if (a[0] < min) {
1064             a[0] = min;
1065 //             fprintf(stderr, "Fixing a[0] = %d\n", min);
1066         }
1067         if (a[2] > max) {
1068             a[0] = max;
1069 //             fprintf(stderr, "Fixing a[2] = %d\n", max);
1070         }
1071 //         if (a[1] == 0) {
1072 //             a[1] = (a[2]+a[0])/2;
1073 //             fprintf(stderr, "Fixing a[1] = %d\n", a[1]);
1074 //         }
1075
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]);
1081         }
1082 //         fprintf(stderr, "\n");
1083         k++;
1084     }
1085
1086     if (override_short) {
1087         p_limit = override_short;
1088         a[0] = override_short;
1089     }
1090
1091     if (override_long) {
1092         a[1] = override_long;
1093     }
1094
1095     if (a[1]<a[0]) {
1096         a[1]=a[0]+1;
1097     }
1098
1099     if (a[2]<a[1]*2) {
1100         a[2] = a[1]*2;
1101     }
1102
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);
1105
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);
1119                 }
1120
1121              }
1122
1123         }
1124         demod_print_bits_packet(&p);
1125     }
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);
1132                 } else {
1133 //                     fprintf(stderr, "1 [%d] %d > %d\n",i, signal_pulse_data[i][2], p_limit);
1134                     demod_add_bit(&p, 1);
1135                 }
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);
1139                 }
1140
1141
1142             }
1143         }
1144         demod_print_bits_packet(&p);
1145     }
1146
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;
1152     }
1153
1154 };
1155
1156
1157 static void pwm_analyze(struct dm_state *demod, int16_t *buf, uint32_t len)
1158 {
1159     unsigned int i;
1160
1161     for (i=0 ; i<len ; i++) {
1162         if (buf[i] > demod->level_limit) {
1163             if (!signal_start)
1164                 signal_start = counter;
1165             if (print) {
1166                 pulses_found++;
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;
1175                 print =0;
1176                 print2 = 1;
1177             }
1178         }
1179         counter++;
1180         if (buf[i] < demod->level_limit) {
1181             if (print2) {
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;
1186                 print2 = 0;
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;
1192                     goto err;
1193                 }
1194             }
1195             print = 1;
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);
1200                 pulses_found = 0;
1201                 classify_signal();
1202
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};
1207                     FILE *sgfp;
1208
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;
1214                     if (sg_idx < 0)
1215                         sg_idx = SIGNAL_GRABBER_BUFFER-demod->sg_len;
1216                     idx = (i-40000)*2;
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);
1222
1223                     if (start_pos < 0) {
1224                         start_pos = SIGNAL_GRABBER_BUFFER+start_pos;
1225                         fprintf(stderr, "restart_pos = %d\n", start_pos);
1226                     }
1227
1228                     fprintf(stderr, "*** Saving signal to file %s\n",sgf_name);
1229                     sgfp = fopen(sgf_name, "wb");
1230                     if (!sgfp) {
1231                         fprintf(stderr, "Failed to open %s\n", sgf_name);
1232                     }
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;
1237                     }
1238                     fprintf(stderr, "*** Writing data from %d, len %d\n",start_pos, wlen);
1239                     fwrite(&demod->sg_buf[start_pos], 1, wlen, sgfp);
1240
1241                     if (wrest) {
1242                         fprintf(stderr, "*** Writing data from %d, len %d\n",0, wrest);
1243                         fwrite(&demod->sg_buf[0], 1, wrest,  sgfp);
1244                     }
1245
1246                     fclose(sgfp);
1247                 }
1248                 signal_start = 0;
1249             }
1250         }
1251
1252
1253     }
1254     return;
1255
1256 err:
1257     fprintf(stderr, "To many pulses detected, probably bad input data or input parameters\n");
1258     return;
1259 }
1260
1261 /* The distance between pulses decodes into bits */
1262
1263 static void pwm_d_decode(struct dm_state *demod, struct protocol_state* p, int16_t *buf, uint32_t len) {
1264     unsigned int i;
1265
1266     for (i=0 ; i<len ; i++) {
1267         if (buf[i] > demod->level_limit) {
1268             p->pulse_count = 1;
1269             p->start_c = 1;
1270         }
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;
1275             p->pulse_count = 0;
1276         }
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);
1283             } else {
1284                 demod_next_bits_packet(p);
1285                 p->pulse_count    = 0;
1286                 p->sample_counter = 0;
1287             }
1288             p->pulse_distance = 0;
1289         }
1290         if (p->sample_counter > p->reset_limit) {
1291             p->start_c    = 0;
1292             p->sample_counter = 0;
1293             p->pulse_distance = 0;
1294             if (p->callback)
1295                 events+=p->callback(p->bits_buffer);
1296             else
1297                 demod_print_bits_packet(p);
1298
1299             demod_reset_bits_packet(p);
1300         }
1301     }
1302 }
1303
1304 /* The length of pulses decodes into bits */
1305
1306 static void pwm_p_decode(struct dm_state *demod, struct protocol_state* p, int16_t *buf, uint32_t len) {
1307     unsigned int i;
1308
1309     for (i=0 ; i<len ; i++) {
1310         if (buf[i] > demod->level_limit && !p->start_bit) {
1311             /* start bit detected */
1312             p->start_bit      = 1;
1313             p->start_c        = 1;
1314             p->sample_counter = 0;
1315 //            fprintf(stderr, "start bit pulse start detected\n");
1316         }
1317
1318         if (!p->real_bits && p->start_bit && (buf[i] < demod->level_limit)) {
1319             /* end of startbit */
1320             p->real_bits = 1;
1321 //            fprintf(stderr, "start bit pulse end detected\n");
1322         }
1323         if (p->start_c) p->sample_counter++;
1324
1325
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");
1330
1331         }
1332
1333         if (p->real_bits && p->pulse_start && (buf[i] < demod->level_limit)) {
1334             /* end of pulse */
1335
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);
1339
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);
1344             }
1345             p->sample_counter = 0;
1346             p->pulse_start    = 0;
1347         }
1348
1349         if (p->real_bits && p->pulse_length > p->long_limit) {
1350             demod_next_bits_packet(p);
1351
1352             p->start_bit = 0;
1353             p->real_bits = 0;
1354         }
1355
1356         if (p->sample_counter > p->reset_limit) {
1357             p->start_c = 0;
1358             p->sample_counter = 0;
1359             if (p->callback)
1360                 events+=p->callback(p->bits_buffer);
1361             else
1362                 demod_print_bits_packet(p);
1363             demod_reset_bits_packet(p);
1364
1365             p->start_bit = 0;
1366             p->real_bits = 0;
1367         }
1368     }
1369 }
1370
1371
1372
1373 /** Something that might look like a IIR lowpass filter
1374  *
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/
1381  */
1382
1383 static uint16_t lp_xmem[FILTER_ORDER] = {0};
1384
1385 #define F_SCALE 15
1386 #define S_CONST (1<<F_SCALE)
1387 #define FIX(x) ((int)(x*S_CONST))
1388
1389 int a[FILTER_ORDER+1] = {FIX(1.00000),FIX(0.96907)};
1390 int b[FILTER_ORDER+1] = {FIX(0.015466),FIX(0.015466)};
1391
1392 static void low_pass_filter(uint16_t *x_buf, int16_t *y_buf, uint32_t len)
1393 {
1394     unsigned int i;
1395
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);
1400     }
1401
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]);
1406 }
1407
1408
1409 static void rtlsdr_callback(unsigned char *buf, uint32_t len, void *ctx)
1410 {
1411     struct dm_state *demod = ctx;
1412     uint16_t* sbuf = (uint16_t*) buf;
1413     int i;
1414     if (demod->file || !demod->save_data) {
1415         if (do_exit || do_exit_async)
1416             return;
1417
1418         if ((bytes_to_read > 0) && (bytes_to_read < len)) {
1419             len = bytes_to_read;
1420             do_exit = 1;
1421             rtlsdr_cancel_async(dev);
1422         }
1423
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);
1427             demod->sg_len =len;
1428             demod->sg_index +=len;
1429             if (demod->sg_index+len > SIGNAL_GRABBER_BUFFER)
1430                 demod->sg_index = 0;
1431         }
1432
1433
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);
1439         }
1440         if (demod->analyze) {
1441             pwm_analyze(demod, demod->f_buf, len/2);
1442         } 
1443         {
1444             for (i=0 ; i<demod->r_dev_num ; i++) {
1445                 switch (demod->r_devs[i]->modulation) {
1446                     case OOK_PWM_D:
1447                         pwm_d_decode(demod, demod->r_devs[i], demod->f_buf, len/2);
1448                         break;
1449                     case OOK_PWM_P:
1450                         pwm_p_decode(demod, demod->r_devs[i], demod->f_buf, len/2);
1451                         break;
1452                     default:
1453                         fprintf(stderr, "Unknown modulation %d in protocol!\n", demod->r_devs[i]->modulation);
1454                 }
1455             }
1456         }
1457
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);
1462             }
1463         }
1464
1465         if (bytes_to_read > 0)
1466             bytes_to_read -= len;
1467
1468         if(frequencies>1) {
1469             time_t rawtime;
1470             time(&rawtime);
1471             if(difftime(rawtime, rawtime_old)>DEFAULT_HOP_TIME || events>=DEFAULT_HOP_EVENTS) {
1472                 rawtime_old=rawtime;
1473                 events=0;
1474                 do_exit_async=1;
1475                 rtlsdr_cancel_async(dev);
1476             }
1477         }
1478     }
1479 }
1480
1481 int main(int argc, char **argv)
1482 {
1483 #ifndef _WIN32
1484     struct sigaction sigact;
1485 #endif
1486     char *filename = NULL;
1487     char *test_mode_file = NULL;
1488     FILE *test_mode;
1489     int n_read;
1490     int r, opt;
1491     int i, gain = 0;
1492     int sync_mode = 0;
1493     int ppm_error = 0;
1494     struct dm_state* demod;
1495     uint8_t *buffer;
1496     uint32_t dev_index = 0;
1497     int frequency_current=0;
1498     uint32_t out_block_size = DEFAULT_BUF_LENGTH;
1499     int device_count;
1500     char vendor[256], product[256], serial[256];
1501
1502     demod = malloc(sizeof(struct dm_state));
1503     memset(demod,0,sizeof(struct dm_state));
1504
1505     /* initialize tables */
1506     calc_squares();
1507
1508     demod->f_buf = &demod->filter_buffer[FILTER_ORDER];
1509     demod->decimation_level = DEFAULT_DECIMATION_LEVEL;
1510     demod->level_limit      = DEFAULT_LEVEL_LIMIT;
1511
1512
1513     while ((opt = getopt(argc, argv, "x:z:p:Dtam:r:c:l:d:f:g:s:b:n:S::")) != -1) {
1514         switch (opt) {
1515         case 'd':
1516             dev_index = atoi(optarg);
1517             break;
1518         case 'f':
1519             if(frequencies<MAX_PROTOCOLS) frequency[frequencies++] = (uint32_t)atof(optarg);
1520             else fprintf(stderr, "Max number of frequencies reached %d\n",MAX_PROTOCOLS);
1521             break;
1522         case 'g':
1523             gain = (int)(atof(optarg) * 10); /* tenths of a dB */
1524             break;
1525         case 'p':
1526             ppm_error = atoi(optarg);
1527             break;
1528         case 's':
1529             samp_rate = (uint32_t)atof(optarg);
1530             break;
1531         case 'b':
1532             out_block_size = (uint32_t)atof(optarg);
1533             break;
1534         case 'l':
1535             demod->level_limit = (uint32_t)atof(optarg);
1536             break;
1537         case 'n':
1538             bytes_to_read = (uint32_t)atof(optarg) * 2;
1539             break;
1540         case 'c':
1541             demod->decimation_level = (uint32_t)atof(optarg);
1542             break;
1543         case 'a':
1544             demod->analyze = 1;
1545             break;
1546         case 'r':
1547             test_mode_file = optarg;
1548             break;
1549         case 't':
1550             demod->signal_grabber = 1;
1551             break;
1552         case 'm':
1553             demod->debug_mode = atoi(optarg);
1554             break;
1555         case 'S':
1556             sync_mode = 1;
1557             break;
1558         case 'D':
1559             debug_output = 1;
1560             break;
1561         case 'z':
1562             override_short = atoi(optarg);
1563             break;
1564         case 'x':
1565             override_long = atoi(optarg);
1566             break;
1567         default:
1568             usage();
1569             break;
1570         }
1571     }
1572
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);
1585
1586     if (argc <= optind-1) {
1587         usage();
1588     } else {
1589         filename = argv[optind];
1590     }
1591
1592     if(out_block_size < MINIMAL_BUF_LENGTH ||
1593        out_block_size > MAXIMAL_BUF_LENGTH ){
1594         fprintf(stderr,
1595             "Output block size wrong value, falling back to default\n");
1596         fprintf(stderr,
1597             "Minimal length: %u\n", MINIMAL_BUF_LENGTH);
1598         fprintf(stderr,
1599             "Maximal length: %u\n", MAXIMAL_BUF_LENGTH);
1600         out_block_size = DEFAULT_BUF_LENGTH;
1601     }
1602
1603     buffer = malloc(out_block_size * sizeof(uint8_t));
1604
1605     device_count = rtlsdr_get_device_count();
1606     if (!device_count) {
1607         fprintf(stderr, "No supported devices found.\n");
1608         if (!test_mode_file)
1609             exit(1);
1610     }
1611
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);
1616     }
1617     fprintf(stderr, "\n");
1618
1619     fprintf(stderr, "Using device %d: %s\n",
1620         dev_index, rtlsdr_get_device_name(dev_index));
1621
1622     r = rtlsdr_open(&dev, dev_index);
1623     if (r < 0) {
1624         fprintf(stderr, "Failed to open rtlsdr device #%d.\n", dev_index);
1625         if (!test_mode_file)
1626             exit(1);
1627     }
1628 #ifndef _WIN32
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);
1636 #else
1637     SetConsoleCtrlHandler( (PHANDLER_ROUTINE) sighandler, TRUE );
1638 #endif
1639     /* Set the sample rate */
1640     r = rtlsdr_set_sample_rate(dev, samp_rate);
1641     if (r < 0)
1642         fprintf(stderr, "WARNING: Failed to set sample rate.\n");
1643     else
1644         fprintf(stderr, "Sample rate set to %d.\n", rtlsdr_get_sample_rate(dev)); // Unfortunately, doesn't return real rate
1645
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);
1648
1649     if (0 == gain) {
1650          /* Enable automatic gain */
1651         r = rtlsdr_set_tuner_gain_mode(dev, 0);
1652         if (r < 0)
1653             fprintf(stderr, "WARNING: Failed to enable automatic gain.\n");
1654         else
1655             fprintf(stderr, "Tuner gain set to Auto.\n");
1656     } else {
1657         /* Enable manual gain */
1658         r = rtlsdr_set_tuner_gain_mode(dev, 1);
1659         if (r < 0)
1660             fprintf(stderr, "WARNING: Failed to enable manual gain.\n");
1661
1662         /* Set the tuner gain */
1663         r = rtlsdr_set_tuner_gain(dev, gain);
1664         if (r < 0)
1665             fprintf(stderr, "WARNING: Failed to set tuner gain.\n");
1666         else
1667             fprintf(stderr, "Tuner gain set to %f dB.\n", gain/10.0);
1668     }
1669
1670     r = rtlsdr_set_freq_correction(dev, ppm_error);
1671
1672     demod->save_data = 1;
1673     if (!filename) {
1674         demod->save_data = 0;
1675     } else if(strcmp(filename, "-") == 0) { /* Write samples to stdout */
1676         demod->file = stdout;
1677 #ifdef _WIN32
1678         _setmode(_fileno(stdin), _O_BINARY);
1679 #endif
1680     } else {
1681         demod->file = fopen(filename, "wb");
1682         if (!demod->file) {
1683             fprintf(stderr, "Failed to open %s\n", filename);
1684             goto out;
1685         }
1686     }
1687
1688     if (demod->signal_grabber)
1689         demod->sg_buf = malloc(SIGNAL_GRABBER_BUFFER);
1690
1691     if (test_mode_file) {
1692         int i = 0;
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");
1696         if (!test_mode) {
1697             fprintf(stderr, "Opening file: %s failed!\n",test_mode_file);
1698             goto out;
1699         }
1700         while(fread(test_mode_buf, 131072, 1, test_mode) != 0) {
1701             rtlsdr_callback(test_mode_buf, 131072, demod);
1702             i++;
1703         }
1704         //Always classify a signal at the end of the file
1705         classify_signal();
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]);
1710         exit(0);
1711     }
1712
1713     /* Reset endpoint before we start reading from it (mandatory) */
1714     r = rtlsdr_reset_buffer(dev);
1715     if (r < 0)
1716         fprintf(stderr, "WARNING: Failed to reset buffers.\n");
1717
1718     if (sync_mode) {
1719         fprintf(stderr, "Reading samples in sync mode...\n");
1720         while (!do_exit) {
1721             r = rtlsdr_read_sync(dev, buffer, out_block_size, &n_read);
1722             if (r < 0) {
1723                 fprintf(stderr, "WARNING: sync read failed.\n");
1724                 break;
1725             }
1726
1727             if ((bytes_to_read > 0) && (bytes_to_read < (uint32_t)n_read)) {
1728                 n_read = bytes_to_read;
1729                 do_exit = 1;
1730             }
1731
1732             if (fwrite(buffer, 1, n_read, demod->file) != (size_t)n_read) {
1733                 fprintf(stderr, "Short write, samples lost, exiting!\n");
1734                 break;
1735             }
1736
1737             if ((uint32_t)n_read < out_block_size) {
1738                 fprintf(stderr, "Short read, samples lost, exiting!\n");
1739                 break;
1740             }
1741
1742             if (bytes_to_read > 0)
1743                 bytes_to_read -= n_read;
1744         }
1745     } else {
1746         if(frequencies==0) {
1747           frequency[0] = DEFAULT_FREQUENCY;
1748           frequencies=1;
1749         } else {
1750           time(&rawtime_old);
1751         }
1752         fprintf(stderr, "Reading samples in async mode...\n");
1753         while(!do_exit) {
1754             /* Set the frequency */
1755             r = rtlsdr_set_center_freq(dev, frequency[frequency_current]);
1756             if (r < 0)
1757                 fprintf(stderr, "WARNING: Failed to set center freq.\n");
1758             else
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);
1762             do_exit_async=0;
1763             frequency_current++;
1764             if(frequency_current>frequencies-1) frequency_current=0;
1765         }
1766     }
1767
1768     if (do_exit)
1769         fprintf(stderr, "\nUser cancel, exiting...\n");
1770     else
1771         fprintf(stderr, "\nLibrary error %d, exiting...\n", r);
1772
1773     if (demod->file && (demod->file != stdout))
1774         fclose(demod->file);
1775
1776     for (i=0 ; i<demod->r_dev_num ; i++)
1777         free(demod->r_devs[i]);
1778
1779     if (demod->signal_grabber)
1780         free(demod->sg_buf);
1781
1782     if(demod)
1783         free(demod);
1784
1785     rtlsdr_close(dev);
1786     free (buffer);
1787 out:
1788     return r >= 0 ? r : -r;
1789 }