Modern Apps git

← Modern-Apps.git

tracker: fix UWB session start, logging, adv restart and teardown

Commit
66c460ebd6c09b9b108f7622788fc2a3127f79fc
Author
vayun-mathur <[email protected]>
When
2026-08-22 14:35 UTC (3 months ago)
Parents
0383413

Diff

firmware/findfamily-tracker/README.md
diff --git a/firmware/findfamily-tracker/README.md b/firmware/findfamily-tracker/README.mdindex 597ce84bb8..3e6d4e8194 100644--- a/firmware/findfamily-tracker/README.md+++ b/firmware/findfamily-tracker/README.md@@ -88,7 +88,9 @@ Logs come out of the on-board J-Link CDC UART at 115200 (COM4 on this machine). Otherwise → pairing mode, so a fresh board is bindable without touching the button.  **Button** (the kit's Button 1, `sw0`):-- long press (≥ 2 s) → pairing mode, to re-bind or to resync the clock+- long press (≥ 2 s) → pairing mode for `CONFIG_FF_TRACKER_PAIRING_TIMEOUT_S`, then back to+  beaconing. This does **not** re-bind: a provisioned tracker refuses provisioning writes+  (the anti-theft lock), and nothing unbinds one today — `ff_store_clear()` has no caller. - short press → mute/unmute the beacon  **Advertising** uses two modes on one state machine, arranged so only the phone's beacon@@ -97,12 +99,14 @@ scanner needed changing: - **Pairing** — *legacy* connectable advertising of the unprovisioned service   (`…2f01…`). Flags + a 128-bit UUID is 21 bytes, comfortably inside the legacy budget,   so `TrackerProvisioner.unprovisioned()` still finds it with default `ScanSettings`.-- **Beacon** — *extended* connectable advertising of `[16B epochId][1B battery%]` as-  service data under `…2f00…`. This one **cannot** be legacy: the AD structure costs+- **Beacon** — *extended* **non-connectable** advertising of `[16B epochId][1B battery%]`+  as service data under `…2f00…`. This one **cannot** be legacy: the AD structure costs   `1B len + 1B type + 16B UUID + 17B payload = 35 bytes` against a 31-byte limit, and the   UUID can't be shortened because the phone looks the service data up by it. Secondary PHY-  stays at 1M so the phone needs no coded-PHY scan config, and it stays connectable so the-  owner can still write UWB session params after binding.+  stays at 1M so the phone needs no coded-PHY scan config. Connectability is a **third,+  legacy, dataless set** running alongside it, so the owner can still write UWB session+  params after binding — a connectable extended set cannot carry advertising data at all,+  which is why the two are separate. See `beacon_param` in `src/tracker_ble.c`.  **Time.** The board has no battery-backed RTC, but `epochId` needs `unix_seconds / 900`, so the provisioning blob carries a timestamp and time is kept as@@ -153,22 +157,22 @@ nrfutil toolchain-manager launch --ncs-version v3.4.0 -- `  Quote the `-D` arguments: PowerShell otherwise splits `uwb.conf` at the dot. -### State: builds, links, runs — but the stack does not come up yet+### State: the stack comes up; ranging does not work yet  Verified on hardware:-- the image builds and links clean (58% flash, 47% RAM) and BLE crowd-finding is-  unaffected — the beacon keeps working in the UWB image;+- the image builds and links clean and BLE crowd-finding is unaffected — the beacon keeps+  working in the UWB image; - the DW3110 answers a direct device-id read over SPI with **`0xdeca0302`**, logged at   startup. That clears the wiring, the `dw3110` devicetree node, chip-select handling and-  the SPI mode.--Not working: `qplatform_init()` returns `QERR_EADDRNOTAVAIL` (-1), so Qorvo's driver-rejects the part even though the bus is demonstrably fine. The fault is somewhere in the-glue below the driver rather than in the hardware — most likely `qspi_transceive` in-`firmware/qorvo-uwb/src/qspi_zephyr.c` (chip-select framing across the driver's-header-then-body transfers is the first thing to check) or the reset sequence in-`qhal_extras_zephyr.c`. **No ranging has been attempted**, and nothing here should be-taken as evidence that FiRa interop with the phone works.+  the SPI mode;+- `qplatform_init()` now succeeds and the Qorvo stack initialises, so ranging has been+  attempted end to end against a phone. It fails: the phone reports UCI RangingStatus+  `0x21` (RX timeout) on every round for its whole 10 s and then drops the controlee, with+  nothing logged on the tracker side.++That failure is being worked through against `docs/DISCREPANCIES.md`, which orders the+candidates and cites each one. Nothing in the current tree has been re-verified on hardware+since those fixes landed, so treat FiRa interop as unproven.  ### What the glue replaces, and why 
firmware/findfamily-tracker/prj.conf
diff --git a/firmware/findfamily-tracker/prj.conf b/firmware/findfamily-tracker/prj.confindex a0cd27c9f5..eaf4bf4714 100644--- a/firmware/findfamily-tracker/prj.conf+++ b/firmware/findfamily-tracker/prj.conf@@ -74,6 +74,26 @@ CONFIG_UART_CONSOLE=y CONFIG_LOG_MODE_DEFERRED=y CONFIG_LOG_BUFFER_SIZE=4096 +# Deferred logging processes every message on one thread, created at+# K_LOWEST_APPLICATION_THREAD_PRIO (14 here) unless told otherwise — below both UWB threads,+# so a busy UWB thread erased the record of what it was doing. Raising that thread above them+# is the fix; CONFIG_LOG_MODE_IMMEDIATE is not. Immediate mode "is processed in the context of+# the call" (Kconfig.mode), i.e. a LOG_INF from the Bluetooth RX thread sits in uart_poll_out+# for milliseconds per line, which is what made every GATT connection fail with Android+# status 133. A separate thread cannot do that to it: the RX thread is cooperative+# (K_PRIO_COOP(CONFIG_BT_RX_PRIO), hci_core.c) so no preemptible priority preempts it.+#+# 3 rather than something higher: above both UWB threads (6 and 7) and level with the Qorvo+# MAC's NORMAL band, which timeslicing then shares with rather than starving.+CONFIG_LOG_PROCESS_THREAD_CUSTOM_PRIORITY=y+CONFIG_LOG_PROCESS_THREAD_PRIORITY=3++# CONFIG_LOG_PRINTK is deliberately left at its default (y), so printk() stays inside the+# logging subsystem. Turning it off would make the ff_uwb_start() markers synchronous, but+# it also sends them to *the console* — the CDC UART, the path that drops lines (see below).+# The lossless path is CONFIG_LOG_BACKEND_RTT, and a log backend only ever sees LOG_*, never+# printk. Bring-up markers therefore go through LOG_INF, which reaches both backends.+ # Also log over SEGGER RTT. The CDC UART path loses lines — a capture that should have held # ~120 once-per-second beacon messages held 46 — which is bad enough to have produced # contradictory evidence while debugging (a GATT write the phone reported as successful and
firmware/findfamily-tracker/src/ff_tracker.h
diff --git a/firmware/findfamily-tracker/src/ff_tracker.h b/firmware/findfamily-tracker/src/ff_tracker.hindex b9307bf87a..1cf9dba50d 100644--- a/firmware/findfamily-tracker/src/ff_tracker.h+++ b/firmware/findfamily-tracker/src/ff_tracker.h@@ -23,7 +23,8 @@ #define FF_PROVISION_BLOB_LEN 48 #define FF_PROVISION_BLOB_LEN_NO_TIME 40 -/* TrackerUwbGatt.encodeSessionParams: [2B addr][4B sessionId BE][1B ch][1B preamble] */+/* TrackerUwbGatt.encodeSessionParams:+ * [2B addr little-endian][4B sessionId BE][1B ch][1B preamble] */ #define FF_UWB_PARAMS_LEN 8  /* Service data payload: [16B epochId][1B battery%] */@@ -82,7 +83,8 @@ enum ff_ble_mode { 	FF_BLE_MODE_IDLE, 	/* Legacy connectable adv of the unprovisioned service, awaiting a bind. */ 	FF_BLE_MODE_PAIRING,-	/* Extended connectable adv carrying the rotating epoch id. */+	/* Extended non-connectable adv carrying the rotating epoch id, plus a separate+	 * legacy connectable set so the owner can still write UWB session params. */ 	FF_BLE_MODE_BEACON, }; @@ -104,14 +106,18 @@ bool ff_ble_take_provision_event(void); bool ff_ble_take_uwb_params(uint8_t *out);  /*- * True once after a disconnect left the tracker in the wrong advertising mode. A- * connectable advertisement needs a free connection slot, so the switch to beacon mode- * right after a bind fails while the phone is still attached.+ * True once after a disconnect. Both cases need it: a mode we could not start while the+ * connection slot was taken, and — in beacon mode — the connectable set the controller+ * stopped when it accepted that connection.  */ bool ff_ble_take_readvertise_event(void); -/* The mode the tracker is meant to be in, which may differ from what actually started. */-enum ff_ble_mode ff_ble_desired_mode(void);+/*+ * Puts advertising back to what it should be after a disconnect. Not the same as+ * ff_ble_set_mode(): that returns early when the mode is already current, which is exactly+ * the case where the connectable set needs restarting.+ */+int ff_ble_readvertise(void);  /* Recomputes the epoch id and pushes fresh service data into the beacon adv set. */ int ff_ble_refresh_beacon(uint8_t battery_percent);
firmware/findfamily-tracker/src/main.c
diff --git a/firmware/findfamily-tracker/src/main.c b/firmware/findfamily-tracker/src/main.cindex 412ef0026a..f774213685 100644--- a/firmware/findfamily-tracker/src/main.c+++ b/firmware/findfamily-tracker/src/main.c@@ -6,8 +6,10 @@  * without needing the button.  *  * Button (the kit's Button 1):- *   long press  (>= 2 s) -> pairing mode, so an already-bound tracker can be re-bound- *                           or have its clock resynced+ *   long press  (>= 2 s) -> pairing mode for CONFIG_FF_TRACKER_PAIRING_TIMEOUT_S, then back+ *                           to beaconing. Note a bound tracker cannot be re-provisioned:+ *                           on_provision_write refuses writes once provisioned, which is+ *                           the anti-theft lock. Nothing unbinds a tracker today.  *   short press          -> toggle the beacon off/on ("mute"), for taking it on a plane  *                           or debugging whether a sighting really came from this board  *@@ -164,10 +166,20 @@ int main(void) { 	psa_status_t status; 	uint64_t last_persisted_epoch = 0;+	/* Non-zero while a long press has put a provisioned tracker into pairing mode. */+	int64_t pairing_deadline_ms = 0; 	int rc;  	LOG_INF("FindFamily tracker starting"); +	/*+	 * Before anything that can fail out of main(). Every `return 0` below leaves a live+	 * board with no advertising and no thread to recover it, which is precisely what+	 * the watchdog exists to bound: armed first, such a board reboots and retries+	 * instead of going quiet until someone unplugs it.+	 */+	watchdog_init();+ 	status = psa_crypto_init(); 	if (status != PSA_SUCCESS) { 		LOG_ERR("psa_crypto_init: %d", (int)status);@@ -191,9 +203,11 @@ int main(void) 	}  	(void)button_init();-	watchdog_init();  #ifdef CONFIG_FF_TRACKER_UWB+	/* Crypto, NVS and bt_enable() are behind us; don't make the UWB bring-up share+	 * their slice of the watchdog window. */+	watchdog_feed(); 	rc = ff_uwb_init(); 	if (rc) { 		LOG_ERR("uwb init failed: %d", rc);@@ -203,8 +217,14 @@ int main(void) 	if (tracker_state.provisioned) { 		LOG_INF("provisioned as userId=%llu", tracker_state.tracker_user_id); 		if (ff_ble_set_mode(FF_BLE_MODE_BEACON) != 0) {-			/* Provisioned but unusable — almost always a missing time base-			 * after a reset. Offer to be re-bound so it can resync. */+			/*+			 * Provisioned but unusable — almost always a missing time base,+			 * without which no epoch id would fall in the owner's search+			 * window. Nothing can currently repair that over the air+			 * (on_provision_write refuses writes once provisioned), so pairing+			 * mode here only makes the tracker visible to the owner's app+			 * rather than silent.+			 */ 			(void)ff_ble_set_mode(FF_BLE_MODE_PAIRING); 		} 	} else {@@ -226,8 +246,8 @@ int main(void) 		}  		if (ff_ble_take_readvertise_event()) {-			LOG_INF("connection slot free: re-applying advertising mode");-			(void)ff_ble_set_mode(ff_ble_desired_mode());+			LOG_INF("connection ended: re-applying advertising");+			(void)ff_ble_readvertise(); 		}  		{@@ -242,6 +262,36 @@ int main(void) 		if (atomic_cas(&pending_long_press, 1, 0)) { 			LOG_INF("long press: entering pairing mode"); 			(void)ff_ble_set_mode(FF_BLE_MODE_PAIRING);+			pairing_deadline_ms = 0;+			if (tracker_state.provisioned) {+				/*+				 * Bound trackers go back to beaconing on their own. Leaving+				 * the unprovisioned service on air indefinitely both stops+				 * crowd-finding and widens the window in which anything+				 * nearby could try to claim the tracker. An unprovisioned+				 * board has nothing to go back to, so it keeps advertising+				 * until it is bound.+				 *+				 * Measured from the press, not from when the advertisement+				 * starts: if it could not start yet — the connection slot was+				 * busy — ff_ble_readvertise() starts it later, and the window+				 * still expires rather than running unbounded.+				 */+				pairing_deadline_ms =+					k_uptime_get() ++					CONFIG_FF_TRACKER_PAIRING_TIMEOUT_S * MSEC_PER_SEC;+			}+		}+		if (pairing_deadline_ms != 0 && ff_ble_mode() == FF_BLE_MODE_PAIRING &&+		    k_uptime_get() >= pairing_deadline_ms) {+			pairing_deadline_ms = 0;+			LOG_INF("pairing window over: back to beaconing");+			if (ff_ble_set_mode(FF_BLE_MODE_BEACON) != 0) {+				/* Same fallback as at boot: beacon mode needs a time base,+				 * and a tracker advertising nothing at all is worse than one+				 * still offering to bind. */+				(void)ff_ble_set_mode(FF_BLE_MODE_PAIRING);+			} 		} 		if (atomic_cas(&pending_short_press, 1, 0)) { 			if (ff_ble_mode() == FF_BLE_MODE_BEACON) {
firmware/findfamily-tracker/src/tracker_ble.c
diff --git a/firmware/findfamily-tracker/src/tracker_ble.c b/firmware/findfamily-tracker/src/tracker_ble.cindex bfafa436e6..78223a3d5f 100644--- a/firmware/findfamily-tracker/src/tracker_ble.c+++ b/firmware/findfamily-tracker/src/tracker_ble.c@@ -9,12 +9,13 @@  *    TrackerProvisioner.unprovisioned() keeps working with default (legacy-only)  *    ScanSettings.  *- *  - Beacon: EXTENDED connectable adv of [16B epochId][1B battery] as service data.+ *  - Beacon: EXTENDED NON-connectable adv of [16B epochId][1B battery] as service data.  *    That AD structure is 18B of overhead + 17B of payload = 35 bytes, past the legacy  *    limit, and the full 16-byte UUID has to be on air because the phone reads it back  *    with ScanRecord.getServiceData(ParcelUuid). Secondary PHY is pinned to 1M so the- *    phone needs no coded-PHY scan configuration. Connectable so the owner can still- *    write UWB session params after binding.+ *    phone needs no coded-PHY scan configuration. Connectability runs on a third, legacy,+ *    dataless set alongside it — see beacon_param for why it cannot live on the beacon+ *    set itself.  *  * Both characteristics stay registered under the "unprovisioned" service for the  * device's whole life; provisioning only stops that service being advertised.@@ -131,14 +132,14 @@ static void on_disconnected(struct bt_conn *conn, uint8_t reason) 	LOG_INF("disconnected (reason=0x%02x)", reason);  	/*-	 * A connectable advertisement cannot start while the single connection slot is-	 * taken, so the switch to beacon mode after a bind fails with -ENOMEM and leaves-	 * the tracker silent. Now that the slot is free, have the main loop re-apply-	 * whatever mode we are supposed to be in.+	 * Always ask the main loop to re-apply advertising, not just when the mode we+	 * wanted differs from the one we got. The controller stops a connectable set when+	 * it yields a connection and Zephyr does not restart it, so after one owner+	 * connection connect_adv is down with both modes still BEACON — and the tracker is+	 * unreachable for every later find, which is what made each bring-up iteration need+	 * a power cycle. 	 */-	if (desired_mode != current_mode) {-		atomic_set(&pending_readvertise, 1);-	}+	atomic_set(&pending_readvertise, 1); }  BT_CONN_CB_DEFINE(conn_callbacks) = {@@ -178,11 +179,14 @@ static ssize_t on_provision_write(struct bt_conn *conn, const struct bt_gatt_att 	/* 	 * The blob is 48 bytes, well past the 20 usable bytes of a default 23-byte ATT 	 * MTU, so a client that hasn't negotiated a larger MTU sends it as a long write:-	 * several Prepare Writes at increasing offsets, then one Execute Write. Chunks are-	 * staged here and only acted on once a whole blob has arrived.+	 * several Prepare Writes at increasing offsets, then one Execute Write. Zephyr+	 * reassembles contiguous fragments itself and calls this once with the first+	 * fragment's offset (att.c exec_write_reassemble), but a client is also free to+	 * write at explicit offsets, so chunks are staged here either way. 	 *-	 * Zephyr invokes this with BT_GATT_WRITE_FLAG_PREPARE and len 0 first, purely to-	 * ask whether the write is permitted; the real data comes at execute time.+	 * The PREPARE flag only ever arrives for an attribute carrying+	 * BT_GATT_PERM_PREPARE_WRITE (att.c:2262), which this one does not; handling it is+	 * kept so that adding the permission cannot silently commit a half blob. 	 */ 	if (flags & BT_GATT_WRITE_FLAG_PREPARE) { 		return 0;@@ -207,7 +211,18 @@ static ssize_t on_provision_write(struct bt_conn *conn, const struct bt_gatt_att 	memcpy(&provision_staging[offset], data, len); 	total = offset + len; -	if (total != FF_PROVISION_BLOB_LEN && total != FF_PROVISION_BLOB_LEN_NO_TIME) {+	/*+	 * 40 counts as a complete blob only when it arrived in one piece. A 48-byte blob+	 * written at offsets 0/20/40 passes through total == 40 on its way, and treating+	 * that as complete committed provisioning with unix_seconds = 0, set `provisioned`,+	 * and then rejected its own final chunk at the guard above — leaving a tracker with+	 * no time base that can never beacon and can never be re-provisioned. Nothing can+	 * tell the two apart mid-write, so the 40-byte form has to arrive whole; every+	 * producer sends it that way (TrackerBle, tools/bench_provision.py), and it fits a+	 * single write at the MTU this build asks for.+	 */+	if (total != FF_PROVISION_BLOB_LEN &&+	    !(offset == 0U && len == FF_PROVISION_BLOB_LEN_NO_TIME)) { 		/* A partial chunk: acknowledge it and wait for the rest. */ 		LOG_DBG("provisioning chunk: offset=%u len=%u", offset, len); 		return len;@@ -291,11 +306,6 @@ bool ff_ble_take_readvertise_event(void) 	return atomic_cas(&pending_readvertise, 1, 0); } -enum ff_ble_mode ff_ble_desired_mode(void)-{-	return desired_mode;-}- BT_GATT_SERVICE_DEFINE(ff_tracker_svc, 	BT_GATT_PRIMARY_SERVICE(&uuid_prov_svc), 	BT_GATT_CHARACTERISTIC(&uuid_prov_chr.uuid,@@ -504,7 +514,7 @@ int ff_ble_set_mode(enum ff_ble_mode mode) 		rc = ff_ble_refresh_beacon(100); 		if (rc == -EAGAIN) { 			current_mode = FF_BLE_MODE_IDLE;-			LOG_WRN("cannot beacon: no time base (re-provision to sync time)");+			LOG_WRN("cannot beacon: no time base"); 			return rc; 		} 		if (rc) {@@ -536,3 +546,39 @@ enum ff_ble_mode ff_ble_mode(void) { 	return current_mode; }++int ff_ble_readvertise(void)+{+	struct bt_le_ext_adv *adv;+	int rc;++	if (desired_mode != current_mode) {+		/* The mode we wanted never started — usually beacon mode attempted while+		 * the binding phone still held the connection slot. */+		return ff_ble_set_mode(desired_mode);+	}+	/*+	 * Otherwise the mode is already current, so ff_ble_set_mode() would return early+	 * and restart nothing — yet the connectable set of that mode is down, because the+	 * controller stops a connectable advertisement when it yields a connection and+	 * nothing in the host restarts an extended-API set. Left alone, the tracker takes+	 * exactly one connection per mode change: one UWB handover, or one attempt at a+	 * bind.+	 */+	if (current_mode == FF_BLE_MODE_BEACON) {+		adv = connect_adv;+	} else if (current_mode == FF_BLE_MODE_PAIRING) {+		adv = pairing_adv;+	} else {+		return 0;+	}++	/* -EALREADY means it is still running, which is not a failure. */+	rc = bt_le_ext_adv_start(adv, BT_LE_EXT_ADV_START_DEFAULT);+	if (rc && rc != -EALREADY) {+		LOG_WRN("restarting connectable adv: %d (not reachable until the next mode "+			"change)", rc);+		return rc;+	}+	return 0;+}
firmware/findfamily-tracker/src/tracker_uwb.c
diff --git a/firmware/findfamily-tracker/src/tracker_uwb.c b/firmware/findfamily-tracker/src/tracker_uwb.cindex c65114cf6f..665fdc0976 100644--- a/firmware/findfamily-tracker/src/tracker_uwb.c+++ b/firmware/findfamily-tracker/src/tracker_uwb.c@@ -9,20 +9,12 @@  *  * Built only when CONFIG_FF_TRACKER_UWB=y, which needs the licensed Qorvo SDK; see  * README.md and firmware/qorvo-uwb/.- *- * Interop caveat: the parameters below are FiRa/Qorvo defaults, which is the best- * available guess at what Android's `UwbRangingParams.CONFIG_UNICAST_DS_TWR` asks for.- * Slot duration, block duration and round length are session parameters under static- * STS — they are configured identically on both ends rather than negotiated — so if- * they disagree with what the phone picked, ranging simply never converges. Expect to- * iterate here against a real phone.  */ #include "ff_tracker.h"  #include <zephyr/kernel.h> #include <zephyr/logging/log.h> #include <zephyr/sys/byteorder.h>-#include <zephyr/sys/printk.h>  /* Qorvo uwbstack. */ #include <ff_qorvo_l1_config.h>@@ -46,7 +38,15 @@ LOG_MODULE_REGISTER(ff_uwb, LOG_LEVEL_INF);  * guard immediately on the first poll.  */ #define UWB_THREAD_STACK_SIZE 8192-#define UWB_THREAD_PRIORITY 5+/*+ * Below the session thread that creates it (6), and below every vendor MAC thread: qosal+ * runs CRITICAL=0..IDLE=6 (qthread.h) and firmware/qorvo-uwb/src/qthread_zephyr.c maps+ * that straight onto K_PRIO_PREEMPT(0..6), so the MAC occupies Zephyr 0..6. At 5 this+ * thread preempted its own creator the instant k_thread_create() returned, which left+ * fira_helper_start_session() — the call immediately after start_polling() — reachable+ * only if the poll loop happened to give the CPU back.+ */+#define UWB_THREAD_PRIORITY 7  /*  * Ranging timing, and the STS/PHY settings that go with it.@@ -79,6 +79,13 @@ static bool session_active; static K_THREAD_STACK_DEFINE(uwb_thread_stack, UWB_THREAD_STACK_SIZE); static struct k_thread uwb_thread; static atomic_t poll_running;+/* Only ever touched from the session thread, which is the only caller of start/stop. */+static bool poll_thread_created;+/*+ * k_uptime_get_32() at session start, then at every notification. Written from MAC+ * context and read by the session thread, so it goes through atomic_t.+ */+static atomic_t last_activity_ms;  /*  * Session setup runs on its own thread rather than on the caller's.@@ -88,10 +95,24 @@ static atomic_t poll_running;  * also what refreshes the beacon and drives the mode state machine — a stall there took  * the whole tracker off the air, so crowd-finding died along with ranging. Keeping it on a  * separate thread means the worst a wedged UWB session can do is lose UWB.+ *+ * 8 KB for the same reason as the poll thread: fira_helper_open, init_session, the 23+ * setters and uwbmac_start all nest MAC work onto this stack, and 4 KB was half what that+ * was measured to need.  */-#define UWB_SESSION_THREAD_STACK_SIZE 4096+#define UWB_SESSION_THREAD_STACK_SIZE 8192 #define UWB_SESSION_THREAD_PRIORITY 6 +/*+ * A find is about 10 s of ranging, and the phone drops the GATT link before ranging even+ * starts (TrackerUwbGatt.writeSessionParams disconnects as soon as the write completes),+ * so a BLE disconnect is not a teardown signal — using one would kill the session before+ * the first round. Stop instead once the session has been silent this long: either the+ * find finished, or it never worked. Without this the radio and a stale session stay up+ * until the next params write or a reset.+ */+#define SESSION_IDLE_TIMEOUT_MS 30000+ static K_THREAD_STACK_DEFINE(uwb_session_stack, UWB_SESSION_THREAD_STACK_SIZE); static struct k_thread uwb_session_thread_data; static K_SEM_DEFINE(session_request, 0, 1);@@ -114,6 +135,119 @@ extern struct l1_config_platform_ops l1_config_platform_ops;  */ uint32_t ff_qorvo_read_dev_id(void); +/*+ * Decoders for the two enums that distinguish the failures this bring-up has to tell+ * apart: "never heard anything" (RX_TIMEOUT) from "heard it, STS wrong"+ * (RX_PHY_STS_FAILED) from "the region rejected a parameter" (the ERROR_INVALID_* reason+ * codes). Switches rather than a table so the compiler ties each name to its enumerator.+ * Only the codes a static-STS unicast controlee can produce are listed; anything else+ * still prints as a number.+ */+static const char *ranging_status_name(uint8_t status)+{+	switch (status) {+	case QUWBS_FBS_STATUS_RANGING_SUCCESS:+		return "SUCCESS";+	case QUWBS_FBS_STATUS_RANGING_TX_FAILED:+		return "TX_FAILED";+	case QUWBS_FBS_STATUS_RANGING_RX_TIMEOUT:+		return "RX_TIMEOUT";+	case QUWBS_FBS_STATUS_RANGING_RX_PHY_DEC_FAILED:+		return "RX_PHY_DEC_FAILED";+	case QUWBS_FBS_STATUS_RANGING_RX_PHY_TOA_FAILED:+		return "RX_PHY_TOA_FAILED";+	case QUWBS_FBS_STATUS_RANGING_RX_PHY_STS_FAILED:+		return "RX_PHY_STS_FAILED";+	case QUWBS_FBS_STATUS_RANGING_RX_MAC_DEC_FAILED:+		return "RX_MAC_DEC_FAILED";+	case QUWBS_FBS_STATUS_RANGING_RX_MAC_IE_DEC_FAILED:+		return "RX_MAC_IE_DEC_FAILED";+	case QUWBS_FBS_STATUS_RANGING_RX_MAC_IE_MISSING:+		return "RX_MAC_IE_MISSING";+	case QUWBS_FBS_STATUS_RANGING_INTERNAL_ERROR:+		return "INTERNAL_ERROR";+	default:+		return "?";+	}+}++static const char *session_state_name(enum quwbs_fbs_session_state state)+{+	switch (state) {+	case QUWBS_FBS_SESSION_STATE_INIT:+		return "INIT";+	case QUWBS_FBS_SESSION_STATE_DEINIT:+		return "DEINIT";+	case QUWBS_FBS_SESSION_STATE_ACTIVE:+		return "ACTIVE";+	case QUWBS_FBS_SESSION_STATE_IDLE:+		return "IDLE";+	default:+		return "?";+	}+}++static const char *reason_code_name(enum quwbs_fbs_reason_code code)+{+	switch (code) {+	case QUWBS_FBS_REASON_CODE_SUCCESS:+		/* Also SESSION_MANAGEMENT_COMMANDS, which shares the value 0. */+		return "SUCCESS/STATE_CHANGE_REQUESTED";+	case QUWBS_FBS_REASON_CODE_MAX_RANGING_ROUND_RETRY_COUNT_REACHED:+		return "MAX_RANGING_ROUND_RETRY_COUNT_REACHED";+	case QUWBS_FBS_REASON_CODE_MAX_NUMBER_OF_MEASUREMENTS_REACHED:+		return "MAX_NUMBER_OF_MEASUREMENTS_REACHED";+	case QUWBS_FBS_REASON_CODE_ERROR_SLOT_LENGTH_NOT_SUPPORTED:+		return "ERROR_SLOT_LENGTH_NOT_SUPPORTED";+	case QUWBS_FBS_REASON_CODE_ERROR_INSUFFICIENT_SLOTS_PER_RR:+		return "ERROR_INSUFFICIENT_SLOTS_PER_RR";+	case QUWBS_FBS_REASON_CODE_ERROR_MAC_ADDRESS_MODE_NOT_SUPPORTED:+		return "ERROR_MAC_ADDRESS_MODE_NOT_SUPPORTED";+	case QUWBS_FBS_REASON_CODE_ERROR_INVALID_RANGING_DURATION:+		return "ERROR_INVALID_RANGING_DURATION";+	case QUWBS_FBS_REASON_CODE_ERROR_INVALID_STS_CONFIG:+		return "ERROR_INVALID_STS_CONFIG";+	case QUWBS_FBS_REASON_CODE_ERROR_INVALID_RFRAME_CONFIG:+		return "ERROR_INVALID_RFRAME_CONFIG";+	case QUWBS_FBS_REASON_CODE_ERROR_INVALID_PREAMBLE_CODE_INDEX:+		return "ERROR_INVALID_PREAMBLE_CODE_INDEX";+	case QUWBS_FBS_REASON_CODE_ERROR_INVALID_SFD_ID:+		return "ERROR_INVALID_SFD_ID";+	case QUWBS_FBS_REASON_CODE_ERROR_INVALID_PHR_DATA_RATE:+		return "ERROR_INVALID_PHR_DATA_RATE";+	case QUWBS_FBS_REASON_CODE_ERROR_INVALID_PREAMBLE_DURATION:+		return "ERROR_INVALID_PREAMBLE_DURATION";+	case QUWBS_FBS_REASON_CODE_ERROR_INVALID_STS_LENGTH:+		return "ERROR_INVALID_STS_LENGTH";+	case QUWBS_FBS_REASON_CODE_ERROR_INVALID_NUM_OF_STS_SEGMENTS:+		return "ERROR_INVALID_NUM_OF_STS_SEGMENTS";+	case QUWBS_FBS_REASON_CODE_ERROR_INVALID_DST_ADDRESS_LIST:+		return "ERROR_INVALID_DST_ADDRESS_LIST";+	case QUWBS_FBS_REASON_CODE_ERROR_INVALID_RESULT_REPORT_CONFIG:+		return "ERROR_INVALID_RESULT_REPORT_CONFIG";+	case QUWBS_FBS_REASON_CODE_ERROR_INVALID_RANGING_ROUND_CONTROL_CONFIG:+		return "ERROR_INVALID_RANGING_ROUND_CONTROL_CONFIG";+	case QUWBS_FBS_REASON_CODE_ERROR_INVALID_RANGING_ROUND_USAGE:+		return "ERROR_INVALID_RANGING_ROUND_USAGE";+	case QUWBS_FBS_REASON_CODE_ERROR_INVALID_MULTI_NODE_MODE:+		return "ERROR_INVALID_MULTI_NODE_MODE";+	case QUWBS_FBS_REASON_CODE_ERROR_INVALID_SCHEDULE_MODE:+		return "ERROR_INVALID_SCHEDULE_MODE";+	case QUWBS_FBS_REASON_CODE_ERROR_INVALID_PRF_MODE:+		return "ERROR_INVALID_PRF_MODE";+	case QUWBS_FBS_REASON_CODE_ERROR_INVALID_DEVICE_ROLE:+		return "ERROR_INVALID_DEVICE_ROLE";+	case QUWBS_FBS_REASON_CODE_ERROR_UWB_INITIATION_TIME_EXPIRED:+		return "ERROR_UWB_INITIATION_TIME_EXPIRED";+	case QUWBS_FBS_REASON_CODE_ERROR_DRIVER_DOWN:+		return "ERROR_DRIVER_DOWN";+	case QUWBS_FBS_REASON_CODE_ERROR_NOMEM:+		return "ERROR_NOMEM";+	default:+		return "?";+	}+}+ static void on_fira_notification(enum fira_helper_cb_type cb_type, const void *content, 				 void *user_data) {@@ -126,21 +260,37 @@ static void on_fira_notification(enum fira_helper_cb_type cb_type, const void *c 		for (int i = 0; i < res->n_measurements; i++) { 			const struct fira_twr_measurements *m = &res->measurements[i]; +			/*+			 * Only a measurement that worked counts as the session being+			 * alive (see SESSION_IDLE_TIMEOUT_MS). A responder that is+			 * hearing nothing may still report a round per block with+			 * RX_TIMEOUT, and treating that as activity would keep a session+			 * that has never worked up forever.+			 */+			if (m->status == QUWBS_FBS_STATUS_RANGING_SUCCESS) {+				atomic_set(&last_activity_ms,+					   (atomic_val_t)k_uptime_get_32());+			}+ 			/* 			 * The phone computes the arrow from its own multi-antenna array; 			 * the tracker is single-port and has no AoA to report. Logging the 			 * distance is purely so the bench can see the session converge. 			 */-			LOG_INF("range: peer=%04x status=%u distance=%dcm rssi=%u",-				m->short_addr, m->status, m->distance_cm, m->rssi);+			LOG_INF("range: peer=%04x status=%u (%s) distance=%dcm rssi=%u",+				m->short_addr, m->status, ranging_status_name(m->status),+				m->distance_cm, m->rssi); 		} 		break; 	} 	case FIRA_HELPER_CB_TYPE_SESSION_STATUS_NTF: { 		const struct fbs_helper_session_status_ntf *ntf = content; -		LOG_INF("session %u state=%d reason=%d", ntf->session_handle, ntf->state,-			ntf->reason_code);+		/* Not periodic, so it cannot hold the idle timeout off indefinitely. */+		atomic_set(&last_activity_ms, (atomic_val_t)k_uptime_get_32());+		LOG_INF("session %u state=%d (%s) reason=%d (%s)", ntf->session_handle,+			ntf->state, session_state_name(ntf->state), ntf->reason_code,+			reason_code_name(ntf->reason_code)); 		break; 	} 	default:@@ -151,34 +301,88 @@ static void on_fira_notification(enum fira_helper_cb_type cb_type, const void *c  static void uwb_poll_thread(void *a, void *b, void *c) {+	enum qerr last_r = QERR_SUCCESS;+	bool logged = false;+ 	ARG_UNUSED(a); 	ARG_UNUSED(b); 	ARG_UNUSED(c);  	while (atomic_get(&poll_running)) { 		/* Drives the MAC event loop; notifications are dispatched from here. */-		(void)uwbmac_poll_events(uwbmac_ctx, 100000);+		enum qerr r = uwbmac_poll_events(uwbmac_ctx, 100000);++		if (!logged || r != last_r) {+			/*+			 * uwbmac.h:331-336 documents a non-zero timeout as blocking, but+			 * :328-329 also says the call only exists when uwbmac_init() was+			 * passed a NULL event_loop_ops — a parameter this delivery's+			 * uwbmac_init() does not have. So the return value is the only way+			 * to know whether the pump works here at all; an immediate error+			 * means nothing is dispatching notifications.+			 */+			LOG_INF("uwbmac_poll_events: %d", r);+			last_r = r;+			logged = true;+		}+		/*+		 * Yield unconditionally, in case the call turns out not to block. This is+		 * defence, not the mechanism: session-start liveness comes from this+		 * thread running *below* the session thread (see UWB_THREAD_PRIORITY).+		 * 1 ms against a 120 ms ranging block costs nothing, and the tick here is+		 * 32768 Hz so it really is ~1 ms.+		 */+		k_sleep(K_MSEC(1)); 	} }  /*- * The MAC event loop has an exact window in which it must be started.- *- * Too early — before uwbmac_start() — and uwbmac_poll_events() hangs on a MAC that is not- * running, which wedges the firmware during boot. Too late — after- * fira_helper_start_session() — and the session start never completes, because it is a- * request/response over the MAC that needs its events dispatched; that deadlock stopped the- * tracker advertising altogether, so it went silent for crowd-finding too and only a reset- * recovered it. So: immediately after uwbmac_start(), before starting the session.+ * Started immediately after uwbmac_start(), because fira_helper_start_session() is a+ * request/response over the MAC and needs its events dispatched to complete.  */ static void start_polling(void) {-	if (atomic_cas(&poll_running, 0, 1)) {-		k_thread_create(&uwb_thread, uwb_thread_stack, UWB_THREAD_STACK_SIZE,-				uwb_poll_thread, NULL, NULL, NULL, UWB_THREAD_PRIORITY, 0,-				K_NO_WAIT);-		k_thread_name_set(&uwb_thread, "ff_uwb");+	if (poll_thread_created) {+		/*+		 * A previous stop_polling() could not join it. If it has exited since,+		 * replace it; otherwise re-arm the one that is there, because creating a+		 * second thread over a live k_thread would corrupt the scheduler. A failed+		 * join only says the thread has not terminated — if it is wedged inside+		 * uwbmac_poll_events() this session has no working pump, hence the warning.+		 */+		if (k_thread_join(&uwb_thread, K_NO_WAIT) != 0) {+			LOG_WRN("reusing a poll thread that would not exit; events may not "+				"be dispatched");+			atomic_set(&poll_running, 1);+			return;+		}+		poll_thread_created = false;+	}+	atomic_set(&poll_running, 1);+	k_thread_create(&uwb_thread, uwb_thread_stack, UWB_THREAD_STACK_SIZE,+			uwb_poll_thread, NULL, NULL, NULL, UWB_THREAD_PRIORITY, 0,+			K_NO_WAIT);+	k_thread_name_set(&uwb_thread, "ff_uwb");+	poll_thread_created = true;+}++static void stop_polling(void)+{+	if (!poll_thread_created) {+		return;+	}+	atomic_set(&poll_running, 0);+	/*+	 * The loop can be inside a poll with a 100 ms timeout, so give it room. If it+	 * somehow does not come back, leave the thread object alone and let+	 * start_polling() sort it out; the alternative is creating a second thread over a+	 * live k_thread.+	 */+	if (k_thread_join(&uwb_thread, K_MSEC(500)) != 0) {+		LOG_ERR("poll thread did not exit within 500 ms");+		return; 	}+	poll_thread_created = false; }  int ff_uwb_init(void)@@ -318,8 +522,17 @@ static int apply_session_params(const struct session_parameters *sp)  int ff_uwb_start(const struct ff_uwb_params *params, const uint8_t *secret) {+	/*+	 * Zero-init is load-bearing. apply_session_params() never pushes sts_config,+	 * preamble_duration, psdu_data_rate, sts_length, number_of_sts_segments or+	 * enable_diagnostics, so the FiRa region's own defaults govern those and the+	 * struct values are only a starting point. Adding setters for them would change+	 * behaviour silently: fira_helper_set_session_sts_config(.., 0x01) selects Dynamic+	 * STS rather than Static (fira_helper.h:2036-2050), and sp.preamble_duration == 0+	 * is FIRA_PREAMBLE_DURATION_32, not 64.+	 */ 	struct session_parameters sp = { 0 };-	struct fbs_session_init_rsp rsp;+	struct fbs_session_init_rsp rsp = { 0 }; 	uint8_t vupper64[FIRA_VUPPER64_SIZE]; 	uint8_t own_address[2]; 	uint16_t own_short_addr;@@ -334,11 +547,7 @@ int ff_uwb_start(const struct ff_uwb_params *params, const uint8_t *secret) 		ff_uwb_stop(); 	} -	/*-	 * vUpper64 is exactly [2B VendorID][6B STATIC_STS_IV], which is the same 8 bytes-	 * Android hands to UwbRangingParams.setSessionKeyInfo. So the derived STS key is-	 * used verbatim on both sides with no reinterpretation.-	 */+	/* Both are derived from the bind-time secret, never taken from the wire. */ 	rc = ff_sts_key(secret, params->session_id, vupper64); 	if (rc) { 		return rc;@@ -347,6 +556,13 @@ int ff_uwb_start(const struct ff_uwb_params *params, const uint8_t *secret) 	if (rc) { 		return rc; 	}+	/*+	 * Little-endian, i.e. byte 0 is the low byte. That is the 802.15.4 convention and+	 * what the vendor's own BLE-provisioned accessory does with an out-of-band address:+	 * AR2U16(x) = ((x[1] << 8) | x[0]) (QANI fira_niq.c:43,218-220). The phone hands the+	 * same two bytes to UwbAddress.fromBytes() without documenting an order, so the+	 * summary log below prints both readings to settle it against a RangingSession log.+	 */ 	own_short_addr = sys_get_le16(own_address); 	peer_short_addr = sys_get_le16(params->peer_address); @@ -355,26 +571,42 @@ int ff_uwb_start(const struct ff_uwb_params *params, const uint8_t *secret) 		LOG_ERR("uwbmac_set_short_addr: %d", r); 		return -EIO; 	}+	/*+	 * Passing true *disables* hardware address filtering (uwbmac.h:580-590; the comment+	 * at fira_niq.c:125 says the opposite of what its own argument does). Without it the+	 * DW3110 drops the phone's polls before the MAC sees them if the two ends disagree+	 * about the address byte order, and there is no error on either side to say so.+	 * QANI, the only vendor BLE-provisioned responder, does the same.+	 */+	r = uwbmac_set_promiscuous_mode(uwbmac_ctx, true);+	if (r != QERR_SUCCESS) {+		LOG_ERR("uwbmac_set_promiscuous_mode: %d", r);+		return -EIO;+	} -	printk("ff_uwb: fira_helper_open\n");+	/* Per-step markers from here on: any of these vendor calls can be the one that does+	 * not return, and which one it is only shows in what the trace stops after. */+	LOG_INF("fira_helper_open"); 	r = fira_helper_open(&fira_ctx, uwbmac_ctx, on_fira_notification, "endless", 0, NULL); 	if (r != QERR_SUCCESS) { 		LOG_ERR("fira_helper_open: %d", r); 		return -EIO; 	} 	/* Must happen while the MAC is stopped. */-	printk("ff_uwb: fira_helper_set_scheduler\n");+	LOG_INF("fira_helper_set_scheduler"); 	r = fira_helper_set_scheduler(&fira_ctx); 	if (r != QERR_SUCCESS) { 		LOG_ERR("fira_helper_set_scheduler: %d", r); 		goto close; 	} -	printk("ff_uwb: fira_helper_init_session\n");+	LOG_INF("fira_helper_init_session"); 	r = fira_helper_init_session(&fira_ctx, params->session_id, 				     QUWBS_FBS_SESSION_TYPE_RANGING_NO_IN_BAND_DATA, &rsp);-	if (r != QERR_SUCCESS) {-		LOG_ERR("fira_helper_init_session: %d", r);+	if (r != QERR_SUCCESS || rsp.status_code != QUWBS_FBS_STATUS_OK) {+		/* The qerr return and the FBS status are separate answers; a session that+		 * was refused reports it in rsp.status_code only. */+		LOG_ERR("fira_helper_init_session: %d (status %d)", r, rsp.status_code); 		goto close; 	} 	session_handle = rsp.session_handle;@@ -389,7 +621,17 @@ int ff_uwb_start(const struct ff_uwb_params *params, const uint8_t *secret) 	sp.short_addr = own_short_addr; 	sp.n_destination_short_address = 1; 	sp.destination_short_address[0] = peer_short_addr;-	memcpy(sp.vupper64, vupper64, sizeof(vupper64));+	/*+	 * The derived 8 bytes are [2B VendorID][6B STATIC_STS_IV], the order Android hands+	 * to setSessionKeyInfo. The Qorvo struct holds the opposite layout — a union over+	 * { static_sts_iv[6]; vendor_id[2]; } (fira_helper.h:382-397) — and its own NI+	 * accessory fills the array as a full reversal of VendorID||StaticStsIv+	 * (fira_niq.c:228-235). Follow that: a straight memcpy puts VendorID into+	 * static_sts_iv[0..1] and the STS silently never matches (tracker_sts.c).+	 */+	for (size_t i = 0; i < FIRA_VUPPER64_SIZE; i++) {+		sp.vupper64[i] = vupper64[FIRA_VUPPER64_SIZE - 1 - i];+	}  	/* One initiator, one responder, deferred DS-TWR: the FiRa shape of Android's 	 * CONFIG_UNICAST_DS_TWR. */@@ -399,14 +641,13 @@ int ff_uwb_start(const struct ff_uwb_params *params, const uint8_t *secret) 	sp.rframe_config = FIRA_RFRAME_CONFIG_SP3; 	sp.sfd_id = FIRA_SFD_ID_2; 	sp.prf_mode = FIRA_PRF_MODE_BPRF;-	sp.phr_data_rate = FIRA_PRF_MODE_BPRF;+	sp.phr_data_rate = FIRA_PHR_DATA_RATE_850K; 	sp.slot_duration_rstu = SLOT_DURATION_RSTU; 	sp.block_duration_ms = BLOCK_DURATION_MS; 	sp.round_duration_slots = ROUND_DURATION_SLOTS; 	sp.round_hopping = ROUND_HOPPING; 	sp.block_stride_length = 0; 	sp.report_rssi = 1;-	sp.enable_diagnostics = false;  	/* Report time-of-flight; no AoA, the DW3110 has a single RF port. */ 	sp.result_report_config = fira_helper_bool_to_result_report_config(true, false, false, false);@@ -422,39 +663,44 @@ int ff_uwb_start(const struct ff_uwb_params *params, const uint8_t *secret) 	sp.meas_seq.steps[0].tx_ant_set_nonranging = 0xff; 	sp.meas_seq.steps[0].tx_ant_set_ranging = 0xff; -	printk("ff_uwb: applying session parameters\n");+	LOG_INF("applying session parameters"); 	rc = apply_session_params(&sp); 	if (rc) { 		goto deinit; 	} -	printk("ff_uwb: uwbmac_start\n");-+	LOG_INF("uwbmac_start"); 	r = uwbmac_start(uwbmac_ctx); 	if (r != QERR_SUCCESS) { 		LOG_ERR("uwbmac_start: %d", r); 		goto deinit; 	}-	/* See start_polling(): the MAC is running now, and the session start below needs-	 * its events pumped to complete. */ 	start_polling(); -	printk("ff_uwb: starting FiRa session\n");+	LOG_INF("starting FiRa session"); 	r = fira_helper_start_session(&fira_ctx, session_handle); 	if (r != QERR_SUCCESS) { 		LOG_ERR("fira_helper_start_session: %d", r);-		uwbmac_stop(uwbmac_ctx);-		goto deinit;+		/* Same order as ff_uwb_stop(): deinit while the pump is up, then take the+		 * pump down while the MAC is still running. */+		(void)fira_helper_deinit_session(&fira_ctx, session_handle);+		stop_polling();+		(void)uwbmac_stop(uwbmac_ctx);+		goto close; 	}-	printk("ff_uwb: FiRa session started\n");+	LOG_INF("FiRa session started");  	session_active = true;-	LOG_INF("FiRa responder started: session=%08x ch=%u preamble=%u own=%04x peer=%04x",+	atomic_set(&last_activity_ms, (atomic_val_t)k_uptime_get_32());+	LOG_INF("FiRa responder started: session=%08x ch=%u preamble=%u own=%04x peer=%04x "+		"(peer bytes %02x%02x, big-endian reading would be %04x)", 		params->session_id, params->channel, params->preamble_index, own_short_addr,-		peer_short_addr);+		peer_short_addr, params->peer_address[0], params->peer_address[1],+		sys_get_be16(params->peer_address)); 	return 0;  deinit:+	/* Only reached before uwbmac_start(), so there is no pump to shut down here. */ 	(void)fira_helper_deinit_session(&fira_ctx, session_handle); close: 	fira_helper_close(&fira_ctx);@@ -468,6 +714,13 @@ void ff_uwb_stop(void) 	} 	(void)fira_helper_stop_session(&fira_ctx, session_handle); 	(void)fira_helper_deinit_session(&fira_ctx, session_handle);+	/*+	 * Between those two and uwbmac_stop(): they are request/response over the MAC and+	 * need the pump, while nothing in the vendor API says what uwbmac_poll_events()+	 * does on a *stopped* MAC. Keeping the pump's lifetime inside+	 * [uwbmac_start, uwbmac_stop) means never finding out.+	 */+	stop_polling(); 	(void)uwbmac_stop(uwbmac_ctx); 	fira_helper_close(&fira_ctx); 	session_active = false;@@ -478,6 +731,9 @@ void ff_uwb_stop(void)  * Runs session setup off the main loop; see the note by uwb_session_stack. One request at a  * time is enough — the phone writes params once per find, and a second write while a session  * is starting is better dropped than queued behind a possibly-wedged one.+ *+ * Teardown lives here too, so that every fira_helper_* call in this file is made from this+ * one thread and needs no locking.  */ static void uwb_session_thread(void *a, void *b, void *c) {@@ -486,9 +742,22 @@ static void uwb_session_thread(void *a, void *b, void *c) 	ARG_UNUSED(c);  	while (true) {-		k_sem_take(&session_request, K_FOREVER);-		LOG_INF("session request picked up: starting FiRa setup");-		(void)ff_uwb_start(&requested_params, requested_secret);+		/* Nothing to do until the phone writes params — unless a session is up,+		 * in which case wake up often enough to notice it going quiet. */+		k_timeout_t wait = session_active ? K_MSEC(1000) : K_FOREVER;++		if (k_sem_take(&session_request, wait) == 0) {+			LOG_INF("session request picked up: starting FiRa setup");+			(void)ff_uwb_start(&requested_params, requested_secret);+			continue;+		}+		if (session_active &&+		    (k_uptime_get_32() - (uint32_t)atomic_get(&last_activity_ms)) >+			    (uint32_t)SESSION_IDLE_TIMEOUT_MS) {+			LOG_WRN("no UWB activity for %d ms: stopping the session",+				SESSION_IDLE_TIMEOUT_MS);+			ff_uwb_stop();+		} 	} } @@ -500,6 +769,22 @@ int ff_uwb_on_params(const uint8_t *data, size_t len, const uint8_t *secret) 	if (!stack_ready) { 		return -EAGAIN; 	}+	/*+	 * Reject what the stack would reject anyway, so an out-of-range value says so here+	 * instead of surfacing as an unexplained session-start failure. Only channels 5 and+	 * 9 exist in this stack, and BPRF preamble indices are 9..12+	 * (FIRA_PCODE_BPRF_MIN/MAX, whose header notes the wider 9..24 range elsewhere in+	 * the SDK does not apply here).+	 */+	if (data[6] != 5U && data[6] != 9U) {+		LOG_WRN("UWB params rejected: channel %u (expected 5 or 9)", data[6]);+		return -EINVAL;+	}+	if (data[7] < FIRA_PCODE_BPRF_MIN || data[7] > FIRA_PCODE_BPRF_MAX) {+		LOG_WRN("UWB params rejected: preamble index %u (expected %d..%d)", data[7],+			FIRA_PCODE_BPRF_MIN, FIRA_PCODE_BPRF_MAX);+		return -EINVAL;+	}  	/* TrackerUwbGatt.encodeSessionParams: [2B addr][4B sessionId BE][1B ch][1B pre] */ 	requested_params.peer_address[0] = data[0];
firmware/qorvo-uwb/src/qplatform_zephyr.c
diff --git a/firmware/qorvo-uwb/src/qplatform_zephyr.c b/firmware/qorvo-uwb/src/qplatform_zephyr.cindex d93e53edca..2ff050d2e1 100644--- a/firmware/qorvo-uwb/src/qplatform_zephyr.c+++ b/firmware/qorvo-uwb/src/qplatform_zephyr.c@@ -82,7 +82,7 @@ struct qspi_config qm33_qspi_config = {  * register file 0 offset 0) followed by four bytes clocked out to shift the value in.  */ static const struct spi_dt_spec uwb_bus =-	SPI_DT_SPEC_GET(UWB_NODE, SPI_WORD_SET(8) | SPI_OP_MODE_MASTER | SPI_TRANSFER_MSB, 0);+	SPI_DT_SPEC_GET(UWB_NODE, SPI_WORD_SET(8) | SPI_OP_MODE_MASTER | SPI_TRANSFER_MSB);  /*  * The devicetree-derived bus spec, shared with the qspi backend.