Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
91 changes: 91 additions & 0 deletions components/switch2_pro/include/switch2_pro.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
#include <chrono>
#include <condition_variable>
#include <cstdint>
#include <functional>
#include <memory>
#include <mutex>
#include <optional>
Expand Down Expand Up @@ -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<void()> on_connected{nullptr};
/// The link dropped; `reason` is the simplified BleGattServer reason.
std::function<void(BleGattServer::DisconnectReason)> 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<void()> 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<void(bool)> on_input_streaming{nullptr};
};

/// Configuration for the controller.
struct Config {
std::string device_name{"Pro Controller"}; ///< BLE advertised name.
Expand Down Expand Up @@ -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.
};

Expand All @@ -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.
Expand Down Expand Up @@ -140,6 +173,49 @@ 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. 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
/// 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 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<NimBLEAddress> 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. 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
/// streaming task notifies the newest stored report once per connection
/// interval (continuously, like a real controller), so you can call this as
Expand Down Expand Up @@ -262,6 +338,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 —
Expand All @@ -281,6 +361,17 @@ 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<bool> 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<bool> readvertise_suppressed_{false};
std::shared_ptr<espp::Timer> wake_timer_; ///< re-issues the wake advertisement until connected
BleGattServer ble_gatt_server_;

Expand Down
13 changes: 13 additions & 0 deletions components/switch2_pro/include/switch2_pro_report.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -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<uint8_t>((static_cast<uint16_t>(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); }
Expand Down
125 changes: 124 additions & 1 deletion components/switch2_pro/src/switch2_pro.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,15 @@ 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");
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.
reconnect_mode_ = load_bond();
Expand Down Expand Up @@ -300,6 +309,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:
Expand Down Expand Up @@ -340,7 +351,18 @@ 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
advertise();
// 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);
// 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
Expand Down Expand Up @@ -375,6 +397,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);
}
Expand Down Expand Up @@ -607,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");
Expand Down Expand Up @@ -766,6 +794,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);
}
}

Expand Down Expand Up @@ -1224,6 +1266,85 @@ 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<uint8_t> 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<int>(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 {
// 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() {
// 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_)
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 == 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;
}
return true;
}

std::optional<NimBLEAddress> Switch2Pro::bonded_console_address() const {
std::lock_guard<std::mutex> lk(bond_mutex_);
if (!paired_.load())
return std::nullopt;
// 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 = BLE_ADDR_PUBLIC;
std::copy(host_addr_.begin(), host_addr_.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
Expand Down Expand Up @@ -1342,6 +1463,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:
Expand Down
Loading