bolar_2 backup
This commit is contained in:
269
main/provisioning/ble_provisioning_codec.cc
Normal file
269
main/provisioning/ble_provisioning_codec.cc
Normal file
@@ -0,0 +1,269 @@
|
||||
#include "provisioning/ble_provisioning_codec.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cstring>
|
||||
|
||||
#include <cJSON.h>
|
||||
|
||||
namespace borla {
|
||||
namespace {
|
||||
|
||||
bool PrintJson(
|
||||
cJSON* root,
|
||||
char* output,
|
||||
size_t capacity,
|
||||
size_t* output_size)
|
||||
{
|
||||
if (root == nullptr || output == nullptr ||
|
||||
capacity < 2 || output_size == nullptr) {
|
||||
cJSON_Delete(root);
|
||||
return false;
|
||||
}
|
||||
const bool printed =
|
||||
cJSON_PrintPreallocated(
|
||||
root,
|
||||
output,
|
||||
static_cast<int>(capacity),
|
||||
false) != 0;
|
||||
cJSON_Delete(root);
|
||||
if (!printed) {
|
||||
output[0] = '\0';
|
||||
*output_size = 0;
|
||||
return false;
|
||||
}
|
||||
*output_size = std::strlen(output);
|
||||
return true;
|
||||
}
|
||||
|
||||
bool AddString(cJSON* object, const char* name, const char* value)
|
||||
{
|
||||
return cJSON_AddStringToObject(object, name, value) != nullptr;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
BleChunkAssemblyResult BleChunkAssembler::Push(
|
||||
const uint8_t* packet,
|
||||
size_t size)
|
||||
{
|
||||
if (packet == nullptr || size < 3) {
|
||||
Reset();
|
||||
return BleChunkAssemblyResult::kInvalid;
|
||||
}
|
||||
const uint8_t sequence = packet[0];
|
||||
const uint8_t flag = packet[1];
|
||||
if (flag > 1 || (!receiving_ && sequence != 0) ||
|
||||
(receiving_ && sequence != next_sequence_)) {
|
||||
Reset();
|
||||
return BleChunkAssemblyResult::kInvalid;
|
||||
}
|
||||
|
||||
if (sequence == 0) {
|
||||
Reset();
|
||||
receiving_ = true;
|
||||
}
|
||||
const size_t payload_size = size - 2;
|
||||
if (payload_size == 0 ||
|
||||
size_ + payload_size >= buffer_.size()) {
|
||||
Reset();
|
||||
return BleChunkAssemblyResult::kInvalid;
|
||||
}
|
||||
std::memcpy(buffer_.data() + size_, packet + 2, payload_size);
|
||||
size_ += payload_size;
|
||||
buffer_[size_] = '\0';
|
||||
next_sequence_ = static_cast<uint8_t>(sequence + 1U);
|
||||
|
||||
if (flag == 0) {
|
||||
return BleChunkAssemblyResult::kAccepted;
|
||||
}
|
||||
receiving_ = false;
|
||||
return BleChunkAssemblyResult::kComplete;
|
||||
}
|
||||
|
||||
void BleChunkAssembler::Reset()
|
||||
{
|
||||
buffer_.fill('\0');
|
||||
size_ = 0;
|
||||
next_sequence_ = 0;
|
||||
receiving_ = false;
|
||||
}
|
||||
|
||||
bool VisitBleNotificationChunks(
|
||||
const char* json,
|
||||
size_t size,
|
||||
uint16_t negotiated_mtu,
|
||||
IBleChunkVisitor& visitor)
|
||||
{
|
||||
if (json == nullptr || size == 0) {
|
||||
return false;
|
||||
}
|
||||
const size_t att_payload =
|
||||
negotiated_mtu > 3
|
||||
? static_cast<size_t>(
|
||||
std::min<uint16_t>(negotiated_mtu, 517) - 3)
|
||||
: 20;
|
||||
const size_t chunk_payload =
|
||||
std::max<size_t>(
|
||||
1,
|
||||
att_payload > 2 ? att_payload - 2 : 18);
|
||||
if ((size + chunk_payload - 1) / chunk_payload > 256) {
|
||||
return false;
|
||||
}
|
||||
|
||||
std::array<uint8_t, 514> packet{};
|
||||
size_t offset = 0;
|
||||
uint8_t sequence = 0;
|
||||
while (offset < size) {
|
||||
const size_t bytes =
|
||||
std::min(chunk_payload, size - offset);
|
||||
const bool last = offset + bytes == size;
|
||||
packet[0] = sequence;
|
||||
packet[1] = last ? 1 : 0;
|
||||
std::memcpy(packet.data() + 2, json + offset, bytes);
|
||||
if (!visitor.OnBleChunk(packet.data(), bytes + 2)) {
|
||||
return false;
|
||||
}
|
||||
offset += bytes;
|
||||
sequence++;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool ParseProvisioningCredential(
|
||||
const char* json,
|
||||
size_t size,
|
||||
WifiCredential* credential)
|
||||
{
|
||||
if (json == nullptr || credential == nullptr ||
|
||||
size == 0 || size >= kBleCredentialJsonCapacity ||
|
||||
std::memchr(json, '\0', size) != nullptr) {
|
||||
return false;
|
||||
}
|
||||
std::array<char, kBleCredentialJsonCapacity> copy{};
|
||||
std::memcpy(copy.data(), json, size);
|
||||
|
||||
cJSON* root = cJSON_Parse(copy.data());
|
||||
if (!cJSON_IsObject(root)) {
|
||||
cJSON_Delete(root);
|
||||
return false;
|
||||
}
|
||||
const cJSON* ssid =
|
||||
cJSON_GetObjectItemCaseSensitive(root, "ssid");
|
||||
const cJSON* password =
|
||||
cJSON_GetObjectItemCaseSensitive(root, "password");
|
||||
const bool valid =
|
||||
cJSON_IsString(ssid) &&
|
||||
ssid->valuestring != nullptr &&
|
||||
(password == nullptr || cJSON_IsString(password));
|
||||
const bool set =
|
||||
valid && credential->Set(
|
||||
ssid->valuestring,
|
||||
password == nullptr ? "" : password->valuestring);
|
||||
cJSON_Delete(root);
|
||||
return set;
|
||||
}
|
||||
|
||||
bool BuildProvisioningDeviceInfoJson(
|
||||
const DeviceIdentity& identity,
|
||||
char* output,
|
||||
size_t capacity,
|
||||
size_t* output_size)
|
||||
{
|
||||
cJSON* root = cJSON_CreateObject();
|
||||
if (root == nullptr ||
|
||||
!AddString(root, "mac", identity.mac) ||
|
||||
!AddString(root, "version", identity.app_version) ||
|
||||
!AddString(root, "board", identity.board)) {
|
||||
cJSON_Delete(root);
|
||||
return false;
|
||||
}
|
||||
return PrintJson(root, output, capacity, output_size);
|
||||
}
|
||||
|
||||
bool BuildProvisioningScanJson(
|
||||
const WifiNetwork* networks,
|
||||
size_t count,
|
||||
char* output,
|
||||
size_t capacity,
|
||||
size_t* output_size)
|
||||
{
|
||||
if ((networks == nullptr && count != 0) ||
|
||||
count > kMaxProvisioningScanResults) {
|
||||
return false;
|
||||
}
|
||||
cJSON* root = cJSON_CreateObject();
|
||||
cJSON* array =
|
||||
root == nullptr ? nullptr : cJSON_AddArrayToObject(root, "networks");
|
||||
if (array == nullptr) {
|
||||
cJSON_Delete(root);
|
||||
return false;
|
||||
}
|
||||
for (size_t index = 0; index < count; ++index) {
|
||||
cJSON* item = cJSON_CreateObject();
|
||||
if (item == nullptr ||
|
||||
!AddString(item, "ssid", networks[index].ssid.data()) ||
|
||||
cJSON_AddNumberToObject(
|
||||
item, "rssi", networks[index].rssi_dbm) == nullptr ||
|
||||
cJSON_AddNumberToObject(
|
||||
item, "auth", networks[index].auth_mode) == nullptr) {
|
||||
cJSON_Delete(item);
|
||||
cJSON_Delete(root);
|
||||
return false;
|
||||
}
|
||||
cJSON_AddItemToArray(array, item);
|
||||
}
|
||||
return PrintJson(root, output, capacity, output_size);
|
||||
}
|
||||
|
||||
bool BuildProvisioningSavedWifiJson(
|
||||
const WifiCredential* credentials,
|
||||
size_t count,
|
||||
char* output,
|
||||
size_t capacity,
|
||||
size_t* output_size)
|
||||
{
|
||||
if ((credentials == nullptr && count != 0) ||
|
||||
count > kMaxSavedWifiCredentials) {
|
||||
return false;
|
||||
}
|
||||
cJSON* root = cJSON_CreateObject();
|
||||
cJSON* array =
|
||||
root == nullptr ? nullptr : cJSON_AddArrayToObject(root, "saved");
|
||||
if (array == nullptr) {
|
||||
cJSON_Delete(root);
|
||||
return false;
|
||||
}
|
||||
for (size_t index = 0; index < count; ++index) {
|
||||
cJSON* item = cJSON_CreateObject();
|
||||
if (item == nullptr ||
|
||||
cJSON_AddNumberToObject(item, "index", index) == nullptr ||
|
||||
!AddString(item, "ssid", credentials[index].ssid.data())) {
|
||||
cJSON_Delete(item);
|
||||
cJSON_Delete(root);
|
||||
return false;
|
||||
}
|
||||
cJSON_AddItemToArray(array, item);
|
||||
}
|
||||
return PrintJson(root, output, capacity, output_size);
|
||||
}
|
||||
|
||||
bool BuildProvisioningResultJson(
|
||||
bool success,
|
||||
const char* error,
|
||||
char* output,
|
||||
size_t capacity,
|
||||
size_t* output_size)
|
||||
{
|
||||
cJSON* root = cJSON_CreateObject();
|
||||
if (root == nullptr ||
|
||||
cJSON_AddBoolToObject(root, "success", success) == nullptr ||
|
||||
(!success && error != nullptr &&
|
||||
error[0] != '\0' &&
|
||||
!AddString(root, "error", error))) {
|
||||
cJSON_Delete(root);
|
||||
return false;
|
||||
}
|
||||
return PrintJson(root, output, capacity, output_size);
|
||||
}
|
||||
|
||||
} // namespace borla
|
||||
84
main/provisioning/ble_provisioning_codec.h
Normal file
84
main/provisioning/ble_provisioning_codec.h
Normal file
@@ -0,0 +1,84 @@
|
||||
#pragma once
|
||||
|
||||
#include "connectivity/wifi_types.h"
|
||||
#include "ports/device_platform.h"
|
||||
|
||||
#include <array>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
|
||||
namespace borla {
|
||||
|
||||
inline constexpr size_t kBleProvisioningJsonCapacity = 4096;
|
||||
inline constexpr size_t kBleCredentialJsonCapacity = 256;
|
||||
|
||||
enum class BleChunkAssemblyResult : uint8_t {
|
||||
kAccepted,
|
||||
kComplete,
|
||||
kInvalid,
|
||||
};
|
||||
|
||||
class BleChunkAssembler final {
|
||||
public:
|
||||
BleChunkAssemblyResult Push(
|
||||
const uint8_t* packet,
|
||||
size_t size);
|
||||
void Reset();
|
||||
|
||||
const char* data() const { return buffer_.data(); }
|
||||
size_t size() const { return size_; }
|
||||
|
||||
private:
|
||||
std::array<char, kBleCredentialJsonCapacity> buffer_{};
|
||||
size_t size_ = 0;
|
||||
uint8_t next_sequence_ = 0;
|
||||
bool receiving_ = false;
|
||||
};
|
||||
|
||||
class IBleChunkVisitor {
|
||||
public:
|
||||
virtual ~IBleChunkVisitor() = default;
|
||||
virtual bool OnBleChunk(
|
||||
const uint8_t* data,
|
||||
size_t size) = 0;
|
||||
};
|
||||
|
||||
bool VisitBleNotificationChunks(
|
||||
const char* json,
|
||||
size_t size,
|
||||
uint16_t negotiated_mtu,
|
||||
IBleChunkVisitor& visitor);
|
||||
|
||||
bool ParseProvisioningCredential(
|
||||
const char* json,
|
||||
size_t size,
|
||||
WifiCredential* credential);
|
||||
|
||||
bool BuildProvisioningDeviceInfoJson(
|
||||
const DeviceIdentity& identity,
|
||||
char* output,
|
||||
size_t capacity,
|
||||
size_t* output_size);
|
||||
|
||||
bool BuildProvisioningScanJson(
|
||||
const WifiNetwork* networks,
|
||||
size_t count,
|
||||
char* output,
|
||||
size_t capacity,
|
||||
size_t* output_size);
|
||||
|
||||
bool BuildProvisioningSavedWifiJson(
|
||||
const WifiCredential* credentials,
|
||||
size_t count,
|
||||
char* output,
|
||||
size_t capacity,
|
||||
size_t* output_size);
|
||||
|
||||
bool BuildProvisioningResultJson(
|
||||
bool success,
|
||||
const char* error,
|
||||
char* output,
|
||||
size_t capacity,
|
||||
size_t* output_size);
|
||||
|
||||
} // namespace borla
|
||||
486
main/provisioning/ble_provisioning_service.cc
Normal file
486
main/provisioning/ble_provisioning_service.cc
Normal file
@@ -0,0 +1,486 @@
|
||||
#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
|
||||
116
main/provisioning/ble_provisioning_service.h
Normal file
116
main/provisioning/ble_provisioning_service.h
Normal file
@@ -0,0 +1,116 @@
|
||||
#pragma once
|
||||
|
||||
#include "connectivity/wifi_credential_store.h"
|
||||
#include "connectivity/wifi_transport.h"
|
||||
#include "core/task_stack_budget.h"
|
||||
#include "platform/borla_s3/ble_provisioning_gatt.h"
|
||||
#include "ports/audio_engine.h"
|
||||
#include "ports/device_platform.h"
|
||||
#include "ports/event_publisher.h"
|
||||
#include "ports/provisioning_service.h"
|
||||
|
||||
#include <array>
|
||||
#include <atomic>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
|
||||
#include <freertos/FreeRTOS.h>
|
||||
#include <freertos/event_groups.h>
|
||||
#include <freertos/queue.h>
|
||||
#include <freertos/task.h>
|
||||
|
||||
namespace borla {
|
||||
|
||||
class BleProvisioningService final
|
||||
: public IProvisioningService,
|
||||
public IBleProvisioningGattObserver,
|
||||
public IWifiTransportObserver {
|
||||
public:
|
||||
BleProvisioningService(
|
||||
IWifiTransport& wifi,
|
||||
IWifiCredentialStore& credentials,
|
||||
IDevicePlatform& platform,
|
||||
IAudioEngine& audio);
|
||||
|
||||
bool Initialize();
|
||||
void SetEventPublisher(IEventPublisher* publisher);
|
||||
void Start() override;
|
||||
void Stop() override;
|
||||
|
||||
void OnBleWifiScanRequested() override;
|
||||
void OnBleWifiCredential(
|
||||
const WifiCredential& credential) override;
|
||||
void OnBleSavedWifiListRequested() override;
|
||||
void OnBleSavedWifiDeleteRequested(uint8_t index) override;
|
||||
void OnBleRebootRequested() override;
|
||||
void OnWifiTransportEvent(
|
||||
const WifiTransportEvent& event) override;
|
||||
|
||||
private:
|
||||
enum class CommandType : uint8_t {
|
||||
kStart,
|
||||
kStop,
|
||||
kSendScan,
|
||||
kConnectCredential,
|
||||
kListSavedWifi,
|
||||
kDeleteSavedWifi,
|
||||
kReboot,
|
||||
};
|
||||
|
||||
struct Command {
|
||||
CommandType type = CommandType::kStart;
|
||||
WifiCredential credential{};
|
||||
uint8_t index = 0;
|
||||
};
|
||||
|
||||
static constexpr size_t kQueueDepth = 12;
|
||||
static constexpr UBaseType_t kTaskPriority = 5;
|
||||
static constexpr EventBits_t kWifiStartedBit = BIT0;
|
||||
static constexpr EventBits_t kWifiConnectedBit = BIT1;
|
||||
static constexpr EventBits_t kWifiDisconnectedBit = BIT2;
|
||||
static constexpr EventBits_t kWifiBits =
|
||||
kWifiStartedBit | kWifiConnectedBit | kWifiDisconnectedBit;
|
||||
|
||||
static void TaskEntry(void* context);
|
||||
[[noreturn]] void Run();
|
||||
bool Post(const Command& command);
|
||||
void Handle(const Command& command);
|
||||
void HandleStart();
|
||||
void HandleConnect(WifiCredential credential);
|
||||
void HandleListSavedWifi();
|
||||
void HandleDeleteSavedWifi(uint8_t index);
|
||||
bool RestoreSavedPassword(WifiCredential* credential);
|
||||
const char* MapDisconnectError(uint16_t reason) const;
|
||||
void Publish(const AppEvent& event);
|
||||
|
||||
IWifiTransport& wifi_;
|
||||
IWifiCredentialStore& credentials_;
|
||||
IDevicePlatform& platform_;
|
||||
IAudioEngine& audio_;
|
||||
BleProvisioningGattServer gatt_;
|
||||
std::array<WifiNetwork, kMaxProvisioningScanResults>
|
||||
scan_results_{};
|
||||
size_t scan_count_ = 0;
|
||||
|
||||
QueueHandle_t queue_ = nullptr;
|
||||
StaticQueue_t queue_control_{};
|
||||
alignas(Command)
|
||||
std::array<uint8_t, kQueueDepth * sizeof(Command)>
|
||||
queue_storage_{};
|
||||
EventGroupHandle_t wifi_events_ = nullptr;
|
||||
StaticEventGroup_t wifi_events_control_{};
|
||||
TaskHandle_t task_ = nullptr;
|
||||
StaticTask_t task_control_{};
|
||||
std::array<
|
||||
StackType_t,
|
||||
task_stack_budget::kBleProvisioningBytes>
|
||||
task_stack_{};
|
||||
|
||||
std::atomic<IEventPublisher*> publisher_{nullptr};
|
||||
std::atomic<uint16_t> disconnect_reason_{0};
|
||||
std::atomic<bool> initialized_{false};
|
||||
bool active_ = false;
|
||||
bool connection_attempt_active_ = false;
|
||||
};
|
||||
|
||||
} // namespace borla
|
||||
Reference in New Issue
Block a user