bolar_2 backup
This commit is contained in:
148
main/platform/borla_s3/battery_monitor.cc
Normal file
148
main/platform/borla_s3/battery_monitor.cc
Normal file
@@ -0,0 +1,148 @@
|
||||
#include "platform/borla_s3/battery_monitor.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
|
||||
#include <esp_adc/adc_cali_scheme.h>
|
||||
#include <esp_err.h>
|
||||
#include <esp_log.h>
|
||||
#include <freertos/FreeRTOS.h>
|
||||
#include <freertos/task.h>
|
||||
|
||||
namespace borla {
|
||||
namespace {
|
||||
|
||||
constexpr const char* kTag = "BatteryMonitor2";
|
||||
constexpr adc_channel_t kBatteryAdcChannel = ADC_CHANNEL_9;
|
||||
constexpr size_t kSampleCount = 32;
|
||||
constexpr size_t kTrimCount = 8;
|
||||
|
||||
} // namespace
|
||||
|
||||
BatteryMonitor::~BatteryMonitor()
|
||||
{
|
||||
if (calibration_ != nullptr) {
|
||||
adc_cali_delete_scheme_curve_fitting(calibration_);
|
||||
}
|
||||
if (adc_ != nullptr) {
|
||||
adc_oneshot_del_unit(adc_);
|
||||
}
|
||||
}
|
||||
|
||||
bool BatteryMonitor::Initialize()
|
||||
{
|
||||
if (adc_ != nullptr) {
|
||||
return true;
|
||||
}
|
||||
const adc_oneshot_unit_init_cfg_t unit_config = {
|
||||
.unit_id = ADC_UNIT_1,
|
||||
.clk_src = ADC_RTC_CLK_SRC_DEFAULT,
|
||||
.ulp_mode = ADC_ULP_MODE_DISABLE,
|
||||
};
|
||||
esp_err_t result =
|
||||
adc_oneshot_new_unit(&unit_config, &adc_);
|
||||
if (result != ESP_OK) {
|
||||
ESP_LOGE(kTag, "ADC unit initialization failed: %s",
|
||||
esp_err_to_name(result));
|
||||
adc_ = nullptr;
|
||||
return false;
|
||||
}
|
||||
const adc_oneshot_chan_cfg_t channel_config = {
|
||||
.atten = ADC_ATTEN_DB_12,
|
||||
.bitwidth = ADC_BITWIDTH_DEFAULT,
|
||||
};
|
||||
result = adc_oneshot_config_channel(
|
||||
adc_, kBatteryAdcChannel, &channel_config);
|
||||
if (result != ESP_OK) {
|
||||
ESP_LOGE(kTag, "ADC channel configuration failed: %s",
|
||||
esp_err_to_name(result));
|
||||
adc_oneshot_del_unit(adc_);
|
||||
adc_ = nullptr;
|
||||
return false;
|
||||
}
|
||||
|
||||
const adc_cali_curve_fitting_config_t calibration_config = {
|
||||
.unit_id = ADC_UNIT_1,
|
||||
.chan = kBatteryAdcChannel,
|
||||
.atten = ADC_ATTEN_DB_12,
|
||||
.bitwidth = ADC_BITWIDTH_DEFAULT,
|
||||
};
|
||||
result = adc_cali_create_scheme_curve_fitting(
|
||||
&calibration_config, &calibration_);
|
||||
if (result != ESP_OK) {
|
||||
calibration_ = nullptr;
|
||||
ESP_LOGW(kTag, "eFuse calibration unavailable: %s",
|
||||
esp_err_to_name(result));
|
||||
}
|
||||
ESP_LOGI(kTag, "battery ADC initialized on GPIO10");
|
||||
return true;
|
||||
}
|
||||
|
||||
bool BatteryMonitor::Read(uint64_t now_ms, BatteryStatus* status)
|
||||
{
|
||||
if (adc_ == nullptr || status == nullptr) {
|
||||
return false;
|
||||
}
|
||||
std::array<int, kSampleCount> samples{};
|
||||
for (int& sample : samples) {
|
||||
if (adc_oneshot_read(
|
||||
adc_, kBatteryAdcChannel, &sample) != ESP_OK) {
|
||||
return false;
|
||||
}
|
||||
vTaskDelay(pdMS_TO_TICKS(1));
|
||||
}
|
||||
std::sort(samples.begin(), samples.end());
|
||||
uint32_t sum = 0;
|
||||
for (size_t i = kTrimCount;
|
||||
i < samples.size() - kTrimCount;
|
||||
++i) {
|
||||
sum += static_cast<uint32_t>(samples[i]);
|
||||
}
|
||||
const int raw = static_cast<int>(
|
||||
sum / (samples.size() - 2 * kTrimCount));
|
||||
int pin_millivolts = raw * 3100 / 4095;
|
||||
if (calibration_ != nullptr) {
|
||||
int calibrated = 0;
|
||||
if (adc_cali_raw_to_voltage(
|
||||
calibration_, raw, &calibrated) == ESP_OK) {
|
||||
pin_millivolts = calibrated;
|
||||
}
|
||||
}
|
||||
const uint16_t battery_millivolts = static_cast<uint16_t>(
|
||||
std::clamp(pin_millivolts * 3 / 2, 0, 5000));
|
||||
if (!BatteryEstimator::IsPlausibleVoltage(
|
||||
battery_millivolts)) {
|
||||
if (!invalid_sample_reported_) {
|
||||
ESP_LOGW(kTag,
|
||||
"invalid battery sample raw=%d pin=%dmV battery=%umV; "
|
||||
"status remains unavailable",
|
||||
raw,
|
||||
pin_millivolts,
|
||||
static_cast<unsigned>(battery_millivolts));
|
||||
invalid_sample_reported_ = true;
|
||||
} else {
|
||||
ESP_LOGD(kTag,
|
||||
"battery sample still invalid raw=%d battery=%umV",
|
||||
raw,
|
||||
static_cast<unsigned>(battery_millivolts));
|
||||
}
|
||||
*status = {};
|
||||
return false;
|
||||
}
|
||||
if (invalid_sample_reported_) {
|
||||
ESP_LOGI(kTag, "battery sample recovered battery=%umV",
|
||||
static_cast<unsigned>(battery_millivolts));
|
||||
invalid_sample_reported_ = false;
|
||||
}
|
||||
estimator_.Update(battery_millivolts);
|
||||
*status = {
|
||||
.timestamp_ms = now_ms,
|
||||
.millivolts = estimator_.smoothed_millivolts(),
|
||||
.percent = estimator_.percent(),
|
||||
.charging = estimator_.charging(),
|
||||
.valid = true,
|
||||
};
|
||||
return true;
|
||||
}
|
||||
|
||||
} // namespace borla
|
||||
26
main/platform/borla_s3/battery_monitor.h
Normal file
26
main/platform/borla_s3/battery_monitor.h
Normal file
@@ -0,0 +1,26 @@
|
||||
#pragma once
|
||||
|
||||
#include "sensor/battery_estimator.h"
|
||||
#include "sensor/sensor_types.h"
|
||||
|
||||
#include <esp_adc/adc_cali.h>
|
||||
#include <esp_adc/adc_oneshot.h>
|
||||
|
||||
namespace borla {
|
||||
|
||||
class BatteryMonitor final {
|
||||
public:
|
||||
BatteryMonitor() = default;
|
||||
~BatteryMonitor();
|
||||
|
||||
bool Initialize();
|
||||
bool Read(uint64_t now_ms, BatteryStatus* status);
|
||||
|
||||
private:
|
||||
adc_oneshot_unit_handle_t adc_ = nullptr;
|
||||
adc_cali_handle_t calibration_ = nullptr;
|
||||
BatteryEstimator estimator_;
|
||||
bool invalid_sample_reported_ = false;
|
||||
};
|
||||
|
||||
} // namespace borla
|
||||
480
main/platform/borla_s3/ble_friend_exchange.cc
Normal file
480
main/platform/borla_s3/ble_friend_exchange.cc
Normal file
@@ -0,0 +1,480 @@
|
||||
#include "platform/borla_s3/ble_friend_exchange.h"
|
||||
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
|
||||
#include <esp_err.h>
|
||||
#include <esp_log.h>
|
||||
#include <host/ble_gap.h>
|
||||
#include <host/ble_hs.h>
|
||||
#include <host/util/util.h>
|
||||
#include <nimble/nimble_port.h>
|
||||
#include <services/gap/ble_svc_gap.h>
|
||||
|
||||
namespace borla {
|
||||
namespace {
|
||||
|
||||
constexpr const char* kTag = "BleFriend2";
|
||||
constexpr uint32_t kModeTimeoutMs = 30000;
|
||||
constexpr uint32_t kPhaseDurationMs = 2000;
|
||||
constexpr uint32_t kGraceDurationMs = 4000;
|
||||
constexpr uint32_t kNimbleInitializationError = 12101;
|
||||
constexpr uint32_t kNimbleSyncError = 12102;
|
||||
constexpr uint32_t kGapStartError = 12103;
|
||||
constexpr uint32_t kNimbleSyncTimeoutMs = 5000;
|
||||
constexpr uint32_t kControllerReleaseDelayMs = 200;
|
||||
|
||||
BleFriendExchange* g_exchange = nullptr;
|
||||
|
||||
} // namespace
|
||||
|
||||
bool BleFriendExchange::Initialize()
|
||||
{
|
||||
if (initialized_.load()) {
|
||||
return true;
|
||||
}
|
||||
if (g_exchange != nullptr && g_exchange != this) {
|
||||
return false;
|
||||
}
|
||||
queue_ = xQueueCreateStatic(
|
||||
kQueueDepth,
|
||||
sizeof(Command),
|
||||
queue_storage_.data(),
|
||||
&queue_control_);
|
||||
if (queue_ == nullptr) {
|
||||
return false;
|
||||
}
|
||||
candidate_mutex_ =
|
||||
xSemaphoreCreateMutexStatic(&candidate_mutex_storage_);
|
||||
if (candidate_mutex_ == nullptr) {
|
||||
return false;
|
||||
}
|
||||
const esp_timer_create_args_t timer_args = {
|
||||
.callback = &BleFriendExchange::TimerCallback,
|
||||
.arg = this,
|
||||
.dispatch_method = ESP_TIMER_TASK,
|
||||
.name = "friend_tick2",
|
||||
.skip_unhandled_events = true,
|
||||
};
|
||||
if (esp_timer_create(&timer_args, &timer_) != ESP_OK) {
|
||||
return false;
|
||||
}
|
||||
worker_task_ = xTaskCreateStatic(
|
||||
&BleFriendExchange::WorkerTaskEntry,
|
||||
"friend_ble2",
|
||||
worker_task_stack_.size(),
|
||||
this,
|
||||
kWorkerPriority,
|
||||
worker_task_stack_.data(),
|
||||
&worker_task_control_);
|
||||
if (worker_task_ == nullptr) {
|
||||
return false;
|
||||
}
|
||||
g_exchange = this;
|
||||
initialized_.store(true);
|
||||
return true;
|
||||
}
|
||||
|
||||
bool BleFriendExchange::Start(
|
||||
const char* local_base_mac,
|
||||
IBleFriendExchangeObserver& observer)
|
||||
{
|
||||
Command command;
|
||||
command.type = CommandType::kStart;
|
||||
command.observer = &observer;
|
||||
if (!BuildFriendAdvertisingName(
|
||||
local_base_mac,
|
||||
command.advertising_name.data(),
|
||||
command.advertising_name.size())) {
|
||||
return false;
|
||||
}
|
||||
return Post(command);
|
||||
}
|
||||
|
||||
void BleFriendExchange::Stop()
|
||||
{
|
||||
Post({CommandType::kStop});
|
||||
}
|
||||
|
||||
void BleFriendExchange::WorkerTaskEntry(void* context)
|
||||
{
|
||||
static_cast<BleFriendExchange*>(context)->Run();
|
||||
}
|
||||
|
||||
void BleFriendExchange::HostTaskEntry(void* context)
|
||||
{
|
||||
auto* exchange = static_cast<BleFriendExchange*>(context);
|
||||
ESP_LOGI(kTag, "NimBLE host task started");
|
||||
nimble_port_run();
|
||||
exchange->host_task_ = nullptr;
|
||||
vTaskDelete(nullptr);
|
||||
}
|
||||
|
||||
void BleFriendExchange::TimerCallback(void* context)
|
||||
{
|
||||
auto* exchange = static_cast<BleFriendExchange*>(context);
|
||||
exchange->Post({CommandType::kTick});
|
||||
}
|
||||
|
||||
void BleFriendExchange::HostSyncCallback()
|
||||
{
|
||||
if (g_exchange == nullptr || !g_exchange->active_.load()) {
|
||||
return;
|
||||
}
|
||||
int result = ble_hs_util_ensure_addr(0);
|
||||
if (result == 0) {
|
||||
result = ble_hs_id_infer_auto(
|
||||
0, &g_exchange->own_address_type_);
|
||||
}
|
||||
if (result != 0) {
|
||||
ESP_LOGE(kTag, "BLE address setup failed rc=%d", result);
|
||||
g_exchange->Post({CommandType::kStop});
|
||||
return;
|
||||
}
|
||||
g_exchange->host_synced_.store(true);
|
||||
g_exchange->Post({CommandType::kSynced});
|
||||
}
|
||||
|
||||
void BleFriendExchange::HostResetCallback(int reason)
|
||||
{
|
||||
ESP_LOGW(kTag, "NimBLE host reset reason=%d", reason);
|
||||
}
|
||||
|
||||
int BleFriendExchange::GapEventCallback(
|
||||
ble_gap_event* event,
|
||||
void* context)
|
||||
{
|
||||
auto* exchange = static_cast<BleFriendExchange*>(context);
|
||||
return exchange == nullptr
|
||||
? 0
|
||||
: exchange->HandleGapEvent(event);
|
||||
}
|
||||
|
||||
[[noreturn]] void BleFriendExchange::Run()
|
||||
{
|
||||
while (true) {
|
||||
Command command;
|
||||
if (xQueueReceive(queue_, &command, portMAX_DELAY) == pdTRUE) {
|
||||
Handle(command);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
bool BleFriendExchange::Post(const Command& command)
|
||||
{
|
||||
return initialized_.load() && queue_ != nullptr &&
|
||||
xQueueSend(queue_, &command, 0) == pdTRUE;
|
||||
}
|
||||
|
||||
void BleFriendExchange::Handle(const Command& command)
|
||||
{
|
||||
switch (command.type) {
|
||||
case CommandType::kStart:
|
||||
HandleStart(command);
|
||||
return;
|
||||
case CommandType::kStop:
|
||||
HandleStop(0);
|
||||
return;
|
||||
case CommandType::kSynced:
|
||||
if (active_.load() && !StartScan()) {
|
||||
HandleStop(kGapStartError);
|
||||
}
|
||||
return;
|
||||
case CommandType::kScanComplete:
|
||||
if (!active_.load()) {
|
||||
return;
|
||||
}
|
||||
if (grace_requested_) {
|
||||
grace_requested_ = false;
|
||||
if (!StartAdvertising(true)) {
|
||||
HandleStop(kGapStartError);
|
||||
}
|
||||
} else if (!StartAdvertising(false)) {
|
||||
HandleStop(kGapStartError);
|
||||
}
|
||||
return;
|
||||
case CommandType::kAdvertiseComplete:
|
||||
if (!active_.load()) {
|
||||
return;
|
||||
}
|
||||
if (phase_ == GapPhase::kGraceAdvertising) {
|
||||
HandleStop(0);
|
||||
} else if (grace_requested_) {
|
||||
grace_requested_ = false;
|
||||
if (!StartAdvertising(true)) {
|
||||
HandleStop(kGapStartError);
|
||||
}
|
||||
} else if (!StartScan()) {
|
||||
HandleStop(kGapStartError);
|
||||
}
|
||||
return;
|
||||
case CommandType::kTick:
|
||||
HandleTick();
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
void BleFriendExchange::HandleStart(const Command& command)
|
||||
{
|
||||
if (active_.load()) {
|
||||
return;
|
||||
}
|
||||
observer_ = command.observer;
|
||||
advertising_name_ = command.advertising_name;
|
||||
ResetCandidates();
|
||||
paired_ = false;
|
||||
match_reported_ = false;
|
||||
grace_requested_ = false;
|
||||
phase_ = GapPhase::kIdle;
|
||||
host_synced_.store(false);
|
||||
active_.store(true);
|
||||
const uint64_t now = NowMs();
|
||||
sync_deadline_ms_ = now + kNimbleSyncTimeoutMs;
|
||||
deadline_ms_ = now + kModeTimeoutMs;
|
||||
|
||||
const esp_err_t init_result = nimble_port_init();
|
||||
if (init_result != ESP_OK) {
|
||||
ESP_LOGE(kTag, "nimble_port_init failed: %s",
|
||||
esp_err_to_name(init_result));
|
||||
HandleStop(kNimbleInitializationError);
|
||||
return;
|
||||
}
|
||||
nimble_initialized_ = true;
|
||||
ble_hs_cfg.reset_cb = &BleFriendExchange::HostResetCallback;
|
||||
ble_hs_cfg.sync_cb = &BleFriendExchange::HostSyncCallback;
|
||||
ble_svc_gap_init();
|
||||
if (ble_svc_gap_device_name_set(
|
||||
advertising_name_.data()) != 0) {
|
||||
HandleStop(kNimbleInitializationError);
|
||||
return;
|
||||
}
|
||||
host_task_ = xTaskCreateStaticPinnedToCore(
|
||||
&BleFriendExchange::HostTaskEntry,
|
||||
"friend_host2",
|
||||
host_task_stack_.size(),
|
||||
this,
|
||||
configMAX_PRIORITIES - 4,
|
||||
host_task_stack_.data(),
|
||||
&host_task_control_,
|
||||
CONFIG_BT_NIMBLE_PINNED_TO_CORE);
|
||||
if (host_task_ == nullptr) {
|
||||
HandleStop(kNimbleInitializationError);
|
||||
return;
|
||||
}
|
||||
esp_timer_stop(timer_);
|
||||
esp_timer_start_periodic(timer_, 1000ULL * 1000ULL);
|
||||
ESP_LOGI(kTag, "friend exchange started name=%s",
|
||||
advertising_name_.data());
|
||||
}
|
||||
|
||||
void BleFriendExchange::HandleStop(uint32_t error_id)
|
||||
{
|
||||
if (!active_.exchange(false) && !nimble_initialized_) {
|
||||
return;
|
||||
}
|
||||
if (timer_ != nullptr) {
|
||||
esp_timer_stop(timer_);
|
||||
}
|
||||
if (host_synced_.load()) {
|
||||
ble_gap_disc_cancel();
|
||||
ble_gap_adv_stop();
|
||||
// Both calls only queue the stop to the controller. Tearing the host
|
||||
// down in the same breath can deinit the port while the controller is
|
||||
// still winding an advertising or scan context down, and the BT memory
|
||||
// then comes back late or not at all — which matters here because the
|
||||
// caller re-attaches WiFi immediately afterwards and the two stacks
|
||||
// together do not fit in internal RAM. The previous firmware waited the
|
||||
// same 200 ms in the same position for the same reason.
|
||||
vTaskDelay(pdMS_TO_TICKS(kControllerReleaseDelayMs));
|
||||
}
|
||||
if (nimble_initialized_) {
|
||||
const int stop_result = nimble_port_stop();
|
||||
if (stop_result == 0) {
|
||||
nimble_port_deinit();
|
||||
} else {
|
||||
ESP_LOGW(kTag, "nimble stop failed rc=%d", stop_result);
|
||||
if (error_id == 0) {
|
||||
error_id = kNimbleInitializationError;
|
||||
}
|
||||
}
|
||||
}
|
||||
nimble_initialized_ = false;
|
||||
host_synced_.store(false);
|
||||
phase_ = GapPhase::kIdle;
|
||||
sync_deadline_ms_ = 0;
|
||||
deadline_ms_ = 0;
|
||||
ResetCandidates();
|
||||
IBleFriendExchangeObserver* observer = observer_;
|
||||
observer_ = nullptr;
|
||||
if (observer != nullptr) {
|
||||
observer->OnBleFriendExchangeStopped(paired_, error_id);
|
||||
}
|
||||
ESP_LOGI(kTag, "friend exchange stopped paired=%d error=%lu",
|
||||
paired_ ? 1 : 0,
|
||||
static_cast<unsigned long>(error_id));
|
||||
}
|
||||
|
||||
bool BleFriendExchange::StartScan()
|
||||
{
|
||||
ble_gap_disc_params parameters{};
|
||||
parameters.passive = 1;
|
||||
parameters.itvl = 80;
|
||||
parameters.window = 60;
|
||||
parameters.filter_duplicates = 0;
|
||||
parameters.limited = 0;
|
||||
const int result = ble_gap_disc(
|
||||
own_address_type_,
|
||||
kPhaseDurationMs,
|
||||
¶meters,
|
||||
&BleFriendExchange::GapEventCallback,
|
||||
this);
|
||||
if (result != 0) {
|
||||
ESP_LOGE(kTag, "scan start failed rc=%d", result);
|
||||
return false;
|
||||
}
|
||||
phase_ = GapPhase::kScanning;
|
||||
return true;
|
||||
}
|
||||
|
||||
bool BleFriendExchange::StartAdvertising(bool grace)
|
||||
{
|
||||
ble_hs_adv_fields fields{};
|
||||
fields.flags =
|
||||
BLE_HS_ADV_F_DISC_GEN | BLE_HS_ADV_F_BREDR_UNSUP;
|
||||
fields.name = reinterpret_cast<uint8_t*>(
|
||||
advertising_name_.data());
|
||||
fields.name_len = static_cast<uint8_t>(
|
||||
std::strlen(advertising_name_.data()));
|
||||
fields.name_is_complete = 1;
|
||||
int result = ble_gap_adv_set_fields(&fields);
|
||||
if (result != 0) {
|
||||
return false;
|
||||
}
|
||||
ble_gap_adv_params parameters{};
|
||||
parameters.conn_mode = BLE_GAP_CONN_MODE_NON;
|
||||
parameters.disc_mode = BLE_GAP_DISC_MODE_GEN;
|
||||
parameters.itvl_min = 48;
|
||||
parameters.itvl_max = 96;
|
||||
result = ble_gap_adv_start(
|
||||
own_address_type_,
|
||||
nullptr,
|
||||
grace ? kGraceDurationMs : kPhaseDurationMs,
|
||||
¶meters,
|
||||
&BleFriendExchange::GapEventCallback,
|
||||
this);
|
||||
if (result != 0) {
|
||||
ESP_LOGE(kTag, "advertising start failed rc=%d", result);
|
||||
return false;
|
||||
}
|
||||
phase_ = grace
|
||||
? GapPhase::kGraceAdvertising
|
||||
: GapPhase::kAdvertising;
|
||||
return true;
|
||||
}
|
||||
|
||||
void BleFriendExchange::HandleTick()
|
||||
{
|
||||
if (!active_.load()) {
|
||||
return;
|
||||
}
|
||||
const uint64_t now = NowMs();
|
||||
if (now >= deadline_ms_) {
|
||||
HandleStop(0);
|
||||
return;
|
||||
}
|
||||
if (!host_synced_.load() && now >= sync_deadline_ms_) {
|
||||
HandleStop(kNimbleSyncError);
|
||||
return;
|
||||
}
|
||||
if (match_reported_) {
|
||||
return;
|
||||
}
|
||||
FriendPeer peer;
|
||||
xSemaphoreTake(candidate_mutex_, portMAX_DELAY);
|
||||
const bool matched = candidates_.Select(now, &peer);
|
||||
xSemaphoreGive(candidate_mutex_);
|
||||
if (!matched) {
|
||||
return;
|
||||
}
|
||||
match_reported_ = true;
|
||||
paired_ = true;
|
||||
grace_requested_ = true;
|
||||
if (observer_ != nullptr) {
|
||||
observer_->OnBleFriendMatched(peer);
|
||||
}
|
||||
if (phase_ == GapPhase::kScanning) {
|
||||
ble_gap_disc_cancel();
|
||||
}
|
||||
}
|
||||
|
||||
int BleFriendExchange::HandleGapEvent(ble_gap_event* event)
|
||||
{
|
||||
if (event == nullptr || !active_.load()) {
|
||||
return 0;
|
||||
}
|
||||
switch (event->type) {
|
||||
case BLE_GAP_EVENT_DISC: {
|
||||
ble_hs_adv_fields fields{};
|
||||
if (ble_hs_adv_parse_fields(
|
||||
&fields,
|
||||
event->disc.data,
|
||||
event->disc.length_data) != 0 ||
|
||||
fields.name == nullptr || fields.name_len == 0 ||
|
||||
fields.name_len >= kFriendAdvertisingNameCapacity) {
|
||||
return 0;
|
||||
}
|
||||
std::array<char, kFriendAdvertisingNameCapacity> name{};
|
||||
std::memcpy(name.data(), fields.name, fields.name_len);
|
||||
char mac[kFriendMacCapacity]{};
|
||||
const ble_addr_t& address = event->disc.addr;
|
||||
// Lower case to match every other MAC in the system; this raw BLE MAC
|
||||
// is only a local dedup key, but NormalizeBleMacToBaseMac's output IS
|
||||
// the peer's device_id and the server matches those case-sensitively.
|
||||
std::snprintf(
|
||||
mac,
|
||||
sizeof(mac),
|
||||
"%02x:%02x:%02x:%02x:%02x:%02x",
|
||||
address.val[5],
|
||||
address.val[4],
|
||||
address.val[3],
|
||||
address.val[2],
|
||||
address.val[1],
|
||||
address.val[0]);
|
||||
xSemaphoreTake(candidate_mutex_, portMAX_DELAY);
|
||||
candidates_.Observe(
|
||||
mac,
|
||||
name.data(),
|
||||
static_cast<int8_t>(event->disc.rssi),
|
||||
NowMs());
|
||||
xSemaphoreGive(candidate_mutex_);
|
||||
return 0;
|
||||
}
|
||||
case BLE_GAP_EVENT_DISC_COMPLETE:
|
||||
Post({CommandType::kScanComplete});
|
||||
return 0;
|
||||
case BLE_GAP_EVENT_ADV_COMPLETE:
|
||||
Post({CommandType::kAdvertiseComplete});
|
||||
return 0;
|
||||
default:
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
void BleFriendExchange::ResetCandidates()
|
||||
{
|
||||
if (candidate_mutex_ == nullptr) {
|
||||
candidates_.Reset();
|
||||
return;
|
||||
}
|
||||
xSemaphoreTake(candidate_mutex_, portMAX_DELAY);
|
||||
candidates_.Reset();
|
||||
xSemaphoreGive(candidate_mutex_);
|
||||
}
|
||||
|
||||
uint64_t BleFriendExchange::NowMs() const
|
||||
{
|
||||
return static_cast<uint64_t>(
|
||||
esp_timer_get_time() / 1000ULL);
|
||||
}
|
||||
|
||||
} // namespace borla
|
||||
130
main/platform/borla_s3/ble_friend_exchange.h
Normal file
130
main/platform/borla_s3/ble_friend_exchange.h
Normal file
@@ -0,0 +1,130 @@
|
||||
#pragma once
|
||||
|
||||
#include "friend/friend_types.h"
|
||||
|
||||
#include <array>
|
||||
#include <atomic>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
|
||||
#include <esp_timer.h>
|
||||
#include <host/ble_gap.h>
|
||||
#include <freertos/FreeRTOS.h>
|
||||
#include <freertos/queue.h>
|
||||
#include <freertos/semphr.h>
|
||||
#include <freertos/task.h>
|
||||
|
||||
namespace borla {
|
||||
|
||||
class IBleFriendExchangeObserver {
|
||||
public:
|
||||
virtual ~IBleFriendExchangeObserver() = default;
|
||||
virtual void OnBleFriendMatched(const FriendPeer& peer) = 0;
|
||||
virtual void OnBleFriendExchangeStopped(
|
||||
bool paired,
|
||||
uint32_t error_id) = 0;
|
||||
};
|
||||
|
||||
class BleFriendExchange final {
|
||||
public:
|
||||
bool Initialize();
|
||||
bool Start(
|
||||
const char* local_base_mac,
|
||||
IBleFriendExchangeObserver& observer);
|
||||
void Stop();
|
||||
bool IsActive() const { return active_.load(); }
|
||||
|
||||
private:
|
||||
enum class CommandType : uint8_t {
|
||||
kStart,
|
||||
kStop,
|
||||
kSynced,
|
||||
kScanComplete,
|
||||
kAdvertiseComplete,
|
||||
kTick,
|
||||
};
|
||||
|
||||
struct Command {
|
||||
CommandType type = CommandType::kTick;
|
||||
IBleFriendExchangeObserver* observer = nullptr;
|
||||
std::array<char, kFriendAdvertisingNameCapacity>
|
||||
advertising_name{};
|
||||
};
|
||||
|
||||
enum class GapPhase : uint8_t {
|
||||
kIdle,
|
||||
kScanning,
|
||||
kAdvertising,
|
||||
kGraceAdvertising,
|
||||
};
|
||||
|
||||
static constexpr size_t kQueueDepth = 12;
|
||||
// ESP-IDF expresses task stack depths in bytes. Its Xtensa
|
||||
// StackType_t is uint8_t, so the static arrays have the same size.
|
||||
//static constexpr uint32_t kWorkerStackDepth = 2048;
|
||||
// 2026-9-6 ckkj fix: worker 在本任务栈上执行 nimble_port_init/deinit
|
||||
// (调用链深),叠加 Xtensa ISR 压栈后 2048 字节溢出触发 canary panic,
|
||||
// 提升到与 host 任务一致的 4096。
|
||||
static constexpr uint32_t kWorkerStackDepth = 4096;
|
||||
static constexpr uint32_t kHostStackDepth = 4096;
|
||||
static constexpr UBaseType_t kWorkerPriority = 5;
|
||||
|
||||
static void WorkerTaskEntry(void* context);
|
||||
static void HostTaskEntry(void* context);
|
||||
static void TimerCallback(void* context);
|
||||
static void HostSyncCallback();
|
||||
static void HostResetCallback(int reason);
|
||||
static int GapEventCallback(
|
||||
ble_gap_event* event,
|
||||
void* context);
|
||||
|
||||
[[noreturn]] void Run();
|
||||
bool Post(const Command& command);
|
||||
void Handle(const Command& command);
|
||||
void HandleStart(const Command& command);
|
||||
void HandleStop(uint32_t error_id);
|
||||
bool StartScan();
|
||||
bool StartAdvertising(bool grace);
|
||||
void HandleTick();
|
||||
void ResetCandidates();
|
||||
int HandleGapEvent(ble_gap_event* event);
|
||||
uint64_t NowMs() const;
|
||||
|
||||
QueueHandle_t queue_ = nullptr;
|
||||
StaticQueue_t queue_control_{};
|
||||
alignas(Command)
|
||||
std::array<uint8_t, kQueueDepth * sizeof(Command)>
|
||||
queue_storage_{};
|
||||
TaskHandle_t worker_task_ = nullptr;
|
||||
StaticTask_t worker_task_control_{};
|
||||
std::array<StackType_t, kWorkerStackDepth>
|
||||
worker_task_stack_{};
|
||||
TaskHandle_t host_task_ = nullptr;
|
||||
StaticTask_t host_task_control_{};
|
||||
std::array<StackType_t, kHostStackDepth>
|
||||
host_task_stack_{};
|
||||
esp_timer_handle_t timer_ = nullptr;
|
||||
|
||||
// Candidate bookkeeping runs string compares and, on selection, sscanf and
|
||||
// snprintf. That is far too much work for a spinlock with interrupts
|
||||
// disabled; both callers (NimBLE host task, friend worker task) can block.
|
||||
SemaphoreHandle_t candidate_mutex_ = nullptr;
|
||||
StaticSemaphore_t candidate_mutex_storage_{};
|
||||
FriendCandidateSelector candidates_;
|
||||
IBleFriendExchangeObserver* observer_ = nullptr;
|
||||
std::array<char, kFriendAdvertisingNameCapacity>
|
||||
advertising_name_{};
|
||||
std::atomic<bool> initialized_{false};
|
||||
std::atomic<bool> active_{false};
|
||||
std::atomic<bool> host_synced_{false};
|
||||
bool nimble_initialized_ = false;
|
||||
bool paired_ = false;
|
||||
bool match_reported_ = false;
|
||||
bool grace_requested_ = false;
|
||||
uint8_t own_address_type_ = 0;
|
||||
GapPhase phase_ = GapPhase::kIdle;
|
||||
uint64_t sync_deadline_ms_ = 0;
|
||||
uint64_t deadline_ms_ = 0;
|
||||
};
|
||||
|
||||
} // namespace borla
|
||||
717
main/platform/borla_s3/ble_provisioning_gatt.cc
Normal file
717
main/platform/borla_s3/ble_provisioning_gatt.cc
Normal file
@@ -0,0 +1,717 @@
|
||||
#include "platform/borla_s3/ble_provisioning_gatt.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cstring>
|
||||
|
||||
#include <esp_err.h>
|
||||
#include <esp_heap_caps.h>
|
||||
#include <esp_log.h>
|
||||
#include <host/ble_att.h>
|
||||
#include <host/ble_gap.h>
|
||||
#include <host/ble_gatt.h>
|
||||
#include <host/ble_hs.h>
|
||||
#include <host/util/util.h>
|
||||
#include <nimble/nimble_port.h>
|
||||
#include <os/os_mbuf.h>
|
||||
#include <services/gap/ble_svc_gap.h>
|
||||
#include <services/gatt/ble_svc_gatt.h>
|
||||
#include <store/config/ble_store_config.h>
|
||||
|
||||
extern "C" void ble_store_config_init(void);
|
||||
|
||||
namespace borla {
|
||||
namespace {
|
||||
|
||||
constexpr const char* kTag = "BleProvisioning2";
|
||||
constexpr uint16_t kPreferredMtu = 517;
|
||||
constexpr uint16_t kInvalidConnectionHandle = 0xffff;
|
||||
constexpr uint32_t kHostSyncTimeoutMs = 3000;
|
||||
|
||||
BleProvisioningGattServer* g_server = nullptr;
|
||||
uint16_t g_scan_value_handle = 0;
|
||||
uint16_t g_result_value_handle = 0;
|
||||
uint16_t g_saved_wifi_value_handle = 0;
|
||||
|
||||
const ble_uuid128_t kServiceUuid =
|
||||
BLE_UUID128_INIT(
|
||||
0xfb, 0x34, 0x9b, 0x5f, 0x80, 0x00, 0x00, 0x80,
|
||||
0x00, 0x10, 0x00, 0x00, 0x01, 0xff, 0x00, 0x00);
|
||||
const ble_uuid128_t kDeviceInfoUuid =
|
||||
BLE_UUID128_INIT(
|
||||
0xfb, 0x34, 0x9b, 0x5f, 0x80, 0x00, 0x00, 0x80,
|
||||
0x00, 0x10, 0x00, 0x00, 0x02, 0xff, 0x00, 0x00);
|
||||
const ble_uuid128_t kWifiScanUuid =
|
||||
BLE_UUID128_INIT(
|
||||
0xfb, 0x34, 0x9b, 0x5f, 0x80, 0x00, 0x00, 0x80,
|
||||
0x00, 0x10, 0x00, 0x00, 0x03, 0xff, 0x00, 0x00);
|
||||
const ble_uuid128_t kWifiConfigUuid =
|
||||
BLE_UUID128_INIT(
|
||||
0xfb, 0x34, 0x9b, 0x5f, 0x80, 0x00, 0x00, 0x80,
|
||||
0x00, 0x10, 0x00, 0x00, 0x04, 0xff, 0x00, 0x00);
|
||||
const ble_uuid128_t kWifiResultUuid =
|
||||
BLE_UUID128_INIT(
|
||||
0xfb, 0x34, 0x9b, 0x5f, 0x80, 0x00, 0x00, 0x80,
|
||||
0x00, 0x10, 0x00, 0x00, 0x05, 0xff, 0x00, 0x00);
|
||||
const ble_uuid128_t kCommandUuid =
|
||||
BLE_UUID128_INIT(
|
||||
0xfb, 0x34, 0x9b, 0x5f, 0x80, 0x00, 0x00, 0x80,
|
||||
0x00, 0x10, 0x00, 0x00, 0x06, 0xff, 0x00, 0x00);
|
||||
const ble_uuid128_t kSavedWifiUuid =
|
||||
BLE_UUID128_INIT(
|
||||
0xfb, 0x34, 0x9b, 0x5f, 0x80, 0x00, 0x00, 0x80,
|
||||
0x00, 0x10, 0x00, 0x00, 0x07, 0xff, 0x00, 0x00);
|
||||
|
||||
ble_gatt_chr_def g_characteristics[] = {
|
||||
{
|
||||
.uuid = &kDeviceInfoUuid.u,
|
||||
.access_cb = BorlaBleGattAccess,
|
||||
.arg = nullptr,
|
||||
.descriptors = nullptr,
|
||||
.flags = BLE_GATT_CHR_F_READ,
|
||||
.min_key_size = 0,
|
||||
.val_handle = nullptr,
|
||||
.cpfd = nullptr,
|
||||
},
|
||||
{
|
||||
.uuid = &kWifiScanUuid.u,
|
||||
.access_cb = BorlaBleGattAccess,
|
||||
.arg = nullptr,
|
||||
.descriptors = nullptr,
|
||||
.flags = BLE_GATT_CHR_F_WRITE | BLE_GATT_CHR_F_NOTIFY,
|
||||
.min_key_size = 0,
|
||||
.val_handle = &g_scan_value_handle,
|
||||
.cpfd = nullptr,
|
||||
},
|
||||
{
|
||||
.uuid = &kWifiConfigUuid.u,
|
||||
.access_cb = BorlaBleGattAccess,
|
||||
.arg = nullptr,
|
||||
.descriptors = nullptr,
|
||||
.flags = BLE_GATT_CHR_F_WRITE,
|
||||
.min_key_size = 0,
|
||||
.val_handle = nullptr,
|
||||
.cpfd = nullptr,
|
||||
},
|
||||
{
|
||||
.uuid = &kWifiResultUuid.u,
|
||||
.access_cb = BorlaBleGattAccess,
|
||||
.arg = nullptr,
|
||||
.descriptors = nullptr,
|
||||
.flags = BLE_GATT_CHR_F_NOTIFY,
|
||||
.min_key_size = 0,
|
||||
.val_handle = &g_result_value_handle,
|
||||
.cpfd = nullptr,
|
||||
},
|
||||
{
|
||||
.uuid = &kCommandUuid.u,
|
||||
.access_cb = BorlaBleGattAccess,
|
||||
.arg = nullptr,
|
||||
.descriptors = nullptr,
|
||||
.flags = BLE_GATT_CHR_F_WRITE,
|
||||
.min_key_size = 0,
|
||||
.val_handle = nullptr,
|
||||
.cpfd = nullptr,
|
||||
},
|
||||
{
|
||||
.uuid = &kSavedWifiUuid.u,
|
||||
.access_cb = BorlaBleGattAccess,
|
||||
.arg = nullptr,
|
||||
.descriptors = nullptr,
|
||||
.flags = BLE_GATT_CHR_F_WRITE | BLE_GATT_CHR_F_NOTIFY,
|
||||
.min_key_size = 0,
|
||||
.val_handle = &g_saved_wifi_value_handle,
|
||||
.cpfd = nullptr,
|
||||
},
|
||||
{},
|
||||
};
|
||||
|
||||
const ble_gatt_svc_def g_services[] = {
|
||||
{
|
||||
.type = BLE_GATT_SVC_TYPE_PRIMARY,
|
||||
.uuid = &kServiceUuid.u,
|
||||
.includes = nullptr,
|
||||
.characteristics = g_characteristics,
|
||||
},
|
||||
{},
|
||||
};
|
||||
|
||||
bool ReadMbuf(
|
||||
os_mbuf* buffer,
|
||||
uint8_t* output,
|
||||
size_t capacity,
|
||||
size_t* size)
|
||||
{
|
||||
if (buffer == nullptr || output == nullptr || size == nullptr) {
|
||||
return false;
|
||||
}
|
||||
const size_t packet_size = OS_MBUF_PKTLEN(buffer);
|
||||
if (packet_size == 0 || packet_size > capacity) {
|
||||
return false;
|
||||
}
|
||||
uint16_t copied = 0;
|
||||
if (ble_hs_mbuf_to_flat(
|
||||
buffer,
|
||||
output,
|
||||
static_cast<uint16_t>(capacity),
|
||||
&copied) != 0 ||
|
||||
copied != packet_size) {
|
||||
return false;
|
||||
}
|
||||
*size = packet_size;
|
||||
return true;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
bool BleProvisioningGattServer::Start(
|
||||
const DeviceIdentity& identity,
|
||||
IBleProvisioningGattObserver& observer)
|
||||
{
|
||||
if (running_.load()) {
|
||||
return true;
|
||||
}
|
||||
if (g_server != nullptr && g_server != this) {
|
||||
ESP_LOGE(kTag, "only one BLE provisioning server is supported");
|
||||
return false;
|
||||
}
|
||||
|
||||
identity_ = identity;
|
||||
observer_ = &observer;
|
||||
if (!BuildProvisioningDeviceInfoJson(
|
||||
identity_,
|
||||
device_info_json_.data(),
|
||||
device_info_json_.size(),
|
||||
&device_info_size_)) {
|
||||
ESP_LOGE(kTag, "device info JSON creation failed");
|
||||
return false;
|
||||
}
|
||||
|
||||
char name[16] = "Borla-0000";
|
||||
size_t suffix_index = 6;
|
||||
for (size_t index = 0;
|
||||
identity_.mac[index] != '\0';
|
||||
++index) {
|
||||
const char value = identity_.mac[index];
|
||||
if (value == ':') {
|
||||
continue;
|
||||
}
|
||||
if (suffix_index == 10) {
|
||||
std::memmove(name + 6, name + 7, 3);
|
||||
suffix_index = 9;
|
||||
}
|
||||
name[suffix_index++] = value;
|
||||
}
|
||||
name[10] = '\0';
|
||||
|
||||
g_server = this;
|
||||
host_started_.store(false);
|
||||
host_synced_.store(false);
|
||||
ClearConnection();
|
||||
|
||||
const esp_err_t init_result = nimble_port_init();
|
||||
if (init_result != ESP_OK) {
|
||||
ESP_LOGE(kTag, "nimble_port_init failed: %s",
|
||||
esp_err_to_name(init_result));
|
||||
g_server = nullptr;
|
||||
return false;
|
||||
}
|
||||
|
||||
ble_hs_cfg.reset_cb = &BleProvisioningGattServer::OnHostReset;
|
||||
ble_hs_cfg.sync_cb = &BleProvisioningGattServer::OnHostSync;
|
||||
ble_hs_cfg.store_status_cb = ble_store_util_status_rr;
|
||||
ble_store_config_init();
|
||||
ble_att_set_preferred_mtu(kPreferredMtu);
|
||||
ble_svc_gap_init();
|
||||
ble_svc_gatt_init();
|
||||
|
||||
int result = ble_gatts_count_cfg(g_services);
|
||||
if (result == 0) {
|
||||
result = ble_gatts_add_svcs(g_services);
|
||||
}
|
||||
if (result == 0) {
|
||||
result = ble_svc_gap_device_name_set(name);
|
||||
}
|
||||
if (result != 0) {
|
||||
ESP_LOGE(kTag, "GATT service setup failed rc=%d", result);
|
||||
nimble_port_deinit();
|
||||
g_server = nullptr;
|
||||
return false;
|
||||
}
|
||||
|
||||
running_.store(true);
|
||||
host_task_ = xTaskCreateStaticPinnedToCore(
|
||||
&BleProvisioningGattServer::HostTask,
|
||||
"nimble_host2",
|
||||
host_task_stack_.size(),
|
||||
this,
|
||||
configMAX_PRIORITIES - 4,
|
||||
host_task_stack_.data(),
|
||||
&host_task_control_,
|
||||
CONFIG_BT_NIMBLE_PINNED_TO_CORE);
|
||||
if (host_task_ == nullptr) {
|
||||
ESP_LOGE(kTag, "static NimBLE host task creation failed");
|
||||
running_.store(false);
|
||||
nimble_port_deinit();
|
||||
g_server = nullptr;
|
||||
return false;
|
||||
}
|
||||
const TickType_t delay = pdMS_TO_TICKS(50);
|
||||
const uint32_t attempts =
|
||||
std::max<uint32_t>(1, kHostSyncTimeoutMs / 50);
|
||||
for (uint32_t attempt = 0;
|
||||
attempt < attempts && !host_synced_.load();
|
||||
++attempt) {
|
||||
vTaskDelay(delay);
|
||||
}
|
||||
if (!host_started_.load() || !host_synced_.load()) {
|
||||
ESP_LOGE(
|
||||
kTag,
|
||||
"NimBLE host unavailable started=%d synced=%d "
|
||||
"internal_free=%u largest=%u",
|
||||
host_started_.load() ? 1 : 0,
|
||||
host_synced_.load() ? 1 : 0,
|
||||
static_cast<unsigned>(
|
||||
heap_caps_get_free_size(MALLOC_CAP_INTERNAL)),
|
||||
static_cast<unsigned>(
|
||||
heap_caps_get_largest_free_block(MALLOC_CAP_INTERNAL)));
|
||||
Stop();
|
||||
return false;
|
||||
}
|
||||
|
||||
ESP_LOGI(kTag, "BLE provisioning ready name=%s mtu=%u",
|
||||
name, static_cast<unsigned>(kPreferredMtu));
|
||||
return true;
|
||||
}
|
||||
|
||||
void BleProvisioningGattServer::Stop()
|
||||
{
|
||||
if (!running_.exchange(false)) {
|
||||
return;
|
||||
}
|
||||
ble_gap_adv_stop();
|
||||
if (connected_.load()) {
|
||||
uint16_t connection = kInvalidConnectionHandle;
|
||||
portENTER_CRITICAL(&connection_lock_);
|
||||
connection = connection_handle_;
|
||||
portEXIT_CRITICAL(&connection_lock_);
|
||||
if (connection != kInvalidConnectionHandle) {
|
||||
ble_gap_terminate(
|
||||
connection, BLE_ERR_REM_USER_CONN_TERM);
|
||||
}
|
||||
}
|
||||
if (nimble_port_stop() == 0) {
|
||||
nimble_port_deinit();
|
||||
}
|
||||
ClearConnection();
|
||||
observer_ = nullptr;
|
||||
g_server = nullptr;
|
||||
ESP_LOGI(kTag, "BLE provisioning stopped");
|
||||
}
|
||||
|
||||
bool BleProvisioningGattServer::NotifyScanResults(
|
||||
const WifiNetwork* networks,
|
||||
size_t count)
|
||||
{
|
||||
notification_json_.fill('\0');
|
||||
size_t size = 0;
|
||||
return BuildProvisioningScanJson(
|
||||
networks,
|
||||
count,
|
||||
notification_json_.data(),
|
||||
notification_json_.size(),
|
||||
&size) &&
|
||||
NotifyChunked(
|
||||
g_scan_value_handle,
|
||||
notification_json_.data(),
|
||||
size);
|
||||
}
|
||||
|
||||
bool BleProvisioningGattServer::NotifyWifiResult(
|
||||
bool success,
|
||||
const char* error)
|
||||
{
|
||||
std::array<char, 128> json{};
|
||||
size_t size = 0;
|
||||
return BuildProvisioningResultJson(
|
||||
success, error, json.data(), json.size(), &size) &&
|
||||
NotifySingle(g_result_value_handle, json.data(), size);
|
||||
}
|
||||
|
||||
bool BleProvisioningGattServer::NotifySavedWifi(
|
||||
const WifiCredential* credentials,
|
||||
size_t count)
|
||||
{
|
||||
notification_json_.fill('\0');
|
||||
size_t size = 0;
|
||||
return BuildProvisioningSavedWifiJson(
|
||||
credentials,
|
||||
count,
|
||||
notification_json_.data(),
|
||||
notification_json_.size(),
|
||||
&size) &&
|
||||
NotifyChunked(
|
||||
g_saved_wifi_value_handle,
|
||||
notification_json_.data(),
|
||||
size);
|
||||
}
|
||||
|
||||
bool BleProvisioningGattServer::NotifySavedWifiResult(
|
||||
bool success,
|
||||
const char* error)
|
||||
{
|
||||
std::array<char, 128> json{};
|
||||
size_t size = 0;
|
||||
return BuildProvisioningResultJson(
|
||||
success, error, json.data(), json.size(), &size) &&
|
||||
NotifyChunked(
|
||||
g_saved_wifi_value_handle, json.data(), size);
|
||||
}
|
||||
|
||||
void BleProvisioningGattServer::HostTask(void* context)
|
||||
{
|
||||
auto* server =
|
||||
static_cast<BleProvisioningGattServer*>(context);
|
||||
server->host_started_.store(true);
|
||||
ESP_LOGI(kTag, "NimBLE host task started");
|
||||
nimble_port_run();
|
||||
server->host_task_ = nullptr;
|
||||
vTaskDelete(nullptr);
|
||||
}
|
||||
|
||||
void BleProvisioningGattServer::OnHostSync()
|
||||
{
|
||||
if (g_server == nullptr) {
|
||||
return;
|
||||
}
|
||||
int result = ble_hs_util_ensure_addr(0);
|
||||
if (result == 0) {
|
||||
result = ble_hs_id_infer_auto(
|
||||
0, &g_server->own_address_type_);
|
||||
}
|
||||
if (result != 0) {
|
||||
ESP_LOGE(kTag, "BLE address setup failed rc=%d", result);
|
||||
return;
|
||||
}
|
||||
g_server->host_synced_.store(true);
|
||||
g_server->StartAdvertising();
|
||||
}
|
||||
|
||||
void BleProvisioningGattServer::OnHostReset(int reason)
|
||||
{
|
||||
ESP_LOGW(kTag, "NimBLE host reset reason=%d", reason);
|
||||
}
|
||||
|
||||
bool BleProvisioningGattServer::StartAdvertising()
|
||||
{
|
||||
if (!running_.load()) {
|
||||
return false;
|
||||
}
|
||||
ble_hs_adv_fields fields{};
|
||||
fields.flags =
|
||||
BLE_HS_ADV_F_DISC_GEN | BLE_HS_ADV_F_BREDR_UNSUP;
|
||||
ble_uuid16_t service = BLE_UUID16_INIT(0xff01);
|
||||
fields.uuids16 = &service;
|
||||
fields.num_uuids16 = 1;
|
||||
fields.uuids16_is_complete = 1;
|
||||
const char* name = ble_svc_gap_device_name();
|
||||
fields.name =
|
||||
reinterpret_cast<uint8_t*>(const_cast<char*>(name));
|
||||
fields.name_len =
|
||||
static_cast<uint8_t>(std::strlen(name));
|
||||
fields.name_is_complete = 1;
|
||||
int result = ble_gap_adv_set_fields(&fields);
|
||||
if (result != 0) {
|
||||
ESP_LOGE(kTag, "advertising data setup failed rc=%d", result);
|
||||
return false;
|
||||
}
|
||||
|
||||
ble_gap_adv_params parameters{};
|
||||
parameters.conn_mode = BLE_GAP_CONN_MODE_UND;
|
||||
parameters.disc_mode = BLE_GAP_DISC_MODE_GEN;
|
||||
result = ble_gap_adv_start(
|
||||
own_address_type_,
|
||||
nullptr,
|
||||
BLE_HS_FOREVER,
|
||||
¶meters,
|
||||
BorlaBleGapEvent,
|
||||
this);
|
||||
if (result != 0) {
|
||||
ESP_LOGE(kTag, "advertising start failed rc=%d", result);
|
||||
return false;
|
||||
}
|
||||
ESP_LOGI(kTag, "BLE provisioning advertising");
|
||||
return true;
|
||||
}
|
||||
|
||||
int BleProvisioningGattServer::HandleGattAccess(
|
||||
ble_gatt_access_ctxt* context)
|
||||
{
|
||||
if (context == nullptr || context->chr == nullptr) {
|
||||
return BLE_ATT_ERR_UNLIKELY;
|
||||
}
|
||||
const ble_uuid_t* uuid = context->chr->uuid;
|
||||
if (ble_uuid_cmp(uuid, &kDeviceInfoUuid.u) == 0) {
|
||||
return HandleDeviceInfoRead(context);
|
||||
}
|
||||
if (ble_uuid_cmp(uuid, &kWifiScanUuid.u) == 0) {
|
||||
return HandleScanWrite(context);
|
||||
}
|
||||
if (ble_uuid_cmp(uuid, &kWifiConfigUuid.u) == 0) {
|
||||
return HandleCredentialWrite(context);
|
||||
}
|
||||
if (ble_uuid_cmp(uuid, &kCommandUuid.u) == 0) {
|
||||
return HandleCommandWrite(context);
|
||||
}
|
||||
if (ble_uuid_cmp(uuid, &kSavedWifiUuid.u) == 0) {
|
||||
return HandleSavedWifiWrite(context);
|
||||
}
|
||||
if (ble_uuid_cmp(uuid, &kWifiResultUuid.u) == 0) {
|
||||
return 0;
|
||||
}
|
||||
return BLE_ATT_ERR_UNLIKELY;
|
||||
}
|
||||
|
||||
int BleProvisioningGattServer::HandleDeviceInfoRead(
|
||||
ble_gatt_access_ctxt* context)
|
||||
{
|
||||
return os_mbuf_append(
|
||||
context->om,
|
||||
device_info_json_.data(),
|
||||
device_info_size_) == 0
|
||||
? 0
|
||||
: BLE_ATT_ERR_INSUFFICIENT_RES;
|
||||
}
|
||||
|
||||
int BleProvisioningGattServer::HandleScanWrite(
|
||||
ble_gatt_access_ctxt* context)
|
||||
{
|
||||
std::array<uint8_t, 4> packet{};
|
||||
size_t size = 0;
|
||||
if (!ReadMbuf(
|
||||
context->om, packet.data(), packet.size(), &size) ||
|
||||
size != 1 || packet[0] != 0x01) {
|
||||
return BLE_ATT_ERR_VALUE_NOT_ALLOWED;
|
||||
}
|
||||
if (observer_ != nullptr) {
|
||||
observer_->OnBleWifiScanRequested();
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
int BleProvisioningGattServer::HandleCredentialWrite(
|
||||
ble_gatt_access_ctxt* context)
|
||||
{
|
||||
std::array<uint8_t, kPreferredMtu> packet{};
|
||||
size_t size = 0;
|
||||
if (!ReadMbuf(
|
||||
context->om, packet.data(), packet.size(), &size)) {
|
||||
credential_assembler_.Reset();
|
||||
return BLE_ATT_ERR_INVALID_ATTR_VALUE_LEN;
|
||||
}
|
||||
const BleChunkAssemblyResult result =
|
||||
credential_assembler_.Push(packet.data(), size);
|
||||
if (result == BleChunkAssemblyResult::kInvalid) {
|
||||
return BLE_ATT_ERR_VALUE_NOT_ALLOWED;
|
||||
}
|
||||
if (result == BleChunkAssemblyResult::kComplete) {
|
||||
WifiCredential credential;
|
||||
if (!ParseProvisioningCredential(
|
||||
credential_assembler_.data(),
|
||||
credential_assembler_.size(),
|
||||
&credential)) {
|
||||
credential_assembler_.Reset();
|
||||
NotifyWifiResult(false, "unknown");
|
||||
return 0;
|
||||
}
|
||||
credential_assembler_.Reset();
|
||||
if (observer_ != nullptr) {
|
||||
observer_->OnBleWifiCredential(credential);
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
int BleProvisioningGattServer::HandleCommandWrite(
|
||||
ble_gatt_access_ctxt* context)
|
||||
{
|
||||
std::array<uint8_t, 4> packet{};
|
||||
size_t size = 0;
|
||||
if (!ReadMbuf(
|
||||
context->om, packet.data(), packet.size(), &size) ||
|
||||
size != 1 || packet[0] != 0x01) {
|
||||
return BLE_ATT_ERR_VALUE_NOT_ALLOWED;
|
||||
}
|
||||
if (observer_ != nullptr) {
|
||||
observer_->OnBleRebootRequested();
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
int BleProvisioningGattServer::HandleSavedWifiWrite(
|
||||
ble_gatt_access_ctxt* context)
|
||||
{
|
||||
std::array<uint8_t, 4> packet{};
|
||||
size_t size = 0;
|
||||
if (!ReadMbuf(
|
||||
context->om, packet.data(), packet.size(), &size)) {
|
||||
return BLE_ATT_ERR_INVALID_ATTR_VALUE_LEN;
|
||||
}
|
||||
if (size == 1 && packet[0] == 0x01) {
|
||||
if (observer_ != nullptr) {
|
||||
observer_->OnBleSavedWifiListRequested();
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
if (size == 2 && packet[0] == 0x02) {
|
||||
if (observer_ != nullptr) {
|
||||
observer_->OnBleSavedWifiDeleteRequested(packet[1]);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
return BLE_ATT_ERR_VALUE_NOT_ALLOWED;
|
||||
}
|
||||
|
||||
bool BleProvisioningGattServer::NotifyChunked(
|
||||
uint16_t value_handle,
|
||||
const char* json,
|
||||
size_t size)
|
||||
{
|
||||
if (!connected_.load() || value_handle == 0) {
|
||||
return false;
|
||||
}
|
||||
uint16_t mtu = 23;
|
||||
portENTER_CRITICAL(&connection_lock_);
|
||||
active_notification_handle_ = value_handle;
|
||||
mtu = negotiated_mtu_;
|
||||
portEXIT_CRITICAL(&connection_lock_);
|
||||
const bool result =
|
||||
VisitBleNotificationChunks(json, size, mtu, *this);
|
||||
portENTER_CRITICAL(&connection_lock_);
|
||||
active_notification_handle_ = 0;
|
||||
portEXIT_CRITICAL(&connection_lock_);
|
||||
return result;
|
||||
}
|
||||
|
||||
bool BleProvisioningGattServer::NotifySingle(
|
||||
uint16_t value_handle,
|
||||
const char* json,
|
||||
size_t size)
|
||||
{
|
||||
if (!connected_.load() || value_handle == 0 ||
|
||||
json == nullptr || size == 0) {
|
||||
return false;
|
||||
}
|
||||
uint16_t connection = kInvalidConnectionHandle;
|
||||
portENTER_CRITICAL(&connection_lock_);
|
||||
connection = connection_handle_;
|
||||
portEXIT_CRITICAL(&connection_lock_);
|
||||
os_mbuf* buffer = ble_hs_mbuf_from_flat(json, size);
|
||||
return buffer != nullptr &&
|
||||
ble_gatts_notify_custom(
|
||||
connection, value_handle, buffer) == 0;
|
||||
}
|
||||
|
||||
bool BleProvisioningGattServer::OnBleChunk(
|
||||
const uint8_t* data,
|
||||
size_t size)
|
||||
{
|
||||
uint16_t connection = kInvalidConnectionHandle;
|
||||
uint16_t value_handle = 0;
|
||||
portENTER_CRITICAL(&connection_lock_);
|
||||
connection = connection_handle_;
|
||||
value_handle = active_notification_handle_;
|
||||
portEXIT_CRITICAL(&connection_lock_);
|
||||
if (!connected_.load() ||
|
||||
connection == kInvalidConnectionHandle ||
|
||||
value_handle == 0) {
|
||||
return false;
|
||||
}
|
||||
os_mbuf* buffer = ble_hs_mbuf_from_flat(data, size);
|
||||
if (buffer == nullptr ||
|
||||
ble_gatts_notify_custom(
|
||||
connection, value_handle, buffer) != 0) {
|
||||
return false;
|
||||
}
|
||||
vTaskDelay(pdMS_TO_TICKS(60));
|
||||
return true;
|
||||
}
|
||||
|
||||
void BleProvisioningGattServer::ClearConnection()
|
||||
{
|
||||
portENTER_CRITICAL(&connection_lock_);
|
||||
connection_handle_ = kInvalidConnectionHandle;
|
||||
negotiated_mtu_ = 23;
|
||||
active_notification_handle_ = 0;
|
||||
portEXIT_CRITICAL(&connection_lock_);
|
||||
connected_.store(false);
|
||||
credential_assembler_.Reset();
|
||||
}
|
||||
|
||||
int BorlaBleGapEvent(
|
||||
ble_gap_event* event,
|
||||
void* context)
|
||||
{
|
||||
auto* server =
|
||||
static_cast<BleProvisioningGattServer*>(context);
|
||||
if (server == nullptr || event == nullptr) {
|
||||
return 0;
|
||||
}
|
||||
switch (event->type) {
|
||||
case BLE_GAP_EVENT_CONNECT:
|
||||
if (event->connect.status == 0) {
|
||||
portENTER_CRITICAL(&server->connection_lock_);
|
||||
server->connection_handle_ =
|
||||
event->connect.conn_handle;
|
||||
server->negotiated_mtu_ =
|
||||
ble_att_mtu(event->connect.conn_handle);
|
||||
portEXIT_CRITICAL(&server->connection_lock_);
|
||||
server->connected_.store(true);
|
||||
ESP_LOGI(kTag, "BLE client connected handle=%u mtu=%u",
|
||||
static_cast<unsigned>(
|
||||
event->connect.conn_handle),
|
||||
static_cast<unsigned>(
|
||||
server->negotiated_mtu_));
|
||||
} else {
|
||||
ESP_LOGW(kTag, "BLE connection failed status=%d",
|
||||
event->connect.status);
|
||||
server->StartAdvertising();
|
||||
}
|
||||
break;
|
||||
case BLE_GAP_EVENT_DISCONNECT:
|
||||
ESP_LOGI(kTag, "BLE client disconnected reason=%d",
|
||||
event->disconnect.reason);
|
||||
server->ClearConnection();
|
||||
server->StartAdvertising();
|
||||
break;
|
||||
case BLE_GAP_EVENT_MTU:
|
||||
portENTER_CRITICAL(&server->connection_lock_);
|
||||
server->negotiated_mtu_ =
|
||||
std::min<uint16_t>(
|
||||
event->mtu.value, kPreferredMtu);
|
||||
portEXIT_CRITICAL(&server->connection_lock_);
|
||||
ESP_LOGI(kTag, "BLE MTU=%u",
|
||||
static_cast<unsigned>(event->mtu.value));
|
||||
break;
|
||||
case BLE_GAP_EVENT_ADV_COMPLETE:
|
||||
if (!server->connected_.load()) {
|
||||
server->StartAdvertising();
|
||||
}
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
int BorlaBleGattAccess(
|
||||
uint16_t,
|
||||
uint16_t,
|
||||
ble_gatt_access_ctxt* context,
|
||||
void*)
|
||||
{
|
||||
return g_server == nullptr
|
||||
? BLE_ATT_ERR_UNLIKELY
|
||||
: g_server->HandleGattAccess(context);
|
||||
}
|
||||
|
||||
} // namespace borla
|
||||
112
main/platform/borla_s3/ble_provisioning_gatt.h
Normal file
112
main/platform/borla_s3/ble_provisioning_gatt.h
Normal file
@@ -0,0 +1,112 @@
|
||||
#pragma once
|
||||
|
||||
#include "connectivity/wifi_types.h"
|
||||
#include "ports/device_platform.h"
|
||||
#include "provisioning/ble_provisioning_codec.h"
|
||||
|
||||
#include <array>
|
||||
#include <atomic>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
|
||||
#include <freertos/FreeRTOS.h>
|
||||
#include <freertos/portmacro.h>
|
||||
#include <freertos/task.h>
|
||||
|
||||
struct ble_gap_event;
|
||||
struct ble_gatt_access_ctxt;
|
||||
|
||||
namespace borla {
|
||||
|
||||
class IBleProvisioningGattObserver {
|
||||
public:
|
||||
virtual ~IBleProvisioningGattObserver() = default;
|
||||
virtual void OnBleWifiScanRequested() = 0;
|
||||
virtual void OnBleWifiCredential(
|
||||
const WifiCredential& credential) = 0;
|
||||
virtual void OnBleSavedWifiListRequested() = 0;
|
||||
virtual void OnBleSavedWifiDeleteRequested(uint8_t index) = 0;
|
||||
virtual void OnBleRebootRequested() = 0;
|
||||
};
|
||||
|
||||
class BleProvisioningGattServer final : private IBleChunkVisitor {
|
||||
public:
|
||||
bool Start(
|
||||
const DeviceIdentity& identity,
|
||||
IBleProvisioningGattObserver& observer);
|
||||
void Stop();
|
||||
|
||||
bool NotifyScanResults(
|
||||
const WifiNetwork* networks,
|
||||
size_t count);
|
||||
bool NotifyWifiResult(bool success, const char* error);
|
||||
bool NotifySavedWifi(
|
||||
const WifiCredential* credentials,
|
||||
size_t count);
|
||||
bool NotifySavedWifiResult(bool success, const char* error);
|
||||
|
||||
bool running() const { return running_.load(); }
|
||||
bool connected() const { return connected_.load(); }
|
||||
|
||||
private:
|
||||
friend int BorlaBleGapEvent(
|
||||
struct ble_gap_event* event,
|
||||
void* context);
|
||||
friend int BorlaBleGattAccess(
|
||||
uint16_t connection_handle,
|
||||
uint16_t attribute_handle,
|
||||
struct ble_gatt_access_ctxt* context,
|
||||
void* argument);
|
||||
|
||||
static void HostTask(void* context);
|
||||
static void OnHostSync();
|
||||
static void OnHostReset(int reason);
|
||||
|
||||
bool StartAdvertising();
|
||||
int HandleGattAccess(struct ble_gatt_access_ctxt* context);
|
||||
int HandleDeviceInfoRead(struct ble_gatt_access_ctxt* context);
|
||||
int HandleScanWrite(struct ble_gatt_access_ctxt* context);
|
||||
int HandleCredentialWrite(struct ble_gatt_access_ctxt* context);
|
||||
int HandleCommandWrite(struct ble_gatt_access_ctxt* context);
|
||||
int HandleSavedWifiWrite(struct ble_gatt_access_ctxt* context);
|
||||
bool NotifyChunked(uint16_t value_handle, const char* json, size_t size);
|
||||
bool NotifySingle(uint16_t value_handle, const char* json, size_t size);
|
||||
bool OnBleChunk(const uint8_t* data, size_t size) override;
|
||||
void ClearConnection();
|
||||
|
||||
IBleProvisioningGattObserver* observer_ = nullptr;
|
||||
DeviceIdentity identity_{};
|
||||
std::array<char, 160> device_info_json_{};
|
||||
size_t device_info_size_ = 0;
|
||||
std::array<char, kBleProvisioningJsonCapacity>
|
||||
notification_json_{};
|
||||
BleChunkAssembler credential_assembler_;
|
||||
|
||||
mutable portMUX_TYPE connection_lock_ =
|
||||
portMUX_INITIALIZER_UNLOCKED;
|
||||
uint16_t connection_handle_ = 0;
|
||||
uint16_t negotiated_mtu_ = 23;
|
||||
uint16_t active_notification_handle_ = 0;
|
||||
uint8_t own_address_type_ = 0;
|
||||
|
||||
std::atomic<bool> running_{false};
|
||||
std::atomic<bool> connected_{false};
|
||||
std::atomic<bool> host_started_{false};
|
||||
std::atomic<bool> host_synced_{false};
|
||||
static constexpr uint32_t kHostTaskStackDepth = 4096;
|
||||
TaskHandle_t host_task_ = nullptr;
|
||||
StaticTask_t host_task_control_{};
|
||||
std::array<StackType_t, kHostTaskStackDepth>
|
||||
host_task_stack_{};
|
||||
};
|
||||
|
||||
int BorlaBleGapEvent(
|
||||
struct ble_gap_event* event,
|
||||
void* context);
|
||||
int BorlaBleGattAccess(
|
||||
uint16_t connection_handle,
|
||||
uint16_t attribute_handle,
|
||||
struct ble_gatt_access_ctxt* context,
|
||||
void* argument);
|
||||
|
||||
} // namespace borla
|
||||
235
main/platform/borla_s3/bmi270_sensor.cc
Normal file
235
main/platform/borla_s3/bmi270_sensor.cc
Normal file
@@ -0,0 +1,235 @@
|
||||
#include "platform/borla_s3/bmi270_sensor.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
|
||||
#include <esp_err.h>
|
||||
#include <esp_log.h>
|
||||
#include <freertos/FreeRTOS.h>
|
||||
#include <freertos/task.h>
|
||||
|
||||
extern "C" {
|
||||
extern const uint8_t bmi270_context_config_file[];
|
||||
extern const int bmi270_context_config_file_size;
|
||||
}
|
||||
|
||||
namespace borla {
|
||||
namespace {
|
||||
|
||||
constexpr const char* kTag = "Bmi270Sensor2";
|
||||
constexpr uint8_t kDeviceAddress = 0x68;
|
||||
constexpr uint8_t kChipIdRegister = 0x00;
|
||||
constexpr uint8_t kExpectedChipId = 0x24;
|
||||
constexpr uint8_t kInternalStatusRegister = 0x21;
|
||||
constexpr uint8_t kAccelDataRegister = 0x0C;
|
||||
constexpr uint8_t kAccelConfigRegister = 0x40;
|
||||
constexpr uint8_t kAccelRangeRegister = 0x41;
|
||||
constexpr uint8_t kGyroConfigRegister = 0x42;
|
||||
constexpr uint8_t kGyroRangeRegister = 0x43;
|
||||
constexpr uint8_t kInitControlRegister = 0x59;
|
||||
constexpr uint8_t kInitAddressLowRegister = 0x5B;
|
||||
constexpr uint8_t kInitAddressHighRegister = 0x5C;
|
||||
constexpr uint8_t kInitDataRegister = 0x5E;
|
||||
constexpr uint8_t kPowerConfigRegister = 0x7C;
|
||||
constexpr uint8_t kPowerControlRegister = 0x7D;
|
||||
constexpr uint8_t kCommandRegister = 0x7E;
|
||||
constexpr uint8_t kSoftResetCommand = 0xB6;
|
||||
constexpr size_t kConfigurationChunkBytes = 32;
|
||||
constexpr float kAccelScale = 16.0F / 32768.0F;
|
||||
constexpr float kGyroScale = 2000.0F / 32768.0F;
|
||||
|
||||
int16_t ReadLe16(const uint8_t* data)
|
||||
{
|
||||
return static_cast<int16_t>(
|
||||
static_cast<uint16_t>(data[0]) |
|
||||
static_cast<uint16_t>(data[1]) << 8);
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
Bmi270Sensor::~Bmi270Sensor()
|
||||
{
|
||||
if (device_ != nullptr) {
|
||||
i2c_master_bus_rm_device(device_);
|
||||
}
|
||||
}
|
||||
|
||||
bool Bmi270Sensor::Initialize()
|
||||
{
|
||||
if (device_ != nullptr) {
|
||||
return true;
|
||||
}
|
||||
if (!bus_.Initialize()) {
|
||||
return false;
|
||||
}
|
||||
const i2c_device_config_t config = {
|
||||
.dev_addr_length = I2C_ADDR_BIT_LEN_7,
|
||||
.device_address = kDeviceAddress,
|
||||
.scl_speed_hz = 400000,
|
||||
.scl_wait_us = 0,
|
||||
.flags = {
|
||||
.disable_ack_check = false,
|
||||
},
|
||||
};
|
||||
esp_err_t result =
|
||||
i2c_master_bus_add_device(bus_.Handle(), &config, &device_);
|
||||
if (result != ESP_OK) {
|
||||
ESP_LOGW(kTag, "device not available: %s",
|
||||
esp_err_to_name(result));
|
||||
device_ = nullptr;
|
||||
return false;
|
||||
}
|
||||
|
||||
uint8_t chip_id = 0;
|
||||
if (!ReadData(kChipIdRegister, &chip_id, 1) ||
|
||||
chip_id != kExpectedChipId) {
|
||||
ESP_LOGW(kTag, "chip id mismatch got=0x%02x expected=0x%02x",
|
||||
chip_id, kExpectedChipId);
|
||||
i2c_master_bus_rm_device(device_);
|
||||
device_ = nullptr;
|
||||
return false;
|
||||
}
|
||||
if (!WriteRegister(kCommandRegister, kSoftResetCommand)) {
|
||||
i2c_master_bus_rm_device(device_);
|
||||
device_ = nullptr;
|
||||
return false;
|
||||
}
|
||||
vTaskDelay(pdMS_TO_TICKS(3));
|
||||
if (!UploadConfiguration()) {
|
||||
i2c_master_bus_rm_device(device_);
|
||||
device_ = nullptr;
|
||||
return false;
|
||||
}
|
||||
|
||||
// 50 Hz normal-performance sampling, ±16 g, ±2000 dps.
|
||||
const bool configured =
|
||||
WriteRegister(kAccelConfigRegister, 0xA7) &&
|
||||
WriteRegister(kAccelRangeRegister, 0x03) &&
|
||||
WriteRegister(kGyroConfigRegister, 0xA7) &&
|
||||
WriteRegister(kGyroRangeRegister, 0x00) &&
|
||||
WriteRegister(kPowerControlRegister, 0x06) &&
|
||||
WriteRegister(kPowerConfigRegister, 0x02);
|
||||
if (!configured) {
|
||||
ESP_LOGE(kTag, "runtime configuration failed");
|
||||
i2c_master_bus_rm_device(device_);
|
||||
device_ = nullptr;
|
||||
return false;
|
||||
}
|
||||
vTaskDelay(pdMS_TO_TICKS(5));
|
||||
ESP_LOGI(kTag, "initialized at 50Hz, accel=16g gyro=2000dps");
|
||||
return true;
|
||||
}
|
||||
|
||||
bool Bmi270Sensor::Read(ImuSample* sample)
|
||||
{
|
||||
if (device_ == nullptr || sample == nullptr) {
|
||||
return false;
|
||||
}
|
||||
std::array<uint8_t, 12> data{};
|
||||
if (!ReadData(kAccelDataRegister, data.data(), data.size())) {
|
||||
read_failure_count_++;
|
||||
if (read_failure_count_ == 1 ||
|
||||
read_failure_count_ % 50 == 0) {
|
||||
ESP_LOGW(kTag, "read failures=%lu",
|
||||
static_cast<unsigned long>(read_failure_count_));
|
||||
}
|
||||
return false;
|
||||
}
|
||||
read_failure_count_ = 0;
|
||||
sample->ax = ReadLe16(&data[0]) * kAccelScale;
|
||||
sample->ay = -ReadLe16(&data[2]) * kAccelScale;
|
||||
sample->az = -ReadLe16(&data[4]) * kAccelScale;
|
||||
sample->gx = ReadLe16(&data[6]) * kGyroScale;
|
||||
sample->gy = -ReadLe16(&data[8]) * kGyroScale;
|
||||
sample->gz = -ReadLe16(&data[10]) * kGyroScale;
|
||||
return true;
|
||||
}
|
||||
|
||||
bool Bmi270Sensor::WriteRegister(uint8_t address, uint8_t value)
|
||||
{
|
||||
return WriteData(address, &value, 1);
|
||||
}
|
||||
|
||||
bool Bmi270Sensor::WriteData(
|
||||
uint8_t address,
|
||||
const uint8_t* data,
|
||||
size_t size)
|
||||
{
|
||||
if (device_ == nullptr || data == nullptr || size > 64) {
|
||||
return false;
|
||||
}
|
||||
std::array<uint8_t, 65> message{};
|
||||
message[0] = address;
|
||||
std::copy_n(data, size, message.begin() + 1);
|
||||
const esp_err_t result = i2c_master_transmit(
|
||||
device_, message.data(), size + 1, 1000);
|
||||
if (result != ESP_OK) {
|
||||
ESP_LOGE(kTag, "write reg=0x%02x failed: %s",
|
||||
address, esp_err_to_name(result));
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool Bmi270Sensor::ReadData(
|
||||
uint8_t address,
|
||||
uint8_t* data,
|
||||
size_t size)
|
||||
{
|
||||
if (device_ == nullptr || data == nullptr || size == 0) {
|
||||
return false;
|
||||
}
|
||||
const esp_err_t result = i2c_master_transmit_receive(
|
||||
device_, &address, 1, data, size, 1000);
|
||||
return result == ESP_OK;
|
||||
}
|
||||
|
||||
bool Bmi270Sensor::UploadConfiguration()
|
||||
{
|
||||
if (bmi270_context_config_file_size <= 0 ||
|
||||
!WriteRegister(kPowerConfigRegister, 0x00)) {
|
||||
return false;
|
||||
}
|
||||
vTaskDelay(pdMS_TO_TICKS(10));
|
||||
if (!WriteRegister(kInitControlRegister, 0x00)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const size_t total =
|
||||
static_cast<size_t>(bmi270_context_config_file_size);
|
||||
for (size_t offset = 0; offset < total;
|
||||
offset += kConfigurationChunkBytes) {
|
||||
const uint16_t word_address =
|
||||
static_cast<uint16_t>(offset / 2);
|
||||
const size_t chunk = std::min(
|
||||
kConfigurationChunkBytes, total - offset);
|
||||
if (!WriteRegister(
|
||||
kInitAddressLowRegister,
|
||||
static_cast<uint8_t>(word_address & 0x0F)) ||
|
||||
!WriteRegister(
|
||||
kInitAddressHighRegister,
|
||||
static_cast<uint8_t>(word_address >> 4)) ||
|
||||
!WriteData(
|
||||
kInitDataRegister,
|
||||
bmi270_context_config_file + offset,
|
||||
chunk)) {
|
||||
ESP_LOGE(kTag, "configuration upload failed at %u/%u",
|
||||
static_cast<unsigned int>(offset),
|
||||
static_cast<unsigned int>(total));
|
||||
return false;
|
||||
}
|
||||
}
|
||||
if (!WriteRegister(kInitControlRegister, 0x01)) {
|
||||
return false;
|
||||
}
|
||||
vTaskDelay(pdMS_TO_TICKS(20));
|
||||
uint8_t status = 0;
|
||||
if (!ReadData(kInternalStatusRegister, &status, 1) ||
|
||||
(status & 0x0F) != 0x01) {
|
||||
ESP_LOGE(kTag, "configuration rejected status=0x%02x", status);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
} // namespace borla
|
||||
35
main/platform/borla_s3/bmi270_sensor.h
Normal file
35
main/platform/borla_s3/bmi270_sensor.h
Normal file
@@ -0,0 +1,35 @@
|
||||
#pragma once
|
||||
|
||||
#include "platform/borla_s3/i2c_bus.h"
|
||||
#include "sensor/sensor_types.h"
|
||||
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
|
||||
#include <driver/i2c_master.h>
|
||||
|
||||
namespace borla {
|
||||
|
||||
class Bmi270Sensor final {
|
||||
public:
|
||||
explicit Bmi270Sensor(BorlaS3I2cBus& bus) : bus_(bus) {}
|
||||
~Bmi270Sensor();
|
||||
|
||||
bool Initialize();
|
||||
bool Read(ImuSample* sample);
|
||||
|
||||
private:
|
||||
bool WriteRegister(uint8_t address, uint8_t value);
|
||||
bool WriteData(
|
||||
uint8_t address,
|
||||
const uint8_t* data,
|
||||
size_t size);
|
||||
bool ReadData(uint8_t address, uint8_t* data, size_t size);
|
||||
bool UploadConfiguration();
|
||||
|
||||
BorlaS3I2cBus& bus_;
|
||||
i2c_master_dev_handle_t device_ = nullptr;
|
||||
uint32_t read_failure_count_ = 0;
|
||||
};
|
||||
|
||||
} // namespace borla
|
||||
90
main/platform/borla_s3/board_config.h
Normal file
90
main/platform/borla_s3/board_config.h
Normal file
@@ -0,0 +1,90 @@
|
||||
#pragma once
|
||||
|
||||
#include <driver/gpio.h>
|
||||
|
||||
#include <cstdint>
|
||||
#include <esp_err.h>
|
||||
#include "tca9555.h"
|
||||
|
||||
namespace borla::board_config
|
||||
{
|
||||
|
||||
inline constexpr const char *kBoardName = "borla-s3";
|
||||
|
||||
// inline constexpr gpio_num_t kMcuPowerGpio = GPIO_NUM_4;
|
||||
// inline constexpr gpio_num_t kPeripheralPowerGpio = GPIO_NUM_6;
|
||||
// inline constexpr gpio_num_t kLedGpio = GPIO_NUM_11;
|
||||
//inline constexpr gpio_num_t kPowerButtonGpio = GPIO_NUM_12;
|
||||
// 2026-9-17 ckkj add: TCA9555 INT 中断脚接主控 GPIO45,
|
||||
// 按键按下/释放时 INT 拉低,下降沿触发唤醒 iot_button 状态机。
|
||||
inline constexpr gpio_num_t kTcaIntGpio = GPIO_NUM_45;
|
||||
|
||||
inline constexpr gpio_num_t kAudioI2cSdaGpio = GPIO_NUM_2;
|
||||
inline constexpr gpio_num_t kAudioI2cSclGpio = GPIO_NUM_1;
|
||||
inline constexpr gpio_num_t kAudioI2sMclkGpio = GPIO_NUM_NC;
|
||||
|
||||
inline constexpr gpio_num_t comSda = GPIO_NUM_9; // LCD_MOSI_GPIO, SD_MOSI_PIN
|
||||
inline constexpr gpio_num_t comScl = GPIO_NUM_10; // LCD_SCK_GPIO
|
||||
|
||||
// inline constexpr gpio_num_t kAudioI2sBclkGpio = GPIO_NUM_16;
|
||||
// inline constexpr gpio_num_t kAudioI2sWordSelectGpio = GPIO_NUM_17;
|
||||
// inline constexpr gpio_num_t kAudioI2sDataInGpio = GPIO_NUM_15;
|
||||
// inline constexpr gpio_num_t kAudioI2sDataOutGpio = GPIO_NUM_18;
|
||||
inline constexpr gpio_num_t kAudioI2sBclkGpio = GPIO_NUM_18;
|
||||
inline constexpr gpio_num_t kAudioI2sWordSelectGpio = GPIO_NUM_16;
|
||||
inline constexpr gpio_num_t kAudioI2sDataInGpio = GPIO_NUM_17;
|
||||
inline constexpr gpio_num_t kAudioI2sDataOutGpio = GPIO_NUM_15;
|
||||
|
||||
// inline constexpr gpio_num_t kAudioPowerAmplifierGpio = GPIO_NUM_40;
|
||||
inline constexpr uint16_t kAudioPowerAmplifierGpio = PA_CTL;
|
||||
|
||||
inline constexpr uint32_t kAudioOutputSampleRate = 48000;
|
||||
inline constexpr uint32_t kAudioInputHardwareSampleRate = 48000;
|
||||
inline constexpr uint32_t kAudioProtocolInputSampleRate = 16000;
|
||||
|
||||
inline constexpr uint32_t kWifiRetryInitialDelayMs = 1000;
|
||||
inline constexpr uint32_t kWifiRetryMaximumDelayMs = 60000;
|
||||
inline constexpr uint8_t kWifiRetryMultiplier = 2;
|
||||
inline constexpr uint8_t kWifiRetryJitterPercent = 20;
|
||||
|
||||
inline constexpr gpio_num_t kMl307TxGpio = GPIO_NUM_43;
|
||||
inline constexpr gpio_num_t kMl307RxGpio = GPIO_NUM_44;
|
||||
inline constexpr uint32_t kMl307BaudRate = 115200;
|
||||
inline constexpr uint32_t kWifiDisconnectFailoverMs = 30000;
|
||||
inline constexpr int8_t kWifiWeakRssiDbm = -80;
|
||||
inline constexpr uint8_t kWifiWeakSampleCount = 6;
|
||||
// 4G physical switch sensing (see DualNetworkPolicyConfig).
|
||||
inline constexpr uint8_t kModemAbsentSampleCount = 2;
|
||||
inline constexpr uint32_t kModemUnavailableRepeatMs = 120000;
|
||||
|
||||
inline constexpr uint16_t kButtonLongPressMs = 2000;
|
||||
// iot_button's short_press_time is NOT a minimum press duration — it is the
|
||||
// window after a release in which the next press still joins the same
|
||||
// multi-click group. 50 ms made every human double-click resolve as two
|
||||
// single clicks; 180 ms is the component default the legacy firmware ran on.
|
||||
// 注意:组件同时把它当作"单次按下时长"阈值,按下超过它的释放会让组件
|
||||
// 直接结束分组并且不产生任何点击事件(四击因此被拆散/丢失)。多击分组
|
||||
// 现已由 ButtonInput 自己实现,这里只保留给组件内部状态机使用。
|
||||
inline constexpr uint16_t kButtonShortPressMs = 180;
|
||||
// 多击分组窗口:一次松开后,只要在这个窗口内再次按下,就并入同一组多击。
|
||||
// 只与"松开→按下"的间隔有关,与按了多久无关,所以慢速连击也能正确识别。
|
||||
// 实测人手连击的松开→按下间隔多在 60~230ms,组间停顿多 >600ms。
|
||||
inline constexpr uint32_t kButtonMultiClickWindowMs = 320;
|
||||
inline constexpr int kButtonReleaseWaitMs = 5000;
|
||||
// TCA9555 KEY(P1.0) 软件去抖:iot_button 以 5ms 周期调用 get_key_level,
|
||||
// 只有连续 N 次采样读到同一电平才认可一次电平变化。
|
||||
// 12 次 ≈ 60ms,用于滤掉弱上拉网络(RF/电源/I2C 串扰)上的短促低电平毛刺,
|
||||
// 这类毛刺此前会被当成真实的按下-松开,产生单击/双击/三击/四击假事件。
|
||||
inline constexpr uint16_t kButtonDebounceSamples = 12;
|
||||
|
||||
} // namespace borla::board_config
|
||||
|
||||
namespace borla // ckkj add
|
||||
{
|
||||
|
||||
constexpr uint16_t kMcuPowerExtIo = MCU_VCC_CTL;
|
||||
constexpr uint16_t kPeripheralPowerExtIo = PREP_VCC_CTL;
|
||||
constexpr uint16_t kPowerButtonExtIo = KEY;
|
||||
// constexpr uint16_t kAudioAmpExtIo = PA_CTL;
|
||||
|
||||
}
|
||||
493
main/platform/borla_s3/borla_s3_platform.cc
Normal file
493
main/platform/borla_s3/borla_s3_platform.cc
Normal file
@@ -0,0 +1,493 @@
|
||||
#include "platform/borla_s3/borla_s3_platform.h"
|
||||
#include "platform/borla_s3/capacitive_touch_input.h"
|
||||
#include "platform/borla_s3/board_config.h"
|
||||
//#include <driver/touch_sensor.h>
|
||||
#include <driver/touch_pad.h>
|
||||
#include <driver/gpio.h>
|
||||
#include <esp_app_desc.h>
|
||||
#include <esp_attr.h>
|
||||
#include <esp_chip_info.h>
|
||||
#include <esp_err.h>
|
||||
#include <esp_log.h>
|
||||
#include <esp_mac.h>
|
||||
#include <esp_system.h>
|
||||
#include <esp_sleep.h>
|
||||
#include <esp_pm.h>
|
||||
#include <freertos/FreeRTOS.h>
|
||||
#include <freertos/task.h>
|
||||
|
||||
#include <algorithm>
|
||||
#include <cstdio>
|
||||
|
||||
namespace borla
|
||||
{
|
||||
namespace
|
||||
{
|
||||
|
||||
constexpr const char *kTag = "BorlaS3Platform2";
|
||||
|
||||
bool CheckGpioResult(esp_err_t result, const char *operation)
|
||||
{
|
||||
if (result == ESP_OK)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
ESP_LOGE(kTag, "%s failed: %s", operation, esp_err_to_name(result));
|
||||
return false;
|
||||
}
|
||||
////2026-9-4 ckkj add
|
||||
// ESP32-S3 深睡仅支持一个触摸通道,浅睡支持全部已配置通道。
|
||||
// 此处使用浅睡(esp_light_sleep_start)实现 IO3/IO5/IO6 三路触摸唤醒。
|
||||
// 选用运行时触摸区中的全部通道作为浅睡唤醒通道。
|
||||
// 与运行时 TouchChannelConfig::minimum_threshold_delta 一致的灵敏度下限。
|
||||
constexpr uint32_t kTouchWakeMinDelta = 80;
|
||||
// 启动 FSM 后等待首轮扫描测量完成、基准收敛的时间。
|
||||
constexpr uint32_t kTouchWakeWarmupMs = 500;
|
||||
|
||||
// 软关机前配置浅睡触摸唤醒通道(PAD3/PAD5/PAD6 全部使能)。
|
||||
// S3 触摸硬件按增量比较:raw - benchmark > threshold 时触发中断唤醒。
|
||||
// 运行时触摸 raw 值随触摸升高(filtered > baseline + delta),
|
||||
// 因此 threshold 取 max(baseline/10, kTouchWakeMinDelta)。
|
||||
void ConfigureTouchWakeup()
|
||||
{
|
||||
if (touch_pad_init() != ESP_OK)
|
||||
{
|
||||
ESP_LOGE(kTag, "touch wakeup init failed, touch wake disabled");
|
||||
return;
|
||||
}
|
||||
touch_pad_config(TOUCH_PAD_NUM3);
|
||||
touch_pad_config(TOUCH_PAD_NUM5);
|
||||
touch_pad_config(TOUCH_PAD_NUM6);
|
||||
// 与运行时 CapacitiveTouchInput 保持一致的电压配置,
|
||||
// 避免默认衰减电压导致计数饱和。
|
||||
touch_pad_set_voltage(
|
||||
TOUCH_HVOLT_2V7,
|
||||
TOUCH_LVOLT_0V5,
|
||||
TOUCH_HVOLT_ATTEN_1V);
|
||||
|
||||
// 去噪配置(内部使用 PAD0 作参考通道)
|
||||
touch_pad_denoise_t denoise = {
|
||||
.grade = TOUCH_PAD_DENOISE_BIT4,
|
||||
.cap_level = TOUCH_PAD_DENOISE_CAP_L4,
|
||||
};
|
||||
touch_pad_denoise_set_config(&denoise);
|
||||
touch_pad_denoise_enable();
|
||||
|
||||
// 滤波器配置,稳定基准值
|
||||
touch_filter_config_t filter_info = {
|
||||
.mode = TOUCH_PAD_FILTER_IIR_16,
|
||||
.debounce_cnt = 1,
|
||||
.noise_thr = 0,
|
||||
.jitter_step = 4,
|
||||
.smh_lvl = TOUCH_PAD_SMOOTH_IIR_2,
|
||||
};
|
||||
touch_pad_filter_set_config(&filter_info);
|
||||
touch_pad_filter_enable();
|
||||
|
||||
touch_pad_set_fsm_mode(TOUCH_FSM_MODE_TIMER);
|
||||
touch_pad_fsm_start();
|
||||
vTaskDelay(pdMS_TO_TICKS(kTouchWakeWarmupMs));
|
||||
|
||||
// 为每个通道设置触发阈值(增量:max(baseline/10, 下限))
|
||||
for (touch_pad_t pad : kTouchPads)
|
||||
{
|
||||
uint32_t raw = 0;
|
||||
if (touch_pad_read_raw_data(pad, &raw) != ESP_OK ||
|
||||
raw == 0 || raw >= 0x3FFFF0)
|
||||
{
|
||||
ESP_LOGW(kTag, "touch PAD%u raw invalid=%lu, skip thresh",
|
||||
static_cast<unsigned>(pad),
|
||||
static_cast<unsigned long>(raw));
|
||||
continue;
|
||||
}
|
||||
const uint32_t threshold =
|
||||
std::max<uint32_t>(raw / 16, kTouchWakeMinDelta);
|
||||
touch_pad_set_thresh(pad, threshold);
|
||||
touch_pad_sleep_set_threshold(pad, threshold);
|
||||
touch_pad_sleep_channel_enable(pad, true);
|
||||
uint32_t sleep_bench = 0;
|
||||
touch_pad_sleep_channel_read_benchmark(pad, &sleep_bench);
|
||||
ESP_LOGI(kTag, "touch wakeup PAD%u baseline=%lu delta_th=%lu sleep_bench=%lu",
|
||||
static_cast<unsigned>(pad),
|
||||
static_cast<unsigned long>(raw),
|
||||
static_cast<unsigned long>(threshold),
|
||||
static_cast<unsigned long>(sleep_bench));
|
||||
}
|
||||
touch_pad_sleep_channel_reset_benchmark();
|
||||
} ///////ckkj add end
|
||||
} // namespace
|
||||
BorlaS3Platform::BorlaS3Platform(TCA9555 &tca9555)
|
||||
: tca9555_(tca9555)
|
||||
{
|
||||
}
|
||||
BorlaS3Platform::~BorlaS3Platform()
|
||||
{
|
||||
if (alert_timer_ != nullptr)
|
||||
{
|
||||
esp_timer_stop(alert_timer_);
|
||||
esp_timer_delete(alert_timer_);
|
||||
}
|
||||
}
|
||||
|
||||
bool BorlaS3Platform::Initialize()
|
||||
{
|
||||
// if (!InitializePowerRails() || !LoadIdentity() ||
|
||||
// !led_.Initialize(board_config::kLedGpio)) {
|
||||
if (!InitializePowerRails() || !LoadIdentity())
|
||||
{
|
||||
ESP_LOGE(kTag, "platform initialization failed");
|
||||
return false;
|
||||
}
|
||||
|
||||
const esp_timer_create_args_t timer_args = {
|
||||
.callback = &BorlaS3Platform::AlertTimerCallback,
|
||||
.arg = this,
|
||||
.dispatch_method = ESP_TIMER_TASK,
|
||||
.name = "led_alert2",
|
||||
.skip_unhandled_events = true,
|
||||
};
|
||||
if (esp_timer_create(&timer_args, &alert_timer_) != ESP_OK)
|
||||
{
|
||||
ESP_LOGE(kTag, "temporary LED alert timer creation failed");
|
||||
return false;
|
||||
}
|
||||
//2026-9-8 ckkj add 省电模式配置
|
||||
esp_pm_config_t pm_config = {};
|
||||
pm_config.max_freq_mhz = 240;
|
||||
pm_config.min_freq_mhz = 10;
|
||||
pm_config.light_sleep_enable = false;
|
||||
const esp_err_t pm_result = esp_pm_configure(&pm_config);
|
||||
if (pm_result != ESP_OK) {
|
||||
ESP_LOGW(kTag, "esp_pm_configure failed: %s (enable CONFIG_PM_ENABLE)",
|
||||
esp_err_to_name(pm_result));
|
||||
} else {
|
||||
ESP_LOGI(kTag, "power management enabled dfs=240/10MHz auto_light_sleep=false");
|
||||
}
|
||||
//////
|
||||
initialized_ = true;
|
||||
ESP_LOGI(kTag, "platform initialized board=%s mac=%s version=%s chip=%s",
|
||||
identity_.board, identity_.mac, identity_.app_version,
|
||||
identity_.chip_model);
|
||||
return true;
|
||||
}
|
||||
|
||||
void BorlaS3Platform::SetLed(LedPattern pattern)
|
||||
{
|
||||
if (!initialized_)
|
||||
{
|
||||
ESP_LOGW(kTag, "LED request ignored before platform initialization");
|
||||
return;
|
||||
}
|
||||
std::lock_guard<std::mutex> lock(led_state_mutex_);
|
||||
desired_led_pattern_ = pattern;
|
||||
if (!temporary_alert_active_)
|
||||
{
|
||||
led_.SetPattern(pattern);
|
||||
}
|
||||
}
|
||||
|
||||
void BorlaS3Platform::ShowTemporaryLedAlert(uint32_t duration_ms)
|
||||
{
|
||||
if (!initialized_ || alert_timer_ == nullptr)
|
||||
{
|
||||
ESP_LOGW(kTag, "temporary LED alert ignored before initialization");
|
||||
return;
|
||||
}
|
||||
duration_ms = std::max<uint32_t>(
|
||||
100, std::min<uint32_t>(duration_ms, 60000));
|
||||
std::lock_guard<std::mutex> lock(led_state_mutex_);
|
||||
const esp_err_t stop = esp_timer_stop(alert_timer_);
|
||||
if (stop != ESP_OK && stop != ESP_ERR_INVALID_STATE)
|
||||
{
|
||||
ESP_LOGW(kTag, "temporary LED timer stop failed: %s",
|
||||
esp_err_to_name(stop));
|
||||
}
|
||||
temporary_alert_active_ = true;
|
||||
led_.SetPattern(LedPattern::kError);
|
||||
const esp_err_t start = esp_timer_start_once(
|
||||
alert_timer_, static_cast<uint64_t>(duration_ms) * 1000ULL);
|
||||
if (start != ESP_OK)
|
||||
{
|
||||
temporary_alert_active_ = false;
|
||||
led_.SetPattern(desired_led_pattern_);
|
||||
ESP_LOGE(kTag, "temporary LED timer start failed: %s",
|
||||
esp_err_to_name(start));
|
||||
}
|
||||
}
|
||||
|
||||
void BorlaS3Platform::ReportError(uint32_t error_id)
|
||||
{
|
||||
ESP_LOGE(kTag, "platform error id=%lu",
|
||||
static_cast<unsigned long>(error_id));
|
||||
if (initialized_)
|
||||
{
|
||||
SetLed(LedPattern::kError);
|
||||
}
|
||||
}
|
||||
|
||||
void BorlaS3Platform::Reboot()
|
||||
{
|
||||
ESP_LOGW(kTag, "reboot requested");
|
||||
vTaskDelay(pdMS_TO_TICKS(100));
|
||||
esp_restart();
|
||||
}
|
||||
|
||||
void BorlaS3Platform::EnterSoftOff(uint64_t timer_wakeup_us)
|
||||
{
|
||||
if (initialized_)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(led_state_mutex_);
|
||||
temporary_alert_active_ = false;
|
||||
desired_led_pattern_ = LedPattern::kOff;
|
||||
if (alert_timer_ != nullptr)
|
||||
{
|
||||
esp_timer_stop(alert_timer_);
|
||||
}
|
||||
led_.SetPattern(LedPattern::kOff);
|
||||
}
|
||||
int waited_ms = 0;
|
||||
// while (gpio_get_level(board_config::kPowerButtonGpio) == 1 &&
|
||||
// waited_ms < board_config::kButtonReleaseWaitMs) {
|
||||
while (waited_ms < board_config::kButtonReleaseWaitMs)
|
||||
{
|
||||
uint8_t p1 = 0xFF;
|
||||
const esp_err_t r = tca9555_.read_p1_input(&p1);
|
||||
const bool still_pressed = (r == ESP_OK) && ((p1 & (1U << TCA_P1_KEY)) == 0);
|
||||
if (!still_pressed)
|
||||
{
|
||||
break;
|
||||
} // 2028-9-4 ckkj mod
|
||||
vTaskDelay(pdMS_TO_TICKS(20));
|
||||
waited_ms += 20;
|
||||
}
|
||||
if (waited_ms >= board_config::kButtonReleaseWaitMs)
|
||||
{
|
||||
ESP_LOGW(kTag, "TCA9555 P1.0 KEY remained pressed after %d ms, proceeding",
|
||||
waited_ms);
|
||||
}
|
||||
// 2026-8-26 ckkj add
|
||||
// tca9555_.clr_pin(MCU_VCC_CTL);
|
||||
tca9555_.clr_pin(EN_4G);
|
||||
tca9555_.clr_pin(PA_CTL);
|
||||
tca9555_.clr_pin(PREP_VCC_CTL);
|
||||
tca9555_.clr_pin(V5_EN);
|
||||
|
||||
tca9555_.clr_pin(SC_LEDA);
|
||||
tca9555_.clr_pin(OV_FLASH);
|
||||
tca9555_.set_pin(OV_PWDN);
|
||||
tca9555_.clr_pin(SC_LEDA);
|
||||
// end
|
||||
esp_sleep_disable_wakeup_source(ESP_SLEEP_WAKEUP_ALL);
|
||||
// esp_err_t result = gpio_wakeup_enable(
|
||||
// board_config::kPowerButtonGpio, GPIO_INTR_HIGH_LEVEL);
|
||||
// if (result == ESP_OK) {
|
||||
// result = esp_sleep_enable_gpio_wakeup();
|
||||
// }
|
||||
// 配置触摸唤醒引脚 (IO3=PAD3, IO5=PAD5, IO6=PAD6)
|
||||
ConfigureTouchWakeup();
|
||||
// touch_pad_fsm_stop();
|
||||
// touch_pad_deinit();
|
||||
// touch_pad_init();
|
||||
// touch_pad_config(TOUCH_PAD_NUM3);
|
||||
// touch_pad_config(TOUCH_PAD_NUM5);
|
||||
// touch_pad_config(TOUCH_PAD_NUM6);
|
||||
|
||||
esp_err_t result = esp_sleep_enable_touchpad_wakeup(); // 配置触摸唤醒引脚 (IO3=PAD3, IO5=PAD5, IO6=PAD6)
|
||||
if (result != ESP_OK)
|
||||
{
|
||||
ESP_LOGE(kTag, "touch wake configuration failed: %s",
|
||||
esp_err_to_name(result));
|
||||
// esp_restart();
|
||||
}
|
||||
//2026-9-8 ckkj add 配置按键唤醒引脚
|
||||
// GPIO45 (TCA9555 INT) 作为按键唤醒源:TCA9555 开漏输出,
|
||||
// 按键按下时 INT 拉低,配置为低电平触发唤醒。
|
||||
// 与触摸唤醒在浅睡眠中可共存(EXT0/EXT1 才与触摸互斥)。
|
||||
// esp_err_t gpio_wake = gpio_wakeup_enable(
|
||||
// board_config::kTcaIntGpio, GPIO_INTR_LOW_LEVEL);
|
||||
// if (gpio_wake != ESP_OK)
|
||||
// {
|
||||
// ESP_LOGW(kTag, "GPIO45 wakeup enable failed: %s",
|
||||
// esp_err_to_name(gpio_wake));
|
||||
// }
|
||||
// gpio_wake = esp_sleep_enable_gpio_wakeup();
|
||||
// if (gpio_wake != ESP_OK)
|
||||
// {
|
||||
// ESP_LOGW(kTag, "esp_sleep_enable_gpio_wakeup failed: %s",
|
||||
// esp_err_to_name(gpio_wake));
|
||||
// }
|
||||
/////////
|
||||
if (timer_wakeup_us > 0)
|
||||
{
|
||||
result = esp_sleep_enable_timer_wakeup(timer_wakeup_us);
|
||||
if (result != ESP_OK)
|
||||
{
|
||||
ESP_LOGE(kTag, "timer wake configuration failed: %s",
|
||||
esp_err_to_name(result));
|
||||
}
|
||||
}
|
||||
//esp_sleep_enable_timer_wakeup(3*60*1000000ULL);
|
||||
|
||||
// ESP_LOGI(kTag, "entering final light sleep timer_us=%llu",
|
||||
esp_sleep_pd_config(ESP_PD_DOMAIN_RTC_PERIPH, ESP_PD_OPTION_ON);
|
||||
esp_sleep_pd_config(ESP_PD_DOMAIN_RC_FAST, ESP_PD_OPTION_ON);
|
||||
esp_sleep_pd_config(ESP_PD_DOMAIN_XTAL, ESP_PD_OPTION_OFF);
|
||||
ESP_LOGI(kTag, "entering light sleep timer_us=%llu",static_cast<unsigned long long>(timer_wakeup_us));
|
||||
|
||||
const esp_err_t sleep_result = esp_light_sleep_start();
|
||||
const esp_sleep_wakeup_cause_t cause =esp_sleep_get_wakeup_cause();
|
||||
|
||||
RTC_DATA_ATTR static esp_sleep_wakeup_cause_t g_rtc_wake_cause;
|
||||
// 在esp_light_sleep_start()返回后,restart之前:
|
||||
g_rtc_wake_cause = esp_sleep_get_wakeup_cause();
|
||||
// 重启后ConsumeSoftOffWakeReason读取g_rtc_wake_cause
|
||||
|
||||
ESP_LOGI(kTag, "light sleep returned result=%s cause=%d",esp_err_to_name(sleep_result), static_cast<int>(cause));
|
||||
// 浅睡唤醒后重启,复用深睡的唤醒原因处理流程
|
||||
esp_restart();
|
||||
}
|
||||
|
||||
void BorlaS3Platform::AlertTimerCallback(void *context)
|
||||
{
|
||||
static_cast<BorlaS3Platform *>(context)->OnAlertTimer();
|
||||
}
|
||||
|
||||
void BorlaS3Platform::OnAlertTimer()
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(led_state_mutex_);
|
||||
temporary_alert_active_ = false;
|
||||
if (initialized_)
|
||||
{
|
||||
led_.SetPattern(desired_led_pattern_);
|
||||
}
|
||||
}
|
||||
|
||||
SoftOffWakeReason BorlaS3Platform::ConsumeSoftOffWakeReason()
|
||||
{ // 2026-8-26 ckkj
|
||||
// const auto reason =
|
||||
// static_cast<SoftOffWakeReason>(g_soft_off_wake_reason);
|
||||
// g_soft_off_wake_reason =
|
||||
// static_cast<uint32_t>(SoftOffWakeReason::kNone);
|
||||
// return reason;
|
||||
const esp_sleep_wakeup_cause_t cause =
|
||||
esp_sleep_get_wakeup_cause();
|
||||
ESP_LOGI(kTag, "wakeup cause=%d", static_cast<int>(cause));
|
||||
switch (cause)
|
||||
{
|
||||
case ESP_SLEEP_WAKEUP_TOUCHPAD:
|
||||
case ESP_SLEEP_WAKEUP_EXT0:
|
||||
case ESP_SLEEP_WAKEUP_EXT1:
|
||||
return SoftOffWakeReason::kButton;
|
||||
case ESP_SLEEP_WAKEUP_TIMER:
|
||||
return SoftOffWakeReason::kTimer;
|
||||
default:
|
||||
return SoftOffWakeReason::kNone;
|
||||
}
|
||||
}
|
||||
// 2026-8-26 ckkj
|
||||
bool BorlaS3Platform::ReadWakeButton()
|
||||
{
|
||||
uint8_t val = 0;
|
||||
esp_err_t ret = tca9555_.read_p1_input(&val);
|
||||
if (ret != ESP_OK)
|
||||
{
|
||||
ESP_LOGW(kTag, "read P1 input failed: %s",
|
||||
esp_err_to_name(ret));
|
||||
return false;
|
||||
}
|
||||
return (val & 0x01) == 0;
|
||||
}
|
||||
bool BorlaS3Platform::InitializePowerRails()
|
||||
{
|
||||
// gpio_config_t config = {};
|
||||
// config.pin_bit_mask =
|
||||
// (1ULL << board_config::kMcuPowerGpio) |
|
||||
// (1ULL << board_config::kPeripheralPowerGpio);
|
||||
// config.mode = GPIO_MODE_OUTPUT;
|
||||
// config.pull_up_en = GPIO_PULLUP_DISABLE;
|
||||
// config.pull_down_en = GPIO_PULLDOWN_DISABLE;
|
||||
// config.intr_type = GPIO_INTR_DISABLE;
|
||||
|
||||
// if (!CheckGpioResult(gpio_config(&config), "configure power GPIOs")) {
|
||||
// return false;
|
||||
// }
|
||||
|
||||
bool valid = true;
|
||||
valid &= CheckGpioResult(
|
||||
// gpio_set_level(board_config::kMcuPowerGpio, 1),
|
||||
tca9555_.set_pin(kMcuPowerExtIo),
|
||||
"preload MCU power (TCA9555)");
|
||||
valid &= CheckGpioResult(
|
||||
// gpio_set_level(board_config::kPeripheralPowerGpio, 1),
|
||||
tca9555_.set_pin(kPeripheralPowerExtIo), "preload peripheral power (TCA9555)");
|
||||
//valid &= CheckGpioResult(tca9555_.set_pin(V5_EN), "enable 5V boost (TCA9555)");
|
||||
vTaskDelay(pdMS_TO_TICKS(300));
|
||||
// valid &= CheckGpioResult(
|
||||
// //gpio_hold_dis(board_config::kMcuPowerGpio),
|
||||
// "release MCU power GPIO hold");
|
||||
// valid &= CheckGpioResult(
|
||||
// //gpio_hold_dis(board_config::kPeripheralPowerGpio),
|
||||
// "release peripheral power GPIO hold");
|
||||
// valid &= CheckGpioResult(
|
||||
// //gpio_set_level(board_config::kMcuPowerGpio, 1),
|
||||
// "enable MCU power rail");
|
||||
// valid &= CheckGpioResult(
|
||||
// //gpio_set_level(board_config::kPeripheralPowerGpio, 1),
|
||||
// "enable peripheral power rail");
|
||||
// valid &= CheckGpioResult(
|
||||
// //gpio_hold_en(board_config::kMcuPowerGpio),
|
||||
// "hold MCU power GPIO");
|
||||
// valid &= CheckGpioResult(
|
||||
// //gpio_hold_en(board_config::kPeripheralPowerGpio),
|
||||
// "hold peripheral power GPIO");
|
||||
|
||||
if (valid)
|
||||
{
|
||||
ESP_LOGI(kTag, "power rails enabled via TCA9555");
|
||||
}
|
||||
return valid;
|
||||
}
|
||||
|
||||
bool BorlaS3Platform::LoadIdentity()
|
||||
{
|
||||
std::snprintf(identity_.board, sizeof(identity_.board), "%s",
|
||||
board_config::kBoardName);
|
||||
|
||||
uint8_t mac[6] = {};
|
||||
const esp_err_t mac_result = esp_read_mac(mac, ESP_MAC_WIFI_STA);
|
||||
if (mac_result != ESP_OK)
|
||||
{
|
||||
ESP_LOGE(kTag, "failed to read station MAC: %s",
|
||||
esp_err_to_name(mac_result));
|
||||
return false;
|
||||
}
|
||||
// Lower case, and it has to stay that way. This string is the device_id the
|
||||
// server keys its live connection map with, verbatim and unnormalised
|
||||
// (websocket_server.py `self._connections[device_id]`). The backend, on the
|
||||
// other hand, lower-cases the MAC before POSTing to
|
||||
// /internal/devices/{mac}/control — which is how an admin activation, a
|
||||
// deactivation or a volume change reaches an online device.
|
||||
//
|
||||
// The previous firmware formatted with %02x (system_info.cc), so those two
|
||||
// always met. Emitting %02X here registered the connection under
|
||||
// "58:E6:C5:..." while every control call looked up "58:e6:c5:...", so the
|
||||
// server answered 404 "device not connected" and silently dropped the
|
||||
// command. Visible symptom: a device that has just been activated keeps
|
||||
// reading out its activation code forever, because the welcome prompt that
|
||||
// ends that loop is delivered through exactly this path.
|
||||
std::snprintf(identity_.mac, sizeof(identity_.mac),
|
||||
"%02x:%02x:%02x:%02x:%02x:%02x",
|
||||
mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
|
||||
|
||||
const esp_app_desc_t *app = esp_app_get_description();
|
||||
std::snprintf(identity_.app_version, sizeof(identity_.app_version), "%s",
|
||||
app == nullptr ? "unknown" : app->version);
|
||||
|
||||
esp_chip_info_t chip = {};
|
||||
esp_chip_info(&chip);
|
||||
std::snprintf(identity_.chip_model, sizeof(identity_.chip_model),
|
||||
"%s-rev%d", CONFIG_IDF_TARGET, chip.revision);
|
||||
return true;
|
||||
}
|
||||
|
||||
} // namespace borla
|
||||
45
main/platform/borla_s3/borla_s3_platform.h
Normal file
45
main/platform/borla_s3/borla_s3_platform.h
Normal file
@@ -0,0 +1,45 @@
|
||||
#pragma once
|
||||
|
||||
#include "platform/borla_s3/ws2812_led.h"
|
||||
#include "ports/device_platform.h"
|
||||
#include "platform/borla_s3/tca9555.h"
|
||||
#include <esp_timer.h>
|
||||
|
||||
#include <mutex>
|
||||
|
||||
namespace borla {
|
||||
|
||||
class BorlaS3Platform final : public IDevicePlatform {
|
||||
public:
|
||||
explicit BorlaS3Platform(TCA9555& tca9555);
|
||||
~BorlaS3Platform();
|
||||
|
||||
bool Initialize() override;
|
||||
const DeviceIdentity& Identity() const override { return identity_; }
|
||||
void SetLed(LedPattern pattern) override;
|
||||
void ShowTemporaryLedAlert(uint32_t duration_ms) override;
|
||||
void ReportError(uint32_t error_id) override;
|
||||
void Reboot() override;
|
||||
void EnterSoftOff(uint64_t timer_wakeup_us) override;
|
||||
SoftOffWakeReason ConsumeSoftOffWakeReason() override;
|
||||
//2026-8-26 ckkj add
|
||||
bool ReadWakeButton() override;
|
||||
|
||||
private:
|
||||
static void AlertTimerCallback(void* context);
|
||||
void OnAlertTimer();
|
||||
bool InitializePowerRails();
|
||||
bool LoadIdentity();
|
||||
|
||||
TCA9555& tca9555_;
|
||||
|
||||
DeviceIdentity identity_{};
|
||||
Ws2812Led led_;
|
||||
std::mutex led_state_mutex_;
|
||||
esp_timer_handle_t alert_timer_ = nullptr;
|
||||
LedPattern desired_led_pattern_ = LedPattern::kOff;
|
||||
bool temporary_alert_active_ = false;
|
||||
bool initialized_ = false;
|
||||
};
|
||||
|
||||
} // namespace borla
|
||||
385
main/platform/borla_s3/button_input.cc
Normal file
385
main/platform/borla_s3/button_input.cc
Normal file
@@ -0,0 +1,385 @@
|
||||
#include "platform/borla_s3/button_input.h"
|
||||
|
||||
#include "platform/borla_s3/board_config.h"
|
||||
|
||||
// #include <button_gpio.h>
|
||||
// #include <driver/gpio.h>
|
||||
// #include <driver/rtc_io.h>
|
||||
#include <esp_err.h>
|
||||
#include <esp_log.h>
|
||||
#include <freertos/FreeRTOS.h>
|
||||
#include <freertos/task.h>
|
||||
|
||||
namespace borla {
|
||||
namespace {
|
||||
|
||||
constexpr const char* kTag = "ButtonInput2";
|
||||
|
||||
// KEY(P1.0) 电平语义:扩展芯片内部上拉,松开=高,按下被拉到低(低有效)。
|
||||
// iot_button 的 get_key_level 要求返回 1 表示"按下"。
|
||||
constexpr uint8_t kKeyPressed = 1;
|
||||
constexpr uint8_t kKeyReleased = 0;
|
||||
|
||||
// I2C 连续读失败达到该次数才认为按键已松开,避免一次总线抖动被当成"松开沿"。
|
||||
constexpr uint32_t kKeyReadFailLimit = 20;
|
||||
|
||||
// 初始化阶段等待按键松开:采样间隔与确认松开所需连续采样次数。
|
||||
constexpr uint32_t kReleaseSampleIntervalMs = 20;
|
||||
constexpr uint8_t kReleaseConfirmSamples = 2;
|
||||
|
||||
bool RegisterButtonCallback(
|
||||
button_handle_t button,
|
||||
button_event_t event,
|
||||
button_event_args_t* args,
|
||||
button_cb_t callback,
|
||||
void* context)
|
||||
{
|
||||
const esp_err_t result =
|
||||
iot_button_register_cb(button, event, args, callback, context);
|
||||
if (result == ESP_OK) {
|
||||
return true;
|
||||
}
|
||||
ESP_LOGE(kTag, "failed to register button event=%d: %s",
|
||||
static_cast<int>(event), esp_err_to_name(result));
|
||||
return false;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
ButtonInput::ButtonInput(
|
||||
IEventPublisher& publisher,
|
||||
//const IRemoteBehaviorConfig& behavior_config)
|
||||
const IRemoteBehaviorConfig& behavior_config,TCA9555& tca9555)
|
||||
: publisher_(publisher),behavior_config_(behavior_config),tca9555_(tca9555)
|
||||
|
||||
{
|
||||
}
|
||||
|
||||
ButtonInput::~ButtonInput()
|
||||
{
|
||||
if (button_ != nullptr) {
|
||||
iot_button_delete(button_);
|
||||
}
|
||||
}
|
||||
|
||||
/*bool ButtonInput::Initialize()
|
||||
{
|
||||
gpio_hold_dis(board_config::kPowerButtonGpio);
|
||||
rtc_gpio_hold_dis(board_config::kPowerButtonGpio);
|
||||
rtc_gpio_deinit(board_config::kPowerButtonGpio);
|
||||
|
||||
gpio_config_t input_config = {};
|
||||
input_config.pin_bit_mask = 1ULL << board_config::kPowerButtonGpio;
|
||||
input_config.mode = GPIO_MODE_INPUT;
|
||||
// input_config.pull_up_en = GPIO_PULLUP_DISABLE;
|
||||
// input_config.pull_down_en = GPIO_PULLDOWN_ENABLE;//2026-7-29 ckkj debug
|
||||
input_config.pull_up_en = GPIO_PULLUP_ENABLE;
|
||||
input_config.pull_down_en = GPIO_PULLDOWN_DISABLE;
|
||||
input_config.intr_type = GPIO_INTR_DISABLE;
|
||||
esp_err_t result = gpio_config(&input_config);
|
||||
if (result != ESP_OK) {
|
||||
ESP_LOGE(kTag, "failed to configure GPIO%d: %s",
|
||||
static_cast<int>(board_config::kPowerButtonGpio),
|
||||
esp_err_to_name(result));
|
||||
return false;
|
||||
}
|
||||
|
||||
int waited_ms = 0;
|
||||
while (gpio_get_level(board_config::kPowerButtonGpio) == 1 &&
|
||||
waited_ms < board_config::kButtonReleaseWaitMs) {
|
||||
vTaskDelay(pdMS_TO_TICKS(20));
|
||||
waited_ms += 20;
|
||||
}
|
||||
if (gpio_get_level(board_config::kPowerButtonGpio) == 1) {
|
||||
ESP_LOGW(kTag, "power button remained pressed after %d ms",
|
||||
waited_ms);
|
||||
}
|
||||
|
||||
const button_config_t button_config = {
|
||||
.long_press_time = board_config::kButtonLongPressMs,
|
||||
.short_press_time = board_config::kButtonShortPressMs,
|
||||
};
|
||||
const button_gpio_config_t gpio_config = {
|
||||
.gpio_num = board_config::kPowerButtonGpio,
|
||||
//.active_level = 1,//2026-7-29 ckkj debug
|
||||
.active_level = 0,
|
||||
.enable_power_save = false,
|
||||
.disable_pull = false,
|
||||
};
|
||||
result =
|
||||
iot_button_new_gpio_device(&button_config, &gpio_config, &button_);
|
||||
if (result != ESP_OK) {
|
||||
ESP_LOGE(kTag, "failed to create GPIO button: %s",
|
||||
esp_err_to_name(result));
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!RegisterCallbacks()) {
|
||||
iot_button_delete(button_);
|
||||
button_ = nullptr;
|
||||
return false;
|
||||
}
|
||||
|
||||
ESP_LOGI(kTag, "power button initialized on GPIO%d",
|
||||
static_cast<int>(board_config::kPowerButtonGpio));
|
||||
return true;
|
||||
}*/
|
||||
|
||||
uint8_t ButtonInput::TcaGetKeyLevel(button_driver_t* driver)
|
||||
{
|
||||
if (driver == nullptr) {
|
||||
return kKeyReleased;
|
||||
}
|
||||
auto* ctx = reinterpret_cast<TcaButtonCtx*>(driver);
|
||||
if (ctx->tca == nullptr) {
|
||||
return kKeyReleased;
|
||||
}
|
||||
|
||||
uint8_t port1 = 0xFF;
|
||||
if (ctx->tca->read_p1_input(&port1) != ESP_OK) {
|
||||
// 读失败不能当成"松开":一次 I2C 抖动就会制造一个假的释放沿,
|
||||
// 让 iot_button 把一次真实长按拆成多个点击。保持上一次去抖结果,
|
||||
// 只有连续失败足够多才退回"未按下"。
|
||||
if (++ctx->read_fail_count >= kKeyReadFailLimit) {
|
||||
ctx->read_fail_count = 0;
|
||||
ctx->same_count = 0;
|
||||
ctx->stable_level = kKeyReleased;
|
||||
ESP_LOGW(kTag, "P1.0 read failed %u times, treat as released",
|
||||
static_cast<unsigned>(kKeyReadFailLimit));
|
||||
}
|
||||
} else {
|
||||
ctx->read_fail_count = 0;
|
||||
|
||||
// 按下 = P1.0 为低(KEY 内部上拉,按下被拉到低),松开 = 高。
|
||||
const uint8_t raw_pressed =
|
||||
((port1 & (1U << TCA_P1_KEY)) == 0U) ? kKeyPressed : kKeyReleased;
|
||||
const uint32_t now_ms = pdTICKS_TO_MS(xTaskGetTickCount());
|
||||
|
||||
if (raw_pressed == ctx->stable_level) {
|
||||
// 与当前稳定电平一致,清空突变计数
|
||||
ctx->same_count = 0;
|
||||
} else if (++ctx->same_count >= board_config::kButtonDebounceSamples) {
|
||||
// 关键:必须是"连续"多次读到新电平才确认变化。
|
||||
// 这样交替抖动的噪声(高-低-高-低)永远累积不到阈值。
|
||||
ctx->same_count = 0;
|
||||
ctx->stable_level = raw_pressed;
|
||||
if (raw_pressed == kKeyPressed) {
|
||||
ctx->press_start_ms = now_ms;
|
||||
ESP_LOGI(kTag, "P1.0 pressed (port1=0x%02x)", port1);
|
||||
} else {
|
||||
ctx->last_press_ms = now_ms - ctx->press_start_ms;
|
||||
ESP_LOGI(kTag, "P1.0 released (held=%lums)",
|
||||
static_cast<unsigned long>(ctx->last_press_ms));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 多击分组收尾:只有在"松开"状态且超过分组窗口后才发布。
|
||||
// 按下期间窗口不生效,因此按得慢的一击不会把整组多击拆散。
|
||||
if (ctx->owner != nullptr) {
|
||||
ctx->owner->CloseClickGroupIfIdle(
|
||||
ctx->stable_level, pdTICKS_TO_MS(xTaskGetTickCount()));
|
||||
}
|
||||
return ctx->stable_level;
|
||||
}
|
||||
|
||||
esp_err_t ButtonInput::TcaDelDriver(button_driver_t* driver)
|
||||
{
|
||||
// driver 嵌在 ButtonInput 对象里,不需要单独释放
|
||||
(void)driver;
|
||||
return ESP_OK;
|
||||
}
|
||||
bool ButtonInput::ReadTcaButtonRaw(bool* pressed)
|
||||
{
|
||||
uint8_t port1 = 0xFF;
|
||||
if (tca9555_.read_p1_input(&port1) != ESP_OK) {
|
||||
return false;
|
||||
}
|
||||
// 与 TcaGetKeyLevel 保持同一极性:KEY 内部上拉,低电平=按下。
|
||||
// (之前这里是 != 0,即把"空闲高电平"当成按下,导致启动时白等 5 秒
|
||||
// 并打印 "power button remained pressed" 的误报警告。)
|
||||
*pressed = (port1 & (1U << TCA_P1_KEY)) == 0U;
|
||||
return true;
|
||||
}
|
||||
|
||||
bool ButtonInput::WaitTcaButtonReleased(uint32_t timeout_ms)
|
||||
{
|
||||
uint32_t waited_ms = 0;
|
||||
uint8_t released_samples = 0;
|
||||
while (waited_ms < timeout_ms) {
|
||||
bool pressed = false;
|
||||
if (!ReadTcaButtonRaw(&pressed)) {
|
||||
// I2C 读失败:不能当成"松开",保持等待并继续采样
|
||||
released_samples = 0;
|
||||
} else if (!pressed) {
|
||||
// 连续多次读到松开才退出,避免毛刺让这里提前返回
|
||||
if (++released_samples >= kReleaseConfirmSamples) {
|
||||
return true;
|
||||
}
|
||||
} else {
|
||||
released_samples = 0;
|
||||
}
|
||||
vTaskDelay(pdMS_TO_TICKS(kReleaseSampleIntervalMs));
|
||||
waited_ms += kReleaseSampleIntervalMs;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
bool ButtonInput::Initialize()
|
||||
{
|
||||
bool pressed = false;
|
||||
if (!ReadTcaButtonRaw(&pressed)) {
|
||||
ESP_LOGE(kTag, "failed to read TCA9555 P1.0 during button init");
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!WaitTcaButtonReleased(board_config::kButtonReleaseWaitMs)) {
|
||||
ESP_LOGW(kTag, "power button remained pressed after %d ms",board_config::kButtonReleaseWaitMs);
|
||||
}
|
||||
|
||||
// 初始化自定义 driver 上下文(嵌入在本对象内,生命周期一致)
|
||||
driver_ctx_.tca = &tca9555_;
|
||||
driver_ctx_.owner = this;
|
||||
driver_ctx_.base.enable_power_save = false;
|
||||
driver_ctx_.base.get_key_level = &ButtonInput::TcaGetKeyLevel;
|
||||
driver_ctx_.base.enter_power_save = nullptr;
|
||||
driver_ctx_.base.del = &ButtonInput::TcaDelDriver;
|
||||
// 用当前真实电平作为去抖初值,避免开机瞬间凭空多出一个按下沿
|
||||
if (ReadTcaButtonRaw(&pressed)) {
|
||||
driver_ctx_.stable_level = pressed ? kKeyPressed : kKeyReleased;
|
||||
}
|
||||
driver_ctx_.same_count = 0;
|
||||
driver_ctx_.read_fail_count = 0;
|
||||
|
||||
const button_config_t button_config = {
|
||||
.long_press_time = board_config::kButtonLongPressMs,
|
||||
.short_press_time = board_config::kButtonShortPressMs,
|
||||
};
|
||||
const esp_err_t result = iot_button_create(&button_config, &driver_ctx_.base, &button_);
|
||||
if (result != ESP_OK) {
|
||||
ESP_LOGE(kTag, "failed to create TCA9555 custom button: %s",esp_err_to_name(result));
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!RegisterCallbacks()) {
|
||||
iot_button_delete(button_);
|
||||
button_ = nullptr;
|
||||
return false;
|
||||
}
|
||||
|
||||
ESP_LOGI(kTag, "power button initialized on TCA9555 P1.0 (bit=%u, active low, debounce=%u samples)",
|
||||
static_cast<unsigned>(TCA_P1_KEY),
|
||||
static_cast<unsigned>(board_config::kButtonDebounceSamples));
|
||||
return true;
|
||||
}//////2026-9-4 ckkj add
|
||||
|
||||
// 边沿事件(iot_button 的按下/松开事件每次物理边沿都会回调一次,
|
||||
// 与组件内部的多击分组无关)——这里只记录时间戳,点击次数自己归组。
|
||||
void ButtonInput::OnPressDown(void*, void* context)
|
||||
{
|
||||
auto* self = static_cast<ButtonInput*>(context);
|
||||
self->press_down_ms_ = pdTICKS_TO_MS(xTaskGetTickCount());
|
||||
}
|
||||
|
||||
void ButtonInput::OnPressUp(void*, void* context)
|
||||
{
|
||||
auto* self = static_cast<ButtonInput*>(context);
|
||||
const uint32_t now_ms = pdTICKS_TO_MS(xTaskGetTickCount());
|
||||
const uint32_t held_ms = now_ms - self->press_down_ms_;
|
||||
|
||||
// 长按由 BUTTON_LONG_PRESS_START 处理,不计入多击分组。
|
||||
// 注意判据是"本次按了多久",与分组窗口无关。
|
||||
if (held_ms >= board_config::kButtonLongPressMs) {
|
||||
ESP_LOGD(kTag, "press released after %lums, treated as long press",
|
||||
static_cast<unsigned long>(held_ms));
|
||||
return;
|
||||
}
|
||||
|
||||
if (self->click_count_ < 0xFFU) {
|
||||
++self->click_count_;
|
||||
}
|
||||
self->last_release_ms_ = now_ms;
|
||||
self->click_group_open_ = true;
|
||||
ESP_LOGD(kTag, "click %u in group (held=%lums)",
|
||||
static_cast<unsigned>(self->click_count_),
|
||||
static_cast<unsigned long>(held_ms));
|
||||
}
|
||||
|
||||
// 松开并保持 kButtonMultiClickWindowMs 之后才发布整组点击次数。
|
||||
// 由 TcaGetKeyLevel 每 5ms 驱动一次,避免额外定时器。
|
||||
void ButtonInput::CloseClickGroupIfIdle(uint8_t stable_level, uint32_t now_ms)
|
||||
{
|
||||
if (!click_group_open_ || stable_level != kKeyReleased) {
|
||||
// 还在按下(或已经发布过)时不收尾:连击间隔再长也会并入同一组
|
||||
return;
|
||||
}
|
||||
if ((now_ms - last_release_ms_) < board_config::kButtonMultiClickWindowMs) {
|
||||
return;
|
||||
}
|
||||
|
||||
click_group_open_ = false;
|
||||
const uint8_t count = click_count_;
|
||||
click_count_ = 0;
|
||||
PublishClick(static_cast<int32_t>(count));
|
||||
}
|
||||
|
||||
void ButtonInput::OnLongPress(void*, void* context)
|
||||
{
|
||||
static_cast<ButtonInput*>(context)->PublishLongPress();
|
||||
}
|
||||
|
||||
void ButtonInput::PublishClick(int32_t count)
|
||||
{
|
||||
static uint64_t last_click_ts = 0;
|
||||
uint32_t now = pdTICKS_TO_MS(xTaskGetTickCount());
|
||||
// 两次click间隔小于120ms,判定为噪声虚假事件,直接丢弃
|
||||
if((now - last_click_ts) < 120U)
|
||||
{
|
||||
ESP_LOGW(kTag,"filter spurious click count=%ld",count);
|
||||
return;
|
||||
}
|
||||
last_click_ts = now;
|
||||
|
||||
ESP_LOGI(kTag, "button clicked count=%ld", static_cast<long>(count));
|
||||
const ButtonAction action =
|
||||
behavior_config_.ResolveButtonAction(
|
||||
static_cast<uint8_t>(count));
|
||||
if (!publisher_.Publish(
|
||||
AppEvent::Make(
|
||||
AppEventType::kButtonClicked,
|
||||
0,
|
||||
count,
|
||||
static_cast<uint32_t>(action)))) {
|
||||
ESP_LOGE(kTag, "failed to publish button click count=%ld",
|
||||
static_cast<long>(count));
|
||||
}
|
||||
}
|
||||
|
||||
void ButtonInput::PublishLongPress()
|
||||
{
|
||||
ESP_LOGI(kTag, "button long-pressed");
|
||||
if (!publisher_.Publish(
|
||||
AppEvent::Make(AppEventType::kButtonLongPressed))) {
|
||||
ESP_LOGE(kTag, "failed to publish long press");
|
||||
}
|
||||
}
|
||||
|
||||
bool ButtonInput::RegisterCallbacks()
|
||||
{
|
||||
// 只注册边沿事件和长按:点击次数由 OnPressUp + CloseClickGroupIfIdle 归组,
|
||||
// 不再使用 iot_button 的 SINGLE/DOUBLE/MULTIPLE_CLICK(其内置分组会把
|
||||
// 按下超过 short_press_time 的那一击当成分组结束并丢弃整组点击)。
|
||||
bool valid = true;
|
||||
valid &= RegisterButtonCallback(
|
||||
button_, BUTTON_PRESS_DOWN, nullptr, &ButtonInput::OnPressDown,
|
||||
this);
|
||||
valid &= RegisterButtonCallback(
|
||||
button_, BUTTON_PRESS_UP, nullptr, &ButtonInput::OnPressUp,
|
||||
this);
|
||||
valid &= RegisterButtonCallback(
|
||||
button_, BUTTON_LONG_PRESS_START, nullptr, &ButtonInput::OnLongPress,
|
||||
this);
|
||||
return valid;
|
||||
}
|
||||
|
||||
} // namespace borla
|
||||
66
main/platform/borla_s3/button_input.h
Normal file
66
main/platform/borla_s3/button_input.h
Normal file
@@ -0,0 +1,66 @@
|
||||
#pragma once
|
||||
|
||||
#include "ports/event_publisher.h"
|
||||
#include "ports/remote_behavior_config.h"
|
||||
#include "platform/borla_s3/tca9555.h"
|
||||
|
||||
#include <button_interface.h>
|
||||
#include <button_types.h>
|
||||
#include <iot_button.h>
|
||||
|
||||
namespace borla {
|
||||
|
||||
class ButtonInput final {
|
||||
public:
|
||||
ButtonInput(
|
||||
IEventPublisher& publisher,
|
||||
//const IRemoteBehaviorConfig& behavior_config);//2026-9-4 ckkj mod
|
||||
const IRemoteBehaviorConfig& behavior_config,TCA9555& tca9555);
|
||||
~ButtonInput();
|
||||
|
||||
bool Initialize();
|
||||
|
||||
private:
|
||||
struct TcaButtonCtx {
|
||||
button_driver_t base{};
|
||||
TCA9555* tca = nullptr;
|
||||
ButtonInput* owner = nullptr; // 用于在轮询回调里收尾多击分组
|
||||
// KEY(P1.0) 去抖状态:get_key_level 由 iot_button 定时器每 5ms 调一次,
|
||||
// 只有连续 kButtonDebounceSamples 次读到同一电平才认可电平变化。
|
||||
uint8_t stable_level = 0; // 去抖后的电平:1=按下,0=松开
|
||||
uint16_t same_count = 0; // 与 stable_level 不同的连续采样次数
|
||||
uint32_t read_fail_count = 0; // 连续 I2C 读失败次数
|
||||
uint32_t press_start_ms = 0; // 本次按下(去抖确认后)的时间戳
|
||||
uint32_t last_press_ms = 0; // 最近一次按下的持续时间,用于诊断
|
||||
};
|
||||
static uint8_t TcaGetKeyLevel(button_driver_t* driver);
|
||||
static esp_err_t TcaDelDriver(button_driver_t* driver);
|
||||
bool ReadTcaButtonRaw(bool* pressed);
|
||||
bool WaitTcaButtonReleased(uint32_t timeout_ms);
|
||||
|
||||
TcaButtonCtx driver_ctx_{};//2026-9-4 ckkj add
|
||||
|
||||
// 多击分组:iot_button 的内置分组会把"按下超过 short_press_time 的那一击"
|
||||
// 当成分组结束并丢弃整组点击(四击因此被拆成多次单击),所以这里只使用
|
||||
// 组件的边沿事件(按下/松开/长按),点击数由自己按"松开→按下"间隔归组。
|
||||
static void OnPressDown(void* handle, void* context);
|
||||
static void OnPressUp(void* handle, void* context);
|
||||
static void OnLongPress(void* handle, void* context);
|
||||
// 松开且超过分组窗口后,发布当前分组的点击次数(由 get_key_level 每 5ms 驱动)
|
||||
void CloseClickGroupIfIdle(uint8_t stable_level, uint32_t now_ms);
|
||||
|
||||
void PublishClick(int32_t count);
|
||||
void PublishLongPress();
|
||||
bool RegisterCallbacks();
|
||||
|
||||
IEventPublisher& publisher_;
|
||||
const IRemoteBehaviorConfig& behavior_config_;
|
||||
TCA9555& tca9555_;
|
||||
button_handle_t button_ = nullptr;
|
||||
uint32_t press_down_ms_ = 0; // 最近一次按下的时间戳
|
||||
uint32_t last_release_ms_ = 0; // 最近一次松开的时间戳(分组窗口起点)
|
||||
uint8_t click_count_ = 0; // 当前分组内累计的点击数
|
||||
bool click_group_open_ = false; // 是否还有未发布的多击分组
|
||||
};
|
||||
|
||||
} // namespace borla
|
||||
81
main/platform/borla_s3/capacitive_touch_input.cc
Normal file
81
main/platform/borla_s3/capacitive_touch_input.cc
Normal file
@@ -0,0 +1,81 @@
|
||||
#include "platform/borla_s3/capacitive_touch_input.h"
|
||||
|
||||
#include <array>
|
||||
|
||||
#include <driver/touch_sensor.h>
|
||||
#include <esp_err.h>
|
||||
#include <esp_log.h>
|
||||
|
||||
namespace borla {
|
||||
namespace {
|
||||
|
||||
constexpr const char* kTag = "BorlaTouch2";
|
||||
// constexpr std::array<touch_pad_t, kTouchZoneCount> kTouchPads{{
|
||||
// TOUCH_PAD_NUM3,
|
||||
// TOUCH_PAD_NUM9,
|
||||
// TOUCH_PAD_NUM13,
|
||||
// TOUCH_PAD_NUM7,
|
||||
// TOUCH_PAD_NUM8,
|
||||
// }};//2026-9-4 ckkj mod
|
||||
|
||||
} // namespace
|
||||
|
||||
CapacitiveTouchInput::~CapacitiveTouchInput()
|
||||
{
|
||||
if (initialized_) {
|
||||
touch_pad_fsm_stop();
|
||||
touch_pad_deinit();
|
||||
}
|
||||
}
|
||||
|
||||
bool CapacitiveTouchInput::Initialize()
|
||||
{
|
||||
if (initialized_) {
|
||||
return true;
|
||||
}
|
||||
esp_err_t result = touch_pad_init();
|
||||
if (result == ESP_OK) {
|
||||
result = touch_pad_set_fsm_mode(TOUCH_FSM_MODE_TIMER);
|
||||
}
|
||||
if (result == ESP_OK) {
|
||||
result = touch_pad_set_voltage(
|
||||
TOUCH_HVOLT_2V7,
|
||||
TOUCH_LVOLT_0V5,
|
||||
TOUCH_HVOLT_ATTEN_1V);
|
||||
}
|
||||
for (touch_pad_t pad : kTouchPads) {
|
||||
if (result == ESP_OK) {
|
||||
result = touch_pad_config(pad);
|
||||
}
|
||||
}
|
||||
if (result == ESP_OK) {
|
||||
result = touch_pad_fsm_start();
|
||||
}
|
||||
if (result != ESP_OK) {
|
||||
ESP_LOGE(kTag, "initialization failed: %s",
|
||||
esp_err_to_name(result));
|
||||
//touch_pad_deinit();
|
||||
return false;
|
||||
}
|
||||
initialized_ = true;
|
||||
ESP_LOGI(kTag, "three touch channels initialized");
|
||||
return true;
|
||||
}
|
||||
|
||||
bool CapacitiveTouchInput::Read(size_t channel, uint32_t* raw)
|
||||
{
|
||||
if (!initialized_ || raw == nullptr ||
|
||||
channel >= kTouchPads.size()) {
|
||||
return false;
|
||||
}
|
||||
const esp_err_t result =touch_pad_read_raw_data(kTouchPads[channel], raw);
|
||||
if (result != ESP_OK) {
|
||||
ESP_LOGW(kTag, "read failed channel=%u: %s",
|
||||
static_cast<unsigned int>(channel),
|
||||
esp_err_to_name(result));
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
} // namespace borla
|
||||
28
main/platform/borla_s3/capacitive_touch_input.h
Normal file
28
main/platform/borla_s3/capacitive_touch_input.h
Normal file
@@ -0,0 +1,28 @@
|
||||
#pragma once
|
||||
|
||||
#include "sensor/sensor_types.h"
|
||||
#include <array>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <driver/touch_sensor.h>
|
||||
namespace borla {
|
||||
// 运行时三路触摸区通道;软关机的深睡触摸唤醒也复用同一组通道。
|
||||
inline constexpr std::array<touch_pad_t, kTouchZoneCount>
|
||||
kTouchPads{{
|
||||
TOUCH_PAD_NUM3,
|
||||
TOUCH_PAD_NUM5,
|
||||
TOUCH_PAD_NUM6,
|
||||
}};
|
||||
class CapacitiveTouchInput final {
|
||||
public:
|
||||
CapacitiveTouchInput() = default;
|
||||
~CapacitiveTouchInput();
|
||||
|
||||
bool Initialize();
|
||||
bool Read(size_t channel, uint32_t* raw);
|
||||
|
||||
private:
|
||||
bool initialized_ = false;
|
||||
};
|
||||
|
||||
} // namespace borla
|
||||
573
main/platform/borla_s3/es8311_audio_output.cc
Normal file
573
main/platform/borla_s3/es8311_audio_output.cc
Normal file
@@ -0,0 +1,573 @@
|
||||
#include "platform/borla_s3/es8311_audio_output.h"
|
||||
|
||||
#include "audio/playback_pipeline.h"
|
||||
#include "diagnostics/audio_tap.h"
|
||||
#include "platform/borla_s3/board_config.h"
|
||||
|
||||
#include <driver/gpio.h>
|
||||
#include <esp_err.h>
|
||||
#include <esp_heap_caps.h>
|
||||
#include <esp_timer.h>
|
||||
#include <esp_log.h>
|
||||
#include <nvs.h>
|
||||
#include <cmath>
|
||||
#include <algorithm>
|
||||
|
||||
namespace borla
|
||||
{
|
||||
namespace
|
||||
{
|
||||
|
||||
// constexpr const char* kTag = "Es8311Output2";
|
||||
constexpr const char *kTag = "Es8389Output2";
|
||||
constexpr const char *kVolumeNamespace = "audio";
|
||||
constexpr const char *kVolumeKey = "output_volume";
|
||||
// constexpr uint8_t kEs8311Address = ES8311_CODEC_DEFAULT_ADDR;
|
||||
constexpr uint8_t kEs8389Address = ES8389_CODEC_DEFAULT_ADDR;
|
||||
|
||||
} // namespace
|
||||
|
||||
// Es8311AudioOutput::Es8311AudioOutput(BorlaS3I2cBus& i2c_bus)
|
||||
// : i2c_bus_(i2c_bus)
|
||||
// {
|
||||
// }
|
||||
Es8311AudioOutput::Es8311AudioOutput(BorlaS3I2cBus &i2c_bus, TCA9555 &tca9555)
|
||||
: i2c_bus_(i2c_bus),
|
||||
tca9555_(tca9555) {}
|
||||
Es8311AudioOutput::~Es8311AudioOutput()
|
||||
{
|
||||
Shutdown();
|
||||
if (scaled_buffer_ != nullptr)
|
||||
{
|
||||
heap_caps_free(scaled_buffer_);
|
||||
}
|
||||
}
|
||||
|
||||
bool Es8311AudioOutput::Initialize()
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
if (initialized_)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
if (!i2c_bus_.Initialize() || !InitializeI2s() ||
|
||||
!InitializeCodec())
|
||||
{
|
||||
DestroyCodec();
|
||||
return false;
|
||||
}
|
||||
|
||||
scaled_buffer_samples_ = PlaybackPipeline::kSamplesPerFrame;
|
||||
if (scaled_buffer_ == nullptr)
|
||||
{
|
||||
scaled_buffer_ = static_cast<int16_t *>(heap_caps_calloc(
|
||||
scaled_buffer_samples_ * 2, //
|
||||
sizeof(int16_t),
|
||||
MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT));
|
||||
}
|
||||
if (scaled_buffer_ == nullptr)
|
||||
{
|
||||
ESP_LOGE(kTag, "failed to allocate PSRAM volume buffer");
|
||||
DestroyCodec();
|
||||
return false;
|
||||
}
|
||||
|
||||
// gpio_set_direction(board_config::kAudioPowerAmplifierGpio, GPIO_MODE_OUTPUT);
|
||||
// gpio_set_level(board_config::kAudioPowerAmplifierGpio, 1);
|
||||
tca9555_.set_pin(board_config::kAudioPowerAmplifierGpio);
|
||||
vTaskDelay(pdMS_TO_TICKS(200));
|
||||
uint8_t tca_out1_final = 0;
|
||||
if (tca9555_.read_reg(0x03, &tca_out1_final) == ESP_OK)
|
||||
{
|
||||
ESP_LOGI(kTag, "TCA9555 OUT1 final=0x%02x PA_CTL bit=%d (exp 1)",
|
||||
tca_out1_final, (tca_out1_final >> 7) & 0x01);
|
||||
}
|
||||
else
|
||||
{
|
||||
ESP_LOGE(kTag, "TCA9555 OUT1 final readback FAILED");
|
||||
} // temp debug
|
||||
// Before anything can play, so the boot prompt already comes out at the
|
||||
// level the user last chose rather than at the 70% default.
|
||||
LoadPersistedVolume();
|
||||
initialized_ = true;
|
||||
ESP_LOGI(kTag, "ES8389 output initialized rate=%lu BCLK=%d WS=%d DOUT=%d",
|
||||
//"ES8311 output initialized rate=%lu BCLK=%d WS=%d DOUT=%d",
|
||||
static_cast<unsigned long>(SampleRate()),
|
||||
static_cast<int>(board_config::kAudioI2sBclkGpio),
|
||||
static_cast<int>(board_config::kAudioI2sWordSelectGpio),
|
||||
static_cast<int>(board_config::kAudioI2sDataOutGpio));
|
||||
return true;
|
||||
}
|
||||
|
||||
void Es8311AudioOutput::Shutdown()
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
if (!initialized_ && device_ == nullptr && tx_handle_ == nullptr)
|
||||
{
|
||||
return;
|
||||
}
|
||||
// gpio_set_level(board_config::kAudioPowerAmplifierGpio, 0);
|
||||
tca9555_.clr_pin(board_config::kAudioPowerAmplifierGpio);
|
||||
DestroyCodec();
|
||||
initialized_ = false;
|
||||
}
|
||||
|
||||
bool Es8311AudioOutput::Write(
|
||||
const int16_t *samples,
|
||||
size_t sample_count)
|
||||
{
|
||||
if (samples == nullptr || sample_count == 0)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
if (!initialized_ || device_ == nullptr || sample_count > scaled_buffer_samples_)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
const int32_t gain =static_cast<int32_t>(volume_percent_.load(std::memory_order_relaxed)) *256 / 100;
|
||||
for (size_t index = 0; index < sample_count; ++index)
|
||||
{
|
||||
const int32_t scaled =
|
||||
(static_cast<int32_t>(samples[index]) * gain) >> 8;
|
||||
// scaled_buffer_[index] = static_cast<int16_t>(
|
||||
const int16_t s = static_cast<int16_t>( // 2026-8-28 ckkj debug
|
||||
std::clamp<int32_t>(scaled, -32768, 32767));
|
||||
scaled_buffer_[index * 2] = s; // 2026-8-28 ckkj debug
|
||||
scaled_buffer_[index * 2 + 1] = s; // 2026-8-28 ckkj debug
|
||||
}
|
||||
|
||||
const int result = esp_codec_dev_write(
|
||||
device_,
|
||||
scaled_buffer_,
|
||||
// static_cast<int>(sample_count * sizeof(int16_t)));
|
||||
static_cast<int>(sample_count * 2 * sizeof(int16_t))); // 2026-8-28 ckkj debug
|
||||
if (result != ESP_CODEC_DEV_OK)
|
||||
{
|
||||
ESP_LOGE(kTag, "I2S write failed code=%d", result);
|
||||
return false;
|
||||
}
|
||||
if (AudioTap *tap =
|
||||
audio_tap_.load(std::memory_order_acquire))
|
||||
{
|
||||
// Keep spk.wav on the acoustic timeline: a late write means the DMA
|
||||
// starved and the room heard silence, so record that silence too
|
||||
// (capped so idle stretches between sessions stay cheap).
|
||||
const uint64_t now_us =
|
||||
static_cast<uint64_t>(esp_timer_get_time());
|
||||
const uint64_t frame_us =
|
||||
static_cast<uint64_t>(sample_count) * 1000000ULL /
|
||||
SampleRate();
|
||||
if (last_tap_write_us_ != 0 &&
|
||||
now_us > last_tap_write_us_ + frame_us)
|
||||
{
|
||||
const uint64_t gap_us = std::min<uint64_t>(
|
||||
now_us - last_tap_write_us_ - frame_us,
|
||||
500000ULL);
|
||||
const size_t gap_samples = static_cast<size_t>(
|
||||
gap_us * SampleRate() / 1000000ULL);
|
||||
if (gap_samples > 0)
|
||||
{
|
||||
// tap->PushOutput(nullptr, gap_samples);
|
||||
// stereo 交错样本数 = 每声道样本数 * 2
|
||||
tap->PushOutput(nullptr, gap_samples * 2); // 2026-8-28 ckkj debug
|
||||
}
|
||||
}
|
||||
last_tap_write_us_ = now_us;
|
||||
tap->PushOutput(scaled_buffer_, sample_count);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool Es8311AudioOutput::Read(
|
||||
int16_t *samples,
|
||||
size_t sample_count,
|
||||
uint32_t timeout_ms)
|
||||
{
|
||||
if (!initialized_.load() || rx_handle_ == nullptr ||
|
||||
samples == nullptr || sample_count == 0)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
size_t bytes_read = 0;
|
||||
const esp_err_t result = i2s_channel_read(
|
||||
rx_handle_,
|
||||
samples,
|
||||
sample_count * sizeof(int16_t),
|
||||
&bytes_read,
|
||||
pdMS_TO_TICKS(timeout_ms));
|
||||
if (result == ESP_ERR_TIMEOUT)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
if (result != ESP_OK || bytes_read != sample_count * sizeof(int16_t))
|
||||
{
|
||||
ESP_LOGW(kTag, "I2S read failed result=%s bytes=%u/%u",
|
||||
esp_err_to_name(result),
|
||||
static_cast<unsigned>(bytes_read),
|
||||
static_cast<unsigned>(
|
||||
sample_count * sizeof(int16_t)));
|
||||
return false;
|
||||
}
|
||||
// 2026-9-6 ckkj temp debug
|
||||
static uint32_t diag_frame = 0;
|
||||
//if (diag_frame < 20 || diag_frame % 100 == 0)
|
||||
{
|
||||
const size_t stereo_frames = sample_count / 2;
|
||||
int64_t l_sq = 0;
|
||||
int64_t r_sq = 0;
|
||||
size_t nonzero_l = 0;
|
||||
size_t nonzero_r = 0;
|
||||
for (size_t i = 0; i < stereo_frames; ++i)
|
||||
{
|
||||
const int32_t l = samples[i * 2];
|
||||
const int32_t r = samples[i * 2 + 1];
|
||||
l_sq += static_cast<int64_t>(l) * l;
|
||||
r_sq += static_cast<int64_t>(r) * r;
|
||||
nonzero_l += l != 0 ? 1 : 0;
|
||||
nonzero_r += r != 0 ? 1 : 0;
|
||||
}
|
||||
const uint32_t l_rms = stereo_frames > 0 ? static_cast<uint32_t>(std::sqrt(static_cast<double>(l_sq) / stereo_frames)) : 0;
|
||||
const uint32_t r_rms = stereo_frames > 0 ? static_cast<uint32_t>(std::sqrt(static_cast<double>(r_sq) / stereo_frames)) : 0;
|
||||
if (diag_frame < 20 || diag_frame % 100 == 0
|
||||
|| l_rms > 300 || r_rms > 300)
|
||||
{
|
||||
ESP_LOGW(kTag, "RX diag f=%u nz=%zu/%zu L_rms=%u R_rms=%u",
|
||||
static_cast<unsigned>(diag_frame),
|
||||
static_cast<unsigned>(nonzero_l),
|
||||
static_cast<unsigned>(nonzero_r),
|
||||
static_cast<unsigned>(l_rms),
|
||||
static_cast<unsigned>(r_rms));
|
||||
}
|
||||
}
|
||||
++diag_frame; ////temp debug end
|
||||
if (AudioTap *tap = audio_tap_.load(std::memory_order_acquire))
|
||||
{
|
||||
tap->PushInput(samples, sample_count);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
void Es8311AudioOutput::SetVolume(uint8_t volume_percent)
|
||||
{
|
||||
const uint8_t clamped = std::min<uint8_t>(volume_percent, 100);
|
||||
const uint8_t previous =
|
||||
volume_percent_.exchange(clamped, std::memory_order_relaxed);
|
||||
ESP_LOGI(kTag, "software volume=%u%%",
|
||||
static_cast<unsigned>(clamped));
|
||||
if (previous != clamped)
|
||||
{
|
||||
PersistVolume(clamped);
|
||||
}
|
||||
}
|
||||
|
||||
void Es8311AudioOutput::LoadPersistedVolume()
|
||||
{
|
||||
nvs_handle_t handle = 0;
|
||||
if (nvs_open(kVolumeNamespace, NVS_READONLY, &handle) != ESP_OK)
|
||||
{
|
||||
return;
|
||||
}
|
||||
uint8_t stored = 0;
|
||||
const esp_err_t read = nvs_get_u8(handle, kVolumeKey, &stored);
|
||||
nvs_close(handle);
|
||||
if (read != ESP_OK)
|
||||
{
|
||||
return;
|
||||
}
|
||||
const uint8_t clamped = std::min<uint8_t>(stored, 100);
|
||||
volume_percent_.store(clamped, std::memory_order_relaxed);
|
||||
ESP_LOGI(kTag, "restored volume=%u%%",
|
||||
static_cast<unsigned>(clamped));
|
||||
}
|
||||
|
||||
void Es8311AudioOutput::PersistVolume(uint8_t volume_percent) const
|
||||
{
|
||||
nvs_handle_t handle = 0;
|
||||
esp_err_t result =
|
||||
nvs_open(kVolumeNamespace, NVS_READWRITE, &handle);
|
||||
if (result == ESP_OK)
|
||||
{
|
||||
result = nvs_set_u8(handle, kVolumeKey, volume_percent);
|
||||
}
|
||||
if (result == ESP_OK)
|
||||
{
|
||||
result = nvs_commit(handle);
|
||||
}
|
||||
if (handle != 0)
|
||||
{
|
||||
nvs_close(handle);
|
||||
}
|
||||
if (result != ESP_OK)
|
||||
{
|
||||
// Losing the setting is not worth failing playback over.
|
||||
ESP_LOGW(kTag, "volume persist failed: %s",esp_err_to_name(result));
|
||||
}
|
||||
}
|
||||
|
||||
uint8_t Es8311AudioOutput::VolumePercent() const
|
||||
{
|
||||
return volume_percent_.load(std::memory_order_relaxed);
|
||||
}
|
||||
|
||||
uint32_t Es8311AudioOutput::SampleRate() const
|
||||
{
|
||||
return board_config::kAudioOutputSampleRate;
|
||||
}
|
||||
|
||||
uint32_t Es8311AudioOutput::InputSampleRate() const
|
||||
{
|
||||
return board_config::kAudioInputHardwareSampleRate;
|
||||
}
|
||||
|
||||
bool Es8311AudioOutput::InitializeI2s()
|
||||
{
|
||||
// 6 x 360 frames @ 24 kHz = 90 ms per direction — the previous firmware's
|
||||
// DMA depth in TIME, not in numbers. It ran 6 x 240 at 16 kHz (= 90 ms);
|
||||
// copying "6 x 240" verbatim to a 24 kHz clock silently cut the buffer to
|
||||
// 60 ms. On TX that 60 ms was the playback task's ONLY runway (decode and
|
||||
// write are fused here, there is no decoded-PCM queue like the previous
|
||||
// firmware's 480 ms one), so any scheduling delay past one frame time
|
||||
// underran the DAC and stuttered audibly. On RX the deeper buffer absorbs
|
||||
// capture-loop jitter that previously overflowed and cost microphone
|
||||
// frames. 720 bytes per descriptor stays well under the 4092-byte limit.
|
||||
i2s_chan_config_t channel = {
|
||||
.id = I2S_NUM_0,
|
||||
.role = I2S_ROLE_MASTER,
|
||||
.dma_desc_num = 6,
|
||||
//.dma_frame_num = 360,
|
||||
.dma_frame_num = 720,
|
||||
.auto_clear_after_cb = true,
|
||||
.auto_clear_before_cb = false,
|
||||
.allow_pd = false,
|
||||
.intr_priority = 0,
|
||||
};
|
||||
esp_err_t result =
|
||||
i2s_new_channel(&channel, &tx_handle_, &rx_handle_);
|
||||
if (result != ESP_OK)
|
||||
{
|
||||
ESP_LOGE(kTag, "I2S channel creation failed: %s",
|
||||
esp_err_to_name(result));
|
||||
return false;
|
||||
}
|
||||
|
||||
i2s_std_config_t standard = {
|
||||
.clk_cfg = {
|
||||
.sample_rate_hz = SampleRate(),
|
||||
.clk_src = I2S_CLK_SRC_DEFAULT,
|
||||
.ext_clk_freq_hz = 0,
|
||||
.mclk_multiple = I2S_MCLK_MULTIPLE_256,
|
||||
},
|
||||
.slot_cfg = {
|
||||
.data_bit_width = I2S_DATA_BIT_WIDTH_16BIT,
|
||||
.slot_bit_width = I2S_SLOT_BIT_WIDTH_AUTO,
|
||||
// .slot_mode = I2S_SLOT_MODE_MONO,
|
||||
//.slot_mask = I2S_STD_SLOT_LEFT,//2026-8-28 ckkj debug
|
||||
.slot_mode = I2S_SLOT_MODE_STEREO,
|
||||
.slot_mask = I2S_STD_SLOT_BOTH,
|
||||
.ws_width = I2S_DATA_BIT_WIDTH_16BIT,
|
||||
.ws_pol = false,
|
||||
.bit_shift = true,
|
||||
.left_align = false, // true,
|
||||
.big_endian = false,
|
||||
.bit_order_lsb = false,
|
||||
},
|
||||
.gpio_cfg = {
|
||||
.mclk = board_config::kAudioI2sMclkGpio,
|
||||
.bclk = board_config::kAudioI2sBclkGpio,
|
||||
.ws = board_config::kAudioI2sWordSelectGpio,
|
||||
.dout = board_config::kAudioI2sDataOutGpio,
|
||||
.din = board_config::kAudioI2sDataInGpio,
|
||||
.invert_flags = {
|
||||
.mclk_inv = false,
|
||||
.bclk_inv = false,
|
||||
.ws_inv = false,
|
||||
},
|
||||
},
|
||||
};
|
||||
result = i2s_channel_init_std_mode(tx_handle_, &standard);
|
||||
if (result != ESP_OK)
|
||||
{
|
||||
ESP_LOGE(kTag, "I2S standard mode failed: %s",
|
||||
esp_err_to_name(result));
|
||||
return false;
|
||||
}
|
||||
result = i2s_channel_init_std_mode(rx_handle_, &standard);
|
||||
if (result != ESP_OK)
|
||||
{
|
||||
ESP_LOGE(kTag, "I2S RX standard mode failed: %s",
|
||||
esp_err_to_name(result));
|
||||
return false;
|
||||
}
|
||||
result = i2s_channel_enable(rx_handle_);
|
||||
if (result != ESP_OK)
|
||||
{
|
||||
ESP_LOGE(kTag, "I2S RX enable failed: %s",
|
||||
esp_err_to_name(result));
|
||||
return false;
|
||||
}
|
||||
rx_enabled_ = true;
|
||||
result = i2s_channel_enable(tx_handle_);
|
||||
if (result != ESP_OK)
|
||||
{
|
||||
ESP_LOGE(kTag, "I2S TX enable failed: %s",
|
||||
esp_err_to_name(result));
|
||||
return false;
|
||||
}
|
||||
tx_enabled_ = true;
|
||||
return true;
|
||||
}
|
||||
|
||||
bool Es8311AudioOutput::InitializeCodec()
|
||||
{
|
||||
audio_codec_i2s_cfg_t i2s = {
|
||||
.port = I2S_NUM_0,
|
||||
.rx_handle = rx_handle_,
|
||||
.tx_handle = tx_handle_,
|
||||
};
|
||||
data_interface_ = audio_codec_new_i2s_data(&i2s);
|
||||
|
||||
audio_codec_i2c_cfg_t i2c = {
|
||||
.port = I2C_NUM_0,
|
||||
//.addr = kEs8311Address,
|
||||
.addr = kEs8389Address,
|
||||
.bus_handle = i2c_bus_.Handle(),
|
||||
};
|
||||
control_interface_ = audio_codec_new_i2c_ctrl(&i2c);
|
||||
gpio_interface_ = audio_codec_new_gpio();
|
||||
if (data_interface_ == nullptr || control_interface_ == nullptr ||
|
||||
gpio_interface_ == nullptr)
|
||||
{
|
||||
ESP_LOGE(kTag, "codec transport interface creation failed");
|
||||
return false;
|
||||
}
|
||||
|
||||
// es8311_codec_cfg_t codec = {};
|
||||
es8389_codec_cfg_t codec = {};
|
||||
codec.ctrl_if = control_interface_;
|
||||
codec.gpio_if = gpio_interface_;
|
||||
codec.codec_mode = ESP_CODEC_DEV_WORK_MODE_BOTH;
|
||||
codec.pa_pin = board_config::kAudioPowerAmplifierGpio; // 2026-8-18 ckkj 已改为扩展芯片引脚
|
||||
// codec.pa_pin = -1;//跳过
|
||||
codec.use_mclk = false;
|
||||
codec.hw_gain.pa_voltage = 5.0f;
|
||||
codec.hw_gain.codec_dac_voltage = 3.3f;
|
||||
// codec_interface_ = es8311_codec_new(&codec);
|
||||
codec_interface_ = es8389_codec_new(&codec);
|
||||
|
||||
if (codec_interface_ == nullptr)
|
||||
{
|
||||
ESP_LOGE(kTag, "ES8389 interface creation failed");
|
||||
return false;
|
||||
}
|
||||
|
||||
esp_codec_dev_cfg_t device = {
|
||||
.dev_type = ESP_CODEC_DEV_TYPE_IN_OUT,
|
||||
.codec_if = codec_interface_,
|
||||
.data_if = data_interface_,
|
||||
};
|
||||
device_ = esp_codec_dev_new(&device);
|
||||
if (device_ == nullptr)
|
||||
{
|
||||
ESP_LOGE(kTag, "codec device creation failed");
|
||||
return false;
|
||||
}
|
||||
|
||||
esp_codec_dev_sample_info_t sample = {
|
||||
.bits_per_sample = 16,
|
||||
.channel = 2, // 1,
|
||||
.channel_mask = 0,
|
||||
.sample_rate = SampleRate(),
|
||||
.mclk_multiple = 0,
|
||||
};
|
||||
int result = esp_codec_dev_open(device_, &sample);
|
||||
if (result != ESP_CODEC_DEV_OK)
|
||||
{
|
||||
ESP_LOGE(kTag, "codec open failed code=%d", result);
|
||||
return false;
|
||||
}
|
||||
|
||||
// esp_codec_dev_write_reg(device_, 0xf0, 0x13);
|
||||
result = esp_codec_dev_set_out_vol(device_, 100);
|
||||
if (result != ESP_CODEC_DEV_OK)
|
||||
{
|
||||
ESP_LOGE(kTag, "codec volume initialization failed code=%d", result);
|
||||
return false;
|
||||
}
|
||||
result = esp_codec_dev_set_in_gain(device_, 40.0f);
|
||||
if (result != ESP_CODEC_DEV_OK)
|
||||
{
|
||||
ESP_LOGE(kTag, "codec input gain initialization failed code=%d",
|
||||
result);
|
||||
return false;
|
||||
}
|
||||
|
||||
// int val = 0;
|
||||
// for (int reg = 0; reg <= 0xFF; reg++) // ES8389有效寄存器0~0xFF
|
||||
// {
|
||||
// esp_err_t ret = esp_codec_dev_read_reg(device_, (uint8_t)reg, &val);
|
||||
|
||||
// if (ret == ESP_OK)
|
||||
// {
|
||||
// ESP_LOGI("DUMP", "REG[%02X] = 0x%02X", reg, val);
|
||||
// }
|
||||
// else
|
||||
// {
|
||||
// ESP_LOGW("DUMP", "REG[%02X] read failed ret:%d", reg, ret);
|
||||
// }
|
||||
// }
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
void Es8311AudioOutput::DestroyCodec()
|
||||
{
|
||||
if (device_ != nullptr)
|
||||
{
|
||||
esp_codec_dev_close(device_);
|
||||
esp_codec_dev_delete(device_);
|
||||
device_ = nullptr;
|
||||
}
|
||||
if (codec_interface_ != nullptr)
|
||||
{
|
||||
audio_codec_delete_codec_if(codec_interface_);
|
||||
codec_interface_ = nullptr;
|
||||
}
|
||||
if (control_interface_ != nullptr)
|
||||
{
|
||||
audio_codec_delete_ctrl_if(control_interface_);
|
||||
control_interface_ = nullptr;
|
||||
}
|
||||
if (gpio_interface_ != nullptr)
|
||||
{
|
||||
audio_codec_delete_gpio_if(gpio_interface_);
|
||||
gpio_interface_ = nullptr;
|
||||
}
|
||||
if (data_interface_ != nullptr)
|
||||
{
|
||||
audio_codec_delete_data_if(data_interface_);
|
||||
data_interface_ = nullptr;
|
||||
}
|
||||
if (tx_handle_ != nullptr)
|
||||
{
|
||||
if (tx_enabled_) {
|
||||
i2s_channel_disable(tx_handle_);
|
||||
tx_enabled_ = false;
|
||||
}
|
||||
i2s_del_channel(tx_handle_);
|
||||
tx_handle_ = nullptr;
|
||||
}
|
||||
if (rx_handle_ != nullptr)
|
||||
{
|
||||
if (rx_enabled_) {
|
||||
i2s_channel_disable(rx_handle_);
|
||||
rx_enabled_ = false;
|
||||
}
|
||||
i2s_del_channel(rx_handle_);
|
||||
rx_handle_ = nullptr;
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace borla
|
||||
83
main/platform/borla_s3/es8311_audio_output.h
Normal file
83
main/platform/borla_s3/es8311_audio_output.h
Normal file
@@ -0,0 +1,83 @@
|
||||
#pragma once
|
||||
|
||||
#include "audio/audio_output.h"
|
||||
#include "audio/audio_input.h"
|
||||
#include "platform/borla_s3/i2c_bus.h"
|
||||
#include "tca9555.h"
|
||||
#include <driver/i2s_std.h>
|
||||
#include <esp_codec_dev.h>
|
||||
#include <esp_codec_dev_defaults.h>
|
||||
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <atomic>
|
||||
#include <mutex>
|
||||
|
||||
namespace borla {
|
||||
|
||||
class AudioTap;
|
||||
|
||||
class Es8311AudioOutput final
|
||||
: public IAudioOutput,
|
||||
public IAudioInput {
|
||||
public:
|
||||
//explicit Es8311AudioOutput(BorlaS3I2cBus& i2c_bus);
|
||||
explicit Es8311AudioOutput(BorlaS3I2cBus& i2c_bus, TCA9555& tca9555);
|
||||
~Es8311AudioOutput();
|
||||
|
||||
bool Initialize() override;
|
||||
void Shutdown() override;
|
||||
bool Write(const int16_t* samples, size_t sample_count) override;
|
||||
void SetVolume(uint8_t volume_percent) override;
|
||||
uint8_t VolumePercent() const override;
|
||||
uint32_t SampleRate() const override;
|
||||
bool Read(
|
||||
int16_t* samples,
|
||||
size_t sample_count,
|
||||
uint32_t timeout_ms) override;
|
||||
uint32_t InputSampleRate() const override;
|
||||
// Debug recorder. This is the hardware boundary, so tapping here captures
|
||||
// exactly what the ADC produced and exactly what the DAC received —
|
||||
// prompts, TTS, tones, everything — regardless of which pipeline made it.
|
||||
void SetAudioTap(AudioTap* tap)
|
||||
{
|
||||
audio_tap_.store(tap, std::memory_order_release);
|
||||
}
|
||||
|
||||
private:
|
||||
bool InitializeI2s();
|
||||
bool InitializeCodec();
|
||||
void DestroyCodec();
|
||||
// Volume survives a reboot, as it did in the previous firmware
|
||||
// (audio_codec.cc: Settings("audio").GetInt/SetInt("output_volume")).
|
||||
// Without this every flash or power cycle came back at the 70% default and
|
||||
// startled whoever had turned it down.
|
||||
void LoadPersistedVolume();
|
||||
void PersistVolume(uint8_t volume_percent) const;
|
||||
|
||||
BorlaS3I2cBus& i2c_bus_;
|
||||
TCA9555& tca9555_;
|
||||
mutable std::mutex mutex_;
|
||||
i2s_chan_handle_t tx_handle_ = nullptr;
|
||||
i2s_chan_handle_t rx_handle_ = nullptr;
|
||||
bool tx_enabled_ = false;//////
|
||||
bool rx_enabled_ = false;/////
|
||||
const audio_codec_data_if_t* data_interface_ = nullptr;
|
||||
const audio_codec_ctrl_if_t* control_interface_ = nullptr;
|
||||
const audio_codec_if_t* codec_interface_ = nullptr;
|
||||
const audio_codec_gpio_if_t* gpio_interface_ = nullptr;
|
||||
esp_codec_dev_handle_t device_ = nullptr;
|
||||
int16_t* scaled_buffer_ = nullptr;
|
||||
size_t scaled_buffer_samples_ = 0;
|
||||
// Lock-free on purpose. VolumePercent() is read on the playback hot path
|
||||
// (once per 60 ms frame) and by the periodic status frame on the esp_timer
|
||||
// task; taking mutex_ there would block behind a full blocking I2S write.
|
||||
std::atomic<uint8_t> volume_percent_{70};
|
||||
std::atomic<bool> initialized_{false};
|
||||
std::atomic<AudioTap*> audio_tap_{nullptr};
|
||||
// Playback-task only (Write holds mutex_): timestamp of the previous
|
||||
// tap-recorded write, used to insert gap silence into spk.wav.
|
||||
uint64_t last_tap_write_us_ = 0;
|
||||
};
|
||||
|
||||
} // namespace borla
|
||||
747
main/platform/borla_s3/esp_websocket_transport.cc
Normal file
747
main/platform/borla_s3/esp_websocket_transport.cc
Normal file
@@ -0,0 +1,747 @@
|
||||
#include "platform/borla_s3/esp_websocket_transport.h"
|
||||
|
||||
#include "connectivity/wifi_types.h"
|
||||
#include "diagnostics/trace_context.h"
|
||||
#include "protocol/websocket_uri.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <new>
|
||||
|
||||
#include <sys/time.h>
|
||||
|
||||
#include <esp_crt_bundle.h>
|
||||
#include <esp_heap_caps.h>
|
||||
#include <esp_log.h>
|
||||
#include <esp_timer.h>
|
||||
#include <esp_transport_ssl.h>
|
||||
#include <esp_transport_tcp.h>
|
||||
#include <esp_transport_ws.h>
|
||||
|
||||
namespace borla {
|
||||
namespace {
|
||||
|
||||
constexpr const char* kTag = "EspWebsocket2";
|
||||
|
||||
// Wall-clock milliseconds, or 0 while the clock still reads 1970 because NTP
|
||||
// has not landed. Callers omit the header in that case rather than reporting a
|
||||
// skew of half a century.
|
||||
int64_t EpochMs()
|
||||
{
|
||||
struct timeval now {};
|
||||
if (gettimeofday(&now, nullptr) != 0 ||
|
||||
now.tv_sec < 1700000000) {
|
||||
return 0;
|
||||
}
|
||||
return static_cast<int64_t>(now.tv_sec) * 1000 +
|
||||
now.tv_usec / 1000;
|
||||
}
|
||||
constexpr int kReadTimeoutMs = 25;
|
||||
constexpr int kWriteTimeoutMs = 2000;
|
||||
constexpr uint32_t kCloseDrainTimeoutMs = 750;
|
||||
constexpr int kRxOverflowError = -3201;
|
||||
constexpr int kConnectError = -3202;
|
||||
constexpr int kReadError = -3203;
|
||||
constexpr int kWriteError = -3204;
|
||||
|
||||
} // namespace
|
||||
|
||||
EspWebsocketTransport::~EspWebsocketTransport()
|
||||
{
|
||||
connected_.store(false);
|
||||
CleanupHandles();
|
||||
if (rx_message_ != nullptr) {
|
||||
heap_caps_free(rx_message_);
|
||||
rx_message_ = nullptr;
|
||||
}
|
||||
if (rx_chunk_ != nullptr) {
|
||||
heap_caps_free(rx_chunk_);
|
||||
rx_chunk_ = nullptr;
|
||||
}
|
||||
if (command_pool_ != nullptr) {
|
||||
heap_caps_free(command_pool_);
|
||||
command_pool_ = nullptr;
|
||||
telemetry_pool_ = nullptr;
|
||||
}
|
||||
}
|
||||
|
||||
bool EspWebsocketTransport::Initialize()
|
||||
{
|
||||
if (initialized_) {
|
||||
return true;
|
||||
}
|
||||
|
||||
rx_message_ = static_cast<uint8_t*>(heap_caps_malloc(
|
||||
kMaxRxMessage,
|
||||
MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT));
|
||||
rx_chunk_ = static_cast<char*>(heap_caps_malloc(
|
||||
kReadChunkSize,
|
||||
MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT));
|
||||
command_pool_ = static_cast<Command*>(heap_caps_calloc(
|
||||
kCommandQueueDepth + kTelemetrySlotCount,
|
||||
sizeof(Command),
|
||||
MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT));
|
||||
if (rx_message_ == nullptr || rx_chunk_ == nullptr ||
|
||||
command_pool_ == nullptr) {
|
||||
ESP_LOGE(kTag,
|
||||
"PSRAM allocation failed rx=%p chunk=%p commands=%p",
|
||||
rx_message_,
|
||||
rx_chunk_,
|
||||
command_pool_);
|
||||
return false;
|
||||
}
|
||||
for (size_t index = 0;
|
||||
index < kCommandQueueDepth + kTelemetrySlotCount;
|
||||
++index) {
|
||||
new (&command_pool_[index]) Command();
|
||||
}
|
||||
telemetry_pool_ = command_pool_ + kCommandQueueDepth;
|
||||
|
||||
free_commands_ = xQueueCreateStatic(
|
||||
kCommandQueueDepth,
|
||||
sizeof(uint16_t),
|
||||
free_commands_storage_.data(),
|
||||
&free_commands_control_);
|
||||
command_queue_ = xQueueCreateStatic(
|
||||
kCommandQueueDepth,
|
||||
sizeof(uint16_t),
|
||||
command_queue_storage_.data(),
|
||||
&command_queue_control_);
|
||||
close_completed_ = xSemaphoreCreateBinaryStatic(
|
||||
&close_completed_storage_);
|
||||
if (free_commands_ == nullptr || command_queue_ == nullptr ||
|
||||
close_completed_ == nullptr) {
|
||||
ESP_LOGE(kTag, "command index queue creation failed");
|
||||
return false;
|
||||
}
|
||||
for (uint16_t index = 0; index < kCommandQueueDepth; ++index) {
|
||||
if (xQueueSend(free_commands_, &index, 0) != pdTRUE) {
|
||||
ESP_LOGE(kTag, "failed to seed command slot=%u", index);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
task_ = xTaskCreateStatic(
|
||||
&EspWebsocketTransport::TaskEntry,
|
||||
"websocket2",
|
||||
task_stack_budget::kWebsocketTransportBytes,
|
||||
this,
|
||||
4,
|
||||
task_stack_.data(),
|
||||
&task_control_);
|
||||
if (task_ == nullptr) {
|
||||
ESP_LOGE(kTag, "transport task creation failed");
|
||||
return false;
|
||||
}
|
||||
initialized_ = true;
|
||||
ESP_LOGI(kTag,
|
||||
"initialized tx_depth=%u tx_payload=%u rx_message=%u "
|
||||
"command_pool=PSRAM telemetry=latest-wins "
|
||||
"stack_bytes=%u memory=internal",
|
||||
static_cast<unsigned>(kCommandQueueDepth),
|
||||
static_cast<unsigned>(kMaxTxPayload),
|
||||
static_cast<unsigned>(kMaxRxMessage),
|
||||
static_cast<unsigned>(
|
||||
task_stack_budget::kWebsocketTransportBytes));
|
||||
return true;
|
||||
}
|
||||
|
||||
bool EspWebsocketTransport::Open(
|
||||
const WebsocketTransportConfig& config,
|
||||
IWebsocketTransportObserver& observer)
|
||||
{
|
||||
if (!initialized_) {
|
||||
return false;
|
||||
}
|
||||
portENTER_CRITICAL(&state_lock_);
|
||||
config_ = config;
|
||||
observer_ = &observer;
|
||||
portEXIT_CRITICAL(&state_lock_);
|
||||
return PostControl(CommandType::kOpen);
|
||||
}
|
||||
|
||||
void EspWebsocketTransport::Close()
|
||||
{
|
||||
if (!initialized_) {
|
||||
return;
|
||||
}
|
||||
if (xTaskGetCurrentTaskHandle() == task_) {
|
||||
DoClose(true, 0);
|
||||
return;
|
||||
}
|
||||
while (xSemaphoreTake(close_completed_, 0) == pdTRUE) {
|
||||
}
|
||||
if (!PostControl(CommandType::kClose)) {
|
||||
ESP_LOGE(kTag, "close command queue full");
|
||||
return;
|
||||
}
|
||||
if (xSemaphoreTake(
|
||||
close_completed_,
|
||||
pdMS_TO_TICKS(kCloseDrainTimeoutMs)) != pdTRUE) {
|
||||
ESP_LOGW(
|
||||
kTag,
|
||||
"close drain timed out after %lu ms",
|
||||
static_cast<unsigned long>(kCloseDrainTimeoutMs));
|
||||
}
|
||||
}
|
||||
|
||||
bool EspWebsocketTransport::SendText(const char* data, size_t size)
|
||||
{
|
||||
return PostPayload(CommandType::kText, data, size);
|
||||
}
|
||||
|
||||
bool EspWebsocketTransport::SendTelemetryText(
|
||||
const char* data,
|
||||
size_t size)
|
||||
{
|
||||
return PostTelemetry(data, size);
|
||||
}
|
||||
|
||||
bool EspWebsocketTransport::SendBinary(
|
||||
const uint8_t* data,
|
||||
size_t size)
|
||||
{
|
||||
return PostPayload(CommandType::kBinary, data, size);
|
||||
}
|
||||
|
||||
void EspWebsocketTransport::TaskEntry(void* context)
|
||||
{
|
||||
static_cast<EspWebsocketTransport*>(context)->Run();
|
||||
}
|
||||
|
||||
[[noreturn]] void EspWebsocketTransport::Run()
|
||||
{
|
||||
ESP_LOGI(kTag, "transport task started");
|
||||
while (true) {
|
||||
if (!connected_.load()) {
|
||||
uint16_t slot_index = 0;
|
||||
if (xQueueReceive(
|
||||
command_queue_,
|
||||
&slot_index,
|
||||
portMAX_DELAY) == pdTRUE) {
|
||||
if (slot_index >= kCommandQueueDepth) {
|
||||
ESP_LOGE(kTag,
|
||||
"invalid command slot=%u",
|
||||
slot_index);
|
||||
continue;
|
||||
}
|
||||
HandleCommand(command_pool_[slot_index]);
|
||||
ReleaseCommand(slot_index);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
if (connected_notification_pending_) {
|
||||
NotifyConnected();
|
||||
if (!connected_.load()) {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
uint16_t slot_index = 0;
|
||||
for (size_t handled = 0;
|
||||
handled < kCommandsPerRead &&
|
||||
xQueueReceive(
|
||||
command_queue_, &slot_index, 0) == pdTRUE;
|
||||
++handled) {
|
||||
if (slot_index >= kCommandQueueDepth) {
|
||||
ESP_LOGE(kTag,
|
||||
"invalid command slot=%u",
|
||||
slot_index);
|
||||
continue;
|
||||
}
|
||||
HandleCommand(command_pool_[slot_index]);
|
||||
ReleaseCommand(slot_index);
|
||||
if (!connected_.load()) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (connected_.load()) {
|
||||
SendPendingTelemetry();
|
||||
}
|
||||
if (connected_.load()) {
|
||||
ReadOnce();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
bool EspWebsocketTransport::PostControl(CommandType type)
|
||||
{
|
||||
return PostPayload(type, nullptr, 0);
|
||||
}
|
||||
|
||||
bool EspWebsocketTransport::PostPayload(
|
||||
CommandType type,
|
||||
const void* data,
|
||||
size_t size)
|
||||
{
|
||||
const bool control =
|
||||
type == CommandType::kOpen || type == CommandType::kClose;
|
||||
if ((!control && (data == nullptr || size == 0)) ||
|
||||
size > kMaxTxPayload) {
|
||||
ESP_LOGW(kTag, "invalid tx payload type=%u size=%u",
|
||||
static_cast<unsigned>(type),
|
||||
static_cast<unsigned>(size));
|
||||
return false;
|
||||
}
|
||||
if (!initialized_ || free_commands_ == nullptr ||
|
||||
command_queue_ == nullptr || command_pool_ == nullptr) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (type == CommandType::kBinary &&
|
||||
uxQueueMessagesWaiting(free_commands_) <=
|
||||
kControlReserveSlots) {
|
||||
return false;
|
||||
}
|
||||
|
||||
uint16_t slot_index = 0;
|
||||
if (xQueueReceive(free_commands_, &slot_index, 0) != pdTRUE) {
|
||||
ESP_LOGE(kTag, "command pool exhausted type=%u",
|
||||
static_cast<unsigned>(type));
|
||||
return false;
|
||||
}
|
||||
Command& command = command_pool_[slot_index];
|
||||
command.type = type;
|
||||
command.size = static_cast<uint16_t>(size);
|
||||
if (size > 0) {
|
||||
std::memcpy(command.payload.data(), data, size);
|
||||
}
|
||||
if (xQueueSend(command_queue_, &slot_index, 0) != pdTRUE) {
|
||||
ReleaseCommand(slot_index);
|
||||
ESP_LOGE(kTag, "tx command queue full type=%u",
|
||||
static_cast<unsigned>(type));
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool EspWebsocketTransport::PostTelemetry(
|
||||
const void* data,
|
||||
size_t size)
|
||||
{
|
||||
if (!initialized_ || !connected_.load() ||
|
||||
telemetry_pool_ == nullptr || data == nullptr || size == 0 ||
|
||||
size > kMaxTxPayload) {
|
||||
return false;
|
||||
}
|
||||
|
||||
portENTER_CRITICAL(&telemetry_lock_);
|
||||
int8_t slot = telemetry_pending_slot_;
|
||||
if (slot < 0) {
|
||||
slot = telemetry_sending_slot_ == 0 ? 1 : 0;
|
||||
}
|
||||
Command& command = telemetry_pool_[slot];
|
||||
command.type = CommandType::kText;
|
||||
command.size = static_cast<uint16_t>(size);
|
||||
std::memcpy(command.payload.data(), data, size);
|
||||
telemetry_pending_slot_ = slot;
|
||||
portEXIT_CRITICAL(&telemetry_lock_);
|
||||
return true;
|
||||
}
|
||||
|
||||
void EspWebsocketTransport::SendPendingTelemetry()
|
||||
{
|
||||
int8_t slot = -1;
|
||||
portENTER_CRITICAL(&telemetry_lock_);
|
||||
if (telemetry_pending_slot_ >= 0) {
|
||||
slot = telemetry_pending_slot_;
|
||||
telemetry_pending_slot_ = -1;
|
||||
telemetry_sending_slot_ = slot;
|
||||
}
|
||||
portEXIT_CRITICAL(&telemetry_lock_);
|
||||
if (slot < 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const Command& command = telemetry_pool_[slot];
|
||||
const bool sent = SendFrame(
|
||||
command.payload.data(), command.size, false);
|
||||
portENTER_CRITICAL(&telemetry_lock_);
|
||||
telemetry_sending_slot_ = -1;
|
||||
portEXIT_CRITICAL(&telemetry_lock_);
|
||||
if (!sent) {
|
||||
DoClose(true, kWriteError);
|
||||
}
|
||||
}
|
||||
|
||||
void EspWebsocketTransport::ReleaseCommand(uint16_t slot_index)
|
||||
{
|
||||
if (slot_index >= kCommandQueueDepth || free_commands_ == nullptr ||
|
||||
xQueueSend(free_commands_, &slot_index, 0) != pdTRUE) {
|
||||
ESP_LOGE(kTag, "failed to release command slot=%u", slot_index);
|
||||
}
|
||||
}
|
||||
|
||||
void EspWebsocketTransport::HandleCommand(const Command& command)
|
||||
{
|
||||
switch (command.type) {
|
||||
case CommandType::kOpen:
|
||||
if (!connected_.load()) {
|
||||
DoOpen();
|
||||
}
|
||||
return;
|
||||
case CommandType::kClose:
|
||||
DoClose(true, 0);
|
||||
if (close_completed_ != nullptr) {
|
||||
xSemaphoreGive(close_completed_);
|
||||
}
|
||||
return;
|
||||
case CommandType::kText:
|
||||
if (!SendFrame(
|
||||
command.payload.data(),
|
||||
command.size,
|
||||
false)) {
|
||||
DoClose(true, kWriteError);
|
||||
}
|
||||
return;
|
||||
case CommandType::kBinary:
|
||||
if (!SendFrame(
|
||||
command.payload.data(),
|
||||
command.size,
|
||||
true)) {
|
||||
DoClose(true, kWriteError);
|
||||
}
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
void EspWebsocketTransport::DoOpen()
|
||||
{
|
||||
WebsocketTransportConfig config;
|
||||
portENTER_CRITICAL(&state_lock_);
|
||||
config = config_;
|
||||
portEXIT_CRITICAL(&state_lock_);
|
||||
|
||||
WebsocketUri uri;
|
||||
if (!ParseWebsocketUri(config.url.data(), &uri)) {
|
||||
ESP_LOGE(kTag, "invalid WebSocket URL");
|
||||
DoClose(true, kConnectError);
|
||||
return;
|
||||
}
|
||||
|
||||
CleanupHandles();
|
||||
parent_transport_ =
|
||||
uri.secure ? esp_transport_ssl_init() : esp_transport_tcp_init();
|
||||
if (parent_transport_ == nullptr) {
|
||||
DoClose(true, kConnectError);
|
||||
return;
|
||||
}
|
||||
if (uri.secure) {
|
||||
esp_transport_ssl_crt_bundle_attach(
|
||||
parent_transport_, esp_crt_bundle_attach);
|
||||
}
|
||||
|
||||
websocket_transport_ =
|
||||
esp_transport_ws_init(parent_transport_);
|
||||
if (websocket_transport_ == nullptr) {
|
||||
DoClose(true, kConnectError);
|
||||
return;
|
||||
}
|
||||
esp_transport_ws_set_path(websocket_transport_, uri.path.data());
|
||||
|
||||
// The server correlates its own trace with the device's using these
|
||||
// headers (websocket_server.py: X-Borla-Trace-Id / X-Borla-Session-Id) and
|
||||
// derives the device-to-server clock delta from the two timestamps. When
|
||||
// they are absent it mints fresh ids instead, and the two halves of a
|
||||
// session can no longer be joined — which is the state this firmware was
|
||||
// in until now.
|
||||
//
|
||||
// client_epoch_ms is omitted entirely rather than sent as 0 when the wall
|
||||
// clock has not been synced: the handshake often happens before NTP, and a
|
||||
// 1970 timestamp would read as a 56-year skew.
|
||||
const int64_t client_epoch_ms = EpochMs();
|
||||
char epoch_header[64]{};
|
||||
if (client_epoch_ms > 0) {
|
||||
std::snprintf(
|
||||
epoch_header,
|
||||
sizeof(epoch_header),
|
||||
"X-Borla-Client-Epoch-Ms: %lld\r\n",
|
||||
static_cast<long long>(client_epoch_ms));
|
||||
}
|
||||
|
||||
// A connect attempt opens a new exchange, so it gets a fresh trace id —
|
||||
// same lifecycle rule as the session id below. This also covers the very
|
||||
// first connect of a boot, where no subsystem has minted a trace yet and
|
||||
// TraceId() still reads "-": the server's `get_header(...) or
|
||||
// new_trace_id()` treats "-" as a present value and would adopt it
|
||||
// verbatim. ServerHello handling refreshes the trace again afterwards,
|
||||
// which is fine — this one correlates the handshake, that one the first
|
||||
// turn.
|
||||
TraceContext::RefreshTrace("ws");
|
||||
|
||||
char headers[512]{};
|
||||
const int header_size = std::snprintf(
|
||||
headers,
|
||||
sizeof(headers),
|
||||
"Device-Id: %s\r\n"
|
||||
"Protocol-Version: %u\r\n"
|
||||
"Firmware-Version: %s\r\n"
|
||||
"X-Borla-Trace-Id: %s\r\n"
|
||||
"X-Borla-Session-Id: %s\r\n"
|
||||
"X-Request-Id: %s\r\n"
|
||||
"X-Borla-Client-Send-Ms: %llu\r\n"
|
||||
"%s",
|
||||
config.device_id.data(),
|
||||
static_cast<unsigned>(config.protocol_version),
|
||||
config.firmware_version.data(),
|
||||
TraceContext::TraceId(),
|
||||
// Minted per connect attempt, not reused: the session is connection-
|
||||
// scoped and the server adopts whatever it is handed here until its own
|
||||
// ServerHello id replaces it.
|
||||
TraceContext::RefreshSession(),
|
||||
TraceContext::NewRequestId(),
|
||||
static_cast<unsigned long long>(
|
||||
esp_timer_get_time() / 1000),
|
||||
epoch_header);
|
||||
if (header_size <= 0 ||
|
||||
header_size >= static_cast<int>(sizeof(headers)) ||
|
||||
esp_transport_ws_set_headers(
|
||||
websocket_transport_, headers) != ESP_OK) {
|
||||
DoClose(true, kConnectError);
|
||||
return;
|
||||
}
|
||||
|
||||
char authorization[kWebsocketTokenCapacity + 16]{};
|
||||
if (config.token[0] != '\0') {
|
||||
const bool has_scheme =
|
||||
std::strchr(config.token.data(), ' ') != nullptr;
|
||||
const int auth_size = std::snprintf(
|
||||
authorization,
|
||||
sizeof(authorization),
|
||||
has_scheme ? "%s" : "Bearer %s",
|
||||
config.token.data());
|
||||
if (auth_size <= 0 ||
|
||||
auth_size >= static_cast<int>(sizeof(authorization)) ||
|
||||
esp_transport_ws_set_auth(
|
||||
websocket_transport_, authorization) != ESP_OK) {
|
||||
DoClose(true, kConnectError);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
ESP_LOGI(kTag, "connecting secure=%d host=%s port=%u path=%s",
|
||||
uri.secure ? 1 : 0,
|
||||
uri.host.data(),
|
||||
static_cast<unsigned>(uri.port),
|
||||
uri.path.data());
|
||||
const int result = esp_transport_connect(
|
||||
websocket_transport_,
|
||||
uri.host.data(),
|
||||
uri.port,
|
||||
static_cast<int>(config.connect_timeout_ms));
|
||||
if (result != 0) {
|
||||
ESP_LOGE(kTag, "WebSocket upgrade failed result=%d http=%d",
|
||||
result,
|
||||
esp_transport_ws_get_upgrade_request_status(
|
||||
websocket_transport_));
|
||||
DoClose(true, kConnectError);
|
||||
return;
|
||||
}
|
||||
|
||||
rx_message_size_ = 0;
|
||||
frame_bytes_remaining_ = 0;
|
||||
rx_message_started_ = false;
|
||||
rx_overflow_ = false;
|
||||
frame_capture_ = false;
|
||||
connected_.store(true);
|
||||
connected_notification_pending_ = true;
|
||||
ESP_LOGI(kTag, "WebSocket connected");
|
||||
}
|
||||
|
||||
void EspWebsocketTransport::DoClose(bool notify, int error_code)
|
||||
{
|
||||
const bool had_transport =
|
||||
connected_.exchange(false) ||
|
||||
websocket_transport_ != nullptr ||
|
||||
parent_transport_ != nullptr;
|
||||
if (websocket_transport_ != nullptr && error_code == 0) {
|
||||
esp_transport_ws_send_raw(
|
||||
websocket_transport_,
|
||||
static_cast<ws_transport_opcodes_t>(
|
||||
WS_TRANSPORT_OPCODES_CLOSE |
|
||||
WS_TRANSPORT_OPCODES_FIN),
|
||||
nullptr,
|
||||
0,
|
||||
100);
|
||||
}
|
||||
CleanupHandles();
|
||||
connected_notification_pending_ = false;
|
||||
portENTER_CRITICAL(&telemetry_lock_);
|
||||
telemetry_pending_slot_ = -1;
|
||||
telemetry_sending_slot_ = -1;
|
||||
portEXIT_CRITICAL(&telemetry_lock_);
|
||||
rx_message_size_ = 0;
|
||||
frame_bytes_remaining_ = 0;
|
||||
rx_message_started_ = false;
|
||||
rx_overflow_ = false;
|
||||
frame_capture_ = false;
|
||||
|
||||
if (notify && had_transport) {
|
||||
IWebsocketTransportObserver* observer = ObserverSnapshot();
|
||||
if (observer != nullptr) {
|
||||
observer->OnWebsocketDisconnected(error_code);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void EspWebsocketTransport::NotifyConnected()
|
||||
{
|
||||
connected_notification_pending_ = false;
|
||||
IWebsocketTransportObserver* observer = ObserverSnapshot();
|
||||
if (observer != nullptr) {
|
||||
observer->OnWebsocketConnected();
|
||||
}
|
||||
}
|
||||
|
||||
bool EspWebsocketTransport::SendFrame(
|
||||
const void* data,
|
||||
size_t size,
|
||||
bool binary)
|
||||
{
|
||||
if (!connected_.load() || websocket_transport_ == nullptr) {
|
||||
return false;
|
||||
}
|
||||
const auto opcode = static_cast<ws_transport_opcodes_t>(
|
||||
(binary
|
||||
? WS_TRANSPORT_OPCODES_BINARY
|
||||
: WS_TRANSPORT_OPCODES_TEXT) |
|
||||
WS_TRANSPORT_OPCODES_FIN);
|
||||
const int written = esp_transport_ws_send_raw(
|
||||
websocket_transport_,
|
||||
opcode,
|
||||
static_cast<const char*>(data),
|
||||
static_cast<int>(size),
|
||||
kWriteTimeoutMs);
|
||||
return written == static_cast<int>(size);
|
||||
}
|
||||
|
||||
void EspWebsocketTransport::ReadOnce()
|
||||
{
|
||||
if (rx_chunk_ == nullptr) {
|
||||
DoClose(true, kReadError);
|
||||
return;
|
||||
}
|
||||
const int received = esp_transport_read(
|
||||
websocket_transport_,
|
||||
rx_chunk_,
|
||||
static_cast<int>(kReadChunkSize),
|
||||
kReadTimeoutMs);
|
||||
if (received > 0) {
|
||||
HandleReadChunk(rx_chunk_, static_cast<size_t>(received));
|
||||
vTaskDelay(1);
|
||||
} else if (received < 0) {
|
||||
ESP_LOGW(kTag, "WebSocket read failed result=%d", received);
|
||||
DoClose(true, kReadError);
|
||||
}
|
||||
}
|
||||
|
||||
void EspWebsocketTransport::HandleReadChunk(
|
||||
const char* data,
|
||||
size_t size)
|
||||
{
|
||||
if (frame_bytes_remaining_ == 0) {
|
||||
const int payload_size =
|
||||
esp_transport_ws_get_read_payload_len(websocket_transport_);
|
||||
if (payload_size < 0) {
|
||||
DoClose(true, kReadError);
|
||||
return;
|
||||
}
|
||||
frame_bytes_remaining_ = static_cast<size_t>(payload_size);
|
||||
frame_fin_ =
|
||||
esp_transport_ws_get_fin_flag(websocket_transport_);
|
||||
const ws_transport_opcodes_t opcode =
|
||||
esp_transport_ws_get_read_opcode(websocket_transport_);
|
||||
|
||||
if (opcode == WS_TRANSPORT_OPCODES_TEXT ||
|
||||
opcode == WS_TRANSPORT_OPCODES_BINARY) {
|
||||
frame_capture_ = true;
|
||||
if (rx_message_started_) {
|
||||
rx_overflow_ = true;
|
||||
} else {
|
||||
rx_message_started_ = true;
|
||||
rx_message_binary_ =
|
||||
opcode == WS_TRANSPORT_OPCODES_BINARY;
|
||||
rx_message_size_ = 0;
|
||||
}
|
||||
} else if (opcode == WS_TRANSPORT_OPCODES_CONT) {
|
||||
frame_capture_ = rx_message_started_;
|
||||
} else {
|
||||
// Control frame (ping/pong/close). Its payload must still be
|
||||
// consumed here: returning early would leave the remaining byte
|
||||
// counter set and make the next data frame's header be skipped,
|
||||
// splicing control bytes into the application message.
|
||||
frame_capture_ = false;
|
||||
}
|
||||
}
|
||||
|
||||
if (size > frame_bytes_remaining_) {
|
||||
DoClose(true, kReadError);
|
||||
return;
|
||||
}
|
||||
frame_bytes_remaining_ -= size;
|
||||
|
||||
if (!frame_capture_) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!rx_overflow_ &&
|
||||
rx_message_size_ + size <= kMaxRxMessage) {
|
||||
std::memcpy(rx_message_ + rx_message_size_, data, size);
|
||||
rx_message_size_ += size;
|
||||
} else {
|
||||
rx_overflow_ = true;
|
||||
}
|
||||
|
||||
if (frame_bytes_remaining_ == 0 && frame_fin_) {
|
||||
if (rx_overflow_) {
|
||||
ESP_LOGE(kTag, "WebSocket message exceeds %u bytes",
|
||||
static_cast<unsigned>(kMaxRxMessage));
|
||||
DoClose(true, kRxOverflowError);
|
||||
return;
|
||||
}
|
||||
DispatchMessage();
|
||||
rx_message_size_ = 0;
|
||||
rx_message_started_ = false;
|
||||
}
|
||||
}
|
||||
|
||||
void EspWebsocketTransport::DispatchMessage()
|
||||
{
|
||||
IWebsocketTransportObserver* observer = ObserverSnapshot();
|
||||
if (observer == nullptr) {
|
||||
return;
|
||||
}
|
||||
if (rx_message_binary_) {
|
||||
observer->OnWebsocketBinary(rx_message_, rx_message_size_);
|
||||
} else {
|
||||
observer->OnWebsocketText(
|
||||
reinterpret_cast<const char*>(rx_message_),
|
||||
rx_message_size_);
|
||||
}
|
||||
}
|
||||
|
||||
void EspWebsocketTransport::CleanupHandles()
|
||||
{
|
||||
if (websocket_transport_ != nullptr) {
|
||||
esp_transport_close(websocket_transport_);
|
||||
esp_transport_destroy(websocket_transport_);
|
||||
websocket_transport_ = nullptr;
|
||||
}
|
||||
if (parent_transport_ != nullptr) {
|
||||
esp_transport_destroy(parent_transport_);
|
||||
parent_transport_ = nullptr;
|
||||
}
|
||||
}
|
||||
|
||||
IWebsocketTransportObserver*
|
||||
EspWebsocketTransport::ObserverSnapshot() const
|
||||
{
|
||||
portENTER_CRITICAL(&state_lock_);
|
||||
IWebsocketTransportObserver* const observer = observer_;
|
||||
portEXIT_CRITICAL(&state_lock_);
|
||||
return observer;
|
||||
}
|
||||
|
||||
} // namespace borla
|
||||
131
main/platform/borla_s3/esp_websocket_transport.h
Normal file
131
main/platform/borla_s3/esp_websocket_transport.h
Normal file
@@ -0,0 +1,131 @@
|
||||
#pragma once
|
||||
|
||||
#include "core/task_stack_budget.h"
|
||||
#include "protocol/websocket_transport.h"
|
||||
#include "protocol/binary_audio_protocol.h"
|
||||
|
||||
#include <array>
|
||||
#include <atomic>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
|
||||
#include <esp_transport.h>
|
||||
#include <freertos/FreeRTOS.h>
|
||||
#include <freertos/portmacro.h>
|
||||
#include <freertos/queue.h>
|
||||
#include <freertos/semphr.h>
|
||||
#include <freertos/task.h>
|
||||
|
||||
namespace borla {
|
||||
|
||||
class EspWebsocketTransport final : public IWebsocketTransport {
|
||||
public:
|
||||
~EspWebsocketTransport();
|
||||
|
||||
bool Initialize() override;
|
||||
bool Open(
|
||||
const WebsocketTransportConfig& config,
|
||||
IWebsocketTransportObserver& observer) override;
|
||||
void Close() override;
|
||||
bool SendText(const char* data, size_t size) override;
|
||||
bool SendTelemetryText(
|
||||
const char* data,
|
||||
size_t size) override;
|
||||
bool SendBinary(const uint8_t* data, size_t size) override;
|
||||
bool IsConnected() const override { return connected_.load(); }
|
||||
|
||||
private:
|
||||
enum class CommandType : uint8_t {
|
||||
kOpen,
|
||||
kClose,
|
||||
kText,
|
||||
kBinary,
|
||||
};
|
||||
|
||||
static constexpr size_t kMaxTxPayload =
|
||||
kBinaryAudioMaximumPacketBytes;
|
||||
static constexpr size_t kMaxRxMessage = 8192;
|
||||
static constexpr size_t kReadChunkSize = 2048;
|
||||
static constexpr size_t kCommandQueueDepth = 10;
|
||||
static constexpr size_t kTelemetrySlotCount = 2;
|
||||
static constexpr size_t kControlReserveSlots = 2;
|
||||
static constexpr size_t kCommandsPerRead = 2;
|
||||
|
||||
struct Command {
|
||||
CommandType type = CommandType::kOpen;
|
||||
uint16_t size = 0;
|
||||
std::array<uint8_t, kMaxTxPayload> payload{};
|
||||
};
|
||||
|
||||
static void TaskEntry(void* context);
|
||||
[[noreturn]] void Run();
|
||||
bool PostControl(CommandType type);
|
||||
bool PostPayload(
|
||||
CommandType type,
|
||||
const void* data,
|
||||
size_t size);
|
||||
bool PostTelemetry(const void* data, size_t size);
|
||||
void SendPendingTelemetry();
|
||||
void ReleaseCommand(uint16_t slot_index);
|
||||
void HandleCommand(const Command& command);
|
||||
void DoOpen();
|
||||
void DoClose(bool notify, int error_code);
|
||||
void NotifyConnected();
|
||||
bool SendFrame(
|
||||
const void* data,
|
||||
size_t size,
|
||||
bool binary);
|
||||
void ReadOnce();
|
||||
void HandleReadChunk(const char* data, size_t size);
|
||||
void DispatchMessage();
|
||||
void CleanupHandles();
|
||||
IWebsocketTransportObserver* ObserverSnapshot() const;
|
||||
|
||||
mutable portMUX_TYPE state_lock_ = portMUX_INITIALIZER_UNLOCKED;
|
||||
WebsocketTransportConfig config_{};
|
||||
IWebsocketTransportObserver* observer_ = nullptr;
|
||||
|
||||
Command* command_pool_ = nullptr;
|
||||
Command* telemetry_pool_ = nullptr;
|
||||
QueueHandle_t free_commands_ = nullptr;
|
||||
QueueHandle_t command_queue_ = nullptr;
|
||||
StaticQueue_t free_commands_control_{};
|
||||
StaticQueue_t command_queue_control_{};
|
||||
SemaphoreHandle_t close_completed_ = nullptr;
|
||||
StaticSemaphore_t close_completed_storage_{};
|
||||
alignas(uint16_t)
|
||||
std::array<uint8_t, kCommandQueueDepth * sizeof(uint16_t)>
|
||||
free_commands_storage_{};
|
||||
alignas(uint16_t)
|
||||
std::array<uint8_t, kCommandQueueDepth * sizeof(uint16_t)>
|
||||
command_queue_storage_{};
|
||||
TaskHandle_t task_ = nullptr;
|
||||
StaticTask_t task_control_{};
|
||||
std::array<
|
||||
StackType_t,
|
||||
task_stack_budget::kWebsocketTransportBytes / sizeof(StackType_t)>
|
||||
task_stack_{};
|
||||
|
||||
bool initialized_ = false;
|
||||
std::atomic<bool> connected_{false};
|
||||
bool connected_notification_pending_ = false;
|
||||
portMUX_TYPE telemetry_lock_ = portMUX_INITIALIZER_UNLOCKED;
|
||||
int8_t telemetry_pending_slot_ = -1;
|
||||
int8_t telemetry_sending_slot_ = -1;
|
||||
|
||||
esp_transport_handle_t parent_transport_ = nullptr;
|
||||
esp_transport_handle_t websocket_transport_ = nullptr;
|
||||
uint8_t* rx_message_ = nullptr;
|
||||
// Read scratch lives in PSRAM instead of on the transport task stack: the
|
||||
// same stack frame also carries the ServerHello parser and the TLS write.
|
||||
char* rx_chunk_ = nullptr;
|
||||
size_t rx_message_size_ = 0;
|
||||
size_t frame_bytes_remaining_ = 0;
|
||||
bool rx_message_binary_ = false;
|
||||
bool rx_message_started_ = false;
|
||||
bool rx_overflow_ = false;
|
||||
bool frame_fin_ = false;
|
||||
bool frame_capture_ = false;
|
||||
};
|
||||
|
||||
} // namespace borla
|
||||
502
main/platform/borla_s3/esp_wifi_transport.cc
Normal file
502
main/platform/borla_s3/esp_wifi_transport.cc
Normal file
@@ -0,0 +1,502 @@
|
||||
#include "platform/borla_s3/esp_wifi_transport.h"
|
||||
|
||||
#include "core/psram_object.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cstring>
|
||||
|
||||
#include <esp_err.h>
|
||||
#include <esp_heap_caps.h>
|
||||
#include <esp_log.h>
|
||||
#include <esp_wifi.h>
|
||||
#include <freertos/FreeRTOS.h>
|
||||
#include <freertos/task.h>
|
||||
namespace borla {
|
||||
namespace {
|
||||
|
||||
constexpr const char* kTag = "EspWifiTransport2";
|
||||
constexpr size_t kMaximumScanRecords = 32;
|
||||
|
||||
using ScanRecords = std::array<wifi_ap_record_t, kMaximumScanRecords>;
|
||||
|
||||
// Guard rail: this buffer overflowed the 4 KB provisioning stack once already.
|
||||
// It now lives in PSRAM, so the only way it can come back is if someone makes
|
||||
// it a stack local again — keep the size visible and bounded.
|
||||
static_assert(
|
||||
sizeof(ScanRecords) > 1024,
|
||||
"scan record buffer is large; it must stay off the task stack");
|
||||
|
||||
bool IsBenignStopResult(esp_err_t result)
|
||||
{
|
||||
return result == ESP_OK ||
|
||||
result == ESP_ERR_WIFI_NOT_INIT ||
|
||||
result == ESP_ERR_WIFI_NOT_STARTED ||
|
||||
result == ESP_ERR_WIFI_NOT_CONNECT ||
|
||||
result == ESP_ERR_INVALID_STATE;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
bool EspWifiTransport::Start(IWifiTransportObserver& observer)
|
||||
{
|
||||
portENTER_CRITICAL(&link_lock_);
|
||||
observer_ = &observer;
|
||||
portEXIT_CRITICAL(&link_lock_);
|
||||
if (started_) {
|
||||
Publish({WifiTransportEventType::kStarted, 0});
|
||||
return true;
|
||||
}
|
||||
|
||||
if (!InitializeDriver() || !RegisterHandlers()) {
|
||||
portENTER_CRITICAL(&link_lock_);
|
||||
observer_ = nullptr;
|
||||
portEXIT_CRITICAL(&link_lock_);
|
||||
return false;
|
||||
}
|
||||
|
||||
const esp_err_t result = esp_wifi_start();
|
||||
if (result != ESP_OK) {
|
||||
ESP_LOGE(kTag, "esp_wifi_start failed: %s",
|
||||
esp_err_to_name(result));
|
||||
UnregisterHandlers();
|
||||
portENTER_CRITICAL(&link_lock_);
|
||||
observer_ = nullptr;
|
||||
portEXIT_CRITICAL(&link_lock_);
|
||||
return false;
|
||||
}
|
||||
started_ = true;
|
||||
ESP_LOGI(kTag, "WiFi STA transport started");
|
||||
return true;
|
||||
}
|
||||
|
||||
void EspWifiTransport::Stop()
|
||||
{
|
||||
portENTER_CRITICAL(&link_lock_);
|
||||
observer_ = nullptr;
|
||||
portEXIT_CRITICAL(&link_lock_);
|
||||
if (started_) {
|
||||
const esp_err_t disconnect_result = esp_wifi_disconnect();
|
||||
if (!IsBenignStopResult(disconnect_result)) {
|
||||
ESP_LOGW(kTag, "esp_wifi_disconnect failed: %s",
|
||||
esp_err_to_name(disconnect_result));
|
||||
}
|
||||
|
||||
const esp_err_t stop_result = esp_wifi_stop();
|
||||
if (!IsBenignStopResult(stop_result)) {
|
||||
ESP_LOGW(kTag, "esp_wifi_stop failed: %s",
|
||||
esp_err_to_name(stop_result));
|
||||
}
|
||||
started_ = false;
|
||||
}
|
||||
UnregisterHandlers();
|
||||
ClearLinkState(0);
|
||||
ESP_LOGI(kTag, "WiFi STA transport stopped");
|
||||
}
|
||||
|
||||
void EspWifiTransport::UseLowMemoryProfile(bool enabled)
|
||||
{
|
||||
low_memory_profile_ = enabled;
|
||||
}
|
||||
|
||||
void EspWifiTransport::ReleaseDriver()
|
||||
{
|
||||
if (!driver_initialized_) {
|
||||
return;
|
||||
}
|
||||
if (started_) {
|
||||
Stop();
|
||||
}
|
||||
const size_t before =
|
||||
heap_caps_get_free_size(MALLOC_CAP_INTERNAL);
|
||||
const esp_err_t result = esp_wifi_deinit();
|
||||
if (!IsBenignStopResult(result)) {
|
||||
ESP_LOGW(kTag, "esp_wifi_deinit failed: %s",
|
||||
esp_err_to_name(result));
|
||||
return;
|
||||
}
|
||||
// The netif is deliberately kept: esp_netif_create_default_wifi_sta() is
|
||||
// not idempotent, and InitializeDriver() reuses the existing handle.
|
||||
driver_initialized_ = false;
|
||||
const size_t after =
|
||||
heap_caps_get_free_size(MALLOC_CAP_INTERNAL);
|
||||
ESP_LOGI(kTag,
|
||||
"WiFi driver released internal_free=%u (+%d) largest=%u",
|
||||
static_cast<unsigned>(after),
|
||||
static_cast<int>(after) - static_cast<int>(before),
|
||||
static_cast<unsigned>(
|
||||
heap_caps_get_largest_free_block(MALLOC_CAP_INTERNAL)));
|
||||
}
|
||||
|
||||
bool EspWifiTransport::Connect(const WifiCredential& credential)
|
||||
{
|
||||
if (!started_ || !credential.IsValid()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
wifi_config_t config{};
|
||||
const size_t ssid_length =
|
||||
BoundedStringLength(credential.ssid.data(), credential.ssid.size());
|
||||
const size_t password_length =
|
||||
BoundedStringLength(
|
||||
credential.password.data(), credential.password.size());
|
||||
std::memcpy(
|
||||
config.sta.ssid,
|
||||
credential.ssid.data(),
|
||||
std::min(ssid_length, sizeof(config.sta.ssid)));
|
||||
std::memcpy(
|
||||
config.sta.password,
|
||||
credential.password.data(),
|
||||
std::min(password_length, sizeof(config.sta.password)));
|
||||
config.sta.threshold.authmode = password_length == 0
|
||||
? WIFI_AUTH_OPEN
|
||||
: WIFI_AUTH_WPA2_PSK;
|
||||
config.sta.pmf_cfg.capable = true;
|
||||
config.sta.pmf_cfg.required = false;
|
||||
|
||||
esp_err_t result = esp_wifi_set_config(WIFI_IF_STA, &config);
|
||||
if (result != ESP_OK) {
|
||||
ESP_LOGE(kTag, "set config for ssid=%s failed: %s",
|
||||
credential.ssid.data(), esp_err_to_name(result));
|
||||
return false;
|
||||
}
|
||||
|
||||
portENTER_CRITICAL(&link_lock_);
|
||||
link_info_.online = false;
|
||||
link_info_.rssi_dbm = -127;
|
||||
link_info_.channel = 0;
|
||||
link_info_.ipv4.fill('\0');
|
||||
link_info_.ssid = credential.ssid;
|
||||
portEXIT_CRITICAL(&link_lock_);
|
||||
|
||||
result = esp_wifi_connect();
|
||||
if (result != ESP_OK) {
|
||||
ESP_LOGW(kTag, "connect request for ssid=%s failed: %s",
|
||||
credential.ssid.data(), esp_err_to_name(result));
|
||||
return false;
|
||||
}
|
||||
ESP_LOGI(kTag, "connecting to ssid=%s", credential.ssid.data());
|
||||
return true;
|
||||
}
|
||||
|
||||
bool EspWifiTransport::Scan(
|
||||
WifiNetwork* output,
|
||||
size_t capacity,
|
||||
size_t* count)
|
||||
{
|
||||
if (!started_ || output == nullptr || capacity == 0 ||
|
||||
count == nullptr) {
|
||||
return false;
|
||||
}
|
||||
*count = 0;
|
||||
|
||||
wifi_scan_config_t config{};
|
||||
config.scan_type = WIFI_SCAN_TYPE_ACTIVE;
|
||||
config.scan_time.active.min = 80;
|
||||
config.scan_time.active.max = 160;
|
||||
esp_err_t result = esp_wifi_scan_start(&config, true);
|
||||
if (result != ESP_OK) {
|
||||
ESP_LOGE(kTag, "WiFi scan failed: %s",
|
||||
esp_err_to_name(result));
|
||||
return false;
|
||||
}
|
||||
|
||||
// wifi_ap_record_t is ~96 bytes, so 32 of them is ~3 KB. The only caller
|
||||
// is the BLE provisioning worker, whose stack also has to carry
|
||||
// esp_wifi_scan_start and nimble_port_init underneath this frame — the
|
||||
// array must not live on it.
|
||||
auto records = MakePsramObject<ScanRecords>();
|
||||
if (!records) {
|
||||
ESP_LOGE(kTag, "scan record buffer allocation failed");
|
||||
return false;
|
||||
}
|
||||
uint16_t record_count =
|
||||
static_cast<uint16_t>(records->size());
|
||||
result = esp_wifi_scan_get_ap_records(
|
||||
&record_count, records->data());
|
||||
if (result != ESP_OK) {
|
||||
ESP_LOGE(kTag, "read WiFi scan results failed: %s",
|
||||
esp_err_to_name(result));
|
||||
return false;
|
||||
}
|
||||
|
||||
std::sort(
|
||||
records->begin(),
|
||||
records->begin() + record_count,
|
||||
[](const wifi_ap_record_t& left,
|
||||
const wifi_ap_record_t& right) {
|
||||
return left.rssi > right.rssi;
|
||||
});
|
||||
|
||||
for (uint16_t index = 0;
|
||||
index < record_count && *count < capacity;
|
||||
++index) {
|
||||
const auto& record = (*records)[index];
|
||||
const char* ssid =
|
||||
reinterpret_cast<const char*>(record.ssid);
|
||||
const size_t ssid_length =
|
||||
BoundedStringLength(ssid, sizeof(record.ssid));
|
||||
if (ssid_length == 0 ||
|
||||
ssid_length >= kWifiSsidCapacity) {
|
||||
continue;
|
||||
}
|
||||
|
||||
bool duplicate = false;
|
||||
for (size_t existing = 0; existing < *count; ++existing) {
|
||||
if (std::strncmp(
|
||||
output[existing].ssid.data(),
|
||||
ssid,
|
||||
kWifiSsidCapacity) == 0) {
|
||||
duplicate = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (duplicate) {
|
||||
continue;
|
||||
}
|
||||
|
||||
WifiNetwork& network = output[(*count)++];
|
||||
network = {};
|
||||
std::memcpy(network.ssid.data(), ssid, ssid_length);
|
||||
network.rssi_dbm = record.rssi;
|
||||
network.auth_mode =
|
||||
static_cast<uint8_t>(record.authmode);
|
||||
}
|
||||
|
||||
ESP_LOGI(kTag, "WiFi pre-scan complete raw=%u unique=%u",
|
||||
static_cast<unsigned>(record_count),
|
||||
static_cast<unsigned>(*count));
|
||||
return true;
|
||||
}
|
||||
|
||||
WifiLinkInfo EspWifiTransport::GetLinkInfo() const
|
||||
{
|
||||
portENTER_CRITICAL(&link_lock_);
|
||||
const WifiLinkInfo snapshot = link_info_;
|
||||
portEXIT_CRITICAL(&link_lock_);
|
||||
return snapshot;
|
||||
}
|
||||
|
||||
void EspWifiTransport::WifiEventHandler(
|
||||
void* context,
|
||||
esp_event_base_t,
|
||||
int32_t event_id,
|
||||
void* event_data)
|
||||
{
|
||||
auto* self = static_cast<EspWifiTransport*>(context);
|
||||
if (event_id == WIFI_EVENT_STA_START) {
|
||||
self->Publish({WifiTransportEventType::kStarted, 0});
|
||||
return;
|
||||
}
|
||||
if (event_id == WIFI_EVENT_STA_DISCONNECTED) {
|
||||
const auto* disconnected =
|
||||
static_cast<const wifi_event_sta_disconnected_t*>(event_data);
|
||||
const uint16_t reason =
|
||||
disconnected == nullptr ? 0 : disconnected->reason;
|
||||
self->ClearLinkState(reason);
|
||||
self->Publish({WifiTransportEventType::kDisconnected, reason});
|
||||
}
|
||||
}
|
||||
|
||||
void EspWifiTransport::IpEventHandler(
|
||||
void* context,
|
||||
esp_event_base_t,
|
||||
int32_t event_id,
|
||||
void* event_data)
|
||||
{
|
||||
if (event_id != IP_EVENT_STA_GOT_IP || event_data == nullptr) {
|
||||
return;
|
||||
}
|
||||
|
||||
auto* self = static_cast<EspWifiTransport*>(context);
|
||||
const auto* got_ip = static_cast<const ip_event_got_ip_t*>(event_data);
|
||||
char ipv4[kWifiIpv4Capacity]{};
|
||||
esp_ip4addr_ntoa(&got_ip->ip_info.ip, ipv4, sizeof(ipv4));
|
||||
|
||||
wifi_ap_record_t access_point{};
|
||||
const esp_err_t ap_result = esp_wifi_sta_get_ap_info(&access_point);
|
||||
|
||||
portENTER_CRITICAL(&self->link_lock_);
|
||||
self->link_info_.online = true;
|
||||
self->link_info_.ipv4.fill('\0');
|
||||
strlcpy(
|
||||
self->link_info_.ipv4.data(),
|
||||
ipv4,
|
||||
self->link_info_.ipv4.size());
|
||||
if (ap_result == ESP_OK) {
|
||||
self->link_info_.rssi_dbm = access_point.rssi;
|
||||
self->link_info_.channel = access_point.primary;
|
||||
}
|
||||
portEXIT_CRITICAL(&self->link_lock_);
|
||||
|
||||
ESP_LOGI(kTag, "DHCP ready ip=%s", ipv4);
|
||||
self->Publish({WifiTransportEventType::kGotIp, 0});
|
||||
}
|
||||
|
||||
bool EspWifiTransport::InitializeDriver()
|
||||
{
|
||||
if (driver_initialized_) {
|
||||
return true;
|
||||
}
|
||||
|
||||
esp_err_t result = esp_netif_init();
|
||||
if (result != ESP_OK && result != ESP_ERR_INVALID_STATE) {
|
||||
ESP_LOGE(kTag, "esp_netif_init failed: %s",
|
||||
esp_err_to_name(result));
|
||||
return false;
|
||||
}
|
||||
|
||||
station_netif_ = esp_netif_get_handle_from_ifkey("WIFI_STA_DEF");
|
||||
if (station_netif_ == nullptr) {
|
||||
station_netif_ = esp_netif_create_default_wifi_sta();
|
||||
}
|
||||
if (station_netif_ == nullptr) {
|
||||
ESP_LOGE(kTag, "default WiFi STA netif creation failed");
|
||||
return false;
|
||||
}
|
||||
|
||||
wifi_init_config_t config = WIFI_INIT_CONFIG_DEFAULT();
|
||||
config.nvs_enable = false;
|
||||
if (low_memory_profile_) {
|
||||
// Enough to associate and complete DHCP, nothing more. The static RX
|
||||
// buffers dominate (10 x 1600 bytes by default) and are what actually
|
||||
// ran out; AMPDU is switched off because its reorder buffers scale
|
||||
// with the same pool and only buy throughput this link never uses.
|
||||
// Field log with static_rx_buf_num = 4: "Expected to init 4 rx buffer,
|
||||
// actual is 2" at dma_free=31019 / dma_largest=6912 — the pool is both
|
||||
// small and fragmented, and the driver's own 6656-byte task stack takes
|
||||
// the one usable block. Ask for the documented minimum instead; this
|
||||
// link only has to associate and pull a DHCP lease.
|
||||
config.static_rx_buf_num = 2;
|
||||
config.dynamic_rx_buf_num = 6;
|
||||
config.static_tx_buf_num = 4;//2026-9-8 ckkj add
|
||||
config.dynamic_tx_buf_num = 6;
|
||||
config.cache_tx_buf_num = 4;//2026-9-8 ckkj add
|
||||
config.rx_mgmt_buf_num = 2;
|
||||
config.mgmt_sbuf_num = 6;
|
||||
config.ampdu_rx_enable = 0;
|
||||
config.ampdu_tx_enable = 0;
|
||||
config.rx_ba_win = 0;
|
||||
}
|
||||
// boot 提示音和 WiFi 驱动初始化会并发抢 DMA 内部 RAM:boot 音在 7.0-7.3s 区间瞬时吃光内部堆
|
||||
// (min=107 字节),esp_wifi_init 申请 static rx buffer 时恰好撞到峰值。
|
||||
// 在低内存配置下仅需 ~12KB (2*1600 rx + 2*~300 mgmt + 6656 task stack);完整配置
|
||||
// 要多出 4 个 static rx 和更多的静态 TX,阈值相应抬高。等到内部堆总空闲量超过
|
||||
// 阈值再进入 esp_wifi_init。最多等 3 秒,boot 音 200ms 内必然抽完。
|
||||
const size_t kWifiInitRequiredFree =
|
||||
low_memory_profile_ ? 12000 : 50000;
|
||||
// const size_t kWifiInitRequiredLargest =
|
||||
// low_memory_profile_ ? 8000 : 32000;
|
||||
constexpr uint32_t kWifiInitWaitMaxMs = 3000;
|
||||
constexpr uint32_t kWifiInitPollMs = 100;
|
||||
for (uint32_t waited = 0;
|
||||
waited < kWifiInitWaitMaxMs;
|
||||
waited += kWifiInitPollMs) {
|
||||
const size_t free =
|
||||
heap_caps_get_free_size(MALLOC_CAP_INTERNAL);
|
||||
if (free >= kWifiInitRequiredFree) {
|
||||
break;
|
||||
}
|
||||
vTaskDelay(pdMS_TO_TICKS(kWifiInitPollMs));
|
||||
}//2026-9-3 ckkj debug :wifi start fail
|
||||
ESP_LOGI(kTag,
|
||||
"WiFi driver init profile=%s internal_free=%u largest=%u",
|
||||
low_memory_profile_ ? "low_memory" : "default",
|
||||
static_cast<unsigned>(
|
||||
heap_caps_get_free_size(MALLOC_CAP_INTERNAL)),
|
||||
static_cast<unsigned>(
|
||||
heap_caps_get_largest_free_block(MALLOC_CAP_INTERNAL)));
|
||||
|
||||
heap_caps_print_heap_info(MALLOC_CAP_INTERNAL);
|
||||
result = esp_wifi_init(&config);
|
||||
if (result != ESP_OK) {
|
||||
ESP_LOGE(kTag, "esp_wifi_init failed: %s",
|
||||
esp_err_to_name(result));
|
||||
return false;
|
||||
}
|
||||
driver_initialized_ = true;
|
||||
|
||||
result = esp_wifi_set_storage(WIFI_STORAGE_RAM);
|
||||
if (result == ESP_OK) {
|
||||
result = esp_wifi_set_mode(WIFI_MODE_STA);
|
||||
}
|
||||
if (result == ESP_OK) {
|
||||
//result = esp_wifi_set_ps(WIFI_PS_NONE);//2026-9-8 ckkj mod 省电模式
|
||||
result = esp_wifi_set_ps(WIFI_PS_MIN_MODEM);
|
||||
}
|
||||
if (result != ESP_OK) {
|
||||
ESP_LOGE(kTag, "WiFi STA setup failed: %s",
|
||||
esp_err_to_name(result));
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool EspWifiTransport::RegisterHandlers()
|
||||
{
|
||||
if (wifi_handler_ == nullptr) {
|
||||
const esp_err_t result = esp_event_handler_instance_register(
|
||||
WIFI_EVENT,
|
||||
ESP_EVENT_ANY_ID,
|
||||
&EspWifiTransport::WifiEventHandler,
|
||||
this,
|
||||
&wifi_handler_);
|
||||
if (result != ESP_OK) {
|
||||
ESP_LOGE(kTag, "register WIFI_EVENT failed: %s",
|
||||
esp_err_to_name(result));
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
if (ip_handler_ == nullptr) {
|
||||
const esp_err_t result = esp_event_handler_instance_register(
|
||||
IP_EVENT,
|
||||
IP_EVENT_STA_GOT_IP,
|
||||
&EspWifiTransport::IpEventHandler,
|
||||
this,
|
||||
&ip_handler_);
|
||||
if (result != ESP_OK) {
|
||||
ESP_LOGE(kTag, "register IP_EVENT failed: %s",
|
||||
esp_err_to_name(result));
|
||||
UnregisterHandlers();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
void EspWifiTransport::UnregisterHandlers()
|
||||
{
|
||||
if (wifi_handler_ != nullptr) {
|
||||
esp_event_handler_instance_unregister(
|
||||
WIFI_EVENT, ESP_EVENT_ANY_ID, wifi_handler_);
|
||||
wifi_handler_ = nullptr;
|
||||
}
|
||||
if (ip_handler_ != nullptr) {
|
||||
esp_event_handler_instance_unregister(
|
||||
IP_EVENT, IP_EVENT_STA_GOT_IP, ip_handler_);
|
||||
ip_handler_ = nullptr;
|
||||
}
|
||||
}
|
||||
|
||||
void EspWifiTransport::Publish(const WifiTransportEvent& event)
|
||||
{
|
||||
portENTER_CRITICAL(&link_lock_);
|
||||
IWifiTransportObserver* const observer = observer_;
|
||||
portEXIT_CRITICAL(&link_lock_);
|
||||
if (observer != nullptr) {
|
||||
observer->OnWifiTransportEvent(event);
|
||||
}
|
||||
}
|
||||
|
||||
void EspWifiTransport::ClearLinkState(uint16_t reason)
|
||||
{
|
||||
portENTER_CRITICAL(&link_lock_);
|
||||
link_info_.online = false;
|
||||
link_info_.rssi_dbm = -127;
|
||||
link_info_.channel = 0;
|
||||
link_info_.last_disconnect_reason = reason;
|
||||
link_info_.ipv4.fill('\0');
|
||||
portEXIT_CRITICAL(&link_lock_);
|
||||
}
|
||||
|
||||
} // namespace borla
|
||||
58
main/platform/borla_s3/esp_wifi_transport.h
Normal file
58
main/platform/borla_s3/esp_wifi_transport.h
Normal file
@@ -0,0 +1,58 @@
|
||||
#pragma once
|
||||
|
||||
#include "connectivity/wifi_transport.h"
|
||||
|
||||
#include <esp_event.h>
|
||||
#include <esp_netif.h>
|
||||
#include <freertos/FreeRTOS.h>
|
||||
#include <freertos/portmacro.h>
|
||||
|
||||
namespace borla {
|
||||
|
||||
class EspWifiTransport final : public IWifiTransport {
|
||||
public:
|
||||
bool Start(IWifiTransportObserver& observer) override;
|
||||
void Stop() override;
|
||||
void ReleaseDriver() override;
|
||||
void UseLowMemoryProfile(bool enabled) override;
|
||||
bool Connect(const WifiCredential& credential) override;
|
||||
bool Scan(
|
||||
WifiNetwork* output,
|
||||
size_t capacity,
|
||||
size_t* count) override;
|
||||
WifiLinkInfo GetLinkInfo() const override;
|
||||
|
||||
private:
|
||||
static void WifiEventHandler(
|
||||
void* context,
|
||||
esp_event_base_t event_base,
|
||||
int32_t event_id,
|
||||
void* event_data);
|
||||
static void IpEventHandler(
|
||||
void* context,
|
||||
esp_event_base_t event_base,
|
||||
int32_t event_id,
|
||||
void* event_data);
|
||||
|
||||
bool InitializeDriver();
|
||||
bool RegisterHandlers();
|
||||
void UnregisterHandlers();
|
||||
void Publish(const WifiTransportEvent& event);
|
||||
void ClearLinkState(uint16_t reason);
|
||||
|
||||
mutable portMUX_TYPE link_lock_ = portMUX_INITIALIZER_UNLOCKED;
|
||||
WifiLinkInfo link_info_{};
|
||||
IWifiTransportObserver* observer_ = nullptr;
|
||||
esp_netif_t* station_netif_ = nullptr;
|
||||
esp_event_handler_instance_t wifi_handler_ = nullptr;
|
||||
esp_event_handler_instance_t ip_handler_ = nullptr;
|
||||
// 正常开机必须用完整缓冲配置(sdkconfig 里的 rx6/dyn8/ba8),否则 OTA
|
||||
// 版本检查的 HTTPS 会打爆动态 RX 缓冲("wifi:mem fail" → HTTP write 失败)。
|
||||
// 低内存配置只用于配网时与 BT 控制器共存,由 BleProvisioningService 显式
|
||||
// 通过 UseLowMemoryProfile() 切换(HandleStart/HandleConnect/HandleStop)。
|
||||
bool low_memory_profile_ = false;
|
||||
bool driver_initialized_ = false;
|
||||
bool started_ = false;
|
||||
};
|
||||
|
||||
} // namespace borla
|
||||
63
main/platform/borla_s3/i2c_bus.cc
Normal file
63
main/platform/borla_s3/i2c_bus.cc
Normal file
@@ -0,0 +1,63 @@
|
||||
#include "platform/borla_s3/i2c_bus.h"
|
||||
|
||||
#include "platform/borla_s3/board_config.h"
|
||||
|
||||
#include <driver/gpio.h>
|
||||
#include <driver/rtc_io.h>
|
||||
#include <esp_err.h>
|
||||
#include <esp_log.h>
|
||||
|
||||
namespace borla {
|
||||
namespace {
|
||||
|
||||
constexpr const char* kTag = "BorlaI2cBus2";
|
||||
|
||||
} // namespace
|
||||
|
||||
BorlaS3I2cBus::~BorlaS3I2cBus()
|
||||
{
|
||||
if (handle_ != nullptr) {
|
||||
i2c_del_master_bus(handle_);
|
||||
}
|
||||
}
|
||||
|
||||
bool BorlaS3I2cBus::Initialize()
|
||||
{
|
||||
if (handle_ != nullptr) {
|
||||
return true;
|
||||
}
|
||||
|
||||
gpio_hold_dis(board_config::kAudioI2cSdaGpio);
|
||||
gpio_hold_dis(board_config::kAudioI2cSclGpio);
|
||||
rtc_gpio_hold_dis(board_config::kAudioI2cSdaGpio);
|
||||
rtc_gpio_hold_dis(board_config::kAudioI2cSclGpio);
|
||||
|
||||
const i2c_master_bus_config_t config = {
|
||||
.i2c_port = I2C_NUM_0,
|
||||
.sda_io_num = board_config::kAudioI2cSdaGpio,
|
||||
.scl_io_num = board_config::kAudioI2cSclGpio,
|
||||
.clk_source = I2C_CLK_SRC_DEFAULT,
|
||||
.glitch_ignore_cnt = 7,
|
||||
.intr_priority = 0,
|
||||
.trans_queue_depth = 0,
|
||||
.flags = {
|
||||
//.enable_internal_pullup = true,
|
||||
.enable_internal_pullup = false,
|
||||
.allow_pd = false,
|
||||
},
|
||||
};
|
||||
const esp_err_t result = i2c_new_master_bus(&config, &handle_);
|
||||
if (result != ESP_OK) {
|
||||
ESP_LOGE(kTag, "bus initialization failed: %s",
|
||||
esp_err_to_name(result));
|
||||
handle_ = nullptr;
|
||||
return false;
|
||||
}
|
||||
|
||||
ESP_LOGI(kTag, "I2C0 initialized SDA=%d SCL=%d",
|
||||
static_cast<int>(board_config::kAudioI2cSdaGpio),
|
||||
static_cast<int>(board_config::kAudioI2cSclGpio));
|
||||
return true;
|
||||
}
|
||||
|
||||
} // namespace borla
|
||||
19
main/platform/borla_s3/i2c_bus.h
Normal file
19
main/platform/borla_s3/i2c_bus.h
Normal file
@@ -0,0 +1,19 @@
|
||||
#pragma once
|
||||
|
||||
#include <driver/i2c_master.h>
|
||||
|
||||
namespace borla {
|
||||
|
||||
class BorlaS3I2cBus final {
|
||||
public:
|
||||
BorlaS3I2cBus() = default;
|
||||
~BorlaS3I2cBus();
|
||||
|
||||
bool Initialize();
|
||||
i2c_master_bus_handle_t Handle() const { return handle_; }
|
||||
|
||||
private:
|
||||
i2c_master_bus_handle_t handle_ = nullptr;
|
||||
};
|
||||
|
||||
} // namespace borla
|
||||
863
main/platform/borla_s3/ml307_transport.cc
Normal file
863
main/platform/borla_s3/ml307_transport.cc
Normal file
@@ -0,0 +1,863 @@
|
||||
#include "platform/borla_s3/ml307_transport.h"
|
||||
|
||||
#include "connectivity/ml307_at_parser.h"
|
||||
#include "platform/borla_s3/board_config.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
|
||||
#include <esp_err.h>
|
||||
#include <esp_intr_alloc.h>
|
||||
#include <esp_log.h>
|
||||
#include <esp_netif_defaults.h>
|
||||
#include <esp_netif_ppp.h>
|
||||
#include <sdkconfig.h>
|
||||
|
||||
namespace borla {
|
||||
namespace {
|
||||
|
||||
constexpr const char* kTag = "Ml307Transport2";
|
||||
constexpr uint16_t kModemMissingReason = 0xF201;
|
||||
constexpr uint16_t kRegistrationReason = 0xF202;
|
||||
constexpr uint16_t kDialReason = 0xF203;
|
||||
constexpr uint16_t kPppSetupReason = 0xF204;
|
||||
constexpr uint16_t kPppLostReason = 0xF205;
|
||||
// 2026-9-4 ckkj add :ML307 从上电到 AT 就绪的典型耗时,留出余量。
|
||||
constexpr uint32_t kModemPowerOnDelayMs = 3000;//
|
||||
TaskHandle_t const kTaskStarting =
|
||||
reinterpret_cast<TaskHandle_t>(1);
|
||||
|
||||
} // namespace
|
||||
//2026-9-4 ckkj add
|
||||
void Ml307Transport::PowerOn()
|
||||
{
|
||||
if (power_control_ != nullptr) {
|
||||
power_control_(true);
|
||||
}
|
||||
// if (!powered_.exchange(true)) {
|
||||
// vTaskDelay(pdMS_TO_TICKS(kModemPowerOnDelayMs));
|
||||
// }
|
||||
bool was_off = !powered_.exchange(true);
|
||||
// 只要模块刚被上电,就做上电延时;如果之前已经上电,跳过长延时
|
||||
if(was_off)
|
||||
{
|
||||
vTaskDelay(pdMS_TO_TICKS(kModemPowerOnDelayMs));
|
||||
}
|
||||
}
|
||||
|
||||
void Ml307Transport::PowerOff()
|
||||
{
|
||||
if (powered_.exchange(false) && power_control_ != nullptr) {
|
||||
power_control_(false);
|
||||
}
|
||||
}//////add end
|
||||
bool Ml307Transport::Start(ICellularTransportObserver& observer)
|
||||
{
|
||||
portENTER_CRITICAL(&state_lock_);
|
||||
observer_ = &observer;
|
||||
portEXIT_CRITICAL(&state_lock_);
|
||||
if (task_.load() != nullptr) {
|
||||
return true;
|
||||
}
|
||||
if (stopped_ == nullptr) {
|
||||
stopped_ = xSemaphoreCreateBinaryStatic(&stopped_control_);
|
||||
if (stopped_ == nullptr) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
xSemaphoreTake(stopped_, 0);
|
||||
stop_requested_.store(false);
|
||||
ppp_lost_.store(false);
|
||||
task_.store(kTaskStarting);
|
||||
TaskHandle_t handle = xTaskCreateStatic(
|
||||
&Ml307Transport::TaskEntry,
|
||||
"ml307_ppp2",
|
||||
task_stack_.size(),
|
||||
this,
|
||||
5,
|
||||
task_stack_.data(),
|
||||
&task_control_);
|
||||
if (handle == nullptr) {
|
||||
task_.store(nullptr);
|
||||
return false;
|
||||
}
|
||||
TaskHandle_t expected = kTaskStarting;
|
||||
task_.compare_exchange_strong(expected, handle);
|
||||
return true;
|
||||
}
|
||||
|
||||
void Ml307Transport::Stop()
|
||||
{
|
||||
if (task_.load() == nullptr) {
|
||||
return;
|
||||
}
|
||||
stop_requested_.store(true);
|
||||
if (stopped_ != nullptr &&
|
||||
xSemaphoreTake(stopped_, pdMS_TO_TICKS(5000)) != pdTRUE) {
|
||||
ESP_LOGE(kTag, "timed out waiting for modem task");
|
||||
}
|
||||
PowerOff();//2026-9-4 ckkj add
|
||||
}
|
||||
|
||||
//bool Ml307Transport::ProbePresent()
|
||||
CellularProbeResult Ml307Transport::ProbePresent()
|
||||
{
|
||||
if (running_.load()) {
|
||||
//return true;
|
||||
return CellularProbeResult::kPresent;
|
||||
}
|
||||
stop_requested_.store(false);
|
||||
PowerOn();//2026-9-4 ckkj add
|
||||
if (!InitializeUart(kProbeUartRxBufferSize, 0)) {
|
||||
PowerOff();//2026-9-4 ckkj add
|
||||
// return false;
|
||||
// 2026-9-7 ckkj add: 开机窗口内部 RAM 紧张,探测 UART 可能装不上;
|
||||
// 这不代表模块不在位,返回 kUnknown 避免污染在位状态。
|
||||
return CellularProbeResult::kUnknown;
|
||||
}
|
||||
bool present = false;
|
||||
unsigned rx_bytes_total = 0;
|
||||
uint8_t rx_first[8] = {};
|
||||
size_t rx_first_len = 0;
|
||||
|
||||
for (uint8_t attempt = 0; attempt < 3 && !present; ++attempt) {
|
||||
// 2026-9-17 ckkj 诊断: 传入 echo 缓冲区,把 AT 等待期内收到的原始
|
||||
// 字节(含乱码)打出来。旧实现 response=nullptr 时窗口内字节被丢弃,
|
||||
// "rx=0" 只反映超时后 60ms 的统计,无法证明线上没信号。
|
||||
char echo[64] = {};
|
||||
present = SendCommand("AT", "OK", 600, echo, sizeof(echo));
|
||||
ESP_LOGI(kTag, "probe AT attempt=%u/3 ok=%d rx=%u echo=[%s]",
|
||||
attempt, present, rx_bytes_total, echo);
|
||||
if (!present) {
|
||||
uint8_t scratch[32] = {};
|
||||
const int n = uart_read_bytes(
|
||||
kUart, scratch, sizeof(scratch), pdMS_TO_TICKS(60));
|
||||
if (n > 0) {
|
||||
rx_bytes_total += static_cast<unsigned>(n);
|
||||
if (rx_first_len == 0) {
|
||||
rx_first_len = std::min(static_cast<size_t>(n), sizeof(rx_first));
|
||||
std::memcpy(rx_first, scratch, rx_first_len);
|
||||
}
|
||||
}
|
||||
vTaskDelay(pdMS_TO_TICKS(500));
|
||||
}
|
||||
}
|
||||
if (!present) {
|
||||
ESP_LOGW(kTag,
|
||||
"modem silent rx=%u first=%02x %02x %02x %02x (rx=0 => no boot or TX wire dead)",
|
||||
rx_bytes_total,
|
||||
rx_first[0], rx_first[1], rx_first[2], rx_first[3]);
|
||||
}
|
||||
CleanupUart();
|
||||
// 2026-9-17 ckkj 诊断: 探测失败后暂不断电,保持 EN_4G=1,便于万用表
|
||||
// 测量模组 VBAT / TCA9555 P0.2 电平并观察 NETLIGHT;定位完成后恢复。
|
||||
// if (!present) {
|
||||
// PowerOff();
|
||||
// }
|
||||
if (!present) {
|
||||
ESP_LOGW(kTag, "probe failed, EN_4G left ON for hardware check (diag)");
|
||||
}
|
||||
portENTER_CRITICAL(&state_lock_);
|
||||
link_info_.modem_present = present;
|
||||
portEXIT_CRITICAL(&state_lock_);
|
||||
//return present;
|
||||
return present ? CellularProbeResult::kPresent: CellularProbeResult::kAbsent;
|
||||
}
|
||||
|
||||
CellularLinkInfo Ml307Transport::GetLinkInfo() const
|
||||
{
|
||||
portENTER_CRITICAL(&state_lock_);
|
||||
const CellularLinkInfo snapshot = link_info_;
|
||||
portEXIT_CRITICAL(&state_lock_);
|
||||
return snapshot;
|
||||
}
|
||||
|
||||
void Ml307Transport::TaskEntry(void* context)
|
||||
{
|
||||
static_cast<Ml307Transport*>(context)->Run();
|
||||
}
|
||||
|
||||
esp_err_t Ml307Transport::Transmit(
|
||||
void* handle,
|
||||
void* buffer,
|
||||
size_t length)
|
||||
{
|
||||
auto* self = static_cast<Ml307Transport*>(handle);
|
||||
if (self == nullptr || !self->uart_installed_) {
|
||||
return ESP_FAIL;
|
||||
}
|
||||
const int written = uart_write_bytes(
|
||||
kUart,
|
||||
static_cast<const char*>(buffer),
|
||||
length);
|
||||
// 2026-9-19 ckkj diag: 打印 PPP 发送帧前 8 字节,确认 lwIP 是否在发 LCP。
|
||||
const uint8_t* p = static_cast<const uint8_t*>(buffer);
|
||||
ESP_LOGI(kTag, "ppp tx len=%u %02x %02x %02x %02x %02x %02x %02x %02x",
|
||||
static_cast<unsigned>(length),
|
||||
p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7]);/////////
|
||||
return written == static_cast<int>(length) ? ESP_OK : ESP_FAIL;
|
||||
}
|
||||
|
||||
void Ml307Transport::IpEventHandler(
|
||||
void* context,
|
||||
esp_event_base_t,
|
||||
int32_t event_id,
|
||||
void* event_data)
|
||||
{
|
||||
auto* self = static_cast<Ml307Transport*>(context);
|
||||
if (self == nullptr) {
|
||||
return;
|
||||
}
|
||||
if (event_id == IP_EVENT_PPP_GOT_IP) {
|
||||
if (event_data == nullptr) {
|
||||
return;
|
||||
}
|
||||
const auto* got_ip =
|
||||
static_cast<const ip_event_got_ip_t*>(event_data);
|
||||
if (got_ip->esp_netif != self->netif_) {
|
||||
return;
|
||||
}
|
||||
char ipv4[kCellularIpv4Capacity]{};
|
||||
esp_ip4addr_ntoa(
|
||||
&got_ip->ip_info.ip, ipv4, sizeof(ipv4));
|
||||
portENTER_CRITICAL(&self->state_lock_);
|
||||
self->link_info_.online = true;
|
||||
self->link_info_.ipv4.fill('\0');
|
||||
// std::strncpy(
|
||||
// self->link_info_.ipv4.data(),
|
||||
// ipv4,
|
||||
// self->link_info_.ipv4.size() - 1);
|
||||
strlcpy(self->link_info_.ipv4.data(),ipv4,self->link_info_.ipv4.size());
|
||||
portEXIT_CRITICAL(&self->state_lock_);
|
||||
ESP_LOGI(kTag, "PPP online ip=%s", ipv4);
|
||||
self->Publish({CellularTransportEventType::kGotIp, 0});
|
||||
} else if (event_id == IP_EVENT_PPP_LOST_IP) {
|
||||
self->ppp_lost_.store(true);
|
||||
}
|
||||
}
|
||||
|
||||
void Ml307Transport::Run()
|
||||
{
|
||||
running_.store(true);
|
||||
PowerOn();//2026-9-4 ckkj add
|
||||
uint16_t failure = 0;
|
||||
//2026-9-6 ckkj add: PPP 环形缓冲需要内部 RAM 最大连续块,切网时 WiFi
|
||||
//资源异步释放中,install 可能 malloc 失败;等待重试,并随重试次数逐级
|
||||
//降档缓冲:115200 波特率下 1024B 环形缓冲仍可缓冲 ~89ms,保证 WiFi
|
||||
//卸载后任意 ≥1KB 连续块都能完成安装。
|
||||
bool uart_ready = false;
|
||||
for (uint8_t attempt = 0;attempt < 6 && !uart_ready && !stop_requested_.load();++attempt) {
|
||||
const size_t rx_bytes = (attempt < 2) ? kPppUartRxBufferSize: (attempt < 4) ? 2048U : 1024U;
|
||||
uart_ready = InitializeUart(rx_bytes, rx_bytes / 2);
|
||||
if (!uart_ready) {
|
||||
ESP_LOGW(kTag, "PPP uart install retry=%u/6 rx=%u (waiting wifi teardown memory)",static_cast<unsigned>(attempt + 1),static_cast<unsigned>(rx_bytes));
|
||||
vTaskDelay(pdMS_TO_TICKS(800));
|
||||
}
|
||||
}
|
||||
// if (!uart_ready || !DetectAndConfigure()) {
|
||||
// failure = kModemMissingReason;
|
||||
// } else {
|
||||
// Publish({CellularTransportEventType::kStarted, 0});
|
||||
// if (!WaitForRegistration()) {
|
||||
// failure = kRegistrationReason;
|
||||
// } else if (!Dial()) {
|
||||
// failure = kDialReason;
|
||||
// } else if (!CreatePppNetif()) {
|
||||
// failure = kPppSetupReason;
|
||||
// } else {
|
||||
//2026-9-7 ckkj add: 注网/拨号阶段成功时静默,排障无法定位卡点,补充阶段日志
|
||||
if (uart_ready) {
|
||||
ESP_LOGI(kTag, "ppp uart installed");
|
||||
}
|
||||
if (!uart_ready || !DetectAndConfigure()) {
|
||||
failure = kModemMissingReason;
|
||||
} else {
|
||||
ESP_LOGI(kTag, "modem configured, waiting registration");
|
||||
Publish({CellularTransportEventType::kStarted, 0});
|
||||
if (!WaitForRegistration()) {
|
||||
ESP_LOGW(kTag, "registration failed");
|
||||
failure = kRegistrationReason;
|
||||
} else if (!Dial()) {
|
||||
ESP_LOGW(kTag, "dial failed");
|
||||
failure = kDialReason;
|
||||
//} else if (!CreatePppNetif()) {
|
||||
} else {
|
||||
// 2026-9-19 ckkj fix: CGDATA OK 后模组需要时间从 AT 模式切换到
|
||||
// PPP 数据模式。立即发送 LCP 可能被模组当作 AT 命令丢弃。
|
||||
vTaskDelay(pdMS_TO_TICKS(1000));
|
||||
if (!CreatePppNetif()) {
|
||||
ESP_LOGW(kTag, "ppp netif create failed");
|
||||
failure = kPppSetupReason;
|
||||
} else {
|
||||
RunPpp();
|
||||
if (ppp_lost_.load() && !stop_requested_.load()) {
|
||||
failure = kPppLostReason;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
CleanupPpp();
|
||||
CleanupUart();
|
||||
const bool explicit_stop = stop_requested_.load();
|
||||
running_.store(false);
|
||||
task_.store(nullptr);
|
||||
if (!explicit_stop) {
|
||||
if (failure != 0) {
|
||||
ESP_LOGE(kTag, "modem task failed reason=0x%04x", failure);
|
||||
}
|
||||
SetDisconnected(failure == 0 ? kPppLostReason : failure);
|
||||
}
|
||||
if (stopped_ != nullptr) {
|
||||
xSemaphoreGive(stopped_);
|
||||
}
|
||||
vTaskDelete(nullptr);
|
||||
}
|
||||
|
||||
bool Ml307Transport::InitializeUart(
|
||||
size_t rx_buffer_size,
|
||||
size_t tx_buffer_size)
|
||||
{
|
||||
if (uart_installed_) {
|
||||
return true;
|
||||
}
|
||||
//2026-8-25 ckkj add for warning
|
||||
gpio_reset_pin(board_config::kMl307TxGpio);
|
||||
gpio_reset_pin(board_config::kMl307RxGpio);
|
||||
//end
|
||||
const esp_err_t install = uart_driver_install(
|
||||
kUart,
|
||||
rx_buffer_size,
|
||||
tx_buffer_size,
|
||||
0,
|
||||
nullptr,
|
||||
ESP_INTR_FLAG_IRAM);
|
||||
if (install != ESP_OK) {
|
||||
ESP_LOGW(kTag, "UART install failed: %s",
|
||||
esp_err_to_name(install));
|
||||
return false;
|
||||
}
|
||||
uart_config_t config{};
|
||||
config.baud_rate = board_config::kMl307BaudRate;
|
||||
config.data_bits = UART_DATA_8_BITS;
|
||||
config.parity = UART_PARITY_DISABLE;
|
||||
config.stop_bits = UART_STOP_BITS_1;
|
||||
config.flow_ctrl = UART_HW_FLOWCTRL_DISABLE;
|
||||
config.source_clk = UART_SCLK_DEFAULT;
|
||||
const esp_err_t configured = uart_param_config(kUart, &config);
|
||||
const esp_err_t pins = configured == ESP_OK
|
||||
? uart_set_pin(
|
||||
kUart,
|
||||
board_config::kMl307TxGpio,
|
||||
board_config::kMl307RxGpio,
|
||||
UART_PIN_NO_CHANGE,
|
||||
UART_PIN_NO_CHANGE)
|
||||
: ESP_FAIL;
|
||||
if (configured != ESP_OK || pins != ESP_OK) {
|
||||
ESP_LOGE(kTag, "UART setup failed config=%s pins=%s",
|
||||
esp_err_to_name(configured), esp_err_to_name(pins));
|
||||
uart_driver_delete(kUart);
|
||||
return false;
|
||||
}
|
||||
uart_set_rx_timeout(kUart, 2);
|
||||
uart_installed_ = true;
|
||||
ESP_LOGI(kTag, "ppp uart installed rx=%u",static_cast<unsigned>(rx_buffer_size));
|
||||
return true;
|
||||
}
|
||||
|
||||
void Ml307Transport::CleanupUart()
|
||||
{
|
||||
if (uart_installed_) {
|
||||
uart_driver_delete(kUart);
|
||||
uart_installed_ = false;
|
||||
}
|
||||
}
|
||||
|
||||
bool Ml307Transport::DetectAndConfigure()
|
||||
{
|
||||
bool detected = false;
|
||||
for (uint8_t attempt = 0;
|
||||
attempt < 3 && !detected && !stop_requested_.load();
|
||||
++attempt) {
|
||||
detected = SendCommand("AT", "OK", 800);
|
||||
}
|
||||
if (!detected) {
|
||||
ESP_LOGE(kTag, "modem silent 30s: not booted / baud mismatch / TX wire dead");
|
||||
return false;
|
||||
}
|
||||
portENTER_CRITICAL(&state_lock_);
|
||||
link_info_ = {};
|
||||
link_info_.modem_present = true;
|
||||
portEXIT_CRITICAL(&state_lock_);
|
||||
// 硬件未连 RTS/CTS 导致模组 PPP 帧完全静默(ppp rx=0)。
|
||||
// 2026-9-19 ckkj diag: 打印关键 AT 命令响应,确认模组是否接受流控/DTR 设置。
|
||||
std::array<char, kAtResponseCapacity> diag{};
|
||||
bool ifc_ok = SendCommand("AT+IFC=0,0", "OK", 1000, diag.data(), diag.size());
|
||||
ESP_LOGI(kTag, "AT+IFC=0,0 ok=%d resp=%s", ifc_ok ? 1 : 0, diag.data());
|
||||
// AT&D0: 忽略 DTR 信号(硬件未连 DTR,否则模组可能不发送 PPP 数据)
|
||||
bool d0_ok = SendCommand("AT&D0", "OK", 1000, diag.data(), diag.size());
|
||||
ESP_LOGI(kTag, "AT&D0 ok=%d resp=%s", d0_ok ? 1 : 0, diag.data());
|
||||
// AT&C0: DCD 始终有效
|
||||
bool c0_ok = SendCommand("AT&C0", "OK", 1000, diag.data(), diag.size());
|
||||
ESP_LOGI(kTag, "AT&C0 ok=%d resp=%s", c0_ok ? 1 : 0, diag.data());
|
||||
|
||||
// 2026-9-20 ckkj: 启用详细错误码,否则ATD失败只返回裸ERROR无法诊断。
|
||||
bool cmee_ok = SendCommand("AT+CMEE=2", "OK", 1000, diag.data(), diag.size());
|
||||
ESP_LOGI(kTag, "AT+CMEE=2 ok=%d resp=%s", cmee_ok ? 1 : 0, diag.data());
|
||||
|
||||
SendCommand("ATE0", "OK", 1000);
|
||||
SendCommand("AT+CMEE=2", "OK", 1000);
|
||||
SendCommand("AT+CFUN=1", "OK", 5000);
|
||||
SendCommand("AT+CEREG=2", "OK", 1000);
|
||||
UpdateModemInformation();
|
||||
return true;
|
||||
}
|
||||
|
||||
bool Ml307Transport::WaitForRegistration()
|
||||
{
|
||||
std::array<char, kAtResponseCapacity> response{};
|
||||
for (uint8_t attempt = 0;attempt < 30 && !stop_requested_.load();++attempt) {
|
||||
// if (SendCommand("AT+CPIN?", "READY", 1500, response.data(), response.size()) &&
|
||||
// SendCommand("AT+CEREG?", "+CEREG:", 1500,response.data(), response.size()))
|
||||
const bool sim_ready = SendCommand("AT+CPIN?", "READY", 1500,response.data(), response.size());
|
||||
ESP_LOGI(kTag, "registration poll %u/30 sim=%d resp=%s",static_cast<unsigned>(attempt + 1),sim_ready ? 1 : 0, response.data());
|
||||
if (sim_ready && SendCommand("AT+CEREG?", "+CEREG:", 1500,response.data(), response.size()))
|
||||
{
|
||||
ESP_LOGI(kTag, "registration poll %u/30 cereg=%s",static_cast<unsigned>(attempt + 1),response.data());
|
||||
CellularRegistration registration;
|
||||
if (ParseMl307Registration(response.data(), ®istration)) {
|
||||
portENTER_CRITICAL(&state_lock_);
|
||||
link_info_.registration_status = registration.status;
|
||||
link_info_.registered = registration.IsRegistered();
|
||||
portEXIT_CRITICAL(&state_lock_);
|
||||
if (registration.IsRegistered()) {
|
||||
UpdateModemInformation();
|
||||
return true;
|
||||
}
|
||||
if (registration.status == 3) {
|
||||
ESP_LOGW(kTag, "registration denied (CEREG stat=3)");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
//2026-9-7 ckkj add: 注网轮询进度,打印原始 CEREG 响应便于定位
|
||||
ESP_LOGI(kTag, "registration poll attempt=%u/30 resp=%s",
|
||||
static_cast<unsigned>(attempt + 1), response.data());
|
||||
vTaskDelay(pdMS_TO_TICKS(2000));
|
||||
}
|
||||
return false;
|
||||
}
|
||||
/*
|
||||
bool Ml307Transport::Dial()
|
||||
{
|
||||
// 2026-9-7 ckkj add: 合并为单个 response buffer 复用,避免 4 个
|
||||
// std::array<char,512> 撑爆 ml307_ppp2 任务的 4KB 栈(Dial 自身栈帧
|
||||
// 从 2048B 降回 512B)。每步执行前重置保证日志不残留上一步内容。
|
||||
std::array<char, kAtResponseCapacity> response{};
|
||||
|
||||
char command[128]{};
|
||||
const int length = std::snprintf(
|
||||
command,
|
||||
sizeof(command),
|
||||
"AT+CGDCONT=1,\"IP\",\"%s\"",
|
||||
CONFIG_BORLA_ML307_APN);
|
||||
const bool ctx_ok =
|
||||
length > 0 && length < static_cast<int>(sizeof(command)) &&
|
||||
SendCommand(command, "OK", 3000,
|
||||
response.data(), response.size());
|
||||
ESP_LOGI(kTag, "cgdcont cid=1 apn=%s ok=%d resp=%s",
|
||||
CONFIG_BORLA_ML307_APN, ctx_ok ? 1 : 0, response.data());
|
||||
if (!ctx_ok) {
|
||||
return false;
|
||||
}
|
||||
// 2. 检查PS域附着状态
|
||||
response.fill('\0');
|
||||
if (!SendCommand("AT+CGATT?", "+CGATT", 2000, response.data(), response.size()))
|
||||
{
|
||||
ESP_LOGW(kTag, "AT+CGATT? query fail");
|
||||
return false;
|
||||
}
|
||||
ESP_LOGI(kTag, "cgatt check resp=%s", response.data());
|
||||
// 3. 2026-9-19 ckkj: 不再预激活PDP上下文。实测"CGACT预激活+CGDATA拨号"
|
||||
// 组合使ML307卡在中间态:OK已回但不发CONNECT、不跑PPP、ATD/ATH全ERROR。
|
||||
// 标准做法是让拨号命令自行触发激活,激活结果由CEER与PPP协商体现。
|
||||
|
||||
// 4. 预检PDP状态
|
||||
response.fill('\0');
|
||||
SendCommand("AT+CGDCONT?", "+CGDCONT", 2000,
|
||||
response.data(), response.size());
|
||||
ESP_LOGI(kTag, "cgdcont query resp=%s", response.data());
|
||||
response.fill('\0');
|
||||
SendCommand("AT+CGACT?", "+CGACT", 2000,
|
||||
response.data(), response.size());
|
||||
ESP_LOGI(kTag, "cgact query resp=%s", response.data());
|
||||
|
||||
|
||||
std::array<char, 64> probe{};
|
||||
bool dialed = false;
|
||||
|
||||
// 主路径:ATD*99#(隐式cid=1)
|
||||
probe.fill('\0');
|
||||
dialed = SendCommand("ATD*99#", "CONNECT", 30000,
|
||||
probe.data(), probe.size());
|
||||
ESP_LOGI(kTag, "ATD*99# ret=%d resp=[%s]",
|
||||
dialed ? 1 : 0, probe.data());
|
||||
|
||||
|
||||
if (!dialed) {
|
||||
probe.fill('\0');
|
||||
dialed = SendCommand("ATD*99***1#", "CONNECT", 30000,
|
||||
probe.data(), probe.size());
|
||||
ESP_LOGI(kTag, "ATD*99***1# ret=%d resp=[%s]",
|
||||
dialed ? 1 : 0, probe.data());
|
||||
}
|
||||
|
||||
if (!dialed) {
|
||||
ESP_LOGE(kTag, "all dial attempts failed, hard power cycle modem");
|
||||
PowerOff();
|
||||
vTaskDelay(pdMS_TO_TICKS(2000));
|
||||
PowerOn();
|
||||
return false;
|
||||
}
|
||||
|
||||
ESP_LOGI(kTag, "dial accepted, observing PPP data stream");
|
||||
// 数据模式观察窗:等HDLC标志帧0x7e(PPP LCP起始)。ATD的CONNECT已
|
||||
// 证明状态机切换成功,此时静默只能是硬件层(TX 4.3V电平/供电)问题。
|
||||
bool saw_bytes = false;
|
||||
for (int i = 0; i < 150 && !saw_bytes && !stop_requested_.load(); ++i) {
|
||||
uint8_t scratch[64] = {};
|
||||
const int n = uart_read_bytes(
|
||||
kUart, scratch, sizeof(scratch), pdMS_TO_TICKS(100));
|
||||
if (n > 0) {
|
||||
saw_bytes = true;
|
||||
ESP_LOGI(kTag, "data-mode first rx=%d %02x %02x %02x %02x",
|
||||
n, scratch[0], scratch[1], scratch[2], scratch[3]);
|
||||
}
|
||||
}
|
||||
if (!saw_bytes) {
|
||||
ESP_LOGE(kTag,
|
||||
"dial returned CONNECT but no PPP bytes: "
|
||||
"check ML307 TX 4.3V level / power supply");
|
||||
PowerOff();
|
||||
vTaskDelay(pdMS_TO_TICKS(2000));
|
||||
PowerOn();
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
*/
|
||||
bool Ml307Transport::Dial()
|
||||
{
|
||||
std::array<char, kAtResponseCapacity> response{};
|
||||
char command[128]{};
|
||||
const int length = std::snprintf(
|
||||
command,
|
||||
sizeof(command),
|
||||
"AT+CGDCONT=1,\"IP\",\"%s\"",
|
||||
CONFIG_BORLA_ML307_APN);
|
||||
const bool ctx_ok =
|
||||
length > 0 && length < static_cast<int>(sizeof(command)) &&
|
||||
SendCommand(command, "OK", 3000,
|
||||
response.data(), response.size());
|
||||
ESP_LOGI(kTag, "cgdcont cid=1 apn=%s ok=%d resp=%s",
|
||||
CONFIG_BORLA_ML307_APN, ctx_ok ? 1 : 0, response.data());
|
||||
if (!ctx_ok) {
|
||||
return false;
|
||||
}
|
||||
|
||||
response.fill('\0');
|
||||
if (!SendCommand("AT+CGATT?", "+CGATT", 2000, response.data(), response.size()))
|
||||
{
|
||||
ESP_LOGW(kTag, "AT+CGATT? query fail");
|
||||
return false;
|
||||
}
|
||||
ESP_LOGI(kTag, "cgatt check resp=%s", response.data());
|
||||
|
||||
response.fill('\0');
|
||||
SendCommand("AT+CGDCONT?", "+CGDCONT", 2000,
|
||||
response.data(), response.size());
|
||||
ESP_LOGI(kTag, "cgdcont query resp=%s", response.data());
|
||||
response.fill('\0');
|
||||
SendCommand("AT+CGACT?", "+CGACT", 2000,
|
||||
response.data(), response.size());
|
||||
ESP_LOGI(kTag, "cgact query resp=%s", response.data());
|
||||
|
||||
std::array<char, 64> probe{};
|
||||
bool dialed = false;
|
||||
bool used_cgdata_fallback = false;
|
||||
|
||||
// 路径1: ATD拨号
|
||||
probe.fill('\0');
|
||||
dialed = SendCommand("ATD*99#", "CONNECT", 30000,
|
||||
probe.data(), probe.size());
|
||||
ESP_LOGI(kTag, "ATD*99# ret=%d resp=[%s]",
|
||||
dialed ? 1 : 0, probe.data());
|
||||
if (!dialed) {
|
||||
probe.fill('\0');
|
||||
dialed = SendCommand("ATD*99***1#", "CONNECT", 30000,
|
||||
probe.data(), probe.size());
|
||||
ESP_LOGI(kTag, "ATD*99***1# ret=%d resp=[%s]",
|
||||
dialed ? 1 : 0, probe.data());
|
||||
}
|
||||
|
||||
// ATD全部失败 → 切换CGDATA fallback
|
||||
if (!dialed)
|
||||
{
|
||||
ESP_LOGW(kTag, "ATD commands rejected by modem, fallback to AT+CGDATA");
|
||||
used_cgdata_fallback = true;
|
||||
probe.fill('\0');
|
||||
// CGDATA命令:不等待CONNECT,只等待OK
|
||||
dialed = SendCommand("AT+CGDATA=\"PPP\",1", "OK", 15000,
|
||||
probe.data(), probe.size());
|
||||
ESP_LOGI(kTag, "AT+CGDATA=\"PPP\",1 ret=%d resp=[%s]",
|
||||
dialed ? 1 : 0, probe.data());
|
||||
if(!dialed)
|
||||
{
|
||||
ESP_LOGE(kTag, "ATD and CGDATA both failed, hard power cycle modem");
|
||||
PowerOff();
|
||||
vTaskDelay(pdMS_TO_TICKS(2000));
|
||||
PowerOn();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
ESP_LOGI(kTag, "dial accepted (%s path), observing PPP data stream",
|
||||
used_cgdata_fallback ? "CGDATA" : "ATD");
|
||||
|
||||
bool saw_bytes = false;
|
||||
for (int i = 0; i < 150 && !saw_bytes && !stop_requested_.load(); ++i) {
|
||||
uint8_t scratch[64] = {};
|
||||
const int n = uart_read_bytes(
|
||||
kUart, scratch, sizeof(scratch), pdMS_TO_TICKS(100));
|
||||
if (n > 0) {
|
||||
saw_bytes = true;
|
||||
ESP_LOGI(kTag, "data-mode first rx=%d %02x %02x %02x %02x",
|
||||
n, scratch[0], scratch[1], scratch[2], scratch[3]);
|
||||
}
|
||||
}
|
||||
|
||||
if (!saw_bytes) {
|
||||
ESP_LOGE(kTag,
|
||||
"dial returned ok but no PPP bytes: "
|
||||
"check ML307 TX 4.3V level / power supply");
|
||||
|
||||
// 尝试 +++ 退出PPP数据模式,再复位
|
||||
ESP_LOGI(kTag, "try send +++ to escape ppp data mode");
|
||||
uart_flush_input(kUart);
|
||||
vTaskDelay(pdMS_TO_TICKS(1000)); // 静默至少1s,+++时序硬性要求
|
||||
uart_write_bytes(kUart, "+++", 3);
|
||||
uart_wait_tx_done(kUart, pdMS_TO_TICKS(500));
|
||||
vTaskDelay(pdMS_TO_TICKS(500));
|
||||
|
||||
// 丢弃逃逸期间收到的二进制垃圾
|
||||
uint8_t trash[128];
|
||||
uart_read_bytes(kUart, trash, sizeof(trash), pdMS_TO_TICKS(200));
|
||||
|
||||
ESP_LOGI(kTag, "escape done, power‑cycle modem");
|
||||
PowerOff();
|
||||
vTaskDelay(pdMS_TO_TICKS(2000));
|
||||
PowerOn();
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
bool Ml307Transport::CreatePppNetif()
|
||||
{
|
||||
esp_netif_inherent_config_t base =
|
||||
ESP_NETIF_INHERENT_DEFAULT_PPP();
|
||||
base.if_desc = "ml307_ppp";
|
||||
base.route_prio = 20;
|
||||
driver_config_ = {};
|
||||
driver_config_.handle = this;
|
||||
driver_config_.transmit = &Ml307Transport::Transmit;
|
||||
const esp_netif_config_t config = {
|
||||
.base = &base,
|
||||
.driver = &driver_config_,
|
||||
.stack = ESP_NETIF_NETSTACK_DEFAULT_PPP,
|
||||
};
|
||||
|
||||
netif_ = esp_netif_new(&config);
|
||||
if (netif_ == nullptr) {
|
||||
return false;
|
||||
}
|
||||
if (esp_event_handler_instance_register(
|
||||
IP_EVENT,
|
||||
ESP_EVENT_ANY_ID,
|
||||
&Ml307Transport::IpEventHandler,
|
||||
this,
|
||||
&ip_handler_) != ESP_OK) {
|
||||
esp_netif_destroy(netif_);
|
||||
netif_ = nullptr;
|
||||
return false;
|
||||
}
|
||||
esp_netif_action_start(netif_, nullptr, 0, nullptr);
|
||||
esp_netif_action_connected(netif_, nullptr, 0, nullptr);
|
||||
return true;
|
||||
}
|
||||
|
||||
void Ml307Transport::RunPpp()
|
||||
{
|
||||
ESP_LOGI(kTag,"RunPpp PPP main loop enter");
|
||||
esp_err_t ret=0;
|
||||
while (!stop_requested_.load() && !ppp_lost_.load()) {
|
||||
const int received = uart_read_bytes(
|
||||
kUart,
|
||||
ppp_buffer_.data(),
|
||||
ppp_buffer_.size(),
|
||||
pdMS_TO_TICKS(100));
|
||||
|
||||
if (received > 0 && netif_ != nullptr) {
|
||||
// 2026-9-19 ckkj diag: 打印 PPP 接收帧前 8 字节,确认模组是否回包。
|
||||
ESP_LOGI(kTag, "ppp rx len=%d %02x %02x %02x %02x %02x %02x %02x %02x",
|
||||
received,
|
||||
ppp_buffer_[0], ppp_buffer_[1], ppp_buffer_[2], ppp_buffer_[3],
|
||||
ppp_buffer_[4], ppp_buffer_[5], ppp_buffer_[6], ppp_buffer_[7]);/////
|
||||
ret=esp_netif_receive(
|
||||
netif_,
|
||||
ppp_buffer_.data(),
|
||||
static_cast<size_t>(received),
|
||||
nullptr);
|
||||
if (ret != ESP_OK) {
|
||||
//ppp_lost_.store(true);
|
||||
ESP_LOGW(kTag,"esp_netif_receive ret=%s drop frame",esp_err_to_name(ret));
|
||||
}
|
||||
}
|
||||
}
|
||||
ESP_LOGI(kTag,"RunPpp PPP main loop exit stop_req=%d ppp_lost=%d",
|
||||
stop_requested_.load(),ppp_lost_.load());
|
||||
}
|
||||
|
||||
void Ml307Transport::CleanupPpp()
|
||||
{
|
||||
if (netif_ != nullptr) {
|
||||
esp_netif_action_disconnected(netif_, nullptr, 0, nullptr);
|
||||
esp_netif_action_stop(netif_, nullptr, 0, nullptr);
|
||||
}
|
||||
if (ip_handler_ != nullptr) {
|
||||
esp_event_handler_instance_unregister(
|
||||
IP_EVENT, ESP_EVENT_ANY_ID, ip_handler_);
|
||||
ip_handler_ = nullptr;
|
||||
}
|
||||
if (netif_ != nullptr) {
|
||||
esp_netif_destroy(netif_);
|
||||
netif_ = nullptr;
|
||||
}
|
||||
portENTER_CRITICAL(&state_lock_);
|
||||
link_info_.online = false;
|
||||
link_info_.ipv4.fill('\0');
|
||||
portEXIT_CRITICAL(&state_lock_);
|
||||
}
|
||||
|
||||
bool Ml307Transport::SendCommand(
|
||||
const char* command,
|
||||
const char* expected,
|
||||
uint32_t timeout_ms,
|
||||
char* response,
|
||||
size_t response_capacity)
|
||||
{
|
||||
if (!uart_installed_ || command == nullptr || expected == nullptr) {
|
||||
return false;
|
||||
}
|
||||
uart_flush_input(kUart);
|
||||
char outgoing[160]{};
|
||||
const int outgoing_size =
|
||||
std::snprintf(outgoing, sizeof(outgoing), "%s\r\n", command);
|
||||
if (outgoing_size <= 0 ||
|
||||
outgoing_size >= static_cast<int>(sizeof(outgoing)) ||
|
||||
uart_write_bytes(kUart, outgoing, outgoing_size) != outgoing_size ||
|
||||
uart_wait_tx_done(kUart, pdMS_TO_TICKS(500)) != ESP_OK) {
|
||||
return false;
|
||||
}
|
||||
|
||||
std::array<char, kAtResponseCapacity> local{};
|
||||
size_t used = 0;
|
||||
uint32_t waited = 0;
|
||||
while (waited < timeout_ms && !stop_requested_.load()) {
|
||||
const uint32_t slice = std::min<uint32_t>(100, timeout_ms - waited);
|
||||
const int received = uart_read_bytes(
|
||||
kUart,
|
||||
reinterpret_cast<uint8_t*>(local.data() + used),
|
||||
local.size() - used - 1,
|
||||
pdMS_TO_TICKS(slice));
|
||||
waited += slice;
|
||||
if (received > 0) {
|
||||
used += static_cast<size_t>(received);
|
||||
local[used] = '\0';
|
||||
if (std::strstr(local.data(), expected) != nullptr) {
|
||||
if (response != nullptr && response_capacity > 0) {
|
||||
std::strncpy(
|
||||
response, local.data(), response_capacity - 1);
|
||||
response[response_capacity - 1] = '\0';
|
||||
}
|
||||
return true;
|
||||
}
|
||||
if (std::strstr(local.data(), "ERROR") != nullptr ||
|
||||
used + 1 >= local.size()) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (response != nullptr && response_capacity > 0) {
|
||||
std::strncpy(response, local.data(), response_capacity - 1);
|
||||
response[response_capacity - 1] = '\0';
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
void Ml307Transport::UpdateModemInformation()
|
||||
{
|
||||
std::array<char, kAtResponseCapacity> response{};
|
||||
CellularLinkInfo next = GetLinkInfo();
|
||||
if (SendCommand(
|
||||
"AT+CSQ", "+CSQ:", 1200,
|
||||
response.data(), response.size())) {
|
||||
ParseMl307SignalQuality(response.data(), &next.csq);
|
||||
}
|
||||
if (SendCommand(
|
||||
"AT+CGSN", "OK", 1200,
|
||||
response.data(), response.size())) {
|
||||
CopyMl307ResponseLine(
|
||||
response.data(), "",
|
||||
next.imei.data(), next.imei.size());
|
||||
}
|
||||
if (SendCommand(
|
||||
"AT+COPS?", "+COPS:", 1500,
|
||||
response.data(), response.size())) {
|
||||
const char* quote = std::strchr(response.data(), '"');
|
||||
if (quote != nullptr) {
|
||||
CopyMl307ResponseLine(
|
||||
quote, "",
|
||||
next.operator_name.data(),
|
||||
next.operator_name.size());
|
||||
}
|
||||
}
|
||||
portENTER_CRITICAL(&state_lock_);
|
||||
link_info_ = next;
|
||||
portEXIT_CRITICAL(&state_lock_);
|
||||
}
|
||||
|
||||
void Ml307Transport::Publish(
|
||||
const CellularTransportEvent& event)
|
||||
{
|
||||
portENTER_CRITICAL(&state_lock_);
|
||||
ICellularTransportObserver* const observer = observer_;
|
||||
portEXIT_CRITICAL(&state_lock_);
|
||||
if (observer != nullptr) {
|
||||
observer->OnCellularTransportEvent(event);
|
||||
}
|
||||
}
|
||||
|
||||
void Ml307Transport::SetDisconnected(uint16_t reason)
|
||||
{
|
||||
portENTER_CRITICAL(&state_lock_);
|
||||
link_info_.online = false;
|
||||
link_info_.ipv4.fill('\0');
|
||||
portEXIT_CRITICAL(&state_lock_);
|
||||
Publish({CellularTransportEventType::kDisconnected, reason});
|
||||
}
|
||||
|
||||
} // namespace borla
|
||||
93
main/platform/borla_s3/ml307_transport.h
Normal file
93
main/platform/borla_s3/ml307_transport.h
Normal file
@@ -0,0 +1,93 @@
|
||||
#pragma once
|
||||
|
||||
#include "connectivity/cellular_transport.h"
|
||||
|
||||
#include <array>
|
||||
#include <atomic>
|
||||
#include <functional>
|
||||
#include <driver/uart.h>
|
||||
#include <esp_event.h>
|
||||
#include <esp_netif.h>
|
||||
#include <freertos/FreeRTOS.h>
|
||||
#include <freertos/portmacro.h>
|
||||
#include <freertos/semphr.h>
|
||||
#include <freertos/task.h>
|
||||
|
||||
namespace borla {
|
||||
|
||||
class Ml307Transport final : public ICellularTransport {
|
||||
public:
|
||||
// 2026-9-4 ckkj add 注入模组供电开关(EN_4G);nullptr 表示模组常供电。
|
||||
void SetPowerControl(std::function<void(bool)> control)
|
||||
{
|
||||
power_control_ = std::move(control);
|
||||
}/////
|
||||
bool Start(ICellularTransportObserver& observer) override;
|
||||
void Stop() override;
|
||||
//bool ProbePresent() override;
|
||||
CellularProbeResult ProbePresent() override;
|
||||
CellularLinkInfo GetLinkInfo() const override;
|
||||
|
||||
private:
|
||||
static constexpr uart_port_t kUart = UART_NUM_1;
|
||||
static constexpr uint32_t kTaskStackDepth = 4096;
|
||||
static constexpr size_t kAtResponseCapacity = 256;//512;
|
||||
static constexpr size_t kPppReadBufferSize = 1536;
|
||||
static constexpr size_t kProbeUartRxBufferSize = 512;
|
||||
static constexpr size_t kPppUartRxBufferSize = 4096;
|
||||
static constexpr size_t kPppUartTxBufferSize = 2048;
|
||||
|
||||
static void TaskEntry(void* context);
|
||||
static esp_err_t Transmit(
|
||||
void* handle,
|
||||
void* buffer,
|
||||
size_t length);
|
||||
static void IpEventHandler(
|
||||
void* context,
|
||||
esp_event_base_t event_base,
|
||||
int32_t event_id,
|
||||
void* event_data);
|
||||
|
||||
void Run();
|
||||
void PowerOn();
|
||||
void PowerOff();///2026-9-4 ckkj add
|
||||
bool InitializeUart(size_t rx_buffer_size, size_t tx_buffer_size);
|
||||
void CleanupUart();
|
||||
bool DetectAndConfigure();
|
||||
bool WaitForRegistration();
|
||||
bool Dial();
|
||||
bool CreatePppNetif();
|
||||
void RunPpp();
|
||||
void CleanupPpp();
|
||||
bool SendCommand(
|
||||
const char* command,
|
||||
const char* expected,
|
||||
uint32_t timeout_ms,
|
||||
char* response = nullptr,
|
||||
size_t response_capacity = 0);
|
||||
void UpdateModemInformation();
|
||||
void Publish(const CellularTransportEvent& event);
|
||||
void SetDisconnected(uint16_t reason);
|
||||
|
||||
mutable portMUX_TYPE state_lock_ = portMUX_INITIALIZER_UNLOCKED;
|
||||
ICellularTransportObserver* observer_ = nullptr;
|
||||
CellularLinkInfo link_info_{};
|
||||
std::atomic<bool> stop_requested_{false};
|
||||
std::atomic<bool> running_{false};
|
||||
std::atomic<bool> ppp_lost_{false};
|
||||
std::atomic<TaskHandle_t> task_{nullptr};
|
||||
std::function<void(bool)> power_control_;//2026-9-4 ckkj add
|
||||
std::atomic<bool> powered_{false};//2026-9-4 ckkj add 模组是否供电
|
||||
StaticTask_t task_control_{};
|
||||
std::array<StackType_t, kTaskStackDepth> task_stack_{};
|
||||
SemaphoreHandle_t stopped_ = nullptr;
|
||||
StaticSemaphore_t stopped_control_{};
|
||||
|
||||
esp_netif_t* netif_ = nullptr;
|
||||
esp_event_handler_instance_t ip_handler_ = nullptr;
|
||||
esp_netif_driver_ifconfig_t driver_config_{};
|
||||
bool uart_installed_ = false;
|
||||
std::array<uint8_t, kPppReadBufferSize> ppp_buffer_{};
|
||||
};
|
||||
|
||||
} // namespace borla
|
||||
244
main/platform/borla_s3/tca9555.cc
Normal file
244
main/platform/borla_s3/tca9555.cc
Normal file
@@ -0,0 +1,244 @@
|
||||
#include "platform/borla_s3/tca9555.h"
|
||||
#include "platform/borla_s3/i2c_bus.h"
|
||||
#include <esp_log.h>
|
||||
#include <cstring>
|
||||
|
||||
namespace borla {
|
||||
namespace {
|
||||
constexpr const char* kTag = "TCA9555";
|
||||
|
||||
}
|
||||
|
||||
TCA9555::TCA9555(BorlaS3I2cBus& bus): bus_ref_(bus)
|
||||
{}
|
||||
|
||||
esp_err_t TCA9555::Init()
|
||||
{
|
||||
i2c_mtx_ = xSemaphoreCreateMutex();
|
||||
if(i2c_mtx_ == nullptr){
|
||||
ESP_LOGE(kTag, "create mutex fail");
|
||||
return ESP_ERR_NO_MEM;
|
||||
}
|
||||
|
||||
bus_ = bus_ref_.Handle();
|
||||
if (!bus_) {
|
||||
ESP_LOGE(kTag, "I2C bus handle null");
|
||||
return ESP_ERR_INVALID_ARG;
|
||||
}
|
||||
|
||||
// 挂载TCA设备到I2C总线
|
||||
i2c_device_config_t dev_cfg = {
|
||||
.dev_addr_length = I2C_ADDR_BIT_LEN_7,
|
||||
.device_address = TCA9555_ADDR,
|
||||
.scl_speed_hz = 100000,
|
||||
.scl_wait_us = 0, // 使用驱动默认超时
|
||||
.flags={.disable_ack_check=0}, // 开启ACK校验(推荐默认)
|
||||
};
|
||||
esp_err_t ret = i2c_master_bus_add_device(bus_, &dev_cfg, &dev_handle_);
|
||||
if(ret != ESP_OK)
|
||||
{
|
||||
ESP_LOGE(kTag, "TCA9555 add iic fail");
|
||||
// i2c_del_master_bus(bus_);
|
||||
// bus_ = nullptr;
|
||||
return ret;
|
||||
}
|
||||
|
||||
// 3. 配置Port0方向:P0.0~P0.7全部设为输出(bit=0输出)
|
||||
// LEDA(0), SC_RESET(1), ADD_IO(2), OV_RESET(3), FLASH(6), PWDN(7)
|
||||
ret = write_reg(TCA9555_REG_CFG0, 0x00);
|
||||
if(ret != ESP_OK) {
|
||||
ESP_LOGI(kTag, "SDA(GPIO%d)=%d SCL(GPIO%d)=%d (1=high/normal, 0=low/bad)",
|
||||
TCA_SDA_GPIO, gpio_get_level(TCA_SDA_GPIO),
|
||||
TCA_SCL_GPIO, gpio_get_level(TCA_SCL_GPIO));
|
||||
return ret;
|
||||
}
|
||||
|
||||
// 4. 配置Port1方向:仅KEY(P1.0)为输入(bit=1),P1.1~P1.7全部输出(bit=0)
|
||||
// KEY(0,输入), MCU_VCC(2), 5V_EN(3), PREP_VCC(5), IMU_INT(6), PA_CTL(7)
|
||||
ret = write_reg(TCA9555_REG_CFG1, (1U << TCA_P1_KEY));// | (1U << TCA_P1_IMU_INT));
|
||||
if(ret != ESP_OK) {
|
||||
ESP_LOGE(kTag, "CFG1 write fail: %s", esp_err_to_name(ret));
|
||||
return ret;
|
||||
}
|
||||
|
||||
// 5. 极性反转寄存器清零(不反转)
|
||||
write_reg(TCA9555_REG_POL0, 0x00);
|
||||
write_reg(TCA9555_REG_POL1, 0x00);
|
||||
|
||||
// 6. 输出寄存器清零,并检查返回值
|
||||
ret = p0_write_all(0x00);
|
||||
if(ret != ESP_OK) {
|
||||
ESP_LOGE(kTag, "OUT0 write fail: %s", esp_err_to_name(ret));
|
||||
return ret;
|
||||
}
|
||||
ret = p1_write_all(0x00);
|
||||
if(ret != ESP_OK) {
|
||||
ESP_LOGE(kTag, "OUT1 write fail: %s", esp_err_to_name(ret));
|
||||
return ret;
|
||||
}
|
||||
|
||||
ESP_LOGI(kTag, "TCA9555 addr 0x%02x init ok", TCA9555_ADDR);
|
||||
return ESP_OK;
|
||||
}
|
||||
|
||||
// 底层写寄存器
|
||||
esp_err_t TCA9555::write_reg(uint8_t reg, uint8_t data)
|
||||
{
|
||||
if (dev_handle_ == nullptr || i2c_mtx_ == nullptr) {
|
||||
return ESP_ERR_INVALID_STATE;
|
||||
}
|
||||
if(xSemaphoreTake(i2c_mtx_, pdMS_TO_TICKS(100)) != pdTRUE)
|
||||
{
|
||||
return ESP_ERR_TIMEOUT;
|
||||
}
|
||||
uint8_t buf[2] = {reg, data};
|
||||
esp_err_t ret = i2c_master_transmit(dev_handle_, buf, sizeof(buf), pdMS_TO_TICKS(100));
|
||||
xSemaphoreGive(i2c_mtx_);
|
||||
return ret;
|
||||
}
|
||||
|
||||
// 底层读寄存器
|
||||
esp_err_t TCA9555::read_reg(uint8_t reg, uint8_t* data)
|
||||
{
|
||||
if (dev_handle_ == nullptr || i2c_mtx_ == nullptr) {
|
||||
return ESP_ERR_INVALID_STATE;
|
||||
}
|
||||
if(xSemaphoreTake(i2c_mtx_, pdMS_TO_TICKS(100)) != pdTRUE)
|
||||
{
|
||||
return ESP_ERR_TIMEOUT;
|
||||
}
|
||||
uint8_t buf = reg;
|
||||
esp_err_t ret = i2c_master_transmit_receive(dev_handle_, &buf, 1, data, 1, pdMS_TO_TICKS(100));
|
||||
xSemaphoreGive(i2c_mtx_);
|
||||
return ret;
|
||||
}
|
||||
|
||||
esp_err_t TCA9555::deinit(void)
|
||||
{
|
||||
if(dev_handle_)
|
||||
{
|
||||
i2c_master_bus_rm_device(dev_handle_);
|
||||
dev_handle_ = nullptr;
|
||||
}
|
||||
if(i2c_mtx_)
|
||||
{
|
||||
vSemaphoreDelete(i2c_mtx_);
|
||||
i2c_mtx_ = nullptr;
|
||||
}
|
||||
bus_ = nullptr;
|
||||
return ESP_OK;
|
||||
}
|
||||
|
||||
// Port0 置1
|
||||
esp_err_t TCA9555::p0_set_bit(uint8_t bit)
|
||||
{
|
||||
if(bit >= 8) return ESP_ERR_INVALID_ARG;
|
||||
uint8_t val;
|
||||
esp_err_t ret = read_reg(TCA9555_REG_OUT0, &val);
|
||||
if(ret != ESP_OK) {
|
||||
ESP_LOGE(kTag, "p0_set_bit read OUT0 fail: %s", esp_err_to_name(ret));
|
||||
return ret;
|
||||
}
|
||||
val |= (1U << bit);
|
||||
return write_reg(TCA9555_REG_OUT0, val);
|
||||
}
|
||||
// Port0 清0
|
||||
esp_err_t TCA9555::p0_clr_bit(uint8_t bit)
|
||||
{
|
||||
if(bit >= 8) return ESP_ERR_INVALID_ARG;
|
||||
uint8_t val;
|
||||
esp_err_t ret = read_reg(TCA9555_REG_OUT0, &val);
|
||||
if(ret != ESP_OK) {
|
||||
ESP_LOGE(kTag, "p0_clr_bit read OUT0 fail: %s", esp_err_to_name(ret));
|
||||
return ret;
|
||||
}
|
||||
val &= ~(1U << bit);
|
||||
return write_reg(TCA9555_REG_OUT0, val);
|
||||
}
|
||||
esp_err_t TCA9555::p0_write_all(uint8_t val)
|
||||
{
|
||||
return write_reg(TCA9555_REG_OUT0, val);
|
||||
}
|
||||
|
||||
// Port1 置1
|
||||
esp_err_t TCA9555::p1_set_bit(uint8_t bit)
|
||||
{
|
||||
if(bit >= 8) return ESP_ERR_INVALID_ARG;
|
||||
uint8_t val = 0;
|
||||
esp_err_t ret = read_reg(TCA9555_REG_OUT1, &val);
|
||||
if(ret != ESP_OK) {
|
||||
ESP_LOGE(kTag, "p1_set_bit(%u) read OUT1 fail: %s", bit, esp_err_to_name(ret));
|
||||
return ret;
|
||||
}
|
||||
const uint8_t old_val = val;
|
||||
val |= (1U << bit);
|
||||
ret = write_reg(TCA9555_REG_OUT1, val);
|
||||
if(ret != ESP_OK) {
|
||||
ESP_LOGE(kTag, "p1_set_bit(%u) write OUT1 fail: %s", bit, esp_err_to_name(ret));
|
||||
return ret;
|
||||
}
|
||||
|
||||
uint8_t verify = 0;
|
||||
if (read_reg(TCA9555_REG_OUT1, &verify) == ESP_OK &&
|
||||
(verify & (1U << bit)) == 0) {
|
||||
ESP_LOGE(kTag, "p1_set_bit(%u) verify FAIL: wrote 0x%02x read 0x%02x "
|
||||
"(bit may be input in CFG1)", bit, val, verify);
|
||||
return ESP_FAIL;
|
||||
}
|
||||
ESP_LOGI(kTag, "p1_set_bit(%u) OK OUT1 0x%02x->0x%02x", bit, old_val, verify);
|
||||
return ESP_OK;
|
||||
}
|
||||
// Port1 清0
|
||||
esp_err_t TCA9555::p1_clr_bit(uint8_t bit)
|
||||
{
|
||||
if(bit >= 8) return ESP_ERR_INVALID_ARG;
|
||||
uint8_t val;
|
||||
|
||||
esp_err_t ret = read_reg(TCA9555_REG_OUT1, &val);
|
||||
if(ret != ESP_OK) {
|
||||
ESP_LOGE(kTag, "p1_clr_bit read OUT1 fail: %s", esp_err_to_name(ret));
|
||||
return ret;
|
||||
}
|
||||
val &= ~(1U << bit);
|
||||
return write_reg(TCA9555_REG_OUT1, val);
|
||||
}
|
||||
esp_err_t TCA9555::p1_write_all(uint8_t val)
|
||||
{
|
||||
return write_reg(TCA9555_REG_OUT1, val);
|
||||
}
|
||||
|
||||
esp_err_t TCA9555::read_p0_input(uint8_t* val)
|
||||
{
|
||||
if(val == nullptr) return ESP_ERR_INVALID_ARG;
|
||||
return read_reg(TCA9555_REG_IN0, val);
|
||||
}
|
||||
esp_err_t TCA9555::read_p1_input(uint8_t* val)
|
||||
{
|
||||
if(val == nullptr) return ESP_ERR_INVALID_ARG;
|
||||
return read_reg(TCA9555_REG_IN1, val);
|
||||
}
|
||||
|
||||
esp_err_t TCA9555::set_pin(uint16_t pin_code)
|
||||
{
|
||||
uint8_t port = TCA_GET_PORT(pin_code);//static_cast<uint8_t>((pin_code >> 8) & 0xFFU);
|
||||
uint8_t bit = TCA_GET_BIT(pin_code);//static_cast<uint8_t>(pin_code & 0xFFU);
|
||||
if(port == 0)
|
||||
return p0_set_bit(bit);
|
||||
else if(port == 1)
|
||||
return p1_set_bit(bit);
|
||||
return ESP_ERR_INVALID_ARG;
|
||||
}
|
||||
|
||||
esp_err_t TCA9555::clr_pin(uint16_t pin_code)
|
||||
{
|
||||
uint8_t port = TCA_GET_PORT(pin_code);
|
||||
uint8_t bit = TCA_GET_BIT(pin_code);
|
||||
if(port == 0)
|
||||
return p0_clr_bit(bit);
|
||||
else if(port == 1)
|
||||
return p1_clr_bit(bit);
|
||||
return ESP_ERR_INVALID_ARG;
|
||||
}
|
||||
|
||||
|
||||
} // borla
|
||||
122
main/platform/borla_s3/tca9555.h
Normal file
122
main/platform/borla_s3/tca9555.h
Normal file
@@ -0,0 +1,122 @@
|
||||
#pragma once
|
||||
#include "driver/gpio.h"
|
||||
#include <driver/i2c_master.h>
|
||||
#include <esp_err.h>
|
||||
#include <cstdint>
|
||||
#include "freertos/FreeRTOS.h"
|
||||
namespace borla
|
||||
{
|
||||
class BorlaS3I2cBus;
|
||||
// 硬件引脚定义(ESP32-S3 I2C总线)
|
||||
#define TCA_I2C_NUM I2C_NUM_0
|
||||
#define TCA_SCL_GPIO GPIO_NUM_1
|
||||
#define TCA_SDA_GPIO GPIO_NUM_2
|
||||
// 端口定义 Port0 / Port1
|
||||
enum TCA_PORT : uint8_t
|
||||
{
|
||||
PORT0 = 0,
|
||||
PORT1 = 1,
|
||||
};
|
||||
// TCA9555 寄存器定义
|
||||
enum TCA9555_REG : uint8_t
|
||||
{
|
||||
TCA9555_REG_IN0 = 0x00, // Port0 输入寄存器
|
||||
TCA9555_REG_IN1 = 0x01, // Port1 输入寄存器
|
||||
TCA9555_REG_OUT0 = 0x02, // Port0 输出寄存器
|
||||
TCA9555_REG_OUT1 = 0x03, // Port1 输出寄存器
|
||||
TCA9555_REG_POL0 = 0x04, // Port0 极性反转
|
||||
TCA9555_REG_POL1 = 0x05, // Port1 极性反转
|
||||
TCA9555_REG_CFG0 = 0x06, // Port0 方向配置 1=输入 0=输出
|
||||
TCA9555_REG_CFG1 = 0x07, // Port1 方向配置
|
||||
};
|
||||
|
||||
// TCA9555 硬件地址(原理图 IIC ADDR:0x20)
|
||||
constexpr uint8_t TCA9555_ADDR = 0x20;
|
||||
|
||||
// 原理图引脚映射宏
|
||||
// Port0 P0~P7
|
||||
#define TCA_P0_LEDA 0U
|
||||
#define TCA_P0_SC_RESET 1U
|
||||
#define TCA_P0_ADD_IO 2U
|
||||
#define TCA_P0_OV_RESET 3U
|
||||
#define TCA_P0_FLASH 6U
|
||||
#define TCA_P0_PWDN 7U
|
||||
// Port1 P10~P17
|
||||
#define TCA_P1_KEY 0U // 输入引脚 P10 Port1 bit0
|
||||
|
||||
#define TCA_P1_MCU_VCC 2U
|
||||
#define TCA_P1_5V_EN 3U
|
||||
#define TCA_P1_PREP_VCC 5U
|
||||
#define TCA_P1_IMU_INT 6U
|
||||
#define TCA_P1_PA_CTL 7U
|
||||
//tcap555扩展芯片引脚配置接口
|
||||
constexpr uint16_t TCA_IO(uint8_t port, uint8_t bit)
|
||||
{
|
||||
return (static_cast<uint16_t>(port) << 8) | static_cast<uint16_t>(bit);
|
||||
}
|
||||
constexpr uint8_t TCA_GET_PORT(uint16_t pin_code)
|
||||
{
|
||||
return static_cast<uint8_t>((pin_code >> 8) & 0xFFU);
|
||||
}
|
||||
constexpr uint8_t TCA_GET_BIT(uint16_t pin_code)
|
||||
{
|
||||
return static_cast<uint8_t>(pin_code & 0xFFU);
|
||||
}
|
||||
|
||||
// PORT0 P00~P07
|
||||
constexpr uint16_t SC_LEDA = TCA_IO(PORT0, TCA_P0_LEDA);
|
||||
constexpr uint16_t SC_RESET = TCA_IO(PORT0, TCA_P0_SC_RESET);
|
||||
constexpr uint16_t EN_4G = TCA_IO(PORT0, TCA_P0_ADD_IO); // 4G
|
||||
constexpr uint16_t OV_RESET = TCA_IO(PORT0, TCA_P0_OV_RESET);
|
||||
constexpr uint16_t OV_FLASH = TCA_IO(PORT0, TCA_P0_FLASH);
|
||||
constexpr uint16_t OV_PWDN = TCA_IO(PORT0, TCA_P0_PWDN);
|
||||
|
||||
// PORT1 P10~P17
|
||||
constexpr uint16_t KEY = TCA_IO(PORT1, TCA_P1_KEY); // 按键输入
|
||||
constexpr uint16_t MCU_VCC_CTL = TCA_IO(PORT1, TCA_P1_MCU_VCC);
|
||||
constexpr uint16_t V5_EN = TCA_IO(PORT1, TCA_P1_5V_EN);
|
||||
constexpr uint16_t PREP_VCC_CTL = TCA_IO(PORT1, TCA_P1_PREP_VCC);
|
||||
constexpr uint16_t IMU_INT = TCA_IO(PORT1, TCA_P1_IMU_INT);
|
||||
constexpr uint16_t PA_CTL = TCA_IO(PORT1, TCA_P1_PA_CTL);
|
||||
|
||||
class TCA9555
|
||||
{
|
||||
public:
|
||||
SemaphoreHandle_t i2c_mtx_ = nullptr;
|
||||
// 传入已初始化完成的I2C总线句柄
|
||||
explicit TCA9555(BorlaS3I2cBus &bus);
|
||||
~TCA9555() = default;
|
||||
|
||||
// 初始化:配置全部端口默认输出0(外设断电)
|
||||
esp_err_t Init();
|
||||
// 底层寄存器读写
|
||||
esp_err_t read_reg(uint8_t reg, uint8_t* data);
|
||||
esp_err_t write_reg(uint8_t reg, uint8_t data);
|
||||
|
||||
// 释放I2C资源
|
||||
esp_err_t deinit(void);
|
||||
|
||||
// Port0 位操作 P0~P7
|
||||
esp_err_t p0_set_bit(uint8_t bit); // 置高
|
||||
esp_err_t p0_clr_bit(uint8_t bit); // 置低
|
||||
esp_err_t p0_write_all(uint8_t val); // 整端口输出
|
||||
|
||||
// Port1 位操作 P10~P17
|
||||
esp_err_t p1_set_bit(uint8_t bit);
|
||||
esp_err_t p1_clr_bit(uint8_t bit);
|
||||
esp_err_t p1_write_all(uint8_t val);
|
||||
|
||||
// 读取输入电平
|
||||
esp_err_t read_p0_input(uint8_t* val);
|
||||
esp_err_t read_p1_input(uint8_t* val);
|
||||
|
||||
esp_err_t set_pin(uint16_t pin_code);
|
||||
esp_err_t clr_pin(uint16_t pin_code);
|
||||
private:
|
||||
|
||||
i2c_master_bus_handle_t bus_ = nullptr;
|
||||
i2c_master_dev_handle_t dev_handle_ = nullptr;
|
||||
BorlaS3I2cBus &bus_ref_;
|
||||
};
|
||||
|
||||
} // namespace borla
|
||||
241
main/platform/borla_s3/ws2812_led.cc
Normal file
241
main/platform/borla_s3/ws2812_led.cc
Normal file
@@ -0,0 +1,241 @@
|
||||
#include "platform/borla_s3/ws2812_led.h"
|
||||
|
||||
#include <esp_err.h>
|
||||
#include <esp_log.h>
|
||||
#include <led_strip_rmt.h>
|
||||
|
||||
#include <algorithm>
|
||||
|
||||
namespace borla {
|
||||
namespace {
|
||||
|
||||
constexpr const char* kTag = "Ws2812Led2";
|
||||
constexpr uint32_t kAnimationTickMs = 30;
|
||||
|
||||
} // namespace
|
||||
|
||||
Ws2812Led::~Ws2812Led()
|
||||
{
|
||||
if (timer_ != nullptr) {
|
||||
esp_timer_stop(timer_);
|
||||
esp_timer_delete(timer_);
|
||||
}
|
||||
if (strip_ != nullptr) {
|
||||
led_strip_clear(strip_);
|
||||
led_strip_del(strip_);
|
||||
}
|
||||
}
|
||||
|
||||
bool Ws2812Led::Initialize(gpio_num_t gpio)
|
||||
{
|
||||
led_strip_config_t strip_config = {};
|
||||
strip_config.strip_gpio_num = gpio;
|
||||
strip_config.max_leds = 1;
|
||||
strip_config.color_component_format = LED_STRIP_COLOR_COMPONENT_FMT_GRB;
|
||||
strip_config.led_model = LED_MODEL_WS2812;
|
||||
|
||||
led_strip_rmt_config_t rmt_config = {};
|
||||
rmt_config.resolution_hz = 10 * 1000 * 1000;
|
||||
|
||||
esp_err_t result =
|
||||
led_strip_new_rmt_device(&strip_config, &rmt_config, &strip_);
|
||||
if (result != ESP_OK) {
|
||||
ESP_LOGE(kTag, "failed to create LED strip: %s",
|
||||
esp_err_to_name(result));
|
||||
return false;
|
||||
}
|
||||
|
||||
const esp_timer_create_args_t timer_args = {
|
||||
.callback = &Ws2812Led::TimerCallback,
|
||||
.arg = this,
|
||||
.dispatch_method = ESP_TIMER_TASK,
|
||||
.name = "borla_led",
|
||||
.skip_unhandled_events = true,
|
||||
};
|
||||
result = esp_timer_create(&timer_args, &timer_);
|
||||
if (result != ESP_OK) {
|
||||
ESP_LOGE(kTag, "failed to create animation timer: %s",
|
||||
esp_err_to_name(result));
|
||||
led_strip_del(strip_);
|
||||
strip_ = nullptr;
|
||||
return false;
|
||||
}
|
||||
|
||||
result = led_strip_clear(strip_);
|
||||
if (result != ESP_OK) {
|
||||
ESP_LOGE(kTag, "failed to clear LED: %s", esp_err_to_name(result));
|
||||
return false;
|
||||
}
|
||||
|
||||
ESP_LOGI(kTag, "WS2812 initialized on GPIO%d", static_cast<int>(gpio));
|
||||
return true;
|
||||
}
|
||||
|
||||
void Ws2812Led::SetPattern(LedPattern pattern)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
if (strip_ == nullptr || timer_ == nullptr) {
|
||||
ESP_LOGW(kTag, "ignored LED pattern before initialization");
|
||||
return;
|
||||
}
|
||||
if (pattern == current_pattern_) {
|
||||
return;
|
||||
}
|
||||
|
||||
StopTimer();
|
||||
current_pattern_ = pattern;
|
||||
phase_ms_ = 0;
|
||||
Configure(pattern);
|
||||
|
||||
if (animation_ == Animation::kOff) {
|
||||
led_strip_clear(strip_);
|
||||
} else if (animation_ == Animation::kSteady) {
|
||||
Render(255);
|
||||
} else {
|
||||
Render(animation_ == Animation::kBlink ? 255 : 0);
|
||||
const esp_err_t result =
|
||||
esp_timer_start_periodic(timer_, kAnimationTickMs * 1000);
|
||||
if (result != ESP_OK) {
|
||||
ESP_LOGE(kTag, "failed to start animation: %s",
|
||||
esp_err_to_name(result));
|
||||
led_strip_clear(strip_);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void Ws2812Led::TimerCallback(void* context)
|
||||
{
|
||||
static_cast<Ws2812Led*>(context)->OnTimer();
|
||||
}
|
||||
|
||||
void Ws2812Led::OnTimer()
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
if (strip_ == nullptr || period_ms_ == 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
phase_ms_ = (phase_ms_ + kAnimationTickMs) % period_ms_;
|
||||
if (animation_ == Animation::kBlink) {
|
||||
Render(phase_ms_ < period_ms_ / 2 ? 255 : 0);
|
||||
return;
|
||||
}
|
||||
|
||||
if (animation_ == Animation::kBreathe) {
|
||||
const uint32_t half = std::max<uint32_t>(period_ms_ / 2, 1);
|
||||
const uint32_t distance =
|
||||
phase_ms_ <= half ? phase_ms_ : period_ms_ - phase_ms_;
|
||||
Render(static_cast<uint8_t>((distance * 255) / half));
|
||||
}
|
||||
}
|
||||
|
||||
void Ws2812Led::StopTimer()
|
||||
{
|
||||
const esp_err_t result = esp_timer_stop(timer_);
|
||||
if (result != ESP_OK && result != ESP_ERR_INVALID_STATE) {
|
||||
ESP_LOGW(kTag, "failed to stop animation: %s",
|
||||
esp_err_to_name(result));
|
||||
}
|
||||
}
|
||||
|
||||
void Ws2812Led::Render(uint8_t scale)
|
||||
{
|
||||
const uint8_t red =
|
||||
static_cast<uint8_t>((static_cast<uint16_t>(red_) * scale) / 255);
|
||||
const uint8_t green =
|
||||
static_cast<uint8_t>((static_cast<uint16_t>(green_) * scale) / 255);
|
||||
const uint8_t blue =
|
||||
static_cast<uint8_t>((static_cast<uint16_t>(blue_) * scale) / 255);
|
||||
led_strip_set_pixel(strip_, 0, red, green, blue);
|
||||
led_strip_refresh(strip_);
|
||||
}
|
||||
|
||||
void Ws2812Led::Configure(LedPattern pattern)
|
||||
{
|
||||
switch (pattern) {
|
||||
case LedPattern::kOff:
|
||||
animation_ = Animation::kOff;
|
||||
red_ = green_ = blue_ = 0;
|
||||
period_ms_ = 0;
|
||||
break;
|
||||
case LedPattern::kStarting:
|
||||
animation_ = Animation::kBreathe;
|
||||
red_ = 8;
|
||||
green_ = 2;
|
||||
blue_ = 0;
|
||||
period_ms_ = 1500;
|
||||
break;
|
||||
case LedPattern::kConnecting:
|
||||
animation_ = Animation::kBreathe;
|
||||
red_ = 0;
|
||||
green_ = 0;
|
||||
blue_ = 8;
|
||||
period_ms_ = 1000;
|
||||
break;
|
||||
case LedPattern::kIdle:
|
||||
animation_ = Animation::kBreathe;
|
||||
red_ = 8;
|
||||
green_ = 6;
|
||||
blue_ = 2;
|
||||
period_ms_ = 4000;
|
||||
break;
|
||||
case LedPattern::kListening:
|
||||
animation_ = Animation::kSteady;
|
||||
red_ = 16;
|
||||
green_ = 0;
|
||||
blue_ = 0;
|
||||
period_ms_ = 0;
|
||||
break;
|
||||
case LedPattern::kSpeaking:
|
||||
animation_ = Animation::kBreathe;
|
||||
red_ = 0;
|
||||
green_ = 8;
|
||||
blue_ = 0;
|
||||
period_ms_ = 1500;
|
||||
break;
|
||||
case LedPattern::kRinging:
|
||||
animation_ = Animation::kBlink;
|
||||
red_ = 12;
|
||||
green_ = 0;
|
||||
blue_ = 12;
|
||||
period_ms_ = 500;
|
||||
break;
|
||||
case LedPattern::kCalling:
|
||||
animation_ = Animation::kSteady;
|
||||
red_ = 0;
|
||||
green_ = 16;
|
||||
blue_ = 0;
|
||||
period_ms_ = 0;
|
||||
break;
|
||||
case LedPattern::kFriendMode:
|
||||
animation_ = Animation::kBreathe;
|
||||
red_ = 8;
|
||||
green_ = 0;
|
||||
blue_ = 12;
|
||||
period_ms_ = 800;
|
||||
break;
|
||||
case LedPattern::kProvisioning:
|
||||
animation_ = Animation::kBlink;
|
||||
red_ = 0;
|
||||
green_ = 8;
|
||||
blue_ = 8;
|
||||
period_ms_ = 500;
|
||||
break;
|
||||
case LedPattern::kUpgrading:
|
||||
animation_ = Animation::kBlink;
|
||||
red_ = 12;
|
||||
green_ = 8;
|
||||
blue_ = 0;
|
||||
period_ms_ = 200;
|
||||
break;
|
||||
case LedPattern::kError:
|
||||
animation_ = Animation::kBlink;
|
||||
red_ = 16;
|
||||
green_ = 0;
|
||||
blue_ = 0;
|
||||
period_ms_ = 100;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace borla
|
||||
49
main/platform/borla_s3/ws2812_led.h
Normal file
49
main/platform/borla_s3/ws2812_led.h
Normal file
@@ -0,0 +1,49 @@
|
||||
#pragma once
|
||||
|
||||
#include "core/runtime_state.h"
|
||||
|
||||
#include <driver/gpio.h>
|
||||
#include <esp_timer.h>
|
||||
#include <led_strip.h>
|
||||
|
||||
#include <cstdint>
|
||||
#include <mutex>
|
||||
|
||||
namespace borla {
|
||||
|
||||
class Ws2812Led final {
|
||||
public:
|
||||
Ws2812Led() = default;
|
||||
~Ws2812Led();
|
||||
|
||||
bool Initialize(gpio_num_t gpio);
|
||||
void SetPattern(LedPattern pattern);
|
||||
|
||||
private:
|
||||
enum class Animation : uint8_t {
|
||||
kOff,
|
||||
kSteady,
|
||||
kBlink,
|
||||
kBreathe,
|
||||
};
|
||||
|
||||
static void TimerCallback(void* context);
|
||||
|
||||
void OnTimer();
|
||||
void StopTimer();
|
||||
void Render(uint8_t scale);
|
||||
void Configure(LedPattern pattern);
|
||||
|
||||
std::mutex mutex_;
|
||||
led_strip_handle_t strip_ = nullptr;
|
||||
esp_timer_handle_t timer_ = nullptr;
|
||||
LedPattern current_pattern_ = LedPattern::kOff;
|
||||
Animation animation_ = Animation::kOff;
|
||||
uint8_t red_ = 0;
|
||||
uint8_t green_ = 0;
|
||||
uint8_t blue_ = 0;
|
||||
uint32_t period_ms_ = 0;
|
||||
uint32_t phase_ms_ = 0;
|
||||
};
|
||||
|
||||
} // namespace borla
|
||||
Reference in New Issue
Block a user