487 lines
17 KiB
C++
487 lines
17 KiB
C++
#include "provisioning/ble_provisioning_service.h"
|
||
|
||
#include <cstring>
|
||
|
||
#include <esp_heap_caps.h>
|
||
#include <esp_log.h>
|
||
#include <esp_wifi_types_generic.h>
|
||
#include <sdkconfig.h>
|
||
|
||
// Self-verifying build stamp: sdkconfig is gitignored, so a fix that only
|
||
// lives in sdkconfig.defaults silently misses any build whose sdkconfig was
|
||
// not regenerated. Logging the compiled mode makes a stale build obvious in
|
||
// the device log instead of reproducing "hci inits failed" mysteries.
|
||
#if CONFIG_BT_NIMBLE_MEM_ALLOC_MODE_EXTERNAL
|
||
#define BORLA_NIMBLE_POOLS "PSRAM"
|
||
#elif CONFIG_BT_NIMBLE_MEM_ALLOC_MODE_INTERNAL
|
||
#define BORLA_NIMBLE_POOLS "internal (STALE sdkconfig — regenerate!)"
|
||
#else
|
||
#define BORLA_NIMBLE_POOLS "default"
|
||
#endif
|
||
|
||
namespace borla {
|
||
namespace {
|
||
|
||
constexpr const char* kTag = "BleProvService2";
|
||
constexpr uint32_t kWifiStartTimeoutMs = 1500;
|
||
constexpr uint32_t kWifiConnectTimeoutMs = 10000;
|
||
constexpr uint32_t kNotifySubscriptionDelayMs = 120;
|
||
constexpr uint32_t kRebootDispatchDelayMs = 150;
|
||
// wifi_success.ogg runs about 1.2 s; 5 s leaves room for it to be queued
|
||
// behind another prompt without letting a stalled producer wedge the reboot.
|
||
constexpr uint32_t kRebootPlaybackDrainMs = 5000;
|
||
// 进配网时先让「请用小程序帮我连接网络」播完,再释放音频引擎给 BT 控制器腾内存。
|
||
constexpr uint32_t kProvisioningPromptDrainMs = 3000;
|
||
constexpr uint32_t kProvisioningStartError = 7001;
|
||
|
||
} // namespace
|
||
|
||
BleProvisioningService::BleProvisioningService(
|
||
IWifiTransport& wifi,
|
||
IWifiCredentialStore& credentials,
|
||
IDevicePlatform& platform,
|
||
IAudioEngine& audio)
|
||
: wifi_(wifi),
|
||
credentials_(credentials),
|
||
platform_(platform),
|
||
audio_(audio)
|
||
{
|
||
}
|
||
|
||
bool BleProvisioningService::Initialize()
|
||
{
|
||
if (initialized_.load()) {
|
||
return true;
|
||
}
|
||
queue_ = xQueueCreateStatic(
|
||
kQueueDepth,
|
||
sizeof(Command),
|
||
queue_storage_.data(),
|
||
&queue_control_);
|
||
wifi_events_ =
|
||
xEventGroupCreateStatic(&wifi_events_control_);
|
||
if (queue_ == nullptr || wifi_events_ == nullptr) {
|
||
ESP_LOGE(kTag, "queue/event group initialization failed");
|
||
return false;
|
||
}
|
||
task_ = xTaskCreateStatic(
|
||
&BleProvisioningService::TaskEntry,
|
||
"ble_provision2",
|
||
task_stack_.size(),
|
||
this,
|
||
kTaskPriority,
|
||
task_stack_.data(),
|
||
&task_control_);
|
||
if (task_ == nullptr) {
|
||
ESP_LOGE(kTag, "worker task creation failed");
|
||
return false;
|
||
}
|
||
initialized_.store(true);
|
||
return true;
|
||
}
|
||
|
||
void BleProvisioningService::SetEventPublisher(
|
||
IEventPublisher* publisher)
|
||
{
|
||
publisher_.store(publisher);
|
||
}
|
||
|
||
void BleProvisioningService::Start()
|
||
{
|
||
if (!Post({CommandType::kStart, {}, 0})) {
|
||
ESP_LOGE(kTag, "failed to enqueue provisioning start");
|
||
}
|
||
}
|
||
|
||
void BleProvisioningService::Stop()
|
||
{
|
||
if (!Post({CommandType::kStop, {}, 0})) {
|
||
ESP_LOGE(kTag, "failed to enqueue provisioning stop");
|
||
}
|
||
}
|
||
|
||
void BleProvisioningService::OnBleWifiScanRequested()
|
||
{
|
||
Post({CommandType::kSendScan, {}, 0});
|
||
}
|
||
|
||
void BleProvisioningService::OnBleWifiCredential(
|
||
const WifiCredential& credential)
|
||
{
|
||
Command command;
|
||
command.type = CommandType::kConnectCredential;
|
||
command.credential = credential;
|
||
Post(command);
|
||
}
|
||
|
||
void BleProvisioningService::OnBleSavedWifiListRequested()
|
||
{
|
||
Post({CommandType::kListSavedWifi, {}, 0});
|
||
}
|
||
|
||
void BleProvisioningService::OnBleSavedWifiDeleteRequested(
|
||
uint8_t index)
|
||
{
|
||
Post({CommandType::kDeleteSavedWifi, {}, index});
|
||
}
|
||
|
||
void BleProvisioningService::OnBleRebootRequested()
|
||
{
|
||
Post({CommandType::kReboot, {}, 0});
|
||
}
|
||
|
||
void BleProvisioningService::OnWifiTransportEvent(
|
||
const WifiTransportEvent& event)
|
||
{
|
||
if (wifi_events_ == nullptr) {
|
||
return;
|
||
}
|
||
switch (event.type) {
|
||
case WifiTransportEventType::kStarted:
|
||
xEventGroupSetBits(wifi_events_, kWifiStartedBit);
|
||
break;
|
||
case WifiTransportEventType::kGotIp:
|
||
xEventGroupSetBits(wifi_events_, kWifiConnectedBit);
|
||
break;
|
||
case WifiTransportEventType::kDisconnected:
|
||
disconnect_reason_.store(event.disconnect_reason);
|
||
xEventGroupSetBits(wifi_events_, kWifiDisconnectedBit);
|
||
break;
|
||
case WifiTransportEventType::kReconnectRequested:
|
||
case WifiTransportEventType::kCellularOn:
|
||
case WifiTransportEventType::kCellularOff:
|
||
case WifiTransportEventType::kCellularUnavailable:
|
||
case WifiTransportEventType::kCellularBootOn:
|
||
break;
|
||
}
|
||
}
|
||
|
||
void BleProvisioningService::TaskEntry(void* context)
|
||
{
|
||
static_cast<BleProvisioningService*>(context)->Run();
|
||
}
|
||
|
||
[[noreturn]] void BleProvisioningService::Run()
|
||
{
|
||
ESP_LOGI(kTag, "BLE provisioning worker started");
|
||
while (true) {
|
||
Command command;
|
||
if (xQueueReceive(queue_, &command, portMAX_DELAY) == pdTRUE) {
|
||
Handle(command);
|
||
}
|
||
}
|
||
}
|
||
|
||
bool BleProvisioningService::Post(const Command& command)
|
||
{
|
||
return initialized_.load() && queue_ != nullptr &&
|
||
xQueueSend(queue_, &command, 0) == pdTRUE;
|
||
}
|
||
|
||
void BleProvisioningService::Handle(const Command& command)
|
||
{
|
||
switch (command.type) {
|
||
case CommandType::kStart:
|
||
HandleStart();
|
||
return;
|
||
case CommandType::kStop:
|
||
gatt_.Stop();
|
||
wifi_.Stop();
|
||
// Leaving provisioning without a reboot: the next full driver init
|
||
// has no BT controller to share with, so give the buffers back.
|
||
wifi_.UseLowMemoryProfile(false);
|
||
// A failed credential test leaves the codec released on purpose; the
|
||
// device is staying alive here rather than rebooting, so restore it or
|
||
// it would be silent from now on.
|
||
if (!audio_.Start()) {
|
||
ESP_LOGW(kTag, "audio restart on provisioning stop failed");
|
||
}
|
||
active_ = false;
|
||
connection_attempt_active_ = false;
|
||
return;
|
||
case CommandType::kSendScan:
|
||
if (active_) {
|
||
vTaskDelay(pdMS_TO_TICKS(kNotifySubscriptionDelayMs));
|
||
if (!gatt_.NotifyScanResults(
|
||
scan_results_.data(), scan_count_)) {
|
||
ESP_LOGW(kTag, "scan result notification failed");
|
||
}
|
||
}
|
||
return;
|
||
case CommandType::kConnectCredential:
|
||
HandleConnect(command.credential);
|
||
return;
|
||
case CommandType::kListSavedWifi:
|
||
HandleListSavedWifi();
|
||
return;
|
||
case CommandType::kDeleteSavedWifi:
|
||
HandleDeleteSavedWifi(command.index);
|
||
return;
|
||
case CommandType::kReboot:
|
||
// The phone sends this the moment it sees the success notification, so
|
||
// "配网成功啦" has only just been queued. Rebooting on a fixed short
|
||
// delay tore the decode queue and the I2S DMA down mid-sentence — the
|
||
// child heard half a word and then silence until the device came back.
|
||
// The previous firmware waited for playback to drain here too
|
||
// (wifi_board.cc SetRebootCallback, 3 s cap); the cap matters because a
|
||
// stuck producer must not be able to block the reboot forever.
|
||
vTaskDelay(pdMS_TO_TICKS(kRebootDispatchDelayMs));
|
||
if (!audio_.WaitForPlaybackIdle(kRebootPlaybackDrainMs)) {
|
||
ESP_LOGW(kTag, "rebooting with playback still active");
|
||
}
|
||
platform_.Reboot();
|
||
return;
|
||
}
|
||
}
|
||
|
||
void BleProvisioningService::HandleStart()
|
||
{
|
||
if (active_) {
|
||
return;
|
||
}
|
||
|
||
scan_results_.fill(WifiNetwork{});
|
||
scan_count_ = 0;
|
||
xEventGroupClearBits(wifi_events_, kWifiBits);
|
||
if (wifi_.Start(*this)) {
|
||
xEventGroupWaitBits(
|
||
wifi_events_,
|
||
kWifiStartedBit,
|
||
pdTRUE,
|
||
pdFALSE,
|
||
pdMS_TO_TICKS(kWifiStartTimeoutMs));
|
||
if (!wifi_.Scan(
|
||
scan_results_.data(),
|
||
scan_results_.size(),
|
||
&scan_count_)) {
|
||
ESP_LOGW(kTag, "pre-scan failed; BLE will expose empty list");
|
||
scan_count_ = 0;
|
||
}
|
||
} else {
|
||
ESP_LOGW(kTag, "WiFi transport unavailable for pre-scan");
|
||
}
|
||
// Tear the WiFi driver all the way down, not just stop it. The BT
|
||
// controller plus NimBLE host need ~65 KB of internal RAM at init and an
|
||
// idle-but-initialised WiFi driver holds tens of KB of packet buffers, so
|
||
// leaving it up makes nimble_port_init fail with "hci inits failed" and
|
||
// the device never advertises. Scan results are already cached above, and
|
||
// HandleConnect brings the driver back up when credentials arrive.
|
||
wifi_.ReleaseDriver();
|
||
// Every later Start() in this provisioning session runs alongside the BT
|
||
// controller, so it must ask the driver for the small buffer profile. The
|
||
// pre-scan above deliberately ran on the default one: BLE was not up yet
|
||
// and scanning benefits from the full RX pool.
|
||
wifi_.UseLowMemoryProfile(true);
|
||
ESP_LOGI(kTag,
|
||
"internal RAM before BLE: free=%u largest=%u dma_free=%u "
|
||
"dma_largest=%u host_pools=%s",
|
||
static_cast<unsigned>(
|
||
heap_caps_get_free_size(MALLOC_CAP_INTERNAL)),
|
||
static_cast<unsigned>(
|
||
heap_caps_get_largest_free_block(MALLOC_CAP_INTERNAL)),
|
||
static_cast<unsigned>(heap_caps_get_free_size(
|
||
MALLOC_CAP_INTERNAL | MALLOC_CAP_DMA)),
|
||
static_cast<unsigned>(heap_caps_get_largest_free_block(
|
||
MALLOC_CAP_INTERNAL | MALLOC_CAP_DMA)),
|
||
BORLA_NIMBLE_POOLS);
|
||
// 分区域明细:BT 控制器要的是一个 30KB 连续内部块,只有看到每个 region 的
|
||
// free/largest 才能判断失败是"总量不够"还是"碎片化"(见 sdkconfig.defaults
|
||
// 里 SPIRAM_MALLOC_RESERVE_INTERNAL 的说明)。
|
||
heap_caps_print_heap_info(MALLOC_CAP_INTERNAL);
|
||
|
||
// Free the audio engine so the BT controller has the internal RAM it needs
|
||
// (~30KB contiguous block for the controller plus the NimBLE host share).
|
||
// EnterProvisioning only applies AudioPolicy::kOff, which idles the capture
|
||
// task but keeps its 16KB internal stack and the I2S DMA descriptors alive;
|
||
// they are the two biggest consumers that would otherwise starve BLE init.
|
||
// Let the provisioning prompt finish first — it is the user's only
|
||
// confirmation that the double-click was heard. HandleConnect restarts the
|
||
// codec when there is something to say.
|
||
if (!audio_.WaitForPlaybackIdle(kProvisioningPromptDrainMs)) {
|
||
ESP_LOGW(kTag, "provisioning prompt still playing; releasing audio anyway");
|
||
}
|
||
audio_.Stop();
|
||
|
||
if (!gatt_.Start(platform_.Identity(), *this)) {
|
||
ESP_LOGE(kTag, "BLE GATT server start failed");
|
||
platform_.ReportError(kProvisioningStartError);
|
||
// Restore the codec so a retry (another double-click) can play the
|
||
// provisioning prompt again before re-entering this path.
|
||
if (!audio_.Start()) {
|
||
ESP_LOGW(kTag, "audio restart after BLE init failure");
|
||
}
|
||
return;
|
||
}
|
||
active_ = true;
|
||
ESP_LOGI(kTag, "provisioning active cached_networks=%u",
|
||
static_cast<unsigned>(scan_count_));
|
||
}
|
||
|
||
void BleProvisioningService::HandleConnect(
|
||
WifiCredential credential)
|
||
{
|
||
if (!active_ || connection_attempt_active_) {
|
||
gatt_.NotifyWifiResult(false, "unknown");
|
||
return;
|
||
}
|
||
connection_attempt_active_ = true;
|
||
|
||
if (credential.password[0] == '\0') {
|
||
RestoreSavedPassword(&credential);
|
||
}
|
||
xEventGroupClearBits(wifi_events_, kWifiBits);
|
||
disconnect_reason_.store(0);
|
||
|
||
// Bringing the WiFi driver back up while the BT controller holds its own
|
||
// allocations is the tightest internal-RAM moment in the whole firmware,
|
||
// and the binding constraint is not plain internal RAM but the DMA-capable
|
||
// subset: the driver's static RX buffers are 1600-byte DMA allocations and
|
||
// that is exactly where it fails ("wifi:malloc buffer fail" with tens of KB
|
||
// still free overall).
|
||
//
|
||
// I2S is the other big consumer of that pool — 6 descriptors x 240 frames
|
||
// on both directions, roughly 11 KB — and nothing needs the speaker or the
|
||
// microphone while a credential is being tested. Release the codec for the
|
||
// duration and bring it back afterwards so the success prompt can still
|
||
// play.
|
||
audio_.Stop();
|
||
ESP_LOGI(kTag,
|
||
"internal RAM before WiFi retry (audio released): "
|
||
"free=%u largest=%u dma_free=%u dma_largest=%u",
|
||
static_cast<unsigned>(
|
||
heap_caps_get_free_size(MALLOC_CAP_INTERNAL)),
|
||
static_cast<unsigned>(
|
||
heap_caps_get_largest_free_block(MALLOC_CAP_INTERNAL)),
|
||
static_cast<unsigned>(heap_caps_get_free_size(
|
||
MALLOC_CAP_INTERNAL | MALLOC_CAP_DMA)),
|
||
static_cast<unsigned>(heap_caps_get_largest_free_block(
|
||
MALLOC_CAP_INTERNAL | MALLOC_CAP_DMA)));
|
||
|
||
bool success = false;
|
||
const char* error = "unknown";
|
||
if (!wifi_.Start(*this)) {
|
||
// Almost always internal-RAM exhaustion at esp_wifi_init(); the log
|
||
// line above carries the number that proves it.
|
||
ESP_LOGE(kTag, "WiFi driver restart failed; cannot test credential");
|
||
} else if (wifi_.Connect(credential)) {
|
||
const EventBits_t result = xEventGroupWaitBits(
|
||
wifi_events_,
|
||
kWifiConnectedBit | kWifiDisconnectedBit,
|
||
pdTRUE,
|
||
pdFALSE,
|
||
pdMS_TO_TICKS(kWifiConnectTimeoutMs));
|
||
if ((result & kWifiConnectedBit) != 0) {
|
||
if (credentials_.SaveAndPromote(credential)) {
|
||
success = true;
|
||
error = "";
|
||
} else {
|
||
ESP_LOGE(kTag, "connected credential NVS save failed");
|
||
}
|
||
} else if ((result & kWifiDisconnectedBit) != 0) {
|
||
error = MapDisconnectError(disconnect_reason_.load());
|
||
} else {
|
||
error = "timeout";
|
||
}
|
||
}
|
||
|
||
// Stop WiFi before notifying: this gives the BLE connection exclusive
|
||
// radio time and makes the result notification reliable on ESP32-S3.
|
||
wifi_.Stop();
|
||
// Only bring the codec back when there is something to say. After a failed
|
||
// attempt the phone will almost certainly send another credential, and that
|
||
// retry starts from a worse position than this one did: esp_wifi_init()
|
||
// leaks a few KB on the failure path (IDF's own cleanup reports "Failed to
|
||
// deinit Wi-Fi driver (0x3001)"). Leaving the codec released keeps its
|
||
// ~7 KB — and the contiguous block it occupies — available for that retry.
|
||
if (!success) {
|
||
ESP_LOGI(kTag, "codec left released for the next attempt");
|
||
} else if (!audio_.Start()) {
|
||
ESP_LOGW(kTag, "audio restart after WiFi retry failed");
|
||
} else {
|
||
// "配网成功啦" — published after the codec is alive again, and routed
|
||
// through the reducer so the control plane stays the single writer of
|
||
// playback decisions.
|
||
Publish(AppEvent::Make(
|
||
AppEventType::kProvisioningWifiSaved));
|
||
}
|
||
if (!gatt_.NotifyWifiResult(success, error)) {
|
||
ESP_LOGW(kTag, "WiFi result notification failed success=%d",
|
||
success ? 1 : 0);
|
||
}
|
||
connection_attempt_active_ = false;
|
||
}
|
||
|
||
void BleProvisioningService::HandleListSavedWifi()
|
||
{
|
||
std::array<WifiCredential, kMaxSavedWifiCredentials> saved{};
|
||
const size_t count =
|
||
credentials_.Load(saved.data(), saved.size());
|
||
if (!gatt_.NotifySavedWifi(saved.data(), count)) {
|
||
ESP_LOGW(kTag, "saved WiFi list notification failed");
|
||
}
|
||
}
|
||
|
||
void BleProvisioningService::HandleDeleteSavedWifi(uint8_t index)
|
||
{
|
||
std::array<WifiCredential, kMaxSavedWifiCredentials> saved{};
|
||
const size_t count =
|
||
credentials_.Load(saved.data(), saved.size());
|
||
const bool valid = index < count;
|
||
const bool success =
|
||
valid && credentials_.Remove(saved[index].ssid.data());
|
||
if (!gatt_.NotifySavedWifiResult(
|
||
success, success ? "" : "invalid_index")) {
|
||
ESP_LOGW(kTag, "saved WiFi delete notification failed");
|
||
}
|
||
}
|
||
|
||
bool BleProvisioningService::RestoreSavedPassword(
|
||
WifiCredential* credential)
|
||
{
|
||
if (credential == nullptr) {
|
||
return false;
|
||
}
|
||
std::array<WifiCredential, kMaxSavedWifiCredentials> saved{};
|
||
const size_t count =
|
||
credentials_.Load(saved.data(), saved.size());
|
||
for (size_t index = 0; index < count; ++index) {
|
||
if (std::strncmp(
|
||
saved[index].ssid.data(),
|
||
credential->ssid.data(),
|
||
kWifiSsidCapacity) == 0) {
|
||
credential->password = saved[index].password;
|
||
return true;
|
||
}
|
||
}
|
||
return false;
|
||
}
|
||
|
||
void BleProvisioningService::Publish(const AppEvent& event)
|
||
{
|
||
IEventPublisher* publisher = publisher_.load();
|
||
if (publisher == nullptr || !publisher->Publish(event)) {
|
||
ESP_LOGE(kTag, "event publish failed type=%s",
|
||
ToString(event.type));
|
||
}
|
||
}
|
||
|
||
const char* BleProvisioningService::MapDisconnectError(
|
||
uint16_t reason) const
|
||
{
|
||
switch (reason) {
|
||
case WIFI_REASON_NO_AP_FOUND:
|
||
case WIFI_REASON_NO_AP_FOUND_IN_AUTHMODE_THRESHOLD:
|
||
case WIFI_REASON_NO_AP_FOUND_IN_RSSI_THRESHOLD:
|
||
return "not_found";
|
||
case WIFI_REASON_AUTH_EXPIRE:
|
||
case WIFI_REASON_AUTH_FAIL:
|
||
case WIFI_REASON_4WAY_HANDSHAKE_TIMEOUT:
|
||
case WIFI_REASON_HANDSHAKE_TIMEOUT:
|
||
return "password_wrong";
|
||
default:
|
||
return "unknown";
|
||
}
|
||
}
|
||
|
||
} // namespace borla
|