bolar_2 backup
This commit is contained in:
266
main/friend/friend_service.cc
Normal file
266
main/friend/friend_service.cc
Normal file
@@ -0,0 +1,266 @@
|
||||
#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
|
||||
104
main/friend/friend_service.h
Normal file
104
main/friend/friend_service.h
Normal file
@@ -0,0 +1,104 @@
|
||||
#pragma once
|
||||
|
||||
#include "core/task_stack_budget.h"
|
||||
#include "friend/friend_store.h"
|
||||
#include "platform/borla_s3/ble_friend_exchange.h"
|
||||
#include "ports/application_observer.h"
|
||||
#include "ports/device_platform.h"
|
||||
#include "ports/device_profile_sink.h"
|
||||
#include "ports/event_publisher.h"
|
||||
#include "ports/friend_service.h"
|
||||
#include "ports/realtime_protocol.h"
|
||||
#include "ports/connectivity_manager.h"
|
||||
#include <array>
|
||||
#include <atomic>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
|
||||
#include <freertos/FreeRTOS.h>
|
||||
#include <freertos/queue.h>
|
||||
#include <freertos/task.h>
|
||||
|
||||
namespace borla {
|
||||
|
||||
class FriendService final
|
||||
: public IFriendService,
|
||||
public IBleFriendExchangeObserver,
|
||||
public IDeviceProfileSink,
|
||||
public IApplicationObserver {
|
||||
public:
|
||||
FriendService(
|
||||
BleFriendExchange& exchange,
|
||||
IFriendStore& store,
|
||||
IRealtimeProtocol& realtime,
|
||||
IConnectivityManager& connectivity);//2026-9-7 ckkj add
|
||||
|
||||
bool Initialize(
|
||||
const DeviceIdentity& identity,
|
||||
IEventPublisher& publisher);
|
||||
void Start() override;
|
||||
void Stop() override;
|
||||
void SetDeviceName(const char* device_name) override;
|
||||
void OnBleFriendMatched(const FriendPeer& peer) override;
|
||||
void OnBleFriendExchangeStopped(
|
||||
bool paired,
|
||||
uint32_t error_id) override;
|
||||
void OnApplicationEvent(
|
||||
const AppEvent& event,
|
||||
const RuntimeState& state) override;
|
||||
|
||||
private:
|
||||
enum class CommandType : uint8_t {
|
||||
kStart,
|
||||
kStop,
|
||||
kMatched,
|
||||
kExchangeStopped,
|
||||
kSetDeviceName,
|
||||
kUploadPending,
|
||||
};
|
||||
|
||||
struct Command {
|
||||
CommandType type = CommandType::kStart;
|
||||
FriendPeer peer{};
|
||||
std::array<char, kFriendNameCapacity> device_name{};
|
||||
uint32_t error_id = 0;
|
||||
bool paired = false;
|
||||
};
|
||||
|
||||
static constexpr size_t kQueueDepth = 10;
|
||||
static constexpr UBaseType_t kTaskPriority = 5;
|
||||
|
||||
static void TaskEntry(void* context);
|
||||
[[noreturn]] void Run();
|
||||
bool Post(const Command& command);
|
||||
void Handle(const Command& command);
|
||||
void HandleStart();
|
||||
void HandleMatched(const FriendPeer& peer);
|
||||
void HandleSetDeviceName(const char* device_name);
|
||||
void UploadPending();
|
||||
const char* LocalName();
|
||||
|
||||
BleFriendExchange& exchange_;
|
||||
IFriendStore& store_;
|
||||
IRealtimeProtocol& realtime_;
|
||||
IConnectivityManager& connectivity_;//2026-9-7 ckkj add
|
||||
IEventPublisher* publisher_ = nullptr;
|
||||
FriendStoreSnapshot snapshot_{};
|
||||
std::array<char, kFriendMacCapacity> local_mac_{};
|
||||
std::array<char, kFriendAdvertisingNameCapacity>
|
||||
fallback_name_{};
|
||||
|
||||
QueueHandle_t queue_ = nullptr;
|
||||
StaticQueue_t queue_control_{};
|
||||
alignas(Command)
|
||||
std::array<uint8_t, kQueueDepth * sizeof(Command)>
|
||||
queue_storage_{};
|
||||
TaskHandle_t task_ = nullptr;
|
||||
StaticTask_t task_control_{};
|
||||
std::array<
|
||||
StackType_t,
|
||||
task_stack_budget::kFriendServiceBytes> task_stack_{};
|
||||
std::atomic<bool> initialized_{false};
|
||||
};
|
||||
|
||||
} // namespace borla
|
||||
313
main/friend/friend_store.cc
Normal file
313
main/friend/friend_store.cc
Normal file
@@ -0,0 +1,313 @@
|
||||
#include "friend/friend_store.h"
|
||||
|
||||
#include "core/psram_object.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
|
||||
#include <cJSON.h>
|
||||
#include <esp_err.h>
|
||||
#include <esp_log.h>
|
||||
#include <nvs.h>
|
||||
|
||||
namespace borla {
|
||||
namespace {
|
||||
|
||||
constexpr const char* kTag = "FriendStore2";
|
||||
constexpr const char* kNamespace = "friend_v2";
|
||||
constexpr const char* kSnapshotKey = "snapshot";
|
||||
constexpr uint32_t kMagic = 0x32444E46;
|
||||
constexpr uint16_t kVersion = 1;
|
||||
constexpr const char* kLegacyDeviceNamespace = "device";
|
||||
constexpr const char* kLegacyDeviceNameKey = "name";
|
||||
constexpr const char* kLegacyFriendsNamespace = "friends";
|
||||
constexpr const char* kLegacyFriendCountKey = "count";
|
||||
|
||||
struct PersistedFriendSnapshot {
|
||||
uint32_t magic = kMagic;
|
||||
uint16_t version = kVersion;
|
||||
uint16_t friend_count = 0;
|
||||
uint8_t has_pending_upload = 0;
|
||||
uint8_t reserved[3]{};
|
||||
char device_name[kFriendNameCapacity]{};
|
||||
FriendPeer friends[kMaximumFriendCount]{};
|
||||
FriendPeer pending_upload{};
|
||||
uint32_t checksum = 0;
|
||||
};
|
||||
|
||||
uint32_t Checksum(const void* data, size_t size)
|
||||
{
|
||||
const auto* bytes = static_cast<const uint8_t*>(data);
|
||||
uint32_t value = 2166136261U;
|
||||
for (size_t index = 0; index < size; ++index) {
|
||||
value ^= bytes[index];
|
||||
value *= 16777619U;
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
bool PeerValid(const FriendPeer& peer)
|
||||
{
|
||||
return peer.mac[0] != '\0' &&
|
||||
std::memchr(peer.mac.data(), '\0', peer.mac.size()) != nullptr &&
|
||||
std::memchr(peer.name.data(), '\0', peer.name.size()) != nullptr;
|
||||
}
|
||||
|
||||
template <size_t Capacity>
|
||||
bool CopyString(
|
||||
const char* value,
|
||||
std::array<char, Capacity>* output)
|
||||
{
|
||||
if (value == nullptr || output == nullptr) {
|
||||
return false;
|
||||
}
|
||||
const size_t length = std::strlen(value);
|
||||
if (length == 0 || length >= Capacity) {
|
||||
return false;
|
||||
}
|
||||
output->fill('\0');
|
||||
std::memcpy(output->data(), value, length);
|
||||
return true;
|
||||
}
|
||||
|
||||
bool LoadLegacy(FriendStoreSnapshot* snapshot)
|
||||
{
|
||||
bool migrated = false;
|
||||
nvs_handle_t device_handle = 0;
|
||||
if (nvs_open(
|
||||
kLegacyDeviceNamespace,
|
||||
NVS_READONLY,
|
||||
&device_handle) == ESP_OK) {
|
||||
size_t size = snapshot->device_name.size();
|
||||
if (nvs_get_str(
|
||||
device_handle,
|
||||
kLegacyDeviceNameKey,
|
||||
snapshot->device_name.data(),
|
||||
&size) == ESP_OK &&
|
||||
snapshot->device_name[0] != '\0') {
|
||||
migrated = true;
|
||||
} else {
|
||||
snapshot->device_name.fill('\0');
|
||||
}
|
||||
nvs_close(device_handle);
|
||||
}
|
||||
|
||||
nvs_handle_t friends_handle = 0;
|
||||
if (nvs_open(
|
||||
kLegacyFriendsNamespace,
|
||||
NVS_READONLY,
|
||||
&friends_handle) != ESP_OK) {
|
||||
return migrated;
|
||||
}
|
||||
int32_t count = 0;
|
||||
if (nvs_get_i32(
|
||||
friends_handle,
|
||||
kLegacyFriendCountKey,
|
||||
&count) != ESP_OK ||
|
||||
count <= 0) {
|
||||
nvs_close(friends_handle);
|
||||
return migrated;
|
||||
}
|
||||
count = std::min<int32_t>(
|
||||
count, static_cast<int32_t>(kMaximumFriendCount));
|
||||
for (int32_t index = 0; index < count; ++index) {
|
||||
char key[16]{};
|
||||
std::snprintf(key, sizeof(key), "f_%u",
|
||||
static_cast<unsigned>(index));
|
||||
std::array<char, 256> json{};
|
||||
size_t size = json.size();
|
||||
if (nvs_get_str(
|
||||
friends_handle,
|
||||
key,
|
||||
json.data(),
|
||||
&size) != ESP_OK) {
|
||||
continue;
|
||||
}
|
||||
cJSON* root = cJSON_Parse(json.data());
|
||||
const cJSON* mac =
|
||||
cJSON_GetObjectItemCaseSensitive(root, "mac");
|
||||
const cJSON* name =
|
||||
cJSON_GetObjectItemCaseSensitive(root, "name");
|
||||
FriendPeer peer;
|
||||
const bool valid =
|
||||
cJSON_IsString(mac) &&
|
||||
cJSON_IsString(name) &&
|
||||
CopyString(mac->valuestring, &peer.mac) &&
|
||||
CopyString(name->valuestring, &peer.name);
|
||||
cJSON_Delete(root);
|
||||
if (valid && AddOrUpdateFriend(snapshot, peer)) {
|
||||
migrated = true;
|
||||
}
|
||||
}
|
||||
nvs_close(friends_handle);
|
||||
return migrated;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
bool NvsFriendStore::Load(FriendStoreSnapshot* snapshot) const
|
||||
{
|
||||
if (snapshot == nullptr) {
|
||||
return false;
|
||||
}
|
||||
auto legacy = MakePsramObject<FriendStoreSnapshot>();
|
||||
auto stored = MakePsramObject<PersistedFriendSnapshot>();
|
||||
if (!legacy || !stored) {
|
||||
ESP_LOGE(kTag, "PSRAM work-buffer allocation failed");
|
||||
return false;
|
||||
}
|
||||
const bool has_legacy = LoadLegacy(legacy.get());
|
||||
*snapshot = {};
|
||||
nvs_handle_t handle = 0;
|
||||
esp_err_t result =
|
||||
nvs_open(kNamespace, NVS_READONLY, &handle);
|
||||
if (result == ESP_ERR_NVS_NOT_FOUND) {
|
||||
*snapshot = *legacy;
|
||||
if (has_legacy) {
|
||||
ESP_LOGI(kTag, "migrated legacy friends/device name");
|
||||
Save(*snapshot);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
if (result != ESP_OK) {
|
||||
ESP_LOGE(kTag, "open failed: %s", esp_err_to_name(result));
|
||||
return false;
|
||||
}
|
||||
size_t size = sizeof(*stored);
|
||||
result = nvs_get_blob(
|
||||
handle, kSnapshotKey, stored.get(), &size);
|
||||
nvs_close(handle);
|
||||
if (result == ESP_ERR_NVS_NOT_FOUND) {
|
||||
*snapshot = *legacy;
|
||||
if (has_legacy) {
|
||||
ESP_LOGI(kTag, "migrated legacy friends/device name");
|
||||
Save(*snapshot);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
const uint32_t expected = Checksum(
|
||||
stored.get(), offsetof(PersistedFriendSnapshot, checksum));
|
||||
if (result != ESP_OK || size != sizeof(*stored) ||
|
||||
stored->magic != kMagic || stored->version != kVersion ||
|
||||
stored->friend_count > kMaximumFriendCount ||
|
||||
stored->checksum != expected ||
|
||||
std::memchr(
|
||||
stored->device_name,
|
||||
'\0',
|
||||
sizeof(stored->device_name)) == nullptr) {
|
||||
ESP_LOGE(kTag, "invalid persisted friend snapshot");
|
||||
return false;
|
||||
}
|
||||
snapshot->friend_count = stored->friend_count;
|
||||
std::memcpy(
|
||||
snapshot->device_name.data(),
|
||||
stored->device_name,
|
||||
snapshot->device_name.size());
|
||||
for (size_t index = 0;
|
||||
index < snapshot->friend_count;
|
||||
++index) {
|
||||
if (!PeerValid(stored->friends[index])) {
|
||||
return false;
|
||||
}
|
||||
snapshot->friends[index] = stored->friends[index];
|
||||
}
|
||||
snapshot->has_pending_upload =
|
||||
stored->has_pending_upload != 0;
|
||||
if (snapshot->has_pending_upload) {
|
||||
if (!PeerValid(stored->pending_upload)) {
|
||||
return false;
|
||||
}
|
||||
snapshot->pending_upload = stored->pending_upload;
|
||||
}
|
||||
if (snapshot->device_name[0] == '\0' &&
|
||||
legacy->device_name[0] != '\0') {
|
||||
snapshot->device_name = legacy->device_name;
|
||||
Save(*snapshot);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool NvsFriendStore::Save(const FriendStoreSnapshot& snapshot) const
|
||||
{
|
||||
if (snapshot.friend_count > kMaximumFriendCount ||
|
||||
std::memchr(
|
||||
snapshot.device_name.data(),
|
||||
'\0',
|
||||
snapshot.device_name.size()) == nullptr ||
|
||||
(snapshot.has_pending_upload &&
|
||||
!PeerValid(snapshot.pending_upload))) {
|
||||
return false;
|
||||
}
|
||||
auto stored = MakePsramObject<PersistedFriendSnapshot>();
|
||||
if (!stored) {
|
||||
ESP_LOGE(kTag, "PSRAM work-buffer allocation failed");
|
||||
return false;
|
||||
}
|
||||
stored->friend_count =
|
||||
static_cast<uint16_t>(snapshot.friend_count);
|
||||
stored->has_pending_upload =
|
||||
snapshot.has_pending_upload ? 1 : 0;
|
||||
std::memcpy(
|
||||
stored->device_name,
|
||||
snapshot.device_name.data(),
|
||||
snapshot.device_name.size());
|
||||
for (size_t index = 0;
|
||||
index < snapshot.friend_count;
|
||||
++index) {
|
||||
if (!PeerValid(snapshot.friends[index])) {
|
||||
return false;
|
||||
}
|
||||
stored->friends[index] = snapshot.friends[index];
|
||||
}
|
||||
stored->pending_upload = snapshot.pending_upload;
|
||||
stored->checksum = Checksum(
|
||||
stored.get(), offsetof(PersistedFriendSnapshot, checksum));
|
||||
|
||||
nvs_handle_t handle = 0;
|
||||
esp_err_t result =
|
||||
nvs_open(kNamespace, NVS_READWRITE, &handle);
|
||||
if (result == ESP_OK) {
|
||||
result = nvs_set_blob(
|
||||
handle, kSnapshotKey, stored.get(), sizeof(*stored));
|
||||
}
|
||||
if (result == ESP_OK) {
|
||||
result = nvs_commit(handle);
|
||||
}
|
||||
if (handle != 0) {
|
||||
nvs_close(handle);
|
||||
}
|
||||
if (result != ESP_OK) {
|
||||
ESP_LOGE(kTag, "save failed: %s", esp_err_to_name(result));
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool AddOrUpdateFriend(
|
||||
FriendStoreSnapshot* snapshot,
|
||||
const FriendPeer& peer)
|
||||
{
|
||||
if (snapshot == nullptr || !PeerValid(peer)) {
|
||||
return false;
|
||||
}
|
||||
for (size_t index = 0;
|
||||
index < snapshot->friend_count;
|
||||
++index) {
|
||||
if (std::strcmp(
|
||||
snapshot->friends[index].mac.data(),
|
||||
peer.mac.data()) == 0) {
|
||||
snapshot->friends[index] = peer;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
if (snapshot->friend_count >= snapshot->friends.size()) {
|
||||
return false;
|
||||
}
|
||||
snapshot->friends[snapshot->friend_count++] = peer;
|
||||
return true;
|
||||
}
|
||||
|
||||
} // namespace borla
|
||||
35
main/friend/friend_store.h
Normal file
35
main/friend/friend_store.h
Normal file
@@ -0,0 +1,35 @@
|
||||
#pragma once
|
||||
|
||||
#include "friend/friend_types.h"
|
||||
|
||||
#include <array>
|
||||
#include <cstddef>
|
||||
|
||||
namespace borla {
|
||||
|
||||
struct FriendStoreSnapshot {
|
||||
std::array<char, kFriendNameCapacity> device_name{};
|
||||
std::array<FriendPeer, kMaximumFriendCount> friends{};
|
||||
size_t friend_count = 0;
|
||||
FriendPeer pending_upload{};
|
||||
bool has_pending_upload = false;
|
||||
};
|
||||
|
||||
class IFriendStore {
|
||||
public:
|
||||
virtual ~IFriendStore() = default;
|
||||
virtual bool Load(FriendStoreSnapshot* snapshot) const = 0;
|
||||
virtual bool Save(const FriendStoreSnapshot& snapshot) const = 0;
|
||||
};
|
||||
|
||||
class NvsFriendStore final : public IFriendStore {
|
||||
public:
|
||||
bool Load(FriendStoreSnapshot* snapshot) const override;
|
||||
bool Save(const FriendStoreSnapshot& snapshot) const override;
|
||||
};
|
||||
|
||||
bool AddOrUpdateFriend(
|
||||
FriendStoreSnapshot* snapshot,
|
||||
const FriendPeer& peer);
|
||||
|
||||
} // namespace borla
|
||||
215
main/friend/friend_types.cc
Normal file
215
main/friend/friend_types.cc
Normal file
@@ -0,0 +1,215 @@
|
||||
#include "friend/friend_types.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
|
||||
namespace borla {
|
||||
namespace {
|
||||
|
||||
constexpr const char* kFriendPrefix = "BorlaF-";
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
bool IsFriendName(const char* name)
|
||||
{
|
||||
return name != nullptr &&
|
||||
std::strncmp(name, kFriendPrefix, std::strlen(kFriendPrefix)) == 0;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
bool FriendCandidateSelector::Observe(
|
||||
const char* ble_mac,
|
||||
const char* advertising_name,
|
||||
int8_t rssi_dbm,
|
||||
uint64_t now_ms)
|
||||
{
|
||||
if (!IsFriendName(advertising_name) ||
|
||||
ble_mac == nullptr || now_ms == 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
FriendCandidate* slot = nullptr;
|
||||
FriendCandidate* oldest = nullptr;
|
||||
for (FriendCandidate& candidate : candidates_) {
|
||||
if (candidate.occupied &&
|
||||
std::strcmp(candidate.peer.mac.data(), ble_mac) == 0) {
|
||||
slot = &candidate;
|
||||
break;
|
||||
}
|
||||
if (!candidate.occupied && slot == nullptr) {
|
||||
slot = &candidate;
|
||||
}
|
||||
if (candidate.occupied &&
|
||||
(oldest == nullptr ||
|
||||
candidate.last_seen_ms < oldest->last_seen_ms)) {
|
||||
oldest = &candidate;
|
||||
}
|
||||
}
|
||||
if (slot == nullptr) {
|
||||
slot = oldest;
|
||||
}
|
||||
if (slot == nullptr) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!slot->occupied ||
|
||||
std::strcmp(slot->peer.mac.data(), ble_mac) != 0) {
|
||||
*slot = {};
|
||||
if (!CopyString(ble_mac, &slot->peer.mac) ||
|
||||
!CopyString(advertising_name, &slot->peer.name)) {
|
||||
*slot = {};
|
||||
return false;
|
||||
}
|
||||
slot->best_rssi_dbm = rssi_dbm;
|
||||
slot->occupied = true;
|
||||
} else {
|
||||
CopyString(advertising_name, &slot->peer.name);
|
||||
slot->best_rssi_dbm =
|
||||
std::max(slot->best_rssi_dbm, rssi_dbm);
|
||||
}
|
||||
if (slot->seen_count != UINT8_MAX) {
|
||||
slot->seen_count++;
|
||||
}
|
||||
slot->last_seen_ms = now_ms;
|
||||
return true;
|
||||
}
|
||||
|
||||
bool FriendCandidateSelector::Select(
|
||||
uint64_t now_ms,
|
||||
FriendPeer* peer)
|
||||
{
|
||||
if (peer == nullptr) {
|
||||
return false;
|
||||
}
|
||||
FriendCandidate* best = nullptr;
|
||||
for (FriendCandidate& candidate : candidates_) {
|
||||
if (!candidate.occupied) {
|
||||
continue;
|
||||
}
|
||||
if (now_ms < candidate.last_seen_ms ||
|
||||
now_ms - candidate.last_seen_ms > kStaleAfterMs) {
|
||||
candidate = {};
|
||||
continue;
|
||||
}
|
||||
const bool eligible =
|
||||
candidate.best_rssi_dbm >= kStrongRssiDbm ||
|
||||
(candidate.best_rssi_dbm >= kWeakRssiDbm &&
|
||||
candidate.seen_count >= kWeakMinimumSeen);
|
||||
if (eligible &&
|
||||
(best == nullptr ||
|
||||
candidate.best_rssi_dbm > best->best_rssi_dbm)) {
|
||||
best = &candidate;
|
||||
}
|
||||
}
|
||||
if (best == nullptr) {
|
||||
return false;
|
||||
}
|
||||
*peer = best->peer;
|
||||
return NormalizeBleMacToBaseMac(
|
||||
best->peer.mac.data(),
|
||||
peer->mac.data(),
|
||||
peer->mac.size());
|
||||
}
|
||||
|
||||
void FriendCandidateSelector::Reset()
|
||||
{
|
||||
candidates_.fill(FriendCandidate{});
|
||||
}
|
||||
|
||||
bool NormalizeBleMacToBaseMac(
|
||||
const char* ble_mac,
|
||||
char* base_mac,
|
||||
size_t capacity)
|
||||
{
|
||||
if (ble_mac == nullptr || base_mac == nullptr ||
|
||||
capacity < kFriendMacCapacity) {
|
||||
return false;
|
||||
}
|
||||
unsigned values[6]{};
|
||||
char trailing = '\0';
|
||||
if (std::sscanf(
|
||||
ble_mac,
|
||||
"%2x:%2x:%2x:%2x:%2x:%2x%c",
|
||||
&values[0],
|
||||
&values[1],
|
||||
&values[2],
|
||||
&values[3],
|
||||
&values[4],
|
||||
&values[5],
|
||||
&trailing) != 6) {
|
||||
return false;
|
||||
}
|
||||
uint64_t value = 0;
|
||||
for (unsigned octet : values) {
|
||||
if (octet > 0xFFU) {
|
||||
return false;
|
||||
}
|
||||
value = (value << 8U) | octet;
|
||||
}
|
||||
if (value < 2) {
|
||||
return false;
|
||||
}
|
||||
value -= 2;
|
||||
// Lower case, non-negotiable. The normalized base MAC is the peer
|
||||
// device's device_id, sent verbatim in friend_add, and the server matches
|
||||
// device ids case-sensitively — the same contract that made the uppercase
|
||||
// MAC in borla_s3_platform.cc loop the activation prompt forever. The
|
||||
// previous firmware's BleMacToBaseMac emitted lower case here too.
|
||||
const int written = std::snprintf(
|
||||
base_mac,
|
||||
capacity,
|
||||
"%02x:%02x:%02x:%02x:%02x:%02x",
|
||||
static_cast<unsigned>((value >> 40U) & 0xFFU),
|
||||
static_cast<unsigned>((value >> 32U) & 0xFFU),
|
||||
static_cast<unsigned>((value >> 24U) & 0xFFU),
|
||||
static_cast<unsigned>((value >> 16U) & 0xFFU),
|
||||
static_cast<unsigned>((value >> 8U) & 0xFFU),
|
||||
static_cast<unsigned>(value & 0xFFU));
|
||||
return written == 17;
|
||||
}
|
||||
|
||||
bool BuildFriendAdvertisingName(
|
||||
const char* base_mac,
|
||||
char* output,
|
||||
size_t capacity)
|
||||
{
|
||||
if (base_mac == nullptr || output == nullptr ||
|
||||
capacity < 12) {
|
||||
return false;
|
||||
}
|
||||
char compact[13]{};
|
||||
size_t count = 0;
|
||||
for (size_t index = 0;
|
||||
base_mac[index] != '\0' && count < 12;
|
||||
++index) {
|
||||
if (base_mac[index] != ':') {
|
||||
compact[count++] = base_mac[index];
|
||||
}
|
||||
}
|
||||
if (count != 12) {
|
||||
return false;
|
||||
}
|
||||
const int written = std::snprintf(
|
||||
output,
|
||||
capacity,
|
||||
"BorlaF-%.4s",
|
||||
compact + 8);
|
||||
return written == 11;
|
||||
}
|
||||
|
||||
} // namespace borla
|
||||
56
main/friend/friend_types.h
Normal file
56
main/friend/friend_types.h
Normal file
@@ -0,0 +1,56 @@
|
||||
#pragma once
|
||||
|
||||
#include <array>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
|
||||
namespace borla {
|
||||
|
||||
inline constexpr size_t kFriendMacCapacity = 18;
|
||||
inline constexpr size_t kFriendNameCapacity = 64;
|
||||
inline constexpr size_t kFriendAdvertisingNameCapacity = 32;
|
||||
inline constexpr size_t kMaximumFriendCount = 20;
|
||||
inline constexpr size_t kMaximumFriendCandidates = 8;
|
||||
|
||||
struct FriendPeer {
|
||||
std::array<char, kFriendMacCapacity> mac{};
|
||||
std::array<char, kFriendNameCapacity> name{};
|
||||
};
|
||||
|
||||
struct FriendCandidate {
|
||||
FriendPeer peer{};
|
||||
int8_t best_rssi_dbm = -127;
|
||||
uint8_t seen_count = 0;
|
||||
uint64_t last_seen_ms = 0;
|
||||
bool occupied = false;
|
||||
};
|
||||
|
||||
class FriendCandidateSelector final {
|
||||
public:
|
||||
static constexpr int8_t kStrongRssiDbm = -60;
|
||||
static constexpr int8_t kWeakRssiDbm = -85;
|
||||
static constexpr uint8_t kWeakMinimumSeen = 2;
|
||||
static constexpr uint64_t kStaleAfterMs = 6000;
|
||||
|
||||
bool Observe(
|
||||
const char* ble_mac,
|
||||
const char* advertising_name,
|
||||
int8_t rssi_dbm,
|
||||
uint64_t now_ms);
|
||||
bool Select(uint64_t now_ms, FriendPeer* peer);
|
||||
void Reset();
|
||||
|
||||
private:
|
||||
std::array<FriendCandidate, kMaximumFriendCandidates> candidates_{};
|
||||
};
|
||||
|
||||
bool NormalizeBleMacToBaseMac(
|
||||
const char* ble_mac,
|
||||
char* base_mac,
|
||||
size_t capacity);
|
||||
bool BuildFriendAdvertisingName(
|
||||
const char* base_mac,
|
||||
char* output,
|
||||
size_t capacity);
|
||||
|
||||
} // namespace borla
|
||||
Reference in New Issue
Block a user