Merge branch 'uart_write_action_store_flash_state_less' into integration

This commit is contained in:
J. Nick Koston
2025-11-08 23:42:55 -06:00
+13 -16
View File
@@ -12,36 +12,33 @@ template<typename... Ts> class UARTWriteAction : public Action<Ts...>, public Pa
public:
void set_data_template(std::vector<uint8_t> (*func)(Ts...)) {
// Stateless lambdas (generated by ESPHome) implicitly convert to function pointers
this->data_.func = func;
this->static_ = false;
this->code_.func = func;
this->len_ = -1; // Sentinel value indicates template mode
}
// Store pointer to static data in flash (no RAM copy)
void set_data_static(const uint8_t *data, size_t len) {
// Simply set pointer and length - no construction needed for POD types
this->data_.static_data.ptr = data;
this->data_.static_data.len = len;
this->static_ = true;
this->code_.data = data;
this->len_ = len; // Length >= 0 indicates static mode
}
void play(const Ts &...x) override {
if (this->static_) {
this->parent_->write_array(this->data_.static_data.ptr, this->data_.static_data.len);
if (this->len_ >= 0) {
// Static mode: use pointer and length
this->parent_->write_array(this->code_.data, static_cast<size_t>(this->len_));
} else {
auto val = this->data_.func(x...);
// Template mode: call function
auto val = this->code_.func(x...);
this->parent_->write_array(val);
}
}
protected:
bool static_{true}; // Default to static mode (most common case)
union Data {
ssize_t len_{-1}; // -1 = template mode, >=0 = static mode with length
union Code {
std::vector<uint8_t> (*func)(Ts...); // Function pointer (stateless lambdas)
struct {
const uint8_t *ptr;
size_t len;
} static_data;
} data_;
const uint8_t *data; // Pointer to static data in flash
} code_;
};
} // namespace uart