fix(m1): add rtc time sources, responsive status rendering, and key documentation (#5)

## Summary

Fixes three user-reported M1 defects (root causes pre-diagnosed):

1. **RTC permanently invalid** (`-` on screen, `"utc":""` in JSONL, 228x
`ESP_ERR_INVALID_CRC`):
nothing ever wrote the PCF85063, so after power loss its OS (oscillator
stopped) bit stays set.
- `board_service::set_rtc_time(int64_t)`: gmtime_r -> BCD -> multi-byte
I2C write of registers
0x04-0x0A with seconds bit7=0 (clears OS), then re-read confirms; I2C
access serialized
against `read_rtc` with a FreeRTOS mutex (console/SNTP context safe).
- `time_sync` service: on Wi-Fi CONNECTED starts `esp_netif_sntp`
(ntp.aliyun.com +
pool.ntp.org, `CONFIG_LWIP_SNTP_MAX_SERVERS=2`), and once `time()`
passes 2020-01-01 writes
     the RTC once per sync (`rtc synced from sntp`).
- Console: `rtc status` (valid/unix/utc/OS bit), `rtc raw` (0x00-0x0A
hex + decode),
`rtc set YYYY-MM-DD HH:MM:SS` (strptime, UTC, range + calendar
round-trip validation).

2. **KEY feels slow**: display rendering was throttled to 10 s.
`display_service::run` now keeps
the 10 s full-render heartbeat (with memory refresh) but adds a 500 ms
fast path that
re-renders as soon as a signature over volatile fields (key counters,
key_pressed, wifi/storage
state, tf_logging_ok, ap_active, ssid_configured, rtc valid+minute)
changes. KEY counter now
   appears within ~0.5-1 s.

3. **Which button?**: README now documents that only KEY (GPIO18) is
monitored; RST reboots and
BOOT (GPIO0) does nothing, plus the `rtc` commands, SNTP behavior, and
the CR1220 coin-cell
   note (without a battery every power loss clears the clock again).

## On-device evidence

Single-session serial on /dev/ttyACM0 (see
`.omo/evidence/m1wp/rtc-render-fix-finish-m1-wifi-provisioning.log`):

- Post-flash boot auto-connected Wi-Fi and SNTP-synced the RTC before
the console attached
(pre-manual-set `rtc status` already showed real UTC 2026-08-31
05:17:55, OS bit clear).
- `rtc set 2026-08-31 12:00:00` -> `ESP_OK`; `rtc status` valid and
advancing across polls
(12:14:59 -> 12:15:49); JSONL `utc_valid:true` + non-empty `utc` with 10
s cadence and crc32c.
- Explicit RTS reset round captured live: `frame-time: sntp started
(ntp.aliyun.com,
pool.ntp.org)` and `frame-time: rtc synced from sntp (unix 1788154496)`
7.8 s after reset;
  device-vs-host time delta 4 s.
- Pre-fix invalid state (OS bit set -> ESP_ERR_INVALID_CRC) is
documented in the prior soak
  evidence (F3 log); the fix clears it on the first SNTP sync.
- KEY latency: no user press within the two assist windows;
console-observer polling at 500 ms
shows counters served immediately from the shared snapshot the display
fast path renders
(CITED: `volatile_signature` + 500 ms check in `display_service.cc`), 10
s heartbeat captured
  via memory-metric refresh.
- Regression: `status --json` tf_logging=true, wifi=CONNECTED, selftest
`wifi_config: ok`.

Build 0 warnings; clang-format 18 clean;
pytest/ruff/frame-evidence/frame-doc-links green.

Co-authored-by: ania-lain <[email protected]>
This commit is contained in:
Lain
2026-08-31 13:42:06 +08:00
committed by GitHub
co-authored by lain
parent 5bbd2fe6cc
commit e9f8b7386b
11 changed files with 398 additions and 11 deletions
+30
View File
@@ -21,6 +21,29 @@ live scan; hidden networks cannot be typed into the browser form — configure t
console with `wifi set <ssid> hidden`. Holding KEY for 3 seconds or longer also requests the setup
hotspot; such a hold is a portal command and does not count as a button press.
## Buttons
The only monitored button is the board's **KEY** button (GPIO18, active-low): a release under 1
second counts as a short press, 1-3 seconds as a long press, and 3 seconds or more requests the
setup hotspot. Both counters appear on the display and in `status`. The **RST** button resets the
board, and **BOOT** (GPIO0) is not monitored — pressing either does not change any counter.
## Real-Time Clock
The PCF85063 RTC shares the I2C bus with the SHTC3. Nothing writes the chip from the factory, so
after a power loss its oscillator-stopped (OS) flag is set and the time reads invalid on the
display (`-`) and in JSONL (`"utc":""`). The firmware now provides two time sources:
- **SNTP:** once the station has an IP address, the firmware starts SNTP against
`ntp.aliyun.com` and `pool.ntp.org`, and on the first successful sync writes the UTC time to
the RTC (log line `rtc synced from sntp`). SNTP keeps running; periodic re-syncs update the
system clock.
- **Console:** `rtc set` writes the chip manually (UTC is assumed).
A CR1220 coin cell on the board keeps the RTC running across power-off. Without a battery (or
with an empty one) every boot loses the time and the OS flag returns — install a fresh cell for
persistence across power loss.
Build with the exact IDF tag:
```sh
@@ -33,6 +56,9 @@ The console is available through USB Serial/JTAG at 115200 baud. Useful commands
```text
status [--json]
rtc status
rtc raw
rtc set YYYY-MM-DD HH:MM:SS
wifi set <ssid> [hidden]
wifi clear
wifi reconnect
@@ -45,6 +71,10 @@ storage status
selftest
```
`rtc status` reports validity, unix time, formatted UTC, and the OS-bit state; `rtc raw` dumps
PCF85063 registers 0x00-0x0A with a decode; `rtc set` parses `YYYY-MM-DD HH:MM:SS` as UTC,
validates the ranges, writes the chip, and re-reads it to confirm.
Do not place real credentials in command transcripts or committed evidence. `wifi set` asks for the
password after parsing the command so it is not stored in command history; terminal software must
also keep local echo disabled. The password is persisted only inside `/system/wifi.json` under the
+1
View File
@@ -8,6 +8,7 @@ idf_component_register(
"sd_service.cc"
"st7305_panel.cc"
"status_log.cc"
"time_sync.cc"
"wifi_provision.cc"
"wifi_service.cc"
INCLUDE_DIRS "."
+6 -3
View File
@@ -6,6 +6,7 @@
#include "hardware_status.hh"
#include "nvs_flash.h"
#include "sd_service.hh"
#include "time_sync.hh"
#include "wifi_provision.hh"
#include "wifi_service.hh"
#include <cinttypes>
@@ -43,7 +44,8 @@ extern "C" void app_main(void) {
static wifi_service wifi(status);
static wifi_provision provision(status, wifi);
static display_service display(status);
static console_service console(status, storage, wifi, provision);
static console_service console(status, board, storage, wifi, provision);
static time_sync timesync(status, board);
const esp_err_t board_result = board.start();
const esp_err_t storage_result = storage.start();
@@ -52,11 +54,12 @@ extern "C" void app_main(void) {
const esp_err_t display_result = display.start();
const esp_err_t console_result = console.start();
const esp_err_t saved_result = provision.start_saved_or_pending();
const esp_err_t timesync_result = timesync.start();
ESP_LOGI(kTag, "services board=%s storage=%s wifi=%s display=%s console=%s",
esp_err_to_name(board_result), esp_err_to_name(storage_result),
esp_err_to_name(wifi_result), esp_err_to_name(display_result),
esp_err_to_name(console_result));
ESP_LOGI(kTag, "provision mount=%s saved=%s", esp_err_to_name(provision_mount_result),
esp_err_to_name(saved_result));
ESP_LOGI(kTag, "provision mount=%s saved=%s time=%s", esp_err_to_name(provision_mount_result),
esp_err_to_name(saved_result), esp_err_to_name(timesync_result));
}
+83 -3
View File
@@ -1,5 +1,7 @@
#include "board_service.hh"
#include <ctime>
#include "board_config.hh"
#include "driver/gpio.h"
#include "esp_log.h"
@@ -13,6 +15,8 @@ constexpr uint16_t kSensorWake = 0x3517;
constexpr uint16_t kSensorMeasure = 0x7866;
constexpr uint16_t kSensorSleep = 0xB098;
constexpr uint8_t kRtcSecondsRegister = 0x04;
constexpr uint8_t kRtcFirstRegister = 0x00;
constexpr std::size_t kRtcRegisterCount = 11;
// KEY release bands: <1s short press, 1s..<3s long press, >=3s provisioning portal command.
constexpr int64_t kKeyLongPressUs = 1000000;
constexpr int64_t kKeyPortalHoldUs = 3000000;
@@ -31,6 +35,10 @@ uint8_t from_bcd(uint8_t value) {
return static_cast<uint8_t>((value >> 4U) * 10U + (value & 0x0FU));
}
uint8_t to_bcd(unsigned value) {
return static_cast<uint8_t>(((value / 10U) << 4U) | (value % 10U));
}
} // namespace
board_service::~board_service() {
@@ -132,11 +140,15 @@ esp_err_t board_service::read_rtc() {
if (rtc_ == nullptr) {
return ESP_ERR_NOT_FOUND;
}
if (i2c_mutex_ == nullptr || xSemaphoreTake(i2c_mutex_, pdMS_TO_TICKS(500)) != pdTRUE) {
return ESP_ERR_INVALID_STATE;
}
uint8_t registers[7]{};
esp_err_t result = i2c_master_transmit(rtc_, &kRtcSecondsRegister, 1, 100);
if (result == ESP_OK) {
result = i2c_master_receive(rtc_, registers, sizeof(registers), 100);
}
xSemaphoreGive(i2c_mutex_);
if (result != ESP_OK) {
status_.update([](status_snapshot& value) { value.rtc.valid = false; });
return result;
@@ -152,9 +164,8 @@ esp_err_t board_service::read_rtc() {
const bool plausible = !oscillator_stopped && second < 60 && minute < 60 && hour < 24 &&
day >= 1 && day <= 31 && month >= 1 && month <= 12 && year <= 2099;
const int64_t unix_seconds = days_from_civil(year, month, day) * 86400LL +
static_cast<int64_t>(hour) * 3600LL +
static_cast<int64_t>(minute) * 60LL + static_cast<int64_t>(second);
const int64_t unix_seconds =
unix_from_utc(static_cast<int>(year), month, day, hour, minute, second);
const bool valid = plausible && unix_seconds > 0;
status_.update([&](status_snapshot& value) {
value.rtc = {.unix_seconds = valid ? unix_seconds : 0,
@@ -164,6 +175,75 @@ esp_err_t board_service::read_rtc() {
return valid ? ESP_OK : ESP_ERR_INVALID_CRC;
}
esp_err_t board_service::read_rtc_raw(uint8_t registers[11]) {
if (rtc_ == nullptr) {
return ESP_ERR_NOT_FOUND;
}
if (i2c_mutex_ == nullptr || xSemaphoreTake(i2c_mutex_, pdMS_TO_TICKS(500)) != pdTRUE) {
return ESP_ERR_INVALID_STATE;
}
esp_err_t result = i2c_master_transmit(rtc_, &kRtcFirstRegister, 1, 100);
if (result == ESP_OK) {
result = i2c_master_receive(rtc_, registers, kRtcRegisterCount, 100);
}
xSemaphoreGive(i2c_mutex_);
return result;
}
esp_err_t board_service::set_rtc_time(int64_t unix_seconds) {
if (rtc_ == nullptr) {
return ESP_ERR_NOT_FOUND;
}
time_t seconds = static_cast<time_t>(unix_seconds);
struct tm utc_time {};
if (unix_seconds <= 0 || gmtime_r(&seconds, &utc_time) == nullptr) {
return ESP_ERR_INVALID_ARG;
}
const int year = utc_time.tm_year + 1900;
if (year < 2000 || year > 2099) {
return ESP_ERR_INVALID_ARG;
}
const unsigned weekday = utc_time.tm_wday == 0 ? 7U : static_cast<unsigned>(utc_time.tm_wday);
// Multi-byte write at 0x04; seconds bit7=0 clears the PCF85063 OS (oscillator stopped) flag.
const uint8_t payload[]{
kRtcSecondsRegister,
to_bcd(static_cast<unsigned>(utc_time.tm_sec)),
to_bcd(static_cast<unsigned>(utc_time.tm_min)),
to_bcd(static_cast<unsigned>(utc_time.tm_hour)),
to_bcd(static_cast<unsigned>(utc_time.tm_mday)),
to_bcd(weekday),
to_bcd(static_cast<unsigned>(utc_time.tm_mon) + 1U),
to_bcd(static_cast<unsigned>(year - 2000)),
};
if (i2c_mutex_ == nullptr || xSemaphoreTake(i2c_mutex_, pdMS_TO_TICKS(500)) != pdTRUE) {
return ESP_ERR_INVALID_STATE;
}
const esp_err_t result = i2c_master_transmit(rtc_, payload, sizeof(payload), 100);
xSemaphoreGive(i2c_mutex_);
if (result != ESP_OK) {
return result;
}
// Confirm by re-reading; the oscillator may tick up to two seconds meanwhile.
const esp_err_t confirm = read_rtc();
if (confirm != ESP_OK) {
return confirm;
}
const status_snapshot value = status_.snapshot();
if (!value.rtc.valid || value.rtc.unix_seconds < unix_seconds ||
value.rtc.unix_seconds > unix_seconds + 2) {
return ESP_ERR_INVALID_CRC;
}
ESP_LOGI(kTag, "rtc time set to unix %" PRId64, unix_seconds);
return ESP_OK;
}
int64_t board_service::unix_from_utc(int year, unsigned month, unsigned day, unsigned hour,
unsigned minute, unsigned second) {
return days_from_civil(year, month, day) * 86400LL + static_cast<int64_t>(hour) * 3600LL +
static_cast<int64_t>(minute) * 60LL + static_cast<int64_t>(second);
}
esp_err_t board_service::sample_sensor() {
const uint8_t wake[]{static_cast<uint8_t>(kSensorWake >> 8U),
static_cast<uint8_t>(kSensorWake)};
+15 -1
View File
@@ -1,8 +1,11 @@
#pragma once
#include <cstdint>
#include "driver/i2c_master.h"
#include "esp_err.h"
#include "freertos/FreeRTOS.h"
#include "freertos/semphr.h"
#include "freertos/task.h"
#include "hardware_status.hh"
@@ -11,7 +14,8 @@ namespace frame::m1 {
class board_service {
public:
explicit board_service(hardware_status& status) : status_(status) {}
explicit board_service(hardware_status& status)
: status_(status), i2c_mutex_(xSemaphoreCreateMutex()) {}
~board_service();
board_service(const board_service&) = delete;
@@ -19,6 +23,15 @@ class board_service {
esp_err_t start();
// Sets the PCF85063 clock from UTC unix seconds; safe from the console or SNTP context
// (I2C access is serialized against read_rtc with i2c_mutex_).
esp_err_t set_rtc_time(int64_t unix_seconds);
// Reads PCF85063 registers 0x00-0x0A for diagnostics; 11 bytes into `registers`.
esp_err_t read_rtc_raw(uint8_t registers[11]);
// Civil UTC date/time to unix seconds; shared by the RTC read and console `rtc set`.
static int64_t unix_from_utc(int year, unsigned month, unsigned day, unsigned hour,
unsigned minute, unsigned second);
private:
static void task_entry(void* context);
static uint8_t crc8(const uint8_t* data, std::size_t size);
@@ -32,6 +45,7 @@ class board_service {
i2c_master_bus_handle_t bus_{};
i2c_master_dev_handle_t sensor_{};
i2c_master_dev_handle_t rtc_{};
SemaphoreHandle_t i2c_mutex_{};
TaskHandle_t task_{};
};
@@ -15,6 +15,10 @@ namespace {
constexpr char kSelftestSsid[] = "frame-selftest";
constexpr char kSelftestPassword[] = "frame-selftest-pass";
uint8_t from_bcd(uint8_t value) {
return static_cast<uint8_t>((value >> 4U) * 10U + (value & 0x0FU));
}
} // namespace
esp_err_t console_service::start() {
@@ -69,6 +73,15 @@ esp_err_t console_service::start() {
.func_w_context = nullptr,
.context = nullptr,
};
const esp_console_cmd_t rtc_cmd{
.command = "rtc",
.help = "rtc status | rtc raw | rtc set YYYY-MM-DD HH:MM:SS (UTC)",
.hint = nullptr,
.func = &console_service::rtc_command,
.argtable = nullptr,
.func_w_context = nullptr,
.context = nullptr,
};
esp_err_t result = esp_console_cmd_register(&status_cmd);
if (result == ESP_OK) {
@@ -83,6 +96,9 @@ esp_err_t console_service::start() {
if (result == ESP_OK) {
result = esp_console_cmd_register(&selftest_cmd);
}
if (result == ESP_OK) {
result = esp_console_cmd_register(&rtc_cmd);
}
if (result != ESP_OK) {
return result;
}
@@ -217,6 +233,111 @@ int console_service::selftest_command(int argc, char** argv) {
return 0;
}
int console_service::rtc_command(int argc, char** argv) {
if (argc == 2 && std::strcmp(argv[1], "status") == 0) {
instance_->print_rtc_status();
return 0;
}
if (argc == 2 && std::strcmp(argv[1], "raw") == 0) {
return instance_->print_rtc_raw();
}
if (argc == 4 && std::strcmp(argv[1], "set") == 0) {
return instance_->run_rtc_set(argv[2], argv[3]);
}
std::printf("usage: rtc status | rtc raw | rtc set YYYY-MM-DD HH:MM:SS\n");
return 1;
}
void console_service::print_rtc_status() const {
const status_snapshot value = status_.snapshot();
std::printf("RTC: %s\n", value.rtc_present ? "present (PCF85063 @0x51)" : "missing (0x51)");
uint8_t registers[11]{};
const esp_err_t raw_result = board_.read_rtc_raw(registers);
const char* os_state = "unknown (raw read failed)";
if (raw_result == ESP_OK) {
os_state = (registers[4] & 0x80U) != 0U ? "set (oscillator stopped)" : "clear";
}
std::printf("valid: %s unix: %" PRId64 "\n", value.rtc.valid ? "true" : "false",
value.rtc.unix_seconds);
char utc[32]{};
if (value.rtc.valid) {
const time_t seconds = static_cast<time_t>(value.rtc.unix_seconds);
struct tm utc_time {};
if (gmtime_r(&seconds, &utc_time) != nullptr) {
const unsigned year = static_cast<unsigned>(utc_time.tm_year + 1900);
std::snprintf(
utc, sizeof(utc), "%04u-%02u-%02u %02u:%02u:%02u", year,
static_cast<unsigned>(utc_time.tm_mon + 1), static_cast<unsigned>(utc_time.tm_mday),
static_cast<unsigned>(utc_time.tm_hour), static_cast<unsigned>(utc_time.tm_min),
static_cast<unsigned>(utc_time.tm_sec));
}
}
std::printf("utc: %s\n", utc[0] == '\0' ? "-" : utc);
std::printf("OS bit: %s\n", os_state);
}
int console_service::print_rtc_raw() const {
uint8_t registers[11]{};
const esp_err_t result = board_.read_rtc_raw(registers);
if (result != ESP_OK) {
std::printf("rtc raw: %s\n", esp_err_to_name(result));
return 1;
}
static const char* names[11] = {"control_1", "control_2", "offset", "ram",
"seconds", "minutes", "hours", "days",
"weekdays", "months", "years"};
for (unsigned index = 0; index < 11; ++index) {
std::printf(" 0x%02X %s\n", registers[index], names[index]);
}
std::printf("OS bit (0x04 bit7): %s\n", (registers[4] & 0x80U) != 0U ? "set" : "clear");
std::printf("decode: %04u-%02u-%02u %02u:%02u:%02u weekday %u\n",
2000 + from_bcd(registers[10]), from_bcd(registers[9] & 0x1FU),
from_bcd(registers[7] & 0x3FU), from_bcd(registers[6] & 0x3FU),
from_bcd(registers[5] & 0x7FU), from_bcd(registers[4] & 0x7FU),
from_bcd(registers[8] & 0x07U));
return 0;
}
int console_service::run_rtc_set(const char* date_text, const char* time_text) {
char text[40]{};
if (std::snprintf(text, sizeof(text), "%s %s", date_text, time_text) >=
static_cast<int>(sizeof(text))) {
std::printf("rtc set: input too long\n");
return 1;
}
struct tm parsed {};
if (strptime(text, "%Y-%m-%d %H:%M:%S", &parsed) == nullptr) {
std::printf("rtc set: unparseable, expected YYYY-MM-DD HH:MM:SS (UTC)\n");
return 1;
}
const int year = parsed.tm_year + 1900;
const unsigned month = static_cast<unsigned>(parsed.tm_mon) + 1U;
if (year < 2000 || year > 2099 || month < 1 || month > 12 || parsed.tm_mday < 1 ||
parsed.tm_mday > 31 || parsed.tm_hour < 0 || parsed.tm_hour > 23 || parsed.tm_min < 0 ||
parsed.tm_min > 59 || parsed.tm_sec < 0 || parsed.tm_sec > 59) {
std::printf("rtc set: value out of range\n");
return 1;
}
const int64_t unix_seconds = board_service::unix_from_utc(
year, month, static_cast<unsigned>(parsed.tm_mday), static_cast<unsigned>(parsed.tm_hour),
static_cast<unsigned>(parsed.tm_min), static_cast<unsigned>(parsed.tm_sec));
time_t check_seconds = static_cast<time_t>(unix_seconds);
struct tm check {};
if (gmtime_r(&check_seconds, &check) == nullptr || check.tm_year != parsed.tm_year ||
check.tm_mon != parsed.tm_mon || check.tm_mday != parsed.tm_mday ||
check.tm_hour != parsed.tm_hour || check.tm_min != parsed.tm_min ||
check.tm_sec != parsed.tm_sec) {
std::printf("rtc set: impossible calendar date\n");
return 1;
}
const esp_err_t result = board_.set_rtc_time(unix_seconds);
std::printf("rtc set: %s (unix %" PRId64 ")\n", esp_err_to_name(result), unix_seconds);
return result == ESP_OK ? 0 : 1;
}
void console_service::run_wifi_config_selftest() const {
char prior_ssid[33]{};
char prior_password[64]{};
+9 -3
View File
@@ -2,6 +2,7 @@
#include "esp_err.h"
#include "board_service.hh"
#include "hardware_status.hh"
#include "sd_service.hh"
#include "wifi_provision.hh"
@@ -11,9 +12,9 @@ namespace frame::m1 {
class console_service {
public:
console_service(hardware_status& status, sd_service& storage, wifi_service& wifi,
wifi_provision& provision)
: status_(status), storage_(storage), wifi_(wifi), provision_(provision) {}
console_service(hardware_status& status, board_service& board, sd_service& storage,
wifi_service& wifi, wifi_provision& provision)
: status_(status), board_(board), storage_(storage), wifi_(wifi), provision_(provision) {}
esp_err_t start();
@@ -23,11 +24,16 @@ class console_service {
static int storage_command(int argc, char** argv);
static int selftest_command(int argc, char** argv);
static int prov_command(int argc, char** argv);
static int rtc_command(int argc, char** argv);
void print_status(bool json) const;
void print_rtc_status() const;
int print_rtc_raw() const;
int run_rtc_set(const char* date_text, const char* time_text);
void run_wifi_config_selftest() const;
inline static console_service* instance_{};
hardware_status& status_;
board_service& board_;
sd_service& storage_;
wifi_service& wifi_;
wifi_provision& provision_;
+35 -1
View File
@@ -19,9 +19,30 @@ constexpr int kDrawRows = 40;
constexpr std::size_t kDrawBytes =
board::kDisplayWidth / 8U * static_cast<std::size_t>(kDrawRows) + 2U * sizeof(lv_color32_t);
constexpr int64_t kRenderIntervalUs = 10LL * 1000LL * 1000LL;
constexpr int64_t kFastCheckIntervalUs = 500LL * 1000LL;
uint32_t tick_milliseconds() { return static_cast<uint32_t>(esp_timer_get_time() / 1000); }
// Volatile-field digest; a change means the visible status text would change, so the
// 500ms fast path re-renders without waiting for the 10s heartbeat.
uint64_t volatile_signature(const status_snapshot& value) {
uint64_t signature = UINT64_C(1469598103934665603);
const auto fold = [&signature](uint64_t field) {
signature = (signature ^ field) * UINT64_C(1099511628211);
};
fold(value.key_short_presses);
fold(value.key_long_presses);
fold(value.key_pressed ? 1U : 0U);
fold(static_cast<uint64_t>(value.wifi));
fold(static_cast<uint64_t>(value.storage));
fold(value.tf_logging_ok ? 1U : 0U);
fold(value.ap_active ? 1U : 0U);
fold(value.ssid_configured ? 1U : 0U);
fold(value.rtc.valid ? 1U : 0U);
fold(value.rtc.valid ? static_cast<uint64_t>(value.rtc.unix_seconds / 60) : 0U);
return signature;
}
void format_rtc_time(const status_snapshot& value, char* output, std::size_t capacity) {
output[0] = '\0';
if (!value.rtc.valid) {
@@ -198,12 +219,25 @@ void display_service::run() {
}
int64_t next_render_at = 0;
int64_t next_check_at = 0;
uint64_t last_signature = 0;
while (true) {
const int64_t now = esp_timer_get_time();
if (now >= next_render_at) {
status_.refresh_memory_metrics();
render_status(status_.snapshot());
const status_snapshot value = status_.snapshot();
render_status(value);
last_signature = volatile_signature(value);
next_render_at = now + kRenderIntervalUs;
next_check_at = now + kFastCheckIntervalUs;
} else if (now >= next_check_at) {
const status_snapshot value = status_.snapshot();
const uint64_t signature = volatile_signature(value);
if (signature != last_signature) {
render_status(value);
last_signature = signature;
}
next_check_at = now + kFastCheckIntervalUs;
}
const uint32_t delay = std::clamp(lv_timer_handler(), UINT32_C(10), UINT32_C(1000));
vTaskDelay(pdMS_TO_TICKS(delay));
+62
View File
@@ -0,0 +1,62 @@
#include "time_sync.hh"
#include <cinttypes>
#include <ctime>
#include "esp_log.h"
#include "esp_netif_sntp.h"
namespace frame::m1 {
namespace {
constexpr char kTag[] = "frame-time";
constexpr const char* kSntpServers[] = {"ntp.aliyun.com", "pool.ntp.org"};
constexpr int kPollIntervalMs = 1000;
// SNTP timestamps before 2020-01-01 mean the system clock never synced.
constexpr time_t kSyncThreshold = 1577836800;
} // namespace
esp_err_t time_sync::start() {
const BaseType_t created =
xTaskCreatePinnedToCore(&time_sync::task_entry, "frame-time", 4096, this, 5, &task_, 0);
return created == pdPASS ? ESP_OK : ESP_ERR_NO_MEM;
}
void time_sync::task_entry(void* context) { static_cast<time_sync*>(context)->run(); }
void time_sync::run() {
for (;;) {
vTaskDelay(pdMS_TO_TICKS(kPollIntervalMs));
const status_snapshot value = status_.snapshot();
if (!sntp_started_ && value.wifi == wifi_state::connected) {
esp_sntp_config_t config{};
config.start = true;
config.wait_for_sync = false;
config.num_of_servers = 2;
config.servers[0] = kSntpServers[0];
config.servers[1] = kSntpServers[1];
const esp_err_t result = esp_netif_sntp_init(&config);
if (result == ESP_OK) {
sntp_started_ = true;
ESP_LOGI(kTag, "sntp started (%s, %s)", kSntpServers[0], kSntpServers[1]);
} else {
ESP_LOGW(kTag, "sntp start failed: %s", esp_err_to_name(result));
}
}
if (sntp_started_ && !rtc_synced_ && time(nullptr) > kSyncThreshold) {
const int64_t unix_seconds = static_cast<int64_t>(time(nullptr));
const esp_err_t result = board_.set_rtc_time(unix_seconds);
if (result == ESP_OK) {
rtc_synced_ = true;
ESP_LOGI(kTag, "rtc synced from sntp (unix %" PRId64 ")", unix_seconds);
} else {
ESP_LOGW(kTag, "rtc sync from sntp failed: %s", esp_err_to_name(result));
}
}
}
}
} // namespace frame::m1
+34
View File
@@ -0,0 +1,34 @@
#pragma once
#include "esp_err.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "board_service.hh"
#include "hardware_status.hh"
namespace frame::m1 {
// Starts SNTP once the station has an IP and mirrors the synced system clock into the
// PCF85063 RTC exactly once per sync (rising edge of time() crossing the sync threshold).
class time_sync {
public:
time_sync(hardware_status& status, board_service& board) : status_(status), board_(board) {}
time_sync(const time_sync&) = delete;
time_sync& operator=(const time_sync&) = delete;
esp_err_t start();
private:
static void task_entry(void* context);
void run();
hardware_status& status_;
board_service& board_;
TaskHandle_t task_{};
bool sntp_started_{};
bool rtc_synced_{};
};
} // namespace frame::m1
+2
View File
@@ -42,3 +42,5 @@ CONFIG_LV_USE_FLEX=y
CONFIG_LV_FONT_MONTSERRAT_16=y
CONFIG_LV_FONT_MONTSERRAT_24=y
CONFIG_LV_FONT_MONTSERRAT_40=y
CONFIG_LWIP_SNTP_MAX_SERVERS=2