RX serial refactor (user selectable CRSF/SBUS serial protocol) (#2094)
[ExpressLRS.git] / src / lib / BLE / devBLE.cpp
blobf0fc6d9c1c1391de86c6e02fbc7ba7ff55edff26
1 #include "devBLE.h"
3 #if defined(PLATFORM_ESP32)
5 #include "common.h"
6 #include "CRSF.h"
7 #include "POWERMGNT.h"
8 #include "hwTimer.h"
9 #include "logging.h"
11 #include <BleGamepad.h>
12 #include <NimBLEDevice.h>
14 class ELRSGamepad : public BleGamepad {
15 public:
16 ELRSGamepad() : BleGamepad("ExpressLRS Joystick", "ELRS", 100) {};
18 protected:
19 void onStarted(NimBLEServer *pServer) {
20 NimBLEDevice::setPower(ESP_PWR_LVL_P9);
24 static ELRSGamepad *bleGamepad;
26 void BluetoothJoystickUpdateValues()
28 if (bleGamepad->isConnected())
30 // map first 8 channels to axis
31 int16_t data[8];
32 for (uint8_t i = 0; i < 8; i++)
34 data[i] = map(ChannelData[i], CRSF_CHANNEL_VALUE_MIN, CRSF_CHANNEL_VALUE_MAX, 0, 32767);
36 bleGamepad->setAxes(data[0], data[1], data[4], data[5], data[2], data[3], data[6], data[7]);
38 // map other 8 channels to buttons
39 for (uint8_t i = 8; i < 16; i++)
41 if (ChannelData[i] >= CRSF_CHANNEL_VALUE_2000) {
42 bleGamepad->press(i - 7);
43 } else {
44 bleGamepad->release(i - 7);
48 // send BLE report
49 bleGamepad->sendReport();
53 void BluetoothJoystickBegin()
55 // bleGamepad is null if it hasn't been started yet
56 if (bleGamepad != nullptr)
57 return;
59 // construct the BLE immediately to prevent reentry from events/timeout
60 bleGamepad = new ELRSGamepad();
62 POWERMGNT::setPower(MinPower);
63 Radio.End();
64 CRSF::RCdataCallback = BluetoothJoystickUpdateValues;
66 BleGamepadConfiguration *gamepadConfig = new BleGamepadConfiguration();
67 gamepadConfig->setAutoReport(false);
69 DBGLN("Starting BLE Joystick!");
70 bleGamepad->begin(gamepadConfig);
73 static int timeout()
75 BluetoothJoystickBegin();
76 return DURATION_NEVER;
79 static int event()
81 if (connectionState == bleJoystick) {
82 hwTimer::stop();
83 return 200;
85 return DURATION_NEVER;
88 device_t BLE_device = {
89 .initialize = NULL,
90 .start = NULL,
91 .event = event,
92 .timeout = timeout
95 #endif