Home IO Control
ESPHome add-on for IO-Homecontrol devices
Loading...
Searching...
No Matches
hub_core.cpp
Go to the documentation of this file.
1/// @file hub_core.cpp
2/// @brief Component lifecycle and main-loop scheduling.
3/// @ingroup hioc_hub
4///
5/// The core file owns the parts of IOHomeControlComponent that are primarily about
6/// runtime orchestration rather than protocol interpretation:
7/// - hardware/radio setup,
8/// - main loop scheduling,
9/// - device registry and callback fan-out.
10///
11/// Protocol exchange, pairing, inbound status handling, and outbound operations live
12/// in dedicated translation units so this file remains the place to understand how the
13/// component is brought up and driven over time.
14
15#include "hub_internal.h"
16
17#include "radio_sx1276.h"
18#include "radio_sx1262.h"
19#include "radio_lr1121.h"
20#include "tuning_config.h"
21#include "tuning_registry.h"
22
23#include <cinttypes>
24#include <new>
25#include <vector>
26
27namespace esphome {
28namespace home_io_control {
29
30namespace {
31
32constexpr uint32_t BLOCKING_WARNING_THRESHOLD_MS =
33 250; ///< setup() and exchanges can legitimately block longer than generic ESPHome components.
34
35} // namespace
36
37static const char *const TAG = detail::TAG;
38
39// === Setup ===
40
41/// Initialize the IO‑Homecontrol component and radio hardware.
42///
43/// This is the main setup entry point called by ESPHome during startup.
44/// The sequence:
45/// 1. Parse node_id and system_key from hex strings (fails early if malformed).
46/// 2. Initialize the SPI bus via spi_setup().
47/// 3. Construct the driver named by the required `radio_type` YAML field
48/// ("sx1276", "sx1262", or "lr1121").
49/// 4. Allocate the appropriate RadioDriver (SX1276 needs DIO0; SX1262/LR1121 need BUSY+DIO1,
50/// DIO1 carrying the LR1121's DIO9 IRQ line).
51/// 5. Call radio_->init() which performs chip reset, calibration, and register configuration.
52/// 6. Enter normal loop() operation with radio in RX mode.
53///
54/// @note Blocking operations in setup() temporarily raise the ESPHome WDT threshold
55/// to 250 ms (warn_if_blocking_over_) because radio init can
56/// exceed the default 30–50 ms budget.
58 // IO-homecontrol exchanges are intentionally blocking and often take a few hundred
59 // milliseconds, so use a higher warning threshold than ESPHome's generic 30-50 ms.
60 this->warn_if_blocking_over_ = BLOCKING_WARNING_THRESHOLD_MS;
61#ifdef IOHOME_UNSAFE_LOG_KEY_MATERIAL
62 // Loud, unconditional, every-boot warning so a build left with this flag on by accident can
63 // never stay quiet about it — see log_frame.h::render_frame_hex_redacted() for the full
64 // rationale and safe-use rules.
65 ESP_LOGE(detail::TAG, "########################################");
66 ESP_LOGE(detail::TAG, "IOHOME_UNSAFE_LOG_KEY_MATERIAL IS ENABLED -- FRAME LOGS EXPOSE YOUR SYSTEM KEY");
67 ESP_LOGE(detail::TAG, "This build is NOT safe to run normally or share logs from. Rebuild without this");
68 ESP_LOGE(detail::TAG, "flag as soon as you are done capturing.");
69 ESP_LOGE(detail::TAG, "########################################");
70#endif
71 ESP_LOGI(detail::TAG, "Initializing...");
72 if (!hex_to_bytes(this->node_id_str_, this->node_id_, NODE_ID_SIZE) ||
73 !hex_to_bytes(this->system_key_str_, this->system_key_, AES_KEY_SIZE)) {
74 // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) — ESPHome's own LOG_STR() macro.
75 this->mark_failed(LOG_STR("Invalid node_id or system_key configuration"));
76 return;
77 }
78
79 // Open the 1W identities' persistent sequence counters. Not done from the generated
80 // add_oneway_controller() wiring, which runs before preferences are usable.
83 for (const auto &callback : this->oneway_report_callbacks_)
84 callback(report);
85 });
86
87 this->spi_setup();
88
89 const char *chip_name_for_log = nullptr;
90 this->radio_ = this->select_and_construct_radio_(&chip_name_for_log);
91 if (this->radio_ == nullptr) {
92 this->radio_failure_reason_ = "no driver for radio_type '" + this->radio_type_ +
93 "' (a required pin is missing, the type is unrecognized, or allocation failed)";
94 // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) — ESPHome's own LOG_STR() macro.
95 this->mark_failed(LOG_STR("Radio driver setup failed (see 'Radio setup failed' in the config dump)"));
96 return;
97 }
98
99#ifdef IOHOME_LR1121_FIRMWARE_UPDATE
100 // Boot-time bootloader-version excursion — deliberately before
101 // init(): nothing has configured the radio yet, so this costs one extra chip reset and needs no
102 // reboot afterward, unlike every other bootloader excursion this feature performs.
103 this->run_lr1121_boot_time_bootloader_read_();
104#endif
105
106 if (!this->radio_->init()) {
107 // Read before the delete: failure_reason() is a member call on the driver.
108 const char *const driver_reason = this->radio_->failure_reason();
110 driver_reason != nullptr ? driver_reason : "driver init failed without a recorded cause";
111 delete this->radio_;
112 this->radio_ = nullptr;
113#ifdef IOHOME_LR1121_FIRMWARE_UPDATE
114 // Cache the verdict even on a failed init() — a null radio_ is exactly the case
115 // trigger_lr1121_firmware_update()'s guard 0 still allows an attempt for (reflashing is the
116 // recovery), and it needs a cached "installed version unknown" verdict to route through.
117 this->cache_lr1121_flash_verdict_();
118#endif
119 // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) — ESPHome's own LOG_STR() macro.
120 this->mark_failed(LOG_STR("Radio hardware initialization failed (see 'Radio setup failed' in the config dump)"));
121 return;
122 }
123
124#ifdef IOHOME_LR1121_FIRMWARE_UPDATE
125 this->cache_lr1121_flash_verdict_();
126#endif
127
128 this->initialized_ = true;
133 if (this->tuning_.active) {
134 std::string const snapshot = tuning_config_full_snapshot(this->tuning_);
135 ESP_LOGI(detail::TAG, "%s", snapshot.c_str());
136 }
137 ESP_LOGI(detail::TAG, "Radio initialized (%s), Node ID: %s", chip_name_for_log, this->node_id_str_.c_str());
138}
139
140// See the declaration in hub_core.h for the full contract. `radio_type_` is one of "lr1121",
141// "sx1262", or "sx1276" — the YAML schema requires the field and validates it against exactly
142// those three values, so the fallthrough below is unreachable in a config-driven build and
143// exists only to fail loudly rather than guess if this method is ever called some other way.
145 if (this->radio_type_ == "lr1121") {
146 *chip_name_out = "LR1121";
147 if (this->busy_pin_ == nullptr || this->dio1_pin_ == nullptr) {
148 ESP_LOGE(detail::TAG, "LR1121 requires busy_pin and dio1_pin (dio1_pin carries the chip's DIO9 IRQ line)");
149 return nullptr;
150 }
151 auto *radio = new (std::nothrow)
152 RadioLR1121(this, this->rst_pin_, this->dio1_pin_, this->busy_pin_, this->tx_power_, this->tcxo_voltage_);
153 if (radio == nullptr)
154 ESP_LOGE(detail::TAG, "Failed to allocate LR1121 radio driver");
155 return radio;
156 }
157
158 if (this->radio_type_ == "sx1262") {
159 *chip_name_out = "SX1262";
160 if (this->busy_pin_ == nullptr || this->dio1_pin_ == nullptr) {
161 ESP_LOGE(detail::TAG, "SX1262 requires busy_pin and dio1_pin");
162 return nullptr;
163 }
164 auto *radio = new (std::nothrow)
165 RadioSX1262(this, this->rst_pin_, this->dio1_pin_, this->busy_pin_, this->tx_power_, this->tcxo_voltage_,
166 this->fem_en_pin_, this->vfem_pin_, this->fem_pa_pin_, this->fem_profile_);
167 if (radio == nullptr)
168 ESP_LOGE(detail::TAG, "Failed to allocate SX1262 radio driver");
169 return radio;
170 }
171
172 if (this->radio_type_ == "sx1276") {
173 *chip_name_out = "SX1276";
174 if (this->dio0_pin_ == nullptr) {
175 ESP_LOGE(detail::TAG, "SX1276 requires dio0_pin");
176 return nullptr;
177 }
178 auto *radio = new (std::nothrow)
179 RadioSX1276(this, this->rst_pin_, this->dio0_pin_, this->dio4_pin_, this->tx_power_, this->pa_pin_);
180 if (radio == nullptr)
181 ESP_LOGE(detail::TAG, "Failed to allocate SX1276 radio driver");
182 return radio;
183 }
184
185 *chip_name_out = "unknown";
186 ESP_LOGE(detail::TAG, "Unrecognized radio_type '%s'", this->radio_type_.c_str());
187 return nullptr;
188}
189
190// === Tuning layer ===
191
192/// Apply the current tuning configuration to the active radio driver.
193///
194/// Only chip-specific parameters are forwarded; the rest are consumed by the
195/// pairing flow and LBT logic. This is called once at the end of setup() and
196/// again whenever a UI-driven change modifies a radio parameter.
198 if (this->radio_ == nullptr)
199 return;
200 this->radio_->apply_tuning(this->tuning_);
201}
202
203/// @brief Take the directed start preamble from the driver when YAML did not choose one.
204///
205/// Runs once, after the radio exists and before the first transmit. How much preamble a start
206/// frame needs depends on what the driver actually puts on air, so the default is the driver's to
207/// give (ADR 0042); an explicit `normal_start_preamble:` always wins, including a shorter value.
208/// The resolved value is reported by dump_config(), not from here — see the note in its body.
210 if (this->radio_ == nullptr || this->tuning_.normal_start_preamble_from_yaml)
211 return;
212 // Silent here on purpose: dump_config() reports the resolved value, because that is the only
213 // output a log client attaching after boot receives.
215}
216
217/// Update a numeric tuning parameter from a Home Assistant `number` entity.
218///
219/// Parses the parameter name and applies the new value to the in-memory tuning
220/// configuration. Radio-affecting parameters are forwarded to the active driver
221/// immediately; the change is logged in YAML-compatible form so it can be copied
222/// back into the configuration file.
223void IOHomeControlComponent::update_tuning_number(const std::string &name, float value) {
224 const TuningNumberParam *param = find_tuning_number(name);
225 if (param == nullptr) {
226 ESP_LOGW(detail::TAG, "Unknown tuning number parameter: %s", name.c_str());
227 return;
228 }
229 param->set(this->tuning_, value);
230 if (param->applies_to_radio)
232 ESP_LOGI(detail::TAG, "%s", tuning_update_log_line(name, std::to_string(static_cast<int>(value))).c_str());
233}
234
235/// Update a select tuning parameter from a Home Assistant `select` entity.
236///
237/// Parses the selected option string and applies it to the in-memory tuning
238/// configuration. Radio-affecting parameters are forwarded to the active driver
239/// immediately; the change is logged in YAML-compatible form.
240void IOHomeControlComponent::update_tuning_select(const std::string &name, const std::string &value) {
241 const TuningSelectParam *param = find_tuning_select(name);
242 if (param == nullptr) {
243 ESP_LOGW(detail::TAG, "Unknown tuning select parameter: %s", name.c_str());
244 return;
245 }
246 // Radio-affecting parameters re-apply only when the option string actually parsed; the
247 // update is still logged for any known parameter, matching the original dispatch.
248 if (param->set(this->tuning_, value) && param->applies_to_radio)
250 ESP_LOGI(detail::TAG, "%s", tuning_update_log_line(name, value).c_str());
251}
252
253/// Return the current value of a numeric tuning parameter.
254///
255/// Mirror of update_tuning_number(); used by IOHomeTuningNumber::setup() to publish
256/// the boot-time value so the Home Assistant slider reflects the active configuration
257/// (default or YAML override) without restating any default on the Python side.
258float IOHomeControlComponent::get_tuning_number_value(const std::string &name) const {
259 const TuningNumberParam *param = find_tuning_number(name);
260 if (param == nullptr) {
261 ESP_LOGW(detail::TAG, "Unknown tuning number parameter: %s", name.c_str());
262 return 0.0F;
263 }
264 return param->get(this->tuning_);
265}
266
267/// Return the current option string of a select tuning parameter.
268///
269/// Mirror of update_tuning_select(); used by IOHomeTuningSelect::setup() to publish the
270/// boot-time option so the Home Assistant dropdown reflects the active configuration. The
271/// returned strings match the YAML/UI option labels exactly. The command list is returned
272/// as a comma-separated preset string (e.g. "0x28,0x2E") matching the dropdown options.
273std::string IOHomeControlComponent::get_tuning_select_value(const std::string &name) const {
274 const TuningSelectParam *param = find_tuning_select(name);
275 if (param == nullptr) {
276 ESP_LOGW(detail::TAG, "Unknown tuning select parameter: %s", name.c_str());
277 return "";
278 }
279 return param->get(this->tuning_);
280}
281
282// === Protocol send/receive (thin wrappers delegating to ExchangeEngine) ===
283
284/// Delegate channel hop to ExchangeEngine (which owns last_hop_us_).
286
287/// Delegate LBT transmit to ExchangeEngine.
288bool IOHomeControlComponent::transmit_frame_(const IoFrame &frame, uint32_t freq, uint16_t preamble) {
289 return this->exchange_engine_.transmit_frame(frame, freq, preamble);
290}
291
292/// Delegate outbound exchange to ExchangeEngine and manage the busy_ flag.
294 uint8_t max_tries) {
295 this->busy_ = true;
296 ExchangeOutcome const outcome = this->exchange_engine_.send_and_receive(request, response, freq, max_tries);
297 this->busy_ = false;
298 return outcome;
299}
300
301/// Delegate inbound authentication to ExchangeEngine.
302bool IOHomeControlComponent::authenticate_request_(const IoFrame &request, uint32_t freq) {
303 return this->exchange_engine_.authenticate_request(request, freq);
304}
305
306void IOHomeControlComponent::notify_device_update_(const std::string &id) { this->registry_.notify(id); }
307
308// === Device management ===
309
310void IOHomeControlComponent::set_device_status_poll_interval(const std::string &device_id, uint32_t poll_interval_ms) {
311 if (this->get_device(device_id) == nullptr)
312 return;
313 this->poll_policy_.set_interval(device_id, poll_interval_ms);
314}
315
316void IOHomeControlComponent::schedule_background_poll_backoff_(const std::string &device_id, bool auth_like) {
317 uint32_t const now = millis();
318 uint32_t const backoff_ms = this->poll_policy_.on_exchange_failed(device_id, auth_like, now);
319 if (backoff_ms > 0) {
320 ESP_LOGD(TAG,
321 "Background status poll backoff for device %s: delay=%" PRIu32
322 " ms auth_like=%s status_failures=%u auth_failures=%u",
323 device_id.c_str(), backoff_ms, YESNO(auth_like), this->poll_policy_.get_status_poll_failures(device_id),
324 this->poll_policy_.get_auth_poll_failures(device_id));
325 }
326}
327
328void IOHomeControlComponent::add_device(const std::string &device_id) { this->registry_.add(device_id); }
329
330void IOHomeControlComponent::add_device(const std::string &device_id, const DeviceConfig &cfg) {
331 this->registry_.add(device_id, cfg);
332}
333
334IoDevice *IOHomeControlComponent::get_device(const std::string &device_id) { return this->registry_.get(device_id); }
335
336void IOHomeControlComponent::set_device_dimmable(const std::string &device_id, bool dimmable) {
337 this->registry_.set_dimmable(device_id, dimmable);
338}
339
340void IOHomeControlComponent::set_device_silent(const std::string &device_id, bool silent) {
341 this->registry_.set_silent(device_id, silent);
342}
343
344// === Main loop ===
345
347 if (!this->initialized_)
348 return;
349 if (this->radio_test_mode_)
350 return;
351
352 // Check for received packets (non-blocking)
353 if (!this->busy_) {
354 RadioRxPacket packet{};
355 if (this->radio_->check_for_packet(packet))
356 this->process_received_packet_(packet);
357 }
358
359 // A blocking exchange makes the radio deaf for 1–3 s. When a linked remote's press schedules a
360 // status poll, dispatching it while that same remote is still transmitting would blind the hub
361 // to the rest of the press — so background polls yield for a moment. Control operations never do.
362 if (!this->busy_ && !this->defer_background_poll_()) {
364 }
365
366 // Frequency hopping — protocol specifies 2.7ms per channel, but ESPHome calls
367 // loop() every ~16-30ms. This is acceptable for a controller: a directed start frame to a
368 // low-power target still goes out with LONG_PREAMBLE (1024 bytes ≈ 330ms airtime), long enough
369 // to be detected regardless of channel alignment; a start frame to an always-alive target uses
370 // the shorter normal_start_preamble (default 32 bytes), which such a receiver hears fine. This
371 // coarse idle hop causes no exchange to miss its channel either way, because every TX retunes
372 // explicitly to a named channel before sending. Precise hopping would only matter for a passive
373 // receiver scanning for unsolicited frames.
374 // Diagnostics build flag: park the receiver on one channel instead of hopping. A hopping monitor
375 // is on any given channel roughly a third of the time, so "the capture never shows frame X" is
376 // weak evidence — locking to the channel under study makes an absence mean something. Define it
377 // to the channel in Hz, e.g. -DIOHOME_LOCK_CHANNEL_HZ=868950000 for CH2, the command channel.
378 // Only useful for a passive monitor: a hub that cannot hop will miss replies on other channels.
379#ifdef IOHOME_LOCK_CHANNEL_HZ
380 if (!this->busy_ && this->radio_ != nullptr && this->radio_->get_current_freq() != IOHOME_LOCK_CHANNEL_HZ)
381 this->radio_->change_frequency(IOHOME_LOCK_CHANNEL_HZ);
382#else
383 if (!this->busy_) {
384 if (this->key_extraction_awaiting_reply_()) {
385 // The key-extraction responder is mid-attempt and expecting the hub's next CH2-only unicast
386 // frame (see wait_for_key_confirm_()'s doc comment in pairing_engine.cpp) — hold CH2 instead
387 // of running the generic idle-hop scan, which would otherwise cycle away from CH2 for 2/3 of
388 // every hop cycle with no key-extraction awareness at all. Frequency test first, deliberately:
389 // reception_in_progress() is not a free predicate (on SX1276 it can force a
390 // set_mode_standby()/set_mode_rx() cycle), so this branch must be as sparing as maybe_hop()
391 // itself, which only consults it once the dwell timer has already decided to hop.
392 if (this->radio_->get_current_freq() != FREQ_CH2 && !this->radio_->reception_in_progress())
393 this->radio_->change_frequency(FREQ_CH2);
394 // exchange_engine_'s last_hop_us_ goes stale while the hold is active (it bypasses
395 // hop_frequency(), which is what normally updates that timestamp). Harmless: once the hold
396 // ends, maybe_hop() will very likely hop on its next call instead of waiting out a full
397 // HOP_TIME_US — resuming idle scanning a little early is not a bug.
398 } else {
400 }
401 }
402#endif
403
404 // Periodic status polling
405 if (!this->busy_) {
406 auto due = this->poll_policy_.pop_due_device(millis());
407 if (due.has_value())
408 this->queue_request_device_status(*due);
409 }
410}
411
413 ESP_LOGCONFIG(detail::TAG, "IO-Homecontrol:");
414 ESP_LOGCONFIG(detail::TAG, " Node ID: %s", this->node_id_str_.c_str());
415 ESP_LOGCONFIG(detail::TAG, " Radio: %s", this->radio_type_.c_str());
416 ESP_LOGCONFIG(detail::TAG, " TX Power: %u dBm", this->tx_power_);
417 // Printed for every board, from the dump rather than from setup(): the value decides whether a
418 // directed start frame is heard at all, it is chip-dependent (ADR 0042), and a reporter's pasted
419 // log is usually captured after boot, where setup()'s output is already gone.
420 ESP_LOGCONFIG(detail::TAG, " Start preamble: %u bytes (%s)", this->tuning_.normal_start_preamble,
421 this->tuning_.normal_start_preamble_from_yaml ? "set in YAML" : "from the radio driver");
422 if (!this->radio_failure_reason_.empty())
423 ESP_LOGE(detail::TAG, " Radio setup failed: %s", this->radio_failure_reason_.c_str());
424#ifdef IOHOME_UNSAFE_LOG_KEY_MATERIAL
425 // The setup() banner in short: a log client that connects after boot only receives this dump, and
426 // it is the reader who most needs the instruction to rebuild before sharing logs.
427 ESP_LOGE(detail::TAG, " IOHOME_UNSAFE_LOG_KEY_MATERIAL IS ENABLED -- FRAME LOGS EXPOSE YOUR SYSTEM KEY");
428 ESP_LOGE(detail::TAG, " Not safe to share logs from: rebuild without this flag as soon as you are done capturing.");
429#endif
430 if (this->tuning_.active) {
431 // Same snapshot setup() logs once at boot, for the same reason.
432 ESP_LOGCONFIG(detail::TAG, " %s", tuning_config_full_snapshot(this->tuning_).c_str());
433 }
434 LOG_PIN(" RST Pin: ", this->rst_pin_);
435 if (this->dio0_pin_ != nullptr)
436 LOG_PIN(" DIO0 Pin: ", this->dio0_pin_);
437 if (this->dio1_pin_ != nullptr)
438 LOG_PIN(" DIO1 Pin: ", this->dio1_pin_);
439 if (this->dio4_pin_ != nullptr)
440 LOG_PIN(" DIO4 Pin: ", this->dio4_pin_);
441 if (this->busy_pin_ != nullptr)
442 LOG_PIN(" BUSY Pin: ", this->busy_pin_);
443 // Stated on every boot/log connect, so a posted log shows whether low-power devices get the
444 // per-try preamble order (ADR 0040) without anyone having to share their tuning YAML.
445 ESP_LOGCONFIG(detail::TAG, " Low-power wake belief: %s",
446 this->tuning_.low_power_wake_belief ? "on" : "off (tuning: low_power_wake_belief: false)");
447 ESP_LOGCONFIG(detail::TAG, " Devices: %zu", this->registry_.size());
448 if (this->registry_.linked_remote_count() > 0) {
449 ESP_LOGCONFIG(detail::TAG, " Linked Remotes: %zu", this->registry_.linked_remote_count());
450 this->registry_.for_each_linked_remote([](const std::string &remote_id, const std::vector<std::string> &devices) {
451 for (const auto &device_id : devices)
452 ESP_LOGCONFIG("home_io_control", " - remote %s -> device %s", remote_id.c_str(), device_id.c_str());
453 });
454 }
455
457
458 if (this->radio_ != nullptr) {
459 // A driver that latched a failure after setup (a runtime BUSY timeout) stays silent otherwise:
460 // it short-circuits every later command while the component itself is not marked failed.
461 if (this->radio_->is_failed()) {
462 const char *const reason = this->radio_->failure_reason();
463 ESP_LOGE(detail::TAG, " Radio failed after setup: %s", reason != nullptr ? reason : "no recorded cause");
464 }
465 this->radio_->dump_front_end();
466 this->radio_->dump_debug();
467 }
468
469#ifdef IOHOME_LR1121_FIRMWARE_UPDATE
470 this->dump_lr1121_firmware_update_debug_();
471#endif
472}
473
475 if (this->oneway_controllers().empty())
476 return;
477 ESP_LOGCONFIG(detail::TAG, " 1W Controllers: %zu", this->oneway_controllers().all().size());
478 for (const auto &identity : this->oneway_controllers().all()) {
479 // A derived address is reproducible from the YAML, but nothing in the YAML shows it — so
480 // print it, and mark it derived, or a user debugging a collision has nowhere to look. Keys
481 // are never printed here (ADR 0011); only addresses and classes. The resolved ACEI and
482 // destination let a user eyeball this against a capture of their real remote (ADR 0031).
483 const OneWayWireProfile profile = resolve_oneway_wire_profile(identity.manufacturer);
484 // The power class is printed for every identity, including the ones that never set the key, so
485 // a reporter's boot log always shows which shape their build actually transmits (ADR 0038).
486 // Where it came from is printed too: an unset key resolves from the manufacturer profile
487 // (ADR 0041), so "always-alive" alone would not tell a VELUX user whether they chose it.
488 ESP_LOGCONFIG(
489 detail::TAG, " - %s: node %s%s, class 0x%02X, acei 0x%02X%s, broadcast %s%s, power %s%s",
490 identity.id.c_str(), node_id_to_string(identity.node_id).c_str(), identity.node_id_derived ? " (derived)" : "",
491 static_cast<unsigned>(identity.io_device_type), static_cast<unsigned>(effective_execute_acei(identity)),
492 has_execute_acei_override(identity) ? " (override)" : "", identity.execute_broadcast_all ? "all" : "typed",
493 profile.profile_is_a_guess ? " [no vendor profile — Somfy-shaped]" : "",
495 has_power_class_override(identity) ? "" : " (from profile)");
496
497 // The VELUX enrollment gesture ignores io_device_type and sweeps a fixed class set instead —
498 // the most surprising resolved value on the identity, so print it (ADR 0032).
500 std::string classes;
501 char byte_hex[3];
502 for (const DeviceType c : effective_enrollment_classes(identity)) {
503 if (c == DeviceType::UNKNOWN)
504 continue;
505 snprintf(byte_hex, sizeof(byte_hex), "%02X", static_cast<unsigned>(c));
506 classes += classes.empty() ? "0x" : " 0x";
507 classes += byte_hex;
508 }
509 ESP_LOGCONFIG(detail::TAG, " enroll: VELUX KLI gesture, 0x30 sweep -> %s", classes.c_str());
510 }
511 }
512}
513
514} // namespace home_io_control
515} // namespace esphome
void set_dimmable(const std::string &device_id, bool dimmable)
Set a device's dimmable flag (see IoDevice::dimmable).
void set_silent(const std::string &device_id, bool silent)
Select a device's travel profile.
void notify(const std::string &device_id)
Invoke all registered callbacks for device_id.
IoDevice * get(const std::string &device_id)
Retrieve a registered device by ID.
void for_each_linked_remote(const std::function< void(const std::string &, const std::vector< std::string > &)> &fn) const
Invoke fn(remote_id, device_id_list) for every linked-remote entry.
void add(const std::string &device_id)
Register a device by ID with default metadata (UNKNOWN type, subtype 0, not inverted).
void maybe_hop()
Hop only if the minimum dwell has elapsed and no frame is currently arriving on this channel — RadioD...
bool transmit_frame(const IoFrame &frame, uint32_t freq, uint16_t preamble)
Transmit a raw IoFrame with LBT and the given preamble length.
bool authenticate_request(const IoFrame &request, uint32_t freq)
Authenticate an inbound device command via 0x3C challenge / 0x3D HMAC.
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).
InternalGPIOPin * fem_en_pin_
Front-end module enable.
Definition hub_core.h:1085
InternalGPIOPin * fem_pa_pin_
Front-end module PA switch.
Definition hub_core.h:1087
void dump_oneway_controllers_config_() const
Emit the 1W controller identities to the config dump — node, class, and the resolved ACEI / broadcast...
Definition hub_core.cpp:474
InternalGPIOPin * dio4_pin_
SX1276 DIO4 preamble detect (optional).
Definition hub_core.h:1082
InternalGPIOPin * dio1_pin_
SX1262 DIO1 interrupt; also carries the LR1121's DIO9 IRQ line.
Definition hub_core.h:1083
void dump_config() override
Dump configuration and radio debug info to the log.
Definition hub_core.cpp:412
void update_tuning_select(const std::string &name, const std::string &value)
Receive a select tuning update from a HA select entity.
Definition hub_core.cpp:240
virtual IoDevice * get_device(const std::string &device_id)
Retrieve a device by ID; returns nullptr if not found.
Definition hub_core.cpp:334
virtual void queue_request_device_status(const std::string &device_id)
Queue an async status request; returns immediately, executed in loop().
void update_tuning_number(const std::string &name, float value)
Receive a numeric tuning update from a HA number entity.
Definition hub_core.cpp:223
virtual void add_device(const std::string &device_id)
Add a device to the registry by device ID only (undeclared/legacy path).
Definition hub_core.cpp:328
InternalGPIOPin * vfem_pin_
Front-end module power.
Definition hub_core.h:1086
TuningConfig tuning_
Runtime tuning overrides.
Definition hub_core.h:1107
ExchangeOutcome send_and_receive_(const IoFrame &request, IoFrame &response, uint32_t freq, uint8_t max_tries=EXCHANGE_RETRY_COUNT)
Main request/response exchange with retry and automatic authentication.
Definition hub_core.cpp:293
virtual void set_device_status_poll_interval(const std::string &device_id, uint32_t poll_interval_ms)
Configure the optional follow-up polling interval for a registered device.
Definition hub_core.cpp:310
void process_pending_operation_()
Pop next pending operation from the queue and execute it (set position, request status,...
void hop_frequency_()
Delegate channel hop to ExchangeEngine (which owns last_hop_us_).
Definition hub_core.cpp:285
virtual void set_device_dimmable(const std::string &device_id, bool dimmable)
Set a device's dimmable flag (see IoDevice::dimmable).
Definition hub_core.cpp:336
float get_tuning_number_value(const std::string &name) const
Current value of a numeric tuning parameter, used to seed a HA number entity on boot.
Definition hub_core.cpp:258
bool defer_background_poll_() const
Whether loop() should skip dispatching the queue this iteration because the pending work is a backgro...
Definition hub_core.h:842
void resolve_start_preamble_default_()
Resolve normal_start_preamble from the driver when YAML did not set it (ADR 0042).
Definition hub_core.cpp:209
void loop() override
Main loop: process pending operations and drive radio state machine.
Definition hub_core.cpp:346
void schedule_background_poll_backoff_(const std::string &device_id, bool auth_like)
Apply backoff after a failed background status poll and log the result.
Definition hub_core.cpp:316
OneWayTransmitter oneway_transmitter_
Owns the 1W controller identities, their rolling-sequence counters and the transmit burst.
Definition hub_core.h:1136
std::string radio_failure_reason_
Why setup() gave up on the radio, or empty.
Definition hub_core.h:1096
std::string radio_type_
"sx1276", "sx1262", or "lr1121"; required by the YAML schema.
Definition hub_core.h:1093
bool key_extraction_awaiting_reply_() const
True while the key-extraction responder is mid-attempt and still within its bounded CH2-hold window.
Definition hub_core.h:775
RadioDriver * select_and_construct_radio_(const char **chip_name_out)
Select and construct the radio driver named by the required radio_type config field.
Definition hub_core.cpp:144
bool transmit_frame_(const IoFrame &frame, uint32_t freq, uint16_t preamble)
Transmit a raw IoFrame on the current frequency with given preamble length.
Definition hub_core.cpp:288
bool radio_test_mode_
When true, loop() is suspended for loopback testing.
Definition hub_core.h:1106
ExchangeEngine exchange_engine_
Owns all authenticated exchange and LBT/hop logic.
Definition hub_core.h:1129
const OneWayControllerRegistry & oneway_controllers() const
Definition hub_core.h:319
virtual void set_device_silent(const std::string &device_id, bool silent)
Select a device's travel profile at runtime (see IOHomeCoverSilentSwitch).
Definition hub_core.cpp:340
InternalGPIOPin * dio0_pin_
SX1276 DIO0 interrupt.
Definition hub_core.h:1081
std::vector< OneWayCommandReportFn > oneway_report_callbacks_
Subscribers to the per-command 1W report; one per "Last 1W Command" sensor.
Definition hub_core.h:1157
void notify_device_update_(const std::string &id)
Fire all registered device update callbacks for the given device ID.
Definition hub_core.cpp:306
std::string get_tuning_select_value(const std::string &name) const
Current option string of a select tuning parameter, used to seed a HA select entity on boot.
Definition hub_core.cpp:273
void setup() override
Initialize hardware (radio and device registry).
Definition hub_core.cpp:57
uint8_t tcxo_voltage_
SX1262/LR1121 TCXO voltage setting (default 1.8 V).
Definition hub_core.h:1101
void process_received_packet_(const RadioRxPacket &packet)
Parse a received frame, merge supported device state or metadata, and notify callbacks.
bool authenticate_request_(const IoFrame &request, uint32_t freq)
Handle an inbound authenticated command from a device (status updates, etc.).
Definition hub_core.cpp:302
InternalGPIOPin * busy_pin_
SX1262/LR1121 BUSY pin.
Definition hub_core.h:1084
void register_management_actions_()
Register hub-level Home Assistant actions; called from setup().
Definition hub_core.h:1000
void apply_tuning_to_radio_()
Apply the current tuning configuration to the active radio driver.
Definition hub_core.cpp:197
FemProfile fem_profile_
Which FEM part fem_pa_pin_ belongs to, if any.
Definition hub_core.h:1088
void setup()
Open each registered identity's persistent sequence counter.
void set_command_report_callback(OneWayCommandReportFn callback)
Register the callback that receives a report after every command attempt.
Abstract radio driver for IO-Homecontrol.
virtual void dump_front_end()
Optional board front-end-module (external PA/LNA) summary emitted from dump_config,...
uint32_t get_current_freq() const
Get the current RF frequency.
virtual uint16_t default_start_preamble() const
Default preamble for a directed start frame, when the user has not set normal_start_preamble in YAML.
virtual void change_frequency(uint32_t freq_hz)=0
Change the carrier frequency using fast hop (no standby transition needed).
const char * failure_reason() const
Short, human-readable reason the driver latched is_failed, or nullptr if it has not.
virtual bool is_failed() const
Returns true if the radio failed to initialize or encountered a fatal error.
virtual bool init()=0
Initialize the radio hardware. Returns true on success.
virtual void apply_tuning(const TuningConfig &tuning)
Apply runtime tuning parameters to the driver.
virtual void dump_debug()
Optional chip-specific diagnostics emitted from dump_config.
virtual bool check_for_packet(RadioRxPacket &packet)=0
Non-blocking check for a received packet.
RadioLR1121(SpiAccess *spi, InternalGPIOPin *rst_pin, InternalGPIOPin *irq_pin, InternalGPIOPin *busy_pin, uint8_t tx_power, uint8_t tcxo_voltage_code)
RadioSX1262(SpiAccess *spi, InternalGPIOPin *rst_pin, InternalGPIOPin *dio1_pin, InternalGPIOPin *busy_pin, uint8_t tx_power, uint8_t tcxo_voltage, InternalGPIOPin *fem_en_pin=nullptr, InternalGPIOPin *vfem_pin=nullptr, InternalGPIOPin *fem_pa_pin=nullptr, FemProfile fem_profile=FemProfile::NONE)
RadioSX1276(SpiAccess *spi, InternalGPIOPin *rst_pin, InternalGPIOPin *dio0_pin, InternalGPIOPin *dio4_pin, uint8_t tx_power, uint8_t pa_pin)
void set_interval(const std::string &device_id, uint32_t interval_ms)
Set the configured follow-up poll interval (ms; 0 = legacy one-shot settle only).
uint32_t on_exchange_failed(const std::string &device_id, bool auth_like, uint32_t now)
Record a failed background poll; apply backoff or clear tracking if the window expired.
uint8_t get_status_poll_failures(const std::string &device_id) const
std::optional< std::string > pop_due_device(uint32_t now)
Return and consume the first device whose next_update is overdue.
Helpers shared only by the hub's own implementation files (hub_*.cpp).
constexpr const char * TAG
Shared log tag for hub-level messages.
Definition log_helpers.h:31
DeviceType
Device type identifiers reported by IO‑Homecontrol products.
@ UNKNOWN
Unknown/unspecified device.
static constexpr const char * TAG
OneWayPowerClass effective_power_class(const OneWayControllerIdentity &identity)
The burst shape this identity actually transmits with.
std::array< DeviceType, 3 > effective_enrollment_classes(const OneWayControllerIdentity &identity)
The device classes this identity's 0x30 enrollment sweep will actually target.
uint8_t effective_execute_acei(const OneWayControllerIdentity &identity)
The ACEI byte a given identity will put on air for a 1W EXECUTE frame.
ExchangeOutcome
Authenticated exchange engine — outbound and inbound protocol flows.
std::string tuning_config_full_snapshot(const TuningConfig &cfg)
Format the current tuning configuration as a full one-line snapshot.
const TuningSelectParam * find_tuning_select(const std::string &name)
Look up a select tuning parameter by name; returns nullptr if unknown.
std::string tuning_update_log_line(const std::string &name, const std::string &value)
Format a single tuning update for the log.
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.
const char * oneway_power_class_name(OneWayPowerClass power_class)
Human-readable name for a OneWayPowerClass, as it appears in the boot log.
const TuningNumberParam * find_tuning_number(const std::string &name)
Look up a numeric tuning parameter by name; returns nullptr if unknown.
bool has_power_class_override(const OneWayControllerIdentity &identity)
Whether this identity's burst shape comes from an explicit low_power: rather than the profile.
OneWayWireProfile resolve_oneway_wire_profile(uint8_t manufacturer)
Resolve an identity's 1W wire profile from its manufacturer byte.
bool has_execute_acei_override(const OneWayControllerIdentity &identity)
Whether this identity's ACEI comes from an explicit execute_acei: rather than the profile.
bool hex_to_bytes(const std::string &hex, uint8_t *out, uint8_t len)
Convert a hex string (e.g., "123ABC") to a byte array.
static const char *const TAG
Definition hub_core.cpp:37
LR1121 radio driver for IO-Homecontrol.
SX1262 radio driver for IO-Homecontrol.
SX1276 radio driver for IO-Homecontrol.
YAML-declared device metadata for registration; defaults match an undeclared device.
Runtime state of a paired IO‑Homecontrol device.
Parsed IO‑Homecontrol frame (CTRL0/1 + addresses + command + data).
Definition proto_frame.h:93
What a 1W command attempt did — the only feedback this feature can ever produce.
Vendor-divergent 1W wire settings for a controller identity.
bool profile_is_a_guess
true when manufacturer matched no known 1W wire profile.
EnrollGesture enroll_gesture
Which enrollment gesture this manufacturer's actuators expect.
Raw packet received from the radio.
bool active
True when the YAML tuning: block is present.
uint16_t normal_start_preamble
Preamble for a directed start frame to a non-low-power target.
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...
bool normal_start_preamble_from_yaml
True when normal_start_preamble: appeared in YAML.
One numeric tuning parameter: its wire name plus accessors over TuningConfig.
void(*) set(TuningConfig &, float)
Write a new value (narrowed to the field type).
bool applies_to_radio
True if changes must be re-applied to the radio.
float(*) get(const TuningConfig &)
Read the current value as a float.
One select tuning parameter: its wire name plus string accessors over TuningConfig.
bool(*) set(TuningConfig &, const std::string &)
Parse/apply an option; false if unparseable.
std::string(*) get(const TuningConfig &)
Read the current option string.
bool applies_to_radio
True if changes must be re-applied to the radio.
Runtime tuning configuration for pairing and radio diagnostics.
Table-driven registry of runtime tuning parameters.