bolar_2 backup

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

135
main/ota/ota_endpoint.cc Normal file
View File

@@ -0,0 +1,135 @@
#include "ota/ota_endpoint.h"
#include <cstring>
namespace borla {
namespace {
constexpr const char kWildcardHost[] = "0.0.0.0";
constexpr size_t kWildcardHostLength = sizeof(kWildcardHost) - 1;
bool Contains(const char* haystack, const char* needle)
{
return haystack != nullptr && needle != nullptr &&
std::strstr(haystack, needle) != nullptr;
}
// Extract the host portion of "<scheme>://<host>[:port][/path]".
// Returns 0 when the URL has no scheme separator or an empty host.
size_t HostSpan(const char* url, const char** host_begin)
{
if (url == nullptr || host_begin == nullptr) {
return 0;
}
const char* separator = std::strstr(url, "://");
if (separator == nullptr) {
return 0;
}
const char* begin = separator + 3;
const char* cursor = begin;
while (*cursor != '\0' && *cursor != ':' && *cursor != '/') {
cursor++;
}
*host_begin = begin;
return static_cast<size_t>(cursor - begin);
}
} // namespace
bool IsRolloverEndpoint(const char* url)
{
if (url == nullptr || url[0] == '\0') {
return false;
}
if (Contains(url, ".lkall.com") &&
(Contains(url, "-dev.") || Contains(url, "-moe.") ||
Contains(url, "borlaws.lkall.com") ||
Contains(url, "borla-ota.lkall.com"))) {
return true;
}
return Contains(url, "192.168.1.121") ||
Contains(url, "117.50.44.247");
}
bool SubstituteWildcardHost(
const char* url,
const char* ota_url,
char* output,
size_t capacity)
{
if (url == nullptr || output == nullptr || capacity == 0) {
return false;
}
const char* wildcard = std::strstr(url, kWildcardHost);
if (wildcard == nullptr) {
return false;
}
const char* ota_host = nullptr;
const size_t ota_host_size = HostSpan(ota_url, &ota_host);
if (ota_host_size == 0 ||
(ota_host_size == kWildcardHostLength &&
std::strncmp(ota_host, kWildcardHost, kWildcardHostLength) == 0)) {
return false;
}
const size_t prefix_size = static_cast<size_t>(wildcard - url);
const char* suffix = wildcard + kWildcardHostLength;
const size_t suffix_size = std::strlen(suffix);
const size_t total = prefix_size + ota_host_size + suffix_size;
if (total >= capacity) {
return false;
}
std::memcpy(output, url, prefix_size);
std::memcpy(output + prefix_size, ota_host, ota_host_size);
std::memcpy(
output + prefix_size + ota_host_size, suffix, suffix_size);
output[total] = '\0';
return true;
}
bool ResolveRealtimeUrl(
const char* url,
const char* ota_url,
const char* default_url,
char* output,
size_t capacity)
{
if (output == nullptr || capacity == 0) {
return false;
}
const char* candidate = url;
if (candidate == nullptr || candidate[0] == '\0') {
candidate = nullptr;
}
if (candidate != nullptr) {
if (SubstituteWildcardHost(
candidate, ota_url, output, capacity)) {
// A substituted URL is by construction the reachable OTA host, so
// it is never treated as a rollover default.
return true;
}
if (std::strstr(candidate, kWildcardHost) != nullptr) {
// Wildcard host that could not be resolved is unusable.
candidate = nullptr;
}
}
if (candidate != nullptr && IsRolloverEndpoint(candidate)) {
candidate = nullptr;
}
if (candidate == nullptr) {
candidate = default_url;
}
if (candidate == nullptr || candidate[0] == '\0') {
return false;
}
const size_t size = std::strlen(candidate);
if (size >= capacity) {
return false;
}
std::memcpy(output, candidate, size + 1);
return true;
}
} // namespace borla

50
main/ota/ota_endpoint.h Normal file
View File

@@ -0,0 +1,50 @@
#pragma once
#include "protocol/websocket_transport.h"
#include <array>
#include <cstddef>
namespace borla {
// Endpoint block carried by the OTA check response. The OTA service is the
// only channel that can repoint a fielded device at a different realtime
// server, so the URL/token pair travels with the firmware manifest rather than
// with the realtime protocol itself.
struct OtaEndpointConfig {
std::array<char, kWebsocketUrlCapacity> url{};
std::array<char, kWebsocketTokenCapacity> token{};
bool has_url = false;
bool has_token = false;
bool HasAny() const { return has_url || has_token; }
};
// True for endpoints that ship as build/staging defaults. A saved value that
// matches one of these is treated as "not deliberately provisioned" and is
// replaced by the current default, so a device that once talked to a retired
// staging host recovers on its own instead of retrying it forever.
bool IsRolloverEndpoint(const char* url);
// Some deployments answer with a wildcard bind address in the websocket block.
// Substitute the host the OTA request itself was answered by, which is the
// only host the device is known to be able to reach.
// Returns false when `url` has no 0.0.0.0 host, when `ota_url` has no usable
// host, or when the result would not fit; `output` is only written on true.
bool SubstituteWildcardHost(
const char* url,
const char* ota_url,
char* output,
size_t capacity);
// Full resolution used by OtaService: applies SubstituteWildcardHost, then
// falls back to `default_url` when the result is a rollover endpoint.
// Returns false when nothing usable could be produced.
bool ResolveRealtimeUrl(
const char* url,
const char* ota_url,
const char* default_url,
char* output,
size_t capacity);
} // namespace borla

View File

@@ -0,0 +1,232 @@
#include "ota/ota_response_parser.h"
#include <algorithm>
#include <cctype>
#include <climits>
#include <cmath>
#include <cstring>
#include <cJSON.h>
namespace borla {
namespace {
const char* StringField(const cJSON* root, const char* name)
{
const cJSON* value =
cJSON_GetObjectItemCaseSensitive(root, name);
return cJSON_IsString(value) ? value->valuestring : nullptr;
}
bool CopyBounded(const char* source, char* output, size_t capacity)
{
if (source == nullptr || output == nullptr || capacity == 0) {
return false;
}
const size_t size = std::strlen(source);
if (size == 0 || size >= capacity) {
return false;
}
std::memcpy(output, source, size);
output[size] = '\0';
return true;
}
bool IsSafeUrl(const char* url, bool allow_insecure_http)
{
return url != nullptr &&
(std::strncmp(url, "https://", 8) == 0 ||
(allow_insecure_http &&
std::strncmp(url, "http://", 7) == 0));
}
int HexNibble(char value)
{
if (value >= '0' && value <= '9') {
return value - '0';
}
value = static_cast<char>(
std::tolower(static_cast<unsigned char>(value)));
return value >= 'a' && value <= 'f'
? value - 'a' + 10
: -1;
}
int NextVersionPart(const char** cursor)
{
const char* value = *cursor;
while (*value == 'v' || *value == 'V' ||
*value == '.' || *value == '-' ||
std::isspace(static_cast<unsigned char>(*value))) {
value++;
}
int part = 0;
while (std::isdigit(static_cast<unsigned char>(*value))) {
if (part <= (INT_MAX - 9) / 10) {
part = part * 10 + (*value - '0');
}
value++;
}
while (*value != '\0' && *value != '.') {
value++;
}
*cursor = value;
return part;
}
} // namespace
OtaParseStatus OtaResponseParser::Parse(
const char* json,
size_t size,
const char* current_version,
bool allow_insecure_http,
OtaManifest* manifest,
OtaEndpointConfig* endpoint) const
{
if (json == nullptr || size == 0 ||
current_version == nullptr || manifest == nullptr) {
return OtaParseStatus::kMalformed;
}
*manifest = {};
if (endpoint != nullptr) {
*endpoint = {};
}
cJSON* root = cJSON_ParseWithLength(json, size);
if (!cJSON_IsObject(root)) {
cJSON_Delete(root);
return OtaParseStatus::kMalformed;
}
// The websocket block is parsed first and kept across every firmware-block
// outcome below: the server may hand out a new realtime endpoint on a
// response that carries no image at all, and losing it would strand the
// device on the previous host.
const cJSON* websocket =
cJSON_GetObjectItemCaseSensitive(root, "websocket");
if (endpoint != nullptr && cJSON_IsObject(websocket)) {
const char* endpoint_url = StringField(websocket, "url");
const char* endpoint_token = StringField(websocket, "token");
if (endpoint_url != nullptr) {
endpoint->has_url = CopyBounded(
endpoint_url,
endpoint->url.data(),
endpoint->url.size());
}
if (endpoint_token != nullptr) {
endpoint->has_token = CopyBounded(
endpoint_token,
endpoint->token.data(),
endpoint->token.size());
}
}
const cJSON* firmware =
cJSON_GetObjectItemCaseSensitive(root, "firmware");
if (cJSON_IsNull(firmware) || firmware == nullptr) {
cJSON_Delete(root);
return OtaParseStatus::kOk;
}
if (!cJSON_IsObject(firmware)) {
cJSON_Delete(root);
return OtaParseStatus::kInvalidManifest;
}
const char* version = StringField(firmware, "version");
const char* url = StringField(firmware, "url");
const char* sha256 = StringField(firmware, "sha256");
const cJSON* size_value =
cJSON_GetObjectItemCaseSensitive(firmware, "size");
uint8_t digest[32]{};
if (!CopyBounded(
version, manifest->version.data(),
manifest->version.size()) ||
!CopyBounded(
url, manifest->url.data(), manifest->url.size()) ||
!CopyBounded(
sha256, manifest->sha256.data(),
manifest->sha256.size()) ||
!DecodeSha256(sha256, digest) ||
!cJSON_IsNumber(size_value) ||
!std::isfinite(size_value->valuedouble) ||
std::floor(size_value->valuedouble) !=
size_value->valuedouble ||
size_value->valuedouble <= 0 ||
size_value->valuedouble > UINT32_MAX) {
cJSON_Delete(root);
return OtaParseStatus::kInvalidManifest;
}
if (!IsSafeUrl(url, allow_insecure_http)) {
cJSON_Delete(root);
return OtaParseStatus::kUnsafeUrl;
}
if (CompareVersions(version, current_version) <= 0) {
*manifest = {};
cJSON_Delete(root);
return OtaParseStatus::kOk;
}
manifest->size =
static_cast<uint32_t>(size_value->valuedouble);
const cJSON* automatic =
cJSON_GetObjectItemCaseSensitive(root, "auto_update");
const cJSON* forced =
cJSON_GetObjectItemCaseSensitive(root, "force_upgrade");
if ((automatic != nullptr && !cJSON_IsBool(automatic)) ||
(forced != nullptr && !cJSON_IsBool(forced))) {
cJSON_Delete(root);
return OtaParseStatus::kInvalidManifest;
}
if (cJSON_IsTrue(automatic)) {
manifest->policy = OtaUpgradePolicy::kAutomatic;
} else if (cJSON_IsTrue(forced)) {
manifest->policy = OtaUpgradePolicy::kForced;
} else {
manifest->policy = OtaUpgradePolicy::kOptional;
}
cJSON_Delete(root);
return OtaParseStatus::kOk;
}
int OtaResponseParser::CompareVersions(
const char* left,
const char* right)
{
if (left == nullptr || right == nullptr) {
return 0;
}
const char* left_cursor = left;
const char* right_cursor = right;
for (size_t i = 0; i < 8; ++i) {
const int left_part = NextVersionPart(&left_cursor);
const int right_part = NextVersionPart(&right_cursor);
if (left_part != right_part) {
return left_part < right_part ? -1 : 1;
}
if (*left_cursor == '\0' && *right_cursor == '\0') {
return 0;
}
}
return 0;
}
bool OtaResponseParser::DecodeSha256(
const char* hex,
uint8_t output[32])
{
if (hex == nullptr || output == nullptr ||
std::strlen(hex) != 64) {
return false;
}
for (size_t i = 0; i < 32; ++i) {
const int upper = HexNibble(hex[i * 2]);
const int lower = HexNibble(hex[i * 2 + 1]);
if (upper < 0 || lower < 0) {
return false;
}
output[i] = static_cast<uint8_t>((upper << 4) | lower);
}
return true;
}
} // namespace borla

View File

@@ -0,0 +1,30 @@
#pragma once
#include "ota/ota_endpoint.h"
#include "ota/ota_types.h"
#include <cstddef>
namespace borla {
class OtaResponseParser final {
public:
// `endpoint` is optional and independent of the firmware block: a
// response may repoint the device without shipping an image. It is kept
// out of OtaManifest on purpose — the manifest is copied under a
// critical section, and the endpoint is consumed immediately.
OtaParseStatus Parse(
const char* json,
size_t size,
const char* current_version,
bool allow_insecure_http,
OtaManifest* manifest,
OtaEndpointConfig* endpoint = nullptr) const;
static int CompareVersions(const char* left, const char* right);
static bool DecodeSha256(
const char* hex,
uint8_t output[32]);
};
} // namespace borla

685
main/ota/ota_service.cc Normal file
View File

@@ -0,0 +1,685 @@
#include "ota/ota_service.h"
#include "diagnostics/trace_context.h"
#include "ota/ota_endpoint.h"
#include <algorithm>
#include <array>
#include <cstdio>
#include <cstring>
#include <esp_app_desc.h>
#include <esp_crt_bundle.h>
#include <esp_err.h>
#include <esp_heap_caps.h>
#include <esp_http_client.h>
#include <esp_log.h>
#include <esp_ota_ops.h>
#include <esp_system.h>
#include <esp_timer.h>
#include <mbedtls/sha256.h>
#include <sdkconfig.h>
#include <sys/time.h>
#ifndef CONFIG_BORLA_OTA_ALLOW_INSECURE_HTTP
#define CONFIG_BORLA_OTA_ALLOW_INSECURE_HTTP 0
#endif
namespace borla {
namespace {
// Wall-clock milliseconds, or 0 while the clock still reads 1970 because NTP
// has not landed yet — which is the normal case for the boot-time OTA check.
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 const char* kTag = "OtaService2";
constexpr uint32_t kCheckFailedError = 3401;
constexpr uint32_t kManifestInvalidError = 3402;
constexpr uint32_t kPartitionError = 3403;
constexpr uint32_t kDownloadError = 3404;
constexpr uint32_t kSizeMismatchError = 3405;
constexpr uint32_t kShaMismatchError = 3406;
constexpr uint32_t kImageValidationError = 3407;
constexpr size_t kMaximumCheckResponseBytes = 4096;
constexpr uint32_t kUpgradeAnnouncementDelayMs = 8000;
constexpr uint32_t kAnnouncementChannelWaitMs = 10000;
constexpr uint32_t kAnnouncementPollMs = 500;
// Kept verbatim from the legacy firmware so the server-side TTS cache and the
// parent-facing copy do not change during the migration.
constexpr const char* kAutoUpgradeText =
"当前有最新版本,即将开始升级!请耐心等候";
constexpr const char* kForcedUpgradeText =
"目前有大版本需要升级,否则设备将不可用,即将升级请耐心等候!";
constexpr const char* kOptionalUpgradeText =
"当前设备有最新版本,是否进行升级?";
constexpr const char* kAutoUpgradeUnavailableText =
"检测到新版本,升级文件准备中,请稍后重试";
constexpr const char* kForcedUpgradeUnavailableText =
"检测到需要升级的版本,升级文件准备中,请稍后重试";
// NOTE: the legacy firmware also announced "升级成功,正在重启" after flashing.
// firmware2 cannot: kUpgradeRequested deterministically closes the realtime
// channel before the download starts, so there is no socket left to speak on.
// The server learns the outcome from the post-reboot hello version instead.
struct ResponseBuffer {
std::array<char, kMaximumCheckResponseBytes> data{};
size_t size = 0;
bool overflow = false;
};
esp_err_t CaptureResponse(esp_http_client_event_t* event)
{
if (event == nullptr || event->user_data == nullptr) {
return ESP_OK;
}
if (event->event_id != HTTP_EVENT_ON_DATA ||
event->data == nullptr || event->data_len <= 0) {
return ESP_OK;
}
auto* response =
static_cast<ResponseBuffer*>(event->user_data);
const size_t incoming =
static_cast<size_t>(event->data_len);
if (response->size + incoming >= response->data.size()) {
response->overflow = true;
return ESP_FAIL;
}
std::memcpy(
response->data.data() + response->size,
event->data,
incoming);
response->size += incoming;
response->data[response->size] = '\0';
return ESP_OK;
}
bool SecureUrlAllowed(const char* url)
{
if (url == nullptr) {
return false;
}
if (std::strncmp(url, "https://", 8) == 0) {
return true;
}
#if CONFIG_BORLA_OTA_ALLOW_INSECURE_HTTP
return std::strncmp(url, "http://", 7) == 0;
#else
return false;
#endif
}
esp_http_client_handle_t CreateHttpClient(
const char* url,
http_event_handle_cb event_handler = nullptr,
void* user_data = nullptr)
{
if (!SecureUrlAllowed(url)) {
return nullptr;
}
esp_http_client_config_t config{};
config.url = url;
config.event_handler = event_handler;
config.user_data = user_data;
config.timeout_ms = 30000;
config.buffer_size = 4096;
config.buffer_size_tx = 1024;
if (std::strncmp(url, "https://", 8) == 0) {
config.crt_bundle_attach = esp_crt_bundle_attach;
}
return esp_http_client_init(&config);
}
} // namespace
bool OtaService::Initialize(
const DeviceIdentity& identity,
IEventPublisher& publisher)
{
identity_ = identity;
publisher_ = &publisher;
if (task_ != nullptr) {
return true;
}
request_ = xSemaphoreCreateBinaryStatic(&request_storage_);
if (request_ == nullptr) {
ESP_LOGE(kTag, "OTA request semaphore creation failed");
return false;
}
task_ = xTaskCreateStatic(
&OtaService::TaskEntry,
"ota_service2",
task_stack_.size(),
this,
5,
task_stack_.data(),
&task_control_);
if (task_ == nullptr) {
ESP_LOGE(kTag, "OTA worker creation failed");
return false;
}
return true;
}
void OtaService::OnApplicationEvent(
const AppEvent& event,
const RuntimeState& state)
{
// 记录实时通道是否已握手完成:RunOnce 用它把版本检查的 TLS 错开
// (原因见 kCheckStaggerMaxMs 的注释)。
realtime_open_.store(state.realtime == RealtimeState::kOpen);
if (event.type != AppEventType::kNetworkConnected ||
task_ == nullptr ||
check_started_.exchange(true)) {
return;
}
if (busy_.exchange(true)) {
check_started_.store(false);
return;
}
task_mode_.store(TaskMode::kCheck);
xSemaphoreGive(request_);
}
void OtaService::StartUpgrade(uint32_t request_id)
{
request_id_.store(request_id);
upgrade_requested_.store(true);
if (task_ == nullptr) {
PublishFailure(kDownloadError);
return;
}
if (busy_.exchange(true)) {
// A check-mode run is already waiting for this flag and will perform
// the upgrade itself.
return;
}
task_mode_.store(TaskMode::kUpgrade);
xSemaphoreGive(request_);
}
bool OtaService::ConfirmCurrentImage()
{
const esp_partition_t* running =
esp_ota_get_running_partition();
esp_ota_img_states_t state = ESP_OTA_IMG_UNDEFINED;
const esp_err_t result =
esp_ota_get_state_partition(running, &state);
if (result == ESP_ERR_NOT_SUPPORTED ||
state != ESP_OTA_IMG_PENDING_VERIFY) {
return result == ESP_OK || result == ESP_ERR_NOT_SUPPORTED;
}
const esp_err_t mark_result =
esp_ota_mark_app_valid_cancel_rollback();
ESP_LOGI(kTag, "current image confirmation: %s",
esp_err_to_name(mark_result));
return mark_result == ESP_OK;
}
void OtaService::RejectCurrentImageAndRollback()
{
const esp_partition_t* running =
esp_ota_get_running_partition();
esp_ota_img_states_t state = ESP_OTA_IMG_UNDEFINED;
if (esp_ota_get_state_partition(running, &state) == ESP_OK &&
state == ESP_OTA_IMG_PENDING_VERIFY) {
ESP_LOGE(kTag, "boot self-test failed; rolling back image");
esp_ota_mark_app_invalid_rollback_and_reboot();
}
}
OtaDiagnostics OtaService::GetDiagnostics() const
{
portENTER_CRITICAL(&lock_);
const OtaDiagnostics result = diagnostics_;
portEXIT_CRITICAL(&lock_);
return result;
}
void OtaService::TaskEntry(void* context)
{
static_cast<OtaService*>(context)->Run();
}
[[noreturn]] void OtaService::Run()
{
for (;;) {
if (xSemaphoreTake(request_, portMAX_DELAY) != pdTRUE) {
continue;
}
RunOnce();
busy_.store(false);
}
}
void OtaService::RunOnce()
{
const TaskMode mode = task_mode_.load();
if (mode == TaskMode::kCheck) {
TraceContext::RefreshTrace("ota");
// 先让实时通道把 TLS 握完(两条 TLS 并发会让 WiFi 拿不到内部 DMA
// 缓冲,见 kCheckStaggerMaxMs)。通道已经打开时一次都不等。
uint32_t staggered_ms = 0;
while (!realtime_open_.load() &&
staggered_ms < kCheckStaggerMaxMs) {
vTaskDelay(pdMS_TO_TICKS(kCheckStaggerStepMs));
staggered_ms += kCheckStaggerStepMs;
}
if (staggered_ms > 0) {
ESP_LOGI(kTag,
"staggered version check waited=%ums realtime_open=%d",
static_cast<unsigned>(staggered_ms),
realtime_open_.load() ? 1 : 0);
}
bool checked = false;
for (uint32_t attempt = 0; attempt < 3 && !checked; ++attempt) {
portENTER_CRITICAL(&lock_);
diagnostics_.checking = true;
diagnostics_.check_attempts++;
portEXIT_CRITICAL(&lock_);
checked = CheckVersion();
if (!checked && attempt < 2) {
vTaskDelay(pdMS_TO_TICKS(10000));
}
}
portENTER_CRITICAL(&lock_);
diagnostics_.checking = false;
portEXIT_CRITICAL(&lock_);
OtaManifest manifest;
portENTER_CRITICAL(&lock_);
manifest = manifest_;
portEXIT_CRITICAL(&lock_);
if (checked && manifest.policy == OtaUpgradePolicy::kOptional) {
// Advisory only: tell the parent a version exists, install nothing.
AnnounceUpgrade(manifest);
}
if (checked && manifest.ShouldStartAutomatically()) {
// Announce first. kUpgradeRequested deterministically closes the
// realtime channel, so anything said after it would never reach
// the server.
AnnounceUpgrade(manifest);
publisher_->Publish(AppEvent::Make(
AppEventType::kUpgradeRequested,
request_id_.load()));
for (uint32_t waited = 0;
!upgrade_requested_.load() && waited < 5000;
waited += 50) {
vTaskDelay(pdMS_TO_TICKS(50));
}
if (upgrade_requested_.load()) {
PerformUpgrade();
} else {
PublishFailure(kDownloadError);
}
}
} else {
PerformUpgrade();
}
}
bool OtaService::CheckVersion()
{
// 碎片防护:内部RAM最大连续块不足,直接跳过版本检查,避免触发socket分配失败
const size_t largest_int_ram = heap_caps_get_largest_free_block(MALLOC_CAP_8BIT);
ESP_LOGI(kTag, "CheckVersion largest_int_ram=%zu", largest_int_ram);
if (largest_int_ram < 12 * 1024U)
{
ESP_LOGW(kTag, "internal ram fragmented, skip ota version check");
PublishFailure(kCheckFailedError);
return false;
}
ResponseBuffer response;
esp_http_client_handle_t client = CreateHttpClient(
CONFIG_BORLA_OTA_URL, &CaptureResponse, &response);
if (client == nullptr) {
PublishFailure(kCheckFailedError);
return false;
}
std::array<char, 512> body{};
const int body_size = std::snprintf(
body.data(),
body.size(),
"{\"mac_address\":\"%s\",\"board_type\":\"%s\","
"\"app_version\":\"%s\",\"idf_version\":\"%s\","
"\"chip_model\":\"%s\",\"free_heap\":%lu}",
identity_.mac,
identity_.board,
identity_.app_version,
esp_get_idf_version(),
identity_.chip_model,
static_cast<unsigned long>(
heap_caps_get_free_size(MALLOC_CAP_8BIT)));
if (body_size <= 0 ||
static_cast<size_t>(body_size) >= body.size()) {
esp_http_client_cleanup(client);
PublishFailure(kCheckFailedError);
return false;
}
esp_http_client_set_method(client, HTTP_METHOD_POST);
esp_http_client_set_header(
client, "Content-Type", "application/json");
esp_http_client_set_header(client, "Device-Id", identity_.mac);
// Correlation headers: server and backend grep the same ids to stitch the
// device-side OTA call into their own request logs.
const char* request_id = TraceContext::NewRequestId();
esp_http_client_set_header(
client, "X-Borla-Trace-Id", TraceContext::TraceId());
esp_http_client_set_header(
client, "X-Borla-Session-Id", TraceContext::SessionId());
esp_http_client_set_header(client, "X-Request-Id", request_id);
// http_server.py reads these two to time the call and derive the device's
// clock offset. The epoch header is skipped while the wall clock still
// reads 1970, since OTA check runs before NTP on a cold boot and a 1970
// stamp would be read as a 56-year skew rather than as "unknown".
char send_ms[24]{};
std::snprintf(
send_ms,
sizeof(send_ms),
"%llu",
static_cast<unsigned long long>(esp_timer_get_time() / 1000));
esp_http_client_set_header(
client, "X-Borla-Client-Send-Ms", send_ms);
const int64_t client_epoch_ms = EpochMs();
if (client_epoch_ms > 0) {
char epoch_ms[24]{};
std::snprintf(
epoch_ms,
sizeof(epoch_ms),
"%lld",
static_cast<long long>(client_epoch_ms));
esp_http_client_set_header(
client, "X-Borla-Client-Epoch-Ms", epoch_ms);
}
ESP_LOGI(kTag, "version check trace=%s request=%s",
TraceContext::TraceId(), request_id);
esp_http_client_set_post_field(
client, body.data(), body_size);
const esp_err_t result = esp_http_client_perform(client);
const int status = esp_http_client_get_status_code(client);
esp_http_client_close(client);//释放内存
esp_http_client_cleanup(client);
if (result != ESP_OK || status != 200 ||
response.overflow || response.size == 0) {
ESP_LOGW(kTag, "version check failed result=%s status=%d",
esp_err_to_name(result), status);
PublishFailure(kCheckFailedError);
return false;
}
OtaManifest parsed;
OtaEndpointConfig endpoint;
const OtaParseStatus parse_status = parser_.Parse(
response.data.data(),
response.size,
identity_.app_version,
CONFIG_BORLA_OTA_ALLOW_INSECURE_HTTP,
&parsed,
&endpoint);
const esp_partition_t* target =
esp_ota_get_next_update_partition(nullptr);
if (parse_status != OtaParseStatus::kOk ||
(parsed.HasUpdate() &&
(target == nullptr || parsed.size > target->size))) {
portENTER_CRITICAL(&lock_);
diagnostics_.last_parse_status = parse_status;
portEXIT_CRITICAL(&lock_);
PublishFailure(kManifestInvalidError);
return false;
}
portENTER_CRITICAL(&lock_);
manifest_ = parsed;
diagnostics_.manifest = parsed;
diagnostics_.last_parse_status = parse_status;
portEXIT_CRITICAL(&lock_);
ESP_LOGI(kTag, "version check policy=%s version=%s size=%lu",
ToString(parsed.policy),
parsed.version.data(),
static_cast<unsigned long>(parsed.size));
// Endpoint handling is deliberately independent of HasUpdate(): the OTA
// response is the only channel that can repoint a fielded device, and it
// routinely carries a websocket block with no firmware block at all.
ApplyEndpoint(endpoint);
return true;
}
void OtaService::ApplyEndpoint(const OtaEndpointConfig& endpoint)
{
if (config_store_ == nullptr || !endpoint.HasAny()) {
return;
}
std::array<char, kWebsocketUrlCapacity> resolved{};
const bool has_url =
endpoint.has_url &&
ResolveRealtimeUrl(
endpoint.url.data(),
CONFIG_BORLA_OTA_URL,
kDefaultRealtimeUrl,
resolved.data(),
resolved.size());
if (!has_url && !endpoint.has_token) {
ESP_LOGW(kTag, "OTA endpoint block unusable; keeping stored value");
return;
}
if (!config_store_->SaveEndpoint(
has_url ? resolved.data() : nullptr,
endpoint.has_token ? endpoint.token.data() : nullptr)) {
ESP_LOGW(kTag, "OTA endpoint persistence failed");
return;
}
// Applied on the next Open(): RealtimeProtocol loads its transport config
// once at Initialize(), so a changed endpoint takes effect after reboot.
ESP_LOGI(kTag, "OTA endpoint stored url=%s",
has_url ? resolved.data() : "(unchanged)");
}
void OtaService::AnnounceUpgrade(const OtaManifest& manifest)
{
if (realtime_ == nullptr || !manifest.HasUpdate()) {
return;
}
const bool forced = manifest.policy == OtaUpgradePolicy::kForced;
const bool optional =
manifest.policy == OtaUpgradePolicy::kOptional;
const char* text = nullptr;
if (optional) {
text = kOptionalUpgradeText;
} else if (manifest.url[0] == '\0') {
text = forced ? kForcedUpgradeUnavailableText
: kAutoUpgradeUnavailableText;
} else {
text = forced ? kForcedUpgradeText : kAutoUpgradeText;
}
// The check can finish before the realtime channel has finished opening
// (both are triggered by the same kNetworkConnected edge), so give the
// channel a bounded grace period rather than dropping the announcement.
bool sent = false;
for (uint32_t waited = 0;
!sent && waited < kAnnouncementChannelWaitMs;
waited += kAnnouncementPollMs) {
sent = realtime_->SendOtaNotify(text, optional);
if (!sent) {
vTaskDelay(pdMS_TO_TICKS(kAnnouncementPollMs));
}
}
if (!sent) {
ESP_LOGW(kTag, "upgrade announcement skipped: channel not open");
return;
}
ESP_LOGI(kTag, "upgrade announcement sent policy=%s",
ToString(manifest.policy));
if (optional) {
return;
}
// Give the server time to synthesise and the device time to play the
// announcement before the download saturates the link.
vTaskDelay(pdMS_TO_TICKS(kUpgradeAnnouncementDelayMs));
}
bool OtaService::PerformUpgrade()
{
portENTER_CRITICAL(&lock_);
diagnostics_.upgrading = true;
portEXIT_CRITICAL(&lock_);
const bool success = DownloadToPartition();
portENTER_CRITICAL(&lock_);
diagnostics_.upgrading = false;
portEXIT_CRITICAL(&lock_);
if (success) {
publisher_->Publish(AppEvent::Make(
AppEventType::kUpgradeCompleted,
request_id_.load()));
}
return success;
}
bool OtaService::DownloadToPartition()
{
OtaManifest manifest;
portENTER_CRITICAL(&lock_);
manifest = manifest_;
diagnostics_.downloaded_bytes = 0;
portEXIT_CRITICAL(&lock_);
if (!manifest.HasUpdate()) {
PublishFailure(kManifestInvalidError);
return false;
}
const esp_partition_t* partition =
esp_ota_get_next_update_partition(nullptr);
if (partition == nullptr || manifest.size > partition->size) {
PublishFailure(kPartitionError);
return false;
}
// 碎片防护
const size_t largest_int_ram = heap_caps_get_largest_free_block(MALLOC_CAP_8BIT);
ESP_LOGI(kTag, "DownloadToPartition largest_int_ram=%zu", largest_int_ram);
if (largest_int_ram < 12 * 1024U)
{
ESP_LOGW(kTag, "internal ram fragmented, abort download");
PublishFailure(kDownloadError);
return false;
}/////
esp_http_client_handle_t client =
CreateHttpClient(manifest.url.data());
if (client == nullptr) {
PublishFailure(kDownloadError);
return false;
}
esp_http_client_set_method(client, HTTP_METHOD_GET);
esp_err_t result = esp_http_client_open(client, 0);
if (result != ESP_OK) {
esp_http_client_cleanup(client);
PublishFailure(kDownloadError);
return false;
}
const int64_t content_length =
esp_http_client_fetch_headers(client);
const int status = esp_http_client_get_status_code(client);
if (status != 200 ||
(content_length > 0 &&
static_cast<uint64_t>(content_length) != manifest.size)) {
esp_http_client_close(client);
esp_http_client_cleanup(client);
PublishFailure(
status == 200 ? kSizeMismatchError : kDownloadError);
return false;
}
esp_ota_handle_t ota_handle = 0;
result = esp_ota_begin(
partition, manifest.size, &ota_handle);
if (result != ESP_OK) {
esp_http_client_close(client);
esp_http_client_cleanup(client);
PublishFailure(kPartitionError);
return false;
}
mbedtls_sha256_context sha;
mbedtls_sha256_init(&sha);
mbedtls_sha256_starts(&sha, 0);
std::array<uint8_t, 4096> buffer{};
uint32_t total = 0;
bool valid = true;
while (total < manifest.size) {
const int read = esp_http_client_read(
client,
reinterpret_cast<char*>(buffer.data()),
std::min<size_t>(
buffer.size(), manifest.size - total));
if (read <= 0) {
valid = false;
break;
}
if (esp_ota_write(
ota_handle, buffer.data(), read) != ESP_OK) {
valid = false;
break;
}
mbedtls_sha256_update(
&sha, buffer.data(), static_cast<size_t>(read));
total += static_cast<uint32_t>(read);
portENTER_CRITICAL(&lock_);
diagnostics_.downloaded_bytes = total;
portEXIT_CRITICAL(&lock_);
}
esp_http_client_close(client);
esp_http_client_cleanup(client);
uint8_t actual_digest[32]{};
uint8_t expected_digest[32]{};
mbedtls_sha256_finish(&sha, actual_digest);
mbedtls_sha256_free(&sha);
if (!valid || total != manifest.size) {
esp_ota_abort(ota_handle);
PublishFailure(kSizeMismatchError);
return false;
}
if (!OtaResponseParser::DecodeSha256(
manifest.sha256.data(), expected_digest) ||
std::memcmp(actual_digest, expected_digest, 32) != 0) {
esp_ota_abort(ota_handle);
PublishFailure(kShaMismatchError);
return false;
}
if (esp_ota_end(ota_handle) != ESP_OK ||
esp_ota_set_boot_partition(partition) != ESP_OK) {
PublishFailure(kImageValidationError);
return false;
}
ESP_LOGI(kTag, "OTA image verified version=%s bytes=%lu",
manifest.version.data(),
static_cast<unsigned long>(total));
return true;
}
void OtaService::PublishFailure(uint32_t error)
{
portENTER_CRITICAL(&lock_);
diagnostics_.last_error = error;
portEXIT_CRITICAL(&lock_);
if (publisher_ != nullptr) {
publisher_->Publish(AppEvent::Make(
AppEventType::kUpgradeFailed, error));
}
}
} // namespace borla

108
main/ota/ota_service.h Normal file
View File

@@ -0,0 +1,108 @@
#pragma once
#include "ota/ota_response_parser.h"
#include "ports/application_observer.h"
#include "ports/device_platform.h"
#include "ports/event_publisher.h"
#include "ports/ota_service.h"
#include "ports/realtime_protocol.h"
#include "protocol/realtime_config.h"
#include <array>
#include <atomic>
#include <freertos/FreeRTOS.h>
#include <freertos/semphr.h>
#include <freertos/task.h>
namespace borla {
struct OtaDiagnostics {
OtaManifest manifest{};
OtaParseStatus last_parse_status = OtaParseStatus::kOk;
uint32_t check_attempts = 0;
uint32_t downloaded_bytes = 0;
uint32_t last_error = 0;
bool checking = false;
bool upgrading = false;
};
class OtaService final
: public IOtaService,
public IApplicationObserver {
public:
bool Initialize(
const DeviceIdentity& identity,
IEventPublisher& publisher);
// Optional collaborators. Both are wired by CompositionRoot; the service
// degrades to "check + install only" when either is absent.
void SetRealtimeConfigStore(IRealtimeConfigStore* store)
{
config_store_ = store;
}
void SetRealtimeProtocol(IRealtimeProtocol* realtime)
{
realtime_ = realtime;
}
void StartUpgrade(uint32_t request_id) override;
void OnApplicationEvent(
const AppEvent& event,
const RuntimeState& state) override;
bool ConfirmCurrentImage();
void RejectCurrentImageAndRollback();
OtaDiagnostics GetDiagnostics() const;
private:
enum class TaskMode : uint8_t {
kCheck,
kUpgrade,
};
static constexpr uint32_t kTaskStackDepth = 12288;
// 版本检查是设备上的第二条 TLS:它与实时通道(websocket)的 TLS 都由
// kNetworkConnected 触发,两条同时握手会把内部 DMA 可用的 RAM 抢空 ——
// WiFi 驱动随即分配不到 RX 缓冲("wifi:mem fail" → ADDBA RX DELBA →
// 收包瘫痪 → "WebSocket read failed"),实测 internal free 掉到 863 B。
// 因此检查前先等实时通道把 TLS 握完;超过 kCheckStaggerMaxMs 就照常进行,
// 避免实时通道一直连不上时版本检查被永久推迟。
static constexpr uint32_t kCheckStaggerMaxMs = 8000;
static constexpr uint32_t kCheckStaggerStepMs = 100;
static void TaskEntry(void* context);
// Long-lived worker: the static task control block and stack cannot be
// recycled for a second task while the first is still terminating, so the
// worker parks on request_ instead of deleting itself.
[[noreturn]] void Run();
void RunOnce();
bool CheckVersion();
bool PerformUpgrade();
bool DownloadToPartition();
void PublishFailure(uint32_t error);
void ApplyEndpoint(const OtaEndpointConfig& endpoint);
void AnnounceUpgrade(const OtaManifest& manifest);
DeviceIdentity identity_{};
IEventPublisher* publisher_ = nullptr;
IRealtimeConfigStore* config_store_ = nullptr;
IRealtimeProtocol* realtime_ = nullptr;
OtaResponseParser parser_;
OtaManifest manifest_{};
OtaDiagnostics diagnostics_{};
mutable portMUX_TYPE lock_ = portMUX_INITIALIZER_UNLOCKED;
std::atomic<TaskMode> task_mode_{TaskMode::kCheck};
// 由 OnApplicationEvent 刷新,RunOnce 用它错开实时通道的 TLS 握手。
std::atomic<bool> realtime_open_{false};
std::atomic<bool> check_started_{false};
std::atomic<bool> busy_{false};
std::atomic<bool> upgrade_requested_{false};
std::atomic<uint32_t> request_id_{0};
SemaphoreHandle_t request_ = nullptr;
StaticSemaphore_t request_storage_{};
TaskHandle_t task_ = nullptr;
StaticTask_t task_control_{};
std::array<StackType_t, kTaskStackDepth> task_stack_{};
};
} // namespace borla

35
main/ota/ota_types.cc Normal file
View File

@@ -0,0 +1,35 @@
#include "ota/ota_types.h"
namespace borla {
const char* ToString(OtaUpgradePolicy policy)
{
switch (policy) {
case OtaUpgradePolicy::kNone:
return "none";
case OtaUpgradePolicy::kOptional:
return "optional";
case OtaUpgradePolicy::kAutomatic:
return "automatic";
case OtaUpgradePolicy::kForced:
return "forced";
}
return "unknown";
}
const char* ToString(OtaParseStatus status)
{
switch (status) {
case OtaParseStatus::kOk:
return "ok";
case OtaParseStatus::kMalformed:
return "malformed";
case OtaParseStatus::kInvalidManifest:
return "invalid_manifest";
case OtaParseStatus::kUnsafeUrl:
return "unsafe_url";
}
return "unknown";
}
} // namespace borla

48
main/ota/ota_types.h Normal file
View File

@@ -0,0 +1,48 @@
#pragma once
#include <array>
#include <cstddef>
#include <cstdint>
namespace borla {
enum class OtaUpgradePolicy : uint8_t {
kNone,
kOptional,
kAutomatic,
kForced,
};
inline constexpr size_t kOtaVersionCapacity = 32;
inline constexpr size_t kOtaUrlCapacity = 384;
inline constexpr size_t kOtaSha256HexCapacity = 65;
struct OtaManifest {
OtaUpgradePolicy policy = OtaUpgradePolicy::kNone;
std::array<char, kOtaVersionCapacity> version{};
std::array<char, kOtaUrlCapacity> url{};
std::array<char, kOtaSha256HexCapacity> sha256{};
uint32_t size = 0;
bool HasUpdate() const
{
return policy != OtaUpgradePolicy::kNone;
}
bool ShouldStartAutomatically() const
{
return policy == OtaUpgradePolicy::kAutomatic ||
policy == OtaUpgradePolicy::kForced;
}
};
enum class OtaParseStatus : uint8_t {
kOk,
kMalformed,
kInvalidManifest,
kUnsafeUrl,
};
const char* ToString(OtaUpgradePolicy policy);
const char* ToString(OtaParseStatus status);
} // namespace borla