CodexPad Arduino Lib 5.0.0
Loading...
Searching...
No Matches
client.h
1#pragma once
2
3#include <functional>
4#include <mutex>
5#include <optional>
6#include <queue>
7#include <string>
8#include <vector>
9
10#include "NimBLEDevice.h"
11#include "cyf.h"
12#include "cyf/hysteresis_quantizer.h"
13#include "gamepad_input_tracker.h"
14
15namespace codex_pad {
16
17/**
18 * @~English
19 * @class Client
20 * @brief Client main class
21 */
22/**
23 * @~Chinese
24 * @class Client
25 * @brief Client主类
26 */
27class Client : public NimBLEClientCallbacks {
28 public:
29 /**
30 * @~English
31 * @brief Constructor
32 */
33 /**
34 * @~Chinese
35 * @brief 构造函数
36 */
37 Client() noexcept;
38
39 /**
40 * @~English
41 * @brief Destructor
42 */
43 /**
44 * @~Chinese
45 * @brief 析构函数
46 */
47 ~Client() noexcept;
48
49 /**
50 * @~English
51 * @brief Initialize
52 */
53 /**
54 * @~Chinese
55 * @brief 初始化
56 */
57 void Init() noexcept;
58
59 /**
60 * @~English
61 * @brief Connect
62 * @param[in] address The Bluetooth device address(BD_ADDR) of the CodexPad, formatted as
63 * "XX:XX:XX:XX:XX:XX", X is a number or uppercase letter, colon separated
64 * @param[in] timeout_ms Timeout in milliseconds
65 * @retval true if connected successfully
66 * @retval false if connection failed
67 * */
68 /**
69 * @~Chinese
70 * @brief 连接
71 * @param[in] address CodexPad的蓝牙设备地址,格式为"XX:XX:XX:XX:XX:XX",X为数字或者大写字母,
72 * 半角冒号分隔
73 * @param[in] timeout_ms 超时时间,单位毫秒
74 * @retval true 连接成功
75 * @retval false 连接失败
76 */
77 bool Connect(const std::string& address, uint32_t timeout_ms = 5000) noexcept;
78
79 /**
80 * @~English
81 * @brief Scans for nearby CodexPad devices and automatically connects to a device whose button state matches the specified
82 * mask.
83 * @details This method actively scans for Bluetooth devices. When it discovers one or more CodexPad devices whose current
84 * button states exactly match the provided `button_mask`, it will attempt to establish a connection. If multiple nearby
85 * devices match the button mask, the device with the strongest signal (highest RSSI) will be selected for connection.
86 * @param[in] button_mask A 32-bit button mask used to match the target device's button states.
87 * Use the `ButtonMask()` function to combine multiple @ref Button values.
88 * @retval true Connection successful (a device matching the button mask was found and connected).
89 * @retval false Connection failed (no matching device found or connection attempt failed).
90 * @note This is a blocking call. It will continuously scan until a matching device is found, a connection is established, or
91 * the internal timeout is reached.
92 * @warning **DO NOT** include `Button::kHome` in the button mask. Holding the Home button triggers a device reboot, which
93 * will interrupt the connection process. Example:
94 * @code
95 * codex_pad::Client g_codex_pad_client;
96 * g_codex_pad_client.Init();
97 * // Continuously try to connect to a device where the Start and Cross/A buttons are pressed.
98 * while (!g_codex_pad_client.ScanAndConnect(gamepad::input::Button::kStart | gamepad::input::Button::kStart)) {
99 * // Optional: Add a small delay or other operations between attempts.
100 * delay(100);
101 * }
102 * // Once the loop exits, connection is successful.
103 * Serial.println("CodexPad connected!");
104 * @endcode
105 */
106 /**
107 * @~Chinese
108 * @brief 扫描附近的 CodexPad 设备,并自动连接到一个按键状态与指定掩码匹配的设备。
109 * @details 此方法会主动扫描蓝牙设备。当发现一个或多个 CodexPad 设备,其当前按键状态与提供的 `button_mask`
110 * 完全匹配时,它将尝试建立连接。 如果附近有多个设备都符合按键掩码,则会选择信号最强(RSSI 值最大)的设备进行连接。
111 * @param[in] button_mask 用于匹配目标设备按键状态的32位按钮掩码。
112 * 使用 `ButtonMask()` 函数来组合多个 @ref Button 枚举值。
113 * @retval true 连接成功(找到了符合按键掩码的设备并成功连接)。
114 * @retval false 连接失败(未找到匹配设备或连接尝试失败)。
115 * @note 这是一个阻塞式调用。它会持续扫描,直到找到匹配的设备、连接建立或达到内部超时时间。
116 * @warning **请勿**在按钮掩码中包含 `Button::kHome`。按住 Home 键会触发设备重启,这将中断连接过程。
117 * 示例:
118 * @code
119 * codex_pad::Client g_codex_pad_client;
120 * g_codex_pad_client.Init();
121 * // 持续尝试连接到 Start 和 Cross/A 按键被同时按下的设备。
122 * while (!g_codex_pad_client.ScanAndConnect(gamepad::input::Button::kStart | gamepad::input::Button::kStart)) {
123 * // 可选:在尝试之间添加短暂延时或其他操作。
124 * delay(100);
125 * }
126 * // 循环退出,意味着连接成功。
127 * Serial.println("CodexPad 连接成功!");
128 * @endcode
129 */
130 bool Connect(gamepad::input::Button buttons) noexcept;
131
132 /**
133 * @~English
134 * @brief Disconnect
135 */
136 /**
137 * @~Chinese
138 * @brief 断开连接
139 */
140 void Disconnect() noexcept { Reset(); }
141
142 /**
143 * @~English
144 * @brief Update, need to be called in Loop
145 */
146 /**
147 * @~Chinese
148 * @brief 更新,需要在Loop中不断调用
149 */
150 const gamepad::input::Tracker& Update() noexcept;
151
152 /**
153 * @~English
154 * @brief Is connected
155 * @retval true if connected
156 * @retval false if not
157 */
158 /**
159 * @~Chinese
160 * @brief 是否连接
161 * @retval true 已连接
162 * @retval false 未连接
163 */
164 bool is_connected() const noexcept;
165
166 /**
167 * @~English
168 * @brief Get model number of the CodexPad
169 * @return Model number of the CodexPad
170 */
171 /**
172 * @~Chinese
173 * @brief 获取CodexPad的型号
174 * @return CodexPad的型号
175 */
176 const std::string& remote_device_name() const noexcept { return remote_device_name_; }
177
178 /**
179 * @~English
180 * @brief Get model number of the CodexPad
181 * @return Model number of the CodexPad
182 */
183 /**
184 * @~Chinese
185 * @brief 获取CodexPad的型号
186 * @return CodexPad的型号
187 */
188 const std::string& remote_model_number() const noexcept { return remote_model_number_; }
189
190 /**
191 * @~English
192 * @brief Get firmware version of the CodexPad
193 * @return Firmware version of the CodexPad
194 */
195 /**
196 * @~Chinese
197 * @brief 获取CodexPad的固件版本
198 * @return CodexPad的固件版本
199 */
200 const std::array<uint8_t, 3>& remote_firmware_version() const noexcept { return remote_firmware_version_; }
201
202 /**
203 * @~English
204 * @brief Get the input tracker object
205 * @details This function returns a reference to the internal input tracker object.
206 * @return Input tracker object
207 */
208 /**
209 * @~Chinese
210 * @brief 获取输入跟踪器对象
211 * @details 此函数返回内部输入跟踪器对象的引用。
212 * @return 输入跟踪器对象
213 */
214 const gamepad::input::Tracker& input_tracker() const noexcept { return input_tracker_; }
215
216 /**
217 * @~English
218 * @brief Get the RSSI of the connected CodexPad.
219 * @details This function retrieves the current Received Signal Strength Indication (RSSI) from the
220 * underlying NimBLE client.
221 * **Note:** On ESP32 Arduino Core versions older than 3.1.0, RSSI readings suffer from severe
222 * fluctuation (drift) and are highly unreliable. Relying on this return value for logic or
223 * display purposes in those older versions is **not recommended**. For accurate RSSI measurements,
224 * please upgrade to ESP32 Arduino Core 3.1.0 or later.
225 * @return The current RSSI value in dBm. Returns 0 if the BLE client is not initialized or not connected.
226 */
227 /**
228 * @~Chinese
229 * @brief 获取已连接 CodexPad 的 RSSI(接收信号强度指示)。
230 * @details 该函数从底层 NimBLE 客户端获取当前的接收信号强度指示(RSSI)值。
231 * **注意:** 在低于 3.1.0 的 ESP32 Arduino Core 版本中,RSSI 读数存在严重漂移(不准确)。
232 * 不推荐在旧版本中依赖此返回值进行逻辑判断或界面显示。如需准确的 RSSI 测量,
233 * 请将 ESP32 Arduino Core 升级至 3.1.0 或更高版本。
234 * @return 当前 RSSI 值,单位为 dBm。如果 BLE 客户端未初始化或未连接,则返回 0。
235 */
236 int32_t rssi() const noexcept;
237
238 /**
239 * @~English
240 * @brief Set the local BLE TX power (manual mode).
241 * @details This function stores the desired TX power level. However, **if dynamic TX power adjustment is enabled**
242 * (which is the default, see @ref set_dynamic_tx_power_enabled), this value will be ignored and overwritten
243 * by the dynamic adjustment logic during @ref Update().
244 * To ensure this manual setting takes effect persistently, you must first call
245 * `set_dynamic_tx_power_enabled(false)`. On ESP32 Arduino Core versions older than 3.1.0, where dynamic
246 * adjustment is internally disabled due to RSSI drift, this setting will apply normally.
247 * @param tx_power Local BLE TX power in dBm.
248 */
249 /**
250 * @~Chinese
251 * @brief 设置本地 BLE 发射功率(手动模式)。
252 * @details 该函数用于保存期望的发射功率值。但是,**如果动态发射功率调节处于开启状态**(默认开启,
253 * 参见 @ref set_dynamic_tx_power_enabled),该值将被忽略,并在 @ref Update() 中被动态调节逻辑覆盖。
254 * 如需使该手动设置持续生效,必须先调用 `set_dynamic_tx_power_enabled(false)` 关闭动态调节功能。
255 * 在低于 3.1.0 的 ESP32 Arduino Core 版本中,由于内部因 RSSI 漂移已禁用动态调节,此设置可正常生效。
256 * @param tx_power 本地 BLE 发射功率,单位 dBm。
257 */
258 void set_local_tx_power(int32_t tx_power) noexcept { local_tx_power_ = tx_power; }
259
260 /**
261 * @~English
262 * @brief Get the manually configured local BLE TX power value.
263 * @details This function returns the value previously stored by @ref set_local_tx_power() (or its default).
264 * **Note:** When dynamic TX power adjustment is enabled (which is the default, see
265 * @ref set_dynamic_tx_power_enabled), the actual TX power is controlled automatically by the
266 * RSSI-based hysteresis quantizer. In that case, the value returned by this function **does not
267 * reflect the real-time TX power** being used; it only reflects the stored manual setting.
268 * @return The stored local BLE TX power setting in dBm.
269 */
270 /**
271 * @~Chinese
272 * @brief 获取用户设定的本地 BLE 发射功率值。
273 * @details 该函数返回之前通过 @ref set_local_tx_power() 保存的值(或其默认值)。
274 * **注意:** 当动态发射功率调节处于开启状态(默认开启,参见 @ref set_dynamic_tx_power_enabled)
275 * 时,实际发射功率由基于 RSSI 的滞环量化器自动控制。此时,该函数返回的值**不能代表当前实时
276 * 使用的发射功率**,它仅代表内部存储的手动设定值。
277 * @return 存储的本地 BLE 发射功率设定值,单位 dBm。
278 */
279 int32_t local_tx_power() const noexcept { return local_tx_power_; }
280
281 /**
282 * @~English
283 * @brief Enable or disable dynamic TX power adjustment based on RSSI.
284 * @details This feature is **enabled by default** and **highly recommended** to keep enabled.
285 * When enabled, the client periodically reads the peer's RSSI during @ref Update() and adjusts
286 * the local BLE transmit power using a hysteresis quantizer:
287 * - Strong signal (high RSSI) → Lower TX power to save energy and reduce interference.
288 * - Weak signal (low RSSI) → Higher TX power to maintain connection stability.
289 * **Conflict with manual power:** When dynamic adjustment is enabled, any value set via
290 * @ref set_local_tx_power() will be **overwritten** and not take effect. To use a fixed manual
291 * TX power, you must first disable this feature by calling `set_dynamic_tx_power_enabled(false)`.
292 * @note On ESP32, this feature relies on @ref NimBLEClient::getRssi(). Due to severe RSSI fluctuation (drift)
293 * in ESP32 Arduino Core versions **older than 3.1.0**, the actual adjustment is only compiled and
294 * executed when `ESP_ARDUINO_VERSION >= ESP_ARDUINO_VERSION_VAL(3, 1, 0)`. In earlier versions,
295 * the logic is disabled via preprocessor macros, allowing @ref set_local_tx_power() to work as a fallback.
296 * @param enabled true to enable (recommended), false to disable and switch to manual control.
297 */
298 /**
299 * @~Chinese
300 * @brief 使能或禁用以 RSSI 为基础的动态发射功率调节。
301 * @details 该功能**默认开启**,且**强烈建议保持开启**。启用后,客户端会在 @ref Update() 中周期性读取对端设备的
302 * RSSI,并通过滞环量化器(Hysteresis Quantizer)动态调整本地 BLE 发射功率:
303 * - 信号较好(RSSI 较高)时,降低发射功率以节省能耗并减少无线干扰;
304 * - 信号较差(RSSI 较低)时,提高发射功率以维持连接稳定性。
305 * **与手动功率的冲突:** 当动态调节开启时,通过 @ref set_local_tx_power() 设置的任何功率值都会被
306 * **覆盖**,无法生效。如果需要使用固定的手动发射功率,必须先调用
307 * `set_dynamic_tx_power_enabled(false)` 关闭此功能。
308 * @note 在 ESP32 平台上,该功能依赖 @ref NimBLEClient::getRssi()。由于在 **3.1.0 之前**的 ESP32 Arduino Core
309 * 版本中 RSSI 读数存在严重漂移(不准确),实际调节逻辑仅在 `ESP_ARDUINO_VERSION >= ESP_ARDUINO_VERSION_VAL(3, 1, 0)`
310 * 时才会编译和执行。在更早的版本中,内部已通过预处理器宏禁用动态调节,此时 @ref set_local_tx_power()
311 * 可以正常生效作为回退方案。
312 * @param enabled true 表示开启(推荐),false 表示关闭并切换为手动控制模式。
313 */
314 void set_dynamic_tx_power_enabled(bool enabled) noexcept { dynamic_tx_power_enabled_ = enabled; }
315 /**
316 * @~English
317 * @brief Get the BLE client object
318 * @details This function returns a pointer to the internal BLE client object. The caller should not try and release/delete
319 * it.
320 * @return BLE client object
321 */
322 /**
323 * @~Chinese
324 * @brief 获取 BLE 客户端对象
325 * @details 此函数返回内部 BLE 客户端对象的指针。调用者不应尝试释放/删除它。
326 * @return BLE 客户端对象
327 */
328 NimBLEClient* ble_client() const noexcept { return ble_client_; }
329
330 private:
331 static constexpr size_t kInputsQueueMax = 10;
332 bool onConnParamsUpdateRequest(NimBLEClient*, const ble_gap_upd_params*) override {
333 return false; // update our own connection parameters, so we reject the request
334 }
335
336 void onPhyUpdate(NimBLEClient*, uint8_t tx_phy, uint8_t rx_phy) override;
337 bool Connect(const NimBLEAddress& address, bool async_connect, const uint32_t timeout_ms);
338 void OnNotify(const NimBLERemoteCharacteristic* remote_characteristic, const uint8_t* data, const size_t length,
339 const bool is_notify);
340 void Reset();
341 void UpdateTxPower();
342
343 mutable std::mutex mutex_;
344 NimBLEClient* ble_client_{nullptr};
345 std::string remote_device_name_;
346 std::string remote_model_number_;
347 std::array<uint8_t, 3> remote_firmware_version_{0, 0, 0};
348 std::queue<gamepad::input::State> inputs_queue_;
349 gamepad::input::Tracker input_tracker_;
350 cyf::HysteresisQuantizer<int32_t> rssi_quantizer_;
351 uint64_t last_update_tx_power_ms_{0};
352 bool dynamic_tx_power_enabled_ = true;
353 int32_t local_tx_power_{0};
354};
355} // namespace codex_pad
Client() noexcept
Constructor.
Definition client.cpp:46
const gamepad::input::Tracker & Update() noexcept
Update, need to be called in Loop.
Definition client.cpp:127
const std::string & remote_device_name() const noexcept
Get model number of the CodexPad.
Definition client.h:176
void set_local_tx_power(int32_t tx_power) noexcept
Set the local BLE TX power (manual mode).
Definition client.h:258
const std::array< uint8_t, 3 > & remote_firmware_version() const noexcept
Get firmware version of the CodexPad.
Definition client.h:200
bool is_connected() const noexcept
Is connected.
Definition client.cpp:158
void set_dynamic_tx_power_enabled(bool enabled) noexcept
Enable or disable dynamic TX power adjustment based on RSSI.
Definition client.h:314
NimBLEClient * ble_client() const noexcept
Get the BLE client object.
Definition client.h:328
void Init() noexcept
Initialize.
Definition client.cpp:51
void Disconnect() noexcept
Disconnect.
Definition client.h:140
const std::string & remote_model_number() const noexcept
Get model number of the CodexPad.
Definition client.h:188
const gamepad::input::Tracker & input_tracker() const noexcept
Get the input tracker object.
Definition client.h:214
int32_t rssi() const noexcept
Get the RSSI of the connected CodexPad.
Definition client.cpp:275
~Client() noexcept
Destructor.
Definition client.cpp:49
int32_t local_tx_power() const noexcept
Get the manually configured local BLE TX power value.
Definition client.h:279
bool Connect(const std::string &address, uint32_t timeout_ms=5000) noexcept
Connect.
Definition client.cpp:57