bolar_1 date 2026-7-1 d:/proc

This commit is contained in:
2026-11-27 17:44:38 +08:00
commit 0dbdfa57bc
890 changed files with 325428 additions and 0 deletions

290
main/ota.cc Normal file
View File

@@ -0,0 +1,290 @@
#include "ota.h"
#include "system_info.h"
#include "settings.h"
#include "boards/board.h"
#include "application.h"
#include "trace_ctx.h"
#include <sdkconfig.h>
#include <esp_log.h>
#include <freertos/FreeRTOS.h>
#include <freertos/task.h>
#include <esp_ota_ops.h>
#include <esp_app_desc.h>
#include <cJSON.h>
#include <http.h>
#include <algorithm>
#include <cstring>
#include <string>
#include <sys/time.h>
#define TAG "OTA"
#ifndef CONFIG_OTA_URL
#define CONFIG_OTA_URL "https://borla-ota.lkall.com/xiaozhi/ota/"
#endif
static constexpr const char* kDevelopmentWebSocketUrl = "wss://borlaws.lkall.com/v1/ws";
static uint64_t TraceMonoMs()
{
return static_cast<uint64_t>(esp_timer_get_time() / 1000ULL);
}
static int64_t TraceEpochMs()
{
struct timeval tv;
gettimeofday(&tv, nullptr);
if (tv.tv_sec < 1700000000) {
return 0;
}
return static_cast<int64_t>(tv.tv_sec) * 1000 + tv.tv_usec / 1000;
}
static std::string MakeTraceId(const char* prefix)
{
std::string mac = SystemInfo::GetMacAddress();
std::replace(mac.begin(), mac.end(), ':', '-');
return std::string(prefix) + "-" + mac + "-" + std::to_string(TraceMonoMs());
}
static bool IsKnownSavedEndpoint(const std::string& url)
{
const bool lkall_host = url.find(".lkall.com") != std::string::npos;
return (lkall_host && (url.find("-dev.") != std::string::npos ||
url.find("-moe.") != std::string::npos ||
url.find("borlaws.lkall.com") != std::string::npos ||
url.find("borla-ota.lkall.com") != std::string::npos)) ||
url.find("192.168.1.121") != std::string::npos ||
url.find("117.50.44.247") != std::string::npos;
}
bool Ota::CheckVersion()
{
Settings wifi_settings("wifi", true);
check_url_ = wifi_settings.GetString("ota_url");
if (check_url_.empty() || IsKnownSavedEndpoint(check_url_)) {
check_url_ = CONFIG_OTA_URL;
wifi_settings.SetString("ota_url", check_url_);
}
current_version_ = SystemInfo::GetAppVersion();
ESP_LOGI(TAG, "Checking at: %s (v%s)", check_url_.c_str(), current_version_.c_str());
// Build request body
cJSON* body = cJSON_CreateObject();
cJSON_AddStringToObject(body, "mac_address", SystemInfo::GetMacAddress().c_str());
cJSON_AddStringToObject(body, "board_type", "borla-s3");
cJSON_AddStringToObject(body, "app_version", current_version_.c_str());
cJSON_AddStringToObject(body, "chip_model", SystemInfo::GetChipModelName().c_str());
cJSON_AddNumberToObject(body, "free_heap", SystemInfo::GetFreeHeapSize());
char* body_str = cJSON_PrintUnformatted(body);
std::string body_content(body_str);
cJSON_free(body_str);
cJSON_Delete(body);
// Use NetworkInterface HTTP (works with both WiFi and 4G)
auto http = Board::GetInstance().GetNetwork()->CreateHttp();
if (!http) {
ESP_LOGE(TAG, "Failed to create HTTP client");
return false;
}
http->SetTimeout(30000);
http->SetHeader("Content-Type", "application/json");
http->SetHeader("Device-Id", SystemInfo::GetMacAddress());
std::string trace_id = MakeTraceId("fw-ota");
::borla::TraceCtx::SetTrace(trace_id.c_str());
std::string request_id = ::borla::TraceCtx::NewRequestId();
uint64_t client_send_ms = TraceMonoMs();
int64_t client_epoch_ms = TraceEpochMs();
http->SetHeader("X-Borla-Trace-Id", trace_id);
http->SetHeader("X-Borla-Session-Id", ::borla::TraceCtx::SessionId());
http->SetHeader("X-Request-Id", request_id);
http->SetHeader("X-Borla-Client-Send-Ms", std::to_string(client_send_ms));
if (client_epoch_ms > 0) {
http->SetHeader("X-Borla-Client-Epoch-Ms", std::to_string(client_epoch_ms));
}
http->SetContent(std::move(body_content));
ESP_LOGI(TAG,
"[TRACE] trace=%s session=%s request_id=%s stage=ota.http.send url=%s client_send_ms=%llu client_epoch_ms=%lld",
trace_id.c_str(), ::borla::TraceCtx::SessionId(), request_id.c_str(),
check_url_.c_str(),
static_cast<unsigned long long>(client_send_ms),
static_cast<long long>(client_epoch_ms));
uint64_t request_start_ms = TraceMonoMs();
if (!http->Open("POST", check_url_)) {
ESP_LOGE(TAG, "HTTP POST failed");
ESP_LOGE(TAG,
"[TRACE] trace=%s session=%s request_id=%s stage=ota.http.open_failed duration_ms=%llu",
trace_id.c_str(), ::borla::TraceCtx::SessionId(), request_id.c_str(),
static_cast<unsigned long long>(TraceMonoMs() - request_start_ms));
http->Close();
return false;
}
int status = http->GetStatusCode();
std::string response = http->ReadAll();
http->Close();
ESP_LOGI(TAG,
"[TRACE] trace=%s session=%s request_id=%s stage=ota.http.recv status=%d duration_ms=%llu response_bytes=%u",
trace_id.c_str(), ::borla::TraceCtx::SessionId(), request_id.c_str(), status,
static_cast<unsigned long long>(TraceMonoMs() - request_start_ms),
static_cast<unsigned>(response.size()));
ESP_LOGI(TAG, "HTTP %d, body: %s", status, response.c_str());
if (status != 200 || response.empty()) {
return false;
}
bool ok = ParseResponse(response.c_str());
// Save WebSocket config to NVS
if (!websocket_url_.empty()) {
if (IsKnownSavedEndpoint(websocket_url_)) {
websocket_url_ = kDevelopmentWebSocketUrl;
}
// Fix 0.0.0.0 → actual server IP from OTA URL
if (websocket_url_.find("0.0.0.0") != std::string::npos) {
std::string ota_host;
size_t start = check_url_.find("://");
if (start != std::string::npos) {
start += 3;
size_t end = check_url_.find(":", start);
if (end == std::string::npos) end = check_url_.find("/", start);
if (end != std::string::npos) ota_host = check_url_.substr(start, end - start);
}
if (!ota_host.empty() && ota_host != "0.0.0.0") {
size_t pos = websocket_url_.find("0.0.0.0");
websocket_url_.replace(pos, 7, ota_host);
}
}
Settings ws("websocket", true);
ws.SetString("url", websocket_url_);
if (!websocket_token_.empty()) {
ws.SetString("token", websocket_token_);
}
ws.SetInt("version", 3);
ESP_LOGI(TAG, "WebSocket URL: %s", websocket_url_.c_str());
}
return ok;
}
bool Ota::ParseResponse(const char* json)
{
cJSON* root = cJSON_Parse(json);
if (!root) {
ESP_LOGE(TAG, "JSON parse failed");
return false;
}
cJSON* firmware = cJSON_GetObjectItem(root, "firmware");
if (cJSON_IsObject(firmware)) {
cJSON* ver = cJSON_GetObjectItem(firmware, "version");
cJSON* url = cJSON_GetObjectItem(firmware, "url");
if (cJSON_IsString(ver) && cJSON_IsString(url)) {
new_version_ = ver->valuestring;
download_url_ = url->valuestring;
has_new_version_ = (new_version_ != current_version_);
}
}
cJSON* ws = cJSON_GetObjectItem(root, "websocket");
if (cJSON_IsObject(ws)) {
cJSON* url = cJSON_GetObjectItem(ws, "url");
if (cJSON_IsString(url)) websocket_url_ = url->valuestring;
cJSON* token = cJSON_GetObjectItem(ws, "token");
if (cJSON_IsString(token)) websocket_token_ = token->valuestring;
}
cJSON* st = cJSON_GetObjectItem(root, "server_time");
has_server_time_ = cJSON_IsObject(st);
// Parse auto-upgrade fields
cJSON* auto_upd = cJSON_GetObjectItem(root, "auto_update");
if (cJSON_IsBool(auto_upd)) auto_update_ = cJSON_IsTrue(auto_upd);
cJSON* force = cJSON_GetObjectItem(root, "force_upgrade");
if (cJSON_IsBool(force)) force_upgrade_ = cJSON_IsTrue(force);
cJSON_Delete(root);
return true;
}
bool Ota::StartUpgrade()
{
if (download_url_.empty()) {
ESP_LOGW(TAG, "Download URL is empty, skip upgrade");
return false;
}
ESP_LOGI(TAG, "Upgrading to %s", download_url_.c_str());
const esp_partition_t* partition = esp_ota_get_next_update_partition(nullptr);
if (!partition) return false;
// Use NetworkInterface HTTP (works with both WiFi and 4G)
auto http = Board::GetInstance().GetNetwork()->CreateHttp();
if (!http) {
ESP_LOGE(TAG, "Failed to create HTTP client for OTA download");
return false;
}
http->SetTimeout(30000);
if (!http->Open("GET", download_url_)) {
ESP_LOGE(TAG, "Failed to open OTA download URL");
http->Close();
return false;
}
size_t content_length = http->GetBodyLength();
esp_ota_handle_t handle;
if (esp_ota_begin(partition, OTA_WITH_SEQUENTIAL_WRITES, &handle) != ESP_OK) {
http->Close();
return false;
}
char buf[1024];
int total = 0;
while (true) {
int n = http->Read(buf, sizeof(buf));
if (n < 0) { esp_ota_abort(handle); http->Close(); return false; }
if (n == 0) break;
if (esp_ota_write(handle, buf, n) != ESP_OK) { esp_ota_abort(handle); http->Close(); return false; }
total += n;
if (content_length > 0) ESP_LOGI(TAG, "OTA: %d%%", (int)(total * 100 / content_length));
}
http->Close();
if (esp_ota_end(handle) != ESP_OK) return false;
if (esp_ota_set_boot_partition(partition) != ESP_OK) return false;
ESP_LOGI(TAG, "OTA done, notifying user before reboot...");
// Notify server to play "upgrade success" TTS before reboot
auto& app = Application::GetInstance();
if (app.GetProtocol() && app.GetProtocol()->IsAudioChannelOpened()) {
app.GetProtocol()->SendText(
"{\"type\":\"ota_notify\",\"text\":\"升级成功,正在重启\"}");
// Wait for TTS playback before restarting
vTaskDelay(pdMS_TO_TICKS(4000));
}
esp_restart();
return true;
}
void Ota::MarkCurrentVersionValid()
{
const esp_partition_t* running = esp_ota_get_running_partition();
esp_ota_img_states_t state;
if (esp_ota_get_state_partition(running, &state) == ESP_OK) {
if (state == ESP_OTA_IMG_PENDING_VERIFY) {
esp_ota_mark_app_valid_cancel_rollback();
}
}
}