[web_server] Reuse scheduler millis_64 for uptime instead of std::chrono

Replace the std::chrono::steady_clock approach with the scheduler's
existing millis_64() rollover tracking. This avoids pulling in
gettimeofday_r, system_clock, and the ArduinoJson int64_t serializer
template, saving ~270 bytes of flash and 8 bytes of RAM on ESP8266.

Send uptime as uint32_t seconds (good for ~136 years) instead of
int64_t milliseconds.
This commit is contained in:
J. Nick Koston
2026-02-19 22:47:05 -06:00
parent 9d0eb63fb4
commit badf09164e
3 changed files with 8 additions and 10 deletions
+3 -10
View File
@@ -15,8 +15,6 @@
#include "StreamString.h"
#endif
#include <chrono>
#include <cinttypes>
#include <cstdlib>
#ifdef USE_LIGHT
@@ -372,12 +370,6 @@ void WebServer::set_css_include(const char *css_include) { this->css_include_ =
void WebServer::set_js_include(const char *js_include) { this->js_include_ = js_include; }
#endif
/// Get uptime in milliseconds using std::chrono::steady_clock (64-bit, no rollover)
static int64_t get_uptime_ms() {
return std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now().time_since_epoch())
.count();
}
json::SerializationBuffer<> WebServer::get_config_json() {
json::JsonBuilder builder;
JsonObject root = builder.root();
@@ -393,7 +385,7 @@ json::SerializationBuffer<> WebServer::get_config_json() {
#endif
root[ESPHOME_F("log")] = this->expose_log_;
root[ESPHOME_F("lang")] = "en";
root[ESPHOME_F("uptime")] = get_uptime_ms();
root[ESPHOME_F("uptime")] = static_cast<uint32_t>(App.scheduler.millis_64() / 1000);
return builder.serialize();
}
@@ -422,7 +414,8 @@ void WebServer::setup() {
// getting a lot of events
this->set_interval(10000, [this]() {
char buf[32];
buf_append_printf(buf, sizeof(buf), 0, "{\"uptime\":%" PRId64 "}", get_uptime_ms());
auto uptime = static_cast<uint32_t>(App.scheduler.millis_64() / 1000);
buf_append_printf(buf, sizeof(buf), 0, "{\"uptime\":%u}", uptime);
this->events_.try_send_nodefer(buf, "ping", millis(), 30000);
});
}
+2
View File
@@ -675,6 +675,8 @@ bool HOT Scheduler::cancel_item_locked_(Component *component, NameType name_type
return total_cancelled > 0;
}
uint64_t Scheduler::millis_64() { return this->millis_64_(millis()); }
uint64_t Scheduler::millis_64_(uint32_t now) {
// THREAD SAFETY NOTE:
// This function has three implementations, based on the precompiler flags
+3
View File
@@ -116,6 +116,9 @@ class Scheduler {
ESPDEPRECATED("cancel_retry is deprecated and will be removed in 2026.8.0.", "2026.2.0")
bool cancel_retry(Component *component, uint32_t id);
/// Get 64-bit millisecond timestamp (handles 32-bit millis() rollover)
uint64_t millis_64();
// Calculate when the next scheduled item should run
// @param now Fresh timestamp from millis() - must not be stale/cached
// Returns the time in milliseconds until the next scheduled item, or nullopt if no items