From 3d0c47113ec5f364febee2f8a08e7ba57e10c02e Mon Sep 17 00:00:00 2001 From: William Emfinger Date: Tue, 17 Nov 2026 20:00:56 -0600 Subject: [PATCH 1/2] feat(switch2_pro): application lifecycle callbacks and control surface Adds the integration surface an application needs to drive its own connection manager, LEDs/telemetry, and pairing-record store around the emulated controller. All additions are additive and opt-in; existing users are unaffected. - Config::callbacks (Callbacks): on_connected, on_disconnected(reason), on_paired, on_input_streaming(bool), mirroring the polling getters so an app can be notified instead of polling. on_input_streaming is edge-triggered off is_input_streaming(); all fire from the NimBLE host-task context (documented). - is_initialized(), is_advertising(), stop_advertising() (also stops the wake re-advertiser), disconnect() (terminate the link, keep the bond). - static erase_stored_bond() erases the persisted bond from NVS with no live instance; Config::start_fresh makes init() drop any stored bond and advertise for a fresh pairing instead of reconnecting. - bonded_console_address() returns the bonded console's address (or nullopt). - Pro2InputReport::set_battery_percent(pct, charging, external) quantises a 0..100 percentage to the report's 0..9 level. Builds the switch2_pro example on esp32s3. Co-Authored-By: Claude Opus 4.8 Claude-Session: https://claude.ai/code/session_01DFjjnq3XCTRAXENSxsCxJU --- .../switch2_pro/include/switch2_pro.hpp | 78 +++++++++++++++ .../include/switch2_pro_report.hpp | 13 +++ components/switch2_pro/src/switch2_pro.cpp | 99 +++++++++++++++++++ 3 files changed, 190 insertions(+) diff --git a/components/switch2_pro/include/switch2_pro.hpp b/components/switch2_pro/include/switch2_pro.hpp index f24f5f9182..892b7a259c 100644 --- a/components/switch2_pro/include/switch2_pro.hpp +++ b/components/switch2_pro/include/switch2_pro.hpp @@ -5,6 +5,7 @@ #include #include #include +#include #include #include #include @@ -48,6 +49,28 @@ namespace espp { /// \snippet switch2_pro_example.cpp switch2_pro example class Switch2Pro : public BaseComponent { public: + /// Optional application callbacks for the connection/pairing lifecycle. All + /// are optional; leave any null to ignore it. They mirror the polling getters + /// (is_connected / is_paired / is_input_streaming) for an application that + /// would rather be notified than poll from its IO tick. + /// @note Every callback is invoked from the NimBLE host-task context. Keep + /// them short and non-blocking, and never destroy this Switch2Pro from + /// one (teardown deinitialises NimBLE from within its own callback). + struct Callbacks { + /// A console established the link (before pairing / encryption / input + /// subscription; see is_input_streaming for when reports actually flow). + std::function on_connected{nullptr}; + /// The link dropped; `reason` is the simplified BleGattServer reason. + std::function on_disconnected{nullptr}; + /// The 0x15 pairing handshake finished and a bond now exists. Fires on a + /// fresh pairing, not on a bonded reconnect (which does not re-pair). + std::function on_paired{nullptr}; + /// is_input_streaming() changed: true once the console has subscribed to the + /// input characteristic on an encrypted link (reports are flowing), false + /// when that stops (e.g. on disconnect). + std::function on_input_streaming{nullptr}; + }; + /// Configuration for the controller. struct Config { std::string device_name{"Pro Controller"}; ///< BLE advertised name. @@ -85,6 +108,14 @@ class Switch2Pro : public BaseComponent { /// packet-count-based one (our-side tx-credit accumulation — survives ~N× /// longer). Ignored in on-change mode. uint32_t continuous_stream_divisor{1}; + /// Start in fresh-pairing (discovery) mode even if a bond is stored: init() + /// erases any persisted bond first, so the controller advertises for a new + /// pairing instead of reconnecting/waking a previously-bonded console. Use + /// this to factory-reset the emulated controller at boot without the + /// load-bond / advertise-reconnect / clear / advertise-discovery flicker. + bool start_fresh{false}; + /// Optional lifecycle callbacks (see Callbacks). Default: none (poll instead). + Callbacks callbacks{}; Logger::Verbosity log_level{Logger::Verbosity::INFO}; ///< Verbosity of the logger. }; @@ -97,6 +128,8 @@ class Switch2Pro : public BaseComponent { , continuous_streaming_enabled_(config.continuous_streaming_enabled) , continuous_stream_divisor_( config.continuous_stream_divisor ? config.continuous_stream_divisor : 1) + , start_fresh_(config.start_fresh) + , callbacks_(config.callbacks) , ble_gatt_server_({.callbacks = {}, .log_level = Logger::Verbosity::WARN}) {} /// Stop the input-streaming task on teardown. @@ -140,6 +173,41 @@ class Switch2Pro : public BaseComponent { return input_subscribed_ && encrypted_ && active_conn_handle_ != 0xffff; } + /// Whether init() has completed successfully, i.e. the radio is up as this + /// controller. False before init() and after a failed init(). Lets a host + /// that manages one BLE personality at a time ask "is the radio mine?" + /// without tracking it in parallel. + bool is_initialized() const { return initialized_; } + + /// Whether the controller is currently broadcasting any advertisement + /// (discovery, reconnect or wake). + bool is_advertising() const; + + /// Stop advertising now and stop the wake re-advertiser, so no pairing / + /// reconnect / wake window stays on the air. Does NOT drop an existing + /// connection (use disconnect() for that). Safe to call when not advertising. + void stop_advertising(); + + /// Terminate the current console connection, if any. The bond is kept (this + /// is not clear_bond()); the console can reconnect. @return true if a + /// disconnect was requested (a connection was live), false if there was none. + bool disconnect(); + + /// The bonded console's identity address, if a bond exists (from a completed + /// pairing this boot or one restored from NVS). Lets a host that keeps its own + /// pairing records name the console. @return the address, or nullopt when no + /// bond is stored. + std::optional bonded_console_address() const; + + /// Erase the persisted bond (console address + LTK) from NVS WITHOUT a live + /// instance, for a host that keeps its own pairing list and wants to forget + /// the stored console while the radio is up as a different personality. Unlike + /// clear_bond() this touches only NVS — it does not remove any live NimBLE + /// security record or re-advertise (there may be no stack up) — so the next + /// Switch2Pro init() simply starts in discovery mode. @return true if a bond + /// was erased or none was stored; false only on an NVS error. + static bool erase_stored_bond(); + /// Store the latest controller state. This does NOT send — a driver-owned /// streaming task notifies the newest stored report once per connection /// interval (continuously, like a real controller), so you can call this as @@ -262,6 +330,10 @@ class Switch2Pro : public BaseComponent { /// Track CCCD subscribe/unsubscribe so we only stream input when the console /// has asked for it (updates input_subscribed_ for the 0x000e characteristic). void on_subscribe(NimBLECharacteristic *characteristic, uint16_t sub_value); + /// Recompute is_input_streaming() and, if it changed since the last report, + /// invoke callbacks_.on_input_streaming. Called from the subscribe / auth- + /// complete / disconnect sites that flip the underlying atomics. + void notify_input_streaming_state(); /// NimBLE NOTIFY_TX callback for `characteristic`. Maintains diagnostics only: /// it decrements notify_in_flight_ and advances the tx-completion telemetry /// (tx_completions_/last_tx_complete_us_). It is NOT the stream's backpressure — @@ -281,6 +353,12 @@ class Switch2Pro : public BaseComponent { bool continuous_streaming_enabled_; ///< see Config::continuous_streaming_enabled uint32_t continuous_stream_divisor_; ///< see Config::continuous_stream_divisor (rate-halving probe) + bool start_fresh_; ///< see Config::start_fresh (erase any bond in init()) + Callbacks callbacks_; ///< application lifecycle callbacks (see Config::callbacks) + /// Last is_input_streaming() value reported through callbacks_.on_input_streaming, + /// so the callback fires only on an actual edge. Written/read from the NimBLE + /// callback thread(s). + std::atomic input_streaming_reported_{false}; std::shared_ptr wake_timer_; ///< re-issues the wake advertisement until connected BleGattServer ble_gatt_server_; diff --git a/components/switch2_pro/include/switch2_pro_report.hpp b/components/switch2_pro/include/switch2_pro_report.hpp index 93ae2ed9f6..8eb1f80e53 100644 --- a/components/switch2_pro/include/switch2_pro_report.hpp +++ b/components/switch2_pro/include/switch2_pro_report.hpp @@ -50,6 +50,19 @@ class Pro2InputReport { (external_power ? 0x01 : 0x00)); } + /// Convenience over set_power() that takes a battery percentage (0..100) and + /// quantises it to the report's 0..9 level, so an application that tracks a + /// percentage does not have to pick its own mapping. 0% -> 0, 100% -> 9, and + /// the range in between is rounded to the nearest level; values above 100 are + /// clamped. charging/external-power flags are passed through. + /// @param percent Battery charge, 0..100 (clamped). + void set_battery_percent(uint8_t percent, bool charging = false, bool external_power = false) { + const uint8_t pct = percent > 100 ? 100 : percent; + // round(pct/100*9) without floating point: (pct*9 + 50) / 100 + const uint8_t level = static_cast((static_cast(pct) * 9 + 50) / 100); + set_power(level, charging, external_power); + } + // Face / shoulder / system buttons. void set_a(bool v) { set_bit(2, 0x02, v); } void set_b(bool v) { set_bit(2, 0x01, v); } diff --git a/components/switch2_pro/src/switch2_pro.cpp b/components/switch2_pro/src/switch2_pro.cpp index f0ae672141..48f65f541a 100644 --- a/components/switch2_pro/src/switch2_pro.cpp +++ b/components/switch2_pro/src/switch2_pro.cpp @@ -146,6 +146,13 @@ bool Switch2Pro::init() { "{:02x}:{:02x}:{:02x}", rnd[5], rnd[4], rnd[3], rnd[2], rnd[1], rnd[0]); } + // Caller asked to start fresh: drop any persisted bond first, so load_bond() + // below finds none and we advertise for a new pairing instead of trying to + // reconnect/wake a previously-bonded console. + if (start_fresh_) { + logger_.info("start_fresh: erasing any stored bond before advertising for a fresh pairing"); + erase_stored_bond(); + } // Load any persisted bond BEFORE configure_security (which otherwise clears // bonds): if present we reconnect instead of re-pairing. reconnect_mode_ = load_bond(); @@ -300,6 +307,8 @@ void Switch2Pro::configure_callbacks() { logger_.info("connected: peer={} interval={:.2f}ms supervision={}ms latency={}", info.getAddress().toString(), info.getConnInterval() * 1.25f, info.getConnTimeout() * 10, info.getConnLatency()); + if (callbacks_.on_connected) + callbacks_.on_connected(); // NOTE: we deliberately do NOT initiate a connection-parameter update here. // NimBLE floors ble_gap_update_params at the 7.5 ms spec minimum, so we could // not request the console's 5 ms even if we wanted to — and we don't need to: @@ -340,6 +349,11 @@ void Switch2Pro::configure_callbacks() { input_subscribed_ = false; encrypted_ = false; // require a fresh encrypted session before streaming again active_conn_handle_ = 0xffff; // so the wake timer knows we're disconnected + // input streaming necessarily stopped with the link; report the edge (and the + // disconnect) before we re-advertise. + notify_input_streaming_state(); + if (callbacks_.on_disconnected) + callbacks_.on_disconnected(r); advertise(); }; callbacks.conn_params_update_callback = [this](const NimBLEConnInfo &info) { @@ -375,6 +389,9 @@ void Switch2Pro::configure_callbacks() { wake_pending_ = false; boot_wake_pending_ = false; } + // Encryption settling can complete the is_input_streaming() condition (if the + // console already subscribed); report the edge if so. + notify_input_streaming_state(); }; ble_gatt_server_.set_callbacks(callbacks); } @@ -766,6 +783,20 @@ void Switch2Pro::on_subscribe(NimBLECharacteristic *characteristic, uint16_t sub const bool subscribed = (sub_value != 0); input_subscribed_.store(subscribed); logger_.info("input-report streaming {}", subscribed ? "ENABLED (0x000e)" : "disabled"); + // Subscribe/unsubscribe can flip is_input_streaming() (if the link is already + // encrypted); report the edge. + notify_input_streaming_state(); + } +} + +void Switch2Pro::notify_input_streaming_state() { + const bool now_streaming = is_input_streaming(); + // Edge-trigger: only call the app when the state actually changed. exchange() + // returns the previous reported value atomically, so concurrent callers (all on + // the NimBLE host task in practice) still fire the callback exactly once per edge. + if (input_streaming_reported_.exchange(now_streaming) != now_streaming) { + if (callbacks_.on_input_streaming) + callbacks_.on_input_streaming(now_streaming); } } @@ -1224,6 +1255,72 @@ bool Switch2Pro::clear_bond() { return ok; } +bool Switch2Pro::erase_stored_bond() { + // Static: erase ONLY the NVS bond blob. With no instance there is no NimBLE + // security record to remove and no advertising to restart. A missing bond is + // success; mirrors the NVS half of clear_bond(). + espp::Nvs nvs; + std::error_code ec; + espp::NvsHandle handle = nvs.get_handle(kNvsNamespace, ec); + if (ec) + return false; // could not open the namespace (a real NVS error) + std::vector existing; + std::error_code get_ec; + handle.get(kNvsBondKey, existing, get_ec); + // The espp NVS error category is per-translation-unit (anonymous namespace), so + // match not-found by value + category name rather than by error_code equality. + const bool not_found = get_ec.value() == static_cast(NvsErrc::Key_Not_Found) && + std::strcmp(get_ec.category().name(), "nvs") == 0; + if (!get_ec) { // a bond is stored — erase it and commit + std::error_code erase_ec, commit_ec; + handle.erase(kNvsBondKey, erase_ec); + handle.commit(commit_ec); + return !erase_ec && !commit_ec; + } + return not_found; // no bond stored = success; a real read error = failure +} + +bool Switch2Pro::is_advertising() const { + NimBLEAdvertising *adv = NimBLEDevice::getAdvertising(); + return adv != nullptr && adv->isAdvertising(); +} + +void Switch2Pro::stop_advertising() { + // Stop the wake re-advertiser first (and clear the wake latches) so it does not + // put a fresh advertisement back on the air, then stop advertising. Stopping the + // timer here (app context) is safe; it must never be stopped/joined from a + // NimBLE host-callback context. + wake_pending_ = false; + boot_wake_pending_ = false; + if (wake_timer_) + wake_timer_->stop(); + ble_gatt_server_.stop_advertising(); +} + +bool Switch2Pro::disconnect() { + const uint16_t h = active_conn_handle_.load(); + if (h == 0xffff) + return false; + const int rc = ble_gap_terminate(h, BLE_ERR_REM_USER_CONN_TERM); + if (rc != 0 && rc != BLE_HS_ENOTCONN) { + logger_.error("disconnect: ble_gap_terminate failed (rc={})", rc); + return false; + } + return true; +} + +std::optional Switch2Pro::bonded_console_address() const { + std::lock_guard lk(bond_mutex_); + if (!paired_.load()) + return std::nullopt; + // bond_peer_val_ is the console's identity address in wire (little-endian) + // order, bond_peer_type_ its address type (see save_bond/load_bond). + ble_addr_t a{}; + a.type = bond_peer_type_; + std::copy(bond_peer_val_.begin(), bond_peer_val_.end(), a.val); + return NimBLEAddress(a); +} + void Switch2Pro::handle_pairing(bool via_vibration_command, uint8_t transport, PairingSub sub, const uint8_t *payload, size_t len) { // Pairing responses use byte4=0x10, byte5=0x78, and a payload that begins @@ -1342,6 +1439,8 @@ void Switch2Pro::handle_pairing(bool via_vibration_command, uint8_t transport, P // without re-running the pairing exchange. save_bond(); reconnect_mode_ = true; + if (callbacks_.on_paired) + callbacks_.on_paired(); break; } default: From 1304f8d1e0e75fc1028407a2967762a13e2a0ba0 Mon Sep 17 00:00:00 2001 From: William Emfinger Date: Wed, 18 Nov 2026 09:01:09 -0600 Subject: [PATCH 2/2] fix(switch2_pro): address review findings on the application API - is_advertising(): use auto for NimBLEDevice::getAdvertising() so it builds under CONFIG_BT_NIMBLE_EXT_ADV (where it returns NimBLEExtAdvertising*), not only the legacy-advertising config. - bonded_console_address(): return the stable identity (host_addr_, the 0x15 exchange address the component trusts for reconnect) instead of bond_peer_val_, which is the NimBLE connection address and may be a rotating private address (no SMP resolution here). host_addr_ is set during the handshake before paired_ flips, so this also removes the narrow FINALISE race the old getter had. - stop_advertising(): latch readvertise_suppressed_ so the disconnect callback does not auto re-advertise afterwards; a "disconnect() then stop_advertising()" go-dark sequence is now race-free regardless of when the disconnect callback runs. wake_console() clears the latch. - disconnect(): return false when the link was already gone (BLE_HS_ENOTCONN), matching the documented "true only if a connection was live". - erase_stored_bond(): document the NVS-initialised precondition; start_fresh now logs an erase failure instead of ignoring the return value. Builds the switch2_pro example on esp32s3. Co-Authored-By: Claude Opus 4.8 Claude-Session: https://claude.ai/code/session_01DFjjnq3XCTRAXENSxsCxJU --- .../switch2_pro/include/switch2_pro.hpp | 29 +++++++---- components/switch2_pro/src/switch2_pro.cpp | 48 ++++++++++++++----- 2 files changed, 57 insertions(+), 20 deletions(-) diff --git a/components/switch2_pro/include/switch2_pro.hpp b/components/switch2_pro/include/switch2_pro.hpp index 892b7a259c..298e3f5563 100644 --- a/components/switch2_pro/include/switch2_pro.hpp +++ b/components/switch2_pro/include/switch2_pro.hpp @@ -184,8 +184,12 @@ class Switch2Pro : public BaseComponent { bool is_advertising() const; /// Stop advertising now and stop the wake re-advertiser, so no pairing / - /// reconnect / wake window stays on the air. Does NOT drop an existing - /// connection (use disconnect() for that). Safe to call when not advertising. + /// reconnect / wake window stays on the air. Also suppresses the automatic + /// re-advertise that a disconnect would otherwise trigger, so the controller + /// stays dark until an explicit wake_console() (or a re-init); this makes a + /// "disconnect() then stop_advertising()" go-dark sequence race-free regardless + /// of when the disconnect callback runs. Does NOT drop an existing connection + /// (use disconnect() for that). Safe to call when not advertising. void stop_advertising(); /// Terminate the current console connection, if any. The bond is kept (this @@ -193,10 +197,13 @@ class Switch2Pro : public BaseComponent { /// disconnect was requested (a connection was live), false if there was none. bool disconnect(); - /// The bonded console's identity address, if a bond exists (from a completed - /// pairing this boot or one restored from NVS). Lets a host that keeps its own - /// pairing records name the console. @return the address, or nullopt when no - /// bond is stored. + /// The bonded console's stable identity address, if a bond exists (from a + /// completed pairing this boot or one restored from NVS) — the value the + /// component uses to recognise the console on reconnect, not the (possibly + /// rotating) connection address. Lets a host that keeps its own pairing records + /// name the console. The identity is matched at the application layer (the 0x15 + /// exchange), not via SMP, so its NimBLE address type is not tracked and is + /// reported as public. @return the address, or nullopt when no bond is stored. std::optional bonded_console_address() const; /// Erase the persisted bond (console address + LTK) from NVS WITHOUT a live @@ -204,8 +211,9 @@ class Switch2Pro : public BaseComponent { /// the stored console while the radio is up as a different personality. Unlike /// clear_bond() this touches only NVS — it does not remove any live NimBLE /// security record or re-advertise (there may be no stack up) — so the next - /// Switch2Pro init() simply starts in discovery mode. @return true if a bond - /// was erased or none was stored; false only on an NVS error. + /// Switch2Pro init() simply starts in discovery mode. Requires NVS to be + /// initialised (nvs_flash_init); if NVS cannot be opened this returns false. + /// @return true if a bond was erased or none was stored; false on an NVS error. static bool erase_stored_bond(); /// Store the latest controller state. This does NOT send — a driver-owned @@ -359,6 +367,11 @@ class Switch2Pro : public BaseComponent { /// so the callback fires only on an actual edge. Written/read from the NimBLE /// callback thread(s). std::atomic input_streaming_reported_{false}; + /// stop_advertising() latched this: the disconnect callback must NOT auto + /// re-advertise, so the controller stays off the air until an explicit + /// wake_console() / re-init. Written by stop_advertising() (app task) and + /// wake_console() (app task), read by the disconnect callback (host task). + std::atomic readvertise_suppressed_{false}; std::shared_ptr wake_timer_; ///< re-issues the wake advertisement until connected BleGattServer ble_gatt_server_; diff --git a/components/switch2_pro/src/switch2_pro.cpp b/components/switch2_pro/src/switch2_pro.cpp index 48f65f541a..138a152a6a 100644 --- a/components/switch2_pro/src/switch2_pro.cpp +++ b/components/switch2_pro/src/switch2_pro.cpp @@ -151,7 +151,9 @@ bool Switch2Pro::init() { // reconnect/wake a previously-bonded console. if (start_fresh_) { logger_.info("start_fresh: erasing any stored bond before advertising for a fresh pairing"); - erase_stored_bond(); + if (!erase_stored_bond()) + logger_.error("start_fresh: erasing the stored bond failed (NVS error) — a prior bond may " + "still be loaded below"); } // Load any persisted bond BEFORE configure_security (which otherwise clears // bonds): if present we reconnect instead of re-pairing. @@ -354,7 +356,13 @@ void Switch2Pro::configure_callbacks() { notify_input_streaming_state(); if (callbacks_.on_disconnected) callbacks_.on_disconnected(r); - advertise(); + // Normally a disconnect re-advertises so the console can reconnect. Skip it if + // the app has called stop_advertising(): it wants the controller to stay dark + // until an explicit wake_console() / re-init. + if (readvertise_suppressed_) + logger_.info("disconnect: advertising suppressed (stop_advertising) — staying off the air"); + else + advertise(); }; callbacks.conn_params_update_callback = [this](const NimBLEConnInfo &info) { // Fires when ANY connection-parameter-update procedure completes — including @@ -624,6 +632,9 @@ bool Switch2Pro::wake_console() { logger_.info("wake: broadcasting wake advertisement (user-requested)"); wake_pending_ = true; // keep the wake variant on the air (across any transient // connect/drop while the console boots) until connected + // An explicit wake re-enables the automatic re-advertise a prior + // stop_advertising() had suppressed. + readvertise_suppressed_ = false; if (!start_advertising(AdvMode::Wake, host_addr)) { wake_pending_ = false; // nothing is on the air — don't leave the latch set logger_.error("wake: failed to start the wake advertisement"); @@ -1281,15 +1292,21 @@ bool Switch2Pro::erase_stored_bond() { } bool Switch2Pro::is_advertising() const { - NimBLEAdvertising *adv = NimBLEDevice::getAdvertising(); + // auto: NimBLEDevice::getAdvertising() returns NimBLEAdvertising* or + // NimBLEExtAdvertising* depending on CONFIG_BT_NIMBLE_EXT_ADV; both expose + // isAdvertising(), so this stays correct under either advertising config. + auto *adv = NimBLEDevice::getAdvertising(); return adv != nullptr && adv->isAdvertising(); } void Switch2Pro::stop_advertising() { - // Stop the wake re-advertiser first (and clear the wake latches) so it does not - // put a fresh advertisement back on the air, then stop advertising. Stopping the - // timer here (app context) is safe; it must never be stopped/joined from a - // NimBLE host-callback context. + // Latch the suppression BEFORE stopping, so a disconnect callback that races + // this (e.g. after a disconnect()) sees it and does not re-advertise. Stop the + // wake re-advertiser and clear the wake latches so nothing puts a fresh + // advertisement back on the air, then stop advertising. Stopping the timer here + // (app context) is safe; it must never be stopped/joined from a NimBLE + // host-callback context. + readvertise_suppressed_ = true; wake_pending_ = false; boot_wake_pending_ = false; if (wake_timer_) @@ -1302,7 +1319,9 @@ bool Switch2Pro::disconnect() { if (h == 0xffff) return false; const int rc = ble_gap_terminate(h, BLE_ERR_REM_USER_CONN_TERM); - if (rc != 0 && rc != BLE_HS_ENOTCONN) { + if (rc == BLE_HS_ENOTCONN) + return false; // the link was already gone — nothing was terminated + if (rc != 0) { logger_.error("disconnect: ble_gap_terminate failed (rc={})", rc); return false; } @@ -1313,11 +1332,16 @@ std::optional Switch2Pro::bonded_console_address() const { std::lock_guard lk(bond_mutex_); if (!paired_.load()) return std::nullopt; - // bond_peer_val_ is the console's identity address in wire (little-endian) - // order, bond_peer_type_ its address type (see save_bond/load_bond). + // Return the console's STABLE IDENTITY (host_addr_, from the 0x15 exchange and + // persisted in the bond) — the value the component itself trusts for reconnect + // (see advertise()), set during the handshake before paired_ flips. NOT + // bond_peer_val_, which is the NimBLE connection address and can be a rotating + // private address (this component does no SMP resolution). The identity is + // matched at the application layer, so its address type is not tracked; report + // it as public. host_addr_ is little-endian wire order, as ble_addr_t.val wants. ble_addr_t a{}; - a.type = bond_peer_type_; - std::copy(bond_peer_val_.begin(), bond_peer_val_.end(), a.val); + a.type = BLE_ADDR_PUBLIC; + std::copy(host_addr_.begin(), host_addr_.end(), a.val); return NimBLEAddress(a); }