Device/event framework optimisation (#3049)
[ExpressLRS.git] / src / lib / Handset / AutoDetect.cpp
blob0249ed7798ee210a028bbbc23ffa08292621fd51
1 #include "targets.h"
3 #if defined(PLATFORM_ESP32) && defined(TARGET_TX)
5 #include "AutoDetect.h"
6 #include "CRSFHandset.h"
7 #include "PPMHandset.h"
8 #include "logging.h"
10 #include <driver/rmt.h>
12 constexpr auto RMT_TICKS_PER_US = 4;
14 void AutoDetect::Begin()
16 constexpr auto divisor = 80 / RMT_TICKS_PER_US;
18 rmt_config_t rmt_rx_config = RMT_DEFAULT_CONFIG_RX(static_cast<gpio_num_t>(GPIO_PIN_RCSIGNAL_RX), PPM_RMT_CHANNEL);
19 rmt_rx_config.clk_div = divisor;
20 rmt_rx_config.rx_config.filter_ticks_thresh = 1;
21 rmt_rx_config.rx_config.idle_threshold = 100;
22 rmt_config(&rmt_rx_config);
23 rmt_driver_install(PPM_RMT_CHANNEL, 1000, 0);
25 rmt_get_ringbuf_handle(PPM_RMT_CHANNEL, &rb);
26 rmt_rx_start(PPM_RMT_CHANNEL, true);
27 input_detect = 0;
30 void AutoDetect::End()
32 rmt_driver_uninstall(PPM_RMT_CHANNEL);
35 bool AutoDetect::IsArmed()
37 return false;
40 void AutoDetect::migrateTo(Handset *that) const
42 that->setRCDataCallback(RCdataCallback);
43 that->registerParameterUpdateCallback(RecvParameterUpdate);
44 that->registerCallbacks(connected, disconnected, RecvModelUpdate, OnBindingCommand);
45 that->Begin();
46 that->setPacketInterval(RequestedRCpacketInterval);
47 delete this;
48 handset = that;
51 void AutoDetect::startPPM() const
53 migrateTo(new PPMHandset());
56 void AutoDetect::startCRSF() const
58 migrateTo(new CRSFHandset());
61 void AutoDetect::handleInput()
63 size_t length = 0;
64 const auto now = millis();
66 const auto items = static_cast<rmt_item32_t *>(xRingbufferReceive(rb, &length, 0));
67 if (items)
69 vRingbufferReturnItem(rb, static_cast<void *>(items));
70 lastDetect = now;
71 length /= 4; // one RMT = 4 Bytes
72 if (length == 0)
74 input_detect++;
75 if (input_detect > 100)
77 DBGLN("PPM signal detected");
78 rmt_driver_uninstall(PPM_RMT_CHANNEL);
79 startPPM();
82 else
84 input_detect--;
85 if (input_detect < -100)
87 DBGLN("Serial signal detected");
88 rmt_driver_uninstall(PPM_RMT_CHANNEL);
89 startCRSF();
93 else
95 if (now - 1000 > lastDetect && input_detect != 0)
97 DBGLN("No signal detected");
98 input_detect = 0;
103 #endif