forked from ExpressLRS/ExpressLRS
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrx_main.cpp
More file actions
1998 lines (1751 loc) · 61 KB
/
rx_main.cpp
File metadata and controls
1998 lines (1751 loc) · 61 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
#include "rxtx_common.h"
#include "LowPassFilter.h"
#include "crc.h"
#include "telemetry_protocol.h"
#include "telemetry.h"
#include "stubborn_sender.h"
#include "stubborn_receiver.h"
#include "lua.h"
#include "msp.h"
#include "msptypes.h"
#include "PFD.h"
#include "options.h"
#include "dynpower.h"
#include "MeanAccumulator.h"
#include "freqTable.h"
#include "rx-serial/SerialIO.h"
#include "rx-serial/SerialNOOP.h"
#include "rx-serial/SerialCRSF.h"
#include "rx-serial/SerialSBUS.h"
#include "rx-serial/SerialSUMD.h"
#include "rx-serial/SerialAirPort.h"
#include "rx-serial/SerialHoTT_TLM.h"
#include "rx-serial/devSerialIO.h"
#include "devLED.h"
#include "devLUA.h"
#include "devWIFI.h"
#include "devButton.h"
#include "devServoOutput.h"
#include "devVTXSPI.h"
#include "devAnalogVbat.h"
#include "devSerialUpdate.h"
#include "devBaro.h"
#include "devMSPVTX.h"
#if defined(PLATFORM_ESP8266)
#include <user_interface.h>
#include <FS.h>
#elif defined(PLATFORM_ESP32)
#include <SPIFFS.h>
#endif
///LUA///
#define LUA_MAX_PARAMS 32
////
//// CONSTANTS ////
#define SEND_LINK_STATS_TO_FC_INTERVAL 100
#define DIVERSITY_ANTENNA_INTERVAL 5
#define DIVERSITY_ANTENNA_RSSI_TRIGGER 5
#define PACKET_TO_TOCK_SLACK 200 // Desired buffer time between Packet ISR and Tock ISR
///////////////////
device_affinity_t ui_devices[] = {
{&Serial_device, 1},
#if defined(PLATFORM_ESP32)
{&SerialUpdate_device, 1},
#endif
#ifdef HAS_LED
{&LED_device, 0},
#endif
{&LUA_device, 0},
#ifdef HAS_RGB
{&RGB_device, 0},
#endif
#ifdef HAS_WIFI
{&WIFI_device, 0},
#endif
#ifdef HAS_BUTTON
{&Button_device, 0},
#endif
#ifdef HAS_VTX_SPI
{&VTxSPI_device, 0},
#endif
#ifdef USE_ANALOG_VBAT
{&AnalogVbat_device, 0},
#endif
#ifdef HAS_SERVO_OUTPUT
{&ServoOut_device, 1},
#endif
#ifdef HAS_BARO
{&Baro_device, 0}, // must come after AnalogVbat_device to slow updates
#endif
#ifdef HAS_MSP_VTX
{&MSPVTx_device, 0}, // dependency on VTxSPI_device
#endif
};
uint8_t antenna = 0; // which antenna is currently in use
uint8_t geminiMode = 0;
PFD PFDloop;
Crc2Byte ota_crc;
ELRS_EEPROM eeprom;
RxConfig config;
Telemetry telemetry;
Stream *SerialLogger;
bool hardwareConfigured = true;
#if defined(USE_MSP_WIFI)
#include "crsf2msp.h"
#include "msp2crsf.h"
CROSSFIRE2MSP crsf2msp;
MSP2CROSSFIRE msp2crsf;
#endif
#if defined(PLATFORM_ESP8266) || defined(PLATFORM_ESP32)
unsigned long rebootTime = 0;
extern bool webserverPreventAutoStart;
bool pwmSerialDefined = false;
#endif
uint32_t serialBaud;
/* SERIAL_PROTOCOL_TX is used by CRSF output */
#if defined(TARGET_RX_FM30_MINI)
HardwareSerial SERIAL_PROTOCOL_TX(USART2);
#elif defined(TARGET_DIY_900_RX_STM32)
HardwareSerial SERIAL_PROTOCOL_TX(USART1);
#else
#define SERIAL_PROTOCOL_TX Serial
#endif
SerialIO *serialIO;
/* SERIAL_PROTOCOL_RX is used by telemetry receiver and can be on a different peripheral */
#if defined(TARGET_RX_GHOST_ATTO_V1) /* !TARGET_RX_GHOST_ATTO_V1 */
#define SERIAL_PROTOCOL_RX CrsfRxSerial
HardwareSerial CrsfRxSerial(USART1, HALF_DUPLEX_ENABLED);
#elif defined(TARGET_R9SLIMPLUS_RX) /* !TARGET_R9SLIMPLUS_RX */
#define SERIAL_PROTOCOL_RX CrsfRxSerial
HardwareSerial CrsfRxSerial(USART3);
#elif defined(TARGET_RX_FM30_MINI)
#define SERIAL_PROTOCOL_RX SERIAL_PROTOCOL_TX
#else
#define SERIAL_PROTOCOL_RX Serial
#endif
StubbornSender TelemetrySender;
static uint8_t telemetryBurstCount;
static uint8_t telemetryBurstMax;
StubbornReceiver MspReceiver;
uint8_t MspData[ELRS_MSP_BUFFER];
static bool tlmSent = false;
static uint8_t NextTelemetryType = ELRS_TELEMETRY_TYPE_LINK;
static bool telemBurstValid;
/// PFD Filters ////////////////
LPF LPF_Offset(2);
LPF LPF_OffsetDx(4);
/// LQ/RSSI/SNR Calculation //////////
LQCALC<100> LQCalc;
LQCALC<100> LQCalcDVDA;
uint8_t uplinkLQ;
LPF LPF_UplinkRSSI0(5); // track rssi per antenna
LPF LPF_UplinkRSSI1(5);
MeanAccumulator<int32_t, int8_t, -16> SnrMean;
static uint8_t scanIndex;
uint8_t ExpressLRS_nextAirRateIndex;
int8_t SwitchModePending;
int32_t PfdPrevRawOffset;
RXtimerState_e RXtimerState;
uint32_t GotConnectionMillis = 0;
const uint32_t ConsiderConnGoodMillis = 1000; // minimum time before we can consider a connection to be 'good'
///////////////////////////////////////////////
bool didFHSS = false;
bool alreadyFHSS = false;
bool alreadyTLMresp = false;
//////////////////////////////////////////////////////////////
///////Variables for Telemetry and Link Quality///////////////
uint32_t LastValidPacket = 0; //Time the last valid packet was recv
uint32_t LastSyncPacket = 0; //Time the last valid packet was recv
static uint32_t SendLinkStatstoFCintervalLastSent;
static uint8_t SendLinkStatstoFCForcedSends;
int16_t RFnoiseFloor; //measurement of the current RF noise floor
#if defined(DEBUG_RX_SCOREBOARD)
static bool lastPacketCrcError;
#endif
///////////////////////////////////////////////////////////////
/// Variables for Sync Behaviour ////
uint32_t cycleInterval; // in ms
uint32_t RFmodeLastCycled = 0;
#define RFmodeCycleMultiplierSlow 10
uint8_t RFmodeCycleMultiplier;
bool LockRFmode = false;
///////////////////////////////////////
#if defined(DEBUG_BF_LINK_STATS)
// Debug vars
uint8_t debug1 = 0;
uint8_t debug2 = 0;
uint8_t debug3 = 0;
int8_t debug4 = 0;
///////////////////////////////////////
#endif
#if defined(DEBUG_RCVR_LINKSTATS)
static bool debugRcvrLinkstatsPending;
static uint8_t debugRcvrLinkstatsFhssIdx;
#endif
#define LOAN_BIND_TIMEOUT_DEFAULT 60000
#define LOAN_BIND_TIMEOUT_MSP 10000U
bool InBindingMode = false;
bool InLoanBindingMode = false;
bool returnModelFromLoan = false;
static unsigned long loanBindTimeout = LOAN_BIND_TIMEOUT_DEFAULT;
static unsigned long loadBindingStartedMs = 0;
void reset_into_bootloader(void);
void EnterBindingMode();
void ExitBindingMode();
void OnELRSBindMSP(uint8_t* packet);
extern void setWifiUpdateMode();
uint8_t getLq()
{
return LQCalc.getLQ();
}
static inline void checkGeminiMode()
{
if (isDualRadio())
{
geminiMode = config.GetAntennaMode();
}
}
static uint8_t minLqForChaos()
{
// Determine the most number of CRC-passing packets we could receive on
// a single channel out of 100 packets that fill the LQcalc span.
// The LQ must be GREATER THAN this value, not >=
// The amount of time we coexist on the same channel is
// 100 divided by the total number of packets in a FHSS loop (rounded up)
// and there would be 4x packets received each time it passes by so
// FHSShopInterval * ceil(100 / FHSShopInterval * numfhss) or
// FHSShopInterval * trunc((100 + (FHSShopInterval * numfhss) - 1) / (FHSShopInterval * numfhss))
// With a interval of 4 this works out to: 2.4=4, FCC915=4, AU915=8, EU868=8, EU/AU433=36
const uint32_t numfhss = FHSSgetChannelCount();
const uint8_t interval = ExpressLRS_currAirRate_Modparams->FHSShopInterval;
return interval * ((interval * numfhss + 99) / (interval * numfhss));
}
void ICACHE_RAM_ATTR getRFlinkInfo()
{
if (GPIO_PIN_NSS_2 != UNDEF_PIN)
{
antenna = (Radio.GetProcessingPacketRadio() == SX12XX_Radio_1) ? 0 : 1;
}
int32_t rssiDBM = Radio.LastPacketRSSI;
if (GPIO_PIN_NSS_2 != UNDEF_PIN)
{
int32_t rssiDBM2 = Radio.LastPacketRSSI2;
#if !defined(DEBUG_RCVR_LINKSTATS)
rssiDBM = LPF_UplinkRSSI0.update(rssiDBM);
rssiDBM2 = LPF_UplinkRSSI1.update(rssiDBM2);
#endif
rssiDBM = (rssiDBM > 0) ? 0 : rssiDBM;
rssiDBM2 = (rssiDBM2 > 0) ? 0 : rssiDBM2;
// BetaFlight/iNav expect positive values for -dBm (e.g. -80dBm -> sent as 80)
CRSF::LinkStatistics.uplink_RSSI_1 = -rssiDBM;
CRSF::LinkStatistics.uplink_RSSI_2 = -rssiDBM2;
antenna = (rssiDBM > rssiDBM2)? 0 : 1; // report a better antenna for the reception
}
else if (antenna == 0)
{
#if !defined(DEBUG_RCVR_LINKSTATS)
rssiDBM = LPF_UplinkRSSI0.update(rssiDBM);
#endif
if (rssiDBM > 0) rssiDBM = 0;
// BetaFlight/iNav expect positive values for -dBm (e.g. -80dBm -> sent as 80)
CRSF::LinkStatistics.uplink_RSSI_1 = -rssiDBM;
}
else
{
#if !defined(DEBUG_RCVR_LINKSTATS)
rssiDBM = LPF_UplinkRSSI1.update(rssiDBM);
#endif
if (rssiDBM > 0) rssiDBM = 0;
// BetaFlight/iNav expect positive values for -dBm (e.g. -80dBm -> sent as 80)
// May be overwritten below if DEBUG_BF_LINK_STATS is set
CRSF::LinkStatistics.uplink_RSSI_2 = -rssiDBM;
}
SnrMean.add(Radio.LastPacketSNRRaw);
CRSF::LinkStatistics.active_antenna = antenna;
CRSF::LinkStatistics.uplink_SNR = SNR_DESCALE(Radio.LastPacketSNRRaw); // possibly overriden below
//CRSF::LinkStatistics.uplink_Link_quality = uplinkLQ; // handled in Tick
CRSF::LinkStatistics.rf_Mode = ExpressLRS_currAirRate_Modparams->enum_rate;
//DBGLN(CRSF::LinkStatistics.uplink_RSSI_1);
#if defined(DEBUG_BF_LINK_STATS)
CRSF::LinkStatistics.downlink_RSSI = debug1;
CRSF::LinkStatistics.downlink_Link_quality = debug2;
CRSF::LinkStatistics.downlink_SNR = debug3;
CRSF::LinkStatistics.uplink_RSSI_2 = debug4;
#endif
#if defined(DEBUG_RCVR_LINKSTATS)
// DEBUG_RCVR_LINKSTATS gets full precision SNR, override the value
CRSF::LinkStatistics.uplink_SNR = Radio.LastPacketSNRRaw;
debugRcvrLinkstatsFhssIdx = FHSSsequence[FHSSptr];
#endif
}
void SetRFLinkRate(uint8_t index) // Set speed of RF link
{
expresslrs_mod_settings_s *const ModParams = get_elrs_airRateConfig(index);
expresslrs_rf_pref_params_s *const RFperf = get_elrs_RFperfParams(index);
bool invertIQ = UID[5] & 0x01;
uint32_t interval = ModParams->interval;
#if defined(DEBUG_FREQ_CORRECTION) && defined(RADIO_SX128X)
interval = interval * 12 / 10; // increase the packet interval by 20% to allow adding packet header
#endif
hwTimer::updateInterval(interval);
Radio.Config(ModParams->bw, ModParams->sf, ModParams->cr, GetInitialFreq(),
ModParams->PreambleLen, invertIQ, ModParams->PayloadLength, 0
#if defined(RADIO_SX128X)
, uidMacSeedGet(), OtaCrcInitializer, (ModParams->radio_type == RADIO_TYPE_SX128x_FLRC)
#endif
);
Radio.FuzzySNRThreshold = (RFperf->DynpowerSnrThreshUp == DYNPOWER_SNR_THRESH_NONE) ? 0 : (RFperf->DynpowerSnrThreshDn - RFperf->DynpowerSnrThreshUp);
checkGeminiMode();
if (geminiMode)
{
Radio.SetFrequencyReg(FHSSgetInitialGeminiFreq(), SX12XX_Radio_2);
}
OtaUpdateSerializers(smWideOr8ch, ModParams->PayloadLength);
MspReceiver.setMaxPackageIndex(ELRS_MSP_MAX_PACKAGES);
TelemetrySender.setMaxPackageIndex(OtaIsFullRes ? ELRS8_TELEMETRY_MAX_PACKAGES : ELRS4_TELEMETRY_MAX_PACKAGES);
// Wait for (11/10) 110% of time it takes to cycle through all freqs in FHSS table (in ms)
cycleInterval = ((uint32_t)11U * FHSSgetChannelCount() * ModParams->FHSShopInterval * interval) / (10U * 1000U);
ExpressLRS_currAirRate_Modparams = ModParams;
ExpressLRS_currAirRate_RFperfParams = RFperf;
ExpressLRS_nextAirRateIndex = index; // presumably we just handled this
telemBurstValid = false;
}
bool ICACHE_RAM_ATTR HandleFHSS()
{
uint8_t modresultFHSS = (OtaNonce + 1) % ExpressLRS_currAirRate_Modparams->FHSShopInterval;
if ((ExpressLRS_currAirRate_Modparams->FHSShopInterval == 0) || alreadyFHSS == true || InBindingMode || (modresultFHSS != 0) || (connectionState == disconnected))
{
return false;
}
alreadyFHSS = true;
if (geminiMode)
{
if (((OtaNonce + 1)/ExpressLRS_currAirRate_Modparams->FHSShopInterval) % 2 == 0)
{
Radio.SetFrequencyReg(FHSSgetNextFreq(), SX12XX_Radio_1);
Radio.SetFrequencyReg(FHSSgetGeminiFreq(), SX12XX_Radio_2);
}
else
{
Radio.SetFrequencyReg(FHSSgetNextFreq(), SX12XX_Radio_2);
Radio.SetFrequencyReg(FHSSgetGeminiFreq(), SX12XX_Radio_1);
}
}
else
{
Radio.SetFrequencyReg(FHSSgetNextFreq());
}
#if defined(RADIO_SX127X)
// SX127x radio has to reset receive mode after hopping
uint8_t modresultTLM = (OtaNonce + 1) % ExpressLRS_currTlmDenom;
if (modresultTLM != 0 || ExpressLRS_currTlmDenom == 1) // if we are about to send a tlm response don't bother going back to rx
{
Radio.RXnb();
}
#endif
#if defined(Regulatory_Domain_EU_CE_2400)
SetClearChannelAssessmentTime();
#endif
return true;
}
void ICACHE_RAM_ATTR LinkStatsToOta(OTA_LinkStats_s * const ls)
{
// The value in linkstatistics is "positivized" (inverted polarity)
// and must be inverted on the TX side. Positive values are used
// so save a bit to encode which antenna is in use
ls->uplink_RSSI_1 = CRSF::LinkStatistics.uplink_RSSI_1;
ls->uplink_RSSI_2 = CRSF::LinkStatistics.uplink_RSSI_2;
ls->antenna = antenna;
ls->modelMatch = connectionHasModelMatch;
ls->lq = CRSF::LinkStatistics.uplink_Link_quality;
ls->mspConfirm = MspReceiver.GetCurrentConfirm() ? 1 : 0;
#if defined(DEBUG_FREQ_CORRECTION)
ls->SNR = FreqCorrection * 127 / FreqCorrectionMax;
#else
ls->SNR = SnrMean.mean();
#endif
}
bool ICACHE_RAM_ATTR HandleSendTelemetryResponse()
{
uint8_t modresult = (OtaNonce + 1) % ExpressLRS_currTlmDenom;
if ((connectionState == disconnected) || (ExpressLRS_currTlmDenom == 1) || (alreadyTLMresp == true) || (modresult != 0))
{
return false; // don't bother sending tlm if disconnected or TLM is off
}
#if defined(Regulatory_Domain_EU_CE_2400)
BeginClearChannelAssessment();
#endif
// ESP requires word aligned buffer
WORD_ALIGNED_ATTR OTA_Packet_s otaPkt = {0};
alreadyTLMresp = true;
otaPkt.std.type = PACKET_TYPE_TLM;
if (NextTelemetryType == ELRS_TELEMETRY_TYPE_LINK || (!firmwareOptions.is_airport && !TelemetrySender.IsActive()))
{
OTA_LinkStats_s * ls;
if (OtaIsFullRes)
{
otaPkt.full.tlm_dl.containsLinkStats = 1;
ls = &otaPkt.full.tlm_dl.ul_link_stats.stats;
// Include some advanced telemetry in the extra space
// Note the use of `ul_link_stats.payload` vs just `payload`
otaPkt.full.tlm_dl.packageIndex = TelemetrySender.GetCurrentPayload(
otaPkt.full.tlm_dl.ul_link_stats.payload,
sizeof(otaPkt.full.tlm_dl.ul_link_stats.payload));
}
else
{
otaPkt.std.tlm_dl.type = ELRS_TELEMETRY_TYPE_LINK;
ls = &otaPkt.std.tlm_dl.ul_link_stats.stats;
}
LinkStatsToOta(ls);
NextTelemetryType = ELRS_TELEMETRY_TYPE_DATA;
// Start the count at 1 because the next will be DATA and doing +1 before checking
// against Max below is for some reason 10 bytes more code
telemetryBurstCount = 1;
}
else
{
if (telemetryBurstCount < telemetryBurstMax)
{
telemetryBurstCount++;
}
else
{
NextTelemetryType = ELRS_TELEMETRY_TYPE_LINK;
}
if (firmwareOptions.is_airport)
{
OtaPackAirportData(&otaPkt, &apInputBuffer);
}
else
{
if (OtaIsFullRes)
{
otaPkt.full.tlm_dl.packageIndex = TelemetrySender.GetCurrentPayload(
otaPkt.full.tlm_dl.payload,
sizeof(otaPkt.full.tlm_dl.payload));
}
else
{
otaPkt.std.tlm_dl.type = ELRS_TELEMETRY_TYPE_DATA;
otaPkt.std.tlm_dl.packageIndex = TelemetrySender.GetCurrentPayload(
otaPkt.std.tlm_dl.payload,
sizeof(otaPkt.std.tlm_dl.payload));
}
}
}
OtaGeneratePacketCrc(&otaPkt);
SX12XX_Radio_Number_t transmittingRadio = geminiMode ? SX12XX_Radio_All : Radio.GetLastSuccessfulPacketRadio();
#if defined(Regulatory_Domain_EU_CE_2400)
transmittingRadio &= ChannelIsClear(transmittingRadio); // weed out the radio(s) if channel in use
#endif
if (config.GetForceTlmOff())
{
transmittingRadio = SX12XX_Radio_NONE;
}
Radio.TXnb((uint8_t*)&otaPkt, ExpressLRS_currAirRate_Modparams->PayloadLength, transmittingRadio);
return true;
}
int32_t ICACHE_RAM_ATTR HandleFreqCorr(bool value)
{
int32_t tempFC = FreqCorrection;
if (Radio.GetProcessingPacketRadio() == SX12XX_Radio_2)
{
tempFC = FreqCorrection_2;
}
if (value)
{
if (tempFC > FreqCorrectionMin)
{
tempFC--; // FREQ_STEP units
if (tempFC == FreqCorrectionMin)
{
DBGLN("Max -FreqCorrection reached!");
}
}
}
else
{
if (tempFC < FreqCorrectionMax)
{
tempFC++; // FREQ_STEP units
if (tempFC == FreqCorrectionMax)
{
DBGLN("Max +FreqCorrection reached!");
}
}
}
if (Radio.GetProcessingPacketRadio() == SX12XX_Radio_1)
{
FreqCorrection = tempFC;
}
else
{
FreqCorrection_2 = tempFC;
}
return tempFC;
}
void ICACHE_RAM_ATTR updatePhaseLock()
{
if (connectionState != disconnected && PFDloop.hasResult())
{
int32_t RawOffset = PFDloop.calcResult();
int32_t Offset = LPF_Offset.update(RawOffset);
int32_t OffsetDx = LPF_OffsetDx.update(RawOffset - PfdPrevRawOffset);
PfdPrevRawOffset = RawOffset;
if (RXtimerState == tim_locked)
{
// limit rate of freq offset adjustment, use slot 1
// because telemetry can fall on slot 1 and will
// never get here
if (OtaNonce % 8 == 1)
{
if (Offset > 0)
{
hwTimer::incFreqOffset();
}
else if (Offset < 0)
{
hwTimer::decFreqOffset();
}
}
}
if (connectionState != connected)
{
hwTimer::phaseShift(RawOffset >> 1);
}
else
{
hwTimer::phaseShift(Offset >> 2);
}
DBGVLN("%d:%d:%d:%d:%d", Offset, RawOffset, OffsetDx, hwTimer::FreqOffset, uplinkLQ);
UNUSED(OffsetDx); // complier warning if no debug
}
PFDloop.reset();
}
void ICACHE_RAM_ATTR HWtimerCallbackTick() // this is 180 out of phase with the other callback, occurs mid-packet reception
{
updatePhaseLock();
OtaNonce++;
// if (!alreadyTLMresp && !alreadyFHSS && !LQCalc.currentIsSet()) // packet timeout AND didn't DIDN'T just hop or send TLM
// {
// Radio.RXnb(); // put the radio cleanly back into RX in case of garbage data
// }
if (ExpressLRS_currAirRate_Modparams->numOfSends == 1)
{
// Save the LQ value before the inc() reduces it by 1
uplinkLQ = LQCalc.getLQ();
} else
if (!((OtaNonce - 1) % ExpressLRS_currAirRate_Modparams->numOfSends))
{
uplinkLQ = LQCalcDVDA.getLQ();
LQCalcDVDA.inc();
}
CRSF::LinkStatistics.uplink_Link_quality = uplinkLQ;
// Only advance the LQI period counter if we didn't send Telemetry this period
if (!alreadyTLMresp)
LQCalc.inc();
alreadyTLMresp = false;
alreadyFHSS = false;
}
//////////////////////////////////////////////////////////////
// flip to the other antenna
// no-op if GPIO_PIN_ANT_CTRL not defined
static inline void switchAntenna()
{
if (GPIO_PIN_ANT_CTRL != UNDEF_PIN && config.GetAntennaMode() == 2)
{
// 0 and 1 is use for gpio_antenna_select
// 2 is diversity
antenna = !antenna;
(antenna == 0) ? LPF_UplinkRSSI0.reset() : LPF_UplinkRSSI1.reset(); // discard the outdated value after switching
digitalWrite(GPIO_PIN_ANT_CTRL, antenna);
if (GPIO_PIN_ANT_CTRL_COMPL != UNDEF_PIN)
{
digitalWrite(GPIO_PIN_ANT_CTRL_COMPL, !antenna);
}
}
}
static void ICACHE_RAM_ATTR updateDiversity()
{
if (GPIO_PIN_ANT_CTRL != UNDEF_PIN)
{
if(config.GetAntennaMode() == 2)
{
// 0 and 1 is use for gpio_antenna_select
// 2 is diversity
static int32_t prevRSSI; // saved rssi so that we can compare if switching made things better or worse
static int32_t antennaLQDropTrigger;
static int32_t antennaRSSIDropTrigger;
int32_t rssi = (antenna == 0) ? LPF_UplinkRSSI0.value() : LPF_UplinkRSSI1.value();
int32_t otherRSSI = (antenna == 0) ? LPF_UplinkRSSI1.value() : LPF_UplinkRSSI0.value();
//if rssi dropped by the amount of DIVERSITY_ANTENNA_RSSI_TRIGGER
if ((rssi < (prevRSSI - DIVERSITY_ANTENNA_RSSI_TRIGGER)) && antennaRSSIDropTrigger >= DIVERSITY_ANTENNA_INTERVAL)
{
switchAntenna();
antennaLQDropTrigger = 1;
antennaRSSIDropTrigger = 0;
}
else if (rssi > prevRSSI || antennaRSSIDropTrigger < DIVERSITY_ANTENNA_INTERVAL)
{
prevRSSI = rssi;
antennaRSSIDropTrigger++;
}
// if we didn't get a packet switch the antenna
if (!LQCalc.currentIsSet() && antennaLQDropTrigger == 0)
{
switchAntenna();
antennaLQDropTrigger = 1;
antennaRSSIDropTrigger = 0;
}
else if (antennaLQDropTrigger >= DIVERSITY_ANTENNA_INTERVAL)
{
// We switched antenna on the previous packet, so we now have relatively fresh rssi info for both antennas.
// We can compare the rssi values and see if we made things better or worse when we switched
if (rssi < otherRSSI)
{
// things got worse when we switched, so change back.
switchAntenna();
antennaLQDropTrigger = 1;
antennaRSSIDropTrigger = 0;
}
else
{
// all good, we can stay on the current antenna. Clear the flag.
antennaLQDropTrigger = 0;
}
}
else if (antennaLQDropTrigger > 0)
{
antennaLQDropTrigger ++;
}
}
else
{
digitalWrite(GPIO_PIN_ANT_CTRL, config.GetAntennaMode());
if (GPIO_PIN_ANT_CTRL_COMPL != UNDEF_PIN)
{
digitalWrite(GPIO_PIN_ANT_CTRL_COMPL, !config.GetAntennaMode());
}
antenna = config.GetAntennaMode();
}
}
}
void ICACHE_RAM_ATTR HWtimerCallbackTock()
{
if (tlmSent && Radio.GetLastTransmitRadio() == SX12XX_Radio_NONE)
{
Radio.TXdoneCallback();
}
PFDloop.intEvent(micros()); // our internal osc just fired
if (ExpressLRS_currAirRate_Modparams->numOfSends > 1 && !(OtaNonce % ExpressLRS_currAirRate_Modparams->numOfSends) && LQCalcDVDA.currentIsSet())
{
crsfRCFrameAvailable();
servoNewChannelsAvailable();
}
if (!didFHSS)
{
HandleFHSS();
}
didFHSS = false;
Radio.isFirstRxIrq = true;
updateDiversity();
tlmSent = HandleSendTelemetryResponse();
#if defined(DEBUG_RX_SCOREBOARD)
static bool lastPacketWasTelemetry = false;
if (!LQCalc.currentIsSet() && !lastPacketWasTelemetry)
DBGW(lastPacketCrcError ? '.' : '_');
lastPacketCrcError = false;
lastPacketWasTelemetry = tlmSent;
#endif
}
void LostConnection(bool resumeRx)
{
DBGLN("lost conn fc=%d fo=%d", FreqCorrection, hwTimer::getFreqOffset());
// Use this rate as the initial rate next time if we connected on it
if (connectionState == connected)
config.SetRateInitialIdx(ExpressLRS_nextAirRateIndex);
RFmodeCycleMultiplier = 1;
connectionState = disconnected; //set lost connection
RXtimerState = tim_disconnected;
hwTimer::resetFreqOffset();
PfdPrevRawOffset = 0;
GotConnectionMillis = 0;
uplinkLQ = 0;
LQCalc.reset();
LQCalcDVDA.reset();
LPF_Offset.init(0);
LPF_OffsetDx.init(0);
alreadyTLMresp = false;
alreadyFHSS = false;
if (!InBindingMode)
{
if (hwTimer::running)
{
while(micros() - PFDloop.getIntEventTime() > 250); // time it just after the tock()
hwTimer::stop();
}
SetRFLinkRate(ExpressLRS_nextAirRateIndex); // also sets to initialFreq
// If not resumRx, Radio will be left in SX127x_OPMODE_STANDBY / SX1280_MODE_STDBY_XOSC
if (resumeRx)
{
Radio.RXnb();
}
}
}
void ICACHE_RAM_ATTR TentativeConnection(unsigned long now)
{
PFDloop.reset();
connectionState = tentative;
connectionHasModelMatch = false;
RXtimerState = tim_disconnected;
DBGLN("tentative conn");
PfdPrevRawOffset = 0;
LPF_Offset.init(0);
SnrMean.reset();
RFmodeLastCycled = now; // give another 3 sec for lock to occur
// The caller MUST call hwTimer::resume(). It is not done here because
// the timer ISR will fire immediately and preempt any other code
}
void GotConnection(unsigned long now)
{
if (connectionState == connected)
{
return; // Already connected
}
LockRFmode = firmwareOptions.lock_on_first_connection;
connectionState = connected; //we got a packet, therefore no lost connection
RXtimerState = tim_tentative;
GotConnectionMillis = now;
#if defined(PLATFORM_ESP32) || defined(PLATFORM_ESP8266)
webserverPreventAutoStart = true;
#endif
if (firmwareOptions.is_airport)
{
apInputBuffer.flush();
apOutputBuffer.flush();
}
DBGLN("got conn");
}
static void ICACHE_RAM_ATTR ProcessRfPacket_RC(OTA_Packet_s const * const otaPktPtr)
{
// Must be fully connected to process RC packets, prevents processing RC
// during sync, where packets can be received before connection
if (connectionState != connected || SwitchModePending)
return;
bool telemetryConfirmValue = OtaUnpackChannelData(otaPktPtr, ChannelData, ExpressLRS_currTlmDenom);
TelemetrySender.ConfirmCurrentPayload(telemetryConfirmValue);
// No channels packets to the FC or PWM pins if no model match
if (connectionHasModelMatch)
{
if (ExpressLRS_currAirRate_Modparams->numOfSends == 1)
{
crsfRCFrameAvailable();
servoNewChannelsAvailable();
}
else if (!LQCalcDVDA.currentIsSet())
{
LQCalcDVDA.add();
}
#if defined(DEBUG_RCVR_LINKSTATS)
debugRcvrLinkstatsPending = true;
#endif
}
}
static void ICACHE_RAM_ATTR ProcessRfPacket_MSP(OTA_Packet_s const * const otaPktPtr)
{
uint8_t packageIndex;
uint8_t const * payload;
uint8_t dataLen;
if (OtaIsFullRes)
{
packageIndex = otaPktPtr->full.msp_ul.packageIndex;
payload = otaPktPtr->full.msp_ul.payload;
dataLen = sizeof(otaPktPtr->full.msp_ul.payload);
}
else
{
packageIndex = otaPktPtr->std.msp_ul.packageIndex;
payload = otaPktPtr->std.msp_ul.payload;
dataLen = sizeof(otaPktPtr->std.msp_ul.payload);
}
// Always examine MSP packets for bind information if in bind mode
// [1] is the package index, first packet of the MSP
if (InBindingMode && packageIndex == 1 && payload[0] == MSP_ELRS_BIND)
{
OnELRSBindMSP((uint8_t *)&payload[1]);
return;
}
// Must be fully connected to process MSP, prevents processing MSP
// during sync, where packets can be received before connection
if (connectionState != connected)
return;
bool currentMspConfirmValue = MspReceiver.GetCurrentConfirm();
MspReceiver.ReceiveData(packageIndex, payload, dataLen);
if (currentMspConfirmValue != MspReceiver.GetCurrentConfirm())
{
NextTelemetryType = ELRS_TELEMETRY_TYPE_LINK;
}
}
static void ICACHE_RAM_ATTR updateSwitchModePendingFromOta(uint8_t newSwitchMode)
{
if (OtaSwitchModeCurrent == newSwitchMode)
{
// Cancel any switch if pending
SwitchModePending = 0;
return;
}
// One is added to the mode because SwitchModePending==0 means no switch pending
// and that's also a valid switch mode. The 1 is removed when this is handled.
// A negative SwitchModePending means not to switch yet
int8_t newSwitchModePending = -(int8_t)newSwitchMode - 1;
// Switch mode can be changed while disconnected
// OR there are two sync packets with the same new switch mode,
// as a "confirm". No RC packets are processed until
if (connectionState == disconnected ||
SwitchModePending == newSwitchModePending)
{
// Add one to the mode because SwitchModePending==0 means no switch pending
// and that's also a valid switch mode. The 1 is removed when this is handled
SwitchModePending = newSwitchMode + 1;
}
else
{
// Save the negative version of the new switch mode to compare
// against on the next SYNC packet, but do not switch yet
SwitchModePending = newSwitchModePending;
}
}
static bool ICACHE_RAM_ATTR ProcessRfPacket_SYNC(uint32_t const now, OTA_Sync_s const * const otaSync)
{
// Verify the first two of three bytes of the binding ID, which should always match
if (otaSync->UID3 != UID[3] || otaSync->UID4 != UID[4])
return false;
// The third byte will be XORed with inverse of the ModelId if ModelMatch is on
// Only require the first 18 bits of the UID to match to establish a connection
// but the last 6 bits must modelmatch before sending any data to the FC
if ((otaSync->UID5 & ~MODELMATCH_MASK) != (UID[5] & ~MODELMATCH_MASK))
return false;
LastSyncPacket = now;
#if defined(DEBUG_RX_SCOREBOARD)
DBGW('s');
#endif
// Will change the packet air rate in loop() if this changes
ExpressLRS_nextAirRateIndex = otaSync->rateIndex;
updateSwitchModePendingFromOta(otaSync->switchEncMode);
// Update TLM ratio, should never be TLM_RATIO_STD/DISARMED, the TX calculates the correct value for the RX
expresslrs_tlm_ratio_e TLMrateIn = (expresslrs_tlm_ratio_e)(otaSync->newTlmRatio + (uint8_t)TLM_RATIO_NO_TLM);
uint8_t TlmDenom = TLMratioEnumToValue(TLMrateIn);
if (ExpressLRS_currTlmDenom != TlmDenom)
{
DBGLN("New TLMrate 1:%u", TlmDenom);
ExpressLRS_currTlmDenom = TlmDenom;
telemBurstValid = false;
}
// modelId = 0xff indicates modelMatch is disabled, the XOR does nothing in that case
uint8_t modelXor = (~config.GetModelId()) & MODELMATCH_MASK;
bool modelMatched = otaSync->UID5 == (UID[5] ^ modelXor);
DBGVLN("MM %u=%u %d", otaSync->UID5, UID[5], modelMatched);
if (connectionState == disconnected
|| OtaNonce != otaSync->nonce
|| FHSSgetCurrIndex() != otaSync->fhssIndex
|| connectionHasModelMatch != modelMatched)
{
//DBGLN("\r\n%ux%ux%u", OtaNonce, otaPktPtr->sync.nonce, otaPktPtr->sync.fhssIndex);
FHSSsetCurrIndex(otaSync->fhssIndex);
OtaNonce = otaSync->nonce;
TentativeConnection(now);
// connectionHasModelMatch must come after TentativeConnection, which resets it
connectionHasModelMatch = modelMatched;
return true;
}
return false;
}
bool ICACHE_RAM_ATTR ProcessRFPacket(SX12xxDriverCommon::rx_status const status)
{
if (status != SX12xxDriverCommon::SX12XX_RX_OK)
{
DBGVLN("HW CRC error");
#if defined(DEBUG_RX_SCOREBOARD)
lastPacketCrcError = true;
#endif
return false;
}
uint32_t const beginProcessing = micros();