-
Notifications
You must be signed in to change notification settings - Fork 48
Expand file tree
/
Copy pathESPiLight.cpp
More file actions
679 lines (592 loc) · 18.6 KB
/
ESPiLight.cpp
File metadata and controls
679 lines (592 loc) · 18.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
/*
ESPiLight - pilight 433.92 MHz protocols library for Arduino
Copyright (c) 2016 Puuu. All right reserved.
Project home: https://github.com/puuu/espilight/
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 3 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU General Public License
along with library. If not, see <http://www.gnu.org/licenses/>
*/
#include <ESPiLight.h>
#include "tools/aprintf.h"
// ESP32 doesn't define ICACHE_RAM_ATTR
#ifndef ICACHE_RAM_ATTR
#define ICACHE_RAM_ATTR IRAM_ATTR
#endif
#ifdef DEBUG
#define Debug(x) Serial.print(x)
#define DebugLn(x) Serial.println(x)
#else
#define Debug(x)
#define DebugLn(x)
#endif
extern "C" {
#include "pilight/libs/pilight/protocols/protocol.h"
}
static protocols_t *used_protocols = nullptr;
volatile PulseTrain_t ESPiLight::_pulseTrains[RECEIVER_BUFFER_SIZE];
bool ESPiLight::_enabledReceiver;
volatile uint8_t ESPiLight::_actualPulseTrain = 0;
uint8_t ESPiLight::_avaiablePulseTrain = 0;
volatile unsigned long ESPiLight::_lastChange =
0; // Timestamp of previous edge
volatile uint8_t ESPiLight::_nrpulses = 0;
int16_t ESPiLight::_interrupt = NOT_AN_INTERRUPT;
uint8_t ESPiLight::minrawlen = std::numeric_limits<uint8_t>::max();
uint8_t ESPiLight::maxrawlen = std::numeric_limits<uint8_t>::min();
uint16_t ESPiLight::mingaplen = std::numeric_limits<uint16_t>::max();
uint16_t ESPiLight::maxgaplen = std::numeric_limits<uint16_t>::min();
uint16_t ESPiLight::minpulselen = 80;
uint16_t ESPiLight::maxpulselen = 16000;
static void fire_callback(protocol_t *protocol, ESPiLightCallBack callback);
static void calc_lengths();
static protocols_t *get_protocols() {
if (pilight_protocols == nullptr) {
ESPiLight::setErrorOutput(Serial);
protocol_init();
calc_lengths();
}
return pilight_protocols;
}
static protocols_t *get_used_protocols() {
if (used_protocols == nullptr) {
used_protocols = get_protocols();
}
return used_protocols;
}
static protocols_t *find_protocol_node(const char *name) {
protocols_t *pnode = get_protocols();
while (pnode != nullptr) {
if (strcmp(name, pnode->listener->id) == 0) {
return pnode;
}
pnode = pnode->next;
}
return nullptr;
}
static protocol_t *find_protocol(const char *name) {
protocols_t *pnode = find_protocol_node(name);
if (pnode != nullptr) {
return pnode->listener;
}
return nullptr;
}
static int create_pulse_train(uint16_t *pulses, protocol_t *protocol,
const String &content) {
Debug("piLightCreatePulseTrain: ");
if (!json_validate(content.c_str())) {
Debug("invalid json: ");
DebugLn(content);
return ESPiLight::ERROR_INVALID_JSON;
}
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wtype-limits"
if ((protocol != nullptr) && (protocol->createCode != nullptr) &&
(protocol->maxrawlen <= MAXPULSESTREAMLENGTH)) {
#pragma GCC diagnostic pop
Debug("protocol: ");
Debug(protocol->id);
protocol->rawlen = 0;
protocol->raw = pulses;
JsonNode *message = json_decode(content.c_str());
int return_value = protocol->createCode(message);
json_delete(message);
// delete message created by createCode()
json_delete(protocol->message);
protocol->message = nullptr;
if (return_value == EXIT_SUCCESS) {
DebugLn(" create Code succeded.");
return protocol->rawlen;
} else {
DebugLn(" create Code failed.");
return ESPiLight::ERROR_INVALID_PILIGHT_MSG;
}
}
return ESPiLight::ERROR_UNAVAILABLE_PROTOCOL;
}
static void calc_lengths() {
protocols_t *pnode = get_used_protocols();
ESPiLight::minrawlen = std::numeric_limits<uint8_t>::max();
ESPiLight::maxrawlen = std::numeric_limits<uint8_t>::min();
ESPiLight::mingaplen = std::numeric_limits<uint16_t>::max();
ESPiLight::maxgaplen = std::numeric_limits<uint16_t>::min();
ESPiLight::minpulselen = 80;
ESPiLight::maxpulselen = 16000;
while (pnode != nullptr) {
if (pnode->listener->parseCode != nullptr) {
const protocol_t *protocol = pnode->listener;
const uint8_t minLen = protocol->minrawlen;
const uint8_t maxLen = protocol->maxrawlen;
const uint16_t minGap = protocol->mingaplen;
const uint16_t maxGap = protocol->maxgaplen;
if (minLen < ESPiLight::minrawlen) {
ESPiLight::minrawlen = minLen;
}
if (maxLen > ESPiLight::maxrawlen && maxLen <= MAXPULSESTREAMLENGTH) {
ESPiLight::maxrawlen = maxLen;
}
if (minGap < ESPiLight::mingaplen) {
ESPiLight::mingaplen = minGap;
}
if (maxGap > ESPiLight::maxgaplen) {
ESPiLight::maxgaplen = maxGap;
}
if (minGap < ESPiLight::minpulselen) {
ESPiLight::minpulselen = minGap;
}
if (maxGap > ESPiLight::maxpulselen) {
ESPiLight::maxpulselen = maxGap;
}
}
pnode = pnode->next;
}
Debug("minrawlen: ");
DebugLn(ESPiLight::minrawlen);
Debug("maxrawlen: ");
DebugLn(ESPiLight::maxrawlen);
Debug("mingaplen: ");
DebugLn(ESPiLight::mingaplen);
Debug("maxgaplen: ");
DebugLn(ESPiLight::maxgaplen);
Debug("minpulselen: ");
DebugLn(ESPiLight::minpulselen);
Debug("maxpulselen: ");
DebugLn(ESPiLight::maxpulselen);
}
void ESPiLight::initReceiver(byte inputPin) {
int16_t interrupt = digitalPinToInterrupt(inputPin);
if (_interrupt == interrupt) {
return;
}
if (_interrupt >= 0) {
detachInterrupt((uint8_t)_interrupt);
}
_interrupt = interrupt;
resetReceiver();
enableReceiver();
if (interrupt >= 0) {
attachInterrupt((uint8_t)interrupt, interruptHandler, CHANGE);
}
}
uint8_t ESPiLight::receivePulseTrain(uint16_t *pulses) {
uint8_t length = nextPulseTrainLength();
if (length > 0) {
volatile PulseTrain_t &pulseTrain = _pulseTrains[_avaiablePulseTrain];
_avaiablePulseTrain = (_avaiablePulseTrain + 1) % RECEIVER_BUFFER_SIZE;
for (uint8_t i = 0; i < length; i++) {
pulses[i] = pulseTrain.pulses[i];
}
pulseTrain.length = 0;
}
return length;
}
uint8_t ESPiLight::nextPulseTrainLength() {
return _pulseTrains[_avaiablePulseTrain].length;
}
void ICACHE_RAM_ATTR ESPiLight::interruptHandler() {
if (!_enabledReceiver) {
return;
}
volatile PulseTrain_t &pulseTrain = _pulseTrains[_actualPulseTrain];
volatile uint16_t *codes = pulseTrain.pulses;
if (pulseTrain.length == 0) {
const unsigned long now = micros();
if (now > _lastChange) { // prevent overflow after 70 minutes
const unsigned long duration = now - _lastChange;
/* We first do some filtering (same as pilight BPF) */
if (duration > minpulselen) {
if (duration < maxpulselen) {
/* All codes are buffered */
codes[_nrpulses] = (uint16_t)duration;
_nrpulses = (uint8_t)((_nrpulses + 1) % MAXPULSESTREAMLENGTH);
/* Let's match footers */
if (duration > mingaplen) {
// Debug('g');
/* Only match minimal length pulse streams */
if (_nrpulses >= minrawlen && _nrpulses <= maxrawlen) {
// Debug(_nrpulses);
// Debug('l');
pulseTrain.length = _nrpulses;
_actualPulseTrain =
(_actualPulseTrain + 1) % RECEIVER_BUFFER_SIZE;
}
_nrpulses = 0;
}
}
}
}
_lastChange = now;
} else {
Debug("_!_");
}
}
void ESPiLight::resetReceiver() {
for (unsigned int i = 0; i < RECEIVER_BUFFER_SIZE; i++) {
_pulseTrains[i].length = 0;
}
_avaiablePulseTrain = 0;
_actualPulseTrain = 0;
_nrpulses = 0;
}
void ESPiLight::enableReceiver() { _enabledReceiver = true; }
void ESPiLight::disableReceiver() { _enabledReceiver = false; }
void ESPiLight::loop() {
int length = 0;
uint16_t pulses[MAXPULSESTREAMLENGTH];
length = receivePulseTrain(pulses);
if (length > 0) {
/*
Debug("RAW (");
Debug(length);
Debug("): ");
for(int i=0;i<length;i++) {
Debug(pulses[i]);
Debug(' ');
}
DebugLn();
*/
parsePulseTrain(pulses, (uint8_t)length);
}
}
ESPiLight::ESPiLight(int8_t outputPin) {
_outputPin = outputPin;
_callback = nullptr;
_rawCallback = nullptr;
_echoEnabled = false;
if (_outputPin >= 0) {
pinMode((uint8_t)_outputPin, OUTPUT);
digitalWrite((uint8_t)_outputPin, LOW);
}
get_protocols();
}
void ESPiLight::setCallback(ESPiLightCallBack callback) {
_callback = callback;
}
void ESPiLight::setPulseTrainCallBack(PulseTrainCallBack rawCallback) {
_rawCallback = rawCallback;
}
void ESPiLight::sendPulseTrain(const uint16_t *pulses, size_t length,
size_t repeats) {
if (_outputPin >= 0) {
bool receiverState = _enabledReceiver;
_enabledReceiver = (_echoEnabled && receiverState);
for (unsigned int r = 0; r < repeats; r++) {
for (unsigned int i = 0; i < length; i += 2) {
digitalWrite((uint8_t)_outputPin, HIGH);
delayMicroseconds(pulses[i]);
digitalWrite((uint8_t)_outputPin, LOW);
if (i + 1 < length) {
delayMicroseconds(pulses[i + 1]);
}
}
}
digitalWrite((uint8_t)_outputPin, LOW);
_enabledReceiver = receiverState;
}
}
int ESPiLight::send(const String &protocol, const String &json,
size_t repeats) {
if (_outputPin < 0) {
DebugLn("No output pin set, cannot send");
return ERROR_NO_OUTPUT_PIN;
}
int length = 0;
uint16_t pulses[MAXPULSESTREAMLENGTH];
protocol_t *protocol_listener = find_protocol(protocol.c_str());
length = create_pulse_train(pulses, protocol_listener, json);
if (length > 0) {
/*
DebugLn();
Debug("send: ");
Debug(length);
Debug(" pulses (");
Debug(protocol);
Debug(", ");
Debug(content);
DebugLn(")");
*/
if (repeats == 0) {
repeats = protocol_listener->txrpt;
}
sendPulseTrain(pulses, (unsigned)length, repeats);
}
return length;
}
int ESPiLight::createPulseTrain(uint16_t *pulses, const String &protocol_id,
const String &content) {
protocol_t *protocol = find_protocol(protocol_id.c_str());
return create_pulse_train(pulses, protocol, content);
}
size_t ESPiLight::parsePulseTrain(uint16_t *pulses, uint8_t length) {
size_t matches = 0;
protocol_t *protocol = nullptr;
protocols_t *pnode = get_used_protocols();
// DebugLn("piLightParsePulseTrain start");
while ((pnode != nullptr) && (_callback != nullptr)) {
protocol = pnode->listener;
if (protocol->parseCode != nullptr && protocol->validate != nullptr) {
protocol->raw = pulses;
protocol->rawlen = length;
if (protocol->validate() == 0) {
Debug("pulses: ");
Debug(length);
Debug(" possible protocol: ");
DebugLn(protocol->id);
if (protocol->first > 0) {
protocol->first = protocol->second;
}
protocol->second = micros();
if (protocol->first == 0) {
protocol->first = protocol->second;
}
/* Reset # of repeats after a certain delay */
if (protocol->second < protocol->first ||
(protocol->second - protocol->first) > 500000) {
protocol->repeats = 0;
}
protocol->message = nullptr;
protocol->parseCode();
if (protocol->message != nullptr) {
matches++;
protocol->repeats++;
fire_callback(protocol, _callback);
json_delete(protocol->message);
protocol->message = nullptr;
}
}
}
pnode = pnode->next;
yield();
}
if (_rawCallback != nullptr) {
(_rawCallback)(pulses, length);
}
// Debug("piLightParsePulseTrain end. matches: ");
// DebugLn(matches);
return matches;
}
static void fire_callback(protocol_t *protocol, ESPiLightCallBack callback) {
PilightRepeatStatus_t status = FIRST;
char *content = json_encode(protocol->message);
String deviceId = "";
double itmp;
char *stmp;
if ((protocol->repeats <= 1) || (protocol->old_content == nullptr)) {
status = FIRST;
json_free(protocol->old_content);
protocol->old_content = content;
} else if (!(protocol->repeats & 0x80)) {
if (strcmp(content, protocol->old_content) == 0) {
protocol->repeats |= 0x80;
status = VALID;
} else {
status = INVALID;
}
json_free(protocol->old_content);
protocol->old_content = content;
} else {
status = KNOWN;
json_free(content);
}
if (json_find_number(protocol->message, "id", &itmp) == 0) {
deviceId = String((int)round(itmp));
} else if (json_find_string(protocol->message, "id", &stmp) == 0) {
deviceId = String(stmp);
};
(callback)(String(protocol->id), String(protocol->old_content), status,
protocol->repeats & 0x7F, deviceId);
}
String ESPiLight::pulseTrainToString(const uint16_t *codes, size_t length) {
bool match = false;
int diff = 0;
uint8_t nrpulses = 0; // number of pulse types
uint16_t plstypes[MAX_PULSE_TYPES] = {};
String data("");
data.reserve(6 + length);
data += "c:";
for (unsigned int i = 0; i < length; i++) {
match = false;
for (uint8_t j = 0; j < MAX_PULSE_TYPES; j++) {
// We device these numbers by 10 to normalize them a bit
diff = (plstypes[j] / 50) - (codes[i] / 50);
if ((diff >= -2) && (diff <= 2)) {
// Write numbers
data += (char)('0' + ((char)j));
match = true;
break;
}
}
if (!match) {
plstypes[nrpulses++] = codes[i];
data += (char)('0' + ((char)(nrpulses - 1)));
if (nrpulses >= MAX_PULSE_TYPES) {
DebugLn("too many pulse types");
return String("");
}
}
}
data += ";p:";
for (uint8_t i = 0; i < nrpulses; i++) {
data += plstypes[i];
if (i + 1 < nrpulses) {
data += ',';
}
}
data += '@';
return data;
}
int ESPiLight::stringToPulseTrain(const String &data, uint16_t *codes,
size_t maxlength) {
unsigned int length = 0; // length of pulse train
unsigned int nrpulses = 0; // number of pulse types
uint16_t plstypes[MAX_PULSE_TYPES] = {};
// validate data string
int scode = data.indexOf('c') + 2;
if (scode < 2 || (unsigned)scode > data.length()) {
DebugLn("'c' not found in data string, or has no data");
return ERROR_INVALID_PULSETRAIN_MSG_C;
}
int spulse = data.indexOf('p') + 2;
if (spulse < 2 || (unsigned)spulse > data.length()) {
DebugLn("'p' not found in data string, or has no data");
return ERROR_INVALID_PULSETRAIN_MSG_P;
}
// parsing pulse types
unsigned int start = (unsigned)spulse;
int end = data.indexOf(',', start);
while (end > 0) {
plstypes[nrpulses++] =
(uint16_t)data.substring(start, (unsigned)end).toInt();
start = (unsigned)end + 1;
end = data.indexOf(',', start);
}
end = data.indexOf(';', start);
if (end < 0) {
end = data.indexOf('@', start);
}
if (end < 0) {
DebugLn("';' or '@' not found in data string");
return ERROR_INVALID_PULSETRAIN_MSG_END;
}
plstypes[nrpulses++] = (uint16_t)data.substring(start, (unsigned)end).toInt();
// parsing pulses
int pulse_index = 0;
for (unsigned int i = (unsigned)scode; i < data.length(); i++) {
if ((data[i] == ';') || (data[i] == '@')) break;
if (i >= maxlength) break;
pulse_index = data[i] - '0';
if ((pulse_index < 0) || ((unsigned)pulse_index >= nrpulses)) {
DebugLn("Pulse type not defined");
return ERROR_INVALID_PULSETRAIN_MSG_TYPE;
}
codes[length++] = plstypes[pulse_index];
}
return length;
}
int ESPiLight::stringToRepeats(const String &data) {
// parsing (optional) repeats
int srepeat = data.indexOf('r') + 2;
if (srepeat < 2 || (unsigned)srepeat > data.length()) {
DebugLn("'r' not found in data string, or has no data");
return ERROR_INVALID_PULSETRAIN_MSG_R;
}
unsigned int start = (unsigned)srepeat;
int end = data.indexOf(';', start);
if (end < 0) {
end = data.indexOf('@', start);
}
if (end < 0) {
DebugLn("';' or '@' not found in data string");
return ERROR_INVALID_PULSETRAIN_MSG_END;
}
return data.substring(start, (unsigned)end).toInt();
}
void ESPiLight::limitProtocols(const String &protos) {
if (!json_validate(protos.c_str())) {
DebugLn("Protocol limit argument is not a valid json message!");
return;
}
JsonNode *message = json_decode(protos.c_str());
if (message->tag != JSON_ARRAY) {
DebugLn("Protocol limit argument is not a json array!");
json_delete(message);
return;
}
if (get_used_protocols() != get_protocols()) {
protocols_t *pnode = get_used_protocols();
while (pnode != nullptr) {
protocols_t *tmp = pnode;
pnode = pnode->next;
delete tmp;
}
}
used_protocols = nullptr;
JsonNode *curr = message->children.head;
unsigned int proto_count = 0;
while (curr != nullptr) {
if (curr->tag != JSON_STRING) {
DebugLn("Element is not a String");
curr = curr->next;
continue;
}
protocols_t *templ = find_protocol_node(curr->string_);
if (templ == nullptr) {
Debug("Protocol not found: ");
DebugLn(curr->string_);
curr = curr->next;
continue;
}
protocols_t *new_node = new protocols_t;
new_node->listener = templ->listener;
new_node->next = used_protocols;
used_protocols = new_node;
Debug("activated protocol ");
DebugLn(templ->listener->id);
proto_count++;
if (curr == message->children.tail) {
break;
}
curr = curr->next;
}
json_delete(message);
calc_lengths();
}
static String protocols_to_array(protocols_t *pnode) {
protocols_t *tmp = pnode;
size_t needed_len = 2; // []
while (tmp != nullptr) {
needed_len += strlen(tmp->listener->id) + 3; // "xx",
tmp = tmp->next;
}
String ret;
ret.reserve(needed_len);
ret += '[';
bool first = true;
while (pnode != nullptr) {
if (first) {
first = false;
} else {
ret += ",";
}
ret += '"';
ret += pnode->listener->id;
ret += '"';
pnode = pnode->next;
}
ret += "]";
return ret;
}
String ESPiLight::availableProtocols() {
return protocols_to_array(get_protocols());
}
String ESPiLight::enabledProtocols() {
return protocols_to_array(get_used_protocols());
}
void ESPiLight::setEchoEnabled(bool enabled) { _echoEnabled = enabled; }
void ESPiLight::setErrorOutput(Print &output) { set_aprintf_output(&output); }