Home IO Control
ESPHome add-on for IO-Homecontrol devices
Loading...
Searching...
No Matches
exchange_engine.cpp
Go to the documentation of this file.
1/// @file exchange_engine.cpp
2/// @brief Authenticated exchange engine — outbound and inbound protocol flows.
3/// @ingroup hioc_hub
4///
5/// Implements ExchangeEngine: the retry loop, challenge-response
6/// authentication, final-response wait, listen-before-talk transmit, and
7/// frequency-hopping. Debug-snapshot helpers are also here.
8
9#include "exchange_engine.h"
10
11#include "hub_decisions.h"
12#include "log_frame.h"
13#include "proto_commands.h"
14#include "proto_constants.h"
15#include "proto_crypto.h"
16#include "esphome/core/application.h"
17#include "esphome/core/hal.h"
18#include "esphome/core/log.h"
19
20#include <algorithm>
21#include <cinttypes>
22#include <cstdio>
23#include <cstring>
24
25namespace esphome {
26namespace home_io_control {
27
28static const char *const TAG = "home_io_control.exchange";
29
30/// Microseconds per millisecond, for rounding a driver's transmit-time estimate up to whole ms.
31static constexpr uint32_t US_PER_MS = 1000;
32
33// ============================================================================
34// Construction
35// ============================================================================
36
37ExchangeEngine::ExchangeEngine(RadioDriver **radio_ptr, const uint8_t *node_id, const uint8_t *system_key,
38 const TuningConfig *tuning)
39 : radio_ptr_(radio_ptr), node_id_(node_id), system_key_(system_key), tuning_(tuning) {}
40
41// ============================================================================
42// Debug snapshot helpers
43// ============================================================================
44
45void ExchangeEngine::reset_debug(uint8_t request_cmd) {
46 this->debug_ = DebugInfo{};
47 this->debug_.request_cmd = request_cmd;
48}
49
50void ExchangeEngine::note_final_wait_(const ListenStats &stats) {
51 DebugInfo &d = this->debug_;
52 const auto add = [](uint8_t &total, uint8_t n) {
53 total = static_cast<uint8_t>(std::min<unsigned>(total + n, UINT8_MAX));
54 };
55 add(d.final_waits, 1);
56 add(d.final_rx_ignored, stats.frames_ignored);
57 add(d.final_rx_failed, stats.failed_receptions);
58 if (stats.failed_receptions != 0)
59 d.final_rx_irq = stats.last_failed_irq;
60}
61
62void ExchangeEngine::record_debug(const char *stage, uint8_t tries, bool saw_challenge) {
63 this->debug_.stage = stage;
64 this->debug_.tries = tries;
65 this->debug_.saw_challenge = this->debug_.saw_challenge || saw_challenge;
66
67 const RadioCaptureInfo &capture = (*this->radio_ptr_)->get_last_capture();
68 // send_and_receive() blanks the radio capture at the start of each exchange (the path this
69 // snapshot mainly serves), so a valid capture here belongs to the current exchange rather than a
70 // previous one. wait_for_packet() re-clears the capture before each listen, so the *last*
71 // record_debug() call is always the final timed-out wait, which saw nothing. Keep the first
72 // informative capture instead: it distinguishes "the radio never detected a frame" from "it
73 // received one and this layer discarded it" — the question a failure report has to answer.
74 // Known gap: record_debug() calls outside that blanking — the bare ones in pairing_engine.cpp,
75 // authenticate_request(), and collect_broadcast_responses()'s "broadcast_tx_failed" branch — can
76 // still carry a capture from before their flow began. None of those snapshots reaches log_debug().
77 if (!capture.valid && this->debug_.capture_valid)
78 return;
79 this->debug_.capture_valid = capture.valid;
80 this->debug_.capture_rx_done = capture.rx_done;
81 this->debug_.capture_crc_error = capture.crc_error;
82 this->debug_.capture_freq_hz = capture.freq_hz;
83 this->debug_.capture_irq_status = capture.irq_status;
84 this->debug_.capture_packet_status = capture.packet_status;
85 this->debug_.capture_reported_len = capture.reported_len;
86 this->debug_.capture_frame_len = capture.frame_len;
87 this->debug_.capture_rssi_dbm = capture.rssi_dbm;
88}
89
90int render_exchange_debug(char *buf, size_t buf_size, const char *device_id, const ExchangeEngine::DebugInfo &d) {
91 return snprintf(buf, buf_size,
92 "device=%s cmd=%s(0x%02X) stage=%s tries=%u max_tries=%u saw_challenge=%u cap_valid=%u "
93 "cap_rx_done=%u cap_crc_err=%u cap_freq=%" PRIu32
94 " cap_irq=0x%04X cap_pkt=0x%02X cap_reported_len=%u cap_frame_len=%u cap_rssi=%d belief=%s "
95 "last_preamble=%u final_waits=%u final_rx_ignored=%u final_rx_failed=%u final_rx_irq=0x%04X",
96 device_id, command_name(d.request_cmd), d.request_cmd, d.stage, d.tries, d.max_tries,
97 // Rendered as 0/1: these are flags in a field list, not prose, and a caller greps them.
98 static_cast<unsigned>(d.saw_challenge), static_cast<unsigned>(d.capture_valid),
99 static_cast<unsigned>(d.capture_rx_done), static_cast<unsigned>(d.capture_crc_error),
106}
107
108void ExchangeEngine::log_debug(const char *device_id) const {
109 char fields[EXCHANGE_DEBUG_LINE_SIZE];
110 render_exchange_debug(fields, sizeof(fields), device_id, this->debug_);
111 ESP_LOGW(TAG, "Exchange failed: %s", fields);
112}
113
114void ExchangeEngine::log_debug_unconfirmed(const char *device_id) const {
115 char fields[EXCHANGE_DEBUG_LINE_SIZE];
116 render_exchange_debug(fields, sizeof(fields), device_id, this->debug_);
117 // "accepted" describes what the device did with the request, not what it did with our challenge
118 // answer — see the WAIT_FINAL_RESPONSE branch in send_and_receive() for why silence here has two
119 // possible causes. The final_rx_* fields are what tells them apart: a reception during the final
120 // wait means something came back and was lost here. The cap_* fields cannot, because they keep
121 // the first informative reception, which is the device's challenge.
122 ESP_LOGI(TAG, "Exchange accepted without a closing reply: %s", fields);
123}
124
125// ============================================================================
126// Frequency hopping
127// ============================================================================
128
129void ExchangeEngine::reset_hop_timestamp() { this->last_hop_us_ = micros(); }
130
131void ExchangeEngine::hop_frequency(uint32_t skip_freq) {
132 RadioDriver *radio = *this->radio_ptr_;
133 uint32_t next = radio->get_current_freq();
134 // At most two iterations: the rotation cycles through all three channels and only one of them
135 // can be skipped, so a channel that is not skip_freq is always one or two steps away.
136 do {
137 switch (next) {
138 case FREQ_CH1:
139 next = FREQ_CH2;
140 break;
141 case FREQ_CH3:
142 next = FREQ_CH1;
143 break;
144 default:
145 next = FREQ_CH3;
146 break;
147 }
148 } while (next == skip_freq);
149 radio->change_frequency(next);
150 this->last_hop_us_ = micros();
151}
152
154 if ((micros() - this->last_hop_us_) <= HOP_TIME_US)
155 return;
156 // A frame arriving on this channel outranks the dwell timer: change_frequency() retunes under a
157 // running demodulator and, on the software-PHY chips, also clears the IRQ word and the DIO
158 // latch, so hopping here destroys the frame rather than deferring it (issue #81).
159 // last_hop_us_ is deliberately left alone: the dwell has already been served, so the hop should
160 // happen on the very next pass once the reception clears, not a further HOP_TIME_US later.
161 if ((*this->radio_ptr_)->reception_in_progress())
162 return;
163 this->hop_frequency();
164}
165
166// ============================================================================
167// Transmit with LBT
168// ============================================================================
169
170namespace {
171
172/// The RadioTxConfig for `frame` on `freq` with `preamble`: the one place a transmission's shape
173/// (channel, preamble, wake-up level) is decided, for transmit_frame() and for the budget estimate.
174RadioTxConfig tx_config_for(const IoFrame &frame, uint32_t freq, uint16_t preamble) {
175 RadioTxConfig tx_config{};
176 tx_config.freq_hz = freq;
177 tx_config.preamble_len = preamble;
178 tx_config.wake = tx_wake_for(is_start(frame), preamble);
179 return tx_config;
180}
181
182} // namespace
183
184bool ExchangeEngine::transmit_frame(const IoFrame &frame, uint32_t freq, uint16_t preamble) {
185 RadioDriver *radio = *this->radio_ptr_;
186 // FRAME_MAX_WIRE_SIZE, not FRAME_MAX_SIZE: a frame with an out-of-length MAC trailer
187 // (IoFrame::has_mac, e.g. CMD_ONEWAY_ADD_CONTROLLER) serializes to more than
188 // FRAME_MAX_SIZE/FRAME_MAX_DECLARED_SIZE bytes, and serialize() rejects a buffer too small to
189 // hold its actual output rather than truncating into it.
190 uint8_t buf[FRAME_MAX_WIRE_SIZE];
191 uint8_t const len = serialize(frame, buf, sizeof(buf));
192 if (len == 0) {
193 ESP_LOGW(TAG, "tx: serialize_failed cmd=0x%02X", frame.cmd);
194 return false;
195 }
196 // Listen before talk: up to lbt_max_retries sends that the radio makes only if the TX channel is
197 // clear, measured by the driver on that channel right before transmitting; after the last busy
198 // result, one send without the check, so a noisy channel delays a frame but never drops it.
199 // Only a frame that opens a session (CTRL0 START) is checked. A frame without START answers one
200 // the peer has just sent and is listening for on this channel for only a few tens of ms, so it
201 // goes out at once: a 5 ms back-off already loses the exchange on some receivers (issue #178),
202 // and the frame that opened the session was checked by whoever sent it (ADR 0045).
203 const uint8_t lbt_checks = is_start(frame) ? this->tuning_->lbt_max_retries : 0;
204 RadioTxConfig tx_config = tx_config_for(frame, freq, preamble);
205 TxResult result;
206 for (uint8_t lbt = 0;; lbt++) {
207 if (lbt < lbt_checks) {
208 tx_config.cca_threshold_dbm = this->tuning_->lbt_rssi_threshold_dbm;
209 } else {
210 tx_config.cca_threshold_dbm.reset();
211 }
212 result = radio->send_packet(buf, len, tx_config);
214 break;
215 ESP_LOGD(TAG, "LBT: channel busy (RSSI %d dBm on %" PRIu32 " Hz), retry %u/%u", result.cca_level_dbm, freq, lbt + 1,
216 lbt_checks);
217 this->counters_.lbt_retries++;
218 if (this->transmit_observer_ != nullptr)
219 this->transmit_observer_->on_lbt_defer(result.cca_level_dbm);
220 delay(LBT_RETRY_DELAY_MS);
221 }
222 if (!result.sent()) {
223 ESP_LOGW(TAG, "tx: send_failed cmd=0x%02X", frame.cmd);
224 return false;
225 }
226 if (this->transmit_observer_ != nullptr)
227 this->transmit_observer_->on_transmit(frame, tx_config, len);
228 return true;
229}
230
231uint32_t ExchangeEngine::tx_time_ms_(const IoFrame &frame, uint32_t freq, uint16_t preamble) const {
232 uint8_t buf[FRAME_MAX_WIRE_SIZE];
233 uint8_t const len = serialize(frame, buf, sizeof(buf));
234 if (len == 0)
235 return 0;
236 uint32_t const tx_us = (*this->radio_ptr_)->tx_air_time_us(len, tx_config_for(frame, freq, preamble));
237 return (tx_us + US_PER_MS - 1) / US_PER_MS;
238}
239
240bool ExchangeEngine::try_fits_budget_(uint32_t elapsed_ms, uint32_t gap_ms, uint32_t tx_ms) const {
241 return elapsed_ms + gap_ms + tx_ms < this->tuning_->exchange_total_budget_ms;
242}
243
244// ============================================================================
245// Outbound exchange — main entry point
246// ============================================================================
247
248namespace {
249
250/// @brief Map OutboundExchangeState to a short string for debug logging.
251///
252/// OutboundExchangeState is written at each step for debug capture but is
253/// never read back for control-flow decisions — all branching is driven by
254/// return values and disposition enums.
255const char *outbound_stage_name(exchange::OutboundExchangeState state) {
256 switch (state) {
258 return "idle";
260 return "tx_request";
262 return "wait_first_response";
264 return "build_auth_response";
266 return "tx_auth_response";
268 return "wait_final_response";
270 return "success";
272 default:
273 return "failed";
274 }
275}
276
277/// @brief Map InboundAuthState to a short string for debug logging.
278const char *inbound_stage_name(exchange::InboundAuthState state) {
279 switch (state) {
281 return "idle";
283 return "tx_challenge";
285 return "wait_challenge_response";
287 return "verified";
289 default:
290 return "failed";
291 }
292}
293
294/// Check if frame is a 0x3D challenge response.
295bool frame_is_challenge_response(const IoFrame &frame) { return frame.cmd == CMD_CHALLENGE_RESP; }
296
297/// Log a frame that arrived but could not be parsed. Printing it distinguishes "the radio heard
298/// nothing" from "we heard something and rejected it" in a failure report — the two need opposite
299/// fixes: a device that never transmitted needs a longer wait or a link check, while one that
300/// transmits noise this layer can't decode needs the RX bandwidth or framing looked at. Redacted
301/// through the same helper as every other frame log, so an unparsable frame can't leak key material
302/// by being unrecognisable (see ADR 0011).
303void log_unparsable_frame(const char *stage, int tries, const RadioRxPacket &packet) {
304 // The *fact* that a frame failed to parse stays unconditional — it is a real fault worth
305 // surfacing to someone who never enables a debug flag. The raw bytes only help someone already
306 // debugging the PHY, and a noisy channel can produce several of these a minute, so they sit
307 // behind the frame-log flag with the rest of that detail.
308 ESP_LOGW(TAG, "%s try=%d: %u bytes did not parse as a frame on %" PRIu32 " Hz", stage, tries, packet.len,
309 packet.freq_hz);
310#ifdef IOHOME_FRAME_LOG
312 render_frame_hex_redacted(packet.data, packet.len, hex, sizeof(hex));
313 ESP_LOGD(TAG, " raw: %s", hex);
314#endif
315}
316
317/// Log an exchanged frame with context (stage, try index, length).
318void log_exchange_frame(const char *stage, int tries, const IoFrame &frame, uint8_t len) {
319 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],
320 frame.src[1], frame.src[2], frame.dst[0], frame.dst[1], frame.dst[2], len);
321}
322
323/// Buffer for format_try_age(): "n/a", or a uint32_t's ten decimal digits, plus the terminator.
324constexpr size_t TRY_AGE_BUFFER_SIZE = 12;
325
326/// Render a try's `age_ms=` field: how long before this try the target was last heard, or "n/a"
327/// when there is no stamp (never heard, or the target evidence was not looked up). Every try line
328/// carries it next to the try's preamble, so field logs show which preamble reaches a low-power
329/// receiver how long after it last spoke — the data the wake-belief windows are sized from. The
330/// stamp is read once, before the exchange, so a challenge heard on an earlier try of the same
331/// exchange does not reset it.
332void format_try_age(const exchange::OutboundExchangeContext &ctx, char (&buf)[TRY_AGE_BUFFER_SIZE]) {
333 if (ctx.target_last_seen_ms == 0) {
334 snprintf(buf, sizeof(buf), "n/a");
335 return;
336 }
337 snprintf(buf, sizeof(buf), "%" PRIu32, ctx.try_start_ms - ctx.target_last_seen_ms);
338}
339
340/// True for a start frame addressed to a duty-cycled receiver — the only frame that has a wake-up
341/// preamble to choose. One definition, shared by the fixed rule and the per-try wake belief.
342bool is_low_power_start(const IoFrame &request) { return is_start(request) && (request.ctrl1 & CTRL1_LOW_POWER) != 0; }
343
344/// Determine if a candidate frame is a valid final response for the request.
345bool is_valid_final_response(const IoFrame &candidate, const IoFrame &request) {
346 return decisions::classify_exchange_final_response(request, candidate) ==
348}
349
350} // namespace
351
352ExchangeOutcome ExchangeEngine::send_and_receive(const IoFrame &request, IoFrame &response, uint32_t freq,
353 uint8_t max_tries, uint16_t request_preamble_override) {
354 this->reset_debug(request.cmd);
355 // Blank the radio's diagnostic capture at the start of the exchange. The radio only clears it
356 // when it actually begins a listen, so an exchange that transmits and then hears nothing at all
357 // would otherwise inherit the *previous* exchange's capture and claim "we heard a frame" when
358 // nothing was on air. Done here rather than in reset_debug() because collect_broadcast_responses()
359 // shares that helper but does not need this: its only capture reader runs per delivered reply
360 // (with the listen repopulating the capture first), and its DebugInfo is never passed to log_debug().
361 (*this->radio_ptr_)->clear_last_capture();
362 // Clamp once: never below 1 (a caller passing 0 must not silently transmit nothing) and never
363 // above EXCHANGE_RETRY_COUNT (the budget check downstream assumes that ceiling).
364 uint8_t tries_allowed = std::max<uint8_t>(1, std::min<uint8_t>(max_tries, EXCHANGE_RETRY_COUNT));
365 this->debug_.max_tries = tries_allowed;
366 const PreamblePlan preamble_plan = this->plan_request_preamble_(request, request_preamble_override);
367 this->debug_.wake_belief_use = preamble_plan.use;
368 if (preamble_plan.use == WakeBeliefUse::APPLIED) {
369 this->debug_.wake_belief = preamble_plan.belief;
370 if (preamble_plan.belief == decisions::WakeBelief::AWAKE) {
371 ESP_LOGD(TAG, "Low-power target %s believed %s: short preamble first", node_id_to_string(request.dst).c_str(),
372 decisions::wake_belief_name(preamble_plan.belief));
373 }
374 }
375 const uint32_t exchange_begin_ms = millis();
376 uint8_t unconfirmed_tries = 0; // tries that ended challenged but never closed
377
378 for (uint8_t tries = 0; tries < tries_allowed; tries++) {
380 context.try_index = tries + 1;
381 context.wait_ms =
382 is_start(request) ? this->tuning_->exchange_start_response_wait_ms : this->tuning_->exchange_response_wait_ms;
384
385 if (tries > 0) {
386 // The retry count is a maximum, not a promise: don't start a try whose transmission would
387 // end past the budget. See EXCHANGE_TOTAL_BUDGET_MS -- this is what keeps a failing command
388 // from blocking the ESPHome loop for the full retries x (transmission + response window)
389 // product.
390 if (!this->try_fits_budget_(millis() - exchange_begin_ms, EXCHANGE_RETRY_DELAY_MS,
391 this->tx_time_ms_(request, freq, preamble_plan.for_try(context.try_index)))) {
392 this->record_debug("retry_budget_exhausted", tries, false);
393 ESP_LOGI(TAG, "Exchange budget exhausted after %u tries for cmd=%s(0x%02X) (%" PRIu32 " of %u ms)", tries,
394 command_name(request.cmd), request.cmd, millis() - exchange_begin_ms,
395 this->tuning_->exchange_total_budget_ms);
396 break;
397 }
398 App.feed_wdt();
399 delay(EXCHANGE_RETRY_DELAY_MS);
400 this->counters_.retransmits++;
401 }
402
403 // Stamped after the retry gap, so a try's wait_ms and age_ms measure from its own transmit and
404 // not from the end of the previous try.
405 context.try_start_ms = millis();
406 context.request_preamble = preamble_plan.for_try(context.try_index);
407 context.target_last_seen_ms = preamble_plan.last_seen_ms;
408 this->debug_.last_try_preamble = context.request_preamble;
409 if (!this->transmit_request_(request, freq, context.request_preamble, context))
410 continue;
411
413 this->record_debug(outbound_stage_name(context.state), context.try_index, false);
414 auto first_disp = this->wait_for_first_response_(request, context);
416 continue;
419 this->record_debug("success_direct", context.try_index, false);
420 // The hit counterpart of "Try N ended": an unauthenticated reply (a status poll's answer)
421 // prints no challenge line, so without this a log would only ever show which preambles missed.
422 char age[TRY_AGE_BUFFER_SIZE];
423 format_try_age(context, age);
424 ESP_LOGI(TAG, "Try %d answered: cmd=%s(0x%02X) wait_ms=%" PRIu32 " preamble=%u age_ms=%s", context.try_index,
425 command_name(request.cmd), request.cmd, context.first_response_ms - context.try_start_ms,
426 context.request_preamble, age);
427 response = context.rx;
429 }
430
431 if (!this->handle_authentication_(request, freq, context))
432 continue;
433
435 this->record_debug(outbound_stage_name(context.state), context.try_index, true);
436 auto final_disp = this->wait_for_final_response_(request, context);
438 // The device challenged us, so it demonstrably received the request. It does not follow that
439 // it acted on it: a challenge says nothing about whether our 0x3D answer arrived and
440 // verified, and a device that never got that answer never executes. Silence here therefore
441 // has two causes that look identical from this side — our answer was lost, or the device
442 // replied and this side lost the reply — on top of the devices that simply never close an
443 // exchange with a synchronous reply (see ExchangeOutcome). log_debug_unconfirmed()'s final_rx_*
444 // fields are what separates them after the fact: a reception during the final wait means a
445 // reply came back and was lost on this side.
446 // How many more tries to spend is tries_after_unconfirmed_(): a CMD_EXECUTE may already be
447 // acting on this copy, so it is repeated only where that is harmless and the silence is an
448 // anomaly, and then only once; everything else keeps its full retry budget.
450 this->record_debug("success_auth_unconfirmed", context.try_index, true);
451 unconfirmed_tries++;
452 const uint8_t further_tries = this->tries_after_unconfirmed_(
453 request, unconfirmed_tries, context.try_index, millis() - exchange_begin_ms,
454 this->tx_time_ms_(request, freq, preamble_plan.for_try(context.try_index + 1)));
455 if (further_tries == 0)
457 tries_allowed = std::min<uint8_t>(tries_allowed, tries + 1 + further_tries);
458 continue;
459 }
460
462 this->record_debug("success_auth", context.try_index, true);
463 response = context.rx;
465 }
466
467 // An exchange that authenticated on some try but never got a reply is not the same as one the
468 // device never answered at all: callers that only need "the request landed" can act on it, and
469 // callers that need the payload still cannot.
470 if (unconfirmed_tries > 0)
472 this->spend_wake_evidence_if_silent_(request, preamble_plan);
474}
475
476void ExchangeEngine::spend_wake_evidence_if_silent_(const IoFrame &request, const PreamblePlan &plan) {
477 // Believed moving, yet silent to the short preamble a moving receiver hears and to the wake-up
478 // preamble alike: it has most likely come to rest. Spend the moving evidence so the next exchange
479 // leads with the wake-up preamble instead of losing its first try (or, for a single-try poll, its
480 // only one) to the short preamble again. A challenge means it heard us, so that keeps the evidence.
481 // So does a silent STOP: nothing was stopped, and the receiver may well still be travelling.
482 if (plan.use == WakeBeliefUse::APPLIED && plan.belief == decisions::WakeBelief::AWAKE &&
483 !this->debug_.saw_challenge && !decisions::is_stop_request(request) && this->wake_evidence_spent_handler_) {
484 ESP_LOGD(TAG, "Low-power target %s silent while believed awake: next exchange leads with the wake-up preamble",
485 node_id_to_string(request.dst).c_str());
486 this->wake_evidence_spent_handler_(request.dst);
487 }
488}
489
490// ============================================================================
491// Outbound exchange step helpers
492// ============================================================================
493
494uint16_t ExchangeEngine::request_preamble_for(const IoFrame &request) const {
495 // Gate on the start flag first: several device-role / continuation builders (key transfer,
496 // status-update response) set CTRL1_LOW_POWER on a non-start frame, and those must keep the
497 // short response preamble, not be lengthened.
498 if (!is_start(request))
499 return (*this->radio_ptr_)->response_preamble();
500 return is_low_power_start(request) ? this->tuning_->low_power_wake_preamble : this->tuning_->normal_start_preamble;
501}
502
504 switch (use) {
506 return "override";
508 return "off";
510 return "no_provider";
512 return "applied";
514 default:
515 return "not_low_power";
516 }
517}
518
519ExchangeEngine::PreamblePlan ExchangeEngine::plan_request_preamble_(const IoFrame &request,
520 uint16_t override_preamble) const {
521 PreamblePlan plan;
522 plan.fixed = override_preamble != 0 ? override_preamble : this->request_preamble_for(request);
523 // Every reason not to apply the belief keeps the fixed preamble and is recorded, so the
524 // exchange-failure log names it. The override is the caller's explicit choice (pairing), so it
525 // is never second-guessed. Only a low-power *start* frame has a wake-up preamble to reorder.
526 // The try count is deliberately not a reason: a single-try exchange (most scheduler-owned status
527 // polls) follows the belief's first try like any other. Its likeliest moment is the settle poll
528 // seconds after a command or STOP, when the receiver is travelling or has just answered — the
529 // state in which a moving VELUX solar receiver ignores the wake-up preamble — so a fixed wake-up
530 // preamble there loses the poll and a backoff slot instead of guarding against anything.
531 if (override_preamble != 0) {
532 plan.use = WakeBeliefUse::OVERRIDE;
533 } else if (!is_low_power_start(request)) {
535 } else if (!this->tuning_->low_power_wake_belief) {
537 } else if (!this->target_evidence_provider_) {
539 } else {
540 plan.use = WakeBeliefUse::APPLIED;
541 }
542 if (plan.use != WakeBeliefUse::APPLIED)
543 return plan;
544
545 // A destination the hub has no record of has no evidence: treat it as asleep, the safe default.
546 decisions::TargetEvidence evidence{};
547 const bool known = this->target_evidence_provider_(request.dst, evidence);
548 plan.short_preamble = this->tuning_->normal_start_preamble;
549 plan.wake_preamble = this->tuning_->low_power_wake_preamble;
550 plan.last_seen_ms = known ? evidence.last_seen_ms : 0;
551 plan.belief = known ? decisions::wake_belief(evidence, millis(), decisions::is_stop_request(request))
552 : decisions::WakeBelief::ASLEEP;
553 return plan;
554}
555
556bool ExchangeEngine::transmit_request_(const IoFrame &request, uint32_t freq, uint16_t preamble,
558 if (!this->transmit_frame(request, freq, preamble)) {
560 this->record_debug("tx_request_failed", ctx.try_index, false);
561 return false;
562 }
563 return true;
564}
565
566decisions::ExchangeFirstResponseDisposition ExchangeEngine::wait_for_first_response_(
567 const IoFrame &request, exchange::OutboundExchangeContext &ctx) {
568 ListenSpec spec;
569 spec.window_ms = ctx.wait_ms;
570 // A unicast reply comes back on the channel the request went out on: 0 of 300 unicast RX
571 // events (CHALLENGE_REQ + PRIVATE_RESP, 50 cycles each on SX1276/SX1262/LR1121) arrived off
572 // the request channel. Holding the channel needs no dwell and no hop-after-timeout guard —
573 // there is nowhere else a reply could come from.
575
577 RadioRxPacket packet{};
578 auto outcome = this->listen(spec, packet, ctx.rx, [&](const IoFrame *parsed, const RadioRxPacket &pkt) {
579 if (parsed == nullptr) {
580 this->record_debug("first_parse_fail", ctx.try_index, false);
581 this->counters_.parse_failures++;
582 log_unparsable_frame("Unparsable first response", ctx.try_index, pkt);
583 return ReplyDisposition::IGNORE;
584 }
585 disp = decisions::classify_exchange_first_response(request, *parsed);
587 this->record_debug("first_wrong_exchange", ctx.try_index, false);
588 log_exchange_frame("Ignored first response", ctx.try_index, *parsed, pkt.len);
590 }
591 ctx.first_response_ms = millis();
593 });
594
595 if (outcome == ListenOutcome::ACCEPTED)
596 return disp;
597
599 this->record_debug("wait_first_timeout", ctx.try_index, false);
600 char age[TRY_AGE_BUFFER_SIZE];
601 format_try_age(ctx, age);
602 ESP_LOGI(TAG, "Try %d ended: no first response for cmd=%s(0x%02X) within %" PRIu32 " ms preamble=%u age_ms=%s",
603 ctx.try_index, command_name(request.cmd), request.cmd, ctx.wait_ms, ctx.request_preamble, age);
605}
606
607bool ExchangeEngine::handle_authentication_(const IoFrame &request, uint32_t freq,
608 exchange::OutboundExchangeContext &ctx) {
609 ctx.saw_challenge = true;
610 ctx.state = exchange::OutboundExchangeState::BUILD_AUTH_RESPONSE;
611 this->record_debug(outbound_stage_name(ctx.state), ctx.try_index, true);
612
613 // No challenge bytes here: the raw 0x3C payload plus the 0x3D response it provokes is a
614 // known-plaintext/known-ciphertext pair under the system key (see redaction.h). The generic
615 // frame-log helpers (log_frame()/log_component_capture()) already mask both commands.
616 char age[TRY_AGE_BUFFER_SIZE];
617 format_try_age(ctx, age);
618 ESP_LOGI(TAG, "Auth challenge try=%d wait_ms=%" PRIu32 " req_cmd=0x%02X req_len=%u preamble=%u age_ms=%s",
619 ctx.try_index, ctx.first_response_ms - ctx.try_start_ms, request.cmd, request.data_len, ctx.request_preamble,
620 age);
621
622 ctx.state = exchange::OutboundExchangeState::TX_AUTH_RESPONSE;
623 this->record_debug(outbound_stage_name(ctx.state), ctx.try_index, true);
624 // answer_challenge() covers both the 0x3D build and its transmit as one step, so a failure here
625 // does not distinguish which of the two failed.
626 if (!this->answer_challenge(request, ctx.rx, freq)) {
627 ctx.state = exchange::OutboundExchangeState::FAILED;
628 this->record_debug("auth_response_failed", ctx.try_index, true);
629 return false;
630 }
631 this->counters_.challenge_round_trips++;
632 return true;
633}
634
635bool ExchangeEngine::answer_challenge(const IoFrame &request, const IoFrame &challenge, uint32_t freq) {
636 IoFrame auth_resp;
637 if (!create_challenge_resp(auth_resp, request.dst, this->node_id_, challenge.data, request,
638 this->key_for(request.dst)))
639 return false;
640 return this->transmit_frame(auth_resp, freq, (*this->radio_ptr_)->response_preamble());
641}
642
643uint8_t ExchangeEngine::tries_after_unconfirmed_(const IoFrame &request, uint8_t unconfirmed_tries, uint8_t try_index,
644 uint32_t elapsed_ms, uint32_t next_tx_ms) {
645 // Only an EXECUTE's answer depends on the target, so only an EXECUTE pays for the lookup. A
646 // destination the hub has no record of has never confirmed anything.
647 decisions::TargetEvidence evidence{};
648 if (request.cmd == CMD_EXECUTE && this->target_evidence_provider_)
649 this->target_evidence_provider_(request.dst, evidence);
650 if (!decisions::retry_after_unconfirmed_accept_is_safe(request, evidence.confirms_execute, unconfirmed_tries))
651 return 0;
652 if (request.cmd != CMD_EXECUTE)
653 return EXCHANGE_RETRY_COUNT; // no cap of its own: the exchange's retry count and budget bound it
654 // A re-send whose transmission could not end inside the exchange budget is not worth waiting for.
655 if (!this->try_fits_budget_(elapsed_ms, UNCONFIRMED_EXECUTE_RESEND_DELAY_MS, next_tx_ms))
656 return 0;
657 // The re-send may well succeed, and then no exchange-failure or unconfirmed line is printed at
658 // all, so this is the one record that the first copy's reply went missing.
659 ESP_LOGI(TAG,
660 "Try %u accepted without a closing reply for cmd=%s(0x%02X): re-sending, the device normally "
661 "confirms (final_rx_ignored=%u final_rx_failed=%u)",
662 try_index, command_name(request.cmd), request.cmd, this->debug_.final_rx_ignored,
663 this->debug_.final_rx_failed);
664 // Stretch the ordinary retry gap the loop is about to wait to the longer re-send gap, so a device
665 // still busy acting on the first copy has finished before the re-send reaches it.
666 App.feed_wdt();
667 delay(UNCONFIRMED_EXECUTE_RESEND_DELAY_MS - EXCHANGE_RETRY_DELAY_MS);
668 // The re-send is the only further copy of a CMD_EXECUTE: if it goes unanswered altogether, the
669 // ordinary failure retry must not add a third one to a device that already has the command.
670 return UNCONFIRMED_EXECUTE_MAX_RESENDS;
671}
672
673decisions::ExchangeFinalResponseDisposition ExchangeEngine::wait_for_final_response_(
674 const IoFrame &request, exchange::OutboundExchangeContext &ctx) {
675 // Same budget as any other continuation frame — RESPONSE_AUTH_WAIT_MS was always an alias for
676 // RESPONSE_WAIT_MS, so the two share one knob rather than inventing a third.
677 const uint32_t auth_wait_ms = this->tuning_->exchange_response_wait_ms;
678
679 ListenSpec spec;
680 spec.window_ms = auth_wait_ms;
681 // Same reasoning as wait_for_first_response_(): a unicast reply comes back on the request
682 // channel (0 of 300 unicast RX events measured off-channel across all three chips), so holding
683 // the channel for the whole wait is strictly correct and needs no dwell.
684 spec.policy = ListenPolicy::HOLD_REQUEST_CHANNEL;
685
686 ListenStats stats;
687 spec.stats = &stats;
688
689 RadioRxPacket packet{};
690 auto outcome = this->listen(spec, packet, ctx.rx, [&](const IoFrame *parsed, const RadioRxPacket &pkt) {
691 if (parsed == nullptr) {
692 this->record_debug("final_parse_fail", ctx.try_index, true);
693 this->counters_.parse_failures++;
694 log_unparsable_frame("Unparsable final response", ctx.try_index, pkt);
695 return ReplyDisposition::IGNORE;
696 }
697 if (is_valid_final_response(*parsed, request))
698 return ReplyDisposition::ACCEPT;
699 this->record_debug("final_wrong_exchange", ctx.try_index, true);
700 log_exchange_frame("Ignored final response", ctx.try_index, *parsed, pkt.len);
701 return ReplyDisposition::IGNORE;
702 });
703
704 this->note_final_wait_(stats);
705 if (outcome == ListenOutcome::ACCEPTED)
706 return decisions::ExchangeFinalResponseDisposition::ACCEPT;
707
708 ctx.state = exchange::OutboundExchangeState::FAILED;
709 this->record_debug("wait_final_timeout", ctx.try_index, true);
710 ESP_LOGI(TAG, "Try %d ended: no matching final response for cmd=%s(0x%02X) within %" PRIu32 " ms", ctx.try_index,
711 command_name(request.cmd), request.cmd, auth_wait_ms);
712 return decisions::ExchangeFinalResponseDisposition::IGNORE_UNRELATED;
713}
714
715// ============================================================================
716// Broadcast roll-call
717// ============================================================================
718
719uint8_t ExchangeEngine::collect_broadcast_responses(const IoFrame &request, uint32_t freq, uint8_t expected_cmd,
720 uint32_t window_ms, const BroadcastReplyHandler &on_reply,
721 ListenPolicy policy) {
722 this->reset_debug(request.cmd);
723
724 if (!this->transmit_frame(request, freq, this->request_preamble_for(request))) {
725 this->record_debug("broadcast_tx_failed", 1, false);
726 return 0;
727 }
728 const uint32_t tx_done_ms = millis();
729
730 RadioDriver *radio = *this->radio_ptr_;
731 uint8_t count = 0;
732
733 ListenSpec spec;
734 spec.window_ms = window_ms;
735 // policy is the caller's choice: ROTATE_SKIPPING_REQUEST (the default) leaves the request
736 // channel unattended because so few replies land there for that caller's population; a caller
737 // whose replies do land there passes ROTATE_ALL_CHANNELS instead. request_freq is set
738 // unconditionally — harmless for ROTATE_ALL_CHANNELS, which never reads it.
739 spec.policy = policy;
740 spec.request_freq = freq;
741 // dwell_ms is left at 0: no measured reason to dwell differently from discovery, so listen()
742 // asks the driver via hop_dwell_ms() instead of hardcoding a value here.
743 // A reception proves this channel carries responders and replies arrive spread across the whole
744 // window, so staying on it costs nothing; hopping away would only shrink the time spent where
745 // responders already are.
746 spec.hop_after_ignored_frame = false;
747 spec.linger_on_preamble = true;
748 spec.linger_dwell_ms = PREAMBLE_LINGER_DWELL_MS;
749
750 RadioRxPacket packet{};
751 IoFrame frame{};
752 this->listen(spec, packet, frame, [&](const IoFrame *parsed, const RadioRxPacket &pkt) {
753 if (parsed == nullptr || parsed->cmd != expected_cmd || memcmp(parsed->dst, this->node_id_, NODE_ID_SIZE) != 0)
755
756 BroadcastReplyInfo info{};
757 info.rssi_dbm = radio->get_last_capture().rssi_dbm;
758 info.rx_freq_hz = pkt.freq_hz;
759 info.after_tx_ms = millis() - tx_done_ms;
760 on_reply(*parsed, info);
761 if (count < UINT8_MAX)
762 ++count;
763 // Collection always runs to the deadline: a roll-call has no single "the" reply, so nothing
764 // this loop can see is ever a reason to stop early.
766 });
767
768 this->record_debug("broadcast_collect_done", 1, false);
769 return count;
770}
771
772// ============================================================================
773// Shared listen primitive
774//
775// The one listen loop every radio wait in this project runs through: send_and_receive()'s
776// first/final-response waits, collect_broadcast_responses(), and PairingEngine's discovery/
777// key-transfer/key-confirm waits all call listen() below with a ListenSpec that picks one of
778// the three ListenPolicy values (hold the request channel, rotate all three, or rotate skipping
779// the request channel). Per-loop behavior — what counts as a match, what aborts, what gets
780// logged — lives entirely in the caller's ReplyHandler; this function owns only the
781// slice/hop/deadline mechanics common to all of them.
782// ============================================================================
783
784namespace {
785
786/// Count one event in a ListenStats field without wrapping past 255.
787void count_saturating(uint8_t &counter) {
788 if (counter < UINT8_MAX)
789 counter++;
790}
791
792/// Parse one received packet, hand it to `on_frame`, and translate an ACCEPT/ABORT disposition
793/// into `outcome`; a frame the handler ignores is counted in `stats` when the caller asked for
794/// counts. Factored out of listen()'s two reception sites to keep that function's cognitive
795/// complexity under the clang-tidy threshold.
796/// @return true if the listen should stop (ACCEPT or ABORT was returned); false to keep waiting.
797bool dispatch_received_packet(const ReplyHandler &on_frame, const RadioRxPacket &packet, IoFrame &frame,
798 ListenOutcome &outcome, ListenStats *stats) {
799 const bool parsed = parse(packet.data, packet.len, frame);
800 switch (on_frame(parsed ? &frame : nullptr, packet)) {
801 case ReplyDisposition::ACCEPT:
802 outcome = ListenOutcome::ACCEPTED;
803 return true;
804 case ReplyDisposition::ABORT:
805 outcome = ListenOutcome::ABORTED;
806 return true;
807 case ReplyDisposition::IGNORE:
808 break;
809 }
810 if (stats != nullptr)
811 count_saturating(stats->frames_ignored);
812 return false;
813}
814
815/// Record a holding listen's failed reception. Called at the moment it happens, because the re-arm
816/// that follows clears the radio capture that describes it.
817void count_failed_reception(ListenStats *stats, const RadioDriver *radio) {
818 if (stats == nullptr)
819 return;
820 count_saturating(stats->failed_receptions);
821 stats->last_failed_irq = radio->get_last_capture().irq_status;
822}
823
824/// A frame is arriving: hopping now would cut it off mid-reception. Both halves are live on every
825/// current chip.
826bool preamble_or_sync_incoming(RadioDriver *radio, const ListenSpec &spec) {
827 return spec.linger_on_preamble && (radio->is_preamble_detected() || radio->is_sync_detected());
828}
829
830/// Per-channel dwell for a rotating listen: `spec.dwell_ms` if the caller set one, otherwise the
831/// driver's own answer to "how long must this radio sit on a channel after retuning before it can
832/// hear anything at all" (see RadioDriver::hop_dwell_ms()). Unused (returns 0) for a holding
833/// listen — HOLD never slices, so it never asks. Factored out of listen() purely to avoid a
834/// nested conditional operator and keep that function's cognitive complexity under the clang-tidy
835/// threshold — no behavior beyond the two-way fallback.
836uint32_t resolve_dwell_ms(const ListenSpec &spec, bool rotating, RadioDriver *radio, const TuningConfig &tuning) {
837 if (!rotating)
838 return 0;
839 if (spec.dwell_ms != 0)
840 return spec.dwell_ms;
841 return radio->hop_dwell_ms(tuning);
842}
843
844} // namespace
845
846void ExchangeEngine::listen_hop_(uint32_t skip, const ListenSpec &spec) {
847 this->hop_frequency(skip);
848 if (spec.on_hop)
849 spec.on_hop();
850}
851
853 const ReplyHandler &on_frame) {
854 RadioDriver *radio = *this->radio_ptr_;
855 const uint32_t deadline = millis() + spec.window_ms;
856 const bool rotating = spec.policy != ListenPolicy::HOLD_REQUEST_CHANNEL;
857 const uint32_t skip = spec.policy == ListenPolicy::ROTATE_SKIPPING_REQUEST ? spec.request_freq : 0;
858 // 0 means "ask the driver": no rotating call site in this project has a measured reason to
859 // dwell differently from the chip's own retune-cost answer (RadioDriver::hop_dwell_ms()), so
860 // all of them leave spec.dwell_ms at 0 and share one chip-specific knob instead of inventing a
861 // second.
862 const uint32_t dwell = resolve_dwell_ms(spec, rotating, radio, *this->tuning_);
863
864 // A skipping listen's replies almost never return on the requesting channel (see ListenPolicy's
865 // own doc comment for why), so it leaves that channel before its first dwell rather than
866 // spending one there.
868 this->listen_hop_(skip, spec);
869
870 while ((int32_t) (deadline - millis()) > 0) {
871 const uint32_t remaining = deadline - millis();
872 // A holding listen waits the whole remaining window in one call: it has nothing to do between
873 // slices, wait_for_packet() feeds the watchdog while it blocks, and every expired slice costs
874 // an RX re-arm. Only a rotating listen needs a per-channel dwell.
875 const uint32_t slice = rotating ? std::min(remaining, dwell) : remaining;
876
877 if (radio->wait_for_packet(packet, slice)) {
879 if (dispatch_received_packet(on_frame, packet, frame, outcome, spec.stats))
880 return outcome;
881 // The roll-call leaves this false because a reception proves responders are on this
882 // channel (see the field doc in hub_exchange.h); discovery is the only listen that hops
883 // after an ignored frame.
884 if (rotating && spec.hop_after_ignored_frame && (int32_t) (deadline - millis()) > 0 &&
885 !preamble_or_sync_incoming(radio, spec))
886 this->listen_hop_(skip, spec);
887 continue;
888 }
889
890 if ((int32_t) (deadline - millis()) <= 0)
891 break;
892 if (!rotating) {
893 count_failed_reception(spec.stats, radio); // HOLD: an early false is a failed reception, not a timeout.
894 continue;
895 }
896 if (!preamble_or_sync_incoming(radio, spec)) {
897 this->listen_hop_(skip, spec);
898 continue;
899 }
900 // Preamble/sync seen at the dwell boundary: extend by linger_dwell_ms and give the frame its
901 // air time instead of hopping — a short extension wait, not another full per-channel dwell.
902 const uint32_t ext = std::min((uint32_t) (deadline - millis()), spec.linger_dwell_ms);
904 if (radio->wait_for_packet(packet, ext) && dispatch_received_packet(on_frame, packet, frame, outcome, spec.stats))
905 return outcome;
906 }
908}
909
910// ============================================================================
911// Inbound authentication
912// ============================================================================
913
914bool ExchangeEngine::authenticate_request(const IoFrame &request, uint32_t freq) {
915 return this->authenticate_request(request, freq, this->key_for(request.src));
916}
917
918const uint8_t *ExchangeEngine::key_for(const uint8_t *node) const {
919 if (this->device_key_provider_) {
920 if (const uint8_t *device_key = this->device_key_provider_(node); device_key != nullptr)
921 return device_key;
922 }
923 return this->system_key_;
924}
925
926bool ExchangeEngine::authenticate_request(const IoFrame &request, uint32_t freq, const uint8_t *key) {
927 return this->challenge_sender(request, freq, key) == ChallengeResult::VERIFIED;
928}
929
931 const uint8_t *key) {
932 RadioDriver *radio = *this->radio_ptr_;
935 this->record_debug(inbound_stage_name(context.state), 1, true);
936
937 if (!create_challenge_req(context.challenge, request.src, this->node_id_)) {
939 this->record_debug(inbound_stage_name(context.state), 1, true);
941 }
942 if (!this->transmit_frame(context.challenge, freq, radio->response_preamble())) {
944 this->record_debug(inbound_stage_name(context.state), 1, true);
946 }
947
949 this->record_debug(inbound_stage_name(context.state), 1, true);
950
951 RadioRxPacket packet{};
952 if (!radio->wait_for_packet(packet, this->tuning_->exchange_response_wait_ms)) {
954 this->record_debug(inbound_stage_name(context.state), 1, true);
956 }
957
958 // Transcript is the *device's* own frame (cmd + data), not our challenge — the challenged
959 // party authenticates what it said. Confirmed against real hardware bytes by the device-side
960 // 0x3D in tests/corpus/captures/pairing/velux_kux100_pairing_full.yaml.
961 // Anything but a 0x3D counts as no answer; a 0x3D that does not verify is a wrong one.
962 IoFrame rx;
963 if (!parse(packet.data, packet.len, rx) || !frame_is_challenge_response(rx) || rx.data_len < HMAC_SIZE) {
965 this->record_debug(inbound_stage_name(context.state), 1, true);
967 }
968 if (!verify_challenge_resp(request, context.challenge.data, rx.data, key)) {
970 this->record_debug(inbound_stage_name(context.state), 1, true);
972 }
973
975 this->record_debug(inbound_stage_name(context.state), 1, true);
976 this->counters_.challenge_round_trips++;
978}
979
980} // namespace home_io_control
981} // namespace esphome
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.
ChallengeResult
What one challenge (our 0x3C, the device's 0x3D) came to.
@ MISMATCH
A 0x3D came back, but it does not verify under the key.
@ VERIFIED
The device's 0x3D verified under the key.
@ NO_ANSWER
Our 0x3C could not be sent, or no 0x3D came back within the response window.
WakeBeliefUse
Whether an exchange's start preamble followed the low-power wake belief, and if not,...
@ OVERRIDE
The caller forced a preamble (pairing's directed frames).
@ SWITCHED_OFF
The low_power_wake_belief tuning switch is off.
@ NO_PROVIDER
No evidence source installed (set_target_evidence_provider()).
@ NOT_LOW_POWER
Not a low-power start frame: there is no wake-up preamble to reorder.
@ APPLIED
The tries followed the belief in DebugInfo::wake_belief.
uint8_t collect_broadcast_responses(const IoFrame &request, uint32_t freq, uint8_t expected_cmd, uint32_t window_ms, const BroadcastReplyHandler &on_reply, ListenPolicy policy=ListenPolicy::ROTATE_SKIPPING_REQUEST)
Transmit request once and hand every matching broadcast reply to on_reply within window_ms.
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.
void log_debug_unconfirmed(const char *device_id) const
Log the debug snapshot for an exchange that ended accepted-but-unconfirmed, at INFO.
void log_debug(const char *device_id) const
Log the debug snapshot as a WARN-level structured line.
const uint8_t * key_for(const uint8_t *node) const
The key an exchange with node uses: the device's own key when the provider has one,...
ChallengeResult challenge_sender(const IoFrame &request, uint32_t freq, const uint8_t *key)
One challenge of request's sender under key, telling a lost answer from a wrong one.
std::function< void(const IoFrame &frame, const BroadcastReplyInfo &info)> BroadcastReplyHandler
Invoked for each matching broadcast reply, as it arrives.
uint16_t request_preamble_for(const IoFrame &request) const
Preamble length for an outbound request frame.
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...
static const char * wake_belief_use_name(WakeBeliefUse use)
Log label for a WakeBeliefUse that is not APPLIED (an applied one logs the belief itself).
bool answer_challenge(const IoFrame &request, const IoFrame &challenge, uint32_t freq)
Send a 0x3D challenge response over request's transcript, proving knowledge of the system key to whoe...
bool transmit_frame(const IoFrame &frame, uint32_t freq, uint16_t preamble)
Transmit a raw IoFrame with the given preamble length.
bool authenticate_request(const IoFrame &request, uint32_t freq)
Authenticate an inbound device command via 0x3C challenge / 0x3D HMAC.
ExchangeOutcome send_and_receive(const IoFrame &request, IoFrame &response, uint32_t freq, uint8_t max_tries=EXCHANGE_RETRY_COUNT, uint16_t request_preamble_override=0)
Execute an outbound authenticated exchange with retry.
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 uint16_t response_preamble() const
Return the preamble length for response/continuation frames.
virtual void change_frequency(uint32_t freq_hz)=0
Change the carrier frequency using fast hop (no standby transition needed).
virtual TxResult 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.
const RadioCaptureInfo & get_last_capture() const
Get the most recent radio capture info.
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.
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.
bool is_stop_request(const IoFrame &request)
True for a CMD_EXECUTE whose main byte is POS_STOP.
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.
const char * wake_belief_name(WakeBelief belief)
Lowercase name of a belief for log lines.
WakeBelief
Whether a low-power receiver is believed to be travelling right now, judged from what this hub has se...
@ ASLEEP
Not known to be moving — lead with the wake-up preamble.
@ AWAKE
Moving, or about to be stopped — the short preamble is the one it hears.
WakeBelief wake_belief(const TargetEvidence &evidence, uint32_t now, bool is_stop)
Judge whether a low-power receiver is travelling.
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.
@ 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 const char * TAG
bool verify_challenge_resp(const IoFrame &origin, const uint8_t challenge[HMAC_SIZE], const uint8_t mac[HMAC_SIZE], const uint8_t *key)
Check a device's 0x3D for origin, in constant time (crypto::verify_hmac()).
bool is_start(const IoFrame &f)
Check START flag.
int render_exchange_debug(char *buf, size_t buf_size, const char *device_id, const ExchangeEngine::DebugInfo &d)
Render the structured field list shared by both exchange-debug log lines.
const char * command_name(uint8_t cmd)
Get a human-readable name for any IO-Homecontrol command ID.
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.
@ 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.
constexpr TxWake tx_wake_for(bool start, uint16_t preamble)
The wake-up level of a frame, from the two facts that decide it: whether it starts an exchange (a con...
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 ...
Definition log_frame.h:71
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.
Definition log_frame.h:19
ListenPolicy
Which channels a listen covers.
@ ROTATE_SKIPPING_REQUEST
The two channels that are not the request channel.
@ 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).
std::string node_id_to_string(const uint8_t id[NODE_ID_SIZE])
Format a 3‑byte node ID as a 6‑character uppercase hex string.
ListenOutcome
How one call to ExchangeEngine::listen() ended.
@ ACCEPTED
The handler returned ReplyDisposition::ACCEPT for some received frame.
@ TIMED_OUT
spec.window_ms elapsed with no ACCEPT/ABORT.
static constexpr uint32_t US_PER_MS
Microseconds per millisecond, for rounding a driver's transmit-time estimate up to whole ms.
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.
uint8_t serialize(const IoFrame &f, uint8_t *buf, uint8_t buf_size)
Serialize a parsed frame into a wire buffer (without CRC).
static const char *const TAG
Command builders for the IO‑Homecontrol protocol.
IO-Homecontrol command IDs, result codes and protocol enumerations.
Cryptographic helpers for the IO‑Homecontrol protocol.
Per-reply facts collect_broadcast_responses() hands its caller alongside the frame.
uint32_t rx_freq_hz
Channel the reply was received on (RadioRxPacket::freq_hz).
int16_t rssi_dbm
RSSI of this reply (from the radio's last capture).
uint32_t after_tx_ms
Milliseconds from the request's transmit completing to this reply's delivery.
Snapshot of the last exchange attempt for diagnostics.
bool saw_challenge
True if a 0x3C was seen during this exchange.
uint16_t final_rx_irq
Radio IRQ status at the most recent of those failed receptions.
uint8_t capture_reported_len
Length reported by radio packet engine.
int16_t capture_rssi_dbm
RSSI of the captured packet (dBm).
bool capture_crc_error
True if CRC error flagged; see RadioCaptureInfo::crc_error.
uint8_t capture_frame_len
Parsed protocol frame length.
decisions::WakeBelief wake_belief
Belief the tries followed; only meaningful when wake_belief_use is WakeBeliefUse::APPLIED.
uint8_t capture_packet_status
Chip packet-status byte.
uint8_t final_rx_ignored
Frames received during those waits and not accepted as the reply.
bool capture_valid
True if radio capture is meaningful.
uint8_t request_cmd
Command ID of the original request.
uint16_t last_try_preamble
Preamble (bytes) of the most recent request transmit attempt, 0 = none.
WakeBeliefUse wake_belief_use
Whether the tries followed wake_belief, and why not if they did not.
uint8_t final_rx_failed
Receptions started during those waits that could not be decoded.
const char * stage
Last recorded stage label.
uint32_t capture_freq_hz
RF frequency of the captured packet.
uint8_t max_tries
Attempt cap this exchange was budgeted for.
uint8_t final_waits
Final-reply waits run (one per try that got as far as our 0x3D).
Parsed IO‑Homecontrol frame (CTRL0/1 + addresses + command + data).
Definition proto_frame.h:93
uint8_t data[FRAME_MAX_DATA_SIZE]
Command parameters (0–23 bytes). Never includes mac.
Definition proto_frame.h:99
uint8_t src[NODE_ID_SIZE]
Source node ID (3 bytes).
Definition proto_frame.h:97
uint8_t dst[NODE_ID_SIZE]
Destination node ID (3 bytes).
Definition proto_frame.h:96
uint8_t data_len
Actual length of data.
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.
ListenStats * stats
Where to count what this listen heard without accepting it; null (the default) counts nothing.
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.
What a listen heard without accepting it — filled by ExchangeEngine::listen() when a caller passes on...
uint16_t last_failed_irq
Radio IRQ status captured at the most recent failed reception.
uint8_t frames_ignored
Frames the radio delivered that the handler did not accept (wrong exchange, unrelated traffic,...
uint8_t failed_receptions
Receptions the radio started but could not deliver: a holding listen's early return before its deadli...
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.
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.
uint32_t freq_hz
Frequency the packet was received on (Hz).
uint8_t data[RADIO_PACKET_BUFFER_SIZE]
Raw packet data buffer.
Configuration for transmitting a packet: carrier frequency, preamble length, wake-up level and clear-...
uint16_t preamble_len
Preamble length in symbol periods (bytes).
uint32_t freq_hz
Carrier frequency in Hz.
std::optional< int16_t > cca_threshold_dbm
If set, send only if the energy on freq_hz, measured right before the first transmitted symbol,...
TxWake wake
Wake-up level the receiver needs (tx_wake_for()).
All runtime tunable parameters for pairing and radio diagnostics.
uint16_t exchange_total_budget_ms
Ceiling on one whole exchange, retries included.
bool low_power_wake_belief
Order a low_power device's start-frame tries by its wake belief (short preamble first when it is beli...
What send_packet() did with a frame.
@ CHANNEL_BUSY
The clear-channel check found the channel busy; nothing was sent.
int16_t cca_level_dbm
The level the clear-channel check measured; set with CHANNEL_BUSY.
What the hub knows about the device an exchange is addressed to, as the exchange engine sees it.
bool confirms_execute
The device has closed a CMD_EXECUTE exchange with a reply before.
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.
uint32_t first_response_ms
Timestamp when the first valid response arrived (for RTT/timing).
uint16_t request_preamble
Start preamble (bytes) this try's request went out with.
uint8_t try_index
Current retry attempt (1‑based within EXCHANGE_RETRY_COUNT).
uint32_t try_start_ms
millis() when this try's request transmit began, after any retry gap.
IoFrame rx
Most recent candidate frame received during the exchange.
uint32_t wait_ms
Current timeout window for the active wait (ms).
OutboundExchangeState state
Current state machine state.
uint32_t target_last_seen_ms
When the target was last heard (millis), 0 = unknown; logged as the try's age_ms= so field logs can r...