430 lines
15 KiB
C++
430 lines
15 KiB
C++
#include "connectivity/connectivity_manager.h"
|
||
|
||
#include "core/playback_types.h"
|
||
|
||
#include <cstring>
|
||
|
||
#include <esp_err.h>
|
||
#include <esp_heap_caps.h>
|
||
#include <esp_log.h>
|
||
#include <esp_random.h>
|
||
|
||
namespace borla {
|
||
namespace {
|
||
|
||
constexpr const char* kTag = "Connectivity2";
|
||
constexpr uint16_t kLocalConnectRequestFailure = 0xFFFE;
|
||
//2026-9-6 ckkj add: DualNetworkTransport 主动切网断开 WiFi 的标记 reason。
|
||
constexpr uint16_t kBearerswitchReason = 0xF101;
|
||
ConnectivityPhase ToPhase(ConnectivityPolicyState state)
|
||
{
|
||
switch (state) {
|
||
case ConnectivityPolicyState::kStopped:
|
||
return ConnectivityPhase::kStopped;
|
||
case ConnectivityPolicyState::kCredentialsMissing:
|
||
return ConnectivityPhase::kCredentialsMissing;
|
||
case ConnectivityPolicyState::kStartingTransport:
|
||
return ConnectivityPhase::kStartingTransport;
|
||
case ConnectivityPolicyState::kConnecting:
|
||
return ConnectivityPhase::kConnecting;
|
||
case ConnectivityPolicyState::kWaitingRetry:
|
||
return ConnectivityPhase::kWaitingRetry;
|
||
case ConnectivityPolicyState::kOnline:
|
||
return ConnectivityPhase::kOnline;
|
||
}
|
||
return ConnectivityPhase::kStopped;
|
||
}
|
||
|
||
} // namespace
|
||
|
||
ConnectivityManager::ConnectivityManager(IWifiTransport& transport,
|
||
IWifiCredentialStore& credentials, ReconnectBackoffConfig retry_config)
|
||
: transport_(transport)
|
||
, credential_store_(credentials)
|
||
, policy_(retry_config)
|
||
{
|
||
}
|
||
|
||
bool ConnectivityManager::Initialize()
|
||
{
|
||
if (initialized_) {
|
||
return true;
|
||
}
|
||
|
||
queue_ = xQueueCreateStatic(kQueueDepth, sizeof(ManagerEvent),
|
||
queue_storage_.data(), &queue_control_);
|
||
if (queue_ == nullptr) {
|
||
ESP_LOGE(kTag, "manager queue creation failed");
|
||
return false;
|
||
}
|
||
stop_completed_ = xSemaphoreCreateBinaryStatic(&stop_completed_control_);
|
||
if (stop_completed_ == nullptr) {
|
||
ESP_LOGE(kTag, "stop completion semaphore creation failed");
|
||
return false;
|
||
}
|
||
|
||
const esp_timer_create_args_t timer_args = {
|
||
.callback = &ConnectivityManager::RetryTimerCallback,
|
||
.arg = this,
|
||
.dispatch_method = ESP_TIMER_TASK,
|
||
.name = "wifi_retry2",
|
||
.skip_unhandled_events = true,
|
||
};
|
||
const esp_err_t timer_result = esp_timer_create(&timer_args, &retry_timer_);
|
||
if (timer_result != ESP_OK) {
|
||
ESP_LOGE(kTag, "retry timer creation failed: %s",
|
||
esp_err_to_name(timer_result));
|
||
return false;
|
||
}
|
||
|
||
const BaseType_t task_result = xTaskCreate(&ConnectivityManager::TaskEntry,
|
||
"connectivity2", task_stack_budget::kConnectivityManagerBytes, this,
|
||
kTaskPriority, &task_);
|
||
if (task_result != pdPASS) {
|
||
task_ = nullptr;
|
||
ESP_LOGE(kTag, "manager task creation failed");
|
||
esp_timer_delete(retry_timer_);
|
||
retry_timer_ = nullptr;
|
||
return false;
|
||
}
|
||
|
||
initialized_ = true;
|
||
ESP_LOGI(kTag,
|
||
"manager initialized queue=%u stack_bytes=%u memory=internal",
|
||
static_cast<unsigned>(kQueueDepth),
|
||
static_cast<unsigned>(task_stack_budget::kConnectivityManagerBytes));
|
||
return true;
|
||
}
|
||
|
||
void ConnectivityManager::Start()
|
||
{
|
||
// 2026-9-7 ckkj add: BLE 好友模式挂起期间忽略启动请求,
|
||
// 否则重连效果会把 WiFi 驱动拉起来与 BT 控制器抢占内部 RAM。
|
||
if (ble_suspended_.load()) {
|
||
ESP_LOGW(kTag, "start ignored: suspended for BLE friend mode");
|
||
return;
|
||
}/////end
|
||
if (!Post({ ManagerEventType::kStart, 0 })) {
|
||
ESP_LOGE(kTag, "failed to enqueue start");
|
||
}
|
||
}
|
||
|
||
// 2026-9-7 ckkj add: BLE 好友模式启动前静默挂起网络。BT 控制器需要 ~65KB
|
||
// 内部 RAM,与已初始化的 WiFi 驱动无法共存:上次三击好友模式 BLE_INIT
|
||
// "Malloc failed" 后在 controller 内部 r_co_list_pop_front 直接 panic,
|
||
// 错误检查来不及执行,唯一可靠手段是启动前腾出内存。Stop() 是同步的且
|
||
// policy_.Stop() 会经 kStopTransport → DualNetworkTransport →
|
||
// wifi_.ReleaseDriver() 拆除驱动,且不发布断开事件(静默);随后再显式
|
||
// 兑底拆一次驱动(幂等),返回时 BLE 可用内存已就绪。
|
||
void ConnectivityManager::SuspendForBle()
|
||
{
|
||
bool expected = false;
|
||
if (!ble_suspended_.compare_exchange_strong(expected, true)) {
|
||
return;
|
||
}
|
||
Stop();
|
||
transport_.ReleaseDriver();
|
||
online_.store(false);
|
||
ESP_LOGI(kTag, "network suspended for BLE internal_free=%u 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)));
|
||
}
|
||
|
||
// 好友模式结束(配对成功/失败/超时)后恢复正常重连。BleFriendExchange
|
||
// 在 nimble_port_deinit() 释放 BT 内存之后才回调,此处再拉起 WiFi 安全。
|
||
void ConnectivityManager::ResumeAfterBle()
|
||
{
|
||
bool expected = true;
|
||
if (!ble_suspended_.compare_exchange_strong(expected, false)) {
|
||
return;
|
||
}
|
||
ESP_LOGI(kTag, "network resume after BLE");
|
||
Start();
|
||
}/////add end
|
||
|
||
void ConnectivityManager::Stop()
|
||
{
|
||
if (!initialized_ || stop_completed_ == nullptr) {
|
||
return;
|
||
}
|
||
xSemaphoreTake(stop_completed_, 0);
|
||
if (!Post({ ManagerEventType::kStop, 0 })) {
|
||
ESP_LOGE(kTag, "failed to enqueue stop");
|
||
return;
|
||
}
|
||
// Handling kStop calls DualNetworkTransport::Stop(), which itself waits up
|
||
// to 5 s for its own worker. The outer wait must outlast that, otherwise a
|
||
// slow-but-successful stop always reports a bogus timeout here.
|
||
if (xSemaphoreTake(stop_completed_, pdMS_TO_TICKS(8000)) != pdTRUE) {
|
||
ESP_LOGE(kTag, "timed out waiting for WiFi transport stop");
|
||
}
|
||
}
|
||
|
||
void ConnectivityManager::SwitchNetwork()
|
||
{
|
||
if (!transport_.RequestNetworkSwitch()) {
|
||
ESP_LOGW(kTag, "active transport does not support network switch");
|
||
}
|
||
}
|
||
|
||
ConnectivityDiagnostics ConnectivityManager::GetDiagnostics() const
|
||
{
|
||
portENTER_CRITICAL(&diagnostics_lock_);
|
||
const ConnectivityDiagnostics snapshot = diagnostics_;
|
||
portEXIT_CRITICAL(&diagnostics_lock_);
|
||
return snapshot;
|
||
}
|
||
|
||
void ConnectivityManager::OnWifiTransportEvent(const WifiTransportEvent& event)
|
||
{
|
||
ManagerEvent manager_event;
|
||
switch (event.type) {
|
||
case WifiTransportEventType::kStarted:
|
||
manager_event.type = ManagerEventType::kTransportReady;
|
||
break;
|
||
case WifiTransportEventType::kGotIp:
|
||
manager_event.type = ManagerEventType::kGotIp;
|
||
break;
|
||
case WifiTransportEventType::kDisconnected:
|
||
manager_event.type = ManagerEventType::kDisconnected;
|
||
manager_event.disconnect_reason = event.disconnect_reason;
|
||
break;
|
||
case WifiTransportEventType::kReconnectRequested:
|
||
manager_event.type = ManagerEventType::kRetryNow;
|
||
break;
|
||
case WifiTransportEventType::kCellularOn:
|
||
PublishAppEvent(AppEvent::Make(AppEventType::kLocalPromptRequested, 0,
|
||
static_cast<int32_t>(LocalPrompt::kNet4gOn),
|
||
static_cast<uint32_t>(PlaybackPriority::kSystem)));
|
||
return;
|
||
case WifiTransportEventType::kCellularOff:
|
||
PublishAppEvent(AppEvent::Make(AppEventType::kLocalPromptRequested, 0,
|
||
static_cast<int32_t>(LocalPrompt::kNet4gOff),
|
||
static_cast<uint32_t>(PlaybackPriority::kSystem)));
|
||
return;
|
||
case WifiTransportEventType::kCellularUnavailable:
|
||
PublishAppEvent(AppEvent::Make(AppEventType::kLocalPromptRequested, 0,
|
||
static_cast<int32_t>(LocalPrompt::kNet4gNoWifi),
|
||
static_cast<uint32_t>(PlaybackPriority::kSystem)));
|
||
return;
|
||
case WifiTransportEventType::kCellularBootOn:
|
||
PublishAppEvent(AppEvent::Make(AppEventType::kLocalPromptRequested, 0,
|
||
static_cast<int32_t>(LocalPrompt::kNet4gBootOn),
|
||
static_cast<uint32_t>(PlaybackPriority::kSystem)));
|
||
return;
|
||
}
|
||
if (!Post(manager_event)) {
|
||
ESP_LOGE(kTag, "transport event queue full type=%u",
|
||
static_cast<unsigned>(event.type));
|
||
}
|
||
}
|
||
|
||
void ConnectivityManager::TaskEntry(void* context)
|
||
{
|
||
static_cast<ConnectivityManager*>(context)->Run();
|
||
}
|
||
|
||
void ConnectivityManager::RetryTimerCallback(void* context)
|
||
{
|
||
auto* self = static_cast<ConnectivityManager*>(context);
|
||
if (!self->Post({ ManagerEventType::kRetryElapsed, 0 })) {
|
||
ESP_LOGE(kTag, "retry timer event queue full");
|
||
}
|
||
}
|
||
|
||
bool ConnectivityManager::Post(const ManagerEvent& event)
|
||
{
|
||
return initialized_ && queue_ != nullptr
|
||
&& xQueueSend(queue_, &event, 0) == pdTRUE;
|
||
}
|
||
|
||
[[noreturn]] void ConnectivityManager::Run()
|
||
{
|
||
ESP_LOGI(kTag, "manager task started");
|
||
while (true) {
|
||
ManagerEvent event;
|
||
if (xQueueReceive(queue_, &event, portMAX_DELAY) == pdTRUE) {
|
||
Handle(event);
|
||
}
|
||
}
|
||
}
|
||
|
||
void ConnectivityManager::Handle(const ManagerEvent& event)
|
||
{
|
||
ConnectivityPolicyResult result;
|
||
switch (event.type) {
|
||
case ManagerEventType::kStart:
|
||
if (policy_.state() == ConnectivityPolicyState::kStopped) {
|
||
credentials_.fill(WifiCredential {});
|
||
credential_count_ = credential_store_.Load(
|
||
credentials_.data(), credentials_.size());
|
||
}
|
||
result = policy_.Start(credential_count_);
|
||
break;
|
||
case ManagerEventType::kStop:
|
||
result = policy_.Stop();
|
||
break;
|
||
case ManagerEventType::kTransportReady:
|
||
result = policy_.OnTransportReady();
|
||
break;
|
||
case ManagerEventType::kTransportStartFailed:
|
||
result = policy_.OnTransportStartFailed(esp_random());
|
||
break;
|
||
case ManagerEventType::kGotIp:
|
||
result = policy_.OnGotIp();
|
||
break;
|
||
case ManagerEventType::kDisconnected:
|
||
//result = policy_.OnDisconnected(event.disconnect_reason, esp_random());
|
||
//2026-9-6 ckkj add: 0xF101 是切网动作主动断开 WiFi,非故障,
|
||
//不触发 WiFi 自动重试,避免与 4G 启动抢内部 RAM 导致 PPP UART 安装失败。
|
||
if (event.disconnect_reason != kBearerswitchReason) {
|
||
result = policy_.OnDisconnected(event.disconnect_reason, esp_random());
|
||
}
|
||
break;
|
||
case ManagerEventType::kRetryElapsed:
|
||
result = policy_.OnRetryElapsed();
|
||
break;
|
||
case ManagerEventType::kRetryNow:
|
||
if (retry_timer_ != nullptr) {
|
||
const esp_err_t stop_result = esp_timer_stop(retry_timer_);
|
||
if (stop_result != ESP_OK && stop_result != ESP_ERR_INVALID_STATE) {
|
||
ESP_LOGW(kTag, "immediate retry timer cancel failed: %s",
|
||
esp_err_to_name(stop_result));
|
||
}
|
||
}
|
||
result = policy_.OnRetryElapsed();
|
||
break;
|
||
}
|
||
Execute(result);
|
||
RefreshDiagnostics();
|
||
if (event.type == ManagerEventType::kStop && stop_completed_ != nullptr) {
|
||
xSemaphoreGive(stop_completed_);
|
||
}
|
||
}
|
||
|
||
void ConnectivityManager::Execute(const ConnectivityPolicyResult& result)
|
||
{
|
||
for (size_t index = 0; index < result.action_count; ++index) {
|
||
Execute(result.actions[index]);
|
||
}
|
||
}
|
||
|
||
void ConnectivityManager::Execute(const ConnectivityAction& action)
|
||
{
|
||
switch (action.type) {
|
||
case ConnectivityActionType::kStartTransport:
|
||
if (!transport_.Start(*this)) {
|
||
Post({ ManagerEventType::kTransportStartFailed, 0 });
|
||
}
|
||
return;
|
||
case ConnectivityActionType::kStopTransport:
|
||
transport_.Stop();
|
||
return;
|
||
case ConnectivityActionType::kConnectCredential:
|
||
if (action.credential_index >= credential_count_
|
||
|| !transport_.Connect(credentials_[action.credential_index])) {
|
||
Post({
|
||
ManagerEventType::kDisconnected,
|
||
kLocalConnectRequestFailure,
|
||
});
|
||
}
|
||
return;
|
||
case ConnectivityActionType::kScheduleRetry: {
|
||
if (retry_timer_ == nullptr) {
|
||
return;
|
||
}
|
||
const esp_err_t stop_result = esp_timer_stop(retry_timer_);
|
||
if (stop_result != ESP_OK && stop_result != ESP_ERR_INVALID_STATE) {
|
||
ESP_LOGW(kTag, "retry timer stop failed: %s",
|
||
esp_err_to_name(stop_result));
|
||
}
|
||
const esp_err_t start_result = esp_timer_start_once(
|
||
retry_timer_, static_cast<uint64_t>(action.delay_ms) * 1000ULL);
|
||
if (start_result != ESP_OK) {
|
||
ESP_LOGE(kTag, "retry timer start failed delay=%lu: %s",
|
||
static_cast<unsigned long>(action.delay_ms),
|
||
esp_err_to_name(start_result));
|
||
} else {
|
||
ESP_LOGI(kTag, "retry scheduled delay=%lu ms attempt=%lu",
|
||
static_cast<unsigned long>(action.delay_ms),
|
||
static_cast<unsigned long>(policy_.retry_attempt_count()));
|
||
}
|
||
return;
|
||
}
|
||
case ConnectivityActionType::kCancelRetry:
|
||
if (retry_timer_ != nullptr) {
|
||
const esp_err_t result = esp_timer_stop(retry_timer_);
|
||
if (result != ESP_OK && result != ESP_ERR_INVALID_STATE) {
|
||
ESP_LOGW(kTag, "retry timer cancel failed: %s",
|
||
esp_err_to_name(result));
|
||
}
|
||
}
|
||
return;
|
||
case ConnectivityActionType::kPublishConnected: {
|
||
const WifiLinkInfo link = transport_.GetLinkInfo();
|
||
ESP_LOGI(kTag, "online ssid=%s ip=%s rssi=%d channel=%u",
|
||
link.ssid.data(), link.ipv4.data(), static_cast<int>(link.rssi_dbm),
|
||
static_cast<unsigned>(link.channel));
|
||
PublishAppEvent(AppEvent::Make(
|
||
AppEventType::kNetworkConnected, 0, link.rssi_dbm, link.channel));
|
||
return;
|
||
}
|
||
case ConnectivityActionType::kPublishDisconnected:
|
||
ESP_LOGW(kTag, "offline reason=%u",
|
||
static_cast<unsigned>(action.disconnect_reason));
|
||
PublishAppEvent(AppEvent::Make(
|
||
AppEventType::kNetworkDisconnected, 0, action.disconnect_reason));
|
||
if (remote_behavior_config_ != nullptr) {
|
||
PublishAppEvent(
|
||
AppEvent::Make(AppEventType::kLocalPromptRequested, 0,
|
||
static_cast<int32_t>(
|
||
remote_behavior_config_->NoNetworkPrompt()),
|
||
static_cast<uint32_t>(PlaybackPriority::kSystem)));
|
||
}
|
||
return;
|
||
case ConnectivityActionType::kRequestProvisioning:
|
||
ESP_LOGW(kTag, "no saved WiFi credentials; provisioning requested");
|
||
PublishAppEvent(AppEvent::Make(AppEventType::kProvisioningRequested));
|
||
return;
|
||
}
|
||
}
|
||
|
||
void ConnectivityManager::RefreshDiagnostics()
|
||
{
|
||
const WifiLinkInfo link = transport_.GetLinkInfo();
|
||
ConnectivityDiagnostics next;
|
||
next.phase = ToPhase(policy_.state());
|
||
next.online = policy_.state() == ConnectivityPolicyState::kOnline;
|
||
next.rssi_dbm = link.rssi_dbm;
|
||
next.channel = link.channel;
|
||
next.last_disconnect_reason = policy_.last_disconnect_reason() != 0
|
||
? policy_.last_disconnect_reason()
|
||
: link.last_disconnect_reason;
|
||
next.retry_attempt_count = policy_.retry_attempt_count();
|
||
next.active_credential_index = policy_.credential_index();
|
||
next.credential_count = policy_.credential_count();
|
||
next.ssid = link.ssid;
|
||
next.ipv4 = link.ipv4;
|
||
|
||
portENTER_CRITICAL(&diagnostics_lock_);
|
||
diagnostics_ = next;
|
||
portEXIT_CRITICAL(&diagnostics_lock_);
|
||
online_.store(next.online);
|
||
}
|
||
|
||
void ConnectivityManager::PublishAppEvent(const AppEvent& event)
|
||
{
|
||
if (publisher_ == nullptr) {
|
||
ESP_LOGE(
|
||
kTag, "event publisher unavailable event=%s", ToString(event.type));
|
||
return;
|
||
}
|
||
if (!publisher_->Publish(event)) {
|
||
ESP_LOGE(
|
||
kTag, "application event rejected event=%s", ToString(event.type));
|
||
}
|
||
}
|
||
|
||
} // namespace borla
|