348 lines
12 KiB
C++
348 lines
12 KiB
C++
#include "wifi_board.h"
|
||
#include "application.h"
|
||
#include "audio/audio_prompt.h"
|
||
#include "settings.h"
|
||
#include "system_info.h"
|
||
#include "ble_prov.h"
|
||
|
||
#include <algorithm>
|
||
#include <esp_log.h>
|
||
#include <esp_wifi.h>
|
||
#include <esp_event.h>
|
||
#include <esp_netif.h>
|
||
#include <freertos/event_groups.h>
|
||
|
||
#define TAG "WifiBoard"
|
||
|
||
WifiBoard::WifiBoard()
|
||
{
|
||
Settings wifi_settings("wifi", true);
|
||
if (wifi_settings.GetInt("force_ap") == 1) {
|
||
wifi_config_mode_ = true;
|
||
// Clear flag immediately so next boot is normal
|
||
wifi_settings.SetInt("force_ap", 0);
|
||
}
|
||
}
|
||
|
||
NetworkInterface* WifiBoard::GetNetwork()
|
||
{
|
||
static EspNetwork network;
|
||
return &network;
|
||
}
|
||
|
||
void WifiBoard::StartNetwork()
|
||
{
|
||
if (wifi_config_mode_) {
|
||
EnterBleConfigMode();
|
||
return;
|
||
}
|
||
|
||
// 检查是否有保存的 WiFi
|
||
auto& ssid_mgr = SsidManager::GetInstance();
|
||
const auto& ssid_list = ssid_mgr.GetSsidList();
|
||
|
||
if (ssid_list.empty()) {
|
||
ESP_LOGW(TAG, "No WiFi configured, entering BLE config mode");
|
||
EnterBleConfigMode();
|
||
return;
|
||
}
|
||
|
||
// 添加所有保存的 WiFi 到 WifiStation
|
||
auto& station = WifiStation::GetInstance();
|
||
for (const auto& item : ssid_list) {
|
||
station.AddAuth(std::string(item.ssid), std::string(item.password));
|
||
}
|
||
|
||
station.OnConnect([](const std::string& ssid) {
|
||
ESP_LOGI(TAG, "Connecting to WiFi: %s", ssid.c_str());
|
||
});
|
||
|
||
station.OnConnected([](const std::string& ssid) {
|
||
ESP_LOGI(TAG, "Connected to WiFi: %s", ssid.c_str());
|
||
});
|
||
|
||
station.Start();
|
||
wifi_initialized_ = true;
|
||
|
||
// WiFi connection timeout:
|
||
// - With 4G fallback (skip_ble_on_timeout_): 15 seconds, then return to try 4G
|
||
// - Without fallback: 60 seconds, then enter BLE config mode
|
||
int timeout_ms = skip_ble_on_timeout_ ? 15000 : 60000;
|
||
if (!station.WaitForConnected(timeout_ms)) {
|
||
station.Stop();
|
||
if (skip_ble_on_timeout_) {
|
||
ESP_LOGW(TAG, "WiFi connection timeout (%ds), returning to caller for 4G fallback", timeout_ms / 1000);
|
||
return;
|
||
}
|
||
ESP_LOGW(TAG, "WiFi connection timeout, entering BLE config mode");
|
||
EnterBleConfigMode();
|
||
return;
|
||
}
|
||
|
||
ESP_LOGI(TAG, "WiFi connected, IP: %s", station.GetIpAddress().c_str());
|
||
}
|
||
|
||
bool WifiBoard::IsNetworkConnected() const
|
||
{
|
||
return WifiStation::GetInstance().IsConnected();
|
||
}
|
||
|
||
void WifiBoard::SetPowerSaveMode(bool enabled)
|
||
{
|
||
WifiStation::GetInstance().SetPowerSaveMode(enabled);
|
||
}
|
||
|
||
void WifiBoard::EnterBleConfigMode()
|
||
{
|
||
wifi_config_mode_ = true;
|
||
ESP_LOGI(TAG, "Entering BLE provisioning mode");
|
||
|
||
// Play wifi config prompt (OGG, async — don't block BLE startup).
|
||
// Use PlayLocal so that if WS is up (rare but possible when server
|
||
// sent {"type":"wifi_config"}), the server is told to stop any TTS.
|
||
auto& app = Application::GetInstance();
|
||
if (app.audio_prompt_.HasPrompts(kPromptWifiConfig)) {
|
||
app.audio_prompt_.PlayLocal(kPromptWifiConfig, app.audio_service_,
|
||
app.GetProtocol(), "wifi_config");
|
||
} else {
|
||
app.audio_service_.PlayConfigSound();
|
||
}
|
||
|
||
// Initialize WiFi STA mode (for scanning and connecting)
|
||
// Skip if WiFi was already initialized (e.g. timeout path from StartNetwork)
|
||
if (!wifi_initialized_) {
|
||
esp_netif_init();
|
||
esp_event_loop_create_default();
|
||
esp_netif_create_default_wifi_sta();
|
||
|
||
wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
|
||
esp_wifi_init(&cfg);
|
||
wifi_initialized_ = true;
|
||
}
|
||
esp_wifi_set_mode(WIFI_MODE_STA);
|
||
esp_wifi_start();
|
||
|
||
// Pre-scan WiFi networks BEFORE BLE starts. Once BLE is connected, running
|
||
// esp_wifi_scan_start on ESP32-S3 hangs the BLE notification path due to
|
||
// 2.4GHz radio coexistence contention — the scan completes but
|
||
// ble_gatts_notify_custom never delivers. Scanning while BLE is still off
|
||
// is fast and reliable; the cached result is returned on every BLE scan
|
||
// request from the miniprogram.
|
||
PreScanWifiForBleProv();
|
||
|
||
// Build BLE device name from MAC last 4 hex chars
|
||
std::string mac = SystemInfo::GetMacAddress();
|
||
std::string suffix = mac.substr(mac.length() - 5);
|
||
// Remove colon: "E:FF" -> "EEFF"
|
||
suffix.erase(std::remove(suffix.begin(), suffix.end(), ':'), suffix.end());
|
||
|
||
auto& ble = BleProv::GetInstance();
|
||
ble.SetDeviceName(suffix);
|
||
ble.SetDeviceInfo(SystemInfo::GetMacAddress(), SystemInfo::GetAppVersion());
|
||
|
||
// WiFi config callback: attempt connection when credentials received
|
||
// Uses raw ESP WiFi events (not WifiStation) since we init WiFi manually
|
||
ble.SetWifiConfigCallback([this](const std::string& ssid, const std::string& password) {
|
||
ESP_LOGI(TAG, "BLE: WiFi config received, ssid=%s", ssid.c_str());
|
||
|
||
// If password is empty, look up saved password from NVS
|
||
std::string actual_password = password;
|
||
if (actual_password.empty()) {
|
||
const auto& saved_list = SsidManager::GetInstance().GetSsidList();
|
||
for (const auto& item : saved_list) {
|
||
if (item.ssid == ssid) {
|
||
actual_password = item.password;
|
||
ESP_LOGI(TAG, "Using saved password for SSID: %s", ssid.c_str());
|
||
break;
|
||
}
|
||
}
|
||
}
|
||
|
||
// Create event group for WiFi connection result
|
||
static EventGroupHandle_t s_wifi_event_group = xEventGroupCreate();
|
||
static const int WIFI_CONNECTED_BIT = BIT0;
|
||
static const int WIFI_FAIL_BIT = BIT1;
|
||
|
||
xEventGroupClearBits(s_wifi_event_group, WIFI_CONNECTED_BIT | WIFI_FAIL_BIT);
|
||
|
||
// Register temporary event handlers for connection result
|
||
esp_event_handler_instance_t ip_handler;
|
||
esp_event_handler_instance_t wifi_handler;
|
||
|
||
esp_event_handler_instance_register(
|
||
IP_EVENT, IP_EVENT_STA_GOT_IP,
|
||
[](void* arg, esp_event_base_t, int32_t, void*) {
|
||
xEventGroupSetBits((EventGroupHandle_t)arg, BIT0);
|
||
}, s_wifi_event_group, &ip_handler);
|
||
|
||
esp_event_handler_instance_register(
|
||
WIFI_EVENT, WIFI_EVENT_STA_DISCONNECTED,
|
||
[](void* arg, esp_event_base_t, int32_t, void*) {
|
||
xEventGroupSetBits((EventGroupHandle_t)arg, BIT1);
|
||
}, s_wifi_event_group, &wifi_handler);
|
||
|
||
// Configure and connect
|
||
wifi_config_t wifi_config = {};
|
||
strncpy(reinterpret_cast<char*>(wifi_config.sta.ssid), ssid.c_str(),
|
||
sizeof(wifi_config.sta.ssid) - 1);
|
||
strncpy(reinterpret_cast<char*>(wifi_config.sta.password), actual_password.c_str(),
|
||
sizeof(wifi_config.sta.password) - 1);
|
||
|
||
esp_wifi_set_config(WIFI_IF_STA, &wifi_config);
|
||
esp_err_t err = esp_wifi_connect();
|
||
if (err != ESP_OK) {
|
||
ESP_LOGE(TAG, "WiFi connect call failed: %s", esp_err_to_name(err));
|
||
esp_event_handler_instance_unregister(IP_EVENT, IP_EVENT_STA_GOT_IP, ip_handler);
|
||
esp_event_handler_instance_unregister(WIFI_EVENT, WIFI_EVENT_STA_DISCONNECTED, wifi_handler);
|
||
BleProv::GetInstance().NotifyWifiResult(false, "unknown");
|
||
return;
|
||
}
|
||
|
||
// Wait for connection result (10 second timeout)
|
||
EventBits_t bits = xEventGroupWaitBits(s_wifi_event_group,
|
||
WIFI_CONNECTED_BIT | WIFI_FAIL_BIT, pdTRUE, pdFALSE, pdMS_TO_TICKS(10000));
|
||
|
||
// Unregister event handlers
|
||
esp_event_handler_instance_unregister(IP_EVENT, IP_EVENT_STA_GOT_IP, ip_handler);
|
||
esp_event_handler_instance_unregister(WIFI_EVENT, WIFI_EVENT_STA_DISCONNECTED, wifi_handler);
|
||
|
||
if (bits & WIFI_CONNECTED_BIT) {
|
||
ESP_LOGI(TAG, "WiFi connected via BLE provisioning");
|
||
SsidManager::GetInstance().AddSsid(ssid, actual_password);
|
||
BleProv::GetInstance().NotifyWifiResult(true, "");
|
||
// 配网成功提示音(异步入解码队列;WS 还未建立,protocol=nullptr)
|
||
auto& app = Application::GetInstance();
|
||
if (app.audio_prompt_.HasPrompts(kPromptWifiSuccess)) {
|
||
app.audio_prompt_.PlayLocal(kPromptWifiSuccess, app.audio_service_,
|
||
/*protocol=*/nullptr, "wifi_success");
|
||
}
|
||
} else {
|
||
ESP_LOGW(TAG, "WiFi connection failed via BLE provisioning");
|
||
esp_wifi_disconnect();
|
||
std::string error = (bits & WIFI_FAIL_BIT) ? "password_wrong" : "timeout";
|
||
BleProv::GetInstance().NotifyWifiResult(false, error);
|
||
}
|
||
});
|
||
|
||
// Reboot callback
|
||
ble.SetRebootCallback([]() {
|
||
ESP_LOGI(TAG, "BLE: Reboot requested, waiting for wifi_success prompt to finish");
|
||
auto& app = Application::GetInstance();
|
||
// wifi_success.ogg 约 1.2s,刚才 PlayLocal 异步入队,必须等它播完再重启,
|
||
// 否则 esp_restart 会把解码队列连同 I2S DMA 一起切掉。3s 兜底超时。
|
||
app.audio_service_.WaitForPlaybackComplete(3000);
|
||
app.audio_service_.PlayBootSound();
|
||
vTaskDelay(pdMS_TO_TICKS(500));
|
||
esp_restart();
|
||
});
|
||
|
||
ble.Start();
|
||
ESP_LOGI(TAG, "BLE provisioning started, waiting for connection...");
|
||
|
||
// Block waiting for provisioning (device reboots after success)
|
||
while (true) {
|
||
vTaskDelay(pdMS_TO_TICKS(1000));
|
||
}
|
||
}
|
||
|
||
void WifiBoard::PreScanWifiForBleProv()
|
||
{
|
||
ESP_LOGI(TAG, "Pre-scanning WiFi (BLE not active yet)...");
|
||
|
||
// Give the WiFi driver a moment to finish STA start before the scan
|
||
vTaskDelay(pdMS_TO_TICKS(300));
|
||
|
||
wifi_scan_config_t scan_config = {};
|
||
scan_config.show_hidden = false;
|
||
scan_config.scan_type = WIFI_SCAN_TYPE_ACTIVE;
|
||
scan_config.scan_time.active.min = 80;
|
||
scan_config.scan_time.active.max = 150;
|
||
|
||
// Try up to twice — first attempt sometimes returns 0 if WiFi STA is
|
||
// still settling.
|
||
std::vector<BleProvWifiNetwork> networks;
|
||
for (int attempt = 0; attempt < 2 && networks.empty(); attempt++) {
|
||
if (attempt > 0) {
|
||
ESP_LOGW(TAG, "Pre-scan attempt %d returned 0 networks, retrying", attempt);
|
||
vTaskDelay(pdMS_TO_TICKS(500));
|
||
}
|
||
|
||
esp_err_t err = esp_wifi_scan_start(&scan_config, true);
|
||
if (err != ESP_OK) {
|
||
ESP_LOGW(TAG, "Pre-scan start failed: %s", esp_err_to_name(err));
|
||
continue;
|
||
}
|
||
|
||
uint16_t ap_count = 0;
|
||
esp_wifi_scan_get_ap_num(&ap_count);
|
||
if (ap_count > 20) ap_count = 20;
|
||
|
||
std::vector<wifi_ap_record_t> ap_records(ap_count);
|
||
if (ap_count > 0) {
|
||
esp_wifi_scan_get_ap_records(&ap_count, ap_records.data());
|
||
}
|
||
|
||
for (int i = 0; i < ap_count; i++) {
|
||
BleProvWifiNetwork net;
|
||
net.ssid = std::string(reinterpret_cast<char*>(ap_records[i].ssid));
|
||
net.rssi = ap_records[i].rssi;
|
||
net.auth = static_cast<int>(ap_records[i].authmode);
|
||
if (!net.ssid.empty()) {
|
||
networks.push_back(net);
|
||
}
|
||
}
|
||
}
|
||
|
||
std::sort(networks.begin(), networks.end(),
|
||
[](const BleProvWifiNetwork& a, const BleProvWifiNetwork& b) {
|
||
return a.rssi > b.rssi;
|
||
});
|
||
if (networks.size() > 8) {
|
||
networks.resize(8);
|
||
}
|
||
|
||
ESP_LOGI(TAG, "Pre-scan complete, %d networks", static_cast<int>(networks.size()));
|
||
BleProv::GetInstance().SetCachedNetworks(networks);
|
||
}
|
||
|
||
// Legacy WiFi AP provisioning (kept for fallback)
|
||
void WifiBoard::EnterWifiConfigMode()
|
||
{
|
||
wifi_config_mode_ = true;
|
||
ESP_LOGI(TAG, "Entering WiFi configuration mode (AP) [legacy]");
|
||
|
||
// Play wifi config prompt (OGG, async — don't block AP startup)
|
||
auto& app = Application::GetInstance();
|
||
if (app.audio_prompt_.HasPrompts(kPromptWifiConfig)) {
|
||
app.audio_prompt_.PlayRandom(kPromptWifiConfig, app.audio_service_);
|
||
} else {
|
||
app.audio_service_.PlayConfigSound();
|
||
}
|
||
|
||
auto& ap = WifiConfigurationAp::GetInstance();
|
||
ap.SetSsidPrefix("播乐");
|
||
ap.SetLanguage("zh-CN");
|
||
|
||
ap.SetConfigSuccessCallback([]() {
|
||
ESP_LOGI(TAG, "WiFi configured successfully, restarting...");
|
||
Application::GetInstance().audio_service_.PlayBootSound();
|
||
vTaskDelay(pdMS_TO_TICKS(1000));
|
||
esp_restart();
|
||
});
|
||
|
||
ap.Start();
|
||
|
||
ESP_LOGI(TAG, "AP mode started, SSID: %s, URL: %s",
|
||
ap.GetSsid().c_str(), ap.GetWebServerUrl().c_str());
|
||
|
||
while (true) {
|
||
vTaskDelay(pdMS_TO_TICKS(1000));
|
||
}
|
||
}
|
||
//2026-6-24 ckkj debug
|
||
void WifiBoard::StopNetwork()
|
||
{
|
||
ESP_LOGI(TAG, "Stopping WiFi");
|
||
esp_wifi_stop();
|
||
}
|