From 0207e6e8b5f9a43afd829afc316b0ce17a58223f Mon Sep 17 00:00:00 2001 From: "J. Nick Koston" Date: Sun, 25 Jan 2026 23:04:26 -1000 Subject: [PATCH] [mqtt] Refactor state publishing with dedicated enum-to-string helpers --- esphome/components/mqtt/mqtt_component.cpp | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/esphome/components/mqtt/mqtt_component.cpp b/esphome/components/mqtt/mqtt_component.cpp index 5783dc2cc0c..66df994a320 100644 --- a/esphome/components/mqtt/mqtt_component.cpp +++ b/esphome/components/mqtt/mqtt_component.cpp @@ -159,10 +159,11 @@ bool MQTTComponent::publish(const char *topic, ProgmemStr payload) { if (topic[0] == '\0') return false; // On ESP8266, ProgmemStr is __FlashStringHelper* - need to copy from flash - size_t len = strlen_P(reinterpret_cast(payload)); - char buf[len + 1]; - memcpy_P(buf, reinterpret_cast(payload), len + 1); - return global_mqtt_client->publish(topic, buf, len, this->qos_, this->retain_); + // Max state string is "armed_custom_bypass" (19 chars) + null = 20 bytes + char buf[24]; + strncpy_P(buf, reinterpret_cast(payload), sizeof(buf) - 1); + buf[sizeof(buf) - 1] = '\0'; + return global_mqtt_client->publish(topic, buf, strlen(buf), this->qos_, this->retain_); } #endif