From 2288f8eb5e2eca255ba039691bc766e13c495942 Mon Sep 17 00:00:00 2001 From: "J. Nick Koston" Date: Mon, 5 Jan 2026 23:35:24 -1000 Subject: [PATCH] [debug] Use stack buffers with buf_append helper instead of std::string --- esphome/components/debug/debug_component.h | 22 ++++++++++++++++++++++ esphome/components/debug/debug_esp8266.cpp | 2 +- 2 files changed, 23 insertions(+), 1 deletion(-) diff --git a/esphome/components/debug/debug_component.h b/esphome/components/debug/debug_component.h index 8c37a66158..09f08a37ba 100644 --- a/esphome/components/debug/debug_component.h +++ b/esphome/components/debug/debug_component.h @@ -8,6 +8,9 @@ #include #include #include +#ifdef USE_ESP8266 +#include +#endif #ifdef USE_SENSOR #include "esphome/components/sensor/sensor.h" @@ -22,6 +25,24 @@ namespace debug { static constexpr size_t DEVICE_INFO_BUFFER_SIZE = 256; static constexpr size_t RESET_REASON_BUFFER_SIZE = 128; +#ifdef USE_ESP8266 +// ESP8266: Use vsnprintf_P to keep format strings in flash (PROGMEM) +// Format strings must be wrapped with PSTR() macro +inline size_t buf_append_P(char *buf, size_t size, size_t pos, PGM_P fmt, ...) { + if (pos >= size) { + return size; + } + va_list args; + va_start(args, fmt); + int written = vsnprintf_P(buf + pos, size - pos, fmt, args); + va_end(args); + if (written < 0) { + return pos; // encoding error + } + return std::min(pos + static_cast(written), size); +} +#define buf_append(buf, size, pos, fmt, ...) buf_append_P(buf, size, pos, PSTR(fmt), ##__VA_ARGS__) +#else /// Safely append formatted string to buffer, returning new position (capped at size) __attribute__((format(printf, 4, 5))) inline size_t buf_append(char *buf, size_t size, size_t pos, const char *fmt, ...) { @@ -37,6 +58,7 @@ __attribute__((format(printf, 4, 5))) inline size_t buf_append(char *buf, size_t } return std::min(pos + static_cast(written), size); } +#endif class DebugComponent : public PollingComponent { public: diff --git a/esphome/components/debug/debug_esp8266.cpp b/esphome/components/debug/debug_esp8266.cpp index 8b36fa46de..274f77e20d 100644 --- a/esphome/components/debug/debug_esp8266.cpp +++ b/esphome/components/debug/debug_esp8266.cpp @@ -12,7 +12,7 @@ const char *DebugComponent::get_reset_reason_(std::span