-
-
Notifications
You must be signed in to change notification settings - Fork 160
/
rf.cpp
1664 lines (1453 loc) · 57.3 KB
/
rf.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
//@IncursioHack - github.com/IncursioHack
#include <driver/rmt.h>
#include <RCSwitch.h>
#include <ELECHOUSE_CC1101_SRC_DRV.h>
#include "PCA9554.h"
#include "core/globals.h"
#include "core/mykeyboard.h"
#include "core/display.h"
#include "core/sd_functions.h"
#include "core/settings.h"
#include "rf.h"
#include <iostream>
#include <string>
#include <sstream>
// Cria um objeto PCA9554 com o endereço I2C do PCA9554PW
// PCA9554 extIo1(pca9554pw_address);
#define RMT_RX_CHANNEL RMT_CHANNEL_6
#define RMT_BLOCK_NUM
#define RMT_CLK_DIV 80 /*!< RMT counter clock divider */
#define RMT_1US_TICKS (80000000 / RMT_CLK_DIV / 1000000)
#define RMT_1MS_TICKS (RMT_1US_TICKS * 1000)
#define SIGNAL_STRENGTH_THRESHOLD 1500 // Adjust this threshold as needed
#define DISPLAY_HEIGHT 130 // Height of the display area for the waveform
#define DISPLAY_WIDTH 240 // Width of the display area
#define LINE_WIDTH 2 // Adjust line width as needed
struct HighLow {
uint8_t high; // 1
uint8_t low; //31
};
struct Protocol {
uint16_t pulseLength; // base pulse length in microseconds, e.g. 350
HighLow syncFactor;
HighLow zero;
HighLow one;
bool invertedSignal;
};
// Global to magane rmt installation.. if it is installed twice, it breakes
bool RxRF = false;
bool sendRF = false;
RfCodes recent_rfcodes[16]; // TODO: save/load in EEPROM
int recent_rfcodes_last_used = 0; // TODO: save/load in EEPROM
void initRMT() {
rmt_config_t rxconfig;
rxconfig.rmt_mode = RMT_MODE_RX;
rxconfig.channel = RMT_RX_CHANNEL;
rxconfig.gpio_num = gpio_num_t(bruceConfig.rfRx);
#ifdef USE_CC1101_VIA_SPI
if(bruceConfig.rfModule==CC1101_SPI_MODULE)
rxconfig.gpio_num = gpio_num_t(CC1101_GDO0_PIN);
#endif
rxconfig.clk_div = RMT_CLK_DIV; // RMT_DEFAULT_CLK_DIV=32
rxconfig.mem_block_num = 1;
rxconfig.flags = 0;
rxconfig.rx_config.idle_threshold = 3 * RMT_1MS_TICKS,
rxconfig.rx_config.filter_ticks_thresh = 200 * RMT_1US_TICKS;
rxconfig.rx_config.filter_en = true;
if(!RxRF) { //If spectrum had beed started before, it won't reinstall the driver to prevent mem alloc fail and restart.
ESP_ERROR_CHECK(rmt_config(&rxconfig));
ESP_ERROR_CHECK(rmt_driver_install(rxconfig.channel, 2048, 0));
RxRF=true;
}
}
void rf_spectrum() { //@IncursioHack - https://github.com/IncursioHack ----thanks @aat440hz - RF433ANY-M5Cardputer
tft.fillScreen(bruceConfig.bgColor);
tft.setTextSize(1);
tft.println("");
tft.println(" RF - Spectrum");
if(!initRfModule("rx", bruceConfig.rfFreq)) return;
initRMT();
RingbufHandle_t rb = nullptr;
rmt_get_ringbuf_handle(RMT_RX_CHANNEL, &rb);
rmt_rx_start(RMT_RX_CHANNEL, true);
while (rb) {
size_t rx_size = 0;
rmt_item32_t* item = (rmt_item32_t*)xRingbufferReceive(rb, &rx_size, 500);
if (item != nullptr) {
if (rx_size != 0) {
// Clear the display area
tft.fillRect(0, 20, WIDTH, HEIGHT, bruceConfig.bgColor);
// Draw waveform based on signal strength
for (size_t i = 0; i < rx_size; i++) {
int lineHeight = map(item[i].duration0 + item[i].duration1, 0, SIGNAL_STRENGTH_THRESHOLD, 0, HEIGHT/2);
int lineX = map(i, 0, rx_size - 1, 0, WIDTH - 1); // Map i to within the display width
// Ensure drawing coordinates stay within the box bounds
int startY = constrain(20 + HEIGHT / 2 - lineHeight / 2, 20, 20 + HEIGHT);
int endY = constrain(20 + HEIGHT / 2 + lineHeight / 2, 20, 20 + HEIGHT);
tft.drawLine(lineX, startY, lineX, endY, bruceConfig.priColor);
}
}
vRingbufferReturnItem(rb, (void*)item);
}
// Checks to leave while
if (checkEscPress()) {
break;
}
}
returnToMenu=true;
rmt_rx_stop(RMT_RX_CHANNEL);
delay(10);
}
void rf_SquareWave() { //@Pirata
RCSwitch rcswitch;
if(!initRfModule("rx", bruceConfig.rfFreq)) return;
#if defined(USE_CC1101_VIA_SPI)
if(bruceConfig.rfModule==CC1101_SPI_MODULE)
rcswitch.enableReceive(CC1101_GDO0_PIN);
else
#endif
rcswitch.enableReceive(bruceConfig.rfRx);
tft.drawPixel(0,0,0);
tft.fillScreen(bruceConfig.bgColor);
tft.setTextSize(1);
tft.println("");
tft.setCursor(3,2);
tft.println(" RF - SquareWave");
int line_w=0;
int line_h=15;
unsigned int* raw;
while (1) {
if (rcswitch.RAWavailable()) {
raw=rcswitch.getRAWReceivedRawdata();
// Clear the display area
// tft.fillRect(0, 0, WIDTH, HEIGHT, bruceConfig.bgColor);
// Draw waveform based on signal strength
for (int i = 0; i < RCSWITCH_RAW_MAX_CHANGES-1; i+=2) {
if(raw[i]==0) break;
#define TIME_DIVIDER WIDTH/8
if(raw[i]>20000) raw[i]=20000;
if(raw[i+1]>20000) raw[i+1]=20000;
if(line_w+(raw[i]+raw[i+1])/TIME_DIVIDER>WIDTH) { line_w=10; line_h+=10; }
if(line_h>HEIGHT) {
line_h = 15;
tft.fillRect(0, 12, WIDTH, HEIGHT, bruceConfig.bgColor);
}
tft.drawFastVLine(line_w ,line_h ,6 ,bruceConfig.priColor);
tft.drawFastHLine(line_w ,line_h ,raw[i]/TIME_DIVIDER ,bruceConfig.priColor);
tft.drawFastVLine(line_w+raw[i]/TIME_DIVIDER,line_h ,6 ,bruceConfig.priColor);
tft.drawFastHLine(line_w+raw[i]/TIME_DIVIDER,line_h+6 ,raw[i+1]/TIME_DIVIDER ,bruceConfig.priColor);
line_w+=(raw[i] + raw[i+1])/TIME_DIVIDER;
}
rcswitch.resetAvailable();
}
// Checks to leave while
if (checkEscPress()) {
break;
}
}
returnToMenu=true;
rmt_rx_stop(RMT_RX_CHANNEL);
delay(10);
}
void setMHZ(float frequency) {
#ifdef USE_CC1101_VIA_SPI
if(frequency>928 || frequency < 300) {
frequency = 433.92;
Serial.println("Frequency out of band");
}
#if defined(T_EMBED_1101)
static uint8_t antenna=200; // 0=(<300), 1=(350-468), 2=(>778), 200=start to settle at the fisrt time
// SW1:1 SW0:0 --- 315MHz
// SW1:0 SW0:1 --- 868/915MHz
// SW1:1 SW0:1 --- 434MHz
if (frequency <= 350 && antenna!=0)
{
digitalWrite(BOARD_LORA_SW1, HIGH);
digitalWrite(BOARD_LORA_SW0, LOW);
antenna=0;
delay(10); // time to settle the antenna signal
}
else if (frequency > 350 && frequency < 468 && antenna!=1)
{
digitalWrite(BOARD_LORA_SW1, HIGH);
digitalWrite(BOARD_LORA_SW0, HIGH);
antenna=1;
delay(10); // time to settle the antenna signal
}
else if (frequency > 778 && antenna!=2)
{
digitalWrite(BOARD_LORA_SW1, LOW);
digitalWrite(BOARD_LORA_SW0, HIGH);
antenna=2;
delay(10); // time to settle the antenna signal
}
#endif
ELECHOUSE_cc1101.setMHZ(frequency);
#endif
}
void rf_jammerFull() { //@IncursioHack - https://github.com/IncursioHack - thanks @EversonPereira - rfcardputer
// init rf module
int nTransmitterPin = bruceConfig.rfTx;
if(!initRfModule("tx")) return;
if(bruceConfig.rfModule == CC1101_SPI_MODULE) { // CC1101 in use
#ifdef USE_CC1101_VIA_SPI
nTransmitterPin = CC1101_GDO0_PIN;
#else
return;
#endif
}
tft.fillScreen(TFT_BLACK);
drawMainBorder();
tft.setCursor(10,30);
tft.setTextSize(FP);
padprintln("RF - Jammer Full");
tft.println("");
tft.println("");
tft.setTextSize(FP);
sendRF = true;
digitalWrite(nTransmitterPin, HIGH); // Turn on Jammer
int tmr0=millis(); // control total jammer time;
padprintln("Sending... Press ESC to stop.");
while (sendRF) {
if (checkEscPress() || (millis() - tmr0 >20000)) {
sendRF = false;
returnToMenu=true;
break;
}
}
deinitRfModule(); // Turn Jammer OFF
}
void rf_jammerIntermittent() { //@IncursioHack - https://github.com/IncursioHack - thanks @EversonPereira - rfcardputer
int nTransmitterPin = bruceConfig.rfTx;
if(!initRfModule("tx")) return;
if(bruceConfig.rfModule == CC1101_SPI_MODULE) { // CC1101 in use
#ifdef USE_CC1101_VIA_SPI
nTransmitterPin = CC1101_GDO0_PIN;
#else
return;
#endif
}
tft.fillScreen(TFT_BLACK);
drawMainBorder();
tft.setCursor(10,30);
tft.setTextSize(FP);
padprintln("RF - Jammer Intermittent");
tft.println("");
tft.println("");
sendRF = true;
padprintln("Sending... Press ESC to stop.");
int tmr0 = millis();
while (sendRF) {
for (int sequence = 1; sequence < 50; sequence++) {
for (int duration = 1; duration <= 3; duration++) {
// Moved Escape check into this loop to check every cycle
if (checkEscPress() || (millis()-tmr0)>20000) {
sendRF = false;
returnToMenu=true;
break;
}
digitalWrite(nTransmitterPin, HIGH); // Ativa o pino
// keeps the pin active for a while and increase increase
for (int widthsize = 1; widthsize <= (1 + sequence); widthsize++) {
delayMicroseconds(10);
}
digitalWrite(nTransmitterPin, LOW); // Desativa o pino
// keeps the pin inactive for the same time as before
for (int widthsize = 1; widthsize <= (1 + sequence); widthsize++) {
delayMicroseconds(10);
}
}
}
}
deinitRfModule();
}
String rf_scan(float start_freq, float stop_freq, int max_loops)
{
// derived from https://github.com/mcore1976/cc1101-tool/blob/main/cc1101-tool-esp32.ino#L480
if(bruceConfig.rfModule != CC1101_SPI_MODULE) {
displayError("rf scanning is available with CC1101 only", true);
return ""; // only CC1101 is supported for this
}
if(!initRfModule("rx", start_freq)) return "";
ELECHOUSE_cc1101.setRxBW(256);
float settingf1 = start_freq;
float settingf2 = stop_freq;
float freq;
long compare_freq;
float mark_freq;
int rssi;
int mark_rssi=-100;
String out="";
while(max_loops || !checkEscPress()) {
delay(1);
max_loops -= 1;
setMHZ(freq);
rssi = ELECHOUSE_cc1101.getRssi();
if (rssi>-75)
{
if (rssi > mark_rssi)
{
mark_rssi = rssi;
mark_freq = freq;
};
};
freq+=0.01;
if (freq > settingf2)
{
freq = settingf1;
if (mark_rssi>-75)
{
long fr = mark_freq*100;
if (fr == compare_freq)
{
Serial.print(F("\r\nSignal found at "));
Serial.print(F("Freq: "));
Serial.print(mark_freq);
Serial.print(F(" Rssi: "));
Serial.println(mark_rssi);
mark_rssi=-100;
compare_freq = 0;
mark_freq = 0;
out += String(mark_freq) + ",";
}
else
{
compare_freq = mark_freq*100;
freq = mark_freq -0.10;
mark_freq=0;
mark_rssi=-100;
};
};
}; // end of IF freq>stop frequency
}; // End of While
deinitRfModule();
return out;
}
void RCSwitch_send(uint64_t data, unsigned int bits, int pulse, int protocol, int repeat)
{
// derived from https://github.com/LSatan/SmartRC-CC1101-Driver-Lib/blob/master/examples/Rc-Switch%20examples%20cc1101/SendDemo_cc1101/SendDemo_cc1101.ino
RCSwitch mySwitch = RCSwitch();
if(bruceConfig.rfModule==CC1101_SPI_MODULE) {
#ifdef USE_CC1101_VIA_SPI
mySwitch.enableTransmit(CC1101_GDO0_PIN);
#else
Serial.println("USE_CC1101_VIA_SPI not defined");
return; // not enabled for this board
#endif
} else {
mySwitch.enableTransmit(bruceConfig.rfTx);
}
mySwitch.setProtocol(protocol); // override
if (pulse) { mySwitch.setPulseLength(pulse); }
mySwitch.setRepeatTransmit(repeat);
mySwitch.send(data, bits);
/*
Serial.println(data,HEX);
Serial.println(bits);
Serial.println(pulse);
Serial.println(protocol);
Serial.println(repeat);
*/
mySwitch.disableTransmit();
deinitRfModule();
}
// Example from https://github.com/sui77/rc-switch/blob/master/examples/ReceiveDemo_Advanced/output.ino
// Converts a Hex char to decimal
uint8_t hexCharToDecimal(char c) {
if (c >= '0' && c <= '9') {
return c - '0';
} else if (c >= 'A' && c <= 'F') {
return c - 'A' + 10;
} else if (c >= 'a' && c <= 'f') {
return c - 'a' + 10;
}
return 0;
}
// converts a Hex string like "11 22 AE FF" to decimal
uint32_t hexStringToDecimal(const char* hexString) {
uint32_t decimal = 0;
int length = strlen(hexString);
for (int i = 0; i < length; i += 3) {
decimal <<= 8; // Shift left to accommodate next byte
// Converts two characters hex to a single byte
uint8_t highNibble = hexCharToDecimal(hexString[i]);
uint8_t lowNibble = hexCharToDecimal(hexString[i + 1]);
decimal |= (highNibble << 4) | lowNibble;
}
return decimal;
}
void decimalToHexString(uint64_t decimal, char* output) {
char hexDigits[] = "0123456789ABCDEF";
char temp[65];
int index = 15;
// Initialize tem string with zeros
for (int i = 0; i < 64; i++) {
temp[i] = '0';
}
temp[65] = '\0';
// Convert decimal to hexadecimal
while (decimal > 0) {
temp[index--] = hexDigits[decimal % 16];
decimal /= 16;
}
// Format string with spaces
int outputIndex = 0;
for (int i = 0; i < 16; i++) {
output[outputIndex++] = temp[i];
if ((i % 2) == 1 && i != 15) {
output[outputIndex++] = ' ';
}
}
output[outputIndex] = '\0';
}
String hexStrToBinStr(const String& hexStr) {
String binStr = "";
String hexByte = "";
// Variables for decimal value
int value;
for (int i = 0; i < hexStr.length(); i++) {
char c = hexStr.charAt(i);
// Check if the character is a hexadecimal digit
if (c >= '0' && c <= '9' || c >= 'A' && c <= 'F' || c >= 'a' && c <= 'f') {
hexByte += c;
if (hexByte.length() == 2) {
// Convert the hexadecimal pair to a decimal value
value = strtol(hexByte.c_str(), NULL, 16);
// Convert the decimal value to binary and add to the binary string
for (int j = 7; j >= 0; j--) {
binStr += (value & (1 << j)) ? '1' : '0';
}
//binStr += ' ';
// Clear the hexByte string for the next byte
hexByte = "";
}
}
}
// Remove the extra trailing space, if any
if (binStr.length() > 0 && binStr.charAt(binStr.length() - 1) == ' ') {
binStr.remove(binStr.length() - 1);
}
return binStr;
}
static char * dec2binWzerofill(unsigned long Dec, unsigned int bitLength) {
static char bin[64];
unsigned int i=0;
while (Dec > 0) {
bin[32+i++] = ((Dec & 1) > 0) ? '1' : '0';
Dec = Dec >> 1;
}
for (unsigned int j = 0; j< bitLength; j++) {
if (j >= bitLength - i) {
bin[j] = bin[ 31 + i - (j - (bitLength - i)) ];
} else {
bin[j] = '0';
}
}
bin[bitLength] = '\0';
return bin;
}
void initCC1101once(SPIClass* SSPI) {
// the init (); command may only be executed once in the entire program sequence. Otherwise problems can arise. https://github.com/LSatan/SmartRC-CC1101-Driver-Lib/issues/65
#ifdef USE_CC1101_VIA_SPI
// derived from https://github.com/LSatan/SmartRC-CC1101-Driver-Lib/blob/master/examples/Rc-Switch%20examples%20cc1101/ReceiveDemo_Advanced_cc1101/ReceiveDemo_Advanced_cc1101.ino
if(SSPI!=NULL) ELECHOUSE_cc1101.setSPIinstance(SSPI); // New, to use the SPI instance we want.
ELECHOUSE_cc1101.setSpiPin(CC1101_SCK_PIN, CC1101_MISO_PIN, CC1101_MOSI_PIN, CC1101_SS_PIN);
#ifdef CC1101_GDO2_PIN
ELECHOUSE_cc1101.setGDO(CC1101_GDO0_PIN, CC1101_GDO2_PIN); //Set Gdo0 (tx) and Gdo2 (rx) for serial transmission function.
#else
ELECHOUSE_cc1101.setGDO0(CC1101_GDO0_PIN); // use Gdo0 for both Tx and Rx
#endif
/*
Don't need to start comunications now
if (ELECHOUSE_cc1101.getCC1101()){ // Check the CC1101 Spi connection.
Serial.println("cc1101 Connection OK");
} else {
Serial.println("cc1101 Connection Error");
return;
}
ELECHOUSE_cc1101.Init();
*/
#else
Serial.println("Error: USE_CC1101_VIA_SPI not defined for this board");
//TODO: interface using PCA9554
#endif
return;
}
void deinitRfModule() {
if(bruceConfig.rfModule==CC1101_SPI_MODULE)
#ifdef USE_CC1101_VIA_SPI
#if CC1101_MOSI_PIN==TFT_MOSI || CC1101_MOSI_PIN==SDCARD_MOSI // (T_EMBED), CORE2 and others
ELECHOUSE_cc1101.setSidle();
#else // (STICK_C_PLUS) || (STICK_C_PLUS2) and others that doesn´t share SPI with other devices (need to change it when Bruce board comes to shore)
ELECHOUSE_cc1101.getSPIinstance()->end();
#endif
#else
return;
#endif
else
digitalWrite(bruceConfig.rfTx, LED_OFF);
}
bool initRfModule(String mode, float frequency) {
#if CC1101_MOSI_PIN==TFT_MOSI // (T_EMBED), CORE2 and others
initCC1101once(&tft.getSPIinstance());
#elif CC1101_MOSI_PIN==SDCARD_MOSI // (CARDPUTER) and (ESP32S3DEVKITC1) and devices that share CC1101 pin with only SDCard
ELECHOUSE_cc1101.setSPIinstance(&sdcardSPI);
#else // (STICK_C_PLUS) || (STICK_C_PLUS2) and others that doesn´t share SPI with other devices (need to change it when Bruce board comes to shore)
ELECHOUSE_cc1101.setBeginEndLogic(true); // make sure to use BeginEndLogic for StickCs in the shared pins (not bus) config
initCC1101once(NULL);
#endif
// use default frequency if no one is passed
if(!frequency) frequency = bruceConfig.rfFreq;
if(bruceConfig.rfModule == CC1101_SPI_MODULE) { // CC1101 in use
#ifdef USE_CC1101_VIA_SPI
ELECHOUSE_cc1101.Init();
if (ELECHOUSE_cc1101.getCC1101()){ // Check the CC1101 Spi connection.
Serial.println("cc1101 Connection OK");
} else {
displayError("CC1101 not found");
Serial.println("cc1101 Connection Error");
return false;
}
// make sure it is in idle state when changing frequency and other parameters
// "If any frequency programming register is altered when the frequency synthesizer is running, the synthesizer may give an undesired response. Hence, the frequency programming should only be updated when the radio is in the IDLE state." https://github.com/LSatan/SmartRC-CC1101-Driver-Lib/issues/65
// ELECHOUSE_cc1101.setSidle();
// Serial.println("cc1101 setSidle();");
if(!( (frequency>=300 && frequency<=350) ||
(frequency>=387 && frequency<=468) ||
(frequency>=779 && frequency<=928))) {
Serial.println("Invalid Frequency, setting default");
frequency=433.92;
displayWarning("Wrong freq, setted 433.92",true);
}
// else
//ELECHOUSE_cc1101.setRxBW(812.50); // reset to default
ELECHOUSE_cc1101.setRxBW(256); // narrow band for better accuracy
ELECHOUSE_cc1101.setClb(1,13,15); // Calibration Offset
ELECHOUSE_cc1101.setClb(2,16,19); // Calibration Offset
ELECHOUSE_cc1101.setModulation(2); // set modulation mode. 0 = 2-FSK, 1 = GFSK, 2 = ASK/OOK, 3 = 4-FSK, 4 = MSK.
ELECHOUSE_cc1101.setDRate(50); // Set the Data Rate in kBaud. Value from 0.02 to 1621.83. Default is 99.97 kBaud!
ELECHOUSE_cc1101.setPktFormat(3); // Format of RX and TX data. 0 = Normal mode, use FIFOs for RX and TX.
// 1 = Synchronous serial mode, Data in on GDO0 and data out on either of the GDOx pins.
// 2 = Random TX mode; sends random data using PN9 generator. Used for test. Works as normal mode, setting 0 (00), in RX.
// 3 = Asynchronous serial mode, Data in on GDO0 and data out on either of the GDOx pins.
setMHZ(frequency);
Serial.println("cc1101 setMHZ(frequency);");
/* MEMO: cannot change other params after this is executed */
if(mode=="tx") {
pinMode(CC1101_GDO0_PIN, OUTPUT);
ELECHOUSE_cc1101.setPA(12); // set TxPower. The following settings are possible depending
Serial.println("cc1101 setPA();");
ELECHOUSE_cc1101.SetTx();
Serial.println("cc1101 SetTx();");
}
else if(mode=="rx") {
pinMode(CC1101_GDO0_PIN, INPUT);
ELECHOUSE_cc1101.SetRx();
Serial.println("cc1101 SetRx();");
}
// else if mode is unspecified wont start TX/RX mode here -> done by the caller
#else
// TODO: PCA9554-based implmentation
return false;
#endif
} else {
// single-pinned module
if(frequency!=bruceConfig.rfFreq) {
Serial.println("unsupported frequency");
return false;
}
if(mode=="tx") {
gsetRfTxPin(false);
pinMode(bruceConfig.rfTx, OUTPUT);
digitalWrite(bruceConfig.rfTx, LOW);
}
else if(mode=="rx") {
// Rx Mode
gsetRfRxPin(false);
pinMode(bruceConfig.rfRx, INPUT);
}
}
// no error
return true;
}
String RCSwitch_Read(float frequency, int max_loops, bool raw) {
RCSwitch rcswitch = RCSwitch();
RfCodes received;
if(!frequency) frequency = bruceConfig.rfFreq; // default from config
char hexString[64];
RestartRec:
drawMainBorder();
tft.setCursor(10, 28);
tft.setTextSize(FP);
tft.println("Waiting for a " + String(frequency) + " MHz " + "signal.");
// init receive
if(!initRfModule("rx", frequency)) return "";
if(bruceConfig.rfModule == CC1101_SPI_MODULE) { // CC1101 in use
#ifdef USE_CC1101_VIA_SPI
#ifdef CC1101_GDO2_PIN
rcswitch.enableReceive(CC1101_GDO2_PIN);
#else
rcswitch.enableReceive(CC1101_GDO0_PIN);
#endif
Serial.println("CC1101 enableReceive()");
#else
return "";
#endif
} else {
rcswitch.enableReceive(bruceConfig.rfRx);
}
while(!checkEscPress()) {
if(rcswitch.available()) {
//Serial.println("Available");
long value = rcswitch.getReceivedValue();
//Serial.println("getReceivedValue()");
if(value) {
//Serial.println("has value");
unsigned int* _raw = rcswitch.getReceivedRawdata();
received.frequency=long(frequency*1000000);
received.key=rcswitch.getReceivedValue();
received.protocol="RcSwitch";
received.preset=rcswitch.getReceivedProtocol();
received.te=rcswitch.getReceivedDelay();
received.Bit=rcswitch.getReceivedBitlength();
received.filepath="unsaved";
//Serial.println(received.te*2);
// derived from https://github.com/sui77/rc-switch/tree/master/examples/ReceiveDemo_Advanced
received.data="";
int sign = +1;
//if(received.preset.invertedSignal) sign = -1;
for(int i=0; i<received.Bit*2; i++) {
if(i>0) received.data+=" ";
if(i % 2 == 0) sign = +1;
else sign = -1;
received.data += String(sign * (int)_raw[i]);
}
//Serial.println(received.protocol);
//Serial.println(received.data);
decimalToHexString(received.key,hexString);
rf_scan_copy_draw_signal(received, 1, raw);
}
rcswitch.resetAvailable();
}
if(raw && rcswitch.RAWavailable()) {
// if no value were decoded, show raw data to be saved
delay(100); //give it time to process and store all signal
unsigned int* _raw = rcswitch.getRAWReceivedRawdata();
int transitions = 0;
signed int sign=1;
for(transitions=0; transitions<RCSWITCH_RAW_MAX_CHANGES; transitions++) {
if(_raw[transitions]==0) break;
if(transitions>0) received.data+=" ";
if(transitions % 2 == 0) sign = +1;
else sign = -1;
received.data += String(sign * (int)_raw[transitions]);
}
if(transitions>20) {
received.frequency = long(frequency*1000000);
received.protocol = "RAW";
received.preset = "0"; // ????
received.filepath = "unsaved";
received.data = "";
rf_scan_copy_draw_signal(received, 1, raw);
}
//ResetSignal:
rcswitch.resetAvailable();
}
if(received.key>0 || received.data.length()>20) { // RAW data does not have "key", 20 is more than 5 transitions
#ifndef HAS_SCREEN
// switch to raw mode if decoding failed
if(received.preset == 0) {
Serial.println("signal decoding failed, switching to RAW mode");
//displayWarning("signal decoding failed, switching to RAW mode", true);
raw = true;
// TODO: show a dialog/warning?
// raw = yesNoDialog("decoding failed, save as RAW?");
}
String subfile_out = "Filetype: Bruce SubGhz File\nVersion 1\n";
subfile_out += "Frequency: " + String(int(frequency*1000000)) + "\n";
if(!raw) {
subfile_out += "Preset: " + String(received.preset) + "\n";
subfile_out += "Protocol: RcSwitch\n";
subfile_out += "Bit: " + String(received.Bit) + "\n";
subfile_out += "Key: " + String(hexString) + "\n";
subfile_out += "TE: " + String(received.te) + "\n";
} else {
// save as raw
if(received.preset=="1") received.preset="FuriHalSubGhzPresetOok270Async";
else if (received.preset=="2") received.preset="FuriHalSubGhzPresetOok650Async";
subfile_out += "Preset: " + String(received.preset) + "\n";
subfile_out += "Protocol: RAW\n";
subfile_out += "RAW_Data: " + received.data;
}
// headless mode
return subfile_out;
#endif
if(checkSelPress()) {
int chosen=0;
options = {
{"Replay signal", [&]() { chosen=1; } },
{"Save signal", [&]() { chosen=2; } },
};
delay(200);
loopOptions(options);
if(chosen==1) {
rcswitch.disableReceive();
sendRfCommand(received);
addToRecentCodes(received);
goto RestartRec;
}
else if (chosen==2) {
decimalToHexString(received.key,hexString);
RCSwitch_SaveSignal(frequency, received, raw, hexString);
delay(2000);
drawMainBorder();
tft.setCursor(10, 28);
tft.setTextSize(FP);
tft.println("Waiting for a " + String(frequency) + " MHz " + "signal.");
}
}
}
//#ifndef HAS_SCREEN
if(max_loops>0) {
// headless mode, quit if nothing received after max_loops
max_loops -= 1;
delay(1000);
if(max_loops==0) {
Serial.println("timeout");
return "";
}
}
//#endif
}
Exit:
delay(1);
deinitRfModule();
return "";
}
bool RCSwitch_SaveSignal(float frequency, RfCodes codes, bool raw, char* key)
{
if (!codes.key && codes.data=="") {
Serial.println("Empty signal, it was not saved.");
return false;
}
String subfile_out = "Filetype: Bruce SubGhz File\nVersion 1\n";
subfile_out += "Frequency: " + String(int(frequency * 1000000)) + "\n";
if(!raw) {
subfile_out += "Preset: " + String(codes.preset) + "\n";
subfile_out += "Protocol: RcSwitch\n";
subfile_out += "Bit: " + String(codes.Bit) + "\n";
subfile_out += "Key: " + String(key) + "\n";
subfile_out += "TE: " + String(codes.te) + "\n";
//subfile_out += "RAW_Data: " + codes.data;
} else {
// save as raw
if (codes.preset=="1") {
codes.preset="FuriHalSubGhzPresetOok270Async";
}
else if (codes.preset=="2") {
codes.preset="FuriHalSubGhzPresetOok650Async";
}
subfile_out += "Preset: " + String(codes.preset) + "\n";
subfile_out += "Protocol: RAW\n";
subfile_out += "RAW_Data: " + codes.data;
}
int i = 0;
File file;
String FS = "";
if (SD.begin()) {
if (!SD.exists("/BruceRF")) {
SD.mkdir("/BruceRF");
}
while (SD.exists("/BruceRF/bruce_" + String(i) + ".sub")) {
i++;
}
file = SD.open("/BruceRF/bruce_"+ String(i) +".sub", FILE_WRITE);
FS="SD";
} else if (LittleFS.begin()) {
sdcardMounted=false;
if (!checkLittleFsSize()) {
return false;
}
if (!LittleFS.exists("/BruceRF")) {
LittleFS.mkdir("/BruceRF");
}
while(LittleFS.exists("/BruceRF/bruce_" + String(i) + ".sub")) {
i++;
}
file = LittleFS.open("/BruceRF/bruce_" + String(i) +".sub", FILE_WRITE);
FS = "LittleFS";
}
if (file) {
file.println(subfile_out);
displaySuccess(FS + "/bruce_" + String(i) + ".sub");
} else {
Serial.println("Fail saving data to LittleFS");
displayError("Error saving file", true);
}
file.close();
return true;
}
// ported from https://github.com/sui77/rc-switch/blob/3a536a172ab752f3c7a58d831c5075ca24fd920b/RCSwitch.cpp
void RCSwitch_RAW_Bit_send(RfCodes data) {
int nTransmitterPin = bruceConfig.rfTx;
if(bruceConfig.rfModule==CC1101_SPI_MODULE) {
#ifdef USE_CC1101_VIA_SPI
nTransmitterPin = CC1101_GDO0_PIN;
#else
return;
#endif
}
if (data.data == "")
return;
bool currentlogiclevel = false;
int nRepeatTransmit = 1;
for (int nRepeat = 0; nRepeat < nRepeatTransmit; nRepeat++) {
int currentBit = data.data.length();
while(currentBit >= 0) { // Starts from the end of the string until the max number of bits to send
char c = data.data[currentBit];
if(c=='1') {
currentlogiclevel = true;
} else if(c=='0') {
currentlogiclevel = false;
} else {
Serial.println("Invalid data");
currentBit--;
continue;
//return;
}
digitalWrite(nTransmitterPin, currentlogiclevel ? HIGH : LOW);
delayMicroseconds(data.te);
//Serial.print(currentBit);
//Serial.print("=");
//Serial.println(currentlogiclevel);
currentBit--;
}
digitalWrite(nTransmitterPin, LOW);
}
}
void RCSwitch_RAW_send(int * ptrtransmittimings) {
int nTransmitterPin = bruceConfig.rfTx;
if(bruceConfig.rfModule==CC1101_SPI_MODULE) {
#ifdef USE_CC1101_VIA_SPI
nTransmitterPin = CC1101_GDO0_PIN;
#else
return;
#endif
}
if (!ptrtransmittimings)
return;
bool currentlogiclevel = true;
int nRepeatTransmit = 5; // repeats RAW signal twice!
//HighLow pulses ;
for (int nRepeat = 0; nRepeat < nRepeatTransmit; nRepeat++) {
unsigned int currenttiming = 0;
while( ptrtransmittimings[currenttiming] ) { // && currenttiming < RCSWITCH_MAX_CHANGES
if(ptrtransmittimings[currenttiming] >= 0) {
currentlogiclevel = true;
} else {
// negative value
currentlogiclevel = false;
ptrtransmittimings[currenttiming] = (-1) * ptrtransmittimings[currenttiming]; // invert sign
}
digitalWrite(nTransmitterPin, currentlogiclevel ? HIGH : LOW);
delayMicroseconds( ptrtransmittimings[currenttiming] );
/*
Serial.print(ptrtransmittimings[currenttiming]);
Serial.print("=");
Serial.println(currentlogiclevel);
*/
currenttiming++;
}
digitalWrite(nTransmitterPin, LOW);
} // end for
}
void sendRfCommand(struct RfCodes rfcode) {
uint32_t frequency = rfcode.frequency;
String protocol = rfcode.protocol;
String preset = rfcode.preset;
String data = rfcode.data;
uint64_t key = rfcode.key;
byte modulation = 2; // possible values for CC1101: 0 = 2-FSK, 1 =GFSK, 2=ASK, 3 = 4-FSK, 4 = MSK
float deviation = 0;
float rxBW = 0; // Receive bandwidth