Files
esphome-lsm6ds/tests/integration/fixtures/external_components/uart_mock/automation.h
T
2026-03-01 22:51:27 -10:00

52 lines
1.7 KiB
C++

#pragma once
#include "esphome/core/component.h"
#include "esphome/core/automation.h"
#include "uart_mock.h"
namespace esphome::uart_mock {
// This pattern is similar to UARTWriteAction but calls inject_rx instead of write_array, and is parented to VirtualUART
// instead of UARTComponent
template<typename... Ts> class MockUartInjectRXAction : public Action<Ts...>, public Parented<MockUartComponent> {
public:
void set_data_template(std::vector<uint8_t> (*func)(Ts...)) {
// Stateless lambdas (generated by ESPHome) implicitly convert to function pointers
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) {
this->code_.data = data;
this->len_ = len; // Length >= 0 indicates static mode
}
void play(const Ts &...x) override {
if (this->len_ >= 0) {
// Static mode: use pointer and length
this->parent_->inject_to_rx_buffer(this->code_.data, static_cast<size_t>(this->len_));
} else {
// Template mode: call function
auto val = this->code_.func(x...);
this->parent_->inject_to_rx_buffer(val);
}
}
protected:
ssize_t len_{-1}; // -1 = template mode, >=0 = static mode with length
union Code {
std::vector<uint8_t> (*func)(Ts...); // Function pointer (stateless lambdas)
const uint8_t *data; // Pointer to static data in flash
} code_;
};
class MockUartTXTrigger : public Trigger<std::vector<uint8_t>> {
public:
explicit MockUartTXTrigger(MockUartComponent *parent) {
parent->set_tx_hook([this](std::vector<uint8_t> data) { this->trigger(data); });
}
};
} // namespace esphome::uart_mock