Enhance timestamp parsing and arrival data handling in MainUIHandler

- Introduced a new helper function to parse ISO 8601-like timestamps into epoch seconds.
- Improved the handling of timezones, allowing for better accuracy in arrival time calculations.
- Refactored arrival data fetching to ensure UI updates only when data changes.
- Enhanced error handling for arrival data retrieval, providing clearer messages for various error states.
- Updated formatting functions for arrival times to handle both relative and absolute formats more robustly.
This commit is contained in:
GW_MC
2026-02-04 11:54:37 +08:00
parent af0da04e7d
commit 05a65988dd
2 changed files with 686 additions and 552 deletions

View File

@@ -4,16 +4,17 @@
#include "esp_log.h"
static const char* TAG = "TravelMainUI";
#define LVGL_PORT_LOCK_TIMEOUT_MS 6000
namespace travel {
MainUI::MainUI() = default;
MainUI::MainUI() = default;
MainUI::~MainUI() {
MainUI::~MainUI() {
deinit();
}
}
esp_err_t MainUI::init(lv_obj_t* parent) {
esp_err_t MainUI::init(lv_obj_t* parent) {
if (!parent) {
ESP_LOGE(TAG, "Parent is null");
return ESP_ERR_INVALID_ARG;
@@ -21,7 +22,7 @@ esp_err_t MainUI::init(lv_obj_t* parent) {
parent_ = parent;
if (!lvgl_port_lock(pdMS_TO_TICKS(1000))) {
if (!lvgl_port_lock(pdMS_TO_TICKS(LVGL_PORT_LOCK_TIMEOUT_MS))) {
ESP_LOGE(TAG, "Failed to acquire LVGL lock");
return ESP_ERR_TIMEOUT;
}
@@ -53,15 +54,15 @@ esp_err_t MainUI::init(lv_obj_t* parent) {
lv_obj_set_width(refresh_time_label_, LV_PCT(100));
lv_label_set_text(refresh_time_label_, "");
lv_obj_set_style_text_font(refresh_time_label_, &noto_sans_tc_14, 0);
lv_obj_set_style_text_color(refresh_time_label_, lv_color_hex(0x808080), 0);
lv_obj_set_style_text_color(refresh_time_label_, lv_color_black(), 0);
lvgl_port_unlock();
return ESP_OK;
}
}
esp_err_t MainUI::deinit() {
if (!lvgl_port_lock(pdMS_TO_TICKS(1000))) {
esp_err_t MainUI::deinit() {
if (!lvgl_port_lock(pdMS_TO_TICKS(LVGL_PORT_LOCK_TIMEOUT_MS))) {
ESP_LOGE(TAG, "Failed to acquire LVGL lock");
return ESP_ERR_TIMEOUT;
}
@@ -88,9 +89,9 @@ esp_err_t MainUI::deinit() {
parent_ = nullptr;
return ESP_OK;
}
}
void MainUI::create_header_() {
void MainUI::create_header_() {
// Header container
lv_obj_t* header = lv_obj_create(container_);
lv_obj_set_size(header, LV_PCT(100), 35);
@@ -101,7 +102,7 @@ void MainUI::create_header_() {
lv_obj_set_style_border_width(header, 0, 0);
lv_obj_set_style_border_width(header, 1, 0);
lv_obj_set_style_border_side(header, LV_BORDER_SIDE_BOTTOM, 0);
lv_obj_set_style_border_color(header, lv_color_hex(0x808080), 0);
lv_obj_set_style_border_color(header, lv_color_black(), 0);
lv_obj_set_style_anim_time(header, 0, 0);
lv_obj_clear_flag(header, LV_OBJ_FLAG_SCROLLABLE);
@@ -117,9 +118,9 @@ void MainUI::create_header_() {
lv_label_set_text(btn_label, LV_SYMBOL_SETTINGS);
lv_obj_center(btn_label);
lv_obj_set_style_anim_time(settings_btn_, 0, 0);
}
}
void MainUI::create_route_displays_() {
void MainUI::create_route_displays_() {
for (int i = 0; i < MAX_DISPLAY_ROUTES; i++) {
RouteDisplay& display = route_displays_[i];
@@ -132,7 +133,7 @@ void MainUI::create_route_displays_() {
lv_obj_set_style_border_width(display.container, 0, 0);
lv_obj_set_style_border_width(display.container, 1, 0);
lv_obj_set_style_border_side(display.container, LV_BORDER_SIDE_BOTTOM, 0);
lv_obj_set_style_border_color(display.container, lv_color_hex(0xC0C0C0), 0);
lv_obj_set_style_border_color(display.container, lv_color_black(), 0);
lv_obj_set_style_anim_time(display.container, 0, 0);
lv_obj_clear_flag(display.container, LV_OBJ_FLAG_SCROLLABLE);
lv_obj_add_flag(display.container, LV_OBJ_FLAG_HIDDEN); // Hidden by default
@@ -152,10 +153,10 @@ void MainUI::create_route_displays_() {
lv_obj_set_style_pad_left(display.arrival_labels[j], 10, 0);
}
}
}
}
void MainUI::update_arrivals(const std::vector<RouteArrivalData>& arrival_data) {
if (!lvgl_port_lock(pdMS_TO_TICKS(1000))) {
void MainUI::update_arrivals(const std::vector<RouteArrivalData>& arrival_data) {
if (!lvgl_port_lock(pdMS_TO_TICKS(LVGL_PORT_LOCK_TIMEOUT_MS))) {
ESP_LOGE(TAG, "Failed to acquire LVGL lock");
return;
}
@@ -179,9 +180,9 @@ void MainUI::update_arrivals(const std::vector<RouteArrivalData>& arrival_data)
}
lvgl_port_unlock();
}
}
void MainUI::update_route_display_(RouteDisplay& display, const RouteArrivalData& data) {
void MainUI::update_route_display_(RouteDisplay& display, const RouteArrivalData& data) {
// Show container if hidden
if (!display.cached_visible) {
lv_obj_clear_flag(display.container, LV_OBJ_FLAG_HIDDEN);
@@ -246,10 +247,10 @@ void MainUI::update_route_display_(RouteDisplay& display, const RouteArrivalData
display.cached_arrival_visible[0] = true;
}
}
}
}
void MainUI::update_last_refresh_time(const std::string& time_str) {
if (!lvgl_port_lock(pdMS_TO_TICKS(1000))) {
void MainUI::update_last_refresh_time(const std::string& time_str) {
if (!lvgl_port_lock(pdMS_TO_TICKS(LVGL_PORT_LOCK_TIMEOUT_MS))) {
ESP_LOGE(TAG, "Failed to acquire LVGL lock");
return;
}
@@ -261,10 +262,10 @@ void MainUI::update_last_refresh_time(const std::string& time_str) {
}
lvgl_port_unlock();
}
}
void MainUI::show_no_routes_message() {
if (!lvgl_port_lock(pdMS_TO_TICKS(1000))) {
void MainUI::show_no_routes_message() {
if (!lvgl_port_lock(pdMS_TO_TICKS(LVGL_PORT_LOCK_TIMEOUT_MS))) {
ESP_LOGE(TAG, "Failed to acquire LVGL lock");
return;
}
@@ -279,10 +280,10 @@ void MainUI::show_no_routes_message() {
lv_obj_clear_flag(msg_label_, LV_OBJ_FLAG_HIDDEN);
lvgl_port_unlock();
}
}
void MainUI::show_error_message(const std::string& message) {
if (!lvgl_port_lock(pdMS_TO_TICKS(1000))) {
void MainUI::show_error_message(const std::string& message) {
if (!lvgl_port_lock(pdMS_TO_TICKS(LVGL_PORT_LOCK_TIMEOUT_MS))) {
ESP_LOGE(TAG, "Failed to acquire LVGL lock");
return;
}
@@ -297,15 +298,15 @@ void MainUI::show_error_message(const std::string& message) {
lv_obj_clear_flag(msg_label_, LV_OBJ_FLAG_HIDDEN);
lvgl_port_unlock();
}
}
void MainUI::register_settings_button_callback(lv_event_cb_t cb, void* user_data) {
void MainUI::register_settings_button_callback(lv_event_cb_t cb, void* user_data) {
if (settings_btn_) {
lv_obj_add_event_cb(settings_btn_, cb, LV_EVENT_CLICKED, user_data);
}
}
}
lv_color_t MainUI::hex_to_lv_color_(const std::string& hex_color) {
lv_color_t MainUI::hex_to_lv_color_(const std::string& hex_color) {
if (hex_color.length() < 7 || hex_color[0] != '#') {
return lv_color_black();
}
@@ -315,6 +316,6 @@ lv_color_t MainUI::hex_to_lv_color_(const std::string& hex_color) {
unsigned int b = std::stoi(hex_color.substr(5, 2), nullptr, 16);
return lv_color_make(r, g, b);
}
}
} // namespace travel

View File

@@ -5,30 +5,160 @@
#include <ctime>
#include <iomanip>
#include <sstream>
#include <algorithm>
#include <cctype>
static const char* TAG = "TravelMainHandler";
namespace travel {
MainUIHandler::MainUIHandler()
// Helper functions shared by formatting routines
namespace {
// Parse an ISO 8601-like timestamp into epoch seconds (UTC).
// Supports formats like: 2024-01-15T14:30:00+08:00, 2026-02-03 23:08:22, or ...Z
bool parse_iso_to_epoch(const std::string& s, time_t& out_epoch) {
auto trim_copy = [](const std::string& in) {
size_t a = 0;
size_t b = in.size();
while (a < b && std::isspace((unsigned char)in[a])) ++a;
while (b > a && std::isspace((unsigned char)in[b - 1])) --b;
return in.substr(a, b - a);
};
std::string s_trim = trim_copy(s);
// Accept either 'T' or space (also lowercase 't') as date/time separator
size_t t_pos = s_trim.find_first_of("Tt ");
if (t_pos == std::string::npos) return false;
std::string date = trim_copy(s_trim.substr(0, t_pos));
std::string tzpart;
std::string timepart = trim_copy(s_trim.substr(t_pos + 1));
// Extract timezone (Z or +HH:MM or +HHMM or +HH)
size_t zpos = timepart.find_first_of("Zz");
if (zpos != std::string::npos) {
tzpart = "Z";
timepart = trim_copy(timepart.substr(0, zpos));
} else {
// Find first '+' or '-' AFTER the numeric time portion
size_t plus = std::string::npos;
for (size_t i = 0; i < timepart.size(); ++i) {
if (timepart[i] == '+' || timepart[i] == '-') { plus = i; break; }
}
if (plus != std::string::npos) {
tzpart = trim_copy(timepart.substr(plus));
timepart = trim_copy(timepart.substr(0, plus));
}
}
int year = 0, month = 0, day = 0;
if (sscanf(date.c_str(), "%d-%d-%d", &year, &month, &day) != 3) {
// Try alternative separators like '/'
if (sscanf(date.c_str(), "%d/%d/%d", &year, &month, &day) != 3) return false;
}
int hour = 0, min = 0, sec = 0;
// Remove fractional seconds if present (e.g., 10:34:52.123)
size_t dot = timepart.find('.');
if (dot != std::string::npos) timepart = timepart.substr(0, dot);
int time_parsed = sscanf(timepart.c_str(), "%d:%d:%d", &hour, &min, &sec);
if (time_parsed < 2) {
// Try hour only or hour:minute
if (sscanf(timepart.c_str(), "%d:%d", &hour, &min) == 2) {
sec = 0;
} else {
return false;
}
}
int parsed_offset_seconds = 0; // seconds east of UTC
bool has_tz = false;
if (!tzpart.empty()) {
has_tz = true;
if (tzpart == "Z" || tzpart == "z") {
parsed_offset_seconds = 0;
} else {
char sign = tzpart[0];
int oh = 0, om = 0;
std::string tznum = tzpart.substr(1);
// Accept +HH:MM, +HHMM, or +HH
if (sscanf(tznum.c_str(), "%d:%d", &oh, &om) == 2) {
parsed_offset_seconds = oh * 3600 + om * 60;
} else if (sscanf(tznum.c_str(), "%d", &oh) == 1) {
// If tz like 0800, interpret as HHMM when length>=3
if (tznum.size() >= 3 && tznum.find(':') == std::string::npos && tznum.size() <= 4) {
if (tznum.size() == 4) {
int hh = 0, mm = 0;
if (sscanf(tznum.c_str(), "%2d%2d", &hh, &mm) == 2) {
oh = hh; om = mm;
}
}
parsed_offset_seconds = oh * 3600 + om * 60;
} else {
parsed_offset_seconds = oh * 3600;
}
}
if (sign == '-') parsed_offset_seconds = -parsed_offset_seconds;
}
}
std::tm tm = {};
tm.tm_year = year - 1900;
tm.tm_mon = month - 1;
tm.tm_mday = day;
tm.tm_hour = hour;
tm.tm_min = min;
tm.tm_sec = sec;
tm.tm_isdst = -1;
time_t now = time(nullptr);
std::tm local_tm = *std::localtime(&now);
std::tm gm_tm = *std::gmtime(&now);
time_t local_epoch = mktime(&local_tm);
time_t gm_epoch = mktime(&gm_tm);
int local_offset = static_cast<int>(difftime(local_epoch, gm_epoch));
time_t epoch_assuming_local = mktime(&tm);
if (epoch_assuming_local == (time_t)-1) return false;
if (!has_tz) {
// No timezone provided: assume local time
out_epoch = epoch_assuming_local;
} else {
// Adjust when parsed time had a specific timezone
out_epoch = epoch_assuming_local + (local_offset - parsed_offset_seconds);
}
return true;
}
std::string format_epoch_HHMM(time_t epoch) {
std::tm at = *std::localtime(&epoch);
char buf[6];
strftime(buf, sizeof(buf), "%H:%M", &at);
return std::string(buf);
}
}
MainUIHandler::MainUIHandler()
: main_ui_(std::make_unique<MainUI>())
, mtr_handler_(std::make_unique<MTRNextTrainHandler>()) {
refresh_mutex_ = xSemaphoreCreateMutex();
}
}
MainUIHandler::~MainUIHandler() {
MainUIHandler::~MainUIHandler() {
deinit();
if (refresh_mutex_) {
vSemaphoreDelete(refresh_mutex_);
}
}
}
esp_err_t MainUIHandler::init(
esp_err_t MainUIHandler::init(
lv_obj_t* parent,
InteractionHandler* interaction_handler,
SettingHandler* setting_handler,
NetworkHandler* network_handler
) {
) {
ESP_LOGI(TAG, "Initializing main UI handler");
setting_handler_ = setting_handler;
@@ -71,9 +201,9 @@ esp_err_t MainUIHandler::init(
fetch_and_update_arrivals_();
return ESP_OK;
}
}
esp_err_t MainUIHandler::deinit() {
esp_err_t MainUIHandler::deinit() {
ESP_LOGI(TAG, "Deinitializing main UI handler");
// Stop polling task
@@ -90,21 +220,21 @@ esp_err_t MainUIHandler::deinit() {
}
return ESP_OK;
}
}
void MainUIHandler::register_on_settings_button_clicked(SettingsButtonCallback cb, void* user_data) {
void MainUIHandler::register_on_settings_button_clicked(SettingsButtonCallback cb, void* user_data) {
on_settings_callback_ = cb;
settings_callback_user_data_ = user_data;
}
}
void MainUIHandler::force_refresh() {
void MainUIHandler::force_refresh() {
if (xSemaphoreTake(refresh_mutex_, pdMS_TO_TICKS(1000)) == pdTRUE) {
fetch_and_update_arrivals_();
xSemaphoreGive(refresh_mutex_);
}
}
}
void MainUIHandler::polling_task_(void* param) {
void MainUIHandler::polling_task_(void* param) {
MainUIHandler* handler = static_cast<MainUIHandler*>(param);
while (handler->polling_running_) {
@@ -120,9 +250,9 @@ void MainUIHandler::polling_task_(void* param) {
}
vTaskDelete(nullptr);
}
}
void MainUIHandler::fetch_and_update_arrivals_() {
void MainUIHandler::fetch_and_update_arrivals_() {
if (!network_handler_ || !setting_handler_) {
return;
}
@@ -244,62 +374,65 @@ void MainUIHandler::fetch_and_update_arrivals_() {
cached_arrival_data_ = arrival_data;
}
main_ui_->update_last_refresh_time(get_current_time_string_());
}
}
std::string MainUIHandler::format_arrival_time_(const std::string& api_time) {
// API returns time in format like "2024-01-15T14:30:00+08:00" or "2"
// Check if it's a simple minute count
if (api_time.length() <= 2) {
std::string MainUIHandler::format_arrival_time_(const std::string& api_time) {
// Keep fallback for numeric minute strings (e.g., "0", "6", "15")
if (!api_time.empty() && std::all_of(api_time.begin(), api_time.end(), [](char c) { return std::isdigit((unsigned char)c); })) {
return api_time + "分鐘";
}
// Try to parse ISO format time
// Extract time part (HH:MM)
size_t t_pos = api_time.find('T');
if (t_pos != std::string::npos && api_time.length() > t_pos + 5) {
std::string time_part = api_time.substr(t_pos + 1, 5);
return time_part;
}
time_t arrival_epoch = 0;
if (parse_iso_to_epoch(api_time, arrival_epoch)) {
time_t now = time(nullptr);
double diff_seconds = difftime(arrival_epoch, now);
if (diff_seconds < 0) diff_seconds = 0; // already arrived -> show 0
int minutes = static_cast<int>((diff_seconds + 59) / 60); // round up
// Try to find HH:MM pattern in the string
for (size_t i = 0; i < api_time.length() - 5; i++) {
if (api_time[i] == ':' && i > 0 && i < api_time.length() - 3) {
std::string candidate = api_time.substr(i - 2, 5);
if (isdigit(candidate[0]) && isdigit(candidate[1]) && candidate[2] == ':' &&
isdigit(candidate[3]) && isdigit(candidate[4])) {
return candidate;
}
if (minutes < 60) {
return std::to_string(minutes) + "分鐘";
}
}
return ""; // Return empty instead of raw input
}
// Only relative minutes are returned from this function.
ESP_LOGW(TAG, "Unable to parse arrival time for relative format: %s", api_time.c_str());
return std::string();
}
std::string MainUIHandler::format_arrival_time_full_(const std::string& api_time) {
std::string MainUIHandler::format_arrival_time_full_(const std::string& api_time) {
// Returns absolute time for display (e.g., "14:32")
// Returns empty string for relative times
if (api_time.length() <= 2) {
ESP_LOGW(TAG, "Arrival time appears to be relative, no full time available: %s", api_time.c_str());
return "";
}
time_t arrival_epoch = 0;
if (parse_iso_to_epoch(api_time, arrival_epoch)) {
return format_epoch_HHMM(arrival_epoch);
}
// fallback: extract HH:MM
size_t t_pos = api_time.find('T');
if (t_pos != std::string::npos && api_time.length() > t_pos + 5) {
return api_time.substr(t_pos + 1, 5);
}
return "";
}
ESP_LOGW(TAG, "Unable to parse arrival time for full format: %s", api_time.c_str());
return std::string();
}
std::string MainUIHandler::get_current_time_string_() {
auto now = std::time(nullptr);
auto tm = *std::localtime(&now);
std::string MainUIHandler::get_current_time_string_() {
time_t now = time(nullptr);
std::tm tm = *std::localtime(&now);
char buffer[6]; // HH:MM\0
strftime(buffer, sizeof(buffer), "%H:%M", &tm);
char buffer[32];
// Return absolute local date and time: YYYY-MM-DD HH:MM
strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M", &tm);
return std::string(buffer);
}
}
bool MainUIHandler::has_arrival_data_changed_(const std::vector<RouteArrivalData>& new_data) {
bool MainUIHandler::has_arrival_data_changed_(const std::vector<RouteArrivalData>& new_data) {
if (new_data.size() != cached_arrival_data_.size()) {
return true;
}
@@ -328,19 +461,19 @@ bool MainUIHandler::has_arrival_data_changed_(const std::vector<RouteArrivalData
}
return false;
}
}
void MainUIHandler::on_settings_button_clicked_static_(lv_event_t* e) {
void MainUIHandler::on_settings_button_clicked_static_(lv_event_t* e) {
MainUIHandler* handler = static_cast<MainUIHandler*>(lv_event_get_user_data(e));
if (handler) {
handler->on_settings_button_clicked_();
}
}
}
void MainUIHandler::on_settings_button_clicked_() {
void MainUIHandler::on_settings_button_clicked_() {
if (on_settings_callback_) {
on_settings_callback_(settings_callback_user_data_);
}
}
}
} // namespace travel