6#if defined(USE_REMOTE_RECEIVER_TIMER_SAMPLING) && !defined(CLANG_TIDY)
9#include <ArduinoPrivate.h>
12#include "fake_clock_pub.h"
17#if !defined(LT_MICROS_HIGH_RES) || !LT_MICROS_HIGH_RES
18#error "remote_receiver timer sampling needs LT_MICROS_HIGH_RES"
27static constexpr uint8_t SAMPLE_TIMER = BKTIMER1;
32static_assert(TIMER_TICKS_PER_US == CFG_XTAL_FREQUENCE / 1000000,
"TIMER_TICKS_PER_US must match the crystal");
33static constexpr uint32_t TICK_COUNTER_WRAP = FCLK_DURATION_MS * 1000 * TIMER_TICKS_PER_US;
37static constexpr uint32_t TICK_READ_SPINS = 100;
40 REG_WRITE(TIMER0_2_READ_CTL, (BKTIMER0 << TIMER0_2_READ_INDEX_POSI) | TIMER0_2_READ_OP_BIT);
41 for (
uint32_t spins = 0; spins < TICK_READ_SPINS && (REG_READ(TIMER0_2_READ_CTL) & TIMER0_2_READ_OP_BIT); spins++) {
43 if (REG_READ(TIMER0_2_READ_CTL) & TIMER0_2_READ_OP_BIT)
45 *
value = REG_READ(TIMER0_2_READ_VALUE);
50static RemoteReceiverComponent *s_receiver =
nullptr;
65 if (!read_tick_counter(&counter)) {
71 return this->
sample(level, 0);
73 if (!read_tick_counter(&counter)) {
81 elapsed += TICK_COUNTER_WRAP;
82 this->last_counter = counter;
83 return this->
sample(level, elapsed);
94 timer_param_t param{};
95 param.channel = SAMPLE_TIMER;
97 param.period = s.sample_period_us;
100 if (sddev_control((
char *) TIMER_DEV_NAME, CMD_TIMER_INIT_PARAM_US, ¶m) != 0) {
110 const int32_t *frame;
114 uint16_t tick_errors;
118 count = s.ready_count;
119 overflow = s.overflow;
121 tick_errors = s.tick_read_errors;
124 s.tick_read_errors = 0;
127 ESP_LOGW(TAG,
"Buffer overflow");
130 ESP_LOGW(TAG,
"Frame dropped, previous frame still being processed");
132 if (tick_errors != 0) {
133 if (tick_errors == UINT16_MAX) {
134 ESP_LOGW(TAG,
"Counter read timed out at least %u times; timings may be wrong", tick_errors);
136 ESP_LOGW(TAG,
"Counter read timed out %u times; timings may be wrong", tick_errors);
139 if (frame ==
nullptr) {
void mark_failed()
Mark this component as failed.
void enable_loop_soon_any_context()
Thread and ISR-safe version of enable_loop() that can be called from any context.
void disable_loop()
Disable this component's loop.
ISRInternalGPIOPin to_isr() const
void call_listeners_dumpers_()
RemoteReceiverComponentStore store_
static void sample_timer_isr(uint8_t channel)
ESPHOME_LOG_TAG(TAG, "remote_receiver")
const int32_t *volatile ready
Finished frame for the loop, nullptr once the loop has dispatched it.
bool sample(bool level, uint32_t elapsed)
Takes one sample: the logical pin level (true for a mark) and the ticks since the previous sample.
void count_tick_read_error()
Counts a failed counter read; saturating so a flood cannot wrap the count to zero.
bool timer_isr()
Returns true when it published a frame, an overflow, or a counter read error for the loop.