-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathEmbedded_System.ino
More file actions
3117 lines (2693 loc) · 91.4 KB
/
Copy pathEmbedded_System.ino
File metadata and controls
3117 lines (2693 loc) · 91.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
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
/////////////////////////////////////////////////CHOOSE BOARD/////////////////////////////////////////////////
#pragma region ShieldSelection
#include "src/lib/boards.h"
#if defined(ARDUINO_ARCH_AVR)
#define USING_BOARD MEGA_OCTA_PTH_MK_I
// #define USING_BOARD MEGA_STACK_DADOS_ACIONAMENTO_2019
// #define USING_BOARD MEGA_STACK_DADOS_ACIONAMENTO_2020
#elif defined(ARDUINO_ARCH_ESP32)
// #define USING_BOARD ESP_ESSENTIALS_2025
// #define USING_BOARD ESP_ESSENTIALS_2026
#define USING_BOARD ESP_MAIN_SMD_2026
// #define USING_BOARD ESP_JOHN_SI_SMD_2026
#else
#error Nao existem placas para a arquitetura selecionada
#endif
#include "src/lib/pinos.h"
#pragma endregion
//////////////////////////////////////////////////CHOOSE MODE//////////////////////////////////////////////////
#pragma region ModeSelection
#include "src/lib/modes.h"
#define USING_MODE MODE_LANCAMENTO
// #define USING_MODE MODE_ELEVADOR
// #define USING_MODE MODE_ASPIRADOR
// #define USING_MODE MODE_MANUAL
#include "src/lib/pressets.h"
#pragma endregion
/////////////////////////////////////////////////CONFIGURATION/////////////////////////////////////////////////
#pragma region Configurations
#define BaudRate 115200
#define USE_GY80 (0) //Use GY80 module
#define USE_GY91 (0) //Use GY91 module
#define USE_GY912 (1) //Use GY912 module
#define SDCard (1) //Use SD card
#define GPSmode (1) //Use GPS
#define LoRamode (1) //Serial mode for transmission on LoRa module
#define TalkingBoard (0) //When two boards are connected for redundancy system
#define BuZZ (1) //Buzzer mode
#define ForceSysC (0)
#define PRINT (0) //Print or not things on Serial
/**************************** GY80 ****************************/
#define USE_BMP085 (USE_GY80 || 0) //Use BMP085 sensor
#define USE_ADXL345 (USE_GY80 || 0) //Use ADXL345 sensor
#define USE_L3G4200D (USE_GY80 || 0) //Use L3G4200D sensor
#define USE_HMC5883 (USE_GY80 || 0) //Use HMC5883 sensor
/**************************** GY91 ****************************/
#define USE_BMP280 (USE_GY91 || 0) //Use BMP280 sensor
#define USE_MPU9250_ACCEL (USE_GY91 || 0) //Use MPU9250 sensor, accelerometer
#define USE_MPU9250_GYRO (USE_GY91 || 0) //Use MPU9250 sensor, gyroscope
#define USE_AK8963 (USE_GY91 || 0) //Use AK8963 sensor
/**************************** GY912 ***************************/
#define USE_BMP388 (USE_GY912 || 0) //Use BMP280 sensor
#define USE_ICM20948_ACCEL (USE_GY912 || 0) //Use ICM20948 sensor, accelerometer
#define USE_ICM20948_GYRO (USE_GY912 || 0) //Use ICM20948 sensor, gyroscope
#define USE_AK09916 (USE_GY912 || 0) //Use AK09916 sensor
/************************** 9DoF IMU **************************/
#define USE_BARO (USE_BMP085 || USE_BMP280 || USE_BMP388) // Use any Barometer
#define USE_ACCEL (USE_ADXL345 || USE_MPU9250_ACCEL || USE_ICM20948_ACCEL) // Use any Accelerometer
#define USE_GYRO (USE_L3G4200D || USE_MPU9250_GYRO || USE_ICM20948_GYRO) // Use any Gyroscope
#define USE_MAGN (USE_HMC5883 || USE_AK8963 || USE_AK09916) // Use any Magnetometer
/**************************** LoRa ****************************/
#define USE_LoRa_CONTIGUOUS (LoRamode && 1) // Force data columns to always exist
#define USE_LoRa_DORJI (LoRamode && defined(BOARD_HAS_LoRa_DORJI)) // Dorji LoRa Module (2019 and before)
#define USE_LoRa_E32 (LoRamode && defined(BOARD_HAS_LoRa_E32)) // E32 LoRa Module (2019 and before)
#define USE_LoRa_E32_settable (USE_LoRa_E32 && 1)
#define USE_LoRa_KEYVALUE (LoRamode && 1) // Send LoRa data Using Key-value pair
/*************************** Others ***************************/
#define ApoGee (USE_BARO && 1) //Detection of apogee
#define RBF (0) //Revome Before Flight
#define WU (ApoGee && 1) //Wait Until Directives
#define WUF (WU && 1) //Wait Until Flight
#define WUPS (WU && 1) //Wait Until Pressure Stabilize
#define ACT_BUZZER (BuZZ && 0) //Active buzzer in hardware
#define PSS_BUZZER (BuZZ && 1) //Passive buzzer in hardware
#define MORSE_MSG (BuZZ && 1) //Morse beeping
#define BEEPING (BuZZ && 0) //Buzzer mode
#define BlinkBuzzer (BuZZ && 0)
#define RGB (defined(BOARD_HAS_RGB) && 0) //RGB LED board
#define AnyDeploy (ApoGee && defined(BOARD_HAS_IGN_1) && 1) //Any Parachute Deployment
#define DualDeploy (AnyDeploy && defined(BOARD_HAS_IGN_3) && 1) //Dual Parachute Deployment
#define DrogueBackup (AnyDeploy && defined(BOARD_HAS_IGN_2) && DualDeploy && 1) //Drogue Redundancy mode
#define MainBackup (AnyDeploy && defined(BOARD_HAS_IGN_4) && 1) //Main Redundancy mode
#define DELAYED_MAIN (AnyDeploy && 1) //Aways delay main deployment
#define PbarT (PRINT && USE_BARO && 1) //Print barometer temperature data
#define PbarP (PRINT && USE_BARO && 1) //Print barometer pressure data
#define PaclX (PRINT && USE_ACCEL && 1) //Print accelerometer X axis data
#define PaclY (PRINT && USE_ACCEL && 1) //Print accelerometer Y axis data
#define PaclZ (PRINT && USE_ACCEL && 1) //Print accelerometer Z axis data
#define PgirX (PRINT && USE_GYRO && 1) //Print gyroscope x axis data
#define PgirY (PRINT && USE_GYRO && 1) //Print gyroscope Y axis data
#define PgirZ (PRINT && USE_GYRO && 1) //Print gyroscope Z axis data
#define PmagX (PRINT && USE_MAGN && 1) //Print magnetometer x axis data
#define PmagY (PRINT && USE_MAGN && 1) //Print magnetometer Y axis data
#define PmagZ (PRINT && USE_MAGN && 1) //Print magnetometer Z axis data
#define papgI (PRINT && ApoGee && 1) //Print MonoDeploy.info of every instance
#define PapgW (PRINT && ApoGee && 1) //Print apogee information when detected
#define PapgH (PRINT && ApoGee && 1) //Print altimeter data
#define PapgB (PRINT && ApoGee && 1) //Print altimeter base
#define PapgP (PRINT && ApoGee && 0) //Print current apogee information
#define PapgA (PRINT && ApoGee && 1) //Print apogee alpha
#define PapgS (PRINT && ApoGee && 1) //Print apogee sigma
#define PapgM (PRINT && ApoGee && 0) //Print apogee sigma max
#define Pgps (PRINT && GPSmode && 1) //Print GPS informations
#define Psep (PRINT && 0) //Print visual separator
/**************************** SD Log ***************************/
#define Sgps (SDCard && GPSmode && 1) //Log GPS data
#define Sapg (SDCard && ApoGee && 1) //Log apogee alpha and sigma
#define Sdpl (SDCard && AnyDeploy && 1) //Log parachute deployment state
#define Shea (SDCard && AnyDeploy && 1) //Log parachute health (igniter continuity)
#define Semg (SDCard && AnyDeploy && 1) //Log emergency state
#define Srst (SDCard && 1) //Log reset reason on file header
#define Crst (COMmode && 1) //Report reset reason on Serial/LoRa
/* Colunas continuas: repetem o ultimo valor conhecido em toda linha.
Com 0, o dado so aparece no instante do evento. */
#define Sgps_C (Sgps && 1) //GPS em toda linha
#define Sdpl_C (Sdpl && 1) //Acionamentos em toda linha
#define Tcom (PRINT && 1) //Print time counter
#define Lcom (PRINT && 0) //Print loop counter
#define Ncom (PRINT && 0) //Print eachN counter
#define Ps_n (PRINT && 1) //Print SYSTEM_n
#define PWMapg (ApoGee && 1) //Show the apogee coefficient in a LED
#define PERF_Tcom_print (0) //Print time counter every 100 iterations (for performance tests)
#define COMmode (PRINT || LoRamode)
#define WIREmode (USE_BARO || USE_ACCEL || USE_GYRO || USE_MAGN)
constexpr uint8_t SYSTEM_n = ( 0
#if SDCard
+ 1
#endif // SDCard
#if USE_BARO
+ 1
#endif // USE_BARO
#if USE_ACCEL
+ 1
#endif // USE_ACCEL
#if USE_GYRO
+ 1
#endif // USE_GYRO
#if USE_MAGN
+ 1
#endif // USE_MAGN
#if GPSmode
+ 1
#endif // GPSmode
#if AnyDeploy
+ 1
#endif // AnyDeploy
#if DualDeploy
+ 1
#endif // DualDeploy
#if DrogueBackup
+ 1
#endif // DrogueBackup
#if MainBackup
+ 1
#endif // MainBackup
); //Expected count of systems functioning for flight
#pragma endregion
/////////////////////////////////////////////////////objects///////////////////////////////////////////////////
#pragma region Declarations
#include "src/lib/Classes.h"
#if USE_BARO
#if 1 < ((USE_BMP085) + (USE_BMP280) + (USE_BMP388))
#error: Múltiplos barômetros definidos
#elif USE_BMP085
#include "src/lib/BMP085/BMP085.h" // Barometro BMP085
BMP085 baro; //Barometer object declaration
#elif USE_BMP280
#include "src/lib/BMP280/BMP280.h" // Barometro BMP280
BMP280 baro; //Barometer object declaration
#elif USE_BMP388
#include "src/lib/BMP388/BMP388.h" // Barometro BMP388
BMP388 baro; //Barometer object declaration
#endif // USE_BMP085 / USE_BMP280
//MovingAverage MM_baro[2]{ (2),(2) }; //Array declaration of the moving average filter objects
float MM_baro[2]{};
bool baroHasData = false;
#endif // USE_BARO
#if ApoGee
#include "src/lib/Apogeu/Apogeu.h" // Processamento de altitude e deteccao de apogeu
Apogeu apg(10, 15, 50); //Apogee checker object declaration
#define LapsMaxT 5 //Maximum time of delay until emergency state declaration by the delay in sensor response. (seconds)
#define EM_mainN_DELAY 60 // Seconds before forced deployment
#if AnyDeploy
#include "src/lib/MonoDeploy/MonoDeploy.h" // Acionamento de paraquedas simples
const bool MonoDeploy::command = IGN_CMD;
#if DualDeploy
#define EM_drogN_DELAY 10 // Seconds before forced deployment
#endif // DualDeploy
#if DrogueBackup || MainBackup
#define sysDelay 2.5
#endif // DrogueBackup || MainBackup
#if MainBackup
#define EM_mainB_DELAY 65 // Seconds before forced deployment
#endif // MainBackup
#if DELAYED_MAIN
#define sysDelay_main 1.0
#endif // DELAYED_MAIN
#if DrogueBackup
#define EM_drogB_DELAY 15 // Seconds before forced deployment
#endif // DrogueBackup
#define pins_drogN (IGN_1, HEAL_1) /*act1*/
#define pins_drogB (IGN_2, HEAL_2) /*act2*/
#define pins_mainN (IGN_3, HEAL_3) /*act3*/
#define pins_mainB (IGN_4, HEAL_4) /*act4*/
struct Recovery
{
static MonoDeploy mainN;
#if DualDeploy
static MonoDeploy drogN;
#endif // DualDeploy
#if MainBackup
static MonoDeploy mainB;
#endif // MainBackup
#if DrogueBackup
static MonoDeploy drogB;
#endif // DrogueBackup
static bool begin()
{
bool aux = true;
aux &= mainN.begin();
#if DualDeploy
aux &= drogN.begin();
#endif // DualDeploy
#if MainBackup
aux &= mainB.begin();
#endif // MainBackup
#if DrogueBackup
aux &= drogB.begin();
#endif // DrogueBackup
return aux;
}
static void emergency(bool state)
{
if(state) MonoDeploy::sealApogee(true);
mainN.emergency(state, EM_mainN_DELAY);
#if DualDeploy
drogN.emergency(state, EM_drogN_DELAY);
#endif // DualDeploy
#if MainBackup
mainB.emergency(state, EM_mainB_DELAY);
#endif // MainBackup
#if DrogueBackup
drogB.emergency(state, EM_drogB_DELAY);
#endif // DrogueBackup
}
static bool getGlobalState()
{
bool aux = false;
aux |= mainN.getGlobalState();
#if DualDeploy
aux |= drogN.getGlobalState();
#endif // DualDeploy
#if MainBackup
aux |= mainB.getGlobalState();
#endif // MainBackup
#if DrogueBackup
aux |= drogB.getGlobalState();
#endif // DrogueBackup
return aux;
}
static void refresh()
{
mainN.refresh();
#if DualDeploy
drogN.refresh();
#endif // DualDeploy
#if MainBackup
mainB.refresh();
#endif // MainBackup
#if DrogueBackup
drogB.refresh();
#endif // DrogueBackup
}
static void resetTimer()
{
MonoDeploy::resetTimer();
}
static void sealApogee(bool apg)
{
MonoDeploy::sealApogee(apg);
}
static void putHeight(float H)
{
MonoDeploy::putHeight(H);
}
static bool getApogee()
{
return MonoDeploy::getApogee();
}
} rec;
MonoDeploy Recovery::mainN pins_mainN;
#if DualDeploy
MonoDeploy Recovery::drogN pins_drogN;
#endif // DualDeploy
#if MainBackup
MonoDeploy Recovery::mainB pins_mainB;
#endif // MainBackup
#if DrogueBackup
MonoDeploy Recovery::drogB pins_drogB;
#endif // DrogueBackup
#else
#warning Essa compilacao nao realiza disparo de paraquedas
#endif // AnyDeploy
#endif // ApoGee
/*
#if WUF
#if ELEVATOR
#define WUFheigh 5
#else
#define WUFheigh 50
#endif // ELEVATOR
#endif // WUF
*/
/*
#if WUPS
#if ELEVATOR
#define WUPSdelay 3
#else
#define WUPSdelay 10
#endif // ELEVATOR
#endif // WUPS
*/
#if USE_ACCEL
#if 1 < ((USE_ADXL345) + (USE_MPU9250_ACCEL) + (USE_ICM20948_ACCEL))
#error: Múltiplos acelerômetros definidos
#elif USE_ADXL345
#include "src/lib/ADXL345/ADXL345.h" // Accelerometer ADXL345
ADXL345 accel; //Accelerometer object declaration
#elif USE_MPU9250_ACCEL
#include "src/lib/MPU9250_ACCEL/MPU9250_ACCEL.h" // Accelerometer MPU9250_ACCEL
MPU9250_ACCEL accel(16); //Accelerometer object declaration
#elif USE_ICM20948_ACCEL
#include "src/lib/ICM20948_ACCEL/ICM20948_ACCEL.h" // Accelerometer MPU9250_ACCEL
ICM20948_ACCEL accel(16); //Accelerometer object declaration
#endif // USE_ADXL345 / USE_MPU9250_ACCEL
//MovingAverage MM_accel[3]{ (5),(5),(5) }; //Array declaration of the moving average filter objects
float MM_accel[3]{};
#endif // USE_ACCEL
#if USE_GYRO
#if 1 < ((USE_L3G4200D) + (USE_MPU9250_GYRO) + (USE_ICM20948_GYRO))
#error: Múltiplos giroscópios definidos
#elif USE_L3G4200D
#include "src/lib/L3G4200D/L3G4200D.h" // Gyroscope L3G4200D
L3G4200D giro(2000); //Gyroscope object declaration
#elif USE_MPU9250_GYRO
#include "src/lib/MPU9250_GYRO/MPU9250_GYRO.h" // Gyroscope MPU9250_GYRO
MPU9250_GYRO giro(2000); //Gyroscope object declaration
#elif USE_ICM20948_GYRO
#include "src/lib/ICM20948_GYRO/ICM20948_GYRO.h" // Gyroscope MPU9250_GYRO
ICM20948_GYRO giro(2000); //Gyroscope object declaration
#endif // USE_L3G4200D / USE_MPU9250_GYRO
//MovingAverage MM_giro[3]{ (5),(5),(5) }; //Array declaration of the moving average filter objects
float MM_giro[3]{};
#endif // USE_GYRO
#if USE_MAGN
#if 1 < ((USE_HMC5883) + (USE_AK8963) + (USE_AK09916))
#error: Múltiplos magnetômetros definidos
#elif USE_HMC5883
#include "src/lib/HMC5883/HMC5883.h" // Magnetometer HMC5883
HMC5883 magn; //Magnetometer object declaration
#elif USE_AK8963
#include "src/lib/AK8963/AK8963.h" // Magnetometer AK8963
AK8963 magn; //Magnetometer object declaration
#elif USE_AK09916
#include "src/lib/AK09916/AK09916.h" // Magnetometer USE_AK09916
AK09916 magn; //Magnetometer object declaration
#endif // USE_HMC5883 / USE_AK8963
//MovingAverage MM_magn[3]{ (5),(5),(5) }; //Array declaration of the moving average filter objects
float MM_magn[3]{};
#endif // USE_MAGN
#if SDCard
#include <SPI.h>
#include <SD.h>
#if ARDUINO_ARCH_ESP32
SPIClass SPI_SD(FSPI);
#endif // ARDUINO_ARCH_ESP32
#include "src/lib/SDCH/SDCH.h" // Auxiliar para gerenciamento de cartao SD
#if ARDUINO_ARCH_ESP32
SDCH SDC(SD_CS_PIN, CURRENT_MODE_PROJECT_NAME, "txt", SPI_SD); //Declaration of object to help SD card file management
#else
SDCH SDC(SD_CS_PIN, CURRENT_MODE_PROJECT_NAME); //Declaration of object to help SD card file management
#endif // ARDUINO_ARCH_ESP32
#endif // SDCard
#if GPSmode
#include "src/lib/GyGPS/GyGPS.h" // Auxiliar para GPS
#ifdef ARDUINO_ARCH_ESP32
HardwareSerial GpSSerial(1);
GyGPS GpS(GpSSerial, 0, SERIAL_8N1, RX_GPS_ESP, TX_GPS_ESP);
#else
GyGPS GpS(Serial1, 0);
#endif // ARDUINO_ARCH_ESP32
#endif // GPSmode
#if LoRamode
#if 1 < ((USE_LoRa_DORJI) + (USE_LoRa_E32))
#error: Múltiplos LoRas definidos
#elif USE_LoRa_DORJI
#define LoRaDelay 2.5
#elif USE_LoRa_E32
#define LoRaDelay 2.5
#else
#define LoRaDelay 5
#endif // USE_LoRa_DORJI || USE_LoRa_E32
#ifdef ARDUINO_ARCH_ESP32
HardwareSerial LoRa(2);
#else
HardwareSerial &LoRa(Serial3);
#endif
Helpful LRutil; //Declaration of helpful object to telemetry system
#define LoRaBaudRate 9600
#if USE_LoRa_E32
#if !defined(M0_LORA_PIN) || !defined(M1_LORA_PIN) || !defined(AUX_LORA_PIN)
#error: Placa selecionada nao utiliza LoRa E32
#endif
#if USE_LoRa_E32_settable
#define FREQUENCY_900
#define LoRa_ADDL 0x2A // 42 decimal (Standardized)
#define LoRa_ADDH 0x00
#define LoRa_CHAN 0x2A // 42 decimal (904 - 862)
#include "LoRa_E32.h"
// #include <EEPROM.h>
#include "src/lib/EEDataRegister/EEMap.h"
// uint16_t LoRaEEAddress = 0x0; // Atualizar este valor no setup
Configuration configLoRa;
// struct LoRaEEConfig{
// Configuration configuration;
// uint16_t compileHash = 0;
// uint16_t checkSum = 0;
// };
EEDataRegister<Configuration> loraReg(eeSlotAddress(EE_SLOT_LORA_CONFIG));
static_assert(EEDataRegister<Configuration>::blockSize() <= EE_SLOT_SIZE,
"LoRa: bloco de configuracao excede o slot");
LoRa_E32 LoRaConfig(&LoRa, byte(AUX_LORA_PIN), byte(M0_LORA_PIN), byte(M1_LORA_PIN), UART_BPS_RATE(LoRaBaudRate));
// uint16_t calcCheckSum(const Configuration& configuration)
// {
// uint16_t sum = 0;
// const byte* p = (const byte*)&configuration;
// for (size_t i = 0; i < sizeof(Configuration); i++) {
// sum += p[i];
// }
// return sum;
// }
void loadLoRaDefaultConfig()
{
configLoRa.ADDL = LoRa_ADDL;
configLoRa.ADDH = LoRa_ADDH;
configLoRa.CHAN = LoRa_CHAN;
// configLoRa.OPTION.fec = FEC_0_OFF;
// configLoRa.OPTION.fixedTransmission = FT_TRANSPARENT_TRANSMISSION;
// configLoRa.OPTION.ioDriveMode = IO_D_MODE_PUSH_PULLS_PULL_UPS;
// configLoRa.OPTION.transmissionPower = POWER_17;
// configLoRa.OPTION.wirelessWakeupTime = WAKE_UP_1250;
// configLoRa.SPED.airDataRate = AIR_DATA_RATE_011_48;
// configLoRa.SPED.uartBaudRate = UART_BPS_9600;
// configLoRa.SPED.uartParity = MODE_00_8N1;
}
bool setLoRaConfig()
{
ResponseStructContainer c = LoRaConfig.getConfiguration();
#if PRINT
Serial.println(c.status.getResponseDescription());
Serial.println(c.status.code);
#endif
if(c.status.code != E32_SUCCESS) {
c.close();
return false;
}
// It's important get configuration pointer before all other operation
Configuration configuration = *(Configuration*)c.data;
// printParameters(configuration);
configuration.ADDL = configLoRa.ADDL;
configuration.ADDH = configLoRa.ADDH;
configuration.CHAN = configLoRa.CHAN;
configuration.OPTION.fec = FEC_1_ON;
configuration.OPTION.fixedTransmission = FT_TRANSPARENT_TRANSMISSION;
configuration.OPTION.ioDriveMode = IO_D_MODE_PUSH_PULLS_PULL_UPS;
configuration.OPTION.transmissionPower = POWER_20;
configuration.OPTION.wirelessWakeupTime = WAKE_UP_250;
configuration.SPED.airDataRate = AIR_DATA_RATE_101_192;
// configuration.SPED.uartBaudRate = configLoRa.SPED.uartBaudRate;
// configuration.SPED.uartParity = configLoRa.SPED.uartParity;
// Set configuration changed and set to not hold the configuration
ResponseStatus rs = LoRaConfig.setConfiguration(configuration, WRITE_CFG_PWR_DWN_SAVE);
#if PRINT
Serial.println(rs.getResponseDescription());
Serial.println(rs.code);
#endif
// printParameters(configuration);
c.close();
return rs.code == E32_SUCCESS;
}
bool getLoRaConfig()
{
ResponseStructContainer c = LoRaConfig.getConfiguration();
// It's important get configuration pointer before all other operation
if(c.status.code != E32_SUCCESS)
{
c.close();
return false;
}
configLoRa = *(Configuration*)c.data;
c.close();
return true;
}
// uint16_t compileTimeHash() {
// const char* date = __DATE__;
// const char* time = __TIME__;
// uint16_t hash = 0;
// while (*date) {
// hash = (hash << 5) - hash + *date++;
// }
// while (*time) {
// hash = (hash << 5) - hash + *time++;
// }
// return hash;
// }
// void saveLoRaEEConfig(){
// LoRaEEConfig loRaEEAux;
// loRaEEAux.configuration = configLoRa;
// loRaEEAux.compileHash = compileTimeHash();
// loRaEEAux.checkSum = calcCheckSum(configLoRa);
// EEPROM.put(LoRaEEAddress, loRaEEAux);
// #if defined(ARDUINO_ARCH_ESP32)
// EEPROM.commit();
// #endif // defined(ARDUINO_ARCH_ESP32)
// }
void saveLoRaEEConfig(){
loraReg.data = configLoRa;
loraReg.saveIfChanged();
}
// bool loadLoRaEEConfig() {
// LoRaEEConfig loRaEEAux;
// EEPROM.get(LoRaEEAddress, loRaEEAux);
// uint16_t sum = calcCheckSum(loRaEEAux.configuration);
// if((sum == loRaEEAux.checkSum) && (loRaEEAux.compileHash == compileTimeHash()) && (loRaEEAux.configuration.HEAD == 0xC0 || loRaEEAux.configuration.HEAD == 0xC2))
// {
// configLoRa = loRaEEAux.configuration;
// return true;
// }
// return false;
// }
bool loadLoRaEEConfig() {
if (!loraReg.load()) return false;
if (!(loraReg.data.HEAD == 0xC0 || loraReg.data.HEAD == 0xC2)) return false;
configLoRa = loraReg.data;
return true;
}
#define RX_CHG_FREQ_REQ_HEAD "MUD4R_FR3Q_PFV.CH4N"
// CHAN
#define RX_CHG_FREQ_REQ_MID "_"
// ADDH / ADDL
#define RX_CHG_FREQ_REQ_TAIL "#"
#define TX_CHG_FREQ_CONFIRM_HEAD "CTZ_FR3Q.CH4N"
// CHAN
#define TX_CHG_FREQ_CONFIRM_MID "_"
// ADDH / ADDL
#define TX_CHG_FREQ_CONFIRM_TAIL "#"
#define RX_CHG_FREQ_OK "1SSO_MSM"
#define RX_CHG_FREQ_VRFY "MUD0U_MSM"
#define TX_CHG_FREQ_RESP "JUR0_JUR4D1NH0"
#define RX_CHG_FREQ_FINAL "B04"
#define TX_CHG_FREQ_ERROR "N4N4N1N4N40"
const char chgFreqReqHead[] = RX_CHG_FREQ_REQ_HEAD;
constexpr size_t chgFreqReqHeadLen = sizeof(chgFreqReqHead) - 1;
const char chgFreqReqMid[] = RX_CHG_FREQ_REQ_MID;
constexpr size_t chgFreqReqMidLen = sizeof(chgFreqReqMid) - 1;
const char chgFreqReqTail[] = RX_CHG_FREQ_REQ_TAIL;
constexpr size_t chgFreqReqTailLen = sizeof(chgFreqReqTail) - 1;
constexpr size_t chgFreqReqLen = chgFreqReqHeadLen + 2 + chgFreqReqMidLen + 4 + chgFreqReqTailLen;
const char chgFreqCfmHead[] = TX_CHG_FREQ_CONFIRM_HEAD;
constexpr size_t chgFreqCfmHeadLen = sizeof(chgFreqCfmHead) - 1;
const char chgFreqCfmMid[] = TX_CHG_FREQ_CONFIRM_MID;
constexpr size_t chgFreqCfmMidLen = sizeof(chgFreqCfmMid) - 1;
const char chgFreqCfmTail[] = TX_CHG_FREQ_CONFIRM_TAIL;
constexpr size_t chgFreqCfmTailLen = sizeof(chgFreqCfmTail) - 1;
constexpr size_t chgFreqCfmLen = chgFreqCfmHeadLen + 2 + chgFreqCfmMidLen + 4 + chgFreqCfmTailLen;
const char chgFreqOk[] = RX_CHG_FREQ_OK;
constexpr size_t chgFreqOkLen = sizeof(chgFreqOk) - 1;
const char chgFreqVrfy[] = RX_CHG_FREQ_VRFY;
constexpr size_t chgFreqVrfyLen = sizeof(chgFreqVrfy) - 1;
const char chgFreqFinal[] = RX_CHG_FREQ_FINAL;
constexpr size_t chgFreqFinalLen = sizeof(chgFreqFinal) - 1;
inline uint8_t asciiHex2Nibble(char c) {
if (c >= '0' && c <= '9') return c - '0';
if (c >= 'A' && c <= 'F') return c - 'A' + 10;
if (c >= 'a' && c <= 'f') return c - 'a' + 10;
return 0;
}
uint8_t nibble2AsciiHex(byte val){
if (val < 10) return '0' + val;
return 'A' + (val - 10);
}
uint8_t hexFromCharPair(const char* ptr) {
return (asciiHex2Nibble(ptr[0]) << 4) | asciiHex2Nibble(ptr[1]);
}
void embedHexByte(char* target, byte val) {
target[0] = nibble2AsciiHex(val >> 4);
target[1] = nibble2AsciiHex(val & 0x0F);
}
unsigned long pauseTelemetryUntil = 0;
void cancelLoRaConfig(bool reverter, Configuration &previousConfig)
{
LoRa.println(TX_CHG_FREQ_ERROR);
#if PRINT
Serial.println(F("[LORA RX] ERRO: Handshake abortado ou configuracao invalida!"));
#endif
if(reverter){
configLoRa = previousConfig;
setLoRaConfig();
saveLoRaEEConfig();
}
}
enum HandshakeState {
HS_IDLE,
HS_WAITING_M_PACKET,
HS_SENDING_CFM,
HS_WAITING_1SSO,
HS_WAITING_MUD0U,
HS_WAITING_B04
};
void updateLoRaFrequency(){
static HandshakeState hsState = HS_IDLE;
HandshakeState oldState = hsState;
static unsigned long stateTimeout = 0;
static unsigned long startWait = 0;
static Configuration previousConfig;
static int CHAN = LoRa_CHAN;
static int ADDH = LoRa_ADDH;
static int ADDL = LoRa_ADDL;
static char recieved[64] = {};
static char toSend[chgFreqCfmLen + 1] = {};
static unsigned long sendCfmAt = 0;
int discardLimit = 256; // Safety limit to prevent infinite loops on serial noise
switch (hsState) {
case HS_IDLE: {
if (LoRa.available() > 0) {
while (LoRa.available() > 0 && LoRa.peek() != 'M' && discardLimit-- > 0) {
LoRa.read();
}
if (LoRa.available() > 0 && LoRa.peek() == 'M') {
startWait = millis();
hsState = HS_WAITING_M_PACKET;
}
}
break;
}
case HS_WAITING_M_PACKET: {
if (LoRa.available() >= chgFreqReqLen) {
char tempRec[64] = {};
uint8_t count = LoRa.readBytesUntil('\n', tempRec, chgFreqReqLen);
tempRec[count] = '\0';
// Pause telemetry for 6s
// extern unsigned long pauseTelemetryUntil;
pauseTelemetryUntil = millis() + 6000;
#if PRINT
Serial.println(F("\n========== [LORA RX] =========="));
Serial.print(F("[LORA RX] Mensagem recebida: "));
Serial.println(tempRec);
#endif
if (getLoRaConfig()) {
previousConfig = configLoRa;
} else {
previousConfig = configLoRa;
}
bool reqCheck = true;
reqCheck &= (strncmp(tempRec, chgFreqReqHead, chgFreqReqHeadLen) == 0);
if (reqCheck) {
reqCheck &= (strncmp(tempRec + chgFreqReqHeadLen + 2, chgFreqReqMid, chgFreqReqMidLen) == 0);
}
if (reqCheck) {
reqCheck &= (strncmp(tempRec + chgFreqReqHeadLen + 2 + chgFreqReqMidLen + 4, chgFreqReqTail, chgFreqReqTailLen) == 0);
}
if (!reqCheck) {
#if PRINT
Serial.println(F("[LORA RX] ERRO: Header/Separador/Tail invalido"));
#endif
cancelLoRaConfig(false, previousConfig);
hsState = HS_IDLE;
break;
}
CHAN = hexFromCharPair(tempRec + chgFreqReqHeadLen);
if (CHAN > 0x45) {
#if PRINT
Serial.println(F("[LORA RX] ERRO: Canal invalido"));
#endif
cancelLoRaConfig(false, previousConfig);
hsState = HS_IDLE;
break;
}
ADDH = hexFromCharPair(tempRec + chgFreqReqHeadLen + 2 + chgFreqReqMidLen);
ADDL = hexFromCharPair(tempRec + chgFreqReqHeadLen + 2 + chgFreqReqMidLen + 2);
#if PRINT
Serial.print(F("[LORA RX] Parse OK! CHAN="));
Serial.print(CHAN, DEC);
Serial.print(F(" ADDH=0x"));
Serial.print(ADDH, HEX);
Serial.print(F(" ADDL=0x"));
Serial.println(ADDL, HEX);
#endif
// char toSend[chgFreqCfmLen + 1] = {};
memset(toSend, 0, sizeof(toSend));
memcpy(toSend, chgFreqCfmHead, chgFreqCfmHeadLen);
embedHexByte(toSend + chgFreqCfmHeadLen, CHAN);
memcpy(toSend + chgFreqCfmHeadLen + 2, chgFreqCfmMid, chgFreqCfmMidLen);
embedHexByte(toSend + chgFreqCfmHeadLen + 2 + chgFreqCfmMidLen, ADDH);
embedHexByte(toSend + chgFreqCfmHeadLen + 2 + chgFreqCfmMidLen + 2, ADDL);
memcpy(toSend + chgFreqCfmHeadLen + 2 + chgFreqCfmMidLen + 4, chgFreqCfmTail, chgFreqCfmTailLen);
toSend[chgFreqCfmLen] = '\0';
#if PRINT
Serial.print(F("[LORA RX] Enviando confirmacao: "));
Serial.println(toSend);
#endif
sendCfmAt = millis() + 900;
hsState = HS_SENDING_CFM;
// delay(900);
// while (LoRa.available() > 0 && discardLimit-- > 0) LoRa.read();
// LoRa.println(toSend);
// #if PRINT
// Serial.println(F("[LORA RX] Aguardando 1SSO_MSM do GS..."));
// #endif
// stateTimeout = millis() + 5000;
// hsState = HS_WAITING_1SSO;
} else if (millis() - startWait >= 100) {
#if PRINT
Serial.print(F("[LORA RX] Bytes insuficientes ou invalido: "));
Serial.print(LoRa.available());
Serial.print(F(" / "));
Serial.print(chgFreqReqLen);
Serial.println(F(". Descartando 'M'"));
#endif
LoRa.read();
hsState = HS_IDLE;
}
break;
}
case HS_SENDING_CFM: {
if(long (millis() - sendCfmAt) < 0) break; // Esperar mais
while (LoRa.available() > 0 && discardLimit-- > 0) LoRa.read();
LoRa.println(toSend);
#if PRINT
Serial.println(F("[LORA RX] Aguardando 1SSO_MSM do GS..."));
#endif
stateTimeout = millis() + 5000;
hsState = HS_WAITING_1SSO;
break;
}
case HS_WAITING_1SSO: {
if (millis() > stateTimeout) {
#if PRINT
Serial.println(F("[LORA RX] TIMEOUT aguardando 1SSO_MSM"));
#endif
cancelLoRaConfig(false, previousConfig);
hsState = HS_IDLE;
break;
}
if (LoRa.available() > 0) {
while (LoRa.available() > 0 && LoRa.peek() != '1' && discardLimit-- > 0) {
LoRa.read();
}
if (LoRa.available() >= chgFreqOkLen) {
uint8_t count = LoRa.readBytesUntil('\n', recieved, chgFreqOkLen);
recieved[count] = '\0';
#if PRINT
Serial.print(F("[LORA RX] Recebeu: "));
Serial.println(recieved);
#endif
if (strncmp(recieved, chgFreqOk, chgFreqOkLen) == 0) {
configLoRa.ADDL = ADDL;
configLoRa.ADDH = ADDH;
configLoRa.CHAN = CHAN;
if (setLoRaConfig()) {
saveLoRaEEConfig();
#if PRINT
Serial.println(F("[LORA RX] Frequencia aplicada. Aguardando MUD0U_MSM do GS..."));
#endif
stateTimeout = millis() + 5000;
hsState = HS_WAITING_MUD0U;
} else {
cancelLoRaConfig(true, previousConfig);
hsState = HS_IDLE;
}
} else {
#if PRINT
Serial.println(F("[LORA RX] ERRO: 1SSO_MSM invalido"));
#endif
cancelLoRaConfig(false, previousConfig);
hsState = HS_IDLE;
}
}
}
break;
}
case HS_WAITING_MUD0U: {
if (millis() > stateTimeout) {
#if PRINT
Serial.println(F("[LORA RX] TIMEOUT aguardando MUD0U_MSM"));
#endif
cancelLoRaConfig(true, previousConfig);
hsState = HS_IDLE;
break;
}
if (LoRa.available() > 0) {
while (LoRa.available() > 0 && LoRa.peek() != 'M' && discardLimit-- > 0) {
LoRa.read();
}
if (LoRa.available() >= chgFreqVrfyLen) {
uint8_t count = LoRa.readBytesUntil('\n', recieved, chgFreqVrfyLen);
recieved[count] = '\0';
#if PRINT
Serial.print(F("[LORA RX] Recebeu: "));
Serial.println(recieved);
#endif
if (strncmp(recieved, chgFreqVrfy, chgFreqVrfyLen) == 0) {