mirror of
https://github.com/esphome/esphome.git
synced 2026-01-08 19:20:51 -07:00
[sun_gtil2] Eliminate heap allocations in text sensor publishing (#13047)
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
This commit is contained in:
@@ -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<char, STATE_BUFFER_SIZE> 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
|
||||
}
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
#pragma once
|
||||
|
||||
#include <span>
|
||||
|
||||
#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<char, STATE_BUFFER_SIZE> buffer);
|
||||
#ifdef USE_SENSOR
|
||||
sensor::Sensor *ac_voltage_{nullptr};
|
||||
sensor::Sensor *dc_voltage_{nullptr};
|
||||
|
||||
Reference in New Issue
Block a user