-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathkidde_cc1101.ino
1314 lines (994 loc) · 27.9 KB
/
kidde_cc1101.ino
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
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// DISCLAIMER: This is not intended to be used for any real-world safety applications - it is for educational/informational purposes only! Use at your own risk.
//
// board=MiniCore:avr:328:bootloader=uart0,variant=modelP,BOD=2v7,LTO=Os_flto,clock=8MHz_external
// port=/dev/serial/by-id/usb-Silicon_Labs_CP2102_USB_to_UART_Bridge_Controller_0001-if00-port0
// verbose=1
#include <avr/interrupt.h>
#include <avr/power.h>
#include <avr/wdt.h>
#include <util/crc16.h>
#include <stdarg.h>
#include <ArduinoJson.h>
#include <EEPROM.h>
#include <SPI.h>
// LOG_LEVEL can be one of ERROR, INFO, DEBUG, or TRACE
// running with TRACE or even DEBUG will likely cause packet loss - not recommended outside of testing
#define LOG_LEVEL INFO
// uncomment this to allow adjusting log level during runtime, otherwise it will be fixed at LOG_LEVEL
// note this will increase flash usage by ~6KiB vs compiling only with INFO or ERROR
#define DYNAMIC_LOG
// uncomment this to gather memory statistics (for TRACE)
// requires library from https://github.com/McNeight/MemoryFree
#define MEMORY_USAGE
// max number of addresses to monitor. limited by ram - each monitored address requires ~96 bytes of ram.
#define ADDRESS_MAX 4
// read this many bytes from uart at a go. effectively limits max json command length.
#define SERIAL_BUFFER 64
// milliseconds to wait for an "\n" upon receiving a byte from the uart. 9600 baud would require < 1ms.
#define SERIAL_TIMEOUT 100
enum log_level {
ERROR,
INFO,
DEBUG,
TRACE,
NUM_LEVELS
};
static const char *log_strs[] = {
"error",
"info",
"debug",
"trace"
};
struct settings {
uint8_t address[ADDRESS_MAX];
uint8_t address_cnt;
uint16_t expiry;
uint32_t baud;
bool promisc;
#ifdef DYNAMIC_LOG
uint8_t log_level;
#endif
} s = { // defaults below if eeprom is blank/corrupt - adjustable during runtime and saved in eeprom
{0}, // default address of 0x00
1, // only 1 address
10, // 10 second expiry
38400, // works well for 8MHz and 16MHz xtals. 500000 recommended on 8MHz.
0, // unicast only
#ifdef DYNAMIC_LOG
LOG_LEVEL // default loglevel
#endif
};
uint8_t s_max_packets; // derived based on baud
// NOTE: pins below will likely need to be changed unless you're using a atmega328p swapped onto a RM1101-USB-232 like me :)
// uncomment below for RM1101-USB-232
//#define RM1101_USB_232
// for "minicore" arduino core - note the different pin naming convention
#define CS PIN_PD4
#define MOSI PIN_PB3
#define MISO PIN_PB4
#define SCLK PIN_PB5
#define GDO0 PIN_PD3
#define GDO2 PIN_PC0
#define LED PIN_PB0
#ifdef RM1101_USB_232
// only change these if you're using RM1101-USB-232
#define EN PIN_PC5
#define ORIG_SCLK PIN_PC2
#define ORIG_MOSI PIN_PC3
#define ORIG_MISO PIN_PC1
#endif
// equivalent pin definitions for standard arduino ide core
/*
#define CS 4
#define MOSI 11
#define MISO 12
#define SCLK 12
#define GDO0 3
#define GDO2 A0
#define LED 8
#ifdef RM1101_USB_232
// only change these if you're using RM1101-USB-232
#define EN A5
#define ORIG_SCLK A2
#define ORIG_MOSI A3
#define ORIG_MISO A1
#endif
*/
SPISettings CC1101(1000000, MSBFIRST, SPI_MODE0);
// some commands appear to work without the MSB (0x80) set. however, the alarm itself always seems to set it
#define KIDDE_COMMAND (0x80)
#define KIDDE_TEST (KIDDE_COMMAND | 0x00)
#define KIDDE_HUSH (KIDDE_COMMAND | 0x01)
#define KIDDE_CO (KIDDE_COMMAND | 0x02)
#define KIDDE_SMOKE (KIDDE_COMMAND | 0x03)
#define KIDDE_BATTERY (KIDDE_COMMAND | 0x0D)
#define CC1101_STROBE_SRES 0x30
#define CC1101_STROBE_SCAL 0x33
#define CC1101_STROBE_SRX 0x34
#define CC1101_STROBE_STX 0x35
#define CC1101_STROBE_SIDLE 0x36
#define CC1101_STROBE_SFRX 0x3A
#define CC1101_STROBE_SFTX 0x3B
#define CC1101_STROBE_SNOP 0x3D
#define CC1101_STATUS_CAL 0x40
#define CC1101_CMD_WRITE 0x00
#define CC1101_CMD_WRITE_BURST 0x40
#define CC1101_CMD_READ 0x80
#define CC1101_CMD_READ_BURST 0xC0
#define CC1101_REG_IOCFG2 0x00
#define CC1101_REG_PARTNUM 0x30
#define CC1101_REG_VERSION 0x31
#define CC1101_REG_PKTSTATUS 0x38
#define CC1101_REG_RXBYTES 0x3B
#define CC1101_RX_FIFO 0x3F
#define CC1101_TX_FIFO 0x3F
#define CC1101_RX_OVERFLOW 0x80
// obtained via pulseview + cc1101 decoder on wink hub 1
// Burst write: IOCFG2 (00) = 07 2E 04 07 D3 91 04 0C 44 00 00 06 00 10 AA 80 4B F9 03 22 F7 46 07 0F 18 1D 1C C7 00 B2 30 AA 69 B6 10 EA 2A 00
static const uint8_t kidde_regs[] PROGMEM = {
// 0x00 ...
0x07, // IOCFG2 GDO2 Output Pin Configuration
0x2e, // IOCFG1 GDO1 Output Pin Configuration
0x04, // IOCFG0 GDO0 Output Pin Configuration
0x07, // FIFOTHR RX FIFO and TX FIFO Thresholds
0xD3, // SYNC1 Sync word, high byte
0x91, // SYNC0 Sync word, low byte
0x04, // PKTLEN Packet Length
0x0C, // PKTCTRL1 Packet Automation Control
0x44, // PKTCTRL0 Packet Automation Control
0x00, // ADDR Device Address
0x00, // CHANR Channel Number
0x06, // FSCTRL1 Frequency Synthesizer Control
0x00, // FSCTRL0 Frequency Synthesizer Control
0x10, // FREQ2 Frequency Control Word, High Byte
0xAA, // FREQ1 Frequency Control Word, Middle Byte
0x80, // FREQ0 Frequency Control Word, Low Byte
0x4B, // MDMCFG4 Modem Configuration
0xF9, // MDMCFG3 Modem Configuration
0x03, // MDMCFG2 Modem Configuration
0x22, // MDMCFG1 Modem Configuration
0xF7, // MDMCFG0 Modem Configuration
0x46, // DEVIATN Modem Deviation Setting
0x07, // MCSM2 Main Radio Control State Machine Configuration
0x0F, // MCSM1 Main Radio Control State Machine Configuration
0x18, // MCSM0 Main Radio Control State Machine Configuration
0x1D, // FOCCFG Frequency Offset Compensation Configuration
0x1C, // BSCFG Bit Synchronization Configuration
0xC7, // AGCCTRL2 AGC Control
0x00, // AGCCTRL1 AGC Control
0xB2, // AGCCTRL0 AGC Control
0x30, // WOREVT1 High Byte Event0 Timeout
0xAA, // WOREVT0 Low Byte Event0 Timeout
0x69, // WORCTRL Wake On Radio Control
0xB6, // FREND1 Front End RX Configuration
0x10, // FREND0 Front End TX Configuration
0xEA, // FSCAL3 Frequency Synthesizer Calibration
0x2A, // FSCAL2 Frequency Synthesizer Calibration
0x00 // FSCAL1 Frequency Synthesizer Calibration
// ... 0x25
};
// call stack depth, for TRACE
uint8_t depth = 0;
#define LOG_BUFFER_SIZE 128
#ifdef DYNAMIC_LOG
#define _LOG_LEVEL_ s.log_level
#else
#define _LOG_LEVEL_ LOG_LEVEL
#endif
#define LOG(_LEVEL_, _MSG_, ...) \
if (_LOG_LEVEL_ >= _LEVEL_) \
logSerial(_LEVEL_, _func_name_, PSTR(_MSG_), ##__VA_ARGS__);
// using __func__ here eats a ton of ram. hence manually passing/setting _FUNC_NAME_ once per function.
#ifdef MEMORY_USAGE
#include <MemoryFree.h>
#define _start(_FUNC_NAME_) \
depth++; \
const static char _func_name_[] PROGMEM = _FUNC_NAME_; \
LOG(TRACE, "start: %i", freeMemory());
#define _end \
LOG(TRACE, "end: %i", freeMemory()) \
depth--;
#else
#define _start(_FUNC_NAME_) \
depth++; \
const static char _func_name_[] PROGMEM = _FUNC_NAME_; \
LOG(TRACE, "start");
#define _end \
LOG(TRACE, "end") \
depth--;
#endif
static const char EEPROM_MAGIC[] = {'k','i','d','d','e'};
struct kidde_pkt {
uint8_t address;
uint8_t command;
uint8_t suffix[2];
uint8_t rssi;
uint8_t crc_lqi;
};
struct alarm_state {
bool active;
uint32_t count;
unsigned long first;
unsigned long last;
uint8_t min_rssi;
uint8_t max_rssi;
};
enum kidde_cmd {
TEST,
HUSH,
CO,
SMOKE,
BATTERY,
UNKNOWN,
NUM_CMDS
};
static const char *kidde_strs[] = {
"test",
"hush",
"co",
"smoke",
"battery",
"unknown"
};
struct alarm_state alarm_states[ADDRESS_MAX][NUM_CMDS];
void logSerial(uint8_t level, const char *caller PROGMEM, const char *msg PROGMEM, ...) {
// 32 = max 'caller' length. 'msg' isn't duplicated as it's cast to const char.
StaticJsonDocument<JSON_OBJECT_SIZE(6) + 32> log;
char buffer[LOG_BUFFER_SIZE];
va_list args;
va_start(args, msg);
vsnprintf_P(buffer, LOG_BUFFER_SIZE, msg, args);
va_end(args);
log["millis"] = millis();
log["type"] = "log";
log["level"] = log_strs[level];
log["caller"] = (const __FlashStringHelper *) caller;
if (_LOG_LEVEL_ == TRACE)
log["depth"] = depth;
log["msg"] = (const char *) buffer;
serializeJson(log, Serial);
Serial.println();
}
enum kidde_cmd kiddeCmdMap(uint8_t command) {
_start("kiddeCmdMap");
enum kidde_cmd mapped;
switch (command) {
case KIDDE_TEST:
mapped = TEST;
break;
case KIDDE_HUSH:
mapped = HUSH;
break;
case KIDDE_CO:
mapped = CO;
break;
case KIDDE_SMOKE:
mapped = SMOKE;
break;
case KIDDE_BATTERY:
mapped = BATTERY;
break;
default:
mapped = UNKNOWN;
break;
}
_end;
return (mapped);
}
void enableWatchdog() {
_start("enableWatchdog");
wdt_enable(WDTO_8S);
_end;
}
void updateWatchdog() {
_start("updateWatchdog");
wdt_reset();
_end;
}
void resetBoard() {
_start("resetBoard");
LOG(INFO, "resetting board");
_end;
wdt_enable(WDTO_1S);
while (1);
}
#if FLASHEND <= 140000
// requires optiboot 7+ to function properly
void jumpBootloader() {
_start("jumpBootloader");
LOG(INFO, "jumping to bootloader");
_end;
// taken from https://github.com/Optiboot/optiboot/blob/20a79ce/optiboot/examples/test_reset/test_reset.ino
typedef void (*do_reboot_t)(void);
const do_reboot_t do_reboot = (do_reboot_t)((FLASHEND - 511) >> 1);
cli(); TCCR0A = TCCR1A = TCCR2A = 0; // make sure interrupts are off and timers are reset.
do_reboot();
}
#endif
void setupPins() {
_start("setupPins");
#ifdef RM1101_USB_232
// disable original bitbanged spi pins on RM1101-USB-232
pinMode(ORIG_SCLK, INPUT);
pinMode(ORIG_MOSI, INPUT);
pinMode(ORIG_MISO, INPUT);
#endif
// set CS as output
pinMode(CS, OUTPUT);
digitalWrite(CS, HIGH);
// set MISO as input
pinMode(MISO, INPUT);
// Asserts when the RX FIFO has overflowed. De-asserts when the FIFO has been flushed.
pinMode(GDO0, INPUT);
digitalWrite(GDO0, LOW);
// Asserts when a packet has been received with CRC OK. De-asserts when the first byte is read from the RX FIFO.
pinMode(GDO2, INPUT);
digitalWrite(GDO2, LOW);
#ifdef RM1101_USB_232
// enable amp on RM1101-USB-232, active high
pinMode(EN, OUTPUT);
digitalWrite(EN, HIGH);
#endif
// LED
pinMode(LED, OUTPUT);
digitalWrite(LED, LOW);
_end;
}
void ledBlink() {
_start("ledBlink");
// blink a few times to signify reset
for (uint8_t x = 0; x < 5; x++) {
digitalWrite(LED, HIGH);
delay(100);
digitalWrite(LED, LOW);
delay(100);
}
_end;
}
void disableUnusedHw() {
_start("disableUnusedHw");
power_adc_disable();
power_timer1_disable();
power_timer2_disable();
power_twi_disable();
_end;
}
void initSerial() {
// clear tx fifo / rx buffer
Serial.end();
// per-byte timeout of incoming commands
Serial.setTimeout(SERIAL_TIMEOUT);
Serial.begin(s.baud);
// adjust rx loop based on baud
setMaxPackets();
}
void setMaxPackets() {
if (s.baud > 115200) {
s_max_packets = 32;
}
else if (s.baud > 57600) {
s_max_packets = 16;
}
else if (s.baud > 28800) {
s_max_packets = 8;
}
else if (s.baud > 14400) {
s_max_packets = 4;
}
else {
s_max_packets = 2;
}
}
void spiInit() {
_start("spiInit");
SPI.begin();
_end;
}
void spiBegin() {
SPI.beginTransaction(CC1101);
digitalWrite(CS, LOW);
}
void spiEnd() {
digitalWrite(CS, HIGH);
SPI.endTransaction();
}
uint8_t readReg(uint8_t reg) {
_start("readReg");
uint8_t val;
spiBegin();
SPI.transfer(reg);
val = SPI.transfer(reg);
spiEnd();
_end;
return (val);
}
void resetCC1101() {
_start("resetCC1101");
unsigned long start_time = micros();
// reset sequence per datasheet
pinMode(MISO, INPUT);
digitalWrite(MISO, HIGH);
digitalWrite(CS, LOW);
delay(1);
digitalWrite(CS, HIGH);
delay(1);
digitalWrite(CS, LOW);
while (digitalRead(MISO) == HIGH);
spiBegin();
SPI.transfer(CC1101_STROBE_SRES);
while (digitalRead(MISO) == HIGH);
spiEnd();
LOG(INFO, "reset took %lu us", micros() - start_time);
_end;
}
void chipInfo() {
_start("chipInfo");
StaticJsonDocument<JSON_OBJECT_SIZE(4)> chip_info;
chip_info["type"] = "chip_info";
// get status
chip_info["status"] = readReg(CC1101_STROBE_SNOP);
// get partnum
chip_info["partnum"] = readReg(CC1101_CMD_READ_BURST | CC1101_REG_PARTNUM);
// get version
chip_info["version"] = readReg(CC1101_CMD_READ_BURST | CC1101_REG_VERSION);
serializeJson(chip_info, Serial);
Serial.println();
_end;
}
void writeKiddeRegs() {
_start("writeKiddeRegs");
uint8_t kidde_regs_m[sizeof(kidde_regs)];
// save a few bytes of ram
memcpy_P(kidde_regs_m, kidde_regs, sizeof(kidde_regs));
// burst write regs for kidde receiver
spiBegin();
SPI.transfer(CC1101_CMD_WRITE_BURST | CC1101_REG_IOCFG2);
for (uint8_t reg = 0; reg < sizeof(kidde_regs_m); reg++) {
SPI.transfer(kidde_regs_m[reg]);
}
spiEnd();
_end;
}
void verifyKiddeRegs() {
_start("verifyKiddeRegs");
uint8_t kidde_regs_m[sizeof(kidde_regs)];
bool error = false;
// save a few bytes of ram
memcpy_P(kidde_regs_m, kidde_regs, sizeof(kidde_regs));
// burst read regs back to verify
spiBegin();
SPI.transfer(CC1101_CMD_READ_BURST | CC1101_REG_IOCFG2);
for (uint8_t reg = 0; reg < sizeof(kidde_regs_m); reg++) {
uint8_t val = SPI.transfer(0);
if (val != kidde_regs_m[reg]) {
error = true;
LOG(ERROR, "mismatch on read of 0x%02hhx: expected 0x%02hhx, got 0x%02hhx", reg, kidde_regs_m[reg], val);
}
}
spiEnd();
if (error)
resetBoard();
_end;
}
void calibrateCC1101() {
_start("calibrateCC1101");
unsigned long start_time = micros();
// frequency synthesizer calibration
spiBegin();
SPI.transfer(CC1101_STROBE_SCAL);
while (SPI.transfer(CC1101_STROBE_SNOP) & CC1101_STATUS_CAL)
delay(1);
spiEnd();
LOG(INFO, "calibration took %lu us", micros() - start_time);
_end;
}
void startRx() {
_start("startRx");
// put radio into receive mode
spiBegin();
SPI.transfer(CC1101_STROBE_SRX);
spiEnd();
_end;
}
void flushRxFifo() {
_start("flushRxFifo");
// flush rx fifo
spiBegin();
SPI.transfer(CC1101_STROBE_SFRX);
spiEnd();
_end;
}
void discardFifoBytes(uint8_t count) {
_start("discardFifoBytes");
spiBegin();
SPI.transfer(CC1101_CMD_READ_BURST | CC1101_RX_FIFO);
for (int pos = 0; pos < count; pos++) {
SPI.transfer(0);
}
spiEnd();
_end;
}
void rxPacket(struct kidde_pkt *pkt) {
_start("rxPacket");
memset(pkt, 0, sizeof(kidde_pkt));
// pull a packet's worth of bytes from the fifo
spiBegin();
SPI.transfer(CC1101_CMD_READ_BURST | CC1101_RX_FIFO);
pkt->address = SPI.transfer(0);
pkt->command = SPI.transfer(0);
pkt->suffix[0] = SPI.transfer(0);
pkt->suffix[1] = SPI.transfer(0);
pkt->rssi = SPI.transfer(0);
pkt->crc_lqi = SPI.transfer(0);
spiEnd();
_end;
}
void printPacket(struct kidde_pkt *pkt) {
_start("printPacket");
StaticJsonDocument<JSON_OBJECT_SIZE(9)> msg;
msg["millis"] = millis();
msg["type"] = "packet";
msg["command"] = kidde_strs[kiddeCmdMap(pkt->command)];
msg["address"] = pkt->address;
msg["raw_command"] = pkt->command;
msg["suffix"] = (uint16_t) (pkt->suffix[0] << 8) + pkt->suffix[1];
msg["rssi"] = pkt->rssi;
msg["crc"] = (bool) (pkt->crc_lqi >> 7);
msg["lqi"] = (pkt->crc_lqi & ~0x80);
serializeJson(msg, Serial);
Serial.println();
_end;
}
void initAlarmStates() {
_start("initAlarmStates");
memset(alarm_states, 0, sizeof(alarm_state) * NUM_CMDS * ADDRESS_MAX);
_end;
}
bool updateAlarmState(struct kidde_pkt *pkt, struct alarm_state *state) {
_start("updateAlarmState");
bool is_new = false;
if (!state->active) {
state->first = millis();
is_new = state->active = true;
state->min_rssi = state->max_rssi = pkt->rssi;
}
else {
if (pkt->rssi < state->min_rssi)
state->min_rssi = pkt->rssi;
if (pkt->rssi > state->max_rssi)
state->max_rssi = pkt->rssi;
}
state->count++;
state->last = millis();
_end;
return (is_new);
}
void printAlarmState(uint8_t address, uint8_t command, struct alarm_state *state) {
_start("printAlarmState");
StaticJsonDocument<JSON_OBJECT_SIZE(9)> msg;
msg["millis"] = millis();
msg["type"] = "alarm";
msg["address"] = address;
msg["command"] = kidde_strs[command];
msg["min_rssi"] = state->min_rssi;
msg["max_rssi"] = state->max_rssi;
msg["duration"] = state->last - state->first;
msg["count"] = state->count;
msg["active"] = state->active;
serializeJson(msg, Serial);
Serial.println();
_end;
}
void expireAlarm(uint8_t address, uint8_t command, struct alarm_state *state) {
_start("expireAlarm");
state->active = false;
printAlarmState(address, command, state);
memset(state, 0, sizeof(alarm_state));
_end;
}
void expireAlarmStates() {
_start("expireAlarmStates");
struct alarm_state *state;
for (uint8_t address = 0; address < s.address_cnt; address++) {
for (uint8_t command = 0; command < NUM_CMDS; command++) {
state = &alarm_states[address][command];
if (!state->active)
continue;
if ((millis() - state->last) < (s.expiry * 1000))
continue;
expireAlarm(s.address[address], command, state);
}
}
_end;
}
void expireAllAlarms() {
_start("expireAllAlarms");
uint16_t expiry = s.expiry;
// force any active alarms to expire
s.expiry = 0;
expireAlarmStates();
s.expiry = expiry;
initAlarmStates();
_end;
}
void processRxFifo() {
_start("processRxFifo");
uint8_t rx_bytes;
struct kidde_pkt pkt;
enum kidde_cmd mapped_cmd;
bool matched;
uint8_t address_idx;
struct alarm_state *state;
// handle the rest on the next loop() iteration
uint8_t max_packets = s_max_packets;
// blinky
digitalWrite(LED, HIGH);
// fetch bytes from fifo and parse packets
while (max_packets && (rx_bytes = readReg(CC1101_CMD_READ_BURST | CC1101_REG_RXBYTES)) >= sizeof(kidde_pkt)) {
if (rx_bytes & CC1101_RX_OVERFLOW) {
LOG(ERROR, "rx fifo overflow. flushing");
discardFifoBytes(rx_bytes & ~CC1101_RX_OVERFLOW);
flushRxFifo();
break;
}
LOG(DEBUG, "got packet. rx fifo has %u bytes", rx_bytes);
rxPacket(&pkt);
// don't let a flood of packets starve mcu (and watchdog)
max_packets--;
// print all packets, even if they're not addressed to us
// alarm state is not kept due to memory constraints
if (s.promisc) {
printPacket(&pkt);
continue;
}
// see if it's addressed to one of the addresses we care about
for (matched = false, address_idx = 0; address_idx < s.address_cnt; address_idx++) {
if (pkt.address == s.address[address_idx]) {
matched = true;
break;
}
}
// don't care
if (!matched)
continue;
mapped_cmd = kiddeCmdMap(pkt.command);
state = &alarm_states[address_idx][mapped_cmd];
// if there's already an active, unexpired alarm, take note and move on
if (!updateAlarmState(&pkt, state))
continue;
printAlarmState(pkt.address, mapped_cmd, state);
}
digitalWrite(LED, LOW);
_end;
}
bool eepromReadConfig() {
//_start("eepromReadConfig");
bool valid = false;
char magic[sizeof(EEPROM_MAGIC)];
uint16_t crc = 0;
struct settings S;
EEPROM.get(0, magic);
if (!strncmp(magic, EEPROM_MAGIC, sizeof(EEPROM_MAGIC))) {
EEPROM.get(sizeof(magic), crc);
//LOG(DEBUG, "crc is 0x%X", crc);
EEPROM.get(sizeof(EEPROM_MAGIC) + sizeof(crc), S);
if (crc == calcChecksum(&S)) {
s = S;
valid = true;
}
//else {
// LOG(ERROR, "checksum mismatch. calculated 0x%X != actual 0x%X", calcChecksum(&S), crc);
//}
}
//else {
// LOG(ERROR, "bad magic: %s", magic);
//}
//_end;
return (valid);
}
void eepromWriteConfig() {
_start("eepromWriteConfig");
uint8_t pos;
uint16_t crc = calcChecksum(&s);
uint8_t *s_bytes = (uint8_t *) &s;
for (pos = 0; pos < sizeof(EEPROM_MAGIC); pos++) {
LOG(DEBUG, "magic: wrote 0x%02X to %u", EEPROM_MAGIC[pos], pos);
EEPROM.put(pos, EEPROM_MAGIC[pos]);
}
EEPROM.put(pos, (byte) (crc & 0xFF));
LOG(DEBUG, "crc: wrote 0x%02X to %u", (byte) (crc & 0xFF), pos);
EEPROM.put(++pos, (byte) (crc >> 8));
LOG(DEBUG, "crc: wrote 0x%02X to %u", (byte) (crc >> 8), pos);
for (uint8_t b = 0; b < sizeof(s); b++) {
EEPROM.put(++pos, s_bytes[b]);
LOG(DEBUG, "s: wrote 0x%02X to %u", s_bytes[b], pos);
}
LOG(INFO, "wrote settings to eeprom");
_end;
}
void eepromClear() {
_start("eepromClear");
uint8_t length = sizeof(EEPROM_MAGIC) + sizeof(uint16_t) + sizeof(settings);
for (uint8_t pos = 0; pos < length; pos++)
EEPROM.put(pos, 0xFF);
LOG(INFO, "eeprom cleared");
_end;
}
uint16_t calcChecksum(struct settings *S) {
uint8_t *bytes = (uint8_t *) S;
uint16_t crc = 0;
for (uint8_t num = 0; num < sizeof(settings); num++)
crc = _crc16_update(crc, bytes[num]);
//LOG(DEBUG, "checksum is 0x%02X", crc);
return (crc);
}
void dumpConfig() {
_start("dumpConfig");
StaticJsonDocument<JSON_OBJECT_SIZE(4) + JSON_ARRAY_SIZE(ADDRESS_MAX)> config;
JsonArray address = config.createNestedArray("address");
for (uint8_t num = 0; num < s.address_cnt; num++)
address.add(s.address[num]);
config["expiry"] = s.expiry;
config["baud"] = s.baud;
config["promisc"] = s.promisc;
serializeJson(config, Serial);
Serial.println();
_end;
}
void parseCommand(char *input) {
_start("parseCommand");
StaticJsonDocument<JSON_OBJECT_SIZE(3) + JSON_ARRAY_SIZE(ADDRESS_MAX)> command;
DeserializationError err = deserializeJson(command, input);
if (err) {
LOG(ERROR, "bad json: %s", input);
}
else if (command["type"] == "get") {
getConfig(command);
}
else if (command["type"] == "set") {
setConfig(command);
}
else {
LOG(ERROR, "'type' unknown");
}
_end;
}
void getConfig(const JsonDocument& command) {
_start("getConfig");