ESPHome 2026.12.0-dev
Loading...
Searching...
No Matches
hdmi_cec.cpp
Go to the documentation of this file.
1#include "hdmi_cec.h"
2
3#include "esphome/core/hal.h"
4#include "esphome/core/log.h"
5#ifdef USE_HDMI_CEC_UART
7#endif
8#ifdef USE_ESP8266
9#include <Arduino.h>
10#endif
11#ifdef USE_RP2040
12#include <pico/time.h>
13#endif
14
16
17ESPHOME_LOG_TAG(TAG, "hdmi_cec");
18
19#if defined(USE_ESP8266) || defined(USE_RP2040)
20// The timer interrupt of these platforms carries no argument
21static HDMICEC *ack_timer_owner = nullptr; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
22#endif
23
24// Bit timing from the HDMI 1.4 CEC specification, in microseconds
25static constexpr uint32_t START_BIT_MIN_US = 3500; // a low period at least this long is a start bit
26static constexpr uint32_t START_BIT_NOM_US = 3700;
27static constexpr uint32_t START_BIT_HIGH_US = 800;
28static constexpr uint32_t HIGH_BIT_MIN_US = 400; // shortest low period of a logical 1
29static constexpr uint32_t HIGH_BIT_US = 600; // nominal low period of a logical 1
30static constexpr uint32_t LOW_BIT_US = 1500; // nominal low period of a logical 0
31static constexpr uint32_t SAFE_SAMPLE_US = 1050; // the line is sampled here; a longer low period is a logical 0
32static constexpr uint32_t TOTAL_BIT_US = 2400;
33static constexpr uint32_t SIGNAL_FREE_TIME_AFTER_RECEIVE = TOTAL_BIT_US * 5; // also for a new initiator
34static constexpr uint32_t SIGNAL_FREE_TIME_AFTER_XMIT_FAIL = TOTAL_BIT_US * 3;
35static constexpr uint32_t SIGNAL_FREE_TIME_AFTER_XMIT_SUCCESS = TOTAL_BIT_US * 7;
36static constexpr uint32_t ABORTED_FRAME_US = TOTAL_BIT_US * 15; // no edge for this long: our frame was cut short
37static constexpr uint8_t MAX_ATTEMPTS = 8; // CEC allows 5, but a busy bus counts as an attempt here too
38
39// Opcodes of the built-in replies
40static constexpr uint8_t OPCODE_FEATURE_ABORT = 0x00;
41static constexpr uint8_t OPCODE_ABORT = 0xFF;
42static constexpr uint8_t ABORT_REASON_UNRECOGNIZED_OPCODE = 0x00;
43static constexpr uint8_t ABORT_REASON_REFUSED = 0x04;
44static constexpr uint8_t OPCODE_GIVE_OSD_NAME = 0x46;
45static constexpr uint8_t OPCODE_GIVE_PHYSICAL_ADDRESS = 0x83;
46static constexpr uint8_t OPCODE_REPORT_PHYSICAL_ADDRESS = 0x84;
47static constexpr uint8_t OPCODE_GET_CEC_VERSION = 0x9F;
48static constexpr uint8_t OPCODE_CEC_VERSION = 0x9E;
49static constexpr uint8_t CEC_VERSION_1_4 = 0x05;
50
51#ifdef USE_HDMI_CEC_FEATURE_ABORT
52// Directed answers to requests, never aborted
53static constexpr uint8_t OPCODE_TUNER_DEVICE_STATUS = 0x07;
54static constexpr uint8_t OPCODE_DECK_STATUS = 0x1B;
55static constexpr uint8_t OPCODE_SET_OSD_NAME = 0x47;
56static constexpr uint8_t OPCODE_REPORT_AUDIO_STATUS = 0x7A;
57static constexpr uint8_t OPCODE_SYSTEM_AUDIO_MODE_STATUS = 0x7E;
58static constexpr uint8_t OPCODE_MENU_STATUS = 0x8E;
59static constexpr uint8_t OPCODE_REPORT_POWER_STATUS = 0x90;
60static constexpr uint8_t OPCODE_REPORT_SHORT_AUDIO_DESCRIPTOR = 0xA3;
61static constexpr uint8_t OPCODE_REPORT_ARC_INITIATED = 0xC1;
62static constexpr uint8_t OPCODE_REPORT_ARC_TERMINATED = 0xC2;
63
66static bool is_response(uint8_t opcode) {
67 switch (opcode) {
68 case OPCODE_TUNER_DEVICE_STATUS:
69 case OPCODE_DECK_STATUS:
70 case OPCODE_SET_OSD_NAME:
71 case OPCODE_REPORT_AUDIO_STATUS:
72 case OPCODE_SYSTEM_AUDIO_MODE_STATUS:
73 case OPCODE_MENU_STATUS:
74 case OPCODE_REPORT_POWER_STATUS:
75 case OPCODE_CEC_VERSION:
76 case OPCODE_REPORT_SHORT_AUDIO_DESCRIPTOR:
77 case OPCODE_REPORT_ARC_INITIATED:
78 case OPCODE_REPORT_ARC_TERMINATED:
79 return true;
80 default:
81 return false;
82 }
83}
84#endif
85
87static bool is_claimed(uint8_t opcode) {
88#ifdef HDMI_CEC_CLAIMED_OPCODE_COUNT
89 for (uint8_t i = 0; i < HDMI_CEC_CLAIMED_OPCODE_COUNT; i++) {
90 if (progmem_read_byte(&CLAIMED_OPCODES[i]) == opcode) {
91 return true;
92 }
93 }
94#endif
95 return false;
96}
97
98Frame::Frame(uint8_t initiator_addr, uint8_t destination_addr, std::span<const uint8_t> payload) {
99 this->data_[0] = ((initiator_addr & 0xf) << 4) | (destination_addr & 0xf);
100 // No length clamp: send() refuses a payload over MAX_PAYLOAD_LENGTH, and the built-in replies are shorter
101 this->size_ = 1 + payload.size();
102 // the payload may be a flash table (hdmi_cec.send); progmem_memcpy reads RAM too. A poll has none,
103 // and memcpy from its null data is undefined even for no bytes
104 if (!payload.empty()) {
105 progmem_memcpy(this->data_.data() + 1, payload.data(), payload.size());
106 }
107}
108
110 // The line is open drain with a weak pull-up: driven low to send, released to read
111 this->pin_->setup();
112 this->isr_pin_ = this->pin_->to_isr();
113 this->set_pin_input_high_();
114 this->required_idle_period_ = SIGNAL_FREE_TIME_AFTER_RECEIVE;
115 if (!this->setup_ack_timer_()) {
116 ESP_LOGE(TAG, "Failed to set up the acknowledge timer");
117 this->mark_failed();
118 return;
119 }
121 // loop() only has work once the interrupt queues a frame or send() queues one
122 this->disable_loop();
123}
124
126 ESP_LOGCONFIG(TAG,
127 "HDMI-CEC:\n"
128 " Address: 0x%X\n"
129 " Monitor mode: %s\n"
130 " Promiscuous mode: %s",
131 this->address_, YESNO(this->monitor_mode_), YESNO(this->promiscuous_mode_));
132 LOG_PIN(" Pin: ", this->pin_);
134 const uint8_t high = this->physical_address_ >> 8;
135 const uint8_t low = this->physical_address_;
136 ESP_LOGCONFIG(TAG, " Physical address: %X.%X.%X.%X", high_nibble(high), low_nibble(high), high_nibble(low),
137 low_nibble(low));
138 }
139#ifdef HDMI_CEC_OSD_NAME_LENGTH
140 ESP_LOGCONFIG(TAG, " OSD name: %s", LOG_STR_ARG(OSD_NAME_REPLY + 1));
141#endif
142#ifdef USE_HDMI_CEC_UART
143 ESP_LOGCONFIG(TAG, " Transmit: UART");
144#endif
145}
146
148 const uint8_t dropped = atomic_get(this->dropped_frames_);
149 if (dropped != this->reported_dropped_frames_) {
150 const uint8_t count = dropped - this->reported_dropped_frames_;
151 ESP_LOGW(TAG, "%u received frame%s dropped (queue full or oversized)", count,
152 count == 1 ? LOG_STR_LITERAL("") : LOG_STR_LITERAL("s"));
153 this->reported_dropped_frames_ = dropped;
154 }
155
156 // One inbound frame per pass keeps the time spent in the automations bounded
157 if (const Frame *frame = this->frames_queue_.front()) {
158 this->handle_received_message_(frame);
159 this->frames_queue_.pop_front();
160 }
161
162 // A frame being sent stays at the front of the queue until its attempts are over
163 if (!this->send_queue_.is_empty()) {
164 this->transmit_message_();
165 }
166 if (this->frames_queue_.is_empty() && this->send_queue_.is_empty()) {
167 this->disable_loop();
168 }
169}
170
171// Polling frames (header only) never get here: the receive interrupt answers them with the acknowledge
173 ESP_LOGD_HEX(TAG, frame->bytes().data(), frame->size(), Frame::MAX_LENGTH, "Received: %s");
174#ifdef HDMI_CEC_MESSAGE_CALLBACK_COUNT
175 this->message_callbacks_.call(frame->initiator_addr(), frame->destination_addr(), frame->payload());
176#endif
177 // Only a frame directed at us from a registered device gets a built-in reply: a broadcast is
178 // never answered (so an instance on the unregistered address 0xF answers nothing, though it may
179 // still send), and an unregistered initiator cannot be answered directly
180 if (!this->monitor_mode_ && !frame->is_broadcast() && frame->destination_addr() == this->address_ &&
181 frame->initiator_addr() != Frame::BROADCAST_ADDRESS && !is_claimed(frame->opcode())) {
182 this->reply_builtin_(frame);
183 }
184}
185
186void HDMICEC::reply_builtin_(const Frame *frame) {
187 const uint8_t source = frame->initiator_addr();
188 const uint8_t opcode = frame->opcode();
189 switch (opcode) {
190 case OPCODE_FEATURE_ABORT:
191 return; // never answered
192 case OPCODE_GET_CEC_VERSION:
193 this->send(source, {OPCODE_CEC_VERSION, CEC_VERSION_1_4});
194 return;
195 case OPCODE_GIVE_PHYSICAL_ADDRESS:
197 // Reported to everybody, with the device type the logical address stands for
199 {OPCODE_REPORT_PHYSICAL_ADDRESS, static_cast<uint8_t>(this->physical_address_ >> 8),
200 static_cast<uint8_t>(this->physical_address_), this->device_type_});
201 return;
202 }
203 break;
204#ifdef HDMI_CEC_OSD_NAME_LENGTH
205 case OPCODE_GIVE_OSD_NAME:
206 this->send(source, std::span<const uint8_t>(reinterpret_cast<const uint8_t *>(OSD_NAME_REPLY),
207 1 + HDMI_CEC_OSD_NAME_LENGTH));
208 return;
209#endif
210 default:
211 break;
212 }
213#ifdef USE_HDMI_CEC_FEATURE_ABORT
214 if (is_response(opcode)) {
215 return;
216 }
217 // Nothing here or in an automation answers it: tell the initiator, as the bus expects. <Abort> is a
218 // test message that CEC requires to be refused
219 this->send(source, {OPCODE_FEATURE_ABORT, opcode,
220 opcode == OPCODE_ABORT ? ABORT_REASON_REFUSED : ABORT_REASON_UNRECOGNIZED_OPCODE});
221#endif
222}
223
224bool HDMICEC::send(uint8_t source, uint8_t destination, std::span<const uint8_t> payload) {
225 if (this->monitor_mode_) {
226 ESP_LOGW(TAG, "Monitor mode, not sending 0x%X->0x%X", source, destination);
227 return false;
228 }
229 if (source > 0xf || destination > 0xf) {
230 ESP_LOGE(TAG, "Send abort: logical address 0x%X->0x%X out of range", source, destination);
231 return false;
232 }
233 if (payload.size() > Frame::MAX_PAYLOAD_LENGTH) {
234 ESP_LOGE(TAG, "Send abort 0x%X->0x%X: payload of %zu bytes exceeds %zu", source, destination, payload.size(),
236 return false;
237 }
238 Frame *frame = this->send_queue_.back();
239 if (frame == nullptr) {
240 ESP_LOGW(TAG, "Send queue full, frame 0x%X->0x%X dropped", source, destination);
241 return false;
242 }
243 *frame = Frame(source, destination, payload);
244 this->send_queue_.push_back();
245 // Not enable_loop_soon_any_context(): send() is only called on the main loop (automations, lambdas
246 // and the built-in replies), where this re-enables a sleeping loop at once
247 this->enable_loop();
248 return true;
249}
250
252 // The edge first: an interrupt after micros() would leave it newer than now, and the difference would wrap
253 const uint32_t last_edge = atomic_get(this->last_edge_us_);
254 const uint32_t now = micros();
255 const uint32_t since_last_edge = now - last_edge;
256 if (this->transmitting_) {
257 // The interrupt sees our own frame; wait for its end of message bit, or give up when the
258 // bus went quiet without one
259 if (!atomic_get(this->eom_received_) && since_last_edge < ABORTED_FRAME_US) {
260 return;
261 }
262 this->transmitting_ = false;
263 atomic_set(this->eom_received_, false); // the end of our own frame is not a foreign one
264 const Frame *frame = this->send_queue_.front();
265 // A broadcast is acknowledged by nobody; a directed frame on every byte
266 const bool bytes_ok = this->n_bytes_received_ == frame->size();
267 const bool acks_ok = this->n_acks_received_ == (frame->is_broadcast() ? 0 : frame->size());
268 if (bytes_ok && acks_ok) {
269 ESP_LOGD(TAG, "Send frame success in %u attempt%s", this->transmit_attempts_,
270 this->transmit_attempts_ > 1 ? LOG_STR_LITERAL("s") : LOG_STR_LITERAL(""));
271 } else if (!bytes_ok) {
272 ESP_LOGD(TAG, "Send frame incorrect on attempt %u, saw %u bytes but expected %zu", this->transmit_attempts_,
273 this->n_bytes_received_, frame->size());
274 } else {
275 ESP_LOGD(TAG, "Send frame not acknowledged on attempt %u", this->transmit_attempts_);
276 }
277 this->finish_attempt_(bytes_ok && acks_ok);
278 } else if (atomic_get(this->eom_received_)) {
279 // Another device finished a frame; the standard asks a new initiator to wait after it
280 this->required_idle_period_ = SIGNAL_FREE_TIME_AFTER_RECEIVE;
281 atomic_set(this->eom_received_, false);
282 }
283
284 const Frame *frame = this->send_queue_.front();
285 // An edge within the signal free time means the bus is in use or not yet free for us; a start
286 // bit refused by a held line drives no edge, so that attempt is timed on its own
287 if (frame == nullptr || since_last_edge < this->required_idle_period_ ||
289 return;
290 }
291
292 this->last_attempt_us_ = now;
293 this->transmit_attempts_++;
294#ifdef ESPHOME_LOG_HAS_DEBUG
295 if (this->transmit_attempts_ == 1) {
297 ESP_LOGD(TAG, "Sending: %s", format_hex_pretty_to(line, frame->bytes().data(), frame->size()));
298 }
299#endif
300 // The interrupt counts the bytes and acknowledge bits of our own frame
301 this->n_bytes_received_ = 0;
302 this->n_acks_received_ = 0;
303 atomic_set(this->eom_received_, false);
304 this->transmitting_ = true;
305 if (!this->transmit_frame_(frame)) {
306 // The line was held, or another initiator sent at the same time
307 this->transmitting_ = false;
308 this->finish_attempt_(false);
309 }
310 // Otherwise, a UART transmit can proceed in the background,
311 // and the transmit acknowledge result arrives through the receiver interrupt
312}
313
314void HDMICEC::finish_attempt_(bool sent_ok) {
315 this->required_idle_period_ = sent_ok ? SIGNAL_FREE_TIME_AFTER_XMIT_SUCCESS : SIGNAL_FREE_TIME_AFTER_XMIT_FAIL;
316 if (!sent_ok) {
317 if (this->transmit_attempts_ < MAX_ATTEMPTS) {
318 return; // the signal free time has to pass before the retry
319 }
320 ESP_LOGW(TAG, "Frame not sent after %u attempts, dropped", this->transmit_attempts_);
321 }
322 this->transmit_attempts_ = 0;
323 this->send_queue_.pop_front();
324}
325
326bool HDMICEC::transmit_frame_(const Frame *frame) {
327 if (!this->send_start_bit_()) {
328 return false;
329 }
330 // The four initiator address bits, most significant first, watch for a collision with another
331 // initiator that started at the same moment; a lower address wins by holding the line
332 const uint8_t header = frame->bytes()[0];
333 for (int8_t i = 7; i >= 4; i--) {
334 if (!this->send_bit_((header >> i) & 0x1)) {
335 ESP_LOGD(TAG, "Bus collision on sending initiator address 0x%X on attempt %u", frame->initiator_addr(),
336 this->transmit_attempts_);
337 return false;
338 }
339 }
340 this->transmit_body_(frame);
341 return true;
342}
343
346static uint16_t frame_bits(std::span<const uint8_t> bytes, size_t i) {
347 return (static_cast<uint16_t>(bytes[i]) << 2) | (i == bytes.size() - 1 ? 0x2 : 0) | 0x1;
348}
350static int8_t frame_first_bit(size_t i) { return i == 0 ? 5 : 9; }
351
352// At 2083 baud one UART byte (start bit, 8 data bits, stop bit) spans two CEC bits of five UART
353// bits each. The UART start bit is low and its stop bit high, so a byte always begins the first
354// CEC bit low and ends the second one high; the data bits, sent least significant first, fill in
355// the rest: a logical 0 is low for three UART bits, a logical 1 for one.
356size_t encode_uart_body(const Frame &frame, uint8_t *out) {
357 static constexpr uint8_t TWO_BITS_TO_UART_BYTE[4] PROGMEM = {0x8C, 0xEC, 0x8F, 0xEF}; // 00, 01, 10, 11
358 size_t length = 0;
359 const auto bytes = frame.bytes();
360 for (size_t i = 0; i < bytes.size(); i++) {
361 const uint16_t bits = frame_bits(bytes, i);
362 for (int8_t pair = frame_first_bit(i) / 2; pair >= 0; pair--) {
363 out[length++] = progmem_read_byte(&TWO_BITS_TO_UART_BYTE[(bits >> (2 * pair)) & 0x3]);
364 }
365 }
366 return length;
367}
368
369#ifdef USE_HDMI_CEC_UART
370void HDMICEC::transmit_body_(const Frame *frame) {
371 uint8_t data[MAX_UART_BODY_LENGTH];
372 this->uart_->write_array(data, encode_uart_body(*frame, data));
373}
374#else
375void HDMICEC::transmit_body_(const Frame *frame) {
376 const auto bytes = frame->bytes();
377 for (size_t i = 0; i < bytes.size(); i++) {
378 const uint16_t bits = frame_bits(bytes, i);
379 for (int8_t bit = frame_first_bit(i); bit >= 0; bit--) {
380 this->send_bit_((bits >> bit) & 0x1);
381 }
382 }
383}
384#endif
385
387 if (!this->isr_pin_.digital_read()) {
388 ESP_LOGD(TAG, "Bus occupied before start bit on attempt %u", this->transmit_attempts_);
389 return false;
390 }
391 this->set_pin_output_low_();
392 delay_microseconds_safe(START_BIT_NOM_US);
393 // Release the line and check that nobody else keeps it low
394 this->set_pin_input_high_();
395 delay_microseconds_safe(START_BIT_HIGH_US / 2);
396 bool value = this->isr_pin_.digital_read();
397 delay_microseconds_safe(START_BIT_HIGH_US / 2);
398 value &= this->isr_pin_.digital_read();
399 if (!value) {
400 ESP_LOGD(TAG, "Bus collision on sending start bit on attempt %u", this->transmit_attempts_);
401 }
402 return value;
403}
404
405bool HDMICEC::send_bit_(bool bit_value) {
406 const uint32_t start_us = micros();
407 this->set_pin_output_low_();
408 delay_microseconds_safe(bit_value ? HIGH_BIT_US : LOW_BIT_US);
409 this->set_pin_input_high_();
410 bool clear = true;
411 if (bit_value) {
412 // Sample in the middle of the safe sample period: a line still low means another initiator
413 // is sending a logical 0 at the same time
414 uint32_t elapsed = micros() - start_us;
415 if (elapsed < SAFE_SAMPLE_US) {
416 delay_microseconds_safe(SAFE_SAMPLE_US - elapsed);
417 }
418 clear = this->isr_pin_.digital_read();
419 }
420 const uint32_t elapsed = micros() - start_us;
421 if (elapsed < TOTAL_BIT_US) {
422 delay_microseconds_safe(TOTAL_BIT_US - elapsed);
423 }
424 return clear;
425}
426
427void IRAM_ATTR HDMICEC::send_ack_() {
428 // The acknowledge has to start right at this falling edge; the timer releases the line
429 this->set_pin_output_low_();
430 this->start_ack_timer_();
431}
432
433#if defined(USE_ESP32)
435 gptimer_config_t config = {
436 .clk_src = GPTIMER_CLK_SRC_DEFAULT,
437 .direction = GPTIMER_COUNT_UP,
438 .resolution_hz = 1000000, // one tick per microsecond
439 };
440 if (gptimer_new_timer(&config, &this->ack_timer_) != ESP_OK) {
441 return false;
442 }
443 gptimer_event_callbacks_t callbacks = {.on_alarm = HDMICEC::ack_timer_isr_s};
444 // The alarm reloads the count to zero itself, so the interrupt only has to start the timer
445 gptimer_alarm_config_t alarm = {
446 .alarm_count = LOW_BIT_US, .reload_count = 0, .flags = {.auto_reload_on_alarm = true}};
447 return gptimer_register_event_callbacks(this->ack_timer_, &callbacks, this) == ESP_OK &&
448 gptimer_set_alarm_action(this->ack_timer_, &alarm) == ESP_OK && gptimer_enable(this->ack_timer_) == ESP_OK;
449}
450
451void IRAM_ATTR HDMICEC::start_ack_timer_() { gptimer_start(this->ack_timer_); }
452
453bool IRAM_ATTR HDMICEC::ack_timer_isr_s(gptimer_handle_t timer, const gptimer_alarm_event_data_t *edata, void *arg) {
454 auto *self = static_cast<HDMICEC *>(arg);
455 self->set_pin_input_high_();
456 gptimer_stop(timer);
457 return false; // no task to wake
458}
459
460#elif defined(USE_ESP8266)
461static constexpr uint32_t TIMER1_TICKS_PER_US = 5; // TIM_DIV16 of the 80 MHz clock
462
464 ack_timer_owner = this;
465 timer1_isr_init();
466 timer1_attachInterrupt(HDMICEC::ack_timer_isr_s);
467 timer1_enable(TIM_DIV16, TIM_EDGE, TIM_SINGLE); // a write arms one shot
468 return true;
469}
470
471void IRAM_ATTR HDMICEC::start_ack_timer_() { timer1_write(LOW_BIT_US * TIMER1_TICKS_PER_US); }
472
473void IRAM_ATTR HDMICEC::ack_timer_isr_s() { ack_timer_owner->set_pin_input_high_(); }
474
475#elif defined(USE_RP2040)
477 this->ack_alarm_ = hardware_alarm_claim_unused(false);
478 if (this->ack_alarm_ < 0) {
479 return false; // every hardware alarm is taken
480 }
481 ack_timer_owner = this;
482 hardware_alarm_set_callback(this->ack_alarm_, HDMICEC::ack_timer_isr_s);
483 return true;
484}
485
486void IRAM_ATTR HDMICEC::start_ack_timer_() {
487 hardware_alarm_set_target(this->ack_alarm_, make_timeout_time_us(LOW_BIT_US));
488}
489
490void IRAM_ATTR HDMICEC::ack_timer_isr_s(uint alarm_num) { ack_timer_owner->set_pin_input_high_(); }
491
492#else
493bool HDMICEC::setup_ack_timer_() { return true; }
494
495// Without a one-shot timer the interrupt holds the line itself
496void IRAM_ATTR HDMICEC::start_ack_timer_() {
497 delay_microseconds_safe(LOW_BIT_US);
498 this->set_pin_input_high_();
499}
500#endif
501
502void IRAM_ATTR HDMICEC::gpio_isr_s(HDMICEC *self) { self->gpio_isr_(); }
503
504void IRAM_ATTR HDMICEC::gpio_isr_() {
505 const uint32_t now = micros();
506 const bool level = this->isr_pin_.digital_read();
507 if (level == this->prev_pin_level_) {
508 return; // a mode change of the pin, not a bus edge
509 }
510 this->prev_pin_level_ = level;
511 atomic_set(this->last_edge_us_, now);
512
513 if (!level) {
514 // Falling edge: the start of a low period
515 if (now - this->last_falling_edge_us_ > START_BIT_NOM_US + TOTAL_BIT_US) {
516 // The bus was quiet; whatever was gathered belongs to an aborted frame
517 this->reset_receiver_();
518 }
519 this->last_falling_edge_us_ = now;
520 if (this->recv_ack_queued_) {
521 // Acknowledge by stretching this low period
522 this->send_ack_();
523 this->recv_ack_queued_ = false;
524 }
525 return;
526 }
527
528 // Rising edge: the low period tells the bit value
529 const uint32_t pulse_duration = now - this->last_falling_edge_us_;
530 if (pulse_duration > START_BIT_MIN_US) {
531 this->reset_receiver_();
533 // Without a free slot the frame is neither acknowledged nor delivered, so its initiator retries
534 this->recv_frame_ = this->frames_queue_.back();
535 if (this->recv_frame_ != nullptr) {
536 this->recv_frame_->clear();
537 }
538 return;
539 }
540 if (pulse_duration < HIGH_BIT_MIN_US / 4) {
541 return; // glitch
542 }
543 const bool value = pulse_duration <= SAFE_SAMPLE_US;
544 // Our own frame is on the bus until its end of message; send() may give it any initiator address
545 const bool own_frame = this->transmitting_ && !atomic_get(this->eom_received_);
546
547 switch (this->receiver_state_) {
549 break;
550
552 this->recv_byte_ = (this->recv_byte_ << 1) | value;
553 if (++this->recv_bit_counter_ == 8) {
554 if (this->recv_length_++ == 0) {
555 this->recv_header_ = this->recv_byte_;
556 }
557 if (this->recv_frame_ != nullptr && !this->recv_frame_->push_back(this->recv_byte_)) {
558 this->recv_frame_ = nullptr; // longer than the bus allows: corrupt, do not deliver it
559 }
560 this->recv_bit_counter_ = 0;
562 }
563 break;
564
566 this->recv_eom_ = value;
567 // A frame for us is acknowledged on the next bit, unless there is no room for it (so its
568 // initiator retries) or it is our own, which includes a polling message from a device
569 // claiming our logical address. A polling message for us (header only) needs no room, and
570 // goes unacknowledged only when nobody holds the address
571 if (!this->monitor_mode_ && !own_frame && (this->recv_frame_ != nullptr || (value && this->recv_length_ == 1)) &&
572 (this->recv_header_ & 0xf) == this->address_ && (this->recv_header_ >> 4) != this->address_) {
573 this->recv_ack_queued_ = true;
574 }
576 break;
577
579 if (own_frame) {
580 // A low acknowledge bit means the addressed device took the byte
581 // (for a broadcast it means some device refused it)
582 this->n_bytes_received_++;
583 if (!value) {
584 this->n_acks_received_++;
585 }
586 }
587 if (!this->recv_eom_) {
589 break;
590 }
591 atomic_set(this->eom_received_, true); // publishes the tally above to loop()
592 // The application only gets frames that are not our own and not a polling message (header
593 // only), which the acknowledge answered already, and that are addressed to us unless
594 // promiscuous
595 const uint8_t destination = this->recv_header_ & 0xf;
596 const bool wanted = this->recv_length_ > 1 && !own_frame && (this->recv_header_ >> 4) != this->address_ &&
597 (this->promiscuous_mode_ || destination == 0xf || destination == this->address_);
598 if (!wanted) {
599 // nothing to deliver
600 } else if (this->recv_frame_ == nullptr) {
602 } else {
603 this->frames_queue_.push_back();
605 }
606 this->reset_receiver_();
607 break;
608 }
609}
610
611void IRAM_ATTR HDMICEC::reset_receiver_() {
613 this->recv_bit_counter_ = 0;
614 this->recv_length_ = 0;
615 this->recv_ack_queued_ = false;
616 this->recv_frame_ = nullptr;
617}
618
619} // namespace esphome::hdmi_cec
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 enable_loop()
Enable this component's loop.
Definition component.h:262
void disable_loop()
Disable this component's loop.
void attach_interrupt(void(*func)(T *), T *arg, gpio::InterruptType type) const
Definition gpio.h:32
ISRInternalGPIOPin to_isr() const
Definition gpio.cpp:77
One CEC bus message: a header byte with the initiator and destination addresses, then up to 15 payloa...
Definition hdmi_cec.h:51
ESPHOME_ALWAYS_INLINE bool push_back(uint8_t data)
False when the frame is full already; the bus allows no more.
Definition hdmi_cec.h:72
std::span< const uint8_t > bytes() const
Definition hdmi_cec.h:67
static constexpr size_t MAX_LENGTH
Definition hdmi_cec.h:53
static constexpr size_t MAX_PAYLOAD_LENGTH
Definition hdmi_cec.h:54
std::span< const uint8_t > payload() const
The bytes after the header, starting with the opcode.
Definition hdmi_cec.h:69
ESPHOME_ALWAYS_INLINE uint8_t initiator_addr() const
Definition hdmi_cec.h:61
ESPHOME_ALWAYS_INLINE size_t size() const
Definition hdmi_cec.h:64
ESPHOME_ALWAYS_INLINE bool is_broadcast() const
Definition hdmi_cec.h:63
static constexpr uint8_t BROADCAST_ADDRESS
Definition hdmi_cec.h:55
ESPHOME_ALWAYS_INLINE uint8_t destination_addr() const
Definition hdmi_cec.h:62
std::array< uint8_t, MAX_LENGTH > data_
Definition hdmi_cec.h:81
ESPHOME_ALWAYS_INLINE void clear()
Definition hdmi_cec.h:70
ESPHOME_ALWAYS_INLINE uint8_t opcode() const
Definition hdmi_cec.h:66
ESPHOME_ALWAYS_INLINE void pop_front()
Definition hdmi_cec.h:101
ESPHOME_ALWAYS_INLINE Frame * back()
Definition hdmi_cec.h:102
ESPHOME_ALWAYS_INLINE void push_back()
Definition hdmi_cec.h:103
ESPHOME_ALWAYS_INLINE Frame * front()
Definition hdmi_cec.h:100
ESPHOME_ALWAYS_INLINE bool is_empty() const
Definition hdmi_cec.h:104
The HDMI-CEC bus on one GPIO pin.
Definition hdmi_cec.h:123
std::atomic< uint32_t > last_edge_us_
Definition hdmi_cec.h:240
void dump_config() override
Definition hdmi_cec.cpp:125
FrameRingBuffer< QUEUE_SIZE > send_queue_
Definition hdmi_cec.h:220
void transmit_body_(const Frame *frame)
Drive the frame after the initiator address: bit-banged, or from the UART, five UART bits per CEC bit...
Definition hdmi_cec.cpp:370
static void gpio_isr_s(HDMICEC *self)
Definition hdmi_cec.cpp:502
std::atomic< uint8_t > dropped_frames_
Definition hdmi_cec.h:251
bool send(uint8_t source, uint8_t destination, std::span< const uint8_t > payload)
Queue a frame for transmission; false when the queue is full or in monitor mode.
Definition hdmi_cec.cpp:224
gptimer_handle_t ack_timer_
Definition hdmi_cec.h:233
static void ack_timer_isr_s()
Definition hdmi_cec.cpp:473
StaticCallbackManager< HDMI_CEC_MESSAGE_CALLBACK_COUNT, void(uint8_t, uint8_t, std::span< const uint8_t >)> message_callbacks_
Definition hdmi_cec.h:225
static constexpr uint16_t UNSET_PHYSICAL_ADDRESS
Definition hdmi_cec.h:269
ISRInternalGPIOPin isr_pin_
Definition hdmi_cec.h:228
void send_ack_()
Pull the line low for the acknowledge bit of a frame addressed to us.
Definition hdmi_cec.cpp:427
ESPHOME_ALWAYS_INLINE void set_pin_output_low_()
Definition hdmi_cec.h:209
void finish_attempt_(bool sent_ok)
Keep the frame for another attempt, or drop it once the attempts are used up.
Definition hdmi_cec.cpp:314
ReceiverState receiver_state_
Definition hdmi_cec.h:259
std::atomic< bool > eom_received_
Definition hdmi_cec.h:250
uart::UARTComponent * uart_
Definition hdmi_cec.h:230
void handle_received_message_(const Frame *frame)
Definition hdmi_cec.cpp:172
bool send_bit_(bool bit_value)
Send one bit; false when a logical 1 found the line held low by another initiator.
Definition hdmi_cec.cpp:405
ESPHOME_ALWAYS_INLINE void set_pin_input_high_()
Definition hdmi_cec.h:208
FrameRingBuffer< QUEUE_SIZE > frames_queue_
Definition hdmi_cec.h:217
InternalGPIOPin * pin_
Definition hdmi_cec.h:227
void reply_builtin_(const Frame *frame)
The built-in replies to a frame directed at us that no automation claims.
Definition hdmi_cec.cpp:186
bool transmit_frame_(const Frame *frame)
Drive the frame onto the line; false when another initiator sent at the same time.
Definition hdmi_cec.cpp:326
void write_array(const std::vector< uint8_t > &data)
std::vector< uint8_t > & out
Definition gif.cpp:49
unsigned count
Definition gif.cpp:51
@ INTERRUPT_ANY_EDGE
Definition gpio_pin.h:54
ESPHOME_ALWAYS_INLINE void atomic_set(std::atomic< T > &atom, T value)
Definition hdmi_cec.h:41
ESPHOME_LOG_TAG(TAG, "hdmi_cec")
size_t encode_uart_body(const Frame &frame, uint8_t *out)
The UART bytes that send a frame after its initiator address bits, at 2083 baud; returns how many it ...
Definition hdmi_cec.cpp:356
const char OSD_NAME_REPLY[] PROGMEM
Definition hdmi_cec.h:35
ESPHOME_ALWAYS_INLINE T atomic_get(const std::atomic< T > &atom)
Definition hdmi_cec.h:44
void progmem_memcpy(void *dst, const void *src, size_t len)
Definition hal.h:56
uint32_t value
Definition hal.cpp:59
char * format_hex_pretty_to(char *buffer, size_t buffer_size, const uint8_t *data, size_t length, char separator)
Format byte array as uppercase hex to buffer (base implementation).
Definition helpers.cpp:529
constexpr uint8_t high_nibble(uint8_t byte)
The high 4 bits of a byte, e.g. high_nibble(0xA5) == 0xA.
Definition helpers.h:1217
void const char int line
Definition log.h:110
uint32_t IRAM_ATTR HOT micros()
Definition hal.cpp:43
void delay_microseconds_safe(uint32_t us)
Delay for the given amount of microseconds, possibly yielding to other processes during the wait.
Definition helpers.cpp:911
constexpr size_t format_hex_pretty_size(size_t byte_count)
Calculate buffer size needed for format_hex_pretty_to with separator: "XX:XX:...:XX\0".
Definition helpers.h:1920
constexpr uint8_t low_nibble(uint8_t byte)
The low 4 bits of a byte, e.g. low_nibble(0xA5) == 0x5.
Definition helpers.h:1219
uint8_t progmem_read_byte(const uint8_t *addr)
Definition hal.h:51
static void uint32_t
uint16_t length
Definition tt21100.cpp:0