Files
bletest/include/ble_core.h
DESKTOP-PUHFO60\dsx2016 8baea73c0c Add CYD BLE foundation with NimBLE Nordic UART.
Reusable ble_core (+ optional LVGL ble_ui), flashable firmware/cyd, aligned with wifitest as a base feature.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-23 15:43:11 +08:00

85 lines
2.4 KiB
C
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#pragma once
/**
* 通用 BLE 外设核心(无 LVGL 依赖)
*
* 栈:NimBLE(比 Bluedroid 省 RAM/Flash,后续可与 WiFi 共存)
* 服务:Nordic UART Service(NUS)— 手机端 nRF Connect / Serial Bluetooth
* Terminal / LightBlue 等主流 App 开箱即用
*
* 流程:
* 1. ble_core_begin() 初始化 NimBLE + NUS,默认开始广播
* 2. 手机连上后写 RX 特征 → 回调 / 收包队列
* 3. ble_core_send() 经 TX 特征 Notify 发回手机
* 4. loop 里 ble_core_loop() 处理断线后自动重广播
*/
#include <Arduino.h>
#ifndef BLE_CORE_DEVICE_NAME
#define BLE_CORE_DEVICE_NAME "CYD-BLE"
#endif
#ifndef BLE_CORE_RX_QUEUE
#define BLE_CORE_RX_QUEUE 8
#endif
#ifndef BLE_CORE_RX_MAX
#define BLE_CORE_RX_MAX 128
#endif
/** Nordic UART Service(业界事实标准) */
#define BLE_NUS_SERVICE_UUID "6E400001-B5A3-F393-E0A9-E50E24DCCA9E"
#define BLE_NUS_RX_UUID "6E400002-B5A3-F393-E0A9-E50E24DCCA9E"
#define BLE_NUS_TX_UUID "6E400003-B5A3-F393-E0A9-E50E24DCCA9E"
enum BleCoreState : uint8_t {
BLE_CORE_IDLE = 0,
BLE_CORE_ADVERTISING,
BLE_CORE_CONNECTED,
};
struct BleRxPacket {
char data[BLE_CORE_RX_MAX + 1];
uint16_t len;
};
using BleCoreStateCb = void (*)(BleCoreState state, void *user);
using BleCoreRxCb = void (*)(const uint8_t *data, size_t len, void *user);
void ble_core_set_state_cb(BleCoreStateCb cb, void *user = nullptr);
void ble_core_set_rx_cb(BleCoreRxCb cb, void *user = nullptr);
/** 初始化栈 + NUS;默认开始广播。返回是否成功。 */
bool ble_core_begin(const char *device_name = BLE_CORE_DEVICE_NAME);
void ble_core_end();
BleCoreState ble_core_state();
bool ble_core_is_connected();
bool ble_core_is_advertising();
const char *ble_core_name();
String ble_core_address();
String ble_core_peer_address();
void ble_core_advertise_start();
void ble_core_advertise_stop();
/** 经 NUS TX Notify 发送;未连接返回 false */
bool ble_core_send(const uint8_t *data, size_t len);
bool ble_core_send_str(const char *text);
/** 演示用:收到数据自动 echo 回去(默认开) */
void ble_core_set_echo(bool on);
bool ble_core_echo();
/**
* 非回调路径取收包(UI 轮询友好)。有包返回 true 并填 out。
* 与 ble_core_set_rx_cb 可同时用。
*/
bool ble_core_poll_rx(BleRxPacket *out);
/** 每 loop 调用:断线后自动重广播 */
void ble_core_loop();