Compare commits

..
11 changed files with 355 additions and 249 deletions

No files matched your search

+3
View File
@@ -25,6 +25,8 @@ CORE_BENCHMARKS_DIR: Path = Path(root_path) / "tests" / "benchmarks" / "core"
# allow benchmarks to compile on the host platform.
STUBS_DIR: Path = Path(root_path) / "tests" / "benchmarks" / "stubs"
HELPERS_DIR: Path = Path(root_path) / "tests" / "benchmarks" / "helpers"
BUILD_FLAGS = [
"-Os", # match firmware optimization level (detects inlining regressions)
"-g", # debug symbols for profiling
@@ -32,6 +34,7 @@ BUILD_FLAGS = [
"-fdata-sections", # required for dead-code stripping with -Os
"-DUSE_BENCHMARK", # disable WarnIfComponentBlockingGuard in finish()
f"-I{STUBS_DIR}", # stub headers for ESP32-only components
f"-I{HELPERS_DIR}", # shared test doubles such as fake_uart.h
]
@@ -0,0 +1,76 @@
#include <benchmark/benchmark.h>
#include "esphome/components/binary_sensor/binary_sensor.h"
#include "esphome/components/ld2450/ld2450.h"
#include "esphome/components/sensor/sensor.h"
#include "fake_uart.h"
namespace esphome::ld2450::benchmarks {
using esphome::benchmarks::FakeUART;
// Inner iteration count to amortize CodSpeed instrumentation overhead.
static constexpr int kInnerIterations = 2000;
static constexpr size_t FRAME_SIZE = 30;
// Periodic frames with one moving target at two positions
static constexpr uint8_t FRAME_A[FRAME_SIZE] = {0xAA, 0xFF, 0x03, 0x00, 0x0E, 0x03, 0xB1, 0x86, 0x10, 0x00,
0x40, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x55, 0xCC};
static constexpr uint8_t FRAME_B[FRAME_SIZE] = {0xAA, 0xFF, 0x03, 0x00, 0x2A, 0x03, 0xC8, 0x86, 0x10, 0x00,
0x40, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x55, 0xCC};
// --- loop() parsing one periodic frame, no entities attached ---
static void LD2450_PeriodicFrame(benchmark::State &state) {
FakeUART uart;
LD2450Component radar;
radar.set_uart_parent(&uart);
radar.set_link_timeout(60000);
// Bring the link up outside the timed loop
uart.load(FRAME_B, FRAME_SIZE);
radar.loop();
for (auto _ : state) {
for (int i = 0; i < kInnerIterations; i++) {
uart.load(FRAME_A, FRAME_SIZE);
radar.loop();
}
benchmark::DoNotOptimize(uart.available());
}
state.SetItemsProcessed(state.iterations() * kInnerIterations);
}
BENCHMARK(LD2450_PeriodicFrame);
// --- loop() parsing a moving target and publishing its sensors ---
static void LD2450_PeriodicFrameSensors(benchmark::State &state) {
FakeUART uart;
LD2450Component radar;
radar.set_uart_parent(&uart);
radar.set_link_timeout(60000);
sensor::Sensor x, y, speed, distance, angle, count;
binary_sensor::BinarySensor presence;
radar.set_move_x_sensor(0, &x);
radar.set_move_y_sensor(0, &y);
radar.set_move_speed_sensor(0, &speed);
radar.set_move_distance_sensor(0, &distance);
radar.set_move_angle_sensor(0, &angle);
radar.set_target_count_sensor(&count);
radar.set_target_binary_sensor(&presence);
uart.load(FRAME_B, FRAME_SIZE);
radar.loop();
for (auto _ : state) {
for (int i = 0; i < kInnerIterations; i++) {
uart.load((i & 1) ? FRAME_B : FRAME_A, FRAME_SIZE);
radar.loop();
}
benchmark::DoNotOptimize(x.state);
}
state.SetItemsProcessed(state.iterations() * kInnerIterations);
}
BENCHMARK(LD2450_PeriodicFrameSensors);
} // namespace esphome::ld2450::benchmarks
@@ -0,0 +1,2 @@
sensor:
binary_sensor:
@@ -12,8 +12,6 @@ def override_manifest(manifest: ComponentManifestOverride) -> None:
async def to_code(config):
await original_to_code(config)
cg.add_define("USE_LIGHT_GAMMA_LUT")
# Lets the flash benchmark set a flash transition length.
cg.add_define("USE_LIGHT_FLASH_TRANSITION_LENGTH")
# Use the light component's own gamma_table_initializer() so the
# benchmark stays in sync with any formula changes.
# Extern-visible (non-static) so the benchmark .cpp can reference it.
@@ -1,26 +0,0 @@
#pragma once
#include "esphome/components/light/light_state.h"
// Gamma 2.8 forward LUT generated by the light component's Python codegen
// (see tests/benchmarks/components/light/__init__.py which calls gamma_table_initializer())
extern const esphome::light::GammaTable bench_gamma_2_8;
namespace esphome::benchmarks {
// Inner iteration count to amortize CodSpeed instrumentation overhead.
static constexpr int kInnerIterations = 2000;
// Exposes configure_entity_(); configure() also sets instant transitions and the gamma 2.8 LUT.
// setup() is not called (no preferences backend), so saving is a no-op.
class TestLightState : public light::LightState {
public:
using LightState::LightState;
void configure(const char *name) {
this->configure_entity_(name, 0x12345678, 0);
this->set_default_transition_length(0);
this->set_gamma_table(&bench_gamma_2_8);
}
};
} // namespace esphome::benchmarks
@@ -3,10 +3,15 @@
#include "esphome/components/light/light_output.h"
#include "esphome/components/light/light_state.h"
#include "bench_helpers.h"
// Gamma 2.8 forward LUT generated by the light component's Python codegen
// (see tests/benchmarks/components/light/__init__.py which calls gamma_table_initializer())
extern const esphome::light::GammaTable bench_gamma_2_8;
namespace esphome::benchmarks {
// Inner iteration count to amortize CodSpeed instrumentation overhead.
static constexpr int kInnerIterations = 2000;
// Minimal LightOutput for benchmarking — no real hardware interaction.
class BenchLightOutput : public light::LightOutput {
public:
@@ -16,12 +21,23 @@ class BenchLightOutput : public light::LightOutput {
light::LightTraits traits_;
};
// Test subclass to access protected configure_entity_() for benchmark setup.
class TestLightState : public light::LightState {
public:
using LightState::LightState;
void configure(const char *name) { this->configure_entity_(name, 0x12345678, 0); }
};
// Helper to create a configured RGBWW light state for benchmarks.
// Note: setup() is not called (no preferences backend), so save_remote_values_()
// is effectively a no-op. This benchmarks the call/validation path, not persistence.
static void setup_rgbww_light(BenchLightOutput &output, TestLightState &light) {
output.traits_.set_supported_color_modes({light::ColorMode::RGB_COLD_WARM_WHITE});
output.traits_.set_min_mireds(153.0f);
output.traits_.set_max_mireds(500.0f);
light.configure("test_light");
light.set_default_transition_length(0);
light.set_gamma_table(&bench_gamma_2_8);
}
// --- LightCall::perform() with instant RGB color change (Home Assistant API path) ---
@@ -1,220 +0,0 @@
#include <benchmark/benchmark.h>
#include <cstdint>
#include "esphome/components/light/addressable_light.h"
#include "esphome/components/light/addressable_light_effect.h"
#include "esphome/components/light/base_light_effects.h"
#include "esphome/components/light/light_output.h"
#include "esphome/components/light/light_state.h"
#include "esphome/core/helpers.h"
#include "bench_helpers.h"
namespace esphome::benchmarks {
static constexpr int kStripIterations = 200;
static constexpr int32_t kStripLeds = 150;
// One hour, so a run never reaches the end of a transition or flash
static constexpr uint32_t kLongMs = 3600000;
// Writes the gamma corrected channels like a PWM driver would
class LoopLightOutput : public light::LightOutput {
public:
explicit LoopLightOutput(light::ColorMode mode) { this->traits_.set_supported_color_modes({mode}); }
light::LightTraits get_traits() override { return this->traits_; }
void write_state(light::LightState *state) override {
if (this->traits_.supports_color_mode(light::ColorMode::BRIGHTNESS)) {
state->current_values_as_brightness(&this->out_[0]);
} else {
state->current_values_as_rgbww(&this->out_[0], &this->out_[1], &this->out_[2], &this->out_[3], &this->out_[4]);
}
benchmark::DoNotOptimize(this->out_);
}
protected:
light::LightTraits traits_;
float out_[5]{};
};
// In-memory RGB strip with no hardware behind it
class FakeStrip : public light::AddressableLight {
public:
static constexpr light::ChannelColors RGB{0, 1, 2};
FakeStrip() : accessor_impl_(this->colors_, this->effect_data_, RGB, &this->correction_) {
this->accessor_ = &this->accessor_impl_;
}
int32_t size() const override { return kStripLeds; }
void clear_effect_data() override { this->accessor_impl_.clear_effect_data(kStripLeds); }
light::LightTraits get_traits() override { return RGB.traits(); }
void write_state(light::LightState * /*state*/) override { benchmark::DoNotOptimize(this->colors_); }
protected:
uint8_t colors_[kStripLeds * 3]{};
uint8_t effect_data_[kStripLeds]{};
light::CorrectedBufferColorAccessor accessor_impl_;
};
static void setup_light(TestLightState &light) {
light.configure("bench_light");
light.get_output()->setup_state(&light);
}
// Registers the effect and seeds the random generator, so seeding is not timed.
// add_effects keeps the pointer, so the table must live as long as the light.
static void add_effect(TestLightState &light, light::LightEffect **effects) {
light.add_effects(effects, 1);
effects[0]->init_internal(&light);
random_uint32();
}
static void run_loop(benchmark::State &state, TestLightState &light, int iterations) {
for (auto _ : state) {
for (int i = 0; i < iterations; i++) {
light.loop();
}
benchmark::DoNotOptimize(light.current_values);
}
state.SetItemsProcessed(state.iterations() * iterations);
}
// --- loop() with an RGBWW transition in progress: lerp, gamma and output write ---
static void LightTransition_RGBWW(benchmark::State &state) {
LoopLightOutput output(light::ColorMode::RGB_COLD_WARM_WHITE);
TestLightState light(&output);
setup_light(light);
light.make_call()
.set_state(true)
.set_brightness(0.2f)
.set_red(1.0f)
.set_green(0.1f)
.set_blue(0.1f)
.set_cold_white(1.0f)
.set_warm_white(0.1f)
.perform();
light.make_call()
.set_brightness(1.0f)
.set_red(0.1f)
.set_green(0.5f)
.set_blue(1.0f)
.set_cold_white(0.1f)
.set_warm_white(1.0f)
.set_transition_length(kLongMs)
.perform();
run_loop(state, light, kInnerIterations);
}
BENCHMARK(LightTransition_RGBWW);
// --- loop() with a brightness-only transition in progress ---
static void LightTransition_Monochromatic(benchmark::State &state) {
LoopLightOutput output(light::ColorMode::BRIGHTNESS);
TestLightState light(&output);
setup_light(light);
light.make_call().set_state(true).set_brightness(0.1f).perform();
light.make_call().set_brightness(1.0f).set_transition_length(kLongMs).perform();
run_loop(state, light, kInnerIterations);
}
BENCHMARK(LightTransition_Monochromatic);
// --- loop() with an RGBWW flash, inside its fade-in transition ---
static void LightFlash_RGBWW(benchmark::State &state) {
LoopLightOutput output(light::ColorMode::RGB_COLD_WARM_WHITE);
TestLightState light(&output);
setup_light(light);
light.set_flash_transition_length(kLongMs);
light.make_call().set_state(true).set_brightness(0.2f).set_red(1.0f).set_green(0.1f).set_blue(0.1f).perform();
light.make_call()
.set_brightness(1.0f)
.set_red(0.1f)
.set_green(0.5f)
.set_blue(1.0f)
.set_flash_length(kLongMs * 2)
.perform();
run_loop(state, light, kInnerIterations);
}
BENCHMARK(LightFlash_RGBWW);
// --- loop() with the flicker effect: one instant LightCall per loop ---
static void LightEffect_Flicker_RGBWW(benchmark::State &state) {
LoopLightOutput output(light::ColorMode::RGB_COLD_WARM_WHITE);
TestLightState light(&output);
setup_light(light);
light::FlickerLightEffect flicker("Flicker");
flicker.set_alpha(0.95f);
flicker.set_intensity(0.0f); // no random noise, so the clamps take the same branch every run
light::LightEffect *effects[] = {&flicker};
add_effect(light, effects);
light.make_call().set_state(true).set_brightness(0.8f).set_red(1.0f).set_green(0.6f).set_blue(0.2f).perform();
light.make_call().set_effect(1u).perform();
run_loop(state, light, kInnerIterations);
}
BENCHMARK(LightEffect_Flicker_RGBWW);
// --- loop() running an addressable effect on a 150 LED strip ---
static void run_strip_effect(benchmark::State &state, light::AddressableLightEffect &effect) {
FakeStrip strip;
TestLightState light(&strip);
light::LightEffect *effects[] = {&effect};
setup_light(light);
add_effect(light, effects);
light.make_call().set_state(true).set_brightness(1.0f).set_red(1.0f).set_green(0.5f).set_blue(0.0f).perform();
light.make_call().set_effect(1u).perform();
// Only the twinkles read it: every LED is lit, the fade position is at least 1 and all eight color codes appear
for (int32_t i = 0; i < kStripLeds; i++)
strip[i].set_effect_data(i | 0b1000);
run_loop(state, light, kStripIterations);
}
static void AddressableEffect_Rainbow_150(benchmark::State &state) {
light::AddressableRainbowLightEffect effect("Rainbow");
effect.set_speed(0); // so the hue does not follow millis()
run_strip_effect(state, effect);
}
BENCHMARK(AddressableEffect_Rainbow_150);
static void AddressableEffect_ColorWipe_150(benchmark::State &state) {
static constexpr light::AddressableColorWipeEffectColor COLORS[] = {
{255, 0, 0, 0, light::NO_RANDOM_SLOT, true, 10},
{0, 0, 0, 0, 0, false, 10}, // random slot 0: a new random color each time this entry starts
};
Color random_colors[1];
light::AddressableColorWipeEffect effect("Color Wipe");
effect.set_colors(COLORS, 2, random_colors);
effect.set_add_led_interval(0); // shift every loop
run_strip_effect(state, effect);
}
BENCHMARK(AddressableEffect_ColorWipe_150);
static void AddressableEffect_Scan_150(benchmark::State &state) {
light::AddressableScanEffect effect("Scan");
effect.set_move_interval(0); // move every loop
effect.set_scan_width(3);
run_strip_effect(state, effect);
}
BENCHMARK(AddressableEffect_Scan_150);
// Twinkles: no new sparkles and no progress, every LED lit, so each loop fades all 150 the same way
static void AddressableEffect_Twinkle_150(benchmark::State &state) {
light::AddressableTwinkleEffect effect("Twinkle");
effect.set_twinkle_probability(0.0f);
effect.set_progress_interval(UINT32_MAX);
run_strip_effect(state, effect);
}
BENCHMARK(AddressableEffect_Twinkle_150);
static void AddressableEffect_RandomTwinkle_150(benchmark::State &state) {
light::AddressableRandomTwinkleEffect effect("Random Twinkle");
effect.set_twinkle_probability(0.0f);
effect.set_progress_interval(UINT32_MAX);
run_strip_effect(state, effect);
}
BENCHMARK(AddressableEffect_RandomTwinkle_150);
} // namespace esphome::benchmarks
@@ -0,0 +1,63 @@
#include <benchmark/benchmark.h>
#include "esphome/components/modbus/modbus.h"
#include "fake_uart.h"
namespace esphome::modbus::benchmarks {
using esphome::benchmarks::FakeUART;
// Inner iteration count to amortize CodSpeed instrumentation overhead.
static constexpr int kInnerIterations = 2000;
static constexpr uint8_t ADDRESS = 1;
static constexpr uint16_t REGISTER_COUNT = 10;
// Read 10 holding registers from address 0, as an energy meter poll does
static constexpr uint8_t REQUEST_PDU[] = {0x03, 0x00, 0x00, 0x00, REGISTER_COUNT};
// Function 3, byte count 20, 10 registers
static constexpr uint8_t RESPONSE_PDU[] = {0x03, 0x14, 0x09, 0x1F, 0x00, 0x00, 0x01, 0xF4, 0x00, 0x00, 0x13,
0x88, 0x00, 0x32, 0x03, 0xE8, 0x00, 0x00, 0x00, 0x64, 0x12, 0x34};
class SumDevice : public ModbusClientDevice {
public:
using ModbusClientDevice::ModbusClientDevice;
void on_read_holding_registers(uint16_t start_address, std::span<const uint16_t> registers,
ResponseStatus status) override {
for (uint16_t value : registers)
this->sum += value;
}
uint32_t sum{0};
};
class NoDelayHub : public ModbusClientHub {
protected:
// No wait before a send, so every loop() can send the next poll
int32_t tx_delay_remaining() override { return 0; }
};
// --- One continuous poll cycle per loop(): receive, decode and resend ---
static void Modbus_ReadHoldingPollCycle(benchmark::State &state) {
const ModbusFrame response(ADDRESS, RESPONSE_PDU, sizeof(RESPONSE_PDU));
FakeUART uart;
uart.set_baud_rate(9600);
NoDelayHub hub;
hub.set_uart_parent(&uart);
hub.setup();
SumDevice device(&hub, ADDRESS);
hub.queue_pdu(ADDRESS, REQUEST_PDU, &device, {.continuous = true});
// The first loop() sends the poll; every send rewinds the response, so the device answers each one
hub.loop();
uart.load(response.data.data(), response.size());
for (auto _ : state) {
for (int i = 0; i < kInnerIterations; i++) {
hub.loop();
}
benchmark::DoNotOptimize(device.sum);
}
state.SetItemsProcessed(state.iterations() * kInnerIterations);
}
BENCHMARK(Modbus_ReadHoldingPollCycle);
} // namespace esphome::modbus::benchmarks
@@ -0,0 +1,56 @@
#include <benchmark/benchmark.h>
#include "esphome/components/uart/uart.h"
#include "fake_uart.h"
namespace esphome::uart::benchmarks {
using esphome::benchmarks::FakeUART;
// Inner iteration count to amortize CodSpeed instrumentation overhead.
static constexpr int kInnerIterations = 2000;
// One second of a GPS module's NMEA output
static constexpr char NMEA_BURST[] = "$GPGGA,123519,4807.038,N,01131.000,E,1,08,0.9,545.4,M,46.9,M,,*47\r\n"
"$GPRMC,123519,A,4807.038,N,01131.000,E,022.4,084.4,230394,003.1,W*6A\r\n"
"$GPGSA,A,3,04,05,,09,12,,,24,,,,,2.5,1.3,2.1*39\r\n"
"$GPGSV,2,1,08,01,40,083,46,02,17,308,41,12,07,344,39,14,22,228,45*75\r\n"
"$GPVTG,054.7,T,034.4,M,005.5,N,010.2,K*48\r\n";
// --- read_available(): drain a whole NMEA burst through a byte-sum callback ---
static void UART_ReadAvailable_NmeaBurst(benchmark::State &state) {
FakeUART uart;
UARTDevice dev(&uart);
uint32_t sum = 0;
for (auto _ : state) {
for (int i = 0; i < kInnerIterations; i++) {
uart.load(reinterpret_cast<const uint8_t *>(NMEA_BURST), sizeof(NMEA_BURST) - 1);
dev.read_available([&](uint8_t b) { sum += b; });
}
benchmark::DoNotOptimize(sum);
}
state.SetItemsProcessed(state.iterations() * kInnerIterations);
}
BENCHMARK(UART_ReadAvailable_NmeaBurst);
// --- discard_available(): drop a 256 byte backlog, two virtual calls per byte ---
static void UART_DiscardAvailable(benchmark::State &state) {
uint8_t backlog[256]{};
FakeUART uart;
UARTDevice dev(&uart);
for (auto _ : state) {
for (int i = 0; i < kInnerIterations; i++) {
uart.load(backlog, sizeof(backlog));
dev.discard_available();
}
benchmark::DoNotOptimize(uart.available());
}
state.SetItemsProcessed(state.iterations() * kInnerIterations);
}
BENCHMARK(UART_DiscardAvailable);
} // namespace esphome::uart::benchmarks
@@ -0,0 +1,96 @@
#include <benchmark/benchmark.h>
#include "esphome/core/frame_reader.h"
#include "esphome/core/helpers.h"
#include "esphome/core/line_reader.h"
namespace esphome::benchmarks {
// Inner iteration count to amortize CodSpeed instrumentation overhead.
static constexpr int kInnerIterations = 2000;
static constexpr char NMEA_GGA[] = "$GPGGA,123519,4807.038,N,01131.000,E,1,08,0.9,545.4,M,46.9,M,,*47\r\n";
// A 30 byte frame with a 4 byte header and a 2 byte tail
static constexpr uint8_t FRAME_30[30] = {0xAA, 0xFF, 0x03, 0x00, 0x0E, 0x03, 0xB1, 0x86, 0x10, 0x00,
0x40, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x55, 0xCC};
// Four A02YYUW frames among noise; the doubled 0xFF fails the checksum and resyncs onto the next frame
static constexpr uint8_t ULTRASONIC_NOISY[] = {0x12, 0xFF, 0x07, 0xA1, 0xA7, 0x34, 0xFF, 0xFF, 0x07, 0xA1, 0xA7,
0x00, 0xFF, 0x07, 0xA1, 0xA7, 0x56, 0xFF, 0x07, 0xA1, 0xA7};
// --- LineReader: one GGA sentence fed byte by byte ---
static void LineReader_NmeaLine(benchmark::State &state) {
LineReader<96> reader;
const auto *bytes = reinterpret_cast<const uint8_t *>(NMEA_GGA);
uint32_t lines = 0;
for (auto _ : state) {
benchmark::DoNotOptimize(bytes);
for (int i = 0; i < kInnerIterations; i++) {
for (size_t j = 0; j < sizeof(NMEA_GGA) - 1; j++) {
char *line = reader.feed(bytes[j]);
if (line == nullptr)
continue;
// Keeps the line copy and its NUL write
benchmark::DoNotOptimize(line);
lines++;
}
}
benchmark::DoNotOptimize(lines);
}
state.SetItemsProcessed(state.iterations() * kInnerIterations);
}
BENCHMARK(LineReader_NmeaLine);
// --- FrameReader: a 30 byte frame behind a 4 byte header ---
static void FrameReader_30ByteFrame(benchmark::State &state) {
FrameReader<sizeof(FRAME_30), 0xAA, 0xFF, 0x03, 0x00> reader;
const uint8_t *bytes = FRAME_30;
uint32_t frames = 0;
for (auto _ : state) {
benchmark::DoNotOptimize(bytes);
for (int i = 0; i < kInnerIterations; i++) {
for (size_t j = 0; j < sizeof(FRAME_30); j++) {
if (reader.feed(bytes[j]) != nullptr)
frames++;
}
}
benchmark::DoNotOptimize(frames);
}
state.SetItemsProcessed(state.iterations() * kInnerIterations);
}
BENCHMARK(FrameReader_30ByteFrame);
// --- FrameReader: 4 byte checksummed frames, skipping noise and resyncing on a bad checksum ---
static void FrameReader_UltrasonicNoisy(benchmark::State &state) {
FrameReader<4, 0xFF> reader;
const uint8_t *bytes = ULTRASONIC_NOISY;
uint32_t frames = 0;
for (auto _ : state) {
benchmark::DoNotOptimize(bytes);
for (int i = 0; i < kInnerIterations; i++) {
for (size_t j = 0; j < sizeof(ULTRASONIC_NOISY); j++) {
const uint8_t *frame = reader.feed(bytes[j]);
if (frame == nullptr)
continue;
if (frame[3] == sum_bytes(frame, 3)) {
frames++;
} else {
reader.resync();
}
}
}
benchmark::DoNotOptimize(frames);
}
state.SetItemsProcessed(state.iterations() * kInnerIterations);
}
BENCHMARK(FrameReader_UltrasonicNoisy);
} // namespace esphome::benchmarks
+42
View File
@@ -0,0 +1,42 @@
#pragma once
#include <cstdint>
#include <cstring>
#include "esphome/components/uart/uart_component.h"
namespace esphome::benchmarks {
// Serves a fixed byte stream as received data. Every write rewinds it, so the stream answers each request.
class FakeUART : public uart::UARTComponent {
public:
void load(const uint8_t *data, size_t len) {
this->data_ = data;
this->len_ = len;
this->pos_ = 0;
}
void write_array(const uint8_t *data, size_t len) override { this->pos_ = 0; }
bool peek_byte(uint8_t *data) override {
if (this->pos_ >= this->len_)
return false;
*data = this->data_[this->pos_];
return true;
}
bool read_array(uint8_t *data, size_t len) override {
if (len > this->len_ - this->pos_)
return false;
std::memcpy(data, this->data_ + this->pos_, len);
this->pos_ += len;
return true;
}
size_t available() override { return this->len_ - this->pos_; }
uart::UARTFlushResult flush() override { return uart::UARTFlushResult::UART_FLUSH_RESULT_ASSUMED_SUCCESS; }
void check_logger_conflict() override {}
protected:
const uint8_t *data_{nullptr};
size_t len_{0};
size_t pos_{0};
};
} // namespace esphome::benchmarks