16#include "esphome/core/application.h"
17#include "esphome/core/hal.h"
18#include "esphome/core/log.h"
27static const char *
const TAG =
"home_io_control.exchange";
35 : radio_ptr_(radio_ptr), node_id_(node_id), system_key_(system_key), tuning_(tuning) {}
47 this->debug_.stage = stage;
48 this->debug_.tries = tries;
49 this->debug_.saw_challenge = this->debug_.saw_challenge || saw_challenge;
61 if (!capture.
valid && this->debug_.capture_valid)
63 this->debug_.capture_valid = capture.
valid;
64 this->debug_.capture_rx_done = capture.
rx_done;
65 this->debug_.capture_crc_error = capture.
crc_error;
66 this->debug_.capture_freq_hz = capture.
freq_hz;
67 this->debug_.capture_irq_status = capture.
irq_status;
69 this->debug_.capture_reported_len = capture.
reported_len;
70 this->debug_.capture_frame_len = capture.
frame_len;
71 this->debug_.capture_rssi_dbm = capture.
rssi_dbm;
75 const auto &d = this->debug_;
77 "Exchange failed: device=%s cmd=%s(0x%02X) stage=%s tries=%u max_tries=%u saw_challenge=%u cap_valid=%u "
78 "cap_rx_done=%u cap_crc_err=%u cap_freq=%" PRIu32
79 " cap_irq=0x%04X cap_pkt=0x%02X cap_reported_len=%u cap_frame_len=%u cap_rssi=%d",
80 device_id,
command_name(d.request_cmd), d.request_cmd, d.stage, d.tries, d.max_tries, d.saw_challenge,
81 d.capture_valid, d.capture_rx_done, d.capture_crc_error, d.capture_freq_hz, d.capture_irq_status,
82 d.capture_packet_status, d.capture_reported_len, d.capture_frame_len, d.capture_rssi_dbm);
108 }
while (next == skip_freq);
110 this->last_hop_us_ = micros();
114 if ((micros() - this->last_hop_us_) <=
HOP_TIME_US)
121 if ((*this->radio_ptr_)->reception_in_progress())
137 uint8_t
const len =
serialize(frame, buf,
sizeof(buf));
139 ESP_LOGW(
TAG,
"tx: serialize_failed cmd=0x%02X", frame.
cmd);
142 for (uint8_t lbt = 0; lbt < this->tuning_->lbt_max_retries; lbt++) {
144 if (rssi < this->tuning_->lbt_rssi_threshold_dbm)
146 ESP_LOGD(
TAG,
"LBT: channel busy (RSSI %d dBm), retry %u/%u", rssi, lbt + 1, this->tuning_->lbt_max_retries);
147 this->counters_.lbt_retries++;
148 if (this->pairing_telemetry_ !=
nullptr)
149 this->pairing_telemetry_->record_lbt_defer(rssi);
156 ESP_LOGW(
TAG,
"tx: send_failed cmd=0x%02X", frame.
cmd);
159 if (this->pairing_telemetry_ !=
nullptr)
160 this->pairing_telemetry_->record_tx(frame.
cmd);
182 return "wait_first_response";
184 return "build_auth_response";
186 return "tx_auth_response";
188 return "wait_final_response";
203 return "tx_challenge";
205 return "wait_challenge_response";
223void log_unparsable_frame(
const char *stage,
int tries,
const RadioRxPacket &packet) {
228 ESP_LOGW(
TAG,
"%s try=%d: %u bytes did not parse as a frame on %" PRIu32
" Hz", stage, tries, packet.len,
230#ifdef IOHOME_FRAME_LOG
233 ESP_LOGD(
TAG,
" raw: %s", hex);
238void log_exchange_frame(
const char *stage,
int tries,
const IoFrame &frame, uint8_t len) {
239 ESP_LOGD(
TAG,
"%s try=%d cmd=0x%02X src=%02X%02X%02X dst=%02X%02X%02X len=%u", stage, tries, frame.cmd, frame.src[0],
240 frame.src[1], frame.src[2], frame.dst[0], frame.dst[1], frame.dst[2], len);
244bool is_valid_final_response(
const IoFrame &candidate,
const IoFrame &request) {
260 (*this->radio_ptr_)->clear_last_capture();
263 const uint8_t tries_allowed = std::max<uint8_t>(1, std::min<uint8_t>(max_tries,
EXCHANGE_RETRY_COUNT));
264 this->debug_.max_tries = tries_allowed;
265 const uint16_t request_preamble = this->request_preamble_for_(request);
266 const uint32_t exchange_begin_ms = millis();
267 bool accepted_without_reply =
false;
269 for (uint8_t tries = 0; tries < tries_allowed; tries++) {
274 is_start(request) ? this->tuning_->exchange_start_response_wait_ms : this->tuning_->exchange_response_wait_ms;
281 if (millis() - exchange_begin_ms >= this->tuning_->exchange_total_budget_ms) {
282 this->
record_debug(
"retry_budget_exhausted", tries,
false);
283 ESP_LOGI(
TAG,
"Exchange budget exhausted after %u tries for cmd=%s(0x%02X) (%" PRIu32
" of %u ms)", tries,
285 this->tuning_->exchange_total_budget_ms);
290 this->counters_.retransmits++;
293 if (!this->transmit_request_(request, freq, request_preamble, context))
298 auto first_disp = this->wait_for_first_response_(request, context);
304 response = context.
rx;
308 if (!this->handle_authentication_(request, freq, context))
313 auto final_disp = this->wait_for_final_response_(request, context);
321 accepted_without_reply =
true;
329 response = context.
rx;
343uint16_t ExchangeEngine::request_preamble_for_(
const IoFrame &request)
const {
348 return (*this->radio_ptr_)->response_preamble();
352bool ExchangeEngine::transmit_request_(
const IoFrame &request, uint32_t freq, uint16_t preamble,
353 exchange::OutboundExchangeContext &ctx) {
356 this->
record_debug(
"tx_request_failed", ctx.try_index,
false);
365 spec.window_ms = ctx.wait_ms;
373 RadioRxPacket packet{};
374 auto outcome = this->
listen(spec, packet, ctx.rx, [&](
const IoFrame *parsed,
const RadioRxPacket &pkt) {
375 if (parsed == nullptr) {
376 this->record_debug(
"first_parse_fail", ctx.try_index, false);
377 this->counters_.parse_failures++;
378 log_unparsable_frame(
"Unparsable first response", ctx.try_index, pkt);
379 return ReplyDisposition::IGNORE;
383 this->
record_debug(
"first_wrong_exchange", ctx.try_index,
false);
384 log_exchange_frame(
"Ignored first response", ctx.try_index, *parsed, pkt.len);
387 ctx.first_response_ms = millis();
395 this->record_debug(
"wait_first_timeout", ctx.try_index,
false);
396 ESP_LOGI(
TAG,
"Try %d ended: no first response for cmd=%s(0x%02X) within %" PRIu32
" ms", ctx.try_index,
401bool ExchangeEngine::handle_authentication_(
const IoFrame &request, uint32_t freq,
402 exchange::OutboundExchangeContext &ctx) {
403 ctx.saw_challenge =
true;
404 ctx.state = exchange::OutboundExchangeState::BUILD_AUTH_RESPONSE;
405 this->record_debug(outbound_stage_name(ctx.state), ctx.try_index,
true);
408 if (!
create_challenge_resp(auth_resp, request.dst, this->node_id_, ctx.rx.data, request, this->system_key_)) {
409 ctx.state = exchange::OutboundExchangeState::FAILED;
410 this->record_debug(
"auth_build_failed", ctx.try_index,
true);
417 ESP_LOGI(TAG,
"Auth challenge try=%d wait_ms=%" PRIu32
" req_cmd=0x%02X req_len=%u", ctx.try_index,
418 ctx.first_response_ms - ctx.exchange_start_ms, request.cmd, request.data_len);
420 ctx.state = exchange::OutboundExchangeState::TX_AUTH_RESPONSE;
421 this->record_debug(outbound_stage_name(ctx.state), ctx.try_index,
true);
422 if (!this->transmit_frame(auth_resp, freq, (*this->radio_ptr_)->response_preamble())) {
423 ctx.state = exchange::OutboundExchangeState::FAILED;
424 this->record_debug(
"tx_auth_failed", ctx.try_index,
true);
427 this->counters_.challenge_round_trips++;
431decisions::ExchangeFinalResponseDisposition ExchangeEngine::wait_for_final_response_(
432 const IoFrame &request, exchange::OutboundExchangeContext &ctx) {
435 const uint32_t auth_wait_ms = this->tuning_->exchange_response_wait_ms;
438 spec.window_ms = auth_wait_ms;
442 spec.policy = ListenPolicy::HOLD_REQUEST_CHANNEL;
444 RadioRxPacket packet{};
445 auto outcome = this->listen(spec, packet, ctx.rx, [&](
const IoFrame *parsed,
const RadioRxPacket &pkt) {
446 if (parsed == nullptr) {
447 this->record_debug(
"final_parse_fail", ctx.try_index, true);
448 this->counters_.parse_failures++;
449 log_unparsable_frame(
"Unparsable final response", ctx.try_index, pkt);
450 return ReplyDisposition::IGNORE;
452 if (is_valid_final_response(*parsed, request))
453 return ReplyDisposition::ACCEPT;
454 this->record_debug(
"final_wrong_exchange", ctx.try_index,
true);
455 log_exchange_frame(
"Ignored final response", ctx.try_index, *parsed, pkt.len);
456 return ReplyDisposition::IGNORE;
459 if (outcome == ListenOutcome::ACCEPTED)
460 return decisions::ExchangeFinalResponseDisposition::ACCEPT;
462 ctx.state = exchange::OutboundExchangeState::FAILED;
463 this->record_debug(
"wait_final_timeout", ctx.try_index,
true);
464 ESP_LOGI(TAG,
"Try %d ended: no matching final response for cmd=%s(0x%02X) within %" PRIu32
" ms", ctx.try_index,
466 return decisions::ExchangeFinalResponseDisposition::IGNORE_UNRELATED;
477 if (!this->
transmit_frame(request, freq, this->request_preamble_for_(request))) {
504 if (parsed ==
nullptr || parsed->
cmd != expected_cmd || memcmp(parsed->
dst, this->node_id_,
NODE_ID_SIZE) != 0)
508 if (count < UINT8_MAX)
539 const bool parsed =
parse(packet.
data, packet.
len, frame);
540 switch (on_frame(parsed ? &frame :
nullptr, packet)) {
555bool preamble_or_sync_incoming(RadioDriver *radio,
const ListenSpec &spec) {
556 return spec.linger_on_preamble && (radio->is_preamble_detected() || radio->is_sync_detected());
565uint32_t resolve_dwell_ms(
const ListenSpec &spec,
bool rotating, RadioDriver *radio,
const TuningConfig &tuning) {
568 if (spec.dwell_ms != 0)
569 return spec.dwell_ms;
570 return radio->hop_dwell_ms(tuning);
575void ExchangeEngine::listen_hop_(uint32_t skip,
const ListenSpec &spec) {
576 this->hop_frequency(skip);
584 const uint32_t deadline = millis() + spec.
window_ms;
590 const uint32_t dwell = resolve_dwell_ms(spec, rotating, radio, *this->tuning_);
596 this->listen_hop_(skip, spec);
598 while ((int32_t) (deadline - millis()) > 0) {
599 const uint32_t remaining = deadline - millis();
603 const uint32_t slice = rotating ? std::min(remaining, dwell) : remaining;
607 if (dispatch_received_packet(on_frame, packet, frame, outcome))
613 !preamble_or_sync_incoming(radio, spec))
614 this->listen_hop_(skip, spec);
618 if ((int32_t) (deadline - millis()) <= 0)
622 if (!preamble_or_sync_incoming(radio, spec)) {
623 this->listen_hop_(skip, spec);
628 const uint32_t ext = std::min((uint32_t) (deadline - millis()), spec.
linger_dwell_ms);
630 if (radio->
wait_for_packet(packet, ext) && dispatch_received_packet(on_frame, packet, frame, outcome))
661 if (!radio->
wait_for_packet(packet, this->tuning_->exchange_response_wait_ms)) {
668 if (!
parse(packet.
data, packet.
len, rx) || !frame_is_challenge_response(rx)) {
679 frame_data[0] = request.
cmd;
689 this->counters_.challenge_round_trips++;
std::function< void(const IoFrame &frame, int16_t rssi_dbm)> BroadcastReplyHandler
Invoked for each matching broadcast reply, as it arrives.
ListenOutcome listen(const ListenSpec &spec, RadioRxPacket &packet, IoFrame &frame, const ReplyHandler &on_frame)
The one listen primitive every radio wait loop in this project is built on.
ExchangeOutcome send_and_receive(const IoFrame &request, IoFrame &response, uint32_t freq, uint8_t max_tries=EXCHANGE_RETRY_COUNT)
Execute an outbound authenticated exchange with retry.
void maybe_hop()
Hop only if the minimum dwell has elapsed and no frame is currently arriving on this channel — RadioD...
void reset_debug(uint8_t request_cmd)
Clear the debug snapshot and record the upcoming request command.
uint8_t collect_broadcast_responses(const IoFrame &request, uint32_t freq, uint8_t expected_cmd, uint32_t window_ms, const BroadcastReplyHandler &on_reply)
Transmit request once and hand every matching broadcast reply to on_reply within window_ms.
void log_debug(const char *device_id) const
Log the debug snapshot as a WARN-level structured line.
ExchangeEngine(RadioDriver **radio_ptr, const uint8_t *node_id, const uint8_t *system_key, const TuningConfig *tuning)
Construct the engine with double-pointer indirection into the hub's RadioDriver pointer and direct po...
bool transmit_frame(const IoFrame &frame, uint32_t freq, uint16_t preamble)
Transmit a raw IoFrame with LBT and the given preamble length.
bool authenticate_request(const IoFrame &request, uint32_t freq)
Authenticate an inbound device command via 0x3C challenge / 0x3D HMAC.
void reset_hop_timestamp()
Reset the hop-timer (called after radio init in hub setup()).
void hop_frequency(uint32_t skip_freq=0)
Advance the receiver one step along the protocol's channel rotation (CH1→CH2→CH3→CH1).
void record_debug(const char *stage, uint8_t tries, bool saw_challenge)
Update the debug snapshot with the current stage and radio capture.
Abstract radio driver for IO-Homecontrol.
uint32_t get_current_freq() const
Get the current RF frequency.
virtual void change_frequency(uint32_t freq_hz)=0
Change the carrier frequency using fast hop (no standby transition needed).
const RadioCaptureInfo & get_last_capture() const
Get the most recent radio capture info.
virtual bool send_packet(const uint8_t *data, uint8_t len, const RadioTxConfig &tx_config)=0
Send a packet using the specified carrier frequency and preamble settings.
virtual int16_t read_rssi()=0
Read instantaneous RSSI (in dBm) while in RX mode.
virtual bool wait_for_packet(RadioRxPacket &packet, uint32_t timeout_ms)=0
Wait (blocking) for a packet with timeout.
Self-contained authenticated exchange engine for IO-Homecontrol 2W.
Pure transition helpers for hub-owned exchange and pairing frame decisions.
Shared frame logging helpers for IO-Homecontrol.
bool verify_hmac(const uint8_t *data, uint8_t len, const uint8_t hmac[HMAC_SIZE], const uint8_t challenge[HMAC_SIZE], const uint8_t key[AES_KEY_SIZE])
Verify a received HMAC using constant-time comparison.
ExchangeFirstResponseDisposition classify_exchange_first_response(const IoFrame &request, const IoFrame &candidate)
Decide how to handle the first response packet in an authenticated exchange.
@ ACCEPT
Frame matches expected response — exchange succeeds.
ExchangeFirstResponseDisposition
Disposition for the first response in an authenticated exchange.
@ IGNORE_UNRELATED
Frame doesn't match endpoints or failed parse — keep waiting.
@ COMPLETE_DIRECT
Matching non-challenge frame — operation complete, no auth needed.
bool retry_after_unconfirmed_accept_is_safe(uint8_t cmd)
Whether an authenticated-but-unanswered request may be sent again.
ExchangeFinalResponseDisposition classify_exchange_final_response(const IoFrame &request, const IoFrame &candidate)
Decide if a candidate frame is an acceptable final response after authentication.
InboundAuthState
Progress stages of inbound authentication (device‑initiated commands).
@ WAIT_CHALLENGE_RESPONSE
Timer running; waiting for device's HMAC proof (0x3D).
@ VERIFIED
Device successfully authenticated; command is trusted.
@ TX_CHALLENGE
Challenge (0x3C) sent to device; awaiting 0x3D response.
@ IDLE
No inbound authentication in progress.
@ FAILED
Authentication failed (timeout or HMAC mismatch).
OutboundExchangeState
Progress stages of an outbound authenticated exchange (non‑pairing).
@ TX_REQUEST
Request frame transmitted; awaiting first response from device.
@ TX_AUTH_RESPONSE
Auth response (0x3D) transmitted; awaiting device's final reply.
@ IDLE
No active exchange; idle state.
@ BUILD_AUTH_RESPONSE
Building the 0x3D challenge response after receiving 0x3C.
@ FAILED
Exchange failed (timeout, retries exhausted, or radio error).
@ SUCCESS
Exchange completed successfully; device acknowledged.
@ WAIT_FIRST_RESPONSE
Listening for first response. This may be a challenge (0x3C) or the final response.
@ WAIT_FINAL_RESPONSE
Listening for the authenticated final response (e.g., status frame).
static constexpr uint8_t NODE_ID_SIZE
Device/node addresses are 3 bytes (e.g., "123ABC").
static constexpr const char * TAG
bool is_start(const IoFrame &f)
Check START flag.
static constexpr uint32_t FREQ_CH1
The protocol uses 3 frequency channels in the 868 MHz ISM band.
static constexpr uint32_t FREQ_CH3
Channel 3: 869.85 MHz (2W only).
static constexpr int32_t HOP_TIME_US
Timing constants for frequency hopping and response waiting.
const char * command_name(uint8_t cmd)
Get a human-readable name for any IO-Homecontrol command ID.
static constexpr uint8_t FRAME_MAX_SIZE
Historical name for FRAME_MAX_DECLARED_SIZE, kept as an alias rather than a second literal so the two...
static constexpr int32_t EXCHANGE_RETRY_DELAY_MS
Gap between retries within one HA command.
std::function< ReplyDisposition(const IoFrame *parsed, const RadioRxPacket &packet)> ReplyHandler
Invoked for every packet the radio delivers during a listen, before the listen decides whether to kee...
@ ACCEPT
This is the frame the caller was waiting for — stop listening, return ACCEPTED.
@ ABORT
An explicit refusal (e.g. CMD_ERROR_RESP) — stop listening, return ABORTED.
@ IGNORE
Unparsable / not ours / wrong exchange — keep listening.
bool create_challenge_resp(IoFrame &f, const uint8_t *dst, const uint8_t *src, const uint8_t challenge[HMAC_SIZE], const IoFrame &origin, const uint8_t *key)
Build a challenge response (0x3D) proving we know the system key.
void render_frame_hex_redacted(const uint8_t *data, uint8_t len, char *out, size_t out_size)
Render a frame's bytes as spaced hex text, masking the payload when the command carries key material ...
ExchangeOutcome
Authenticated exchange engine — outbound and inbound protocol flows.
@ SUCCESS_WITH_RESPONSE
Device replied; the caller's response frame is populated.
@ SUCCESS_UNCONFIRMED
Device authenticated the request — so it received and accepted it — but sent no final response.
@ FAILED
No usable reply; the device may never have heard the request.
constexpr size_t FRAME_LOG_HEX_BUFFER_SIZE
Fits a full 32-byte frame rendered as spaced hex text.
static constexpr uint8_t FRAME_MAX_WIRE_SIZE
Largest number of bytes a buffer must hold to receive or transmit any frame this project knows about,...
@ ROTATE_SKIPPING_REQUEST
The two channels that are not the request channel. Roll-call.
@ HOLD_REQUEST_CHANNEL
Never retunes, never slices. Unicast replies.
bool parse(const uint8_t *buf, uint8_t buf_len, IoFrame &f)
Parse a wire buffer into a parsed IoFrame (validates length and CTRL0).
static constexpr uint8_t EXCHANGE_RETRY_COUNT
Attempts per command before reporting failure.
static constexpr uint32_t FREQ_CH2
Channel 2: 868.95 MHz (1W and 2W, TX channel).
ListenOutcome
How one call to ExchangeEngine::listen() ended.
@ ABORTED
The handler returned ReplyDisposition::ABORT for some received frame.
@ ACCEPTED
The handler returned ReplyDisposition::ACCEPT for some received frame.
@ TIMED_OUT
spec.window_ms elapsed with no ACCEPT/ABORT.
static constexpr uint8_t LBT_RETRY_DELAY_MS
Backoff between LBT checks (≥ 5ms per ETSI).
static constexpr uint16_t SHORT_PREAMBLE
8 bytes for response/continuation frames
static constexpr uint8_t CMD_CHALLENGE_RESP
HMAC proof answering a 0x3C.
static constexpr uint32_t PREAMBLE_LINGER_DWELL_MS
Preamble/sync linger extension for a rotating listen (ListenSpec::linger_dwell_ms): how much longer t...
static constexpr uint16_t LONG_PREAMBLE
Preamble is a sequence of 0xAA bytes that precedes every frame.
bool create_challenge_req(IoFrame &f, const uint8_t *dst, const uint8_t *src, const uint8_t challenge[HMAC_SIZE])
Build a challenge request (0x3C) using a caller-supplied challenge.
static constexpr uint8_t CTRL1_LOW_POWER
Bit 5: low-power device (e.g., solar-powered).
uint8_t serialize(const IoFrame &f, uint8_t *buf, uint8_t buf_size)
Serialize a parsed frame into a wire buffer (without CRC).
Command builders for the IO‑Homecontrol protocol.
IO-Homecontrol command IDs, result codes and protocol enumerations.
Cryptographic helpers for the IO‑Homecontrol protocol.
Snapshot of the last exchange attempt for diagnostics.
uint8_t request_cmd
Command ID of the original request.
Parsed IO‑Homecontrol frame (CTRL0/1 + addresses + command + data).
uint8_t data[FRAME_MAX_DATA_SIZE]
Command parameters (0–23 bytes). Never includes mac.
uint8_t src[NODE_ID_SIZE]
Source node ID (3 bytes).
uint8_t dst[NODE_ID_SIZE]
Destination node ID (3 bytes).
uint8_t data_len
Actual length of data.
uint8_t ctrl1
Control byte 1: low power, beacon, etc.
How one listen window is to be spent — everything ExchangeEngine::listen() needs; everything else is ...
uint32_t request_freq
Channel the request went out on (Hz).
uint32_t window_ms
Total time budget for this listen, in milliseconds.
uint32_t linger_dwell_ms
Length of the preamble/sync extension, in milliseconds.
ListenPolicy policy
Which channels this listen covers.
bool linger_on_preamble
Extend the listen instead of hopping while the chip reports a preamble or sync word,...
bool hop_after_ignored_frame
Hop after a frame the handler ignored.
Diagnostic capture from a radio operation.
uint8_t frame_len
Number of valid bytes in frame[].
uint16_t irq_status
Raw IRQ status register value.
uint8_t packet_status
Packet status byte (chip-specific).
bool crc_error
True if a CRC error was detected.
bool valid
True if capture is valid.
uint8_t reported_len
Length reported by the radio chip.
bool rx_done
True if RxDone IRQ fired.
uint32_t freq_hz
RF frequency of capture (Hz).
int16_t rssi_dbm
Received signal strength (dBm).
Raw packet received from the radio.
uint8_t len
Length of packet in bytes.
uint8_t data[RADIO_PACKET_BUFFER_SIZE]
Raw packet data buffer.
Configuration for transmitting a packet: carrier frequency and preamble length.
uint16_t preamble_len
Preamble length in symbol periods (bytes).
uint32_t freq_hz
Carrier frequency in Hz.
All runtime tunable parameters for pairing and radio diagnostics.
uint16_t normal_start_preamble
Preamble for a directed start frame to a non-low-power target.
Context for a single inbound authentication (device‑initiated command).
IoFrame challenge
The 0x3C challenge frame we sent (needed to verify 0x3D response).
InboundAuthState state
Current authentication state.
Context carried across one outbound authenticated exchange.
uint8_t try_index
Current retry attempt (1‑based within EXCHANGE_RETRY_COUNT).
IoFrame rx
Most recent candidate frame received during the exchange.
uint32_t exchange_start_ms
Timestamp when the exchange attempt began (millis).
uint32_t wait_ms
Current timeout window for the active wait (ms).
OutboundExchangeState state
Current state machine state.