Bug fixes
[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 void printBits(size_t const size, void const * const ptr)
165 {
166     unsigned char *b = (unsigned char*) ptr;
167     unsigned char byte;
168     int i, j;
169             
170     for (i=0;i<size;i++) {
171         
172         fprintf(stderr,"%2x:",b[i]);
173         
174         for (j=0;j<7;j++) {
175             byte = b[i] & (1<<j);
176             byte >>= j;
177             fprintf(stderr,"%u", byte);
178         }
179         fprintf(stderr," ");
180     }
181     fprintf(stderr,"\n");
182 }
183
184 static int wh2_callback(uint8_t bb[BITBUF_ROWS][BITBUF_COLS]) {
185     int i,j,k;
186
187     uint8_t payload[4];
188     int received_crc8,payload_crc8;
189
190     int wh2_id;
191     float wh2_temp;
192     float wh2_humidity;
193     
194     if (bb[0][0] != 0xFE) return 0;
195
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 );
200     
201     received_crc8 = (bb[0][5]>>1) | ((bb[0][4]&1) << 7 );
202
203     payload_crc8 = crc8(payload,4);
204     
205     if (payload_crc8 != received_crc8) {
206         fprintf(stderr,"Bad WH2 payload CRC, skipping...\n");
207         return 0;
208     }
209     
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;
214     }
215     wh2_temp = wh2_temp/10;
216     
217     wh2_humidity = payload[3];
218     
219     fprintf(stdout, "SENSOR:TYPE=WH2,ID=%X,HUMIDITY=%g,TEMPERATURE=%g\n",wh2_id,wh2_humidity,wh2_temp);
220
221     return 1;
222         
223 }
224
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 &&
228         bb[2][0] == 0xF8 &&
229         bb[3][0] == 0xF8 &&
230         bb[4][0] == 0xF8 &&
231         bb[1][1] == 0x4d &&
232         bb[2][1] == 0x4d &&
233         bb[3][1] == 0x4d &&
234         bb[4][1] == 0x4d) {
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]);
237
238         if (debug_output)
239             debug_callback(bb);
240
241         return 1;
242     }
243     return 0;
244 }
245
246 static int rubicson_callback(uint8_t bb[BITBUF_ROWS][BITBUF_COLS]) {
247     int temperature_before_dec;
248     int temperature_after_dec;
249     int16_t temp;
250     float ftemp;
251
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)) {
256
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));
260         temp = temp >> 4;
261         ftemp = (float)temp/10;
262
263         fprintf(stdout, "SENSOR:TYPE=RUBICSON,ID=%X,TEMPERATURE=%f\n",bb[0][0],ftemp);
264
265         if (debug_output)
266             debug_callback(bb);
267
268         return 1;
269     }
270     return 0;
271 }
272
273 static int prologue_callback(uint8_t bb[BITBUF_ROWS][BITBUF_COLS]) {
274     int rid;
275
276     int16_t temp2;
277     float ftemp;
278
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)) {
283
284         /* Prologue sensor */
285         temp2 = (int16_t)((uint16_t)(bb[1][2] << 8) | (bb[1][3]&0xF0));
286         temp2 = temp2 >> 4;
287         ftemp = (float)temp2/10;
288         rid = ((bb[1][0]&0x0F)<<4)|(bb[1][1]&0xF0)>>4;
289         fprintf(stdout, 
290           "SENSOR:TYPE=PROLOGUE,BUTTON=%d,BATTERY=%s,TEMPERATURE=%f,HUMIDITY=%d,CHANNEL=%d,ID=%d,RID=%02x\n",
291             bb[1][1]&0x04?1:0,
292             bb[1][1]&0x08?"Ok":"Low",
293             ftemp,
294             ((bb[1][3]&0x0F)<<4)|(bb[1][4]>>4),
295             (int)((bb[1][1]&0x03)+1),
296             (int)((bb[1][0]&0xF0)>>4),
297             rid);
298
299         if (debug_output)
300             debug_callback(bb);
301
302         return 1;
303     }
304     return 0;
305 }
306
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 */
309     int i;
310     uint8_t nb[3] = {0};
311
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;
318         }
319
320         fprintf(stdout, 
321           "BUTTON:TYPE=WAVEMAN,ID=%c,CHANNEL=%d,BUTTON=%d,STATE=%s\n",
322           'A'+nb[0],
323           (int)((nb[1]>>2)+1),
324           (int)((nb[1]&3)+1),
325           ((nb[2]==0xe) ? "on" : "off"));
326
327         if (debug_output)
328             debug_callback(bb);
329
330         return 1;
331     }
332     return 0;
333 }
334
335 static int steffen_callback(uint8_t bb[BITBUF_ROWS][BITBUF_COLS]) {
336
337     if (bb[0][0]==0x00 && ((bb[1][0]&0x07)==0x07) && bb[1][0]==bb[2][0] && bb[2][0]==bb[3][0]) {
338         
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);
340
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,");
351         else
352             fprintf(stdout, "BUTTON=UNKNOWN,");
353
354         if ((bb[1][2]&0xf0)==0xf0) {
355             fprintf(stdout, "STATE=OFF\n");
356         } else {
357             fprintf(stdout, "STATE=ON\n");
358         }
359
360         if (debug_output)
361             debug_callback(bb);
362
363         return 1;
364     }
365     return 0;
366 }
367
368
369 uint16_t AD_POP(uint8_t bb[BITBUF_COLS], uint8_t bits, uint8_t bit) {
370     uint16_t val = 0;
371     uint8_t i, byte_no, bit_no;
372     for (i=0;i<bits;i++) {
373         byte_no=   (bit+i)/8 ;
374         bit_no =7-((bit+i)%8);
375         if (bb[byte_no]&(1<<bit_no)) val = val | (1<<i);
376     }
377     return val;
378 }
379
380 static int em1000_callback(uint8_t bb[BITBUF_ROWS][BITBUF_COLS]) {
381     // based on fs20.c
382     uint8_t dec[10];
383     uint8_t bytes=0;
384     uint8_t bit=18; // preamble
385     uint8_t bb_p[14];
386     char* types[] = {"S", "?", "GZ"};
387     uint8_t checksum_calculated = 0;
388     uint8_t i;
389         uint8_t stopbit;
390         uint8_t checksum_received;
391
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];
396         else return 0;
397     }
398
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;
403         if (!stopbit) {
404 //            fprintf(stderr, "!stopbit: %i\n", i);
405             return 0;
406         }
407         checksum_calculated ^= dec[i];
408         bytes++;
409     }
410
411     // Read checksum
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);
415         return 0;
416     }
417
418 //for (i = 0; i < bytes; i++) fprintf(stderr, "%02X ", dec[i]); fprintf(stderr, "\n");
419
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);
422
423     return 1;
424 }
425
426 static int ws2000_callback(uint8_t bb[BITBUF_ROWS][BITBUF_COLS]) {
427     // based on http://www.dc3yc.privat.t-online.de/protocol.htm
428     uint8_t dec[13];
429     uint8_t nibbles=0;
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;
433     uint8_t i;
434     uint8_t stopbit;
435         uint8_t sum_received;
436
437     dec[0] = AD_POP (bb[0], 4, bit); bit+=4;
438     stopbit= AD_POP (bb[0], 1, bit); bit+=1;
439     if (!stopbit) {
440 //fprintf(stderr, "!stopbit\n");
441         return 0;
442     }
443     check_calculated ^= dec[0];
444     sum_calculated   += dec[0];
445
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;
450         if (!stopbit) {
451 //fprintf(stderr, "!stopbit %i\n", i);
452             return 0;
453         }
454         check_calculated ^= dec[i];
455         sum_calculated   += dec[i];
456         nibbles++;
457     }
458
459     if (check_calculated) {
460 //fprintf(stderr, "check_calculated (%d) != 0\n", check_calculated);
461         return 0;
462     }
463
464     // Read sum
465     sum_received = AD_POP (bb[0], 4, bit); bit+=4;
466     sum_calculated+=5;
467     sum_calculated&=0xF;
468     if (sum_received != sum_calculated) {
469 //fprintf(stderr, "sum_received (%d) != sum_calculated (%d) ", sum_received, sum_calculated);
470         return 0;
471     }
472
473 //for (i = 0; i < nibbles; i++) fprintf(stderr, "%02X ", dec[i]); fprintf(stderr, "\n");
474
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]);
476     if(dec[0]==4) {
477         fprintf(stdout, "PRESSURE=%d\n", 200+dec[10]*100+dec[9]*10+dec[8]);
478     } else {
479         fprintf(stdout, "\n");
480     }
481
482     return 1;
483 }
484
485 // ** Acurite 5n1 functions **
486
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 };
490
491 static int acurite_raincounter = 0;
492
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
495     int i;
496     int sum = 0;
497     for ( i=0; i < cols; i++) 
498         sum += row[i]; 
499     if ( sum % 256 == row[cols] ) 
500         return 1;
501     else 
502         return 0;
503 }
504
505 static int acurite_detect(uint8_t *pRow) {
506     int i;
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
512
513         if (acurite_crc(pRow, 7)) 
514             return 1;  // passes crc check
515     }
516     return 0;   
517 }
518
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;
525     return temp;
526 }
527
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;
533     return speed;
534 }
535
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];
540 }
541
542 static int acurite_getHumidity (uint8_t byte) {
543     // range: 1 to 99 %RH
544     int humidity = byte & 0x7F;
545     return humidity;
546 }
547
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;
553     return raincounter;
554 }
555
556 static int acurite5n1_callback(uint8_t bb[BITBUF_ROWS][BITBUF_COLS]) {
557     // acurite 5n1 weather sensor decoding for rtl_433
558     // Jens Jensen 2014
559     int i;
560     uint8_t *buf = NULL;
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])) {
564             buf = bb[i];
565             break; // done
566         }
567     }
568
569     if (buf) {
570         // decode packet here
571         fprintf(stdout, "SENSOR:TYPE=ACURITE");
572         if (debug_output) { 
573             for (i=0; i < 8; i++)
574                 fprintf(stderr, "%02X ", buf[i]);
575             fprintf(stderr, "CRC OK\n");
576         }
577
578         if ((buf[2] & 0x0F) == 1) {
579             // wind speed, wind direction, rainfall
580
581             float rainfall = 0.00;
582             int raincounter = 0;
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;
587             } else {
588                 // capture starting counter
589                 acurite_raincounter = raincounter;
590             }
591
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);
597
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]));
606         }
607     }
608     //if (debug_output)
609     //   debug_callback(bb);
610     return 1;
611 }
612
613
614 // timings based on samp_rate=1024000
615 r_device rubicson = {
616     /* .id             = */ 1,
617     /* .name           = */ "Rubicson Temperature Sensor",
618     /* .modulation     = */ OOK_PWM_D,
619     /* .short_limit    = */ 1744/4,
620     /* .long_limit     = */ 3500/4,
621     /* .reset_limit    = */ 5000/4,
622     /* .json_callback  = */ &rubicson_callback,
623 };
624
625 r_device prologue = {
626     /* .id             = */ 2,
627     /* .name           = */ "Prologue Temperature Sensor",
628     /* .modulation     = */ OOK_PWM_D,
629     /* .short_limit    = */ 3500/4,
630     /* .long_limit     = */ 7000/4,
631     /* .reset_limit    = */ 15000/4,
632     /* .json_callback  = */ &prologue_callback,
633 };
634
635 r_device silvercrest = {
636     /* .id             = */ 3,
637     /* .name           = */ "Silvercrest Remote Control",
638     /* .modulation     = */ OOK_PWM_P,
639     /* .short_limit    = */ 600/4,
640     /* .long_limit     = */ 5000/4,
641     /* .reset_limit    = */ 15000/4,
642     /* .json_callback  = */ &silvercrest_callback,
643 };
644
645 r_device tech_line_fws_500 = {
646     /* .id             = */ 4,
647     /* .name           = */ "Tech Line FWS-500 Sensor",
648     /* .modulation     = */ OOK_PWM_D,
649     /* .short_limit    = */ 3500/4,
650     /* .long_limit     = */ 7000/4,
651     /* .reset_limit    = */ 15000/4,
652     /* .json_callback  = */ &rubicson_callback,
653 };
654
655 r_device generic_hx2262 = {
656     /* .id             = */ 5,
657     /* .name           = */ "Window/Door sensor",
658     /* .modulation     = */ OOK_PWM_P,
659     /* .short_limit    = */ 1300/4,
660     /* .long_limit     = */ 10000/4,
661     /* .reset_limit    = */ 40000/4,
662     /* .json_callback  = */ &silvercrest_callback,
663 };
664
665 r_device technoline_ws9118 = {
666     /* .id             = */ 6,
667     /* .name           = */ "Technoline WS9118",
668     /* .modulation     = */ OOK_PWM_D,
669     /* .short_limit    = */ 1800/4,
670     /* .long_limit     = */ 3500/4,
671     /* .reset_limit    = */ 15000/4,
672     /* .json_callback  = */ &debug_callback,
673 };
674
675
676 r_device elv_em1000 = {
677     /* .id             = */ 7,
678     /* .name           = */ "ELV EM 1000",
679     /* .modulation     = */ OOK_PWM_D,
680     /* .short_limit    = */ 750/4,
681     /* .long_limit     = */ 7250/4,
682     /* .reset_limit    = */ 30000/4,
683     /* .json_callback  = */ &em1000_callback,
684 };
685
686 r_device elv_ws2000 = {
687     /* .id             = */ 8,
688     /* .name           = */ "ELV WS 2000",
689     /* .modulation     = */ OOK_PWM_D,
690     /* .short_limit    = */ (602+(1155-602)/2)/4,
691     /* .long_limit     = */ ((1755635-1655517)/2)/4, // no repetitions
692     /* .reset_limit    = */ ((1755635-1655517)*2)/4,
693     /* .json_callback  = */ &ws2000_callback,
694 };
695
696 r_device waveman = {
697     /* .id             = */ 6,
698     /* .name           = */ "Waveman Switch Transmitter",
699     /* .modulation     = */ OOK_PWM_P,
700     /* .short_limit    = */ 1000/4,
701     /* .long_limit     = */ 8000/4,
702     /* .reset_limit    = */ 30000/4,
703     /* .json_callback  = */ &waveman_callback,
704 };
705
706 r_device steffen = {
707     /* .id             = */ 9,
708     /* .name           = */ "Steffen Switch Transmitter",
709     /* .modulation     = */ OOK_PWM_D,
710     /* .short_limit    = */ 140,
711     /* .long_limit     = */ 270,
712     /* .reset_limit    = */ 1500,
713     /* .json_callback  = */ &steffen_callback,
714 };
715
716 r_device acurite5n1 = {
717     /* .id             = */ 10,
718     /* .name           = */ "Acurite 5n1 Weather Station",
719     /* .modulation     = */ OOK_PWM_P,
720     /* .short_limit    = */ 75,
721     /* .long_limit     = */ 220, 
722     /* .reset_limit    = */ 20000,
723     /* .json_callback  = */ &acurite5n1_callback,
724 };
725
726 r_device wh2 = {
727     /* .id             = */ 11,
728     /* .name           = */ "WH2 Weather Station",
729     /* .modulation     = */ OOK_PWM_P,
730     /* .short_limit    = */ 150,
731     /* .long_limit     = */ 400, 
732     /* .reset_limit    = */ 20000,
733     /* .json_callback  = */ &wh2_callback,
734 };
735
736 struct protocol_state {
737     int (*callback)(uint8_t bits_buffer[BITBUF_ROWS][BITBUF_COLS]);
738
739     /* bits state */
740     int bits_col_idx;
741     int bits_row_idx;
742     int bits_bit_col_idx;
743     uint8_t bits_buffer[BITBUF_ROWS][BITBUF_COLS];
744     int16_t bits_per_row[BITBUF_ROWS];
745     int     bit_rows;
746     unsigned int modulation;
747
748     /* demod state */
749     int pulse_length;
750     int pulse_count;
751     int pulse_distance;
752     int sample_counter;
753     int start_c;
754
755     int packet_present;
756     int pulse_start;
757     int real_bits;
758     int start_bit;
759     /* pwm limits */
760     int short_limit;
761     int long_limit;
762     int reset_limit;
763
764
765 };
766
767
768 struct dm_state {
769     FILE *file;
770     int save_data;
771     int32_t level_limit;
772     int32_t decimation_level;
773     int16_t filter_buffer[MAXIMAL_BUF_LENGTH+FILTER_ORDER];
774     int16_t* f_buf;
775     int analyze;
776     int debug_mode;
777
778     /* Signal grabber variables */
779     int signal_grabber;
780     int8_t* sg_buf;
781     int sg_index;
782     int sg_len;
783
784
785     /* Protocol states */
786     int r_dev_num;
787     struct protocol_state *r_devs[MAX_PROTOCOLS];
788
789 };
790
791 void usage(void)
792 {
793     fprintf(stderr,
794         "rtl_433, an ISM band generic data receiver for RTL2832 based DVB-T receivers\n\n"
795         "Usage:\t[-d device_index (default: 0)]\n"
796         "\t[-g gain (default: 0 for auto)]\n"
797         "\t[-a analyze mode, print a textual description of the signal]\n"
798         "\t[-t signal auto save, use it together with analyze mode (-a -t)\n"
799         "\t[-l change the detection level used to determine pulses (0-3200) default: %i]\n"
800         "\t[-f [-f...] receive frequency[s], default: %i Hz]\n"
801         "\t[-s samplerate (default: %i Hz)]\n"
802         "\t[-S force sync output (default: async)]\n"
803         "\t[-r read data from file instead of from a receiver]\n"
804         "\t[-p ppm_error (default: 0)]\n"
805         "\t[-r test file name (indata)]\n"
806         "\t[-m test file mode (0 rtl_sdr data, 1 rtl_433 data)]\n"
807         "\t[-D print debug info on event\n"
808         "\t[-z override short value\n"
809         "\t[-x override long value\n"
810         "\tfilename (a '-' dumps samples to stdout)\n\n", DEFAULT_LEVEL_LIMIT, DEFAULT_FREQUENCY, DEFAULT_SAMPLE_RATE);
811     exit(1);
812 }
813
814 #ifdef _WIN32
815 BOOL WINAPI
816 sighandler(int signum)
817 {
818     if (CTRL_C_EVENT == signum) {
819         fprintf(stderr, "Signal caught, exiting!\n");
820         do_exit = 1;
821         rtlsdr_cancel_async(dev);
822         return TRUE;
823     }
824     return FALSE;
825 }
826 #else
827 static void sighandler(int signum)
828 {
829     fprintf(stderr, "Signal caught, exiting!\n");
830     do_exit = 1;
831     rtlsdr_cancel_async(dev);
832 }
833 #endif
834
835 /* precalculate lookup table for envelope detection */
836 static void calc_squares() {
837     int i;
838     for (i=0 ; i<256 ; i++)
839         scaled_squares[i] = (128-i) * (128-i);
840 }
841
842 /** This will give a noisy envelope of OOK/ASK signals
843  *  Subtract the bias (-128) and get an envelope estimation
844  *  The output will be written in the input buffer
845  *  @returns   pointer to the input buffer
846  */
847
848 static void envelope_detect(unsigned char *buf, uint32_t len, int decimate)
849 {
850     uint16_t* sample_buffer = (uint16_t*) buf;
851     unsigned int i;
852     unsigned op = 0;
853     unsigned int stride = 1<<decimate;
854
855     for (i=0 ; i<len/2 ; i+=stride) {
856         sample_buffer[op++] = scaled_squares[buf[2*i  ]]+scaled_squares[buf[2*i+1]];
857     }
858 }
859
860 static void demod_reset_bits_packet(struct protocol_state* p) {
861     memset(p->bits_buffer, 0 ,BITBUF_ROWS*BITBUF_COLS);
862     memset(p->bits_per_row, 0 ,BITBUF_ROWS);
863     p->bits_col_idx = 0;
864     p->bits_bit_col_idx = 7;
865     p->bits_row_idx = 0;
866     p->bit_rows = 0;
867 }
868
869 static void demod_add_bit(struct protocol_state* p, int bit) {
870     p->bits_buffer[p->bits_row_idx][p->bits_col_idx] |= bit<<p->bits_bit_col_idx;
871     p->bits_bit_col_idx--;
872     if (p->bits_bit_col_idx<0) {
873         p->bits_bit_col_idx = 7;
874         p->bits_col_idx++;
875         if (p->bits_col_idx>BITBUF_COLS-1) {
876             p->bits_col_idx = BITBUF_COLS-1;
877 //            fprintf(stderr, "p->bits_col_idx>%i!\n", BITBUF_COLS-1);
878         }
879     }
880     p->bits_per_row[p->bit_rows]++;
881 }
882
883 static void demod_next_bits_packet(struct protocol_state* p) {
884     p->bits_col_idx = 0;
885     p->bits_row_idx++;
886     p->bits_bit_col_idx = 7;
887     if (p->bits_row_idx>BITBUF_ROWS-1) {
888         p->bits_row_idx = BITBUF_ROWS-1;
889         //fprintf(stderr, "p->bits_row_idx>%i!\n", BITBUF_ROWS-1);
890     }
891     p->bit_rows++;
892     if (p->bit_rows > BITBUF_ROWS-1)
893         p->bit_rows -=1;
894 }
895
896 static void demod_print_bits_packet(struct protocol_state* p) {
897     int i,j,k;
898
899     fprintf(stderr, "\n");
900     for (i=0 ; i<p->bit_rows+1 ; i++) {
901         fprintf(stderr, "[%02d] {%d} ",i, p->bits_per_row[i]);
902         for (j=0 ; j<((p->bits_per_row[i]+8)/8) ; j++) {
903                 fprintf(stderr, "%02x ", p->bits_buffer[i][j]);
904         }
905         fprintf(stderr, ": ");
906         for (j=0 ; j<((p->bits_per_row[i]+8)/8) ; j++) {
907             for (k=7 ; k>=0 ; k--) {
908                 if (p->bits_buffer[i][j] & 1<<k)
909                     fprintf(stderr, "1");
910                 else
911                     fprintf(stderr, "0");
912             }
913 //            fprintf(stderr, "=0x%x ",demod->bits_buffer[i][j]);
914             fprintf(stderr, " ");
915         }
916         fprintf(stderr, "\n");
917     }
918     fprintf(stderr, "\n");
919     return;
920 }
921
922 static void register_protocol(struct dm_state *demod, r_device *t_dev) {
923     struct protocol_state *p =  calloc(1,sizeof(struct protocol_state));
924     p->short_limit  = (float)t_dev->short_limit/((float)DEFAULT_SAMPLE_RATE/(float)samp_rate);
925     p->long_limit   = (float)t_dev->long_limit /((float)DEFAULT_SAMPLE_RATE/(float)samp_rate);
926     p->reset_limit  = (float)t_dev->reset_limit/((float)DEFAULT_SAMPLE_RATE/(float)samp_rate);
927     p->modulation   = t_dev->modulation;
928     p->callback     = t_dev->json_callback;
929     demod_reset_bits_packet(p);
930
931     demod->r_devs[demod->r_dev_num] = p;
932     demod->r_dev_num++;
933
934     fprintf(stderr, "Registering protocol[%02d] %s\n",demod->r_dev_num, t_dev->name);
935
936     if (demod->r_dev_num > MAX_PROTOCOLS)
937         fprintf(stderr, "Max number of protocols reached %d\n",MAX_PROTOCOLS);
938 }
939
940
941 static unsigned int counter = 0;
942 static unsigned int print = 1;
943 static unsigned int print2 = 0;
944 static unsigned int pulses_found = 0;
945 static unsigned int prev_pulse_start = 0;
946 static unsigned int pulse_start = 0;
947 static unsigned int pulse_end = 0;
948 static unsigned int pulse_avg = 0;
949 static unsigned int signal_start = 0;
950 static unsigned int signal_end   = 0;
951 static unsigned int signal_pulse_data[4000][3] = {{0}};
952 static unsigned int signal_pulse_counter = 0;
953
954
955 static void classify_signal() {
956     unsigned int i,k, max=0, min=1000000, t;
957     unsigned int delta, count_min, count_max, min_new, max_new, p_limit;
958     unsigned int a[3], b[2], a_cnt[3], a_new[3], b_new[2];
959     unsigned int signal_distance_data[4000] = {0};
960     struct protocol_state p = {0};
961     unsigned int signal_type;
962
963     if (!signal_pulse_data[0][0])
964         return;
965
966     for (i=0 ; i<1000 ; i++) {
967         if (signal_pulse_data[i][0] > 0) {
968             //fprintf(stderr, "[%03d] s: %d\t  e:\t %d\t l:%d\n",
969             //i, signal_pulse_data[i][0], signal_pulse_data[i][1],
970             //signal_pulse_data[i][2]);
971             if (signal_pulse_data[i][2] > max)
972                 max = signal_pulse_data[i][2];
973             if (signal_pulse_data[i][2] <= min)
974                 min = signal_pulse_data[i][2];
975         }
976     }
977     t=(max+min)/2;
978     //fprintf(stderr, "\n\nMax: %d, Min: %d  t:%d\n", max, min, t);
979
980     delta = (max - min)*(max-min);
981
982     //TODO use Lloyd-Max quantizer instead
983     k=1;
984     while((k < 10) && (delta > 0)) {
985         min_new = 0; count_min = 0;
986         max_new = 0; count_max = 0;
987
988         for (i=0 ; i < 1000 ; i++) {
989             if (signal_pulse_data[i][0] > 0) {
990                 if (signal_pulse_data[i][2] < t) {
991                     min_new = min_new + signal_pulse_data[i][2];
992                     count_min++;
993                 }
994                 else {
995                     max_new = max_new + signal_pulse_data[i][2];
996                     count_max++;
997                 }
998             }
999         }
1000         min_new = min_new / count_min;
1001         max_new = max_new / count_max;
1002
1003         delta = (min - min_new)*(min - min_new) + (max - max_new)*(max - max_new);
1004         min = min_new;
1005         max = max_new;
1006         t = (min + max)/2;
1007
1008         fprintf(stderr, "Iteration %d. t: %d    min: %d (%d)    max: %d (%d)    delta %d\n", k,t, min, count_min, max, count_max, delta);
1009         k++;
1010     }
1011
1012     for (i=0 ; i<1000 ; i++) {
1013         if (signal_pulse_data[i][0] > 0) {
1014             //fprintf(stderr, "%d\n", signal_pulse_data[i][1]);
1015         }
1016     }
1017     /* 50% decision limit */
1018     if (max/min > 1) {
1019         fprintf(stderr, "Pulse coding: Short pulse length %d - Long pulse length %d\n", min, max);
1020         signal_type = 2;
1021     } else {
1022         fprintf(stderr, "Distance coding: Pulse length %d\n", (min+max)/2);
1023         signal_type = 1;
1024     }
1025     p_limit = (max+min)/2;
1026
1027     /* Initial guesses */
1028     a[0] = 1000000;
1029     a[2] = 0;
1030     for (i=1 ; i<1000 ; i++) {
1031         if (signal_pulse_data[i][0] > 0) {
1032 //               fprintf(stderr, "[%03d] s: %d\t  e:\t %d\t l:%d\t  d:%d\n",
1033 //               i, signal_pulse_data[i][0], signal_pulse_data[i][1],
1034 //               signal_pulse_data[i][2], signal_pulse_data[i][0]-signal_pulse_data[i-1][1]);
1035             signal_distance_data[i-1] = signal_pulse_data[i][0]-signal_pulse_data[i-1][1];
1036             if (signal_distance_data[i-1] > a[2])
1037                 a[2] = signal_distance_data[i-1];
1038             if (signal_distance_data[i-1] <= a[0])
1039                 a[0] = signal_distance_data[i-1];
1040         }
1041     }
1042     min = a[0];
1043     max = a[2];
1044     a[1] = (a[0]+a[2])/2;
1045 //    for (i=0 ; i<1 ; i++) {
1046 //        b[i] = (a[i]+a[i+1])/2;
1047 //    }
1048     b[0] = (a[0]+a[1])/2;
1049     b[1] = (a[1]+a[2])/2;
1050 //     fprintf(stderr, "a[0]: %d\t a[1]: %d\t a[2]: %d\t\n",a[0],a[1],a[2]);
1051 //     fprintf(stderr, "b[0]: %d\t b[1]: %d\n",b[0],b[1]);
1052
1053     k=1;
1054     delta = 10000000;
1055     while((k < 10) && (delta > 0)) {
1056         for (i=0 ; i<3 ; i++) {
1057             a_new[i] = 0;
1058             a_cnt[i] = 0;
1059         }
1060
1061         for (i=0 ; i < 1000 ; i++) {
1062             if (signal_distance_data[i] > 0) {
1063                 if (signal_distance_data[i] < b[0]) {
1064                     a_new[0] += signal_distance_data[i];
1065                     a_cnt[0]++;
1066                 } else if (signal_distance_data[i] < b[1] && signal_distance_data[i] >= b[0]){
1067                     a_new[1] += signal_distance_data[i];
1068                     a_cnt[1]++;
1069                 } else if (signal_distance_data[i] >= b[1]) {
1070                     a_new[2] += signal_distance_data[i];
1071                     a_cnt[2]++;
1072                 }
1073             }
1074         }
1075
1076 //         fprintf(stderr, "Iteration %d.", k);
1077         delta = 0;
1078         for (i=0 ; i<3 ; i++) {
1079             if (a_cnt[i])
1080                 a_new[i] /= a_cnt[i];
1081             delta += (a[i]-a_new[i])*(a[i]-a_new[i]);
1082 //             fprintf(stderr, "\ta[%d]: %d (%d)", i, a_new[i], a[i]);
1083             a[i] = a_new[i];
1084         }
1085 //         fprintf(stderr, " delta %d\n", delta);
1086
1087         if (a[0] < min) {
1088             a[0] = min;
1089 //             fprintf(stderr, "Fixing a[0] = %d\n", min);
1090         }
1091         if (a[2] > max) {
1092             a[0] = max;
1093 //             fprintf(stderr, "Fixing a[2] = %d\n", max);
1094         }
1095 //         if (a[1] == 0) {
1096 //             a[1] = (a[2]+a[0])/2;
1097 //             fprintf(stderr, "Fixing a[1] = %d\n", a[1]);
1098 //         }
1099
1100 //         fprintf(stderr, "Iteration %d.", k);
1101         for (i=0 ; i<2 ; i++) {
1102 //             fprintf(stderr, "\tb[%d]: (%d) ", i, b[i]);
1103             b[i] = (a[i]+a[i+1])/2;
1104 //             fprintf(stderr, "%d  ", b[i]);
1105         }
1106 //         fprintf(stderr, "\n");
1107         k++;
1108     }
1109
1110     if (override_short) {
1111         p_limit = override_short;
1112         a[0] = override_short;
1113     }
1114
1115     if (override_long) {
1116         a[1] = override_long;
1117     }
1118
1119     if (a[1]<a[0]) {
1120         a[1]=a[0]+1;
1121     }
1122
1123     if (a[2]<a[1]*2) {
1124         a[2] = a[1]*2;
1125     }
1126
1127     fprintf(stderr, "\nShort distance: %d, long distance: %d, packet distance: %d\n",a[0],a[1],a[2]);
1128     fprintf(stderr, "\np_limit: %d\n",p_limit);
1129
1130     demod_reset_bits_packet(&p);
1131     if (signal_type == 1) {
1132         for(i=0 ; i<1000 ; i++){
1133             if (signal_distance_data[i] > 0) {
1134                 if (signal_distance_data[i] < (a[0]+a[1])/2) {
1135 //                     fprintf(stderr, "0 [%d] %d < %d\n",i, signal_distance_data[i], (a[0]+a[1])/2);
1136                     demod_add_bit(&p, 0);
1137                 } else if ((signal_distance_data[i] > (a[0]+a[1])/2) && (signal_distance_data[i] < (a[1]+a[2])/2)) {
1138 //                     fprintf(stderr, "0 [%d] %d > %d\n",i, signal_distance_data[i], (a[0]+a[1])/2);
1139                     demod_add_bit(&p, 1);
1140                 } else if (signal_distance_data[i] > (a[1]+a[2])/2) {
1141 //                     fprintf(stderr, "0 [%d] %d > %d\n",i, signal_distance_data[i], (a[1]+a[2])/2);
1142                     demod_next_bits_packet(&p);
1143                 }
1144
1145              }
1146
1147         }
1148         demod_print_bits_packet(&p);
1149     }
1150     if (signal_type == 2) {
1151         for(i=0 ; i<1000 ; i++){
1152             if(signal_pulse_data[i][2] > 0) {
1153                 if (signal_pulse_data[i][2] < p_limit) {
1154 //                     fprintf(stderr, "0 [%d] %d < %d\n",i, signal_pulse_data[i][2], p_limit);
1155                     demod_add_bit(&p, 0);
1156                 } else {
1157 //                     fprintf(stderr, "1 [%d] %d > %d\n",i, signal_pulse_data[i][2], p_limit);
1158                     demod_add_bit(&p, 1);
1159                 }
1160                 if ((signal_distance_data[i] >= (a[1]+a[2])/2)) {
1161 //                     fprintf(stderr, "\\n [%d] %d > %d\n",i, signal_distance_data[i], (a[1]+a[2])/2);
1162                     demod_next_bits_packet(&p);
1163                 }
1164
1165
1166             }
1167         }
1168         demod_print_bits_packet(&p);
1169     }
1170
1171     for (i=0 ; i<1000 ; i++) {
1172         signal_pulse_data[i][0] = 0;
1173         signal_pulse_data[i][1] = 0;
1174         signal_pulse_data[i][2] = 0;
1175         signal_distance_data[i] = 0;
1176     }
1177
1178 };
1179
1180
1181 static void pwm_analyze(struct dm_state *demod, int16_t *buf, uint32_t len)
1182 {
1183     unsigned int i;
1184
1185     for (i=0 ; i<len ; i++) {
1186         if (buf[i] > demod->level_limit) {
1187             if (!signal_start)
1188                 signal_start = counter;
1189             if (print) {
1190                 pulses_found++;
1191                 pulse_start = counter;
1192                 signal_pulse_data[signal_pulse_counter][0] = counter;
1193                 signal_pulse_data[signal_pulse_counter][1] = -1;
1194                 signal_pulse_data[signal_pulse_counter][2] = -1;
1195                 if (debug_output) fprintf(stderr, "pulse_distance %d\n",counter-pulse_end);
1196                 if (debug_output) fprintf(stderr, "pulse_start distance %d\n",pulse_start-prev_pulse_start);
1197                 if (debug_output) fprintf(stderr, "pulse_start[%d] found at sample %d, value = %d\n",pulses_found, counter, buf[i]);
1198                 prev_pulse_start = pulse_start;
1199                 print =0;
1200                 print2 = 1;
1201             }
1202         }
1203         counter++;
1204         if (buf[i] < demod->level_limit) {
1205             if (print2) {
1206                 pulse_avg += counter-pulse_start;
1207                 if (debug_output) fprintf(stderr, "pulse_end  [%d] found at sample %d, pulse length = %d, pulse avg length = %d\n",
1208                         pulses_found, counter, counter-pulse_start, pulse_avg/pulses_found);
1209                 pulse_end = counter;
1210                 print2 = 0;
1211                 signal_pulse_data[signal_pulse_counter][1] = counter;
1212                 signal_pulse_data[signal_pulse_counter][2] = counter-pulse_start;
1213                 signal_pulse_counter++;
1214                 if (signal_pulse_counter >= 4000) {
1215                     signal_pulse_counter = 0;
1216                     goto err;
1217                 }
1218             }
1219             print = 1;
1220             if (signal_start && (pulse_end + 50000 < counter)) {
1221                 signal_end = counter - 40000;
1222                 fprintf(stderr, "*** signal_start = %d, signal_end = %d\n",signal_start-10000, signal_end);
1223                 fprintf(stderr, "signal_len = %d,  pulses = %d\n", signal_end-(signal_start-10000), pulses_found);
1224                 pulses_found = 0;
1225                 classify_signal();
1226
1227                 signal_pulse_counter = 0;
1228                 if (demod->sg_buf) {
1229                     int start_pos, signal_bszie, wlen, wrest=0, sg_idx, idx;
1230                     char sgf_name[256] = {0};
1231                     FILE *sgfp;
1232
1233                     sprintf(sgf_name, "gfile%03d.data",demod->signal_grabber);
1234                     demod->signal_grabber++;
1235                     signal_bszie = 2*(signal_end-(signal_start-10000));
1236                     signal_bszie = (131072-(signal_bszie%131072)) + signal_bszie;
1237                     sg_idx = demod->sg_index-demod->sg_len;
1238                     if (sg_idx < 0)
1239                         sg_idx = SIGNAL_GRABBER_BUFFER-demod->sg_len;
1240                     idx = (i-40000)*2;
1241                     start_pos = sg_idx+idx-signal_bszie;
1242                     fprintf(stderr, "signal_bszie = %d  -      sg_index = %d\n", signal_bszie, demod->sg_index);
1243                     fprintf(stderr, "start_pos    = %d  -   buffer_size = %d\n", start_pos, SIGNAL_GRABBER_BUFFER);
1244                     if (signal_bszie > SIGNAL_GRABBER_BUFFER)
1245                         fprintf(stderr, "Signal bigger then buffer, signal = %d > buffer %d !!\n", signal_bszie, SIGNAL_GRABBER_BUFFER);
1246
1247                     if (start_pos < 0) {
1248                         start_pos = SIGNAL_GRABBER_BUFFER+start_pos;
1249                         fprintf(stderr, "restart_pos = %d\n", start_pos);
1250                     }
1251
1252                     fprintf(stderr, "*** Saving signal to file %s\n",sgf_name);
1253                     sgfp = fopen(sgf_name, "wb");
1254                     if (!sgfp) {
1255                         fprintf(stderr, "Failed to open %s\n", sgf_name);
1256                     }
1257                     wlen = signal_bszie;
1258                     if (start_pos + signal_bszie > SIGNAL_GRABBER_BUFFER) {
1259                         wlen = SIGNAL_GRABBER_BUFFER - start_pos;
1260                         wrest = signal_bszie - wlen;
1261                     }
1262                     fprintf(stderr, "*** Writing data from %d, len %d\n",start_pos, wlen);
1263                     fwrite(&demod->sg_buf[start_pos], 1, wlen, sgfp);
1264
1265                     if (wrest) {
1266                         fprintf(stderr, "*** Writing data from %d, len %d\n",0, wrest);
1267                         fwrite(&demod->sg_buf[0], 1, wrest,  sgfp);
1268                     }
1269
1270                     fclose(sgfp);
1271                 }
1272                 signal_start = 0;
1273             }
1274         }
1275
1276
1277     }
1278     return;
1279
1280 err:
1281     fprintf(stderr, "To many pulses detected, probably bad input data or input parameters\n");
1282     return;
1283 }
1284
1285 /* The distance between pulses decodes into bits */
1286
1287 static void pwm_d_decode(struct dm_state *demod, struct protocol_state* p, int16_t *buf, uint32_t len) {
1288     unsigned int i;
1289
1290     for (i=0 ; i<len ; i++) {
1291         if (buf[i] > demod->level_limit) {
1292             p->pulse_count = 1;
1293             p->start_c = 1;
1294         }
1295         if (p->pulse_count && (buf[i] < demod->level_limit)) {
1296             p->pulse_length = 0;
1297             p->pulse_distance = 1;
1298             p->sample_counter = 0;
1299             p->pulse_count = 0;
1300         }
1301         if (p->start_c) p->sample_counter++;
1302         if (p->pulse_distance && (buf[i] > demod->level_limit)) {
1303             if (p->sample_counter < p->short_limit) {
1304                 demod_add_bit(p, 0);
1305             } else if (p->sample_counter < p->long_limit) {
1306                 demod_add_bit(p, 1);
1307             } else {
1308                 demod_next_bits_packet(p);
1309                 p->pulse_count    = 0;
1310                 p->sample_counter = 0;
1311             }
1312             p->pulse_distance = 0;
1313         }
1314         if (p->sample_counter > p->reset_limit) {
1315             p->start_c    = 0;
1316             p->sample_counter = 0;
1317             p->pulse_distance = 0;
1318             if (p->callback)
1319                 events+=p->callback(p->bits_buffer);
1320             else
1321                 demod_print_bits_packet(p);
1322
1323             demod_reset_bits_packet(p);
1324         }
1325     }
1326 }
1327
1328 /* The length of pulses decodes into bits */
1329
1330 static void pwm_p_decode(struct dm_state *demod, struct protocol_state* p, int16_t *buf, uint32_t len) {
1331     unsigned int i;
1332     
1333     for (i=0 ; i<len ; i++) {
1334         if (buf[i] > demod->level_limit && !p->start_bit) {
1335             /* start bit detected */
1336             p->start_bit      = 1;
1337             p->start_c        = 1;
1338             p->sample_counter = 0;
1339             if (debug_output) 
1340               fprintf(stderr, "start bit pulse start detected\n");
1341         }
1342
1343         if (!p->real_bits && p->start_bit && (buf[i] < demod->level_limit)) {
1344             /* end of startbit */
1345             p->real_bits = 1;
1346             p->pulse_length = 0;
1347             if (debug_output)
1348               fprintf(stderr, "start bit pulse end detected\n");
1349         }
1350         if (p->start_c) p->sample_counter++;
1351
1352
1353         if (!p->pulse_start && p->real_bits && (buf[i] > demod->level_limit)) {
1354             /* save the pulse start, it will never be zero */
1355             p->pulse_start = p->sample_counter;
1356             if (debug_output)
1357               fprintf(stderr, "real bit pulse start detected\n");
1358
1359         }
1360
1361         if (p->real_bits && p->pulse_start && (buf[i] < demod->level_limit)) {
1362             /* end of pulse */
1363
1364             p->pulse_length = p->sample_counter-p->pulse_start;
1365             if (debug_output) {
1366               fprintf(stderr, "real bit pulse end detected %d\n", p->pulse_length);
1367               fprintf(stderr, "space duration %d\n", p->sample_counter);
1368             }
1369
1370             if (p->pulse_length <= p->short_limit) {
1371                 if (debug_output)
1372                   fprintf(stderr, "1 received\n");
1373                 demod_add_bit(p, 1);
1374             } else {
1375                 if (debug_output)
1376                   fprintf(stderr, "0 received\n");
1377                 demod_add_bit(p, 0);
1378             }
1379             p->sample_counter = 0;
1380             p->pulse_start    = 0;
1381         }
1382
1383         if (p->real_bits && (p->pulse_length > p->long_limit)) {
1384             if (debug_output)
1385               fprintf(stderr, "End of packet\n");
1386             demod_next_bits_packet(p);
1387
1388             p->start_bit = 0;
1389             p->real_bits = 0;
1390         }
1391
1392         if (p->sample_counter > p->reset_limit) {
1393             p->start_c = 0;
1394             p->sample_counter = 0;
1395             if (p->callback)
1396                 events+=p->callback(p->bits_buffer);
1397             else
1398                 demod_print_bits_packet(p);
1399             demod_reset_bits_packet(p);
1400
1401             p->start_bit = 0;
1402             p->real_bits = 0;
1403         }
1404     }
1405 }
1406
1407
1408
1409 /** Something that might look like a IIR lowpass filter
1410  *
1411  *  [b,a] = butter(1, 0.01) ->  quantizes nicely thus suitable for fixed point
1412  *  Q1.15*Q15.0 = Q16.15
1413  *  Q16.15>>1 = Q15.14
1414  *  Q15.14 + Q15.14 + Q15.14 could possibly overflow to 17.14
1415  *  but the b coeffs are small so it wont happen
1416  *  Q15.14>>14 = Q15.0 \o/
1417  */
1418
1419 static uint16_t lp_xmem[FILTER_ORDER] = {0};
1420
1421 #define F_SCALE 15
1422 #define S_CONST (1<<F_SCALE)
1423 #define FIX(x) ((int)(x*S_CONST))
1424
1425 int a[FILTER_ORDER+1] = {FIX(1.00000),FIX(0.96907)};
1426 int b[FILTER_ORDER+1] = {FIX(0.015466),FIX(0.015466)};
1427
1428 static void low_pass_filter(uint16_t *x_buf, int16_t *y_buf, uint32_t len)
1429 {
1430     unsigned int i;
1431
1432     /* Calculate first sample */
1433     y_buf[0] = ((a[1]*y_buf[-1]>>1) + (b[0]*x_buf[0]>>1) + (b[1]*lp_xmem[0]>>1)) >> (F_SCALE-1);
1434     for (i=1 ; i<len ; i++) {
1435         y_buf[i] = ((a[1]*y_buf[i-1]>>1) + (b[0]*x_buf[i]>>1) + (b[1]*x_buf[i-1]>>1)) >> (F_SCALE-1);
1436     }
1437
1438     /* Save last sample */
1439     memcpy(lp_xmem, &x_buf[len-1-FILTER_ORDER], FILTER_ORDER*sizeof(int16_t));
1440     memcpy(&y_buf[-FILTER_ORDER], &y_buf[len-1-FILTER_ORDER], FILTER_ORDER*sizeof(int16_t));
1441     //fprintf(stderr, "%d\n", y_buf[0]);
1442 }
1443
1444
1445 static void rtlsdr_callback(unsigned char *buf, uint32_t len, void *ctx)
1446 {
1447     struct dm_state *demod = ctx;
1448     uint16_t* sbuf = (uint16_t*) buf;
1449     int i;
1450     if (demod->file || !demod->save_data) {
1451         if (do_exit || do_exit_async)
1452             return;
1453
1454         if ((bytes_to_read > 0) && (bytes_to_read < len)) {
1455             len = bytes_to_read;
1456             do_exit = 1;
1457             rtlsdr_cancel_async(dev);
1458         }
1459
1460         if (demod->signal_grabber) {
1461             //fprintf(stderr, "[%d] sg_index - len %d\n", demod->sg_index, len );
1462             memcpy(&demod->sg_buf[demod->sg_index], buf, len);
1463             demod->sg_len =len;
1464             demod->sg_index +=len;
1465             if (demod->sg_index+len > SIGNAL_GRABBER_BUFFER)
1466                 demod->sg_index = 0;
1467         }
1468
1469
1470         if (demod->debug_mode == 0) {
1471             envelope_detect(buf, len, demod->decimation_level);
1472             low_pass_filter(sbuf, demod->f_buf, len>>(demod->decimation_level+1));
1473         } else if (demod->debug_mode == 1){
1474             memcpy(demod->f_buf, buf, len);
1475         }
1476         if (demod->analyze) {
1477             pwm_analyze(demod, demod->f_buf, len/2);
1478         } 
1479         {
1480             for (i=0 ; i<demod->r_dev_num ; i++) {
1481                 switch (demod->r_devs[i]->modulation) {
1482                     case OOK_PWM_D:
1483                         pwm_d_decode(demod, demod->r_devs[i], demod->f_buf, len/2);
1484                         break;
1485                     case OOK_PWM_P:
1486                         pwm_p_decode(demod, demod->r_devs[i], demod->f_buf, len/2);
1487                         break;
1488                     default:
1489                         fprintf(stderr, "Unknown modulation %d in protocol!\n", demod->r_devs[i]->modulation);
1490                 }
1491             }
1492             fflush(stdout);
1493         }
1494
1495         if (demod->save_data) {
1496             if (fwrite(demod->f_buf, 1, len>>demod->decimation_level, demod->file) != len>>demod->decimation_level) {
1497                 fprintf(stderr, "Short write, samples lost, exiting!\n");
1498                 rtlsdr_cancel_async(dev);
1499             }
1500         }
1501
1502         if (bytes_to_read > 0)
1503             bytes_to_read -= len;
1504
1505         if(frequencies>1) {
1506             time_t rawtime;
1507             time(&rawtime);
1508             if(difftime(rawtime, rawtime_old)>DEFAULT_HOP_TIME || events>=DEFAULT_HOP_EVENTS) {
1509                 rawtime_old=rawtime;
1510                 events=0;
1511                 do_exit_async=1;
1512                 rtlsdr_cancel_async(dev);
1513             }
1514         }
1515     }
1516 }
1517
1518 int main(int argc, char **argv)
1519 {
1520 #ifndef _WIN32
1521     struct sigaction sigact;
1522 #endif
1523     char *filename = NULL;
1524     char *test_mode_file = NULL;
1525     FILE *test_mode;
1526     int n_read;
1527     int r, opt;
1528     int i, gain = 0;
1529     int sync_mode = 0;
1530     int ppm_error = 0;
1531     struct dm_state* demod;
1532     uint8_t *buffer;
1533     uint32_t dev_index = 0;
1534     int frequency_current=0;
1535     uint32_t out_block_size = DEFAULT_BUF_LENGTH;
1536     int device_count;
1537     char vendor[256], product[256], serial[256];
1538
1539     demod = malloc(sizeof(struct dm_state));
1540     memset(demod,0,sizeof(struct dm_state));
1541
1542     /* initialize tables */
1543     calc_squares();
1544
1545     demod->f_buf = &demod->filter_buffer[FILTER_ORDER];
1546     demod->decimation_level = DEFAULT_DECIMATION_LEVEL;
1547     demod->level_limit      = DEFAULT_LEVEL_LIMIT;
1548
1549
1550     while ((opt = getopt(argc, argv, "x:z:p:Dtam:r:c:l:d:f:g:s:b:n:S::")) != -1) {
1551         switch (opt) {
1552         case 'd':
1553             dev_index = atoi(optarg);
1554             break;
1555         case 'f':
1556             if(frequencies<MAX_PROTOCOLS) frequency[frequencies++] = (uint32_t)atof(optarg);
1557             else fprintf(stderr, "Max number of frequencies reached %d\n",MAX_PROTOCOLS);
1558             break;
1559         case 'g':
1560             gain = (int)(atof(optarg) * 10); /* tenths of a dB */
1561             break;
1562         case 'p':
1563             ppm_error = atoi(optarg);
1564             break;
1565         case 's':
1566             samp_rate = (uint32_t)atof(optarg);
1567             break;
1568         case 'b':
1569             out_block_size = (uint32_t)atof(optarg);
1570             break;
1571         case 'l':
1572             demod->level_limit = (uint32_t)atof(optarg);
1573             break;
1574         case 'n':
1575             bytes_to_read = (uint32_t)atof(optarg) * 2;
1576             break;
1577         case 'c':
1578             demod->decimation_level = (uint32_t)atof(optarg);
1579             break;
1580         case 'a':
1581             demod->analyze = 1;
1582             break;
1583         case 'r':
1584             test_mode_file = optarg;
1585             break;
1586         case 't':
1587             demod->signal_grabber = 1;
1588             break;
1589         case 'm':
1590             demod->debug_mode = atoi(optarg);
1591             break;
1592         case 'S':
1593             sync_mode = 1;
1594             break;
1595         case 'D':
1596             debug_output = 1;
1597             break;
1598         case 'z':
1599             override_short = atoi(optarg);
1600             break;
1601         case 'x':
1602             override_long = atoi(optarg);
1603             break;
1604         default:
1605             usage();
1606             break;
1607         }
1608     }
1609
1610     /* init protocols somewhat ok */
1611     register_protocol(demod, &rubicson);
1612     register_protocol(demod, &prologue);
1613     register_protocol(demod, &silvercrest);
1614 //    register_protocol(demod, &generic_hx2262);
1615 //    register_protocol(demod, &technoline_ws9118);
1616     register_protocol(demod, &elv_em1000);
1617     register_protocol(demod, &elv_ws2000);
1618     register_protocol(demod, &waveman);
1619     register_protocol(demod, &steffen);
1620     register_protocol(demod, &acurite5n1);
1621     register_protocol(demod, &wh2);
1622
1623     if (argc <= optind-1) {
1624         usage();
1625     } else {
1626         filename = argv[optind];
1627     }
1628
1629     if(out_block_size < MINIMAL_BUF_LENGTH ||
1630        out_block_size > MAXIMAL_BUF_LENGTH ){
1631         fprintf(stderr,
1632             "Output block size wrong value, falling back to default\n");
1633         fprintf(stderr,
1634             "Minimal length: %u\n", MINIMAL_BUF_LENGTH);
1635         fprintf(stderr,
1636             "Maximal length: %u\n", MAXIMAL_BUF_LENGTH);
1637         out_block_size = DEFAULT_BUF_LENGTH;
1638     }
1639
1640     buffer = malloc(out_block_size * sizeof(uint8_t));
1641
1642     device_count = rtlsdr_get_device_count();
1643     if (!device_count) {
1644         fprintf(stderr, "No supported devices found.\n");
1645         if (!test_mode_file)
1646             exit(1);
1647     }
1648
1649     fprintf(stderr, "Found %d device(s):\n", device_count);
1650     for (i = 0; i < device_count; i++) {
1651         rtlsdr_get_device_usb_strings(i, vendor, product, serial);
1652         fprintf(stderr, "  %d:  %s, %s, SN: %s\n", i, vendor, product, serial);
1653     }
1654     fprintf(stderr, "\n");
1655
1656     fprintf(stderr, "Using device %d: %s\n",
1657         dev_index, rtlsdr_get_device_name(dev_index));
1658
1659     r = rtlsdr_open(&dev, dev_index);
1660     if (r < 0) {
1661         fprintf(stderr, "Failed to open rtlsdr device #%d.\n", dev_index);
1662         if (!test_mode_file)
1663             exit(1);
1664     }
1665 #ifndef _WIN32
1666     sigact.sa_handler = sighandler;
1667     sigemptyset(&sigact.sa_mask);
1668     sigact.sa_flags = 0;
1669     sigaction(SIGINT, &sigact, NULL);
1670     sigaction(SIGTERM, &sigact, NULL);
1671     sigaction(SIGQUIT, &sigact, NULL);
1672     sigaction(SIGPIPE, &sigact, NULL);
1673 #else
1674     SetConsoleCtrlHandler( (PHANDLER_ROUTINE) sighandler, TRUE );
1675 #endif
1676     /* Set the sample rate */
1677     r = rtlsdr_set_sample_rate(dev, samp_rate);
1678     if (r < 0)
1679         fprintf(stderr, "WARNING: Failed to set sample rate.\n");
1680     else
1681         fprintf(stderr, "Sample rate set to %d.\n", rtlsdr_get_sample_rate(dev)); // Unfortunately, doesn't return real rate
1682
1683     fprintf(stderr, "Sample rate decimation set to %d. %d->%d\n",demod->decimation_level, samp_rate, samp_rate>>demod->decimation_level);
1684     fprintf(stderr, "Bit detection level set to %d.\n", demod->level_limit);
1685
1686     if (0 == gain) {
1687          /* Enable automatic gain */
1688         r = rtlsdr_set_tuner_gain_mode(dev, 0);
1689         if (r < 0)
1690             fprintf(stderr, "WARNING: Failed to enable automatic gain.\n");
1691         else
1692             fprintf(stderr, "Tuner gain set to Auto.\n");
1693     } else {
1694         /* Enable manual gain */
1695         r = rtlsdr_set_tuner_gain_mode(dev, 1);
1696         if (r < 0)
1697             fprintf(stderr, "WARNING: Failed to enable manual gain.\n");
1698
1699         /* Set the tuner gain */
1700         r = rtlsdr_set_tuner_gain(dev, gain);
1701         if (r < 0)
1702             fprintf(stderr, "WARNING: Failed to set tuner gain.\n");
1703         else
1704             fprintf(stderr, "Tuner gain set to %f dB.\n", gain/10.0);
1705     }
1706
1707     r = rtlsdr_set_freq_correction(dev, ppm_error);
1708
1709     demod->save_data = 1;
1710     if (!filename) {
1711         demod->save_data = 0;
1712     } else if(strcmp(filename, "-") == 0) { /* Write samples to stdout */
1713         demod->file = stdout;
1714 #ifdef _WIN32
1715         _setmode(_fileno(stdin), _O_BINARY);
1716 #endif
1717     } else {
1718         demod->file = fopen(filename, "wb");
1719         if (!demod->file) {
1720             fprintf(stderr, "Failed to open %s\n", filename);
1721             goto out;
1722         }
1723     }
1724
1725     if (demod->signal_grabber)
1726         demod->sg_buf = malloc(SIGNAL_GRABBER_BUFFER);
1727
1728     if (test_mode_file) {
1729         int i = 0;
1730         unsigned char test_mode_buf[DEFAULT_BUF_LENGTH];
1731         fprintf(stderr, "Test mode active. Reading samples from file: %s\n",test_mode_file);
1732         test_mode = fopen(test_mode_file, "r");
1733         if (!test_mode) {
1734             fprintf(stderr, "Opening file: %s failed!\n",test_mode_file);
1735             goto out;
1736         }
1737         while(fread(test_mode_buf, 131072, 1, test_mode) != 0) {
1738             rtlsdr_callback(test_mode_buf, 131072, demod);
1739             i++;
1740         }
1741         //Always classify a signal at the end of the file
1742         classify_signal();
1743         fprintf(stderr, "Test mode file issued %d packets\n", i);
1744         fprintf(stderr, "Filter coeffs used:\n");
1745         fprintf(stderr, "a: %d %d\n", a[0], a[1]);
1746         fprintf(stderr, "b: %d %d\n", b[0], b[1]);
1747         exit(0);
1748     }
1749
1750     /* Reset endpoint before we start reading from it (mandatory) */
1751     r = rtlsdr_reset_buffer(dev);
1752     if (r < 0)
1753         fprintf(stderr, "WARNING: Failed to reset buffers.\n");
1754
1755     if (sync_mode) {
1756         fprintf(stderr, "Reading samples in sync mode...\n");
1757         while (!do_exit) {
1758             r = rtlsdr_read_sync(dev, buffer, out_block_size, &n_read);
1759             if (r < 0) {
1760                 fprintf(stderr, "WARNING: sync read failed.\n");
1761                 break;
1762             }
1763
1764             if ((bytes_to_read > 0) && (bytes_to_read < (uint32_t)n_read)) {
1765                 n_read = bytes_to_read;
1766                 do_exit = 1;
1767             }
1768
1769             if (fwrite(buffer, 1, n_read, demod->file) != (size_t)n_read) {
1770                 fprintf(stderr, "Short write, samples lost, exiting!\n");
1771                 break;
1772             }
1773
1774             if ((uint32_t)n_read < out_block_size) {
1775                 fprintf(stderr, "Short read, samples lost, exiting!\n");
1776                 break;
1777             }
1778
1779             if (bytes_to_read > 0)
1780                 bytes_to_read -= n_read;
1781         }
1782     } else {
1783         if(frequencies==0) {
1784           frequency[0] = DEFAULT_FREQUENCY;
1785           frequencies=1;
1786         } else {
1787           time(&rawtime_old);
1788         }
1789         fprintf(stderr, "Reading samples in async mode...\n");
1790         while(!do_exit) {
1791             /* Set the frequency */
1792             r = rtlsdr_set_center_freq(dev, frequency[frequency_current]);
1793             if (r < 0)
1794                 fprintf(stderr, "WARNING: Failed to set center freq.\n");
1795             else
1796                 fprintf(stderr, "Tuned to %u Hz.\n", rtlsdr_get_center_freq(dev));
1797             r = rtlsdr_read_async(dev, rtlsdr_callback, (void *)demod,
1798                           DEFAULT_ASYNC_BUF_NUMBER, out_block_size);
1799             do_exit_async=0;
1800             frequency_current++;
1801             if(frequency_current>frequencies-1) frequency_current=0;
1802         }
1803     }
1804
1805     if (do_exit)
1806         fprintf(stderr, "\nUser cancel, exiting...\n");
1807     else
1808         fprintf(stderr, "\nLibrary error %d, exiting...\n", r);
1809
1810     if (demod->file && (demod->file != stdout))
1811         fclose(demod->file);
1812
1813     for (i=0 ; i<demod->r_dev_num ; i++)
1814         free(demod->r_devs[i]);
1815
1816     if (demod->signal_grabber)
1817         free(demod->sg_buf);
1818
1819     if(demod)
1820         free(demod);
1821
1822     rtlsdr_close(dev);
1823     free (buffer);
1824 out:
1825     return r >= 0 ? r : -r;
1826 }