diff --git a/esphome/components/sun_gtil2/sun_gtil2.cpp b/esphome/components/sun_gtil2/sun_gtil2.cpp index 46b4902654..d416d9a636 100644 --- a/esphome/components/sun_gtil2/sun_gtil2.cpp +++ b/esphome/components/sun_gtil2/sun_gtil2.cpp @@ -47,14 +47,15 @@ void SunGTIL2::loop() { } } -std::string SunGTIL2::state_to_string_(uint8_t state) { +const char *SunGTIL2::state_to_string_(uint8_t state, std::span buffer) { switch (state) { case 0x02: return "Starting voltage too low"; case 0x07: return "Working"; default: - return str_sprintf("Unknown (0x%02x)", state); + snprintf(buffer.data(), buffer.size(), "Unknown (0x%02x)", state); + return buffer.data(); } } @@ -106,12 +107,11 @@ void SunGTIL2::handle_char_(uint8_t c) { #endif #ifdef USE_TEXT_SENSOR if (this->state_ != nullptr) { - this->state_->publish_state(this->state_to_string_(msg.state)); + char state_buffer[STATE_BUFFER_SIZE]; + this->state_->publish_state(this->state_to_string_(msg.state, state_buffer)); } if (this->serial_number_ != nullptr) { - std::string serial_number; - serial_number.assign(msg.serial_number, 10); - this->serial_number_->publish_state(serial_number); + this->serial_number_->publish_state(msg.serial_number, 10); } #endif } diff --git a/esphome/components/sun_gtil2/sun_gtil2.h b/esphome/components/sun_gtil2/sun_gtil2.h index 0c29ae695d..3e28527cf7 100644 --- a/esphome/components/sun_gtil2/sun_gtil2.h +++ b/esphome/components/sun_gtil2/sun_gtil2.h @@ -1,5 +1,7 @@ #pragma once +#include + #include "esphome/core/component.h" #include "esphome/core/defines.h" @@ -34,8 +36,10 @@ class SunGTIL2 : public Component, public uart::UARTDevice { void set_serial_number(text_sensor::TextSensor *text_sensor) { serial_number_ = text_sensor; } #endif + static constexpr size_t STATE_BUFFER_SIZE = 32; + protected: - std::string state_to_string_(uint8_t state); + const char *state_to_string_(uint8_t state, std::span buffer); #ifdef USE_SENSOR sensor::Sensor *ac_voltage_{nullptr}; sensor::Sensor *dc_voltage_{nullptr};