Files
bolar_2/main/friend/friend_service.cc
2026-11-27 16:38:11 +08:00

267 lines
6.8 KiB
C++
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#include "friend/friend_service.h"
#include <cstring>
#include <esp_log.h>
namespace borla {
namespace {
constexpr const char* kTag = "FriendService2";
constexpr uint32_t kFriendStartError = 12201;
constexpr uint32_t kFriendStoreError = 12202;
template <size_t Capacity>
bool CopyString(
const char* value,
std::array<char, Capacity>* output)
{
if (value == nullptr || output == nullptr) {
return false;
}
const size_t size = std::strlen(value);
if (size == 0 || size >= Capacity) {
return false;
}
output->fill('\0');
std::memcpy(output->data(), value, size);
return true;
}
} // namespace
FriendService::FriendService(
BleFriendExchange& exchange,
IFriendStore& store,
IRealtimeProtocol& realtime,IConnectivityManager& connectivity)
: exchange_(exchange),
store_(store),
realtime_(realtime),
connectivity_(connectivity)//2026-9-7 ckkj add
{
}
bool FriendService::Initialize(
const DeviceIdentity& identity,
IEventPublisher& publisher)
{
if (initialized_.load()) {
return true;
}
if (!CopyString(identity.mac, &local_mac_) ||
!BuildFriendAdvertisingName(
identity.mac,
fallback_name_.data(),
fallback_name_.size()) ||
!store_.Load(&snapshot_) ||
!exchange_.Initialize()) {
return false;
}
queue_ = xQueueCreateStatic(
kQueueDepth,
sizeof(Command),
queue_storage_.data(),
&queue_control_);
if (queue_ == nullptr) {
return false;
}
task_ = xTaskCreateStatic(
&FriendService::TaskEntry,
"friend_service2",
task_stack_.size(),
this,
kTaskPriority,
task_stack_.data(),
&task_control_);
if (task_ == nullptr) {
return false;
}
publisher_ = &publisher;
initialized_.store(true);
return true;
}
void FriendService::Start()
{
if (!Post({CommandType::kStart})) {
ESP_LOGE(kTag, "failed to enqueue friend start");
}
}
void FriendService::Stop()
{
Post({CommandType::kStop});
}
void FriendService::SetDeviceName(const char* device_name)
{
Command command;
command.type = CommandType::kSetDeviceName;
if (CopyString(device_name, &command.device_name)) {
Post(command);
}
}
void FriendService::OnBleFriendMatched(const FriendPeer& peer)
{
Command command;
command.type = CommandType::kMatched;
command.peer = peer;
Post(command);
}
void FriendService::OnBleFriendExchangeStopped(
bool paired,
uint32_t error_id)
{
Command command;
command.type = CommandType::kExchangeStopped;
command.paired = paired;
command.error_id = error_id;
Post(command);
}
void FriendService::OnApplicationEvent(
const AppEvent& event,
const RuntimeState&)
{
if (event.type == AppEventType::kRealtimeConnected) {
Post({CommandType::kUploadPending});
}
}
void FriendService::TaskEntry(void* context)
{
static_cast<FriendService*>(context)->Run();
}
[[noreturn]] void FriendService::Run()
{
while (true) {
Command command;
if (xQueueReceive(queue_, &command, portMAX_DELAY) == pdTRUE) {
Handle(command);
}
}
}
bool FriendService::Post(const Command& command)
{
return initialized_.load() && queue_ != nullptr &&
xQueueSend(queue_, &command, 0) == pdTRUE;
}
void FriendService::Handle(const Command& command)
{
switch (command.type) {
case CommandType::kStart:
HandleStart();
return;
case CommandType::kStop:
exchange_.Stop();
return;
case CommandType::kMatched:
HandleMatched(command.peer);
return;
case CommandType::kExchangeStopped:
// 2026-9-7 ckkj add: BLE 会话已结束(BleFriendExchange 在
// nimble_port_deinit 释放 BT 内存后才回调),立即恢复网络。
connectivity_.ResumeAfterBle();/////
if (publisher_ != nullptr) {
publisher_->Publish(AppEvent::Make(
AppEventType::kFriendModeEnded,
command.error_id,
0,
command.paired ? 1U : 0U));
}
return;
case CommandType::kSetDeviceName:
HandleSetDeviceName(command.device_name.data());
return;
case CommandType::kUploadPending:
UploadPending();
return;
}
}
void FriendService::HandleStart()
{
if (exchange_.IsActive()) {
return;
}
// if (!exchange_.Start(local_mac_.data(), *this) &&
// publisher_ != nullptr) {
// publisher_->Publish(AppEvent::Make(
// AppEventType::kFriendModeEnded,
// kFriendStartError));
// 2026-9-7 ckkj add: BT 控制器需要 ~65KB 内部 RAM,与已初始化的 WiFi
// 驱动无法共存,必须在 nimble_port_init 之前拆除驱动,否则 BLE_INIT
// "Malloc failed" 后 controller 内部直接 panic。结束时在
// kExchangeStopped 恢复;启动请求本身失败也立即恢复,避免网络永久挂起。
connectivity_.SuspendForBle();
if (!exchange_.Start(local_mac_.data(), *this)) {
connectivity_.ResumeAfterBle();
if (publisher_ != nullptr) {
publisher_->Publish(AppEvent::Make(
AppEventType::kFriendModeEnded,
kFriendStartError));
}
}
}
void FriendService::HandleMatched(const FriendPeer& peer)
{
if (!AddOrUpdateFriend(&snapshot_, peer)) {
if (publisher_ != nullptr) {
publisher_->Publish(AppEvent::Make(
AppEventType::kRealtimeProtocolError,
kFriendStoreError));
}
return;
}
snapshot_.pending_upload = peer;
snapshot_.has_pending_upload = true;
if (!store_.Save(snapshot_) && publisher_ != nullptr) {
publisher_->Publish(AppEvent::Make(
AppEventType::kRealtimeProtocolError,
kFriendStoreError));
}
}
void FriendService::HandleSetDeviceName(const char* device_name)
{
if (CopyString(device_name, &snapshot_.device_name) &&
!store_.Save(snapshot_)) {
ESP_LOGE(kTag, "device name persistence failed");
}
}
void FriendService::UploadPending()
{
if (!snapshot_.has_pending_upload) {
return;
}
if (!realtime_.SendFriendAdd(
local_mac_.data(),
LocalName(),
snapshot_.pending_upload.mac.data(),
snapshot_.pending_upload.name.data())) {
ESP_LOGW(kTag, "friend_add deferred until next reconnect");
return;
}
snapshot_.has_pending_upload = false;
snapshot_.pending_upload = {};
if (!store_.Save(snapshot_)) {
ESP_LOGE(kTag, "pending friend clear persistence failed");
}
}
const char* FriendService::LocalName()
{
return snapshot_.device_name[0] != '\0'
? snapshot_.device_name.data()
: fallback_name_.data();
}
} // namespace borla