-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathAskSin.cpp
2479 lines (2113 loc) · 104 KB
/
AskSin.cpp
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
//- -----------------------------------------------------------------------------------------------------------------------
// AskSin driver implementation
// 2013-08-03 <[email protected]> Creative Commons - http://creativecommons.org/licenses/by-nc-sa/3.0/de/
// Trx868 documentation https://github.com/ccier/openhm/wiki/Trx868
// Parser sketch from: http://jeelabs.org/2010/10/24/parsing-input-commands/
//- -----------------------------------------------------------------------------------------------------------------------
#include "AskSin.h"
s_pci pci;
s_prl prl;
//- ----------------------------------------------------------------------------------------------------------------------
//- CC1101 communication functions ----------------------------------------------------------------------------------------
//- -----------------------------------------------------------------------------------------------------------------------
const uint8_t initVal[] PROGMEM = { // define init settings for TRX868
0x00, 0x2E, // IOCFG2: tristate // non inverted GDO2, high impedance tri state
0x01, 0x2E, // IOCFG1: tristate // low output drive strength, non inverted GD=1, high impedance tri state
0x02, 0x06, // IOCFG0: packet CRC ok // disable temperature sensor, non inverted GDO0, asserts when a sync word has been sent/received, and de-asserts at the end of the packet. in RX, the pin will also de-assert when a package is discarded due to address or maximum length filtering
0x03, 0x0D, // FIFOTHR: TX:9 / RX:56 // 0 ADC retention, 0 close in RX, TX FIFO = 9 / RX FIFO = 56 byte
0x04, 0xE9, // SYNC1 // Sync word
0x05, 0xCA, // SYNC0
0x06, 0x3D, // PKTLEN(x): 61 // packet length 61
0x07, 0x0C, // PKTCTRL1: // PQT = 0, CRC auto flush = 1, append status = 1, no address check
0x0B, 0x06, // FSCTRL1: // frequency synthesizer control
0x0D, 0x21, // FREQ2
0x0E, 0x65, // FREQ1
0x0F, 0x6A, // FREQ0
0x10, 0xC8, // MDMCFG4
0x11, 0x93, // MDMCFG3
0x12, 0x03, // MDMCFG2
0x15, 0x34, // DEVIATN
0x16, 0x01, // MCSM2
0x17, 0x30, // MCSM1: always go into IDLE
0x18, 0x18, // MCSM0
0x19, 0x16, // FOCCFG
0x1B, 0x43, // AGCTRL2
//0x1E, 0x28, // ..WOREVT1: tEVENT0 = 50 ms, RX timeout = 390 us
//0x1F, 0xA0, // ..WOREVT0:
//0x20, 0xFB, // ..WORCTRL: EVENT1 = 3, WOR_RES = 0
0x21, 0x56, // FREND1
0x25, 0x00,
0x26, 0x11, // FSCAL0
0x2D, 0x35, // TEST1
0x3E, 0xC3, // ?
};
void CC::init(void) { // initialize CC1101
#if defined(CC_DBG)
Serial << F("CC1101_init: ");
#endif
pinMode(SS, OUTPUT); // set pins for SPI communication
pinMode(MOSI, OUTPUT);
pinMode(MISO, INPUT);
pinMode(SCK, OUTPUT);
pinMode(GDO0, INPUT); // config GDO0 as input
digitalWrite(SS, HIGH); // SPI init
digitalWrite(SCK, HIGH);
digitalWrite(MOSI, LOW);
SPCR = _BV(SPE) | _BV(MSTR); // SPI speed = CLK/4
cc1101_Deselect(); // some deselect and selects to init the TRX868modul
delayMicroseconds(5);
cc1101_Select();
delayMicroseconds(10);
cc1101_Deselect();
delayMicroseconds(41);
cmdStrobe(CC1101_SRES); // send reset
delay(10);
#if defined(CC_DBG)
Serial << '1';
#endif
for (uint8_t i=0; i<sizeof(initVal); i += 2) { // write init value to TRX868
writeReg(pgm_read_byte(&initVal[i]), pgm_read_byte(&initVal[i + 1]));
}
#if defined(CC_DBG)
Serial << '2';
#endif
cmdStrobe(CC1101_SCAL); // calibrate frequency synthesizer and turn it off
while (readReg(CC1101_MARcurStatTE, CC1101_STATUS) != 1) { // waits until module gets ready
delayMicroseconds(1);
#if defined(CC_DBG)
Serial << '.';
#endif
}
#if defined(CC_DBG)
Serial << '3';
#endif
writeReg(CC1101_PATABLE, PA_MaxPower); // configure PATABLE
cmdStrobe(CC1101_SRX); // flush the RX buffer
cmdStrobe(CC1101_SWORRST); // reset real time clock
#if defined(CC_DBG)
Serial << F(" - ready\n");
#endif
}
boolean CC::sendData(uint8_t *buf, uint8_t burst) { // send data packet via RF
// Going from RX to TX does not work if there was a reception less than 0.5
// sec ago. Due to CCA? Using IDLE helps to shorten this period(?)
//ccStrobe(CC1100_SIDLE);
//uint8_t cnt = 0xff;
//while(cnt-- && (ccStrobe( CC1100_STX ) & 0x70) != 2)
//my_delay_us(10);
cmdStrobe(CC1101_SIDLE); // go to idle mode
cmdStrobe(CC1101_SFRX ); // flush RX buffer
cmdStrobe(CC1101_SFTX ); // flush TX buffer
//Serial << "tx\n";
if (burst) { // BURST-bit set?
cmdStrobe(CC1101_STX ); // send a burst
delay(360); // according to ELV, devices get activated every 300ms, so send burst for 360ms
//Serial << "send burst\n";
} else {
delay(1); // wait a short time to set TX mode
}
writeBurst(CC1101_TXFIFO, buf, buf[0]+1); // write in TX FIFO
cmdStrobe(CC1101_SFRX); // flush the RX buffer
cmdStrobe(CC1101_STX); // send a burst
for(uint8_t i=0; i< 200;++i) { // after sending out all bytes the chip should go automatically in RX mode
if( readReg(CC1101_MARcurStatTE, CC1101_STATUS) == MARcurStatTE_RX)
break; //now in RX mode, good
if( readReg(CC1101_MARcurStatTE, CC1101_STATUS) != MARcurStatTE_TX) {
break; //neither in RX nor TX, probably some error
}
delayMicroseconds(10);
}
//uint8_t cnt = 0xff;
//while(cnt-- && (sendSPI(CC1101_SRX) & 0x70) != 1)
//delayMicroseconds(10);
#if defined(CC_DBG) // some debug message
Serial << F("<- ") << pHexL(&buf[0], buf[0]+1) << pTime();
#endif
//Serial << "rx\n";
return true;
}
uint8_t CC::receiveData(uint8_t *buf) { // read data packet from RX FIFO
uint8_t rxBytes = readReg(CC1101_RXBYTES, CC1101_STATUS); // how many bytes are in the buffer
if (rxBytes & 0x7F && !(rxBytes & 0x80)) { // any byte waiting to be read and no overflow?
buf[0] = readReg(CC1101_RXFIFO, CC1101_CONFIG); // read data length
if (buf[0] > CC1101_DATA_LEN) // if packet is too long
buf[0] = 0; // discard packet
else {
readBurst(&buf[1], CC1101_RXFIFO, buf[0]); // read data packet
readReg(CC1101_RXFIFO, CC1101_CONFIG); // read RSSI
uint8_t val = readReg(CC1101_RXFIFO, CC1101_CONFIG); // read LQI and CRC_OK
trx868.lqi = val & 0x7F;
trx868.crc_ok = bitRead(val, 7);
}
} else buf[0] = 0; // nothing to do, or overflow
cmdStrobe(CC1101_SFRX); // flush Rx FIFO
cmdStrobe(CC1101_SIDLE); // enter IDLE state
cmdStrobe(CC1101_SRX); // back to RX state
cmdStrobe(CC1101_SWORRST); // reset real time clock
// trx868.rfState = RFSTATE_RX; // declare to be in Rx state
#if defined(CC_DBG) // debug message, string should be short, otherwise program stops
if (buf[0] > 0) Serial << pHexL(&buf[1], buf[0]) << pTime();
#endif
return buf[0]; // return the data buffer
}
uint8_t CC::detectBurst(void) { // wake up CC1101 from power down state
// 10 7/10 5 in front of the received string; 33 after received string
// 10 - 00001010 - sync word found
// 7 - 00000111 - GDO0 = 1, GDO2 = 1
// 5 - 00000101 - GDO0 = 1, GDO2 = 1
// 33 - 00100001 - GDO0 = 1, preamble quality reached
// 96 - 01100000 - burst sent
// 48 - 00110000 - in receive mode
//
// Status byte table:
// 0 current GDO0 value
// 1 reserved
// 2 GDO2
// 3 sync word found
// 4 channel is clear
// 5 preamble quality reached
// 6 carrier sense
// 7 CRC ok
//
// possible solution for finding a burst is to check for bit 6, carrier sense
// set RXTX module in receive mode
cc1101_Select(); // select CC1101
wait_Miso(); // wait until MISO goes low
cc1101_Deselect(); // deselect CC1101
cmdStrobe(CC1101_SRX); // set RX mode again
delay(3); // wait a short time to set RX mode
// todo: check carrier sense for 5ms to avoid wakeup due to normal transmition
//Serial << "rx\n";
return bitRead(hm.cc.monitorStatus(),6); // return the detected signal
}
void CC::setPowerDownxtStatte() { // put CC1101 into power-down state
cmdStrobe(CC1101_SIDLE); // coming from RX state, we need to enter the IDLE state first
cmdStrobe(CC1101_SFRX);
cmdStrobe(CC1101_SPWD); // enter power down state
//Serial << "pd\n";
}
uint8_t CC::monitorStatus() {
return readReg(CC1101_PKTSTATUS, CC1101_STATUS);
}
uint8_t CC::sendSPI(uint8_t val) { // send byte via SPI
SPDR = val; // transfer byte via SPI
while(!(SPSR & _BV(SPIF))); // wait until SPI operation is terminated
return SPDR;
}
void CC::cmdStrobe(uint8_t cmd) { // send command strobe to the CC1101 IC via SPI
cc1101_Select(); // select CC1101
wait_Miso(); // wait until MISO goes low
sendSPI(cmd); // send strobe command
cc1101_Deselect(); // deselect CC1101
}
void CC::writeBurst(uint8_t regAddr, uint8_t *buf, uint8_t len) { // write multiple registers into the CC1101 IC via SPI
cc1101_Select(); // select CC1101
wait_Miso(); // wait until MISO goes low
sendSPI(regAddr | WRITE_BURST); // send register address
for(uint8_t i=0 ; i<len ; i++) sendSPI(buf[i]); // send value
cc1101_Deselect(); // deselect CC1101
}
void CC::readBurst(uint8_t *buf, uint8_t regAddr, uint8_t len) { // read burst data from CC1101 via SPI
cc1101_Select(); // select CC1101
wait_Miso(); // wait until MISO goes low
sendSPI(regAddr | READ_BURST); // send register address
for(uint8_t i=0 ; i<len ; i++) buf[i] = sendSPI(0x00); // read result byte by byte
cc1101_Deselect(); // deselect CC1101
}
uint8_t CC::readReg(uint8_t regAddr, uint8_t regType) { // read CC1101 register via SPI
cc1101_Select(); // select CC1101
wait_Miso(); // wait until MISO goes low
sendSPI(regAddr | regType); // send register address
uint8_t val = sendSPI(0x00); // read result
cc1101_Deselect(); // deselect CC1101
return val;
}
void CC::writeReg(uint8_t regAddr, uint8_t val) { // write single register into the CC1101 IC via SPI
cc1101_Select(); // select CC1101
wait_Miso(); // wait until MISO goes low
sendSPI(regAddr); // send register address
sendSPI(val); // send value
cc1101_Deselect(); // deselect CC1101
}
//- -----------------------------------------------------------------------------------------------------------------------
//- status led functions --------------------------------------------------------------------------------------------------
//- -----------------------------------------------------------------------------------------------------------------------
void LD::config(uint8_t tPin) {
pin = tPin;
pinMode(tPin, OUTPUT); // setting the pin to output mode
}
void LD::poll() {
if ((nTime == 0) || (nTime > millis())) return; // nothing to do or wrong time to do
if (mode == 0) { // led off
off();
nTime = 0;
} else if (mode == 1) { // led on
on();
nTime = 0;
} else if (mode == 2) { // blink slow
toggle();
nTime = millis() + slowRate;
} else if (mode == 3) { // blink fast
toggle();
nTime = millis() + fastRate;
} else if (mode == 4) { // blink short one
if (!bCnt++) {
on();
nTime = millis() + fastRate;
} else set(0);
} else if (mode == 5) { // blink short three
if (bCnt++ >= 5) set(0);
toggle();
nTime = millis() + fastRate;
} else if (mode == 6) { // heartbeat
if (bCnt > 3) bCnt = 0;
toggle();
nTime = millis() + heartBeat[bCnt++];
}
}
void LD::set(uint8_t tMode) {
mode = tMode;
bCnt = 0;
nTime = millis();
}
void LD::stop() {
digitalWrite(pin,0); // switch led off
mode = 0;
bCnt = 0;
nTime = 0;
state = 0;
}
void LD::shortBlink() {
on();
delay(50);
off();
delay(50);
}
void LD::shortBlink3() {
shortBlink();
shortBlink();
shortBlink();
}
void LD::on() {
digitalWrite(pin,1); // switch led on
state = 1;
}
void LD::off() {
digitalWrite(pin,0); // switch led off
state = 0;
}
void LD::toggle() {
if (state) off();
else on();
}
//- -----------------------------------------------------------------------------------------------------------------------
//- AskSin protocol functions ---------------------------------------------------------------------------------------------
//- with a lot of support from martin876 at FHEM forum
//- -----------------------------------------------------------------------------------------------------------------------
// general functions for initializing and operating of module
HM::HM(s_jumptable *jtPtr, void *mcPtr) {
jTblPtr = jtPtr; // jump table for call back functions
mcConfPtr = (uint16_t)mcPtr; // store pointer to main channel structure
}
void HM::init() { // starts also the send/receive class for the rf module
cc.init(); // init the TRX module
initRegisters(); // init the storage management module
setPowerMode(0); // set default power mode of HM device
delay(100); // otherwise we get a problem with serial console
enableIRQ_GDO0(); // attach callback function for GDO0 (INT0)
}
void HM::poll() { // task scheduler
if (recv.data[0] > 0) recv_poll(); // trace the received string and decide what to do further
if (send.counter > 0) send_poll(); // something to send in the buffer?
if (conf.act > 0) send_conf_poll(); // some config to be send out
if (pevt.act > 0) send_peer_poll(); // send peer events
power_poll();
ld.poll();
}
void HM::send_out() {
if (bitRead(send.data[2],5)) send.retries = maxRetries; // check for ACK request and set max retries counter
else send.retries = 1; // otherwise send only one time
send.burst = bitRead(send.data[2],4); // burst necessary?
if (memcmp(&send.data[7], HMID, 3) == 0) { // if the message is addressed to us,
memcpy(recv.data,send.data,send.data[0]+1); // then copy in receive buffer. could be the case while sending from serial console
}
send.counter = 1;
/*
send.counter = 0; // no need to fire
} else { // it's not for us, so encode and put in send queue
send.counter = 1; // and fire
}*/
}
void HM::reset(void) {
setEEpromBlock((uint16_t)&ee->magNbr,2,(uint8_t*) &broadCast); // clear magic byte in eeprom and step in initRegisters
initRegisters(); // reload the registers
ld.stop(); // stop blinking
ld.shortBlink3(); // blink three times short
}
void HM::setConfigEvent(void) {
s_jumptable x;
for (s_jumptable* p = jTblPtr; ; ++p) { // find the call back function
x.code = pgm_read_byte(&p->code); // get back variables, because they are in program memory
x.spec = pgm_read_byte(&p->spec);
x.fun = (void (*)(uint8_t, uint8_t*, uint8_t))pgm_read_word(&p->fun);
if ((x.code == 0xFF) && (x.spec == 0xFF)) {
x.fun(0,(uint8_t*) &broadCast,0);
break; // and jump into
}
}
}
void HM::setPowerMode(uint8_t mode) {
// there are 3 power modes for the TRX868 module
// TX mode will switched on while something is in the send queue
// 0 - RX mode enabled by default, take approx 17ma
// 1 - RX is in burst mode, RX will be switched on every 250ms to check if there is a carrier signal
// if yes - RX will stay enabled until timeout is reached, prolongation of timeout via receive function seems not necessary
// to be able to receive an ACK, RX mode should be switched on by send function
// if no - RX will go in idle mode and wait for the next carrier sense check
// 2 - RX is off by default, TX mode is enabled while sending something
// configuration mode is required in this setup to be able to receive at least pairing and config request strings
// should be realized by a 30 sec timeout function for RX mode
// as output we need a status indication if TRX868 module is in receive, send or idle mode
// idle mode is then the indication for power down mode of AVR
switch (mode) {
case 1: // no power savings, RX is in receiving mode
powr.mode = 1; // set power mode
set_sleep_mode(SLEEP_MODE_IDLE); // normal power saving
break;
case 2: // some power savings, RX is in burst mode
powr.mode = 2; // set power mode
powr.parTO = 15000; // pairing timeout
powr.minTO = 2000; // stay awake for 2 seconds after sending
powr.nxtTO = millis() + 250; // check in 250ms for a burst signal
MCUSR &= ~(1<<WDRF); // clear the reset flag
WDTCSR |= (1<<WDCE) | (1<<WDE); // set control register to change enabled and enable the watch dog
WDTCSR = 1<<WDP2; // 250 ms
powr.wdTme = 256; // store the watch dog time for adding in the poll function
set_sleep_mode(SLEEP_MODE_PWR_DOWN); // max power saving
break;
case 3: // most power savings, RX is off beside a special function where RX stay in receive for 30 sec
MCUSR &= ~(1<<WDRF); // clear the reset flag
WDTCSR |= (1<<WDCE) | (1<<WDE); // set control register to change enabled and enable the watch dog
//WDTCSR = 1<<WDP2; // 250 ms
//WDTCSR = 1<<WDP1 | 1<<WDP2; // 1000 ms
//WDTCSR = 1<<WDP0 | 1<<WDP1 | 1<<WDP2; // 2000 ms
WDTCSR = 1<<WDP0 | 1<<WDP3; // 8000 ms
powr.wdTme = 8190; // store the watch dog time for adding in the poll function
case 4: // most power savings, RX is off beside a special function where RX stay in receive for 30 sec
powr.mode = mode; // set power mode
powr.parTO = 15000; // pairing timeout
powr.minTO = 1000; // stay awake for 1 seconds after sending
powr.nxtTO = millis() + 4000; // stay 4 seconds awake to finish boot time
set_sleep_mode(SLEEP_MODE_PWR_DOWN); // max power saving
ld.set(2); // blink the led to show it is awake
break;
default: // no power saving, same as case 0, if user had chosen a wrong power saving mode
powr.mode = 0; // set power mode
}
powr.state = 1; // after init of the TRX module it is in RX mode
//Serial << "pwr.mode:" << powr.mode << '\n';
}
void HM::stayAwake(uint32_t xMillis) {
if (powr.state == 0) cc.detectBurst(); // if TRX is in sleep, switch it on
powr.state = 1; // remember TRX state
powr.nxtTO = millis() + xMillis; // stay awake for some time by setting next check time
}
// external functions for pairing and communicating with the module
void HM::startPairing(void) { // send a pairing request to master
// 01 02 03 04 05 06 07
// 1A 00 A2 00 3F A6 5C 00 00 00 10 80 02 50 53 30 30 30 30 30 30 30 31 9F 04 01 01
if (powr.mode > 1) stayAwake(powr.parTO); // stay awake for the next 30 seconds
memcpy_P(send_payLoad, devParam, 17); // copy details out of register.h
send_prep(send.mCnt++,0xA2,0x00,regDev.pairCentral,send_payLoad,17);
}
void HM::sendInfoActuatorStatus(uint8_t cnl, uint8_t status, uint8_t flag) {
if (memcmp(regDev.pairCentral,broadCast,3) == 0) return; // not paired, nothing to send
// "10;p01=06" => { txt => "INFO_ACTUATOR_STATUS", params => {
// CHANNEL => "2,2",
// STATUS => '4,2',
// UNKNOWN => "6,2",
// RSSI => '08,02,$val=(-1)*(hex($val))' } },
send_payLoad[0] = 0x06; // INFO_ACTUATOR_STATUS
send_payLoad[1] = cnl; // channel
send_payLoad[2] = status; // status
send_payLoad[3] = flag; // unknown
send_payLoad[4] = cc.trx868.rssi; // RSSI
// if it is an answer to a CONFIG_STATUS_REQUEST we have to use the same message id as the request
uint8_t tCnt;
if ((recv.data[3] == 0x01) && (recv.data[11] == 0x0E)) tCnt = recv_rCnt;
else tCnt = send.mCnt++;
send_prep(tCnt,0xA4,0x10,regDev.pairCentral,send_payLoad,5); // prepare the message
}
void HM::sendACKStatus(uint8_t cnl, uint8_t status, uint8_t douolo) {
//if (memcmp(regDev.pairCentral,broadCast,3) == 0) return; // not paired, nothing to send
// "02;p01=01" => { txt => "ACK_STATUS", params => {
// CHANNEL => "02,2",
// STATUS => "04,2",
// DOWN => '06,02,$val=(hex($val)&0x20)?1:0',
// UP => '06,02,$val=(hex($val)&0x10)?1:0',
// LOWBAT => '06,02,$val=(hex($val)&0x80)?1:0',
// RSSI => '08,02,$val=(-1)*(hex($val))', }},
send_payLoad[0] = 0x01; // ACK Status
send_payLoad[1] = cnl; // channel
send_payLoad[2] = status; // status
send_payLoad[3] = douolo; // down, up, low battery
send_payLoad[4] = cc.trx868.rssi; // RSSI
// l> 0E EA 80 02 1F B7 4A 63 19 63 01 01 C8 00 4B
//send_prep(recv_rCnt,0x80,0x02,regDev.pairCentral,send_payLoad,5); // prepare the message
send_prep(recv_rCnt,0x80,0x02,recv_reID,send_payLoad,5); // prepare the message
}
void HM::sendSensorData(uint32_t energyCounter, uint32_t power, uint16_t current, uint16_t voltage, uint8_t frequency) {
if (memcmp(regDev.pairCentral,broadCast,3) == 0) return; // not paired, nothing to send
// energy counter 3 Bytes
// power: 3 Bytes
// current: 2 Bytes
// voltage: 2 Bytes
// frequency: 1 Byte
send_payLoad[0] = energyCounter >> 16;
send_payLoad[1] = energyCounter >> 8;
send_payLoad[2] = energyCounter;
send_payLoad[3] = power >> 16;
send_payLoad[4] = power >> 8;
send_payLoad[5] = power;
send_payLoad[6] = current >> 8;
send_payLoad[7] = current;
send_payLoad[8] = voltage >> 8;
send_payLoad[9] = voltage;
send_payLoad[10] = frequency;
send_prep(send.mCnt++,0x80,0x5E,regDev.pairCentral,send_payLoad,11); // prepare the message // short led blink
}
void HM::sendPeerREMOTE(uint8_t button, uint8_t longPress, uint8_t lowBat) {
// no data needed, because it is a (40)REMOTE EVENT
// "40" => { txt => "REMOTE" , params => {
// BUTTON => '00,2,$val=(hex($val)&0x3F)',
// LONG => '00,2,$val=(hex($val)&0x40)?1:0',
// LOWBAT => '00,2,$val=(hex($val)&0x80)?1:0',
// COUNTER => "02,2", } },
if (button > maxChannel) return; // channel out of range, do nothing
if (doesListExist(button,4) == 0) { // check if a list4 exist, otherwise leave
//Serial << "sendPeerREMOTE failed\n";
return;
}
// set variables in struct and make send_peer_poll active
pevt.cnl = button; // peer database channel
pevt.type = 0x40; // message type
pevt.mFlg = (uint8_t)((longPress == 1)?0x80:0xA0); // no ACK needed while long key press is send
pevt.data[0] = button | ((longPress)?1:0) << 6 | lowBat << 7; // construct message
pevt.data[1] = pevt.mCnt[pevt.cnl-1];
pevt.len = 2; // 2 bytes payload
pevt.act = 1; // active, 1 = yes, 0 = no
ld.shortBlink(); // short led blink
if (longPress != 1) {
++pevt.mCnt[pevt.cnl-1]; // increase event counter except for long press (until long press end)
}
}
void HM::sendPeerRAW(uint8_t cnl, uint8_t type, uint8_t *data, uint8_t len) {
// validate the input, and fill the respective variables in the struct
// message handling is taken from send_peer_poll
if (cnl > maxChannel) return; // channel out of range, do nothing
if (pevt.act) return; // already sending an event, leave
if (doesListExist(cnl,4) == 0) { // check if a list4 exist, otherwise leave
//Serial << "sendPeerREMOTE failed\n";
return;
}
// set variables in struct and make send_peer_poll active
pevt.cnl = cnl; // peer database channel
pevt.type = type; // message type
pevt.mFlg = 0xA2;
if (len > 0) { // copy data if there are some
memcpy(pevt.data, data, len); // data to send
pevt.len = len; // len of data to send
}
pevt.act = 1; // active, 1 = yes, 0 = no
ld.shortBlink(); // short led blink
}
void HM::send_ACK(void) {
uint8_t payLoad[] = {0x00}; // ACK
send_prep(recv_rCnt,0x80,0x02,recv_reID,payLoad,1);
}
void HM::send_NACK(void) {
uint8_t payLoad[] = {0x80}; // NACK
send_prep(recv_rCnt,0x80,0x02,recv_reID,payLoad,1);
}
#if defined(USE_SERIAL)
// some debug functions
void HM::printSettings() {
Serial << F("Serial: ");
for (int i = 0; i < 10; i++) { // serial number has 10 bytes
Serial << (char)pgm_read_byte(&(devParam[i+3])); // get the serial number from program space
}
Serial << F(", Model ID: ");
for (int i = 0; i < 2; i++) { // model id has 2 bytes
Serial << pHex(pgm_read_byte(&(devParam[i+1]))) << ' '; // get the model id from program space
}
Serial << F(", HMID: ") << pHex(HMID,3) << '\n'; // displays the own id
Serial << F("Paired: ") << pHex(regDev.pairCentral,3) << F("\n\n"); // pairing id
}
void HM::printConfig() {
s_slcVar sV; // size some variables
uint8_t peer[] = {0xff,0xff,0xff,0x00,0x00,0x00,0x00,0x00};
// show device config
Serial << F("\nDevice config, size: ") << sizeof(ee) << F(" byte\n");
Serial << F("cnl\tlst\tslcPtr\tslcEnd\tphyAddr\tphyLen\n");
for (uint8_t i = 0; i < 20; i++) { // count through the channel
for (uint8_t j = 0; j < 20; j++) { // count through the lists
if (!getSliceDetail(i, j, &peer[0], &sV)) continue; // get the slice details
Serial << i << '\t' << j << '\t' << sV.slcPtr << '\t' << sV.slcLen << '\t' << sV.phyAddr << '\t' << sV.phyLen << '\n';
}
}
// step through the complete channel list
Serial << F("\nPeer Database, size: ") << sizeof(peerdb) << F(" byte\n"); // some headline
Serial << F("cnl\tpIdx\tslcPtr\tslcEnd\tphyAddr\tphyLen\tlist\tpeer\n");
for (uint8_t i = 0; i < 20; i++) { // step through all channels
// check if we have a list3 or list4
uint8_t lst = 0;
if (doesListExist(i+1, 3)) lst = 3; // check for list3
if (doesListExist(i+1, 4)) lst = 4; // check for list4
if (lst == 0) continue; // no list3 or list4 therefore next i
// step through the peers
for (uint8_t j = 0; j < 20; j++) { // step through all possible peers
if (!getPeerByIdx(i+1,j,&peer[4])) continue; // ask for the peer by channel and peer index
peer[3] = j; // store the peer channel byte
if (!getSliceDetail(i+1, lst, &peer[0], &sV)) continue; // ask for the slice details as list3
Serial << (i+1) << '\t' << (j) << '\t' << sV.slcPtr << '\t' << sV.slcLen << '\t' << sV.phyAddr << '\t' << sV.phyLen << '\t' << lst << '\t'; // print the slice details
Serial << pHex(&peer[4],4) << '\n'; // and print the peer incl peer channel
}
}
Serial << '\n';
}
#endif
//- private: //------------------------------------------------------------------------------------------------------------
// hardware definition for interrupt handling
void HM::isrGDO0event(void) {
disableIRQ_GDO0(); // disable interrupt otherwise we could get some new content while we copy the buffer
if (hm.cc.receiveData(hm.recv.data)) { // is something in the receive string
hm.hm_dec(hm.recv.data); // decode the content
}
enableIRQ_GDO0(); // enable the interrupt again
}
// some polling functions
void HM::recv_poll(void) { // handles the receive objects
// do some checkups
if (memcmp(&recv.data[7], HMID, 3) == 0) recv.forUs = 1; // for us
else recv.forUs = 0;
if (memcmp(&recv.data[7], broadCast, 3) == 0) recv.bCast = 1; // or a broadcast
else recv.bCast = 0; // otherwise only a log message
// show debug message
#if defined(AS_DBG) // some debug message
if(recv.forUs) Serial << F("-> ");
else if(recv.bCast) Serial << F("b> ");
else Serial << F("l> ");
Serial << pHexL(recv.data, recv.data[0]+1) << pTime();
exMsg(recv.data); // explain message
#endif
// is the message from a valid sender (pair or peer), if not then exit - takes ~2ms
if ((isPairKnown(recv_reID) == 0) && (isPeerKnown(recv_reID) == 0)) { // check against peers
#if defined(AS_DBG) // some debug message
//Serial << "pair/peer did not fit, exit\n";
#endif
recv.data[0] = 0; // clear receive string
return;
}
// check if it was a repeated message, delete while already received - takes ~2ms
if (bitRead(recv.data[2],6)) { // check repeated flag
bitSet(recv.p_data[2],6); // set repeated flag in prev received string
uint16_t ret = memcmp(recv.p_data,recv.data,recv.data[0]+1); // compare with already received string
#if defined(AS_DBG) // some debug message
Serial << F(" repeated message; ");
if (ret == 0) Serial << F("already received - skip\n");
else Serial << F("not received before...\n");
#endif
if (ret == 0) { // already received
recv.data[0] = 0; // therefore ignore
return; // and skip
}
}
memcpy(recv.p_data,recv.data,recv.data[0]+1); // save received string for next compare
// decide where to jump in
if((recv.forUs) && (recv_isMsg) && (recv_msgTp == 0x01)) { // message is a config message
if (recv_by11 == 0x01) recv_ConfigPeerAdd(); // 01, 01
else if (recv_by11 == 0x02) recv_ConfigPeerRemove(); // 01, 02
else if (recv_by11 == 0x03) recv_ConfigPeerListReq(); // 01, 03
else if (recv_by11 == 0x04) recv_ConfigParamReq(); // 01, 04
else if (recv_by11 == 0x05) recv_ConfigStart(); // 01, 05
else if (recv_by11 == 0x06) recv_ConfigEnd(); // 01, 06
else if (recv_by11 == 0x08) recv_ConfigWriteIndex(); // 01, 08
else if (recv_by11 == 0x09) recv_ConfigSerialReq(); // 01, 09
else if (recv_by11 == 0x0A) recv_Pair_Serial(); // 01, 0A
else if (recv_by11 == 0x0E) recv_ConfigStatusReq(); // 01, 0E
#if defined(AS_DBG) // some debug message
else Serial << F("\nUNKNOWN MESSAGE, PLEASE REPORT!\n\n");
#endif
}
// l> 0A 73 80 02 63 19 63 2F B7 4A 00
if((recv.forUs) && (recv_isMsg) && (recv_msgTp == 0x02)) { // message seems to be an ACK
send.counter = 0;
}
if((recv.forUs) && (recv_isMsg) && (recv_msgTp == 0x11)) {
recv_PairEvent();
}
if((recv.forUs) && (recv.data[2] == 0x30) && (recv_msgTp == 0x11)) {
recv_UpdateEvent();
}
if((recv.forUs) && (recv_isMsg) && (recv_msgTp >= 0x12)) {
recv_PeerEvent();
}
//to do: if it is a broadcast message, do something with
recv.data[0] = 0; // otherwise ignore
}
void HM::send_poll(void) { // handles the send queue
if((send.counter <= send.retries) && (send.timer <= millis())) { // not all sends done and timing is OK
// here we encode and send the string
hm_enc(send.data); // encode the string
disableIRQ_GDO0(); // disable interrupt otherwise we could get some new content while we copy the buffer
cc.sendData(send.data,send.burst); // and send
enableIRQ_GDO0(); // enable the interrupt again
hm_dec(send.data); // decode the string
// setting some variables
send.counter++; // increase send counter
send.timer = millis() + timeOut; // set the timer for next action
powr.state = 1; // remember TRX module status, after sending it is always in RX mode
if ((powr.mode > 0) && (powr.nxtTO < (millis() + powr.minTO))) stayAwake(powr.minTO); // stay awake for some time
#if defined(AS_DBG) // some debug messages
Serial << F("<- ") << pHexL(send.data, send.data[0]+1) << pTime();
#endif
}
if((send.counter > send.retries) && (send.counter < maxRetries)) { // all send but don't wait for an ACK
send.counter = 0; send.timer = 0; // clear send flag
}
if((send.counter > send.retries) && (send.timer <= millis())) { // max retries achieved, but seems to have no answer
send.counter = 0; send.timer = 0; // cleanup of send buffer
// todo: error handling, here we could jump some were to blink a led or whatever
#if defined(AS_DBG)
Serial << F("-> NA ") << pTime();
#endif
}
} // ready, should work
void HM::send_conf_poll(void) {
if (send.counter > 0) return; // send queue is busy, let's wait
uint8_t len;
if (conf.type == 0x01) {
// answer Cnl Peer Peer Peer Peer
// l> 1A 05 A0 10 1E 7A AD 63 19 63 01 1F A6 5C 02 1F A6 5C 01 11 22 33 02 11 22 33 01
// Cnl Termination
// l> 0E 06 A0 10 1E 7A AD 63 19 63 01 00 00 00 00
len = getPeerListForMsg(conf.channel, send_payLoad+1); // get peer list
if (len == 0x00) { // check if all done
memset(&conf, 0, sizeof(conf)); // clear the channel struct
return; // exit
} else if (len == 0xff) { // failure, out of range
memset(&conf, 0, sizeof(conf)); // clear the channel struct
send_NACK();
} else { // seems to be ok, answer
send_payLoad[0] = 0x01; // INFO_PEER_LIST
send_prep(conf.mCnt++,0xA0,0x10,conf.reID,send_payLoad,len+1); // prepare the message
//send_prep(send.mCnt++,0xA0,0x10,conf.reID,send_payLoad,len+1); // prepare the message
}
} else if (conf.type == 0x02) {
// INFO_PARAM_RESPONSE_PAIRS message
// RegL_01: 30:06 32:50 34:4B 35:50 56:00 57:24 58:01 59:01 00:00
// l> 1A 04 A0 10 1E 7A AD 63 19 63 02 30 06 32 50 34 4B 35 50 56 00 57 24 58 01 59 01 (l:27)(131405)
//Serial << "hab dich\n";
len = getListForMsg2(conf.channel, conf.list, conf.peer, send_payLoad+1); // get the message
if (len == 0) { // check if all done
memset(&conf, 0, sizeof(conf)); // clear the channel struct
return; // and exit
} else if (len == 0xff) { // failure, out of range
memset(&conf, 0, sizeof(conf)); // clear the channel struct
send_NACK();
} else { // seems to be ok, answer
send_payLoad[0] = 0x02; // INFO_PARAM_RESPONSE_PAIRS
send_prep(conf.mCnt++,0xA0,0x10,conf.reID,send_payLoad,len+1); // prepare the message
//send_prep(send.mCnt++,0xA0,0x10,conf.reID,send_payLoad,len+1); // prepare the message
}
} else if (conf.type == 0x03) {
// INFO_PARAM_RESPONSE_SEQ message
// RegL_01: 30:06 32:50 34:4B 35:50 56:00 57:24 58:01 59:01 00:00
// l> 1A 04 A0 10 1E 7A AD 63 19 63 02 30 06 32 50 34 4B 35 50 56 00 57 24 58 01 59 01 (l:27)(131405)
}
}
void HM::send_peer_poll(void) {
// go through the peer database and get the idx per slot, load the respective list4
// if no peer exist in the respective channel then send to master
// send out the message accordingly, loop until send_poll is clear and start the next peer.
// if the message was a long key press, then prepare the struct for sending out a last message
// with ACK requested
if (send.counter > 0) return; // something is in the send queue, lets wait for the next free slot
// we are in a loop, therefore check if the request is completed and clear struct
if (pevt.idx >= peermax[pevt.cnl-1]) { // we are through the list of peers, clear variables
// check if a message was send to at least on device, if not send to master
if (pevt.sta == 0) send_prep(send.mCnt++,(bitRead(pevt.mFlg,5)?0xA2:0x82),pevt.type,regDev.pairCentral,pevt.data,pevt.len);
pevt.idx = 0; pevt.sta = 0; pevt.act = 0; // clear struct object, no need to jump in again
return;
}
// prepare the next peer address
//Serial << "cnl: " << pevt.cnl << ", idx: " << pevt.idx << '\n';
uint8_t peerBuf[4];
uint8_t ret = getPeerByIdx(pevt.cnl,pevt.idx,peerBuf); // get the respective peer from database
if ((memcmp(peerBuf,broadCast,4) == 0) || (ret == 0)) { // if peer is empty, increase the idx and leave while we are in a loop
pevt.idx++;
return;
}
// get the respective list4
s_slcVar sV; // some declarations
uint8_t regLstByte = 0;
ret = getSliceDetail(pevt.cnl, 4, peerBuf, &sV); // get cnl list4
if (ret) {
// at the moment we are looking only for register address 1 in list 4 (peerNeedsBurst, expectAES), list 4 will not be available in user space
uint8_t tLst[sV.phyLen]; // size a variable
ret = getRegList(sV.slcPtr, sV.slcLen, tLst); // get the register in the variable
void *x = memchr(tLst, 0x01, sV.phyLen); // search the character in the address string
if ((uint16_t)x) { // if we found the searched string
uint16_t dataPtr = (uint16_t)x-(uint16_t)tLst; // calculate the respective address in list
regLstByte = getEEpromByte(dataPtr+(uint16_t)&ee->regs+sV.phyAddr); // get the respective byte
//Serial << "get byte: " << pHex(regLstByte) << '\n';
//Serial << "dataPtr:" << dataPtr << ", phyAddr:" << sV.phyAddr << ", eepromAddr:" << (uint16_t)&sEEPROM->regs << '\n';
}
//Serial << "peer: " << pHex(peerBuf,4) << ", tLst: " << pHex(tLst,sV.phyLen) << ", rB: " << regLstByte << '\n';
}
// in regLstByte there are two information. peer needs AES and burst needed
// AES will be ignored at the moment, but burst needed will be translated into the message flag - bit 0 in regLstByte, translated to bit 4 = burst transmission in msgFlag
uint8_t mFlg = pevt.mFlg; // copy the message flag
mFlg |= bitRead(regLstByte,0) << 4; // read the need burst flag
// prepare send string and increase timer
send_prep(send.mCnt++,mFlg,pevt.type,peerBuf,pevt.data,pevt.len); // prepare the message
pevt.sta = 1; // indicates that we had found a peer and string was send
pevt.idx++; // increase idx for next try
}
void HM::power_poll(void) {
// there are 3 power modes for the TRX868 module
// TX mode will switched on while something is in the send queue
// 1 - RX mode enabled by default, take approx 17ma
// 2 - RX is in burst mode, RX will be switched on every 250ms to check if there is a carrier signal
// if yes - RX will stay enabled until timeout is reached, prolongation of timeout via receive function seems not necessary
// to be able to receive an ACK, RX mode should be switched on by send function
// if no - RX will go in idle mode and wait for the next carrier sense check
// 3 - RX is off by default, TX mode is enabled while sending something
// configuration mode is required in this setup to be able to receive at least pairing and config request strings
// should be realized by a 15 sec timeout function for RX mode
// system time in millis will be hold by a regular wakeup from the watchdog timer
// 4 - Same as power mode 3 but without watchdog
if (powr.mode == 0) return; // in mode 0 there is nothing to do
if (powr.nxtTO > millis()) return; // no need to do anything
if (send.counter > 0) return; // send queue not empty
// power mode 2, module is in sleep and next check is reached
if ((powr.mode == 2) && (powr.state == 0)) {
if (cc.detectBurst()) { // check for a burst signal, if we have one, we should stay awake
powr.nxtTO = millis() + powr.minTO; // schedule next timeout with some delay
} else { // no burst was detected, go to sleep in next cycle
powr.nxtTO = millis(); // set timer accordingly
}
powr.state = 1; // set status to awake
return;
}
// power mode 2, module is active and next check is reached
if ((powr.mode == 2) && (powr.state == 1)) {
cc.setPowerDownxtStatte(); // go to sleep
powr.state = 0;
powr.nxtTO = millis() + 250; // schedule next check in 250 ms
}
// power mode 3, check RX mode against timer. typically RX is off beside a special command to switch RX on for at least 30 seconds
if ((powr.mode >= 3) && (powr.state == 1)) {
cc.setPowerDownxtStatte(); // go to sleep
powr.state = 0;
}
// sleep for mode 2, 3 and 4
if ((powr.mode > 1) && (powr.state == 0)) { // TRX module is off, so lets sleep for a while
ld.stop(); // stop blinking, because we are going to sleep
if ((powr.mode == 2) || (powr.mode == 3)) WDTCSR |= (1<<WDIE); // enable watch dog if power mode 2 or 3
ADCSRA = 0; // disable ADC
uint8_t xPrr = PRR; // turn off various modules
PRR = 0xFF;
sleep_enable(); // enable the sleep mode
// MCUCR |= (1<<BODS) | (1<<BODSE); // turn off brown-out enable in software
// MCUCR &= ~(1<<BODSE); // must be done right before sleep
sleep_cpu(); // goto sleep
/* wake up here */
sleep_disable(); // disable sleep
if ((powr.mode == 2) || (powr.mode == 3)) WDTCSR &= ~(1<<WDIE); // disable watch dog
PRR = xPrr; // restore modules
if (wd_flag == 1) { // add the watchdog time to millis()
wd_flag = 0; // to detect the next watch dog timeout
timer0_millis += powr.wdTme; // add watchdog time to millis() function
} else {
stayAwake(powr.minTO); // stay awake for some time, if the wakeup where not raised from watchdog
}
ld.set(2); // blink the led to show it is awake
}
}
// receive message handling
void HM::recv_ConfigPeerAdd(void) {
// description --------------------------------------------------------
// Cnl PeerID PeerCnl_A PeerCnl_B
// l> 10 55 A0 01 63 19 63 1E 7A AD 03 01 1F A6 5C 06 05
// do something with the information ----------------------------------
addPeerFromMsg(recv_payLoad[0], recv_payLoad+2);
// send appropriate answer ---------------------------------------------
// l> 0A 55 80 02 1E 7A AD 63 19 63 00
if (recv_ackRq) send_ACK(); // send ACK if requested
//if ((recv_ackRq) && (ret == 1)) send_ACK();
//else if (recv_ackRq) send_NACK();
}
void HM::recv_ConfigPeerRemove(void) {
// description --------------------------------------------------------
// Cnl PeerID PeerCnl_A PeerCnl_B
// l> 10 55 A0 01 63 19 63 1E 7A AD 03 02 1F A6 5C 06 05
// do something with the information ----------------------------------
removePeerFromMsg(recv_payLoad[0], recv_payLoad+2);
// send appropriate answer ---------------------------------------------
// l> 0A 55 80 02 1E 7A AD 63 19 63 00
if (recv_ackRq) send_ACK();
//if ((recv_ackRq) && (ret == 1)) send_ACK(); // send ACK if requested
//else if (recv_ackRq) send_NACK();