bolar_2 backup

This commit is contained in:
2026-11-27 16:38:11 +08:00
commit e96d6d19df
305 changed files with 43350 additions and 0 deletions

View File

@@ -0,0 +1,59 @@
#pragma once
#include <array>
#include <cstddef>
#include <cstdint>
namespace borla {
inline constexpr size_t kCellularIpv4Capacity = 16;
inline constexpr size_t kCellularImeiCapacity = 24;
inline constexpr size_t kCellularOperatorCapacity = 32;
enum class CellularTransportEventType : uint8_t {
kStarted,
kGotIp,
kDisconnected,
};
struct CellularTransportEvent {
CellularTransportEventType type = CellularTransportEventType::kStarted;
uint16_t reason = 0;
};
struct CellularLinkInfo {
bool modem_present = false;
bool registered = false;
bool online = false;
int8_t csq = -1;
uint8_t registration_status = 0;
std::array<char, kCellularIpv4Capacity> ipv4{};
std::array<char, kCellularImeiCapacity> imei{};
std::array<char, kCellularOperatorCapacity> operator_name{};
};
class ICellularTransportObserver {
public:
virtual ~ICellularTransportObserver() = default;
virtual void OnCellularTransportEvent(
const CellularTransportEvent& event) = 0;
};
//2026-9-9 ckkj add: 新增探测结果枚举,用于表示模块是否在位
enum class CellularProbeResult : uint8_t {
kPresent,
kAbsent,
// 探测本身没能执行(如内部 RAM 不足装不下探测 UART),不代表模块不在位。
kUnknown,
};
class ICellularTransport {
public:
virtual ~ICellularTransport() = default;
virtual bool Start(ICellularTransportObserver& observer) = 0;
virtual void Stop() = 0;
//virtual bool ProbePresent() = 0;
virtual CellularProbeResult ProbePresent() = 0;
virtual CellularLinkInfo GetLinkInfo() const = 0;
};
} // namespace borla

View File

@@ -0,0 +1,429 @@
#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

View File

@@ -0,0 +1,107 @@
#pragma once
#include "connectivity/connectivity_policy.h"
#include "connectivity/wifi_credential_store.h"
#include "connectivity/wifi_transport.h"
#include "core/task_stack_budget.h"
#include "ports/connectivity_manager.h"
#include "ports/event_publisher.h"
#include "ports/remote_behavior_config.h"
#include <array>
#include <atomic>
#include <cstddef>
#include <cstdint>
#include <esp_timer.h>
#include <freertos/FreeRTOS.h>
#include <freertos/portmacro.h>
#include <freertos/queue.h>
#include <freertos/semphr.h>
#include <freertos/task.h>
namespace borla {
class ConnectivityManager final : public IConnectivityManager,
public IWifiTransportObserver {
public:
ConnectivityManager(IWifiTransport& transport,
IWifiCredentialStore& credentials, ReconnectBackoffConfig retry_config);
bool Initialize();
void SetEventPublisher(IEventPublisher* publisher)
{
publisher_ = publisher;
}
void SetRemoteBehaviorConfig(IRemoteBehaviorConfig* config)
{
remote_behavior_config_ = config;
}
void Start() override;
void Stop() override;
void SwitchNetwork() override;
// 2026-9-7 ckkj add: BLE 好友模式前后静默挂起/恢复网络,释放 WiFi 驱动内存。
void SuspendForBle() override;
void ResumeAfterBle() override;//////////
bool IsOnline() const override { return online_.load(); }
ConnectivityDiagnostics GetDiagnostics() const override;
void OnWifiTransportEvent(const WifiTransportEvent& event) override;
private:
enum class ManagerEventType : uint8_t {
kStart,
kStop,
kTransportReady,
kTransportStartFailed,
kGotIp,
kDisconnected,
kRetryElapsed,
kRetryNow,
};
struct ManagerEvent {
ManagerEventType type = ManagerEventType::kStart;
uint16_t disconnect_reason = 0;
};
static constexpr size_t kQueueDepth = 24;
static constexpr UBaseType_t kTaskPriority = 4;
static void TaskEntry(void* context);
static void RetryTimerCallback(void* context);
bool Post(const ManagerEvent& event);
[[noreturn]] void Run();
void Handle(const ManagerEvent& event);
void Execute(const ConnectivityPolicyResult& result);
void Execute(const ConnectivityAction& action);
void RefreshDiagnostics();
void PublishAppEvent(const AppEvent& event);
IWifiTransport& transport_;
IWifiCredentialStore& credential_store_;
ConnectivityPolicy policy_;
IEventPublisher* publisher_ = nullptr;
IRemoteBehaviorConfig* remote_behavior_config_ = nullptr;
std::array<WifiCredential, kMaxSavedWifiCredentials> credentials_ {};
size_t credential_count_ = 0;
QueueHandle_t queue_ = nullptr;
StaticQueue_t queue_control_ {};
alignas(ManagerEvent) std::array<uint8_t,
kQueueDepth * sizeof(ManagerEvent)> queue_storage_ {};
TaskHandle_t task_ = nullptr;
SemaphoreHandle_t stop_completed_ = nullptr;
StaticSemaphore_t stop_completed_control_ {};
esp_timer_handle_t retry_timer_ = nullptr;
bool initialized_ = false;
std::atomic<bool> online_ { false };
std::atomic<bool> ble_suspended_ { false };//2026-9-7 ckkj add
mutable portMUX_TYPE diagnostics_lock_ = portMUX_INITIALIZER_UNLOCKED;
ConnectivityDiagnostics diagnostics_ {};
};
} // namespace borla

View File

@@ -0,0 +1,164 @@
#include "connectivity/connectivity_policy.h"
namespace borla {
namespace {
ConnectivityAction Action(ConnectivityActionType type)
{
ConnectivityAction action;
action.type = type;
return action;
}
} // namespace
ConnectivityPolicy::ConnectivityPolicy(ReconnectBackoffConfig config)
: backoff_(config)
{
}
ConnectivityPolicyResult ConnectivityPolicy::Start(size_t credential_count)
{
ConnectivityPolicyResult result;
if (state_ != ConnectivityPolicyState::kStopped) {
return result;
}
credential_count_ = credential_count;
credential_index_ = 0;
last_disconnect_reason_ = 0;
transport_ready_ = false;
backoff_.Reset();
if (credential_count_ == 0) {
state_ = ConnectivityPolicyState::kCredentialsMissing;
result.Add(Action(ConnectivityActionType::kRequestProvisioning));
return result;
}
state_ = ConnectivityPolicyState::kStartingTransport;
result.Add(Action(ConnectivityActionType::kStartTransport));
return result;
}
ConnectivityPolicyResult ConnectivityPolicy::Stop()
{
ConnectivityPolicyResult result;
if (state_ == ConnectivityPolicyState::kStopped) {
return result;
}
result.Add(Action(ConnectivityActionType::kCancelRetry));
result.Add(Action(ConnectivityActionType::kStopTransport));
state_ = ConnectivityPolicyState::kStopped;
credential_count_ = 0;
credential_index_ = 0;
last_disconnect_reason_ = 0;
transport_ready_ = false;
backoff_.Reset();
return result;
}
ConnectivityPolicyResult ConnectivityPolicy::OnTransportReady()
{
ConnectivityPolicyResult result;
if (state_ != ConnectivityPolicyState::kStartingTransport ||
credential_count_ == 0) {
return result;
}
transport_ready_ = true;
state_ = ConnectivityPolicyState::kConnecting;
ConnectivityAction connect =
Action(ConnectivityActionType::kConnectCredential);
connect.credential_index = credential_index_;
result.Add(connect);
return result;
}
ConnectivityPolicyResult ConnectivityPolicy::OnTransportStartFailed(
uint32_t entropy)
{
if (state_ != ConnectivityPolicyState::kStartingTransport) {
return {};
}
transport_ready_ = false;
return ScheduleRetry(false, 0, entropy);
}
ConnectivityPolicyResult ConnectivityPolicy::OnDisconnected(
uint16_t reason,
uint32_t entropy)
{
if (state_ == ConnectivityPolicyState::kStopped ||
state_ == ConnectivityPolicyState::kCredentialsMissing ||
state_ == ConnectivityPolicyState::kWaitingRetry) {
return {};
}
const bool was_online = state_ == ConnectivityPolicyState::kOnline;
if (credential_count_ > 0) {
credential_index_ = (credential_index_ + 1U) % credential_count_;
}
return ScheduleRetry(was_online, reason, entropy);
}
ConnectivityPolicyResult ConnectivityPolicy::OnRetryElapsed()
{
ConnectivityPolicyResult result;
if (state_ != ConnectivityPolicyState::kWaitingRetry) {
return result;
}
if (!transport_ready_) {
state_ = ConnectivityPolicyState::kStartingTransport;
result.Add(Action(ConnectivityActionType::kStartTransport));
return result;
}
state_ = ConnectivityPolicyState::kConnecting;
ConnectivityAction connect =
Action(ConnectivityActionType::kConnectCredential);
connect.credential_index = credential_index_;
result.Add(connect);
return result;
}
ConnectivityPolicyResult ConnectivityPolicy::OnGotIp()
{
ConnectivityPolicyResult result;
if (state_ != ConnectivityPolicyState::kConnecting) {
return result;
}
state_ = ConnectivityPolicyState::kOnline;
backoff_.Reset();
result.Add(Action(ConnectivityActionType::kCancelRetry));
result.Add(Action(ConnectivityActionType::kPublishConnected));
return result;
}
ConnectivityPolicyResult ConnectivityPolicy::ScheduleRetry(
bool publish_disconnected,
uint16_t reason,
uint32_t entropy)
{
ConnectivityPolicyResult result;
state_ = ConnectivityPolicyState::kWaitingRetry;
last_disconnect_reason_ = reason;
if (publish_disconnected) {
ConnectivityAction disconnected =
Action(ConnectivityActionType::kPublishDisconnected);
disconnected.disconnect_reason = reason;
result.Add(disconnected);
}
ConnectivityAction schedule =
Action(ConnectivityActionType::kScheduleRetry);
schedule.delay_ms = backoff_.NextDelayMs(entropy);
result.Add(schedule);
return result;
}
} // namespace borla

View File

@@ -0,0 +1,94 @@
#pragma once
#include "connectivity/reconnect_backoff.h"
#include <array>
#include <cstddef>
#include <cstdint>
namespace borla {
enum class ConnectivityPolicyState : uint8_t {
kStopped,
kCredentialsMissing,
kStartingTransport,
kConnecting,
kWaitingRetry,
kOnline,
};
enum class ConnectivityActionType : uint8_t {
kStartTransport,
kStopTransport,
kConnectCredential,
kScheduleRetry,
kCancelRetry,
kPublishConnected,
kPublishDisconnected,
kRequestProvisioning,
};
struct ConnectivityAction {
ConnectivityActionType type = ConnectivityActionType::kStartTransport;
size_t credential_index = 0;
uint32_t delay_ms = 0;
uint16_t disconnect_reason = 0;
};
struct ConnectivityPolicyResult {
std::array<ConnectivityAction, 4> actions{};
size_t action_count = 0;
bool Add(const ConnectivityAction& action)
{
if (action_count >= actions.size()) {
return false;
}
actions[action_count++] = action;
return true;
}
};
class ConnectivityPolicy final {
public:
explicit ConnectivityPolicy(
ReconnectBackoffConfig config = ReconnectBackoffConfig{});
ConnectivityPolicyResult Start(size_t credential_count);
ConnectivityPolicyResult Stop();
ConnectivityPolicyResult OnTransportReady();
ConnectivityPolicyResult OnTransportStartFailed(uint32_t entropy);
ConnectivityPolicyResult OnDisconnected(
uint16_t reason,
uint32_t entropy);
ConnectivityPolicyResult OnRetryElapsed();
ConnectivityPolicyResult OnGotIp();
ConnectivityPolicyState state() const { return state_; }
size_t credential_count() const { return credential_count_; }
size_t credential_index() const { return credential_index_; }
uint16_t last_disconnect_reason() const
{
return last_disconnect_reason_;
}
uint32_t retry_attempt_count() const
{
return backoff_.attempt_count();
}
bool transport_ready() const { return transport_ready_; }
private:
ConnectivityPolicyResult ScheduleRetry(
bool publish_disconnected,
uint16_t reason,
uint32_t entropy);
ReconnectBackoff backoff_;
ConnectivityPolicyState state_ = ConnectivityPolicyState::kStopped;
size_t credential_count_ = 0;
size_t credential_index_ = 0;
uint16_t last_disconnect_reason_ = 0;
bool transport_ready_ = false;
};
} // namespace borla

View File

@@ -0,0 +1,292 @@
#include "connectivity/dual_network_policy.h"
namespace borla {
DualNetworkPolicy::DualNetworkPolicy(DualNetworkPolicyConfig config)
: config_(config)
{
if (config_.wifi_weak_sample_count == 0) {
config_.wifi_weak_sample_count = 1;
}
if (config_.modem_absent_sample_count == 0) {
config_.modem_absent_sample_count = 1;
}
}
DualNetworkPolicyResult DualNetworkPolicy::OnModemPresence(
ModemPresence observed,
uint64_t now_ms)
{
DualNetworkPolicyResult result;
if (!started_ || observed == ModemPresence::kUnknown) {
// An unusable probe (UART driver refused to install) must not be read
// as "the switch was turned off".
if (selected_bearer_ == NetworkBearer::kWifi &&
online_bearer_ != NetworkBearer::kWifi) {
result.Add(DualNetworkActionType::kStartWifi);
}//2026-9-8 ckkj add
return result;
}
if (stable_modem_presence_ == ModemPresence::kUnknown) {
stable_modem_presence_ = observed;
modem_absent_streak_ = 0;
if (observed == ModemPresence::kPresent) {
// Booted with the switch left on while running on WiFi: the modem
// is burning power for nothing, so say so once.
result.Add(DualNetworkActionType::kPromptCellularBootOn);
}
return result;
}
if (observed == ModemPresence::kPresent) {
modem_absent_streak_ = 0;
if (stable_modem_presence_ != ModemPresence::kPresent) {
stable_modem_presence_ = ModemPresence::kPresent;
modem_unavailable_announced_ = false;
result.Add(DualNetworkActionType::kPromptCellularOn);
}
return result;
}
if (stable_modem_presence_ != ModemPresence::kAbsent) {
if (modem_absent_streak_ < UINT8_MAX) {
++modem_absent_streak_;
}
if (modem_absent_streak_ >= config_.modem_absent_sample_count) {
stable_modem_presence_ = ModemPresence::kAbsent;
modem_absent_streak_ = 0;
result.Add(DualNetworkActionType::kPromptCellularOff);
}
}
(void)now_ms;
return result;
}
DualNetworkPolicyResult DualNetworkPolicy::NotifyWifiLostWithoutModem(
uint64_t now_ms)
{
DualNetworkPolicyResult result;
if (!started_ ||
selected_bearer_ != NetworkBearer::kWifi ||
online_bearer_ == NetworkBearer::kWifi ||
stable_modem_presence_ != ModemPresence::kAbsent) {
return result;
}
// Same threshold the automatic failover uses. Announcing earlier would
// fire during a normal boot (WiFi not up yet) and on every brief blip;
// this only speaks once the device would otherwise have switched to 4G
// and found the modem unpowered.
if (wifi_disconnected_since_ms_ == 0 ||
now_ms < wifi_disconnected_since_ms_ ||
now_ms - wifi_disconnected_since_ms_ <
config_.wifi_disconnect_failover_ms) {
return result;
}
if (modem_unavailable_announced_ &&
now_ms >= modem_unavailable_announced_ms_ &&
now_ms - modem_unavailable_announced_ms_ <
config_.modem_unavailable_repeat_ms) {
return result;
}
modem_unavailable_announced_ = true;
modem_unavailable_announced_ms_ = now_ms;
result.Add(DualNetworkActionType::kPromptCellularUnavailable);
return result;
}
DualNetworkPolicyResult DualNetworkPolicy::Start(
bool has_wifi_credentials,
uint64_t now_ms)
{
DualNetworkPolicyResult result;
if (started_) {
return result;
}
started_ = true;
selected_since_ms_ = now_ms;
if (!has_wifi_credentials) {
selected_bearer_ = NetworkBearer::kNone;
result.Add(DualNetworkActionType::kRequestProvisioning);
return result;
}
selected_bearer_ = NetworkBearer::kWifi;
result.Add(DualNetworkActionType::kStartWifi);
return result;
}
DualNetworkPolicyResult DualNetworkPolicy::Stop()
{
DualNetworkPolicyResult result;
if (!started_) {
return result;
}
if (selected_bearer_ == NetworkBearer::kWifi) {
result.Add(DualNetworkActionType::kStopWifi);
} else if (selected_bearer_ == NetworkBearer::kCellular) {
result.Add(DualNetworkActionType::kStopCellular);
}
started_ = false;
selected_bearer_ = NetworkBearer::kNone;
online_bearer_ = NetworkBearer::kNone;
wifi_disconnected_since_ms_ = 0;
weak_sample_count_ = 0;
stable_modem_presence_ = ModemPresence::kUnknown;
modem_absent_streak_ = 0;
modem_unavailable_announced_ = false;
modem_unavailable_announced_ms_ = 0;
return result;
}
DualNetworkPolicyResult DualNetworkPolicy::OnWifiOnline(uint64_t now_ms)
{
if (!started_ || selected_bearer_ != NetworkBearer::kWifi) {
return {};
}
online_bearer_ = NetworkBearer::kWifi;
selected_since_ms_ = now_ms;
wifi_disconnected_since_ms_ = 0;
weak_sample_count_ = 0;
return {};
}
DualNetworkPolicyResult DualNetworkPolicy::OnWifiDisconnected(
uint64_t now_ms)
{
if (!started_ || selected_bearer_ != NetworkBearer::kWifi) {
return {};
}
online_bearer_ = NetworkBearer::kNone;
if (wifi_disconnected_since_ms_ == 0) {
wifi_disconnected_since_ms_ = now_ms == 0 ? 1 : now_ms;
}
weak_sample_count_ = 0;
return {};
}
DualNetworkPolicyResult DualNetworkPolicy::OnCellularOnline(
uint64_t now_ms)
{
if (!started_ || selected_bearer_ != NetworkBearer::kCellular) {
return {};
}
online_bearer_ = NetworkBearer::kCellular;
selected_since_ms_ = now_ms;
return {};
}
DualNetworkPolicyResult DualNetworkPolicy::OnCellularDisconnected(
uint64_t now_ms)
{
if (!started_ || selected_bearer_ != NetworkBearer::kCellular) {
return {};
}
online_bearer_ = NetworkBearer::kNone;
return SwitchToWifi(now_ms, false);
}
DualNetworkPolicyResult DualNetworkPolicy::OnMonitor(
uint64_t now_ms,
int8_t wifi_rssi_dbm,
ModemPresence modem)
{
if (!started_ || selected_bearer_ != NetworkBearer::kWifi ||
modem == ModemPresence::kAbsent) {
return {};
}
if (online_bearer_ == NetworkBearer::kWifi) {
if (wifi_rssi_dbm != 0 &&
wifi_rssi_dbm != -127 &&
wifi_rssi_dbm < config_.wifi_weak_rssi_dbm) {
if (weak_sample_count_ < UINT8_MAX) {
++weak_sample_count_;
}
} else {
weak_sample_count_ = 0;
}
if (weak_sample_count_ >= config_.wifi_weak_sample_count) {
return SwitchToCellular(now_ms, false);
}
return {};
}
if (wifi_disconnected_since_ms_ != 0 &&
now_ms >= wifi_disconnected_since_ms_ &&
now_ms - wifi_disconnected_since_ms_ >=
config_.wifi_disconnect_failover_ms) {
return SwitchToCellular(now_ms, false);
}
return {};
}
DualNetworkPolicyResult DualNetworkPolicy::RequestManualSwitch(
uint64_t now_ms,
ModemPresence modem)
{
if (!started_) {
return {};
}
if (selected_bearer_ == NetworkBearer::kCellular) {
return SwitchToWifi(now_ms, true);
}
if (modem == ModemPresence::kAbsent) {
DualNetworkPolicyResult result;
result.Add(DualNetworkActionType::kPromptCellularUnavailable);
return result;
}
return SwitchToCellular(now_ms, true);
}
DualNetworkPolicyResult DualNetworkPolicy::SwitchToCellular(
uint64_t now_ms,
bool prompt)
{
DualNetworkPolicyResult result;
if (selected_bearer_ == NetworkBearer::kCellular) {
return result;
}
if (online_bearer_ != NetworkBearer::kNone) {
result.Add(DualNetworkActionType::kNotifyDisconnected);
}
result.Add(DualNetworkActionType::kStopWifi);
result.Add(DualNetworkActionType::kStartCellular);
result.Add(DualNetworkActionType::kRequestReconnect);
if (prompt) {
result.Add(DualNetworkActionType::kPromptCellularOn);
}
selected_bearer_ = NetworkBearer::kCellular;
online_bearer_ = NetworkBearer::kNone;
selected_since_ms_ = now_ms;
wifi_disconnected_since_ms_ = 0;
weak_sample_count_ = 0;
return result;
}
DualNetworkPolicyResult DualNetworkPolicy::SwitchToWifi(
uint64_t now_ms,
bool prompt)
{
DualNetworkPolicyResult result;
if (selected_bearer_ == NetworkBearer::kWifi) {
return result;
}
if (online_bearer_ != NetworkBearer::kNone) {
result.Add(DualNetworkActionType::kNotifyDisconnected);
}
result.Add(DualNetworkActionType::kStopCellular);
result.Add(DualNetworkActionType::kStartWifi);
result.Add(DualNetworkActionType::kRequestReconnect);
if (prompt) {
result.Add(DualNetworkActionType::kPromptCellularOff);
}
selected_bearer_ = NetworkBearer::kWifi;
online_bearer_ = NetworkBearer::kNone;
selected_since_ms_ = now_ms;
wifi_disconnected_since_ms_ = now_ms == 0 ? 1 : now_ms;
weak_sample_count_ = 0;
return result;
}
} // namespace borla

View File

@@ -0,0 +1,133 @@
#pragma once
#include <array>
#include <cstddef>
#include <cstdint>
namespace borla {
enum class NetworkBearer : uint8_t {
kNone,
kWifi,
kCellular,
};
enum class ModemPresence : uint8_t {
kUnknown,
kAbsent,
kPresent,
};
struct DualNetworkPolicyConfig {
uint32_t wifi_disconnect_failover_ms = 30000;
int8_t wifi_weak_rssi_dbm = -80;
uint8_t wifi_weak_sample_count = 6;
// The 4G switch cuts modem power directly, so the only way to sense it is
// whether the modem answers AT. An OFF reading needs two consecutive
// misses (UART jitter produces false absences); an ON reading is accepted
// immediately because an AT reply cannot be noise.
uint8_t modem_absent_sample_count = 2;
// Re-announce "no WiFi and 4G is off" at most this often. The WiFi monitor
// fires every few seconds while disconnected.
uint32_t modem_unavailable_repeat_ms = 120000;
};
enum class DualNetworkActionType : uint8_t {
kStartWifi,
kStopWifi,
kStartCellular,
kStopCellular,
kNotifyDisconnected,
kRequestReconnect,
kRequestProvisioning,
kPromptCellularOn,
kPromptCellularOff,
kPromptCellularUnavailable,
kPromptCellularBootOn,
};
struct DualNetworkAction {
DualNetworkActionType type = DualNetworkActionType::kStartWifi;
};
struct DualNetworkPolicyResult {
std::array<DualNetworkAction, 8> actions{};
size_t action_count = 0;
bool Add(DualNetworkActionType type)
{
if (action_count >= actions.size()) {
return false;
}
actions[action_count++].type = type;
return true;
}
};
class DualNetworkPolicy final {
public:
explicit DualNetworkPolicy(
DualNetworkPolicyConfig config = DualNetworkPolicyConfig{});
DualNetworkPolicyResult Start(
bool has_wifi_credentials,
uint64_t now_ms);
DualNetworkPolicyResult Stop();
DualNetworkPolicyResult OnWifiOnline(uint64_t now_ms);
DualNetworkPolicyResult OnWifiDisconnected(uint64_t now_ms);
DualNetworkPolicyResult OnCellularOnline(uint64_t now_ms);
DualNetworkPolicyResult OnCellularDisconnected(uint64_t now_ms);
DualNetworkPolicyResult OnMonitor(
uint64_t now_ms,
int8_t wifi_rssi_dbm,
ModemPresence modem);
DualNetworkPolicyResult RequestManualSwitch(
uint64_t now_ms,
ModemPresence modem);
// Physical 4G switch sensing, independent of bearer selection: flipping
// the switch only announces itself, it never moves the device between
// WiFi and cellular. Fed by every modem probe while WiFi is the bearer.
// first known reading, present -> kPromptCellularBootOn
// absent -> present -> kPromptCellularOn
// present -> absent (debounced) -> kPromptCellularOff
DualNetworkPolicyResult OnModemPresence(
ModemPresence observed,
uint64_t now_ms);
// WiFi is down and the modem is not powered: tell the parent to flip the
// switch. Rate-limited by modem_unavailable_repeat_ms.
DualNetworkPolicyResult NotifyWifiLostWithoutModem(uint64_t now_ms);
NetworkBearer selected_bearer() const { return selected_bearer_; }
ModemPresence stable_modem_presence() const
{
return stable_modem_presence_;
}
NetworkBearer online_bearer() const { return online_bearer_; }
bool started() const { return started_; }
uint8_t weak_sample_count() const { return weak_sample_count_; }
private:
DualNetworkPolicyResult SwitchToCellular(
uint64_t now_ms,
bool prompt);
DualNetworkPolicyResult SwitchToWifi(
uint64_t now_ms,
bool prompt);
DualNetworkPolicyConfig config_;
NetworkBearer selected_bearer_ = NetworkBearer::kNone;
NetworkBearer online_bearer_ = NetworkBearer::kNone;
uint64_t wifi_disconnected_since_ms_ = 0;
uint64_t selected_since_ms_ = 0;
uint8_t weak_sample_count_ = 0;
bool started_ = false;
ModemPresence stable_modem_presence_ = ModemPresence::kUnknown;
uint8_t modem_absent_streak_ = 0;
uint64_t modem_unavailable_announced_ms_ = 0;
bool modem_unavailable_announced_ = false;
};
} // namespace borla

View File

@@ -0,0 +1,437 @@
#include "connectivity/dual_network_transport.h"
#include <algorithm>
#include <cstring>
#include <esp_err.h>
#include <esp_log.h>
namespace borla {
namespace {
constexpr const char* kTag = "DualNetwork2";
constexpr uint16_t kBearerSwitchReason = 0xF101;
} // namespace
DualNetworkTransport::DualNetworkTransport(IWifiTransport& wifi,
ICellularTransport& cellular, DualNetworkPolicyConfig config)
: wifi_(wifi)
, cellular_(cellular)
, config_(config)
, policy_(config)
{
}
bool DualNetworkTransport::Initialize()
{
if (initialized_) {
return true;
}
queue_ = xQueueCreateStatic(
kQueueDepth, sizeof(Event), queue_storage_.data(), &queue_control_);
stop_completed_ = xSemaphoreCreateBinaryStatic(&stop_completed_control_);
if (queue_ == nullptr || stop_completed_ == nullptr) {
ESP_LOGE(kTag, "failed to allocate static control objects");
return false;
}
const esp_timer_create_args_t timer_args = {
.callback = &DualNetworkTransport::MonitorTimerCallback,
.arg = this,
.dispatch_method = ESP_TIMER_TASK,
.name = "dual_net_mon",
.skip_unhandled_events = true,
};
if (esp_timer_create(&timer_args, &monitor_timer_) != ESP_OK) {
ESP_LOGE(kTag, "monitor timer creation failed");
return false;
}
const BaseType_t task_result = xTaskCreate(&DualNetworkTransport::TaskEntry,
"dual_network2", task_stack_budget::kDualNetworkBytes, this, 4, &task_);
if (task_result != pdPASS) {
task_ = nullptr;
esp_timer_delete(monitor_timer_);
monitor_timer_ = nullptr;
return false;
}
initialized_ = true;
ESP_LOGI(kTag, "initialized queue=%u stack_bytes=%u memory=internal",
static_cast<unsigned>(kQueueDepth),
static_cast<unsigned>(task_stack_budget::kDualNetworkBytes));
return true;
}
bool DualNetworkTransport::Start(IWifiTransportObserver& observer)
{
if (!initialized_ && !Initialize()) {
return false;
}
portENTER_CRITICAL(&state_lock_);
upstream_ = &observer;
portEXIT_CRITICAL(&state_lock_);
return Post({ EventType::kStart, 0, {} });
}
void DualNetworkTransport::Stop()
{
if (!initialized_) {
return;
}
xSemaphoreTake(stop_completed_, 0);
if (!Post({ EventType::kStop, 0, {} })) {
return;
}
if (xSemaphoreTake(stop_completed_, pdMS_TO_TICKS(5000)) != pdTRUE) {
ESP_LOGE(kTag, "timed out stopping network transports");
}
}
// 2026-9-7 ckkj add: 转发拆除内部 WiFi 驱动释放内部 RAM。幂等(
// EspWifiTransport 内部有 driver_initialized_ 检查),供 BLE 好友模式
// 挂起时调用;仅在 Stop() 同步完成后调用,内部任务已空闲,无竞态。
void DualNetworkTransport::ReleaseDriver()
{
wifi_.ReleaseDriver();
wifi_ready_ = false;
}////
bool DualNetworkTransport::Connect(const WifiCredential& credential)
{
if (!credential.IsValid()) {
return false;
}
Event event;
event.type = EventType::kConnect;
event.credential = credential;
return Post(event);
}
bool DualNetworkTransport::Scan(
WifiNetwork* output, size_t capacity, size_t* count)
{
return wifi_.Scan(output, capacity, count);
}
WifiLinkInfo DualNetworkTransport::GetLinkInfo() const
{
if (selected_bearer_.load() != NetworkBearer::kCellular) {
return wifi_.GetLinkInfo();
}
const CellularLinkInfo cellular = cellular_.GetLinkInfo();
WifiLinkInfo link;
link.online = cellular.online;
link.rssi_dbm = cellular.csq >= 0 && cellular.csq <= 31
? static_cast<int8_t>(-113 + (2 * cellular.csq))
: -127;
// std::strncpy(link.ssid.data(), "cellular", link.ssid.size() - 1);
// std::strncpy(link.ipv4.data(), cellular.ipv4.data(), link.ipv4.size() - 1);
snprintf(link.ssid.data(), link.ssid.size(), "%s", "cellular");
snprintf(link.ipv4.data(),link.ipv4.size(),"%s",reinterpret_cast<const char*>(cellular.ipv4.data()));
return link;
}
bool DualNetworkTransport::RequestNetworkSwitch()
{
return Post({ EventType::kManualSwitch, 0, {} });
}
void DualNetworkTransport::OnWifiTransportEvent(const WifiTransportEvent& event)
{
Event converted;
switch (event.type) {
case WifiTransportEventType::kStarted:
converted.type = EventType::kWifiStarted;
break;
case WifiTransportEventType::kGotIp:
converted.type = EventType::kWifiGotIp;
break;
case WifiTransportEventType::kDisconnected:
converted.type = EventType::kWifiDisconnected;
converted.reason = event.disconnect_reason;
break;
case WifiTransportEventType::kReconnectRequested:
case WifiTransportEventType::kCellularOn:
case WifiTransportEventType::kCellularOff:
case WifiTransportEventType::kCellularUnavailable:
case WifiTransportEventType::kCellularBootOn:
return;
}
Post(converted);
}
void DualNetworkTransport::OnCellularTransportEvent(
const CellularTransportEvent& event)
{
Event converted;
switch (event.type) {
case CellularTransportEventType::kStarted:
converted.type = EventType::kCellularStarted;
break;
case CellularTransportEventType::kGotIp:
converted.type = EventType::kCellularGotIp;
break;
case CellularTransportEventType::kDisconnected:
converted.type = EventType::kCellularDisconnected;
converted.reason = event.reason;
break;
}
Post(converted);
}
void DualNetworkTransport::TaskEntry(void* context)
{
static_cast<DualNetworkTransport*>(context)->Run();
}
void DualNetworkTransport::MonitorTimerCallback(void* context)
{
static_cast<DualNetworkTransport*>(context)->Post(
{ EventType::kMonitor, 0, {} });
}
[[noreturn]] void DualNetworkTransport::Run()
{
while (true) {
Event event;
if (xQueueReceive(queue_, &event, portMAX_DELAY) == pdTRUE) {
Handle(event);
}
}
}
bool DualNetworkTransport::Post(const Event& event)
{
return initialized_ && queue_ != nullptr
&& xQueueSend(queue_, &event, 0) == pdTRUE;
}
void DualNetworkTransport::Handle(const Event& event)
{
const uint64_t now_ms = NowMs();
switch (event.type) {
case EventType::kStart:
initial_started_published_ = false;
Execute(policy_.Start(true, now_ms));
if (monitor_timer_ != nullptr) {
const esp_err_t result = esp_timer_start_periodic(monitor_timer_,
static_cast<uint64_t>(kMonitorIntervalMs) * 1000ULL);
if (result != ESP_OK && result != ESP_ERR_INVALID_STATE) {
ESP_LOGW(kTag, "monitor timer start failed: %s",
esp_err_to_name(result));
}
}
break;
case EventType::kStop:
if (monitor_timer_ != nullptr) {
const esp_err_t result = esp_timer_stop(monitor_timer_);
if (result != ESP_OK && result != ESP_ERR_INVALID_STATE) {
ESP_LOGW(kTag, "monitor timer stop failed: %s",
esp_err_to_name(result));
}
}
Execute(policy_.Stop());
pending_wifi_connect_ = false;
wifi_ready_ = false;
selected_bearer_.store(NetworkBearer::kNone);
portENTER_CRITICAL(&state_lock_);
upstream_ = nullptr;
portEXIT_CRITICAL(&state_lock_);
xSemaphoreGive(stop_completed_);
break;
case EventType::kConnect:
pending_credential_ = event.credential;
if (policy_.selected_bearer() == NetworkBearer::kWifi) {
if (wifi_ready_) {
if (!wifi_.Connect(pending_credential_)) {
PublishUpstream({
WifiTransportEventType::kDisconnected,
0xF102,
});
}
} else {
pending_wifi_connect_ = true;
}
}
break;
case EventType::kWifiStarted:
wifi_ready_ = true;
if (!initial_started_published_) {
initial_started_published_ = true;
PublishUpstream({ WifiTransportEventType::kStarted, 0 });
}
if (pending_wifi_connect_) {
pending_wifi_connect_ = false;
if (!wifi_.Connect(pending_credential_)) {
PublishUpstream({
WifiTransportEventType::kDisconnected,
0xF102,
});
}
}
break;
case EventType::kWifiGotIp:
policy_.OnWifiOnline(now_ms);
selected_bearer_.store(NetworkBearer::kWifi);
PublishUpstream({ WifiTransportEventType::kGotIp, 0 });
break;
case EventType::kWifiDisconnected:
policy_.OnWifiDisconnected(now_ms);
PublishUpstream({
WifiTransportEventType::kDisconnected,
event.reason,
});
break;
case EventType::kCellularStarted:
modem_presence_ = ModemPresence::kPresent;
break;
case EventType::kCellularGotIp:
policy_.OnCellularOnline(now_ms);
selected_bearer_.store(NetworkBearer::kCellular);
PublishUpstream({ WifiTransportEventType::kGotIp, 0 });
break;
case EventType::kCellularDisconnected:
PublishUpstream({
WifiTransportEventType::kDisconnected,
event.reason,
});
Execute(policy_.OnCellularDisconnected(now_ms));
break;
case EventType::kMonitor: {
const WifiLinkInfo link = wifi_.GetLinkInfo();
if (policy_.selected_bearer() == NetworkBearer::kWifi && !link.online
&& (last_modem_probe_ms_ == 0 || now_ms - last_modem_probe_ms_ >= kModemProbeIntervalMs))
{
// Probe unconditionally (not only when WiFi is degraded): the
// 4G switch is a physical control the user can flip at any time
// and the announcement is the only feedback they get. Cadence is
// kModemProbeIntervalMs because each probe drives the AT UART.
// modem_presence_ = cellular_.ProbePresent() ? ModemPresence::kPresent
// : ModemPresence::kAbsent;
const CellularProbeResult probe = cellular_.ProbePresent();
last_modem_probe_ms_ = now_ms;
//Execute(policy_.OnModemPresence(modem_presence_, now_ms));//2026-9-7 ckkj mod
if (probe != CellularProbeResult::kUnknown) {
modem_presence_ = probe == CellularProbeResult::kPresent
? ModemPresence::kPresent
: ModemPresence::kAbsent;
Execute(policy_.OnModemPresence(modem_presence_, now_ms));
}
}
// The policy owns the "long enough to matter" judgement; it uses the
// same disconnect deadline as the automatic failover.
Execute(policy_.NotifyWifiLostWithoutModem(now_ms));
Execute(policy_.OnMonitor(now_ms, link.rssi_dbm, modem_presence_));
break;
}
case EventType::kManualSwitch:
if (policy_.selected_bearer() == NetworkBearer::kWifi) {
// modem_presence_ = cellular_.ProbePresent() ? ModemPresence::kPresent
// : ModemPresence::kAbsent;
const CellularProbeResult probe = cellular_.ProbePresent();
last_modem_probe_ms_ = now_ms;
// kUnknown(内存不足探测没跑成)按在位处理:切换流程先释放 WiFi
// 驱动腾出内存,真实结果由 cellular_.Start() 给出;若模块确实
// 不在位,OnCellularDisconnected 会兜底回退 WiFi。
modem_presence_ = probe == CellularProbeResult::kAbsent
? ModemPresence::kAbsent
: ModemPresence::kPresent;//2026-9-9 ckkj mod
last_modem_probe_ms_ = now_ms;
}
Execute(policy_.RequestManualSwitch(now_ms, modem_presence_));
break;
}
selected_bearer_.store(policy_.selected_bearer());
}
void DualNetworkTransport::Execute(const DualNetworkPolicyResult& result)
{
for (size_t index = 0; index < result.action_count; ++index) {
Execute(result.actions[index].type);
}
}
void DualNetworkTransport::Execute(DualNetworkActionType action)
{
switch (action) {
case DualNetworkActionType::kStartWifi:
wifi_ready_ = false;
if (!wifi_.Start(*this)) {
PublishUpstream({
WifiTransportEventType::kDisconnected,
0xF103,
});
}
return;
case DualNetworkActionType::kStopWifi:
//wifi_.Stop();
// 2026-9-6 ckkj fix: 切 4G 时仅 Stop() 不释放 WiFi 驱动的几十 KB
// 内部 RAM,堆最大连续块被压到 ~3KB,PPP UART(4096B)永远安装失败
// (largest=3072)。ReleaseDriver() 彻底拆除驱动释放内存,
// 4G->WiFi 回切时 Start() 会自动重建驱动(BLE 配网已验证此流程)。
wifi_.ReleaseDriver();//// 释放 WiFi 驱动内存
wifi_ready_ = false;
return;
case DualNetworkActionType::kStartCellular:
if (!cellular_.Start(*this)) {
Post({ EventType::kCellularDisconnected, 0xF104, {} });
}
return;
case DualNetworkActionType::kStopCellular:
cellular_.Stop();
return;
case DualNetworkActionType::kNotifyDisconnected:
PublishUpstream({
WifiTransportEventType::kDisconnected,
kBearerSwitchReason,
});
return;
case DualNetworkActionType::kRequestReconnect:
PublishUpstream({
WifiTransportEventType::kReconnectRequested,
0,
});
return;
case DualNetworkActionType::kRequestProvisioning:
PublishUpstream({
WifiTransportEventType::kDisconnected,
0xF105,
});
return;
case DualNetworkActionType::kPromptCellularOn:
PublishUpstream({ WifiTransportEventType::kCellularOn, 0 });
return;
case DualNetworkActionType::kPromptCellularOff:
PublishUpstream({ WifiTransportEventType::kCellularOff, 0 });
return;
case DualNetworkActionType::kPromptCellularUnavailable:
PublishUpstream({
WifiTransportEventType::kCellularUnavailable,
0,
});
return;
case DualNetworkActionType::kPromptCellularBootOn:
PublishUpstream({
WifiTransportEventType::kCellularBootOn,
0,
});
return;
}
}
void DualNetworkTransport::PublishUpstream(const WifiTransportEvent& event)
{
portENTER_CRITICAL(&state_lock_);
IWifiTransportObserver* const observer = upstream_;
portEXIT_CRITICAL(&state_lock_);
if (observer != nullptr) {
observer->OnWifiTransportEvent(event);
}
}
uint64_t DualNetworkTransport::NowMs() const
{
return static_cast<uint64_t>(esp_timer_get_time() / 1000);
}
} // namespace borla

View File

@@ -0,0 +1,104 @@
#pragma once
#include "connectivity/cellular_transport.h"
#include "connectivity/dual_network_policy.h"
#include "connectivity/wifi_transport.h"
#include "core/task_stack_budget.h"
#include <array>
#include <atomic>
#include <esp_timer.h>
#include <freertos/FreeRTOS.h>
#include <freertos/portmacro.h>
#include <freertos/queue.h>
#include <freertos/semphr.h>
#include <freertos/task.h>
namespace borla {
class DualNetworkTransport final : public IWifiTransport,
public IWifiTransportObserver,
public ICellularTransportObserver {
public:
DualNetworkTransport(IWifiTransport& wifi, ICellularTransport& cellular,
DualNetworkPolicyConfig config);
bool Initialize();
bool Start(IWifiTransportObserver& observer) override;
void Stop() override;
// 2026-9-7 ckkj add: 彻底拆除内部 WiFi 驱动释放内部 RAM(BLE 好友模式
// 挂起时由 ConnectivityManager 调用);不发布事件,下一步 Start() 重建驱动。
void ReleaseDriver() override;////
bool Connect(const WifiCredential& credential) override;
bool Scan(WifiNetwork* output, size_t capacity, size_t* count) override;
WifiLinkInfo GetLinkInfo() const override;
bool RequestNetworkSwitch() override;
void OnWifiTransportEvent(const WifiTransportEvent& event) override;
void OnCellularTransportEvent(const CellularTransportEvent& event) override;
NetworkBearer SelectedBearer() const { return selected_bearer_.load(); }
private:
enum class EventType : uint8_t {
kStart,
kStop,
kConnect,
kWifiStarted,
kWifiGotIp,
kWifiDisconnected,
kCellularStarted,
kCellularGotIp,
kCellularDisconnected,
kMonitor,
kManualSwitch,
};
struct Event {
EventType type = EventType::kStart;
uint16_t reason = 0;
WifiCredential credential {};
};
static constexpr size_t kQueueDepth = 20;
static constexpr uint32_t kMonitorIntervalMs = 5000;
static constexpr uint32_t kModemProbeIntervalMs = 30000;
static void TaskEntry(void* context);
static void MonitorTimerCallback(void* context);
[[noreturn]] void Run();
bool Post(const Event& event);
void Handle(const Event& event);
void Execute(const DualNetworkPolicyResult& result);
void Execute(DualNetworkActionType action);
void PublishUpstream(const WifiTransportEvent& event);
uint64_t NowMs() const;
IWifiTransport& wifi_;
ICellularTransport& cellular_;
DualNetworkPolicyConfig config_;
DualNetworkPolicy policy_;
mutable portMUX_TYPE state_lock_ = portMUX_INITIALIZER_UNLOCKED;
IWifiTransportObserver* upstream_ = nullptr;
WifiCredential pending_credential_ {};
bool pending_wifi_connect_ = false;
bool wifi_ready_ = false;
bool initial_started_published_ = false;
ModemPresence modem_presence_ = ModemPresence::kUnknown;
uint64_t last_modem_probe_ms_ = 0;
QueueHandle_t queue_ = nullptr;
StaticQueue_t queue_control_ {};
alignas(Event)
std::array<uint8_t, kQueueDepth * sizeof(Event)> queue_storage_ {};
TaskHandle_t task_ = nullptr;
SemaphoreHandle_t stop_completed_ = nullptr;
StaticSemaphore_t stop_completed_control_ {};
esp_timer_handle_t monitor_timer_ = nullptr;
bool initialized_ = false;
std::atomic<NetworkBearer> selected_bearer_ { NetworkBearer::kNone };
};
} // namespace borla

View File

@@ -0,0 +1,90 @@
#include "connectivity/ml307_at_parser.h"
#include <cstdio>
#include <cstring>
namespace borla {
bool ParseMl307Registration(
const char* response,
CellularRegistration* registration)
{
if (response == nullptr || registration == nullptr) {
return false;
}
const char* marker = std::strstr(response, "+CEREG:");
if (marker == nullptr) {
return false;
}
unsigned mode = 0;
unsigned status = 0;
const int fields =
std::sscanf(marker, "+CEREG: %u,%u", &mode, &status);
if (fields == 1) {
status = mode;
mode = 0;
} else if (fields != 2) {
return false;
}
if (mode > UINT8_MAX || status > UINT8_MAX) {
return false;
}
registration->mode = static_cast<uint8_t>(mode);
registration->status = static_cast<uint8_t>(status);
return true;
}
bool ParseMl307SignalQuality(const char* response, int8_t* csq)
{
if (response == nullptr || csq == nullptr) {
return false;
}
const char* marker = std::strstr(response, "+CSQ:");
if (marker == nullptr) {
return false;
}
int value = -1;
if (std::sscanf(marker, "+CSQ: %d", &value) != 1 ||
!((value >= 0 && value <= 31) || value == 99)) {
return false;
}
*csq = value == 99 ? -1 : static_cast<int8_t>(value);
return true;
}
bool CopyMl307ResponseLine(
const char* response,
const char* prefix,
char* output,
size_t output_capacity)
{
if (response == nullptr || prefix == nullptr || output == nullptr ||
output_capacity == 0) {
return false;
}
const char* begin =
prefix[0] == '\0' ? response : std::strstr(response, prefix);
if (begin == nullptr) {
return false;
}
begin += std::strlen(prefix);
while (*begin == ' ' || *begin == ':' || *begin == '"' ||
*begin == '\r' || *begin == '\n') {
++begin;
}
const char* end = begin;
while (*end != '\0' && *end != '\r' && *end != '\n' &&
*end != '"') {
++end;
}
const size_t size = static_cast<size_t>(end - begin);
if (size == 0 || size >= output_capacity) {
return false;
}
std::memset(output, 0, output_capacity);
std::memcpy(output, begin, size);
return true;
}
} // namespace borla

View File

@@ -0,0 +1,31 @@
#pragma once
#include <cstddef>
#include <cstdint>
namespace borla {
struct CellularRegistration {
uint8_t mode = 0;
uint8_t status = 0;
bool IsRegistered() const
{
return status == 1 || status == 5;
}
};
bool ParseMl307Registration(
const char* response,
CellularRegistration* registration);
bool ParseMl307SignalQuality(
const char* response,
int8_t* csq);
bool CopyMl307ResponseLine(
const char* response,
const char* prefix,
char* output,
size_t output_capacity);
} // namespace borla

View File

@@ -0,0 +1,62 @@
#include "connectivity/reconnect_backoff.h"
#include <algorithm>
#include <cstdint>
#include <limits>
namespace borla {
ReconnectBackoff::ReconnectBackoff(ReconnectBackoffConfig config)
: config_(Normalize(config))
{
}
uint32_t ReconnectBackoff::NextDelayMs(uint32_t entropy)
{
if (current_base_delay_ms_ == 0) {
current_base_delay_ms_ = config_.initial_delay_ms;
} else {
const uint64_t multiplied =
static_cast<uint64_t>(current_base_delay_ms_) *
config_.multiplier;
current_base_delay_ms_ = static_cast<uint32_t>(
std::min<uint64_t>(multiplied, config_.maximum_delay_ms));
}
++attempt_count_;
const uint32_t jitter_range = static_cast<uint32_t>(
(static_cast<uint64_t>(current_base_delay_ms_) *
config_.jitter_percent) /
100U);
if (jitter_range == 0) {
return current_base_delay_ms_;
}
const uint64_t bucket_count =
static_cast<uint64_t>(jitter_range) * 2U + 1U;
const int64_t offset =
static_cast<int64_t>(entropy % bucket_count) -
static_cast<int64_t>(jitter_range);
const int64_t jittered =
static_cast<int64_t>(current_base_delay_ms_) + offset;
return static_cast<uint32_t>(std::max<int64_t>(1, jittered));
}
void ReconnectBackoff::Reset()
{
current_base_delay_ms_ = 0;
attempt_count_ = 0;
}
ReconnectBackoffConfig ReconnectBackoff::Normalize(
ReconnectBackoffConfig config)
{
config.initial_delay_ms = std::max<uint32_t>(1, config.initial_delay_ms);
config.maximum_delay_ms =
std::max(config.initial_delay_ms, config.maximum_delay_ms);
config.multiplier = std::max<uint8_t>(1, config.multiplier);
config.jitter_percent = std::min<uint8_t>(50, config.jitter_percent);
return config;
}
} // namespace borla

View File

@@ -0,0 +1,35 @@
#pragma once
#include <cstdint>
namespace borla {
struct ReconnectBackoffConfig {
uint32_t initial_delay_ms = 1000;
uint32_t maximum_delay_ms = 60000;
uint8_t multiplier = 2;
uint8_t jitter_percent = 20;
};
class ReconnectBackoff final {
public:
explicit ReconnectBackoff(
ReconnectBackoffConfig config = ReconnectBackoffConfig{});
uint32_t NextDelayMs(uint32_t entropy);
void Reset();
uint32_t attempt_count() const { return attempt_count_; }
uint32_t current_base_delay_ms() const { return current_base_delay_ms_; }
const ReconnectBackoffConfig& config() const { return config_; }
private:
static ReconnectBackoffConfig Normalize(
ReconnectBackoffConfig config);
ReconnectBackoffConfig config_;
uint32_t current_base_delay_ms_ = 0;
uint32_t attempt_count_ = 0;
};
} // namespace borla

View File

@@ -0,0 +1,229 @@
#include "connectivity/wifi_credential_store.h"
#include <algorithm>
#include <array>
#include <cstdio>
#include <cstring>
#include <esp_err.h>
#include <esp_log.h>
#include <nvs.h>
namespace borla {
namespace {
constexpr const char* kTag = "WifiCredentials2";
constexpr const char* kNvsNamespace = "wifi";
void MakeKey(const char* prefix, size_t index, char* output, size_t size)
{
if (index == 0) {
std::snprintf(output, size, "%s", prefix);
} else {
std::snprintf(output, size, "%s%u", prefix,
static_cast<unsigned>(index));
}
}
bool SameSsid(const WifiCredential& credential, const char* ssid)
{
return ssid != nullptr &&
std::strncmp(
credential.ssid.data(), ssid, credential.ssid.size()) == 0;
}
} // namespace
size_t NvsWifiCredentialStore::Load(
WifiCredential* output,
size_t capacity) const
{
if (output == nullptr || capacity == 0) {
return 0;
}
nvs_handle_t handle = 0;
const esp_err_t open_result =
nvs_open(kNvsNamespace, NVS_READONLY, &handle);
if (open_result == ESP_ERR_NVS_NOT_FOUND) {
return 0;
}
if (open_result != ESP_OK) {
ESP_LOGE(kTag, "open namespace failed: %s",
esp_err_to_name(open_result));
return 0;
}
size_t count = 0;
for (size_t index = 0;
index < kMaxSavedWifiCredentials && count < capacity;
++index) {
char ssid_key[16]{};
char password_key[16]{};
MakeKey("ssid", index, ssid_key, sizeof(ssid_key));
MakeKey("password", index, password_key, sizeof(password_key));
WifiCredential credential;
size_t ssid_size = credential.ssid.size();
size_t password_size = credential.password.size();
if (nvs_get_str(
handle, ssid_key, credential.ssid.data(), &ssid_size) !=
ESP_OK) {
continue;
}
if (nvs_get_str(
handle, password_key, credential.password.data(),
&password_size) != ESP_OK) {
continue;
}
if (!credential.IsValid()) {
ESP_LOGW(kTag, "ignored invalid credential slot=%u",
static_cast<unsigned>(index));
continue;
}
output[count++] = credential;
}
nvs_close(handle);
ESP_LOGI(kTag, "loaded %u saved WiFi credential(s)",
static_cast<unsigned>(count));
return count;
}
bool NvsWifiCredentialStore::SaveAndPromote(
const WifiCredential& credential)
{
if (!credential.IsValid()) {
ESP_LOGE(kTag, "refused invalid WiFi credential");
return false;
}
std::array<WifiCredential, kMaxSavedWifiCredentials> credentials{};
size_t count = Load(credentials.data(), credentials.size());
size_t existing = count;
for (size_t index = 0; index < count; ++index) {
if (SameSsid(credentials[index], credential.ssid.data())) {
existing = index;
break;
}
}
if (existing < count) {
for (size_t index = existing; index > 0; --index) {
credentials[index] = credentials[index - 1];
}
} else {
count = std::min(count + 1U, credentials.size());
for (size_t index = count - 1; index > 0; --index) {
credentials[index] = credentials[index - 1];
}
}
credentials[0] = credential;
if (!SaveAll(credentials.data(), count)) {
return false;
}
ESP_LOGI(kTag, "saved WiFi credential ssid=%s",
credential.ssid.data());
return true;
}
bool NvsWifiCredentialStore::Remove(const char* ssid)
{
if (ssid == nullptr || ssid[0] == '\0') {
return false;
}
std::array<WifiCredential, kMaxSavedWifiCredentials> credentials{};
size_t count = Load(credentials.data(), credentials.size());
size_t remove_index = count;
for (size_t index = 0; index < count; ++index) {
if (SameSsid(credentials[index], ssid)) {
remove_index = index;
break;
}
}
if (remove_index == count) {
return false;
}
for (size_t index = remove_index; index + 1 < count; ++index) {
credentials[index] = credentials[index + 1];
}
--count;
if (!SaveAll(credentials.data(), count)) {
return false;
}
ESP_LOGI(kTag, "removed WiFi credential ssid=%s", ssid);
return true;
}
bool NvsWifiCredentialStore::Clear()
{
return SaveAll(nullptr, 0);
}
bool NvsWifiCredentialStore::SaveAll(
const WifiCredential* credentials,
size_t count) const
{
if ((credentials == nullptr && count != 0) ||
count > kMaxSavedWifiCredentials) {
return false;
}
nvs_handle_t handle = 0;
esp_err_t result =
nvs_open(kNvsNamespace, NVS_READWRITE, &handle);
if (result != ESP_OK) {
ESP_LOGE(kTag, "open writable namespace failed: %s",
esp_err_to_name(result));
return false;
}
for (size_t index = 0; index < kMaxSavedWifiCredentials; ++index) {
char ssid_key[16]{};
char password_key[16]{};
MakeKey("ssid", index, ssid_key, sizeof(ssid_key));
MakeKey("password", index, password_key, sizeof(password_key));
if (index < count) {
result = nvs_set_str(
handle, ssid_key, credentials[index].ssid.data());
if (result == ESP_OK) {
result = nvs_set_str(
handle, password_key,
credentials[index].password.data());
}
} else {
const esp_err_t ssid_result = nvs_erase_key(handle, ssid_key);
const esp_err_t password_result =
nvs_erase_key(handle, password_key);
if (ssid_result != ESP_OK &&
ssid_result != ESP_ERR_NVS_NOT_FOUND) {
result = ssid_result;
}
if (password_result != ESP_OK &&
password_result != ESP_ERR_NVS_NOT_FOUND) {
result = password_result;
}
}
if (result != ESP_OK) {
ESP_LOGE(kTag, "write credential slot=%u failed: %s",
static_cast<unsigned>(index),
esp_err_to_name(result));
nvs_close(handle);
return false;
}
}
result = nvs_commit(handle);
nvs_close(handle);
if (result != ESP_OK) {
ESP_LOGE(kTag, "commit credentials failed: %s",
esp_err_to_name(result));
return false;
}
return true;
}
} // namespace borla

View File

@@ -0,0 +1,32 @@
#pragma once
#include "connectivity/wifi_types.h"
#include <cstddef>
namespace borla {
class IWifiCredentialStore {
public:
virtual ~IWifiCredentialStore() = default;
virtual size_t Load(WifiCredential* output, size_t capacity) const = 0;
virtual bool SaveAndPromote(const WifiCredential& credential) = 0;
virtual bool Remove(const char* ssid) = 0;
virtual bool Clear() = 0;
};
class NvsWifiCredentialStore final : public IWifiCredentialStore {
public:
size_t Load(WifiCredential* output, size_t capacity) const override;
bool SaveAndPromote(const WifiCredential& credential) override;
bool Remove(const char* ssid) override;
bool Clear() override;
private:
bool SaveAll(
const WifiCredential* credentials,
size_t count) const;
};
} // namespace borla

View File

@@ -0,0 +1,69 @@
#pragma once
#include "connectivity/wifi_types.h"
#include <cstddef>
#include <cstdint>
namespace borla {
enum class WifiTransportEventType : uint8_t {
kStarted,
kGotIp,
kDisconnected,
kReconnectRequested,
kCellularOn,
kCellularOff,
kCellularUnavailable,
kCellularBootOn,
};
struct WifiTransportEvent {
WifiTransportEventType type = WifiTransportEventType::kStarted;
uint16_t disconnect_reason = 0;
};
class IWifiTransportObserver {
public:
virtual ~IWifiTransportObserver() = default;
virtual void OnWifiTransportEvent(
const WifiTransportEvent& event) = 0;
};
class IWifiTransport {
public:
virtual ~IWifiTransport() = default;
virtual bool Start(IWifiTransportObserver& observer) = 0;
virtual void Stop() = 0;
// Stop() only halts the driver; it keeps tens of KB of internal RAM in
// static/dynamic packet buffers. ReleaseDriver() tears the driver all the
// way down so that memory is available to something else — currently the
// BLE controller, which needs ~65 KB internal and cannot coexist with an
// idle-but-initialised WiFi driver on this board. The next Start() brings
// the driver back up. Default is a no-op for transports without one.
virtual void ReleaseDriver() {}
// Selects a trimmed buffer configuration for the next InitializeDriver().
//
// The default profile wants ~36 KB of internal RAM, most of it 10 static
// 1600-byte RX buffers. That is unaffordable in exactly one place: BLE
// provisioning, where the BT controller already holds ~53 KB and the
// driver has to come back up to test the credential the phone just sent.
// Field log: free=44287 at that moment, esp_wifi_init consumed 34 KB and
// then failed on the tenth RX buffer with ESP_ERR_NO_MEM, so the app
// reported "connection failed" on a perfectly good password.
//
// That link only has to associate and pull a DHCP lease before the driver
// is stopped again and the phone reboots the device, so throughput is
// irrelevant there. Everywhere else the default profile stays.
virtual void UseLowMemoryProfile(bool enabled) { (void)enabled; }
virtual bool Connect(const WifiCredential& credential) = 0;
virtual bool Scan(
WifiNetwork* output,
size_t capacity,
size_t* count) = 0;
virtual WifiLinkInfo GetLinkInfo() const = 0;
virtual bool RequestNetworkSwitch() { return false; }
};
} // namespace borla

View File

@@ -0,0 +1,78 @@
#pragma once
#include <array>
#include <cstddef>
#include <cstdint>
#include <cstring>
namespace borla {
inline constexpr size_t kWifiSsidCapacity = 33;
inline constexpr size_t kWifiPasswordCapacity = 65;
inline constexpr size_t kWifiIpv4Capacity = 16;
inline constexpr size_t kMaxSavedWifiCredentials = 10;
inline constexpr size_t kMaxProvisioningScanResults = 20;
inline size_t BoundedStringLength(const char* value, size_t capacity)
{
if (value == nullptr) {
return capacity;
}
size_t length = 0;
while (length < capacity && value[length] != '\0') {
++length;
}
return length;
}
struct WifiCredential {
std::array<char, kWifiSsidCapacity> ssid{};
std::array<char, kWifiPasswordCapacity> password{};
bool Set(const char* new_ssid, const char* new_password)
{
if (new_ssid == nullptr || new_password == nullptr) {
return false;
}
const size_t ssid_length =
BoundedStringLength(new_ssid, kWifiSsidCapacity);
const size_t password_length =
BoundedStringLength(new_password, kWifiPasswordCapacity);
if (ssid_length == 0 || ssid_length >= kWifiSsidCapacity ||
password_length >= kWifiPasswordCapacity) {
return false;
}
ssid.fill('\0');
password.fill('\0');
std::memcpy(ssid.data(), new_ssid, ssid_length);
std::memcpy(password.data(), new_password, password_length);
return true;
}
bool IsValid() const
{
return ssid[0] != '\0' &&
BoundedStringLength(ssid.data(), ssid.size()) < ssid.size() &&
BoundedStringLength(password.data(), password.size()) <
password.size();
}
};
struct WifiLinkInfo {
bool online = false;
int8_t rssi_dbm = -127;
uint8_t channel = 0;
uint16_t last_disconnect_reason = 0;
std::array<char, kWifiSsidCapacity> ssid{};
std::array<char, kWifiIpv4Capacity> ipv4{};
};
struct WifiNetwork {
std::array<char, kWifiSsidCapacity> ssid{};
int8_t rssi_dbm = -127;
uint8_t auth_mode = 0;
};
} // namespace borla