Bugfixes
[rtl-433.git] / src / devices / current_cost.c
1 #include "rtl_433.h"
2 #include "pulse_demod.h"
3 #include "util.h"
4 #include "data.h"
5
6 static int current_cost_callback(bitbuffer_t *bitbuffer) {
7     bitbuffer_invert(bitbuffer);
8     bitrow_t *bb = bitbuffer->bb;
9     uint8_t *b = bb[0];
10
11     char time_str[LOCAL_TIME_BUFLEN];
12     data_t *data;
13     local_time_str(0, time_str);
14
15     uint8_t init_pattern[] = {
16       0b11001100, //8
17       0b11001100, //16
18       0b11001100, //24
19       0b11001110, //32
20       0b10010001, //40
21       0b01011101, //45 (! last 3 bits is not init)
22     };
23     unsigned int start_pos = bitbuffer_search(bitbuffer, 0, 0, init_pattern, 45);
24
25     if(start_pos == bitbuffer->bits_per_row[0]){
26         return 0;
27     }
28     start_pos += 45;
29
30     bitbuffer_t packet_bits = {0};
31
32     start_pos = bitbuffer_manchester_decode(bitbuffer, 0, start_pos, &packet_bits, 0);
33
34     uint8_t *packet = packet_bits.bb[0];
35     // Read data
36     if(packet_bits.bits_per_row[0] >= 56 && ((packet[0] & 0xf0) == 0) ){
37                     uint16_t device_id = (packet[0] & 0x0f) << 8 | packet[1];
38
39         uint16_t watt0 = (packet[2] & 0x7F) << 8 | packet[3] ;
40         uint16_t watt1 = (packet[4] & 0x7F) << 8 | packet[5] ;
41         uint16_t watt2 = (packet[6] & 0x7F) << 8 | packet[7] ;
42         data = data_make("time",          "",       DATA_STRING, time_str,
43                 "model",         "",              DATA_STRING, "CurrentCost TX", //TODO: it may have different CC Model ? any ref ?
44                 //"rc",            "Rolling Code",  DATA_INT, rc, //TODO: add rolling code b[1] ? test needed
45                                                                 "dev_id",       "Device Id",     DATA_FORMAT, "%d", DATA_INT, device_id,
46                 "power0",       "Power 0",       DATA_FORMAT, "%d W", DATA_INT, watt0,
47                 "power1",       "Power 1",       DATA_FORMAT, "%d W", DATA_INT, watt1,
48                 "power2",       "Power 2",       DATA_FORMAT, "%d W", DATA_INT, watt2,
49                 //"battery",       "Battery",       DATA_STRING, battery_low ? "LOW" : "OK", //TODO is there some low battery indicator ?
50                 NULL);
51         data_acquired_handler(data);
52         return 1;
53     }
54     return 0;
55 }
56
57 static char *output_fields[] = {
58     "time",
59     "model",
60     "rc",
61     "power0",
62     "power1",
63     "power2",
64     NULL
65 };
66
67 r_device current_cost = {
68     .name           = "CurrentCost Current Sensor",
69     .modulation     = FSK_PULSE_PCM,
70     .short_limit    = 250,
71     .long_limit     = 250, // NRZ
72     .reset_limit    = 8000,
73     .json_callback  = &current_cost_callback,
74     .disabled       = 0,
75     .fields         = output_fields,
76 };