bolar_1 date 2026-7-1 d:/proc

This commit is contained in:
2026-11-27 17:44:38 +08:00
commit 0dbdfa57bc
890 changed files with 325428 additions and 0 deletions

586
main/ble/friend_exchange.cc Normal file
View File

@@ -0,0 +1,586 @@
/**
* BLE Friend Exchange — alternating advertise/scan for "BorlaF-*" devices.
*
* NimBLE cannot advertise and scan simultaneously (non-extended).
* Solution: use timed adv (2s) → on completion callback → timed scan (2s) → loop.
* NimBLE cleans up internally when duration expires, avoiding EBUSY race.
*/
#include "friend_exchange.h"
#include "system_info.h"
#include <esp_log.h>
#include <esp_timer.h>
#include <freertos/FreeRTOS.h>
#include <freertos/task.h>
#include <nimble/nimble_port.h>
#include <nimble/nimble_port_freertos.h>
#include <host/ble_hs.h>
#include <host/ble_gap.h>
#include <host/util/util.h>
#include <services/gap/ble_svc_gap.h>
// NimBLE os.h defines min/max macros that conflict with C++ <limits>
#undef min
#undef max
#include <atomic>
#include <map>
#include <mutex>
#include <string>
#include <cstring>
#include <algorithm>
#define TAG "FriendExch"
static constexpr int FRIEND_MODE_TIMEOUT_S = 30;
static constexpr int SCAN_LOG_INTERVAL_MS = 1000;
// Duration for each phase in milliseconds
static constexpr int ADV_DURATION_MS = 2000; // Advertise for 2 seconds
static constexpr int SCAN_DURATION_MS = 2000; // Scan for 2 seconds
static constexpr int MATCH_ADV_GRACE_MS = 4000;
static constexpr int MATCH_STOP_FALLBACK_MS = 9000;
static constexpr int FRIEND_STRONG_RSSI_THRESHOLD = -60;
static constexpr int FRIEND_WEAK_RSSI_THRESHOLD = -85;
static constexpr int FRIEND_WEAK_MIN_SEEN = 2;
static constexpr const char* FRIEND_PREFIX = "BorlaF-";
// --- State ---
static std::atomic<bool> s_active{false};
static std::atomic<bool> s_nimble_ready{false};
static std::atomic<bool> s_nimble_task_started{false};
static std::atomic<bool> s_is_advertising{false};
static std::atomic<bool> s_match_reported{false};
static std::atomic<bool> s_match_grace_requested{false};
static std::atomic<bool> s_match_grace_advertising{false};
struct DiscoveredDevice {
std::string name;
int rssi = -127;
int best_rssi = -127;
int seen_count = 0;
int64_t last_seen_ms = 0;
ble_addr_t addr = {};
};
static std::mutex s_devices_mutex;
static std::map<std::string, DiscoveredDevice> s_discovered;
static FriendInfo s_local_info;
static FriendExchangeCallback s_on_complete;
static FriendExchangeOnStopped s_on_stopped;
static std::atomic<bool> s_paired{false}; // 区分 timeout vs successful exit
static esp_timer_handle_t s_timeout_timer = nullptr;
static esp_timer_handle_t s_log_timer = nullptr;
static esp_timer_handle_t s_sync_watchdog_timer = nullptr;
static esp_timer_handle_t s_release_timer = nullptr;
static esp_timer_handle_t s_match_stop_timer = nullptr;
static bool s_adv_fields_set = false;
static constexpr int NIMBLE_SYNC_TIMEOUT_MS = 5000; // 5s 没 sync 就直接 stop friend mode(不重试)
static constexpr int NIMBLE_RELEASE_DELAY_MS = 200; // GAP stop 稍等 200ms 后释放 BLE,再恢复 WS
// Forward declarations
static void StartAdvertisePhase(int duration_ms = ADV_DURATION_MS);
static void StartScanPhase();
static int OnGapEvent(struct ble_gap_event* event, void* arg);
static std::string AddrToString(const ble_addr_t& addr);
// --- NimBLE host ---
static void NimbleHostTask(void* arg)
{
ESP_LOGI(TAG, "NimBLE host task started");
nimble_port_run();
nimble_port_freertos_deinit();
}
static void OnNimbleSync()
{
s_nimble_ready.store(true);
ESP_LOGI(TAG, "NimBLE synced, starting scan phase");
// Sync 来了,watchdog 不再需要触发
if (s_sync_watchdog_timer) esp_timer_stop(s_sync_watchdog_timer);
if (s_active.load()) {
// Start with scan to find already-advertising peers
StartScanPhase();
}
}
// Sync watchdog: 5s 内 sync_cb 没回调就强制重启 NimBLE。
// 解决 ble_prov 配网过后 NimBLE 残留导致的"task spawn 了但 controller 不发 sync"症状。
static void OnNimbleSyncWatchdog(void* arg);
static void OnMatchStopFallback(void* arg);
static void NotifyStopped()
{
if (s_on_stopped) {
auto cb = s_on_stopped;
s_on_stopped = nullptr;
cb(s_paired.load());
}
}
static bool StartNimbleStack()
{
ESP_LOGI(TAG, "nimble_port_init() begin");
esp_err_t ret = nimble_port_init();
ESP_LOGI(TAG, "nimble_port_init() returned 0x%x (%s)",
ret, ret == ESP_OK ? "OK" : esp_err_to_name(ret));
if (ret != ESP_OK) {
ESP_LOGE(TAG, "NimBLE port init failed: 0x%x", ret);
s_nimble_task_started.store(false);
return false;
}
ble_hs_cfg.sync_cb = OnNimbleSync;
ESP_LOGI(TAG, "Spawning NimBLE host task via nimble_port_freertos_init");
nimble_port_freertos_init(NimbleHostTask);
// Set after spawn so a failure to spawn doesn't poison the flag.
s_nimble_task_started.store(true);
ESP_LOGI(TAG, "nimble_port_freertos_init returned (task should now be scheduled)");
// Arm sync watchdog: if controller never delivers sync within 5s, full reset.
if (!s_sync_watchdog_timer) {
esp_timer_create_args_t args = {
.callback = OnNimbleSyncWatchdog, .arg = nullptr,
.dispatch_method = ESP_TIMER_TASK, .name = "friend_sync_wd",
.skip_unhandled_events = true,
};
esp_timer_create(&args, &s_sync_watchdog_timer);
}
esp_timer_stop(s_sync_watchdog_timer);
esp_timer_start_once(s_sync_watchdog_timer,
(uint64_t)NIMBLE_SYNC_TIMEOUT_MS * 1000);
return true;
}
static void HardResetNimble(const char* reason)
{
ESP_LOGW(TAG, "Hard-resetting NimBLE: %s", reason ? reason : "");
// These no-op safely if not running.
if (s_nimble_task_started.load() || s_nimble_ready.load()) {
ble_gap_disc_cancel();
ble_gap_adv_stop();
}
nimble_port_stop();
nimble_port_deinit();
s_nimble_task_started.store(false);
s_nimble_ready.store(false);
s_adv_fields_set = false;
}
static void EnsureNimbleStarted()
{
// 如果刚退出 friend mode 但 release_timer 还没执行,用户又立刻重试,
// 复用已同步的 NimBLE host,避免一边释放一边重新初始化。
if (s_release_timer) esp_timer_stop(s_release_timer);
if (s_nimble_task_started.load() && s_nimble_ready.load()) {
// 健康复用 — 直接进 scan
ESP_LOGI(TAG, "NimBLE already running, reusing for new friend mode session");
StartScanPhase();
return;
}
if (s_nimble_task_started.load() && !s_nimble_ready.load()) {
// 上次 init 卡住了(sync_cb 一直没来),用户主动重试 → 强制清理重来。
// 这种场景才 deinit;正常 stop 路径不动 NimBLE。
ESP_LOGW(TAG, "NimBLE stuck (init OK but no sync) — hard reset before re-init");
HardResetNimble("user retry after stuck state");
}
if (!StartNimbleStack()) {
FriendExchange::StopFriendMode();
}
}
static void OnNimbleSyncWatchdog(void* arg)
{
if (!s_active.load()) return;
if (s_nimble_ready.load()) return; // sync 来过了,watchdog 不需要做事
// sync_cb 没回调 → controller 起不来 / coex 卡死。直接结束 friend mode
// 让用户重试(不再原地 hard-reset 重试 — 每次 reinit 都新占 4-6 个 task
// slot,累积起来 web_socket.cc:387 std::thread create 会 abort)。
// StopFriendMode 会调 on_stopped(false) 让 button_config 恢复 WS。
ESP_LOGW(TAG, "NimBLE sync_cb never fired within %dms — exiting friend mode (user retry)",
NIMBLE_SYNC_TIMEOUT_MS);
FriendExchange::StopFriendMode();
}
static void OnMatchStopFallback(void* arg)
{
if (!s_active.load() || !s_match_reported.load()) return;
ESP_LOGW(TAG, "Matched but grace ADV did not complete within %dms — stopping friend mode",
MATCH_STOP_FALLBACK_MS);
FriendExchange::StopFriendMode();
}
// stop 后异步释放 NimBLE。释放完成后再通知上层重开 WS,避免 WS 握手
// 和 nimble_port_stop/deinit 同时争抢 task slot / WiFi-BLE coex 资源。
static void OnReleaseNimble(void* arg)
{
if (s_active.load()) {
// 又有人开了 friend mode(用户连按按钮),跳过释放,让它继续工作
ESP_LOGI(TAG, "Release skipped: friend mode reactivated");
return;
}
if (!s_nimble_task_started.load()) {
NotifyStopped();
return;
}
HardResetNimble("post-stop full release (async)");
NotifyStopped();
}
// --- Advertising phase (timed, auto-expires) ---
static void StartAdvertisePhase(int duration_ms)
{
if (!s_active.load()) return;
std::string adv_name = s_local_info.name;
if (adv_name.empty()) adv_name = "BorlaF-0000";
// Set adv fields once
if (!s_adv_fields_set) {
ble_svc_gap_device_name_set(adv_name.c_str());
struct ble_hs_adv_fields adv_fields = {};
adv_fields.flags = BLE_HS_ADV_F_DISC_GEN | BLE_HS_ADV_F_BREDR_UNSUP;
adv_fields.name = (uint8_t*)adv_name.c_str();
adv_fields.name_len = adv_name.size();
adv_fields.name_is_complete = 1;
int rc = ble_gap_adv_set_fields(&adv_fields);
if (rc != 0) {
ESP_LOGE(TAG, "Set adv fields failed: %d", rc);
return;
}
s_adv_fields_set = true;
}
struct ble_gap_adv_params adv_params = {};
adv_params.conn_mode = BLE_GAP_CONN_MODE_NON;
adv_params.disc_mode = BLE_GAP_DISC_MODE_GEN;
adv_params.itvl_min = 48; // 30ms
adv_params.itvl_max = 96; // 60ms
// Timed advertising: auto-stops after ADV_DURATION_MSms
// OnGapEvent will receive BLE_GAP_EVENT_ADV_COMPLETE → start scan phase
int rc = ble_gap_adv_start(BLE_OWN_ADDR_PUBLIC, nullptr,
duration_ms,
&adv_params, OnGapEvent, nullptr);
if (rc == 0) {
s_is_advertising.store(true);
ESP_LOGI(TAG, "[Phase] ADV \"%s\" for %dms", adv_name.c_str(), duration_ms);
} else {
ESP_LOGW(TAG, "[Phase] ADV failed: rc=%d, retrying scan", rc);
// Fallback: try scan instead
StartScanPhase();
}
}
// --- Scanning phase (timed, auto-expires) ---
static void StartScanPhase()
{
if (!s_active.load()) return;
struct ble_gap_disc_params scan_params = {};
scan_params.passive = 1;
scan_params.itvl = 80; // 50ms
scan_params.window = 60; // 37.5ms
scan_params.filter_duplicates = 0;
scan_params.limited = 0;
// Timed scan: auto-stops after SCAN_DURATION_MS
// OnGapEvent will receive BLE_GAP_EVENT_DISC_COMPLETE → start adv phase
int rc = ble_gap_disc(BLE_OWN_ADDR_PUBLIC,
SCAN_DURATION_MS, // duration in ms
&scan_params, OnGapEvent, nullptr);
if (rc == 0) {
s_is_advertising.store(false);
ESP_LOGI(TAG, "[Phase] SCAN for %dms", SCAN_DURATION_MS);
} else {
ESP_LOGW(TAG, "[Phase] SCAN failed: rc=%d, retrying adv", rc);
// Fallback: try adv instead
StartAdvertisePhase();
}
}
// --- GAP event handler ---
static std::string AddrToString(const ble_addr_t& addr)
{
char buf[18];
snprintf(buf, sizeof(buf), "%02X:%02X:%02X:%02X:%02X:%02X",
addr.val[5], addr.val[4], addr.val[3],
addr.val[2], addr.val[1], addr.val[0]);
return std::string(buf);
}
static int OnGapEvent(struct ble_gap_event* event, void* arg)
{
switch (event->type) {
case BLE_GAP_EVENT_DISC: {
// Scan result
if (!s_active.load()) break;
const struct ble_gap_disc_desc* disc = &event->disc;
struct ble_hs_adv_fields fields = {};
if (ble_hs_adv_parse_fields(&fields, disc->data, disc->length_data) != 0) break;
std::string name;
if (fields.name_len > 0 && fields.name != nullptr) {
name.assign((const char*)fields.name, fields.name_len);
}
if (name.find(FRIEND_PREFIX) != 0) break;
std::string mac = AddrToString(disc->addr);
int64_t now_ms = esp_timer_get_time() / 1000;
{
std::lock_guard<std::mutex> lock(s_devices_mutex);
auto& dev = s_discovered[mac];
int rssi = static_cast<int>(disc->rssi);
dev.name = name;
dev.rssi = rssi;
dev.best_rssi = std::max(dev.best_rssi, rssi);
dev.seen_count++;
dev.last_seen_ms = now_ms;
dev.addr = disc->addr;
}
break;
}
case BLE_GAP_EVENT_DISC_COMPLETE:
// Scan phase finished → start advertise phase
ESP_LOGD(TAG, "Scan complete, switching to ADV");
if (s_active.load()) {
if (s_match_grace_requested.exchange(false)) {
s_match_grace_advertising.store(true);
StartAdvertisePhase(MATCH_ADV_GRACE_MS);
} else {
StartAdvertisePhase();
}
}
break;
case BLE_GAP_EVENT_ADV_COMPLETE:
// Advertise phase finished → start scan phase
ESP_LOGD(TAG, "Adv complete, switching to SCAN");
s_is_advertising.store(false);
if (s_active.load()) {
if (s_match_grace_advertising.load()) {
FriendExchange::StopFriendMode();
} else if (s_match_grace_requested.exchange(false)) {
s_match_grace_advertising.store(true);
StartAdvertisePhase(MATCH_ADV_GRACE_MS);
} else {
StartScanPhase();
}
}
break;
default:
break;
}
return 0;
}
// --- Periodic log (every 1s) ---
static void OnLogTimer(void* arg)
{
if (!s_active.load()) return;
int64_t now_ms = esp_timer_get_time() / 1000;
std::unique_lock<std::mutex> lock(s_devices_mutex);
// Remove stale (not seen in 6s)
for (auto it = s_discovered.begin(); it != s_discovered.end();) {
if (now_ms - it->second.last_seen_ms > 6000) {
it = s_discovered.erase(it);
} else {
++it;
}
}
const char* phase = s_is_advertising.load() ? "ADV" : "SCAN";
if (s_discovered.empty()) {
ESP_LOGI(TAG, "[%s] No BorlaF-* devices nearby", phase);
return;
}
ESP_LOGI(TAG, "[%s] %zu device(s):", phase, s_discovered.size());
FriendInfo remote;
FriendExchangeCallback cb = nullptr;
for (auto& [mac, dev] : s_discovered) {
bool strong = dev.best_rssi >= FRIEND_STRONG_RSSI_THRESHOLD;
bool weak_confirmed = dev.best_rssi >= FRIEND_WEAK_RSSI_THRESHOLD &&
dev.seen_count >= FRIEND_WEAK_MIN_SEEN;
bool close = strong || weak_confirmed;
ESP_LOGI(TAG, " %s %-16s RSSI: %d dBm best=%d seen=%d%s",
mac.c_str(), dev.name.c_str(), dev.rssi,
dev.best_rssi, dev.seen_count,
close ? " *** CLOSE ***" : "");
if (close && !s_match_reported.load() && s_on_complete && !cb) {
remote.mac = SystemInfo::BleMacToBaseMac(mac);
remote.name = dev.name;
ESP_LOGI(TAG, ">>> FRIEND MATCHED: %s BLE=%s BASE=%s RSSI=%d <<<",
dev.name.c_str(), mac.c_str(), remote.mac.c_str(), dev.rssi);
cb = s_on_complete;
}
}
// Release the mutex before calling StopFriendMode/cb — StopFriendMode
// acquires s_devices_mutex to clear s_discovered, and std::mutex is not
// recursive. Doing it inside the lock deadlocks the esp_timer task, after
// which neither the callback nor subsequent button presses work.
if (cb) {
lock.unlock();
s_paired.store(true);
s_match_reported.store(true);
s_match_grace_requested.store(true);
if (s_timeout_timer) esp_timer_stop(s_timeout_timer);
if (!s_match_stop_timer) {
esp_timer_create_args_t args = {
.callback = OnMatchStopFallback, .arg = nullptr,
.dispatch_method = ESP_TIMER_TASK, .name = "friend_match_to",
.skip_unhandled_events = true,
};
esp_timer_create(&args, &s_match_stop_timer);
}
esp_timer_stop(s_match_stop_timer);
esp_timer_start_once(s_match_stop_timer,
(uint64_t)MATCH_STOP_FALLBACK_MS * 1000);
cb(s_local_info, remote);
ESP_LOGI(TAG, "Friend matched; waiting for current GAP phase to finish before grace ADV");
}
}
// --- Timeout ---
static void OnScanTimeout(void* arg)
{
ESP_LOGI(TAG, "Friend mode timeout (%ds)", FRIEND_MODE_TIMEOUT_S);
FriendExchange::StopFriendMode();
}
// === Public API ===
void FriendExchange::StartFriendMode(const FriendInfo& local_info,
FriendExchangeCallback on_complete,
FriendExchangeOnStopped on_stopped)
{
if (s_active.load()) {
ESP_LOGW(TAG, "Friend mode already active");
return;
}
s_active.store(true);
s_paired.store(false);
s_match_reported.store(false);
s_match_grace_requested.store(false);
s_match_grace_advertising.store(false);
s_local_info = local_info;
s_on_complete = on_complete;
s_on_stopped = on_stopped;
s_adv_fields_set = false;
ESP_LOGI(TAG, "========================================");
ESP_LOGI(TAG, " FRIEND MODE START");
ESP_LOGI(TAG, " Local: %s (%s)", local_info.name.c_str(), local_info.mac.c_str());
ESP_LOGI(TAG, " ADV %dms ↔ SCAN %dms Timeout: %ds",
ADV_DURATION_MS, SCAN_DURATION_MS, FRIEND_MODE_TIMEOUT_S);
ESP_LOGI(TAG, " RSSI threshold: strong=%d dBm, weak=%d dBm x%d",
FRIEND_STRONG_RSSI_THRESHOLD, FRIEND_WEAK_RSSI_THRESHOLD,
FRIEND_WEAK_MIN_SEEN);
ESP_LOGI(TAG, "========================================");
{
std::lock_guard<std::mutex> lock(s_devices_mutex);
s_discovered.clear();
}
// Timeout timer (30s)
if (!s_timeout_timer) {
esp_timer_create_args_t args = {
.callback = OnScanTimeout, .arg = nullptr,
.dispatch_method = ESP_TIMER_TASK, .name = "friend_to",
.skip_unhandled_events = true,
};
esp_timer_create(&args, &s_timeout_timer);
}
esp_timer_start_once(s_timeout_timer, (uint64_t)FRIEND_MODE_TIMEOUT_S * 1000000);
// Log timer (1s)
if (!s_log_timer) {
esp_timer_create_args_t args = {
.callback = OnLogTimer, .arg = nullptr,
.dispatch_method = ESP_TIMER_TASK, .name = "friend_log",
.skip_unhandled_events = true,
};
esp_timer_create(&args, &s_log_timer);
}
esp_timer_start_periodic(s_log_timer, (uint64_t)SCAN_LOG_INTERVAL_MS * 1000);
// Start NimBLE (OnNimbleSync → StartScanPhase)
EnsureNimbleStarted();
}
void FriendExchange::StopFriendMode()
{
if (!s_active.load()) return;
s_active.store(false);
if (s_timeout_timer) esp_timer_stop(s_timeout_timer);
if (s_log_timer) esp_timer_stop(s_log_timer);
if (s_sync_watchdog_timer) esp_timer_stop(s_sync_watchdog_timer);
if (s_match_stop_timer) esp_timer_stop(s_match_stop_timer);
// 同步停 GAP,让 host task 退出 adv/scan 状态。NimBLE host 本身稍后
// 由 release_timer 异步释放(见下面注释)。
if (s_nimble_task_started.load() || s_nimble_ready.load()) {
ble_gap_disc_cancel();
ble_gap_adv_stop();
}
{
std::lock_guard<std::mutex> lock(s_devices_mutex);
s_discovered.clear();
}
s_on_complete = nullptr;
s_adv_fields_set = false;
s_match_grace_requested.store(false);
s_match_grace_advertising.store(false);
ESP_LOGI(TAG, "=== FRIEND MODE STOP ===");
// 先释放 NimBLE host(还给 WS 握手需要的 task slot),释放完成后再通知
// button_config 重开 WS。不能反过来,否则会出现日志里的 WS handshake timeout。
if (!s_nimble_task_started.load()) {
NotifyStopped();
return;
}
if (!s_release_timer) {
esp_timer_create_args_t args = {
.callback = OnReleaseNimble, .arg = nullptr,
.dispatch_method = ESP_TIMER_TASK, .name = "friend_rel",
.skip_unhandled_events = true,
};
esp_timer_create(&args, &s_release_timer);
}
esp_timer_stop(s_release_timer);
esp_timer_start_once(s_release_timer, (uint64_t)NIMBLE_RELEASE_DELAY_MS * 1000);
}
bool FriendExchange::IsActive()
{
return s_active.load();
}

View File

@@ -0,0 +1,56 @@
#pragma once
#include <string>
#include <functional>
/**
* BLE Friend Exchange module.
*
* Handles BLE advertise/scan based device-to-device friend pairing.
* Flow:
* 1. Triple-click → StartFriendMode()
* 2. Advertise as "BorlaF-XXXX" + scan for "BorlaF-*"
* 3. On discovery: derive peer identity from BorlaF-* advertisement
* 4. Report to server via WebSocket friend_add message
* 5. Auto-close BLE after timeout (30s)
*
* This module intentionally does not register the BLE provisioning GATT
* service. Double-click provisioning owns that service in BleProv.
*/
struct FriendInfo {
std::string mac;
std::string name;
};
// Callback when friend exchange completes successfully
using FriendExchangeCallback = std::function<void(const FriendInfo& local, const FriendInfo& remote)>;
// Callback fired when friend mode exits — either after a successful pairing
// (right after FriendExchangeCallback) or after a 30s timeout. Always called
// exactly once per StartFriendMode invocation, on the esp_timer task.
// Caller uses this to restore resources it disabled at start time (e.g. WS).
using FriendExchangeOnStopped = std::function<void(bool paired)>;
class FriendExchange {
public:
/**
* Start BLE friend discovery mode.
* Advertises and scans simultaneously for 30 seconds.
* Calls on_complete when a friend is successfully exchanged.
* Calls on_stopped at the end (paired or timeout) — always once.
*/
static void StartFriendMode(const FriendInfo& local_info,
FriendExchangeCallback on_complete,
FriendExchangeOnStopped on_stopped = nullptr);
/**
* Stop friend mode early (e.g., button press to cancel).
*/
static void StopFriendMode();
/**
* Check if friend mode is currently active.
*/
static bool IsActive();
};