16#include "esphome/core/application.h"
17#include "esphome/core/hal.h"
18#include "esphome/core/log.h"
28static const char *
const TAG =
"home_io_control.exchange";
39 : radio_ptr_(radio_ptr), node_id_(node_id), system_key_(system_key), tuning_(tuning) {}
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));
55 add(d.final_waits, 1);
63 this->debug_.stage = stage;
64 this->debug_.tries = tries;
65 this->debug_.saw_challenge = this->debug_.saw_challenge || saw_challenge;
77 if (!capture.
valid && this->debug_.capture_valid)
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;
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;
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",
109 char fields[EXCHANGE_DEBUG_LINE_SIZE];
111 ESP_LOGW(
TAG,
"Exchange failed: %s", fields);
115 char fields[EXCHANGE_DEBUG_LINE_SIZE];
122 ESP_LOGI(
TAG,
"Exchange accepted without a closing reply: %s", fields);
148 }
while (next == skip_freq);
150 this->last_hop_us_ = micros();
154 if ((micros() - this->last_hop_us_) <= HOP_TIME_US)
161 if ((*this->radio_ptr_)->reception_in_progress())
190 uint8_t buf[FRAME_MAX_WIRE_SIZE];
191 uint8_t
const len =
serialize(frame, buf,
sizeof(buf));
193 ESP_LOGW(
TAG,
"tx: serialize_failed cmd=0x%02X", frame.
cmd);
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);
206 for (uint8_t lbt = 0;; lbt++) {
207 if (lbt < lbt_checks) {
215 ESP_LOGD(
TAG,
"LBT: channel busy (RSSI %d dBm on %" PRIu32
" Hz), retry %u/%u", result.
cca_level_dbm, freq, lbt + 1,
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);
222 if (!result.
sent()) {
223 ESP_LOGW(
TAG,
"tx: send_failed cmd=0x%02X", frame.
cmd);
226 if (this->transmit_observer_ !=
nullptr)
227 this->transmit_observer_->on_transmit(frame, tx_config, len);
231uint32_t ExchangeEngine::final_reply_tail_ms_(
const IoFrame &request, uint32_t freq)
const {
235 this->
tx_time_ms(request, freq, (*this->radio_ptr_)->response_preamble()) + EXCHANGE_ATTEMPT_OVERHEAD_MS;
239 uint8_t buf[FRAME_MAX_WIRE_SIZE];
240 uint8_t
const len =
serialize(frame, buf,
sizeof(buf));
243 uint32_t
const tx_us = (*this->radio_ptr_)->tx_air_time_us(len, tx_config_for(frame, freq, preamble));
248 uint16_t request_preamble_override,
bool state_unknown)
const {
249 const bool low_power = (request.
ctrl1 & CTRL1_LOW_POWER) != 0;
252 std::optional<uint32_t> short_lead_tx_ms;
254 const PreamblePlan preamble_plan = this->plan_request_preamble_(request, request_preamble_override, state_unknown);
256 short_lead_tx_ms = this->
tx_time_ms(request, freq, preamble_plan.short_preamble);
265 uint32_t freq, uint16_t preamble, uint16_t last_window_ms,
266 std::optional<uint32_t> short_lead_tx_ms)
const {
268 last_window_ms, short_lead_tx_ms);
271bool ExchangeEngine::try_fits_budget_(uint32_t elapsed_ms, uint32_t gap_ms, uint32_t tx_ms, uint32_t window_ms,
272 uint32_t auth_tail_ms, uint32_t allowance_ms)
const {
295 return "wait_first_response";
297 return "build_auth_response";
299 return "tx_auth_response";
301 return "wait_final_response";
316 return "tx_challenge";
318 return "wait_challenge_response";
328bool frame_is_challenge_response(
const IoFrame &frame) {
return frame.cmd == CMD_CHALLENGE_RESP; }
336void log_unparsable_frame(
const char *stage,
int tries,
const RadioRxPacket &packet) {
341 ESP_LOGW(
TAG,
"%s try=%d: %u bytes did not parse as a frame on %" PRIu32
" Hz", stage, tries, packet.len,
343#ifdef IOHOME_FRAME_LOG
346 ESP_LOGD(
TAG,
" raw: %s", hex);
351void log_exchange_frame(
const char *stage,
int tries,
const IoFrame &frame, uint8_t len) {
352 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],
353 frame.src[1], frame.src[2], frame.dst[0], frame.dst[1], frame.dst[2], len);
357constexpr size_t TRY_AGE_BUFFER_SIZE = 12;
366 if (ctx.target_last_seen_ms == 0) {
367 snprintf(buf,
sizeof(buf),
"n/a");
370 snprintf(buf,
sizeof(buf),
"%" PRIu32, ctx.try_start_ms - ctx.target_last_seen_ms);
375bool is_low_power_start(
const IoFrame &request) {
return is_start(request) && (request.ctrl1 & CTRL1_LOW_POWER) != 0; }
378bool is_valid_final_response(
const IoFrame &candidate,
const IoFrame &request) {
387uint32_t auth_tail_after_unconfirmed(
const IoFrame &request, uint32_t final_window_ms) {
388 return request.cmd == CMD_EXECUTE ? 0 : final_window_ms;
394 uint8_t max_tries, uint16_t request_preamble_override) {
397 const uint16_t window_ms =
398 is_start(request) ? this->tuning_->exchange_start_response_wait_ms : this->tuning_->exchange_response_wait_ms;
400 request_preamble_override);
405 uint16_t request_preamble_override) {
413 (*this->radio_ptr_)->clear_last_capture();
415 uint8_t tries_allowed = std::max<uint8_t>(1, std::min<uint8_t>(plan.
max_attempts, EXCHANGE_MAX_ATTEMPTS));
416 this->debug_.max_tries = tries_allowed;
417 const PreamblePlan preamble_plan =
418 this->plan_request_preamble_(request, request_preamble_override, plan.
state_unknown);
419 this->debug_.wake_belief_use = preamble_plan.use;
421 this->debug_.wake_belief = preamble_plan.belief;
427 const uint32_t exchange_begin_ms = millis();
428 uint8_t unconfirmed_tries = 0;
429 uint32_t auth_tail_ms = 0;
431 for (uint8_t tries = 0; tries < tries_allowed; tries++) {
445 if (!this->try_fits_budget_(
446 millis() - exchange_begin_ms, plan.
gap_ms,
447 this->tx_time_ms(request, freq, this->try_preamble_(plan, preamble_plan, context.
try_index)), window_ms,
449 this->
record_debug(
"retry_budget_exhausted", tries,
false);
450 ESP_LOGI(
TAG,
"Exchange budget exhausted after %u tries for cmd=%s(0x%02X) (%" PRIu32
" of %u ms)", tries,
452 this->tuning_->exchange_total_budget_ms);
457 this->counters_.retransmits++;
466 if (!this->transmit_request_(request, freq, context.
request_preamble, context))
471 auto first_disp = this->wait_for_first_response_(request, context);
479 char age[TRY_AGE_BUFFER_SIZE];
480 format_try_age(context, age);
481 ESP_LOGI(
TAG,
"Try %d answered: cmd=%s(0x%02X) wait_ms=%" PRIu32
" preamble=%u age_ms=%s", context.
try_index,
484 response = context.
rx;
488 auth_tail_ms = this->final_reply_tail_ms_(request, freq);
489 if (!this->handle_authentication_(request, freq, context))
494 auto final_disp = this->wait_for_final_response_(request, context);
511 const uint8_t further_tries = this->tries_after_unconfirmed_(
512 request, unconfirmed_tries, context.
try_index,
static_cast<uint8_t
>(tries_allowed - context.
try_index),
513 millis() - exchange_begin_ms,
514 this->
tx_time_ms(request, freq, this->try_preamble_(plan, preamble_plan, context.
try_index + 1)), plan);
515 if (further_tries == 0)
517 auth_tail_ms = auth_tail_after_unconfirmed(request, auth_tail_ms);
518 tries_allowed = std::min<uint8_t>(tries_allowed, tries + 1 + further_tries);
524 response = context.
rx;
531 if (unconfirmed_tries > 0)
533 this->spend_wake_evidence_if_silent_(request, preamble_plan);
537uint16_t ExchangeEngine::try_preamble_(
const decisions::AttemptPlan &plan,
const PreamblePlan &preamble_plan,
538 uint8_t try_index)
const {
543 return preamble_plan.for_try(try_index);
546void ExchangeEngine::spend_wake_evidence_if_silent_(
const IoFrame &request,
const PreamblePlan &plan) {
557 !this->still_travelling_by_its_own_count_(request)) {
558 ESP_LOGD(
TAG,
"Low-power target %s silent while believed awake: next exchange leads with the wake-up preamble",
560 this->wake_evidence_spent_handler_(request.dst);
564bool ExchangeEngine::still_travelling_by_its_own_count_(
const IoFrame &request)
const {
565 decisions::TargetEvidence evidence{};
566 return this->target_evidence_provider_ && this->target_evidence_provider_(request.dst, evidence) &&
579 return (*this->radio_ptr_)->response_preamble();
580 return is_low_power_start(request) ? this->tuning_->low_power_wake_preamble : this->tuning_->normal_start_preamble;
590 return "no_provider";
595 return "not_low_power";
599ExchangeEngine::PreamblePlan ExchangeEngine::plan_request_preamble_(
const IoFrame &request, uint16_t override_preamble,
600 bool state_unknown)
const {
611 if (override_preamble != 0) {
613 }
else if (!is_low_power_start(request)) {
617 }
else if (!this->target_evidence_provider_) {
626 decisions::TargetEvidence evidence{};
627 const bool known = this->target_evidence_provider_(request.
dst, evidence);
628 plan.short_preamble = this->tuning_->normal_start_preamble;
629 plan.wake_preamble = this->tuning_->low_power_wake_preamble;
630 plan.last_seen_ms = known ? evidence.last_seen_ms : 0;
632 request.
cmd == CMD_PRIVATE, state_unknown)
637bool ExchangeEngine::transmit_request_(
const IoFrame &request, uint32_t freq, uint16_t preamble,
641 this->
record_debug(
"tx_request_failed", ctx.try_index,
false);
650 spec.window_ms = ctx.wait_ms;
658 RadioRxPacket packet{};
665 auto outcome = this->
listen(spec, packet, ctx.rx, [&](
const IoFrame *parsed,
const RadioRxPacket &pkt) {
666 if (parsed == nullptr) {
668 this->record_debug(
"first_parse_fail", ctx.try_index, false);
669 this->counters_.parse_failures++;
670 log_unparsable_frame(
"Unparsable first response", ctx.try_index, pkt);
671 return ReplyDisposition::IGNORE;
676 this->
record_debug(
"first_wrong_exchange", ctx.try_index,
false);
677 log_exchange_frame(
"Ignored first response", ctx.try_index, *parsed, pkt.len);
680 ctx.first_response_ms = millis();
681 ctx.first_response_us = micros();
693 this->record_debug(
"wait_first_timeout", ctx.try_index,
false);
694 char age[TRY_AGE_BUFFER_SIZE];
695 format_try_age(ctx, age);
696 ESP_LOGI(
TAG,
"Try %d ended: no first response for cmd=%s(0x%02X) within %" PRIu32
" ms preamble=%u age_ms=%s",
697 ctx.try_index,
command_name(request.cmd), request.cmd, ctx.wait_ms, ctx.request_preamble, age);
701bool ExchangeEngine::handle_authentication_(
const IoFrame &request, uint32_t freq,
702 exchange::OutboundExchangeContext &ctx) {
703 ctx.saw_challenge =
true;
704 ctx.state = exchange::OutboundExchangeState::BUILD_AUTH_RESPONSE;
705 this->record_debug(outbound_stage_name(ctx.state), ctx.try_index,
true);
710 ctx.state = exchange::OutboundExchangeState::TX_AUTH_RESPONSE;
711 this->record_debug(outbound_stage_name(ctx.state), ctx.try_index,
true);
717 const bool answered = this->answer_challenge(request, ctx.rx, freq);
718 const uint32_t answer_us = micros() - ctx.first_response_us;
722 char age[TRY_AGE_BUFFER_SIZE];
723 format_try_age(ctx, age);
727 "Auth challenge try=%d wait_ms=%" PRIu32
728 " req_cmd=0x%02X req_len=%u preamble=%u age_ms=%s answer_us=%" PRIu32,
729 ctx.try_index, ctx.first_response_ms - ctx.try_start_ms, request.cmd, request.data_len, ctx.request_preamble,
733 ctx.state = exchange::OutboundExchangeState::FAILED;
734 this->record_debug(
"auth_response_failed", ctx.try_index,
true);
737 this->counters_.challenge_round_trips++;
744 this->key_for(request.
dst)))
746 return this->
transmit_frame(auth_resp, freq, (*this->radio_ptr_)->response_preamble());
749uint8_t ExchangeEngine::tries_after_unconfirmed_(
const IoFrame &request, uint8_t unconfirmed_tries, uint8_t try_index,
750 uint8_t tries_left, uint32_t elapsed_ms, uint32_t next_tx_ms,
759 if (request.
cmd == CMD_EXECUTE && this->target_evidence_provider_)
760 this->target_evidence_provider_(request.
dst, evidence);
761 if (!decisions::retry_after_unconfirmed_accept_is_safe(request, evidence.
confirms_execute, unconfirmed_tries))
765 if (request.
cmd == CMD_SUBSCRIBE_EVENT)
766 return UNCONFIRMED_SUBSCRIBE_MAX_RESENDS;
770 if (request.
cmd != CMD_EXECUTE)
771 return static_cast<uint8_t
>(EXCHANGE_RETRY_COUNT - std::min<uint8_t>(try_index, EXCHANGE_RETRY_COUNT));
775 if (!this->try_fits_budget_(elapsed_ms, UNCONFIRMED_EXECUTE_RESEND_DELAY_MS, next_tx_ms, plan.
window_ms, 0,
781 "Try %u accepted without a closing reply for cmd=%s(0x%02X): re-sending, the device normally "
782 "confirms (final_rx_ignored=%u final_rx_failed=%u)",
783 try_index, command_name(request.
cmd), request.
cmd, this->debug_.final_rx_ignored,
784 this->debug_.final_rx_failed);
788 delay(UNCONFIRMED_EXECUTE_RESEND_DELAY_MS - std::min<uint32_t>(plan.
gap_ms, UNCONFIRMED_EXECUTE_RESEND_DELAY_MS));
791 return UNCONFIRMED_EXECUTE_MAX_RESENDS;
794decisions::ExchangeFinalResponseDisposition ExchangeEngine::wait_for_final_response_(
795 const IoFrame &request, exchange::OutboundExchangeContext &ctx) {
798 const uint32_t auth_wait_ms = this->tuning_->exchange_response_wait_ms;
801 spec.window_ms = auth_wait_ms;
805 spec.policy = ListenPolicy::HOLD_REQUEST_CHANNEL;
810 RadioRxPacket packet{};
811 auto outcome = this->listen(spec, packet, ctx.rx, [&](
const IoFrame *parsed,
const RadioRxPacket &pkt) {
812 if (parsed == nullptr) {
813 this->record_debug(
"final_parse_fail", ctx.try_index, true);
814 this->counters_.parse_failures++;
815 log_unparsable_frame(
"Unparsable final response", ctx.try_index, pkt);
816 return ReplyDisposition::IGNORE;
818 if (is_valid_final_response(*parsed, request))
819 return ReplyDisposition::ACCEPT;
820 this->record_debug(
"final_wrong_exchange", ctx.try_index,
true);
821 log_exchange_frame(
"Ignored final response", ctx.try_index, *parsed, pkt.len);
822 return ReplyDisposition::IGNORE;
825 this->note_final_wait_(stats);
826 if (outcome == ListenOutcome::ACCEPTED)
827 return decisions::ExchangeFinalResponseDisposition::ACCEPT;
829 ctx.state = exchange::OutboundExchangeState::FAILED;
830 this->record_debug(
"wait_final_timeout", ctx.try_index,
true);
831 ESP_LOGI(TAG,
"Try %d ended: no matching final response for cmd=%s(0x%02X) within %" PRIu32
" ms", ctx.try_index,
833 return decisions::ExchangeFinalResponseDisposition::IGNORE_UNRELATED;
849 const uint32_t tx_done_ms = millis();
874 if (parsed ==
nullptr || parsed->
cmd != expected_cmd || memcmp(parsed->
dst, this->node_id_, NODE_ID_SIZE) != 0)
881 on_reply(*parsed, info);
882 if (count < UINT8_MAX)
908void count_saturating(uint8_t &counter) {
909 if (counter < UINT8_MAX)
918bool dispatch_received_packet(
const ReplyHandler &on_frame,
const RadioRxPacket &packet, IoFrame &frame,
919 ListenOutcome &outcome, ListenStats *stats) {
920 const bool parsed = parse(packet.data, packet.len, frame);
921 switch (on_frame(parsed ? &frame :
nullptr, packet)) {
922 case ReplyDisposition::ACCEPT:
923 outcome = ListenOutcome::ACCEPTED;
925 case ReplyDisposition::ABORT:
926 outcome = ListenOutcome::ABORTED;
928 case ReplyDisposition::IGNORE:
931 if (stats !=
nullptr)
932 count_saturating(stats->frames_ignored);
938void count_failed_reception(ListenStats *stats,
const RadioDriver *radio) {
939 if (stats ==
nullptr)
941 count_saturating(stats->failed_receptions);
942 stats->last_failed_irq = radio->get_last_capture().irq_status;
947bool preamble_or_sync_incoming(RadioDriver *radio,
const ListenSpec &spec) {
948 return spec.linger_on_preamble && (radio->is_preamble_detected() || radio->is_sync_detected());
957uint32_t resolve_dwell_ms(
const ListenSpec &spec,
bool rotating, RadioDriver *radio,
const TuningConfig &tuning) {
960 if (spec.dwell_ms != 0)
961 return spec.dwell_ms;
962 return radio->hop_dwell_ms(tuning);
967void ExchangeEngine::listen_hop_(uint32_t skip,
const ListenSpec &spec) {
968 this->hop_frequency(skip);
976 const uint32_t deadline = millis() + spec.
window_ms;
983 const uint32_t dwell = resolve_dwell_ms(spec, rotating, radio, *this->tuning_);
989 this->listen_hop_(skip, spec);
991 while ((int32_t) (deadline - millis()) > 0) {
992 const uint32_t remaining = deadline - millis();
996 const uint32_t slice = rotating ? std::min(remaining, dwell) : remaining;
1000 if (dispatch_received_packet(on_frame, packet, frame, outcome, spec.
stats))
1006 !preamble_or_sync_incoming(radio, spec))
1007 this->listen_hop_(skip, spec);
1011 if ((int32_t) (deadline - millis()) <= 0)
1014 count_failed_reception(spec.
stats, radio);
1017 if (!preamble_or_sync_incoming(radio, spec)) {
1018 this->listen_hop_(skip, spec);
1023 const uint32_t ext = std::min((uint32_t) (deadline - millis()), spec.
linger_dwell_ms);
1025 if (radio->
wait_for_packet(packet, ext) && dispatch_received_packet(on_frame, packet, frame, outcome, spec.
stats))
1040 if (this->device_key_provider_) {
1041 if (
const uint8_t *device_key = this->device_key_provider_(node); device_key !=
nullptr)
1044 return this->system_key_;
1052 const uint8_t *key) {
1053 uint8_t challenge[HMAC_SIZE];
1055 return this->
challenge_sender(request, freq, key, challenge, (*this->radio_ptr_)->response_preamble());
1059 const uint8_t *key,
const uint8_t challenge[HMAC_SIZE],
1060 uint16_t preamble) {
1081 if (!radio->
wait_for_packet(packet, this->tuning_->exchange_response_wait_ms)) {
1092 if (!
parse(packet.
data, packet.
len, rx) || !frame_is_challenge_response(rx) || rx.
data_len < HMAC_SIZE) {
1105 this->counters_.challenge_round_trips++;
decisions::AttemptPlan plan_attempts(decisions::ReadKind kind, bool low_power, const IoFrame &request, uint32_t freq, uint16_t preamble, uint16_t last_window_ms=0, std::optional< uint32_t > short_lead_tx_ms=std::nullopt) const
The attempt plan for a request sent with an explicit preamble, for a loop that runs its own attempts ...
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.
uint32_t tx_time_ms(const IoFrame &frame, uint32_t freq, uint16_t preamble) const
The radio's estimate of how long transmitting frame on freq with preamble takes, in whole millisecond...
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()).
decisions::AttemptPlan plan_read(decisions::ReadKind kind, const IoFrame &request, uint32_t freq, uint16_t request_preamble_override=0, bool state_unknown=false) const
The attempt plan for a read of request's target, with the transmit time this engine would plan for th...
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).
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.
void generate_challenge(uint8_t out[HMAC_SIZE])
Generate 6 random bytes for a challenge using the ESP32 hardware RNG.
bool moving_until_holds(const TargetEvidence &evidence, uint32_t now)
True while the remaining time the receiver last reported has not run out: by its own account it is st...
AttemptPlan attempt_plan(ReadKind kind, bool low_power, const TuningConfig &tuning, uint32_t attempt_tx_ms, uint16_t last_window_ms=0, std::optional< uint32_t > short_lead_tx_ms=std::nullopt)
The attempt plan for a request, from what it is for and who it asks.
bool attempt_fits(uint32_t elapsed_ms, uint32_t gap_ms, uint32_t tx_ms, uint32_t window_ms, uint32_t auth_tail_ms, uint32_t budget_ms)
The attempt budget rule: an attempt starts only if the whole attempt, up to the end of the last wait ...
ExchangeFirstResponseDisposition classify_exchange_first_response(const IoFrame &request, const IoFrame &candidate)
Decide how to handle the first response packet in an authenticated exchange.
AttemptPlan attempt_plan_for_tries(uint8_t max_tries, uint16_t window_ms)
The plan for a caller that names only a number of attempts: that many (at least one,...
@ 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.
@ REQUIRE_AUTH
Matching 0x3C challenge — device demands authentication.
@ IGNORE_UNRELATED
Frame doesn't match endpoints or failed parse — keep waiting.
@ COMPLETE_DIRECT
Matching non-challenge frame — operation complete, no auth needed.
ReadKind
What a request is for, which decides how its attempts are spent.
@ SETTLING
A read that decides where a device ended up: as many attempts as fit the budget.
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.
@ UNKNOWN
A status read to a receiver the hub has no recent news of (no moving evidence, and either no status r...
@ 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, bool is_status_read=false, bool state_unknown=false)
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.
@ 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 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 ...
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.
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 tries
Retry count (1-based).
uint16_t capture_irq_status
Raw IRQ register value.
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.
bool capture_rx_done
True if RxDone IRQ fired.
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).
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.
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.
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.
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 normal_start_preamble
Preamble for a directed start frame to a non-low-power target.
uint16_t exchange_response_wait_ms
Reply window for continuation frames and the post-auth final response.
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.
How one exchange spends its attempts. Handed to ExchangeEngine::send_and_receive().
uint16_t window_ms
How long the last attempt listens for the first reply.
bool short_lead
True when the first attempt is a short lead to a low-power receiver in an unknown state (WakeBelief::...
uint16_t gap_ms
Wait before each attempt after the first; 0 for none.
uint32_t budget_allowance_ms
Time the exchange may run past exchange_total_budget_ms.
bool state_unknown
True when the caller asked for the read to treat the receiver's state as unknown (AttemptRequest::wit...
uint8_t max_attempts
Most transmissions of the request, [1, EXCHANGE_MAX_ATTEMPTS].
uint16_t window_for_attempt(uint8_t attempt, uint8_t attempts) const
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...