Modern Apps git

← Modern-Apps.git

findfamily: BLE tracker firmware for Qorvo DWM3001CDK

Commit
a1b515d82deebda75a4bf4ddace7b162b8501362
Author
vayun-mathur <[email protected]>
When
2026-08-21 20:14 UTC (3 months ago)
Parents
cf90373

Diff

firmware/findfamily-tracker/.gitattributes
diff --git a/firmware/findfamily-tracker/.gitattributes b/firmware/findfamily-tracker/.gitattributesnew file mode 100644index 0000000000..21219ec882--- /dev/null+++ b/firmware/findfamily-tracker/.gitattributes@@ -0,0 +1,10 @@+# The rest of this repo has mixed line endings with core.autocrlf=false, so a+# global text=auto would renormalise the whole Kotlin/Rust tree the next time+# anyone touched it (see rules/line-endings.md). Scope it to this directory only:+# Zephyr/CMake tooling and the arm-none-eabi toolchain want LF.+* text=auto eol=lf++*.bin binary+*.elf binary+*.hex binary+*.uf2 binary
firmware/findfamily-tracker/CMakeLists.txt
diff --git a/firmware/findfamily-tracker/CMakeLists.txt b/firmware/findfamily-tracker/CMakeLists.txtnew file mode 100644index 0000000000..0527b9b300--- /dev/null+++ b/firmware/findfamily-tracker/CMakeLists.txt@@ -0,0 +1,25 @@+#+# FindFamily UWB tracker firmware (Qorvo DWM3001CDK: nRF52833 + DW3110).+#+# Build:+#   west build -b nrf52833dk/nrf52833 firmware/findfamily-tracker+# See README.md for the DWM3001CDK board notes.+#+cmake_minimum_required(VERSION 3.20.0)++find_package(Zephyr REQUIRED HINTS $ENV{ZEPHYR_BASE})+project(findfamily_tracker)++target_sources(app PRIVATE+  src/main.c+  src/tracker_store.c+  src/tracker_epoch.c+  src/tracker_ble.c+)++# UWB is written but not built by default: the FiRa responder session needs the+# licensed Qorvo DW3xxx driver, which isn't vendored here. See README.md.+target_sources_ifdef(CONFIG_FF_TRACKER_UWB app PRIVATE+  src/tracker_sts.c+  src/tracker_uwb.c+)
firmware/findfamily-tracker/Kconfig
diff --git a/firmware/findfamily-tracker/Kconfig b/firmware/findfamily-tracker/Kconfignew file mode 100644index 0000000000..12a0e31d27--- /dev/null+++ b/firmware/findfamily-tracker/Kconfig@@ -0,0 +1,35 @@+# Copyright (c) 2026 Vayun Mathur+# SPDX-License-Identifier: Apache-2.0++menu "FindFamily tracker"++config FF_TRACKER_UWB+	bool "Build the UWB (FiRa responder) path"+	default n+	help+	  Compile src/tracker_sts.c and src/tracker_uwb.c, which run a FiRa+	  responder/controlee session on the DW3110. Off by default because it needs+	  the licensed Qorvo DW3xxx driver, which is not vendored in this tree — the+	  BLE crowd-finding image builds and flashes without it. See README.md.++config FF_TRACKER_BEACON_INTERVAL_MS+	int "Beacon advertising interval (ms)"+	default 1000+	range 100 10000+	help+	  Extended-advertising interval for the rotating epoch-id beacon. The tradeoff is+	  battery against how quickly a passing finder phone hears the tracker; 1 s is+	  roughly what commercial trackers use.++config FF_TRACKER_PAIRING_TIMEOUT_S+	int "Pairing-mode timeout (seconds)"+	default 120+	range 10 600+	help+	  How long an unprovisioned-service advertisement runs after a long button press+	  before falling back to the previous mode. Bounds the window in which anything+	  nearby could claim an already-bound tracker.++endmenu++source "Kconfig.zephyr"
firmware/findfamily-tracker/README.md
diff --git a/firmware/findfamily-tracker/README.md b/firmware/findfamily-tracker/README.mdnew file mode 100644index 0000000000..2865788af5--- /dev/null+++ b/firmware/findfamily-tracker/README.md@@ -0,0 +1,151 @@+# FindFamily UWB tracker firmware++Zephyr / nRF Connect SDK firmware for a FindFamily item tracker. Target: **Qorvo+DWM3001CDK** — a DWM3001C module (Nordic **nRF52833** + Qorvo **DW3110**) on a dev kit+with an on-board J-Link OB.++What it does today: binds to the phone over BLE GATT and broadcasts a rotating,+unlinkable epoch id so any FindFamily phone that walks past can report the tracker's+location back to its owner. UWB precision finding is written but **not compiled** — see+[UWB](#uwb-precision-finding) below.++The wire formats here are not local decisions; they mirror the phone. See+`findfamily/src/main/java/com/vayunmathur/findfamily/tracker/TrackerBle.kt` (the contract),+`TrackerProtocol.kt` (epoch ids) and `TrackerUwbKeys.kt` (session material), plus+`FINDFAMILY_UWB_TRACKER_DESIGN.md` and `FINDFAMILY_UWB_TRACKER_HARDWARE.md` at the repo+root. Changing a format means changing it in both places at once.++> This directory is invisible to the repo's builds: `settings.gradle.kts` uses an explicit+> `include()` list, `Cargo.toml` an explicit `members` list, and CI discovers modules by+> looking for `build.gradle.kts`. Nothing here needs excluding anywhere.++---++## Layout++| File | Role |+|---|---|+| `src/ff_tracker.h` | Shared types + the wire-format constants that mirror the phone |+| `src/main.c` | Mode state machine, button handling, once-a-second beacon refresh |+| `src/tracker_store.c` | NVS persistence: user id, secret, time base |+| `src/tracker_epoch.c` | `epochId = HMAC-SHA256(secret, "fftrk1" ‖ u64be(epoch))[..16]`, time base |+| `src/tracker_ble.c` | Two advertising modes + the GATT server |+| `src/tracker_sts.c` | HKDF-SHA256 STS key + UWB address (`CONFIG_FF_TRACKER_UWB`) |+| `src/tracker_uwb.c` | FiRa responder session on the DW3110 (`CONFIG_FF_TRACKER_UWB`) |++Crypto goes through **PSA Crypto** (nrf_security/mbedTLS) rather than anything+hand-rolled, because the epoch id has to be byte-identical to the Kotlin+(`TrackerProtocol.epochId`) and Rust (`tracker_epoch_id`) implementations. A one-byte+disagreement doesn't fail loudly — it just means no sighting ever resolves.++---++## Toolchain++```powershell+winget install NordicSemiconductor.nrfutil+nrfutil install toolchain-manager+nrfutil toolchain-manager install --ncs-version v3.4.0+```++Plus **SEGGER J-Link** (from segger.com) for the on-board probe. Install it even if the+kit already enumerates: without the SEGGER driver the probe comes up as+`BULK interface ... Status: Error` and nothing can flash it.++Then fetch the SDK **outside this repo** (~10 GB; `release.sh` requires a clean tree and+runs `git add .`, so a west workspace inside the repo would be a problem):++```powershell+mkdir C:\ncs\v3.4.0+nrfutil toolchain-manager launch --ncs-version v3.4.0 -- `+  west init -m https://github.com/nrfconnect/sdk-nrf --mr v3.4.0 C:/ncs/v3.4.0+cd C:\ncs\v3.4.0+nrfutil toolchain-manager launch --ncs-version v3.4.0 -- west update --narrow -o=--depth=1+```++## Build and flash++The board is supported upstream as `decawave_dwm3001cdk/nrf52833`, so no custom board+definition is needed. Build from inside the west workspace, with the build directory+outside the repo:++```powershell+cd C:\ncs\v3.4.0+nrfutil toolchain-manager launch --ncs-version v3.4.0 -- `+  west build -b decawave_dwm3001cdk/nrf52833 -d C:/ncs/ff-build `+  <path-to-repo>/firmware/findfamily-tracker --pristine++nrfutil toolchain-manager launch --ncs-version v3.4.0 -- west flash -d C:/ncs/ff-build+```++Logs come out of the on-board J-Link CDC UART at 115200 (COM4 on this machine).++---++## Behaviour++**On boot:** loads persisted state. Provisioned *and* time-synced → beacon mode.+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+- short press → mute/unmute the beacon++**Advertising** uses two modes on one state machine, arranged so only the phone's beacon+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+  `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.++**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+`unix_at_provision + k_uptime_get()` (LFCLK-backed, survives sleep). The current time is+re-persisted to NVS once per epoch, so a reset costs at most one epoch of drift rather+than the whole time base. A tracker with **no** time base refuses to beacon and returns to+pairing mode instead of broadcasting ids nobody is searching for.++The owner only searches `TrackerProtocol.recentEpochIds(back = 8)` ≈ 2.25 h, so a tracker+left unpowered long enough for its persisted time to go stale needs re-provisioning to+resync.++---++## Bench verification without the phone++The log prints the live epoch id every second:++```+<inf> ff_ble: epoch=1985934 id=96592d51... batt=100%+```++Cross-check it against an independent computation from the same secret and timestamp —+`epochId = HMAC-SHA256(secret, "fftrk1" ‖ u64be(epoch))[..16]`. This separates "the+firmware's crypto is wrong" from "the phone isn't hearing the advertisement", which+otherwise look identical.++---++## UWB precision finding++`src/tracker_sts.c` and `src/tracker_uwb.c` are **guarded by `CONFIG_FF_TRACKER_UWB`,+default `n`, and have never been compiled.** They call into Qorvo's DW3xxx driver, which+is licensed and not vendored here. To enable:++1. Obtain the Qorvo DW3xxx driver / FiRa stack and add it as a Zephyr module (a `west.yml`+   entry or `ZEPHYR_EXTRA_MODULES`), so `deca_device_api.h` is on the include path.+2. Add a devicetree overlay binding the driver to `spi3` and the module's IRQ/RST/WAKEUP+   lines. The board's `spi3` node already exists for the DW3000.+3. Build with `-DCONFIG_FF_TRACKER_UWB=y`.++Expect this to need iteration. The uncertain part isn't the key derivation — that has+fixed vectors on both sides — it's matching Android's `CONFIG_UNICAST_DS_TWR` against a+hand-configured DW3110 responder: STS mode, RFRAME/packet format, and ranging-round and+block timing all have to line up. That is exactly why it is staged behind BLE rather than+blocking it.
firmware/findfamily-tracker/prj.conf
diff --git a/firmware/findfamily-tracker/prj.conf b/firmware/findfamily-tracker/prj.confnew file mode 100644index 0000000000..7d6c0124b4--- /dev/null+++ b/firmware/findfamily-tracker/prj.conf@@ -0,0 +1,62 @@+# FindFamily UWB tracker — nRF52833 (Qorvo DWM3001C module)++# PSA crypto needs a few KB of stack, and the main loop is where the epoch id is+# derived and the beacon started (both moved off the Bluetooth RX thread, whose stack+# is far too small for either — doing them inline in a GATT callback faults).+CONFIG_MAIN_STACK_SIZE=4096++# --- Bluetooth ------------------------------------------------------------+CONFIG_BT=y+CONFIG_BT_PERIPHERAL=y+CONFIG_BT_DEVICE_NAME="FF Tracker"+CONFIG_BT_DEVICE_APPEARANCE=0++# The crowd-finding beacon is [16B epochId][1B battery] of service data under a+# 128-bit UUID = 35 bytes on air, past the 31-byte legacy limit, so it has to be an+# extended advertisement. Pairing mode stays legacy (21 bytes) so the phone can find+# it with default scan settings.+CONFIG_BT_EXT_ADV=y+CONFIG_BT_EXT_ADV_MAX_ADV_SET=2+CONFIG_BT_CTLR_ADV_EXT=y++CONFIG_BT_GATT_DYNAMIC_DB=y+CONFIG_BT_ATT_PREPARE_COUNT=2+# Must fit the 48-byte provisioning write in a single ATT operation.+CONFIG_BT_BUF_ACL_RX_SIZE=69+CONFIG_BT_L2CAP_TX_MTU=65++# --- Crypto (PSA / nrf_security) -----------------------------------------+# Epoch ids must be byte-identical to TrackerProtocol.epochId on the phone and+# tracker_epoch_id on the server, so use the same primitives: HMAC-SHA256 and+# HKDF-SHA256. CONFIG_NRF_SECURITY is deliberately not set: it is def_bool y once+# PSA_CRYPTO selects the Nordic provider, and assigning it directly is an error.+CONFIG_PSA_CRYPTO=y+CONFIG_PSA_WANT_ALG_SHA_256=y+CONFIG_PSA_WANT_ALG_HMAC=y+CONFIG_PSA_WANT_ALG_HKDF=y+CONFIG_PSA_WANT_KEY_TYPE_HMAC=y+CONFIG_PSA_WANT_KEY_TYPE_DERIVE=y+CONFIG_HEAP_MEM_POOL_SIZE=4096++# --- Persistence ---------------------------------------------------------+# The provisioning blob and the time base have to survive a reset, or the tracker+# beacons ids no owner is looking for.+CONFIG_NVS=y+CONFIG_FLASH=y+CONFIG_FLASH_MAP=y+CONFIG_FLASH_PAGE_LAYOUT=y+CONFIG_SETTINGS=y+CONFIG_SETTINGS_NVS=y++# --- Board I/O -----------------------------------------------------------+CONFIG_GPIO=y++# --- Logging over the on-board J-Link CDC UART ---------------------------+CONFIG_LOG=y+CONFIG_SERIAL=y+CONFIG_CONSOLE=y+CONFIG_UART_CONSOLE=y+CONFIG_LOG_MODE_DEFERRED=y+CONFIG_LOG_BUFFER_SIZE=2048++CONFIG_REBOOT=y
firmware/findfamily-tracker/src/ff_tracker.h
diff --git a/firmware/findfamily-tracker/src/ff_tracker.h b/firmware/findfamily-tracker/src/ff_tracker.hnew file mode 100644index 0000000000..53fdd4c086--- /dev/null+++ b/firmware/findfamily-tracker/src/ff_tracker.h@@ -0,0 +1,139 @@+/*+ * FindFamily UWB tracker — internal interfaces.+ *+ * The wire formats here are fixed by the phone side; see+ * findfamily/src/main/java/com/vayunmathur/findfamily/tracker/TrackerBle.kt and+ * TrackerProtocol.kt. Any change has to be made in both places at once.+ */+#ifndef FF_TRACKER_H_+#define FF_TRACKER_H_++#include <stdbool.h>+#include <stdint.h>+#include <stddef.h>++/* TrackerProtocol.SECRET_LEN */+#define FF_SECRET_LEN 32+/* TrackerProtocol.EPOCH_ID_LEN */+#define FF_EPOCH_ID_LEN 16+/* TrackerProtocol.EPOCH_SECONDS */+#define FF_EPOCH_SECONDS 900U++/* TrackerBle.PROVISION_BLOB_LEN / PROVISION_BLOB_LEN_NO_TIME */+#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] */+#define FF_UWB_PARAMS_LEN 8++/* Service data payload: [16B epochId][1B battery%] */+#define FF_BEACON_DATA_LEN (FF_EPOCH_ID_LEN + 1)++/* Everything the tracker persists across resets. */+struct ff_tracker_state {+	uint64_t tracker_user_id;+	uint8_t secret[FF_SECRET_LEN];+	bool provisioned;+	/*+	 * Wall-clock seconds at the moment `uptime_at_base_ms` was taken. Zero means+	 * "no time base": the tracker cannot compute an epoch id anyone is looking for+	 * and stays quiet rather than beaconing garbage.+	 */+	uint64_t unix_at_base;+	int64_t uptime_at_base_ms;+};++/* ---- tracker_store.c: NVS-backed persistence ---------------------------- */++int ff_store_init(void);++/* Loads persisted state into `out`. Returns 0 even when nothing is stored yet, in+ * which case `out->provisioned` is false. */+int ff_store_load(struct ff_tracker_state *out);++int ff_store_save_provisioning(uint64_t tracker_user_id, const uint8_t *secret,+			       uint64_t unix_seconds);++/* Re-persists just the time base. Called once per epoch so a reset costs at most one+ * epoch of drift instead of the whole time base. */+int ff_store_save_time(uint64_t unix_seconds);++/* Wipes provisioning so the device can be re-bound. */+int ff_store_clear(void);++/* ---- tracker_epoch.c: rotating beacon id ------------------------------- */++/* Current wall-clock seconds, or 0 if there is no time base yet. */+uint64_t ff_now_unix(const struct ff_tracker_state *st);++/* epoch = unix_seconds / FF_EPOCH_SECONDS */+uint64_t ff_current_epoch(const struct ff_tracker_state *st);++/*+ * epochId = HMAC-SHA256(secret, "fftrk1" || u64_be(epoch))[..16].+ * Mirrors TrackerProtocol.epochId; `out` must hold FF_EPOCH_ID_LEN bytes.+ */+int ff_epoch_id(const uint8_t *secret, uint64_t epoch, uint8_t *out);++/* ---- tracker_ble.c: advertising + GATT --------------------------------- */++enum ff_ble_mode {+	/* Nothing on air: unprovisioned and not pairing, or muted by the user. */+	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. */+	FF_BLE_MODE_BEACON,+};++int ff_ble_init(struct ff_tracker_state *state);++int ff_ble_set_mode(enum ff_ble_mode mode);++enum ff_ble_mode ff_ble_mode(void);++/*+ * GATT writes are handled on the Bluetooth RX thread, whose stack is nowhere near big+ * enough for PSA crypto plus starting an advertisement — doing that work inline faults+ * with a stack overflow. The write callbacks therefore only record what arrived, and the+ * main loop drains it. Both of these return true once per event and clear it.+ */+bool ff_ble_take_provision_event(void);++/* Copies FF_UWB_PARAMS_LEN bytes into `out` when a session-params write is pending. */+bool ff_ble_take_uwb_params(uint8_t *out);++/* Recomputes the epoch id and pushes fresh service data into the beacon adv set. */+int ff_ble_refresh_beacon(uint8_t battery_percent);++/* ---- UWB (CONFIG_FF_TRACKER_UWB) --------------------------------------- */++#ifdef CONFIG_FF_TRACKER_UWB+/*+ * HKDF-SHA256 derivations mirroring TrackerUwbKeys.kt. `out` must hold 8 bytes for+ * the STS key and 2 for the address.+ */+int ff_sts_key(const uint8_t *secret, uint32_t session_id, uint8_t *out);+int ff_uwb_address(const uint8_t *secret, uint8_t *out);++struct ff_uwb_params {+	uint8_t peer_address[2]; /* the phone's UWB MAC, from the GATT write */+	uint32_t session_id;+	uint8_t channel;+	uint8_t preamble_index;+};++int ff_uwb_init(void);++/* Starts a FiRa responder/controlee session. Session key and our own address are+ * derived from `secret`, never taken from the wire. */+int ff_uwb_start(const struct ff_uwb_params *params, const uint8_t *secret);++void ff_uwb_stop(void);+#endif /* CONFIG_FF_TRACKER_UWB */++/* Handles a write to the UWB session characteristic. Defined in tracker_uwb.c when+ * CONFIG_FF_TRACKER_UWB is set, and stubbed in tracker_ble.c otherwise. */+int ff_uwb_on_params(const uint8_t *data, size_t len, const uint8_t *secret);++#endif /* FF_TRACKER_H_ */
firmware/findfamily-tracker/src/main.c
diff --git a/firmware/findfamily-tracker/src/main.c b/firmware/findfamily-tracker/src/main.cnew file mode 100644index 0000000000..d1e2e1bfaa--- /dev/null+++ b/firmware/findfamily-tracker/src/main.c@@ -0,0 +1,202 @@+/*+ * FindFamily UWB tracker — main state machine.+ *+ * On boot: load persisted provisioning. Provisioned and time-synced -> beacon.+ * Otherwise -> pairing mode, so a brand-new board is bindable straight out of the box+ * 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+ *   short press          -> toggle the beacon off/on ("mute"), for taking it on a plane+ *                           or debugging whether a sighting really came from this board+ *+ * The beacon id and battery percent are refreshed once a second and logged, so the+ * board can be verified on the bench against an independently computed epoch id+ * without involving the phone at all.+ */+#include "ff_tracker.h"++#include <zephyr/kernel.h>+#include <zephyr/device.h>+#include <zephyr/drivers/gpio.h>+#include <zephyr/logging/log.h>+#include <psa/crypto.h>++LOG_MODULE_REGISTER(ff_main, LOG_LEVEL_INF);++#define LONG_PRESS_MS 2000+#define TICK_MS 1000++static struct ff_tracker_state tracker_state;++/* ---- Button ------------------------------------------------------------ */++static const struct gpio_dt_spec button =+	GPIO_DT_SPEC_GET_OR(DT_ALIAS(sw0), gpios, { 0 });+static struct gpio_callback button_cb;++static int64_t press_started_ms;+static atomic_t pending_short_press;+static atomic_t pending_long_press;++static void button_changed(const struct device *dev, struct gpio_callback *cb,+			   uint32_t pins)+{+	ARG_UNUSED(dev);+	ARG_UNUSED(cb);+	ARG_UNUSED(pins);++	if (gpio_pin_get_dt(&button) == 1) {+		press_started_ms = k_uptime_get();+		return;+	}+	if (press_started_ms == 0) {+		return;+	}+	if (k_uptime_get() - press_started_ms >= LONG_PRESS_MS) {+		atomic_set(&pending_long_press, 1);+	} else {+		atomic_set(&pending_short_press, 1);+	}+	press_started_ms = 0;+}++static int button_init(void)+{+	int rc;++	if (!gpio_is_ready_dt(&button)) {+		LOG_WRN("no sw0 button on this board; pairing mode is boot-only");+		return -ENODEV;+	}+	rc = gpio_pin_configure_dt(&button, GPIO_INPUT);+	if (rc) {+		return rc;+	}+	rc = gpio_pin_interrupt_configure_dt(&button, GPIO_INT_EDGE_BOTH);+	if (rc) {+		return rc;+	}+	gpio_init_callback(&button_cb, button_changed, BIT(button.pin));+	return gpio_add_callback(button.port, &button_cb);+}++/* ---- Battery ---------------------------------------------------------- */++/*+ * The DWM3001CDK is USB-powered on the bench, so there is no meaningful cell voltage+ * to read through the kit's SAADC wiring. Report a constant until a battery-backed+ * carrier exists; the advertisement byte and the phone-side parsing are exercised+ * either way. Sampling VDD here instead would just report the regulator, which reads+ * as a permanently full battery and is more misleading than an obvious placeholder.+ */+static uint8_t battery_percent(void)+{+	return 100;+}++/* ---- Main ------------------------------------------------------------- */++int main(void)+{+	psa_status_t status;+	uint64_t last_persisted_epoch = 0;+	int rc;++	LOG_INF("FindFamily tracker starting");++	status = psa_crypto_init();+	if (status != PSA_SUCCESS) {+		LOG_ERR("psa_crypto_init: %d", (int)status);+		return 0;+	}++	rc = ff_store_init();+	if (rc) {+		LOG_ERR("store init failed: %d", rc);+		return 0;+	}+	rc = ff_store_load(&tracker_state);+	if (rc) {+		LOG_ERR("store load failed: %d", rc);+	}++	rc = ff_ble_init(&tracker_state);+	if (rc) {+		LOG_ERR("ble init failed: %d", rc);+		return 0;+	}++	(void)button_init();++#ifdef CONFIG_FF_TRACKER_UWB+	rc = ff_uwb_init();+	if (rc) {+		LOG_ERR("uwb init failed: %d", rc);+	}+#endif++	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. */+			(void)ff_ble_set_mode(FF_BLE_MODE_PAIRING);+		}+	} else {+		LOG_INF("unprovisioned; entering pairing mode");+		(void)ff_ble_set_mode(FF_BLE_MODE_PAIRING);+	}++	while (true) {+		if (ff_ble_take_provision_event()) {+			LOG_INF("provisioning accepted: switching to beacon mode");+			if (ff_ble_set_mode(FF_BLE_MODE_BEACON) != 0) {+				(void)ff_ble_set_mode(FF_BLE_MODE_PAIRING);+			}+		}++		{+			uint8_t uwb_params[FF_UWB_PARAMS_LEN];++			if (ff_ble_take_uwb_params(uwb_params)) {+				(void)ff_uwb_on_params(uwb_params, sizeof(uwb_params),+						       tracker_state.secret);+			}+		}++		if (atomic_cas(&pending_long_press, 1, 0)) {+			LOG_INF("long press: entering pairing mode");+			(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) {+				LOG_INF("short press: muting beacon");+				(void)ff_ble_set_mode(FF_BLE_MODE_IDLE);+			} else if (tracker_state.provisioned) {+				LOG_INF("short press: unmuting beacon");+				(void)ff_ble_set_mode(FF_BLE_MODE_BEACON);+			}+		}++		if (tracker_state.provisioned) {+			uint64_t epoch = ff_current_epoch(&tracker_state);++			(void)ff_ble_refresh_beacon(battery_percent());++			/*+			 * Re-persist the time base once per epoch. k_uptime_get() restarts+			 * at 0 on reset, so without this a reset would lose the time base+			 * entirely; with it, the worst case is one epoch of drift.+			 */+			if (epoch != 0U && epoch != last_persisted_epoch) {+				(void)ff_store_save_time(ff_now_unix(&tracker_state));+				last_persisted_epoch = epoch;+			}+		}++		k_msleep(TICK_MS);+	}+	return 0;+}
firmware/findfamily-tracker/src/tracker_ble.c
diff --git a/firmware/findfamily-tracker/src/tracker_ble.c b/firmware/findfamily-tracker/src/tracker_ble.cnew file mode 100644index 0000000000..ec80cef71c--- /dev/null+++ b/firmware/findfamily-tracker/src/tracker_ble.c@@ -0,0 +1,368 @@+/*+ * Advertising (two modes) and the GATT server.+ *+ * Two advertising modes on one state machine, chosen so only the phone's beacon+ * scanner needs a change:+ *+ *  - Pairing: LEGACY connectable adv of the unprovisioned service. Flags + a 128-bit+ *    service UUID is 21 bytes, well inside the 31-byte legacy budget, so+ *    TrackerProvisioner.unprovisioned() keeps working with default (legacy-only)+ *    ScanSettings.+ *+ *  - Beacon: EXTENDED 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.+ *+ * Both characteristics stay registered under the "unprovisioned" service for the+ * device's whole life; provisioning only stops that service being advertised.+ */+#include "ff_tracker.h"++#include <zephyr/kernel.h>+#include <zephyr/logging/log.h>+#include <zephyr/bluetooth/bluetooth.h>+#include <zephyr/bluetooth/conn.h>+#include <zephyr/bluetooth/gatt.h>+#include <zephyr/bluetooth/uuid.h>+#include <zephyr/sys/byteorder.h>++#include <string.h>++LOG_MODULE_REGISTER(ff_ble, LOG_LEVEL_INF);++/* TrackerBle UUIDs, little-endian byte order as bt_uuid_128 wants them. */+#define FF_UUID_BEACON_SVC \+	BT_UUID_128_ENCODE(0x6b1d2f00, 0x4b3a, 0x4c7e, 0x9a10, 0x1f2e3d4c5b6a)+#define FF_UUID_PROV_SVC \+	BT_UUID_128_ENCODE(0x6b1d2f01, 0x4b3a, 0x4c7e, 0x9a10, 0x1f2e3d4c5b6a)+#define FF_UUID_PROV_CHR \+	BT_UUID_128_ENCODE(0x6b1d2f02, 0x4b3a, 0x4c7e, 0x9a10, 0x1f2e3d4c5b6a)+#define FF_UUID_UWB_CHR \+	BT_UUID_128_ENCODE(0x6b1d2f03, 0x4b3a, 0x4c7e, 0x9a10, 0x1f2e3d4c5b6a)++static const struct bt_uuid_128 uuid_prov_svc = BT_UUID_INIT_128(FF_UUID_PROV_SVC);+static const struct bt_uuid_128 uuid_prov_chr = BT_UUID_INIT_128(FF_UUID_PROV_CHR);+static const struct bt_uuid_128 uuid_uwb_chr = BT_UUID_INIT_128(FF_UUID_UWB_CHR);++static struct ff_tracker_state *state;+static enum ff_ble_mode current_mode = FF_BLE_MODE_IDLE;++static struct bt_le_ext_adv *pairing_adv;+static struct bt_le_ext_adv *beacon_adv;++/*+ * Service-data AD payload: the 16-byte UUID followed by [16B epochId][1B battery].+ * Held in a static buffer because bt_le_ext_adv_set_data() does not copy — the+ * controller reads it back when it refreshes the advertisement.+ */+static uint8_t beacon_sd[16 + FF_BEACON_DATA_LEN] = { FF_UUID_BEACON_SVC };++static const struct bt_data pairing_ad[] = {+	BT_DATA_BYTES(BT_DATA_FLAGS, (BT_LE_AD_GENERAL | BT_LE_AD_NO_BREDR)),+	BT_DATA_BYTES(BT_DATA_UUID128_ALL, FF_UUID_PROV_SVC),+};++static struct bt_data beacon_ad[] = {+	BT_DATA(BT_DATA_SVC_DATA128, beacon_sd, sizeof(beacon_sd)),+};++/*+ * Work handed from the Bluetooth RX thread to the main loop. The RX thread's stack+ * cannot absorb PSA crypto plus bt_le_ext_adv_start(); doing either inline in a write+ * callback faults with a stack overflow.+ */+static atomic_t pending_provision;+static atomic_t pending_uwb;+static uint8_t pending_uwb_params[FF_UWB_PARAMS_LEN];++/* ---- GATT -------------------------------------------------------------- */++static ssize_t on_provision_write(struct bt_conn *conn, const struct bt_gatt_attr *attr,+				  const void *buf, uint16_t len, uint16_t offset, uint8_t flags)+{+	const uint8_t *data = buf;+	uint64_t user_id;+	uint64_t unix_seconds = 0U;+	int rc;++	ARG_UNUSED(conn);+	ARG_UNUSED(attr);+	ARG_UNUSED(flags);++	if (offset != 0U) {+		return BT_GATT_ERR(BT_ATT_ERR_INVALID_OFFSET);+	}+	if (len != FF_PROVISION_BLOB_LEN && len != FF_PROVISION_BLOB_LEN_NO_TIME) {+		LOG_WRN("provisioning write of %u bytes rejected (want %d or %d)", len,+			FF_PROVISION_BLOB_LEN_NO_TIME, FF_PROVISION_BLOB_LEN);+		return BT_GATT_ERR(BT_ATT_ERR_INVALID_ATTRIBUTE_LEN);+	}++	user_id = sys_get_be64(data);+	if (len == FF_PROVISION_BLOB_LEN) {+		unix_seconds = sys_get_be64(&data[8 + FF_SECRET_LEN]);+	}++	rc = ff_store_save_provisioning(user_id, &data[8], unix_seconds);+	if (rc) {+		LOG_ERR("persisting provisioning failed: %d", rc);+		return BT_GATT_ERR(BT_ATT_ERR_UNLIKELY);+	}++	state->tracker_user_id = user_id;+	memcpy(state->secret, &data[8], FF_SECRET_LEN);+	state->provisioned = true;+	state->unix_at_base = unix_seconds;+	state->uptime_at_base_ms = k_uptime_get();++	LOG_INF("provisioned: userId=%llu, %u-byte blob, unix=%llu", user_id, len,+		unix_seconds);+	if (unix_seconds == 0U) {+		LOG_WRN("no timestamp in blob: epoch ids will not resolve for the owner");+	}++	/* The main loop stops offering to be claimed and starts crowd-finding. */+	atomic_set(&pending_provision, 1);+	return len;+}++static ssize_t on_uwb_write(struct bt_conn *conn, const struct bt_gatt_attr *attr,+			    const void *buf, uint16_t len, uint16_t offset, uint8_t flags)+{+	ARG_UNUSED(conn);+	ARG_UNUSED(attr);+	ARG_UNUSED(flags);++	if (offset != 0U) {+		return BT_GATT_ERR(BT_ATT_ERR_INVALID_OFFSET);+	}+	if (len != FF_UWB_PARAMS_LEN) {+		return BT_GATT_ERR(BT_ATT_ERR_INVALID_ATTRIBUTE_LEN);+	}+	if (!state->provisioned) {+		/* Without the secret there is no session key, so there is nothing to+		 * start — and an unprovisioned tracker has no owner to be ranged by. */+		return BT_GATT_ERR(BT_ATT_ERR_WRITE_NOT_PERMITTED);+	}++	/* Deriving the STS key is PSA work; hand it to the main loop. */+	memcpy(pending_uwb_params, buf, FF_UWB_PARAMS_LEN);+	atomic_set(&pending_uwb, 1);+	return len;+}++bool ff_ble_take_provision_event(void)+{+	return atomic_cas(&pending_provision, 1, 0);+}++bool ff_ble_take_uwb_params(uint8_t *out)+{+	if (!atomic_cas(&pending_uwb, 1, 0)) {+		return false;+	}+	memcpy(out, pending_uwb_params, FF_UWB_PARAMS_LEN);+	return true;+}++BT_GATT_SERVICE_DEFINE(ff_tracker_svc,+	BT_GATT_PRIMARY_SERVICE(&uuid_prov_svc),+	BT_GATT_CHARACTERISTIC(&uuid_prov_chr.uuid,+			       BT_GATT_CHRC_WRITE,+			       BT_GATT_PERM_WRITE,+			       NULL, on_provision_write, NULL),+	BT_GATT_CHARACTERISTIC(&uuid_uwb_chr.uuid,+			       BT_GATT_CHRC_WRITE | BT_GATT_CHRC_NOTIFY,+			       BT_GATT_PERM_WRITE,+			       NULL, on_uwb_write, NULL),+	BT_GATT_CCC(NULL, BT_GATT_PERM_READ | BT_GATT_PERM_WRITE),+);++#ifndef CONFIG_FF_TRACKER_UWB+int ff_uwb_on_params(const uint8_t *data, size_t len, const uint8_t *secret)+{+	ARG_UNUSED(data);+	ARG_UNUSED(len);+	ARG_UNUSED(secret);+	/* Accepted and logged so the phone-side GATT write can be exercised on a+	 * BLE-only image; ranging itself needs CONFIG_FF_TRACKER_UWB. */+	LOG_INF("UWB session params received but CONFIG_FF_TRACKER_UWB=n; ignoring");+	return 0;+}+#endif++/* ---- Advertising ------------------------------------------------------- */++static int create_adv_sets(void)+{+	/* Legacy connectable+scannable, so a default-settings scanner sees it. */+	const struct bt_le_adv_param pairing_param = {+		.id = BT_ID_DEFAULT,+		.options = BT_LE_ADV_OPT_CONN,+		.interval_min = BT_GAP_ADV_FAST_INT_MIN_2,+		.interval_max = BT_GAP_ADV_FAST_INT_MAX_2,+	};+	/*+	 * Extended connectable. BT_LE_ADV_OPT_EXT_ADV without OPT_CODED pins the+	 * secondary PHY to 1M, so a phone scanning with setLegacy(false) and the default+	 * PHY sees it. BT_LE_ADV_OPT_SCANNABLE is intentionally absent: extended+	 * advertisements can be connectable or scannable, not both, and connectable is+	 * what lets the owner write UWB params.+	 */+	const struct bt_le_adv_param beacon_param = {+		.id = BT_ID_DEFAULT,+		.options = BT_LE_ADV_OPT_EXT_ADV | BT_LE_ADV_OPT_CONN,+		.interval_min = BT_GAP_MS_TO_ADV_INTERVAL(CONFIG_FF_TRACKER_BEACON_INTERVAL_MS),+		.interval_max = BT_GAP_MS_TO_ADV_INTERVAL(CONFIG_FF_TRACKER_BEACON_INTERVAL_MS + 100),+		.secondary_max_skip = 0,+	};+	int rc;++	rc = bt_le_ext_adv_create(&pairing_param, NULL, &pairing_adv);+	if (rc) {+		LOG_ERR("creating pairing adv set: %d", rc);+		return rc;+	}+	rc = bt_le_ext_adv_set_data(pairing_adv, pairing_ad, ARRAY_SIZE(pairing_ad), NULL, 0);+	if (rc) {+		LOG_ERR("setting pairing adv data: %d", rc);+		return rc;+	}++	rc = bt_le_ext_adv_create(&beacon_param, NULL, &beacon_adv);+	if (rc) {+		LOG_ERR("creating beacon adv set: %d", rc);+		return rc;+	}+	return 0;+}++int ff_ble_init(struct ff_tracker_state *st)+{+	int rc;++	state = st;++	rc = bt_enable(NULL);+	if (rc) {+		LOG_ERR("bt_enable: %d", rc);+		return rc;+	}+	LOG_INF("Bluetooth initialised");+	return create_adv_sets();+}++int ff_ble_refresh_beacon(uint8_t battery_percent)+{+	uint8_t epoch_id[FF_EPOCH_ID_LEN];+	uint64_t epoch;+	int rc;++	if (!state->provisioned) {+		return -EPERM;+	}+	epoch = ff_current_epoch(state);+	if (epoch == 0U) {+		/* No time base: any id we produced would fall outside the owner's search+		 * window, so stay quiet rather than fill the air with unresolvable ids. */+		return -EAGAIN;+	}+	rc = ff_epoch_id(state->secret, epoch, epoch_id);+	if (rc) {+		return rc;+	}++	memcpy(&beacon_sd[16], epoch_id, FF_EPOCH_ID_LEN);+	beacon_sd[16 + FF_EPOCH_ID_LEN] = battery_percent;++	LOG_INF("epoch=%llu id=%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x batt=%u%%",+		epoch, epoch_id[0], epoch_id[1], epoch_id[2], epoch_id[3], epoch_id[4],+		epoch_id[5], epoch_id[6], epoch_id[7], epoch_id[8], epoch_id[9],+		epoch_id[10], epoch_id[11], epoch_id[12], epoch_id[13], epoch_id[14],+		epoch_id[15], battery_percent);++	if (current_mode != FF_BLE_MODE_BEACON) {+		return 0;+	}+	rc = bt_le_ext_adv_set_data(beacon_adv, beacon_ad, ARRAY_SIZE(beacon_ad), NULL, 0);+	if (rc) {+		LOG_ERR("refreshing beacon adv data: %d", rc);+	}+	return rc;+}++int ff_ble_set_mode(enum ff_ble_mode mode)+{+	int rc;++	if (mode == current_mode) {+		return 0;+	}++	/* Stopping a set that isn't running returns -EALREADY, which is not a failure+	 * here — mode changes can arrive from the button and from a GATT write. */+	if (current_mode == FF_BLE_MODE_PAIRING) {+		rc = bt_le_ext_adv_stop(pairing_adv);+		if (rc && rc != -EALREADY) {+			LOG_WRN("stopping pairing adv: %d", rc);+		}+	} else if (current_mode == FF_BLE_MODE_BEACON) {+		rc = bt_le_ext_adv_stop(beacon_adv);+		if (rc && rc != -EALREADY) {+			LOG_WRN("stopping beacon adv: %d", rc);+		}+	}+	current_mode = FF_BLE_MODE_IDLE;++	switch (mode) {+	case FF_BLE_MODE_IDLE:+		LOG_INF("advertising off");+		return 0;++	case FF_BLE_MODE_PAIRING:+		rc = bt_le_ext_adv_start(pairing_adv, BT_LE_EXT_ADV_START_DEFAULT);+		if (rc) {+			LOG_ERR("starting pairing adv: %d", rc);+			return rc;+		}+		current_mode = FF_BLE_MODE_PAIRING;+		LOG_INF("pairing mode: advertising unprovisioned service (legacy)");+		return 0;++	case FF_BLE_MODE_BEACON:+		if (!state->provisioned) {+			LOG_WRN("cannot beacon: not provisioned");+			return -EPERM;+		}+		/* Fill in service data before the first start, or the controller would+		 * advertise a zeroed epoch id for one interval. */+		current_mode = FF_BLE_MODE_BEACON;+		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)");+			return rc;+		}+		if (rc) {+			current_mode = FF_BLE_MODE_IDLE;+			return rc;+		}+		rc = bt_le_ext_adv_start(beacon_adv, BT_LE_EXT_ADV_START_DEFAULT);+		if (rc) {+			current_mode = FF_BLE_MODE_IDLE;+			LOG_ERR("starting beacon adv: %d", rc);+			return rc;+		}+		LOG_INF("beacon mode: advertising rotating epoch id (extended)");+		return 0;+	}+	return -EINVAL;+}++enum ff_ble_mode ff_ble_mode(void)+{+	return current_mode;+}
firmware/findfamily-tracker/src/tracker_epoch.c
diff --git a/firmware/findfamily-tracker/src/tracker_epoch.c b/firmware/findfamily-tracker/src/tracker_epoch.cnew file mode 100644index 0000000000..4c016dce8f--- /dev/null+++ b/firmware/findfamily-tracker/src/tracker_epoch.c@@ -0,0 +1,102 @@+/*+ * Rotating beacon id and the tracker's notion of wall-clock time.+ *+ * The id must be byte-identical to TrackerProtocol.epochId (Kotlin) and+ * tracker_epoch_id (Rust), or the owner's recomputed ids never match what finders+ * upload and a sighting silently resolves to nothing. Hence PSA HMAC-SHA256 here+ * rather than any hand-rolled hashing.+ */+#include "ff_tracker.h"++#include <zephyr/kernel.h>+#include <zephyr/logging/log.h>+#include <psa/crypto.h>++#include <string.h>++LOG_MODULE_REGISTER(ff_epoch, LOG_LEVEL_INF);++/* TrackerProtocol.EPOCH_DOMAIN */+static const uint8_t epoch_domain[6] = { 'f', 'f', 't', 'r', 'k', '1' };++uint64_t ff_now_unix(const struct ff_tracker_state *st)+{+	int64_t elapsed_ms;++	if (st->unix_at_base == 0U) {+		return 0U;+	}+	/*+	 * k_uptime_get() is LFCLK-backed and keeps counting through sleep, so this+	 * holds across the idle periods between beacons. It does reset to 0 on reboot,+	 * which is why the caller re-persists the time base once per epoch.+	 */+	elapsed_ms = k_uptime_get() - st->uptime_at_base_ms;+	if (elapsed_ms < 0) {+		elapsed_ms = 0;+	}+	return st->unix_at_base + (uint64_t)(elapsed_ms / 1000);+}++uint64_t ff_current_epoch(const struct ff_tracker_state *st)+{+	uint64_t now = ff_now_unix(st);++	return now == 0U ? 0U : now / FF_EPOCH_SECONDS;+}++int ff_epoch_id(const uint8_t *secret, uint64_t epoch, uint8_t *out)+{+	psa_status_t status;+	psa_key_attributes_t attr = PSA_KEY_ATTRIBUTES_INIT;+	psa_key_id_t key = PSA_KEY_ID_NULL;+	psa_mac_operation_t op = PSA_MAC_OPERATION_INIT;+	uint8_t mac[32];+	uint8_t epoch_be[8];+	size_t mac_len = 0;++	for (int i = 0; i < 8; i++) {+		epoch_be[i] = (uint8_t)(epoch >> (56 - i * 8));+	}++	psa_set_key_usage_flags(&attr, PSA_KEY_USAGE_SIGN_MESSAGE);+	psa_set_key_algorithm(&attr, PSA_ALG_HMAC(PSA_ALG_SHA_256));+	psa_set_key_type(&attr, PSA_KEY_TYPE_HMAC);+	psa_set_key_bits(&attr, FF_SECRET_LEN * 8);++	status = psa_import_key(&attr, secret, FF_SECRET_LEN, &key);+	if (status != PSA_SUCCESS) {+		LOG_ERR("psa_import_key: %d", (int)status);+		return -EIO;+	}++	status = psa_mac_sign_setup(&op, key, PSA_ALG_HMAC(PSA_ALG_SHA_256));+	if (status != PSA_SUCCESS) {+		goto out;+	}+	status = psa_mac_update(&op, epoch_domain, sizeof(epoch_domain));+	if (status != PSA_SUCCESS) {+		goto out;+	}+	status = psa_mac_update(&op, epoch_be, sizeof(epoch_be));+	if (status != PSA_SUCCESS) {+		goto out;+	}+	status = psa_mac_sign_finish(&op, mac, sizeof(mac), &mac_len);++out:+	if (status != PSA_SUCCESS) {+		LOG_ERR("HMAC failed: %d", (int)status);+		(void)psa_mac_abort(&op);+		(void)psa_destroy_key(key);+		return -EIO;+	}+	(void)psa_destroy_key(key);++	if (mac_len < FF_EPOCH_ID_LEN) {+		return -EIO;+	}+	/* Truncate to 16 bytes, exactly as the Kotlin and Rust sides do. */+	memcpy(out, mac, FF_EPOCH_ID_LEN);+	return 0;+}
firmware/findfamily-tracker/src/tracker_store.c
diff --git a/firmware/findfamily-tracker/src/tracker_store.c b/firmware/findfamily-tracker/src/tracker_store.cnew file mode 100644index 0000000000..7b1fbc48e3--- /dev/null+++ b/firmware/findfamily-tracker/src/tracker_store.c@@ -0,0 +1,146 @@+/*+ * NVS persistence for the provisioning blob and the time base.+ *+ * A tracker that forgets its secret is a brick — it can only be recovered by+ * re-binding — and one that forgets its time base beacons epoch ids outside the+ * owner's ~2.25 h search window, which looks identical to being out of range. Both+ * therefore live in flash rather than RAM.+ */+#include "ff_tracker.h"++#include <zephyr/kernel.h>+#include <zephyr/device.h>+#include <zephyr/drivers/flash.h>+#include <zephyr/kvss/nvs.h>+#include <zephyr/logging/log.h>+#include <zephyr/storage/flash_map.h>++#include <string.h>++LOG_MODULE_REGISTER(ff_store, LOG_LEVEL_INF);++#define NVS_PARTITION		storage_partition+#define NVS_PARTITION_DEVICE	PARTITION_DEVICE(NVS_PARTITION)+#define NVS_PARTITION_OFFSET	PARTITION_OFFSET(NVS_PARTITION)++/* NVS ids. Append only — reusing an id would read back another field's bytes. */+#define ID_USER_ID  1+#define ID_SECRET   2+#define ID_UNIX     3++static struct nvs_fs fs;+static bool initialized;++int ff_store_init(void)+{+	struct flash_pages_info info;+	const struct device *flash_dev = NVS_PARTITION_DEVICE;+	int rc;++	if (initialized) {+		return 0;+	}+	if (!device_is_ready(flash_dev)) {+		LOG_ERR("flash device not ready");+		return -ENODEV;+	}++	fs.flash_device = flash_dev;+	fs.offset = NVS_PARTITION_OFFSET;+	rc = flash_get_page_info_by_offs(flash_dev, fs.offset, &info);+	if (rc) {+		LOG_ERR("flash_get_page_info_by_offs: %d", rc);+		return rc;+	}+	fs.sector_size = info.size;+	fs.sector_count = 3U;++	rc = nvs_mount(&fs);+	if (rc) {+		LOG_ERR("nvs_mount: %d", rc);+		return rc;+	}+	initialized = true;+	return 0;+}++int ff_store_load(struct ff_tracker_state *out)+{+	ssize_t rc;++	if (!initialized) {+		return -EINVAL;+	}+	memset(out, 0, sizeof(*out));++	rc = nvs_read(&fs, ID_SECRET, out->secret, FF_SECRET_LEN);+	if (rc != FF_SECRET_LEN) {+		LOG_INF("no provisioning stored (secret read = %d)", (int)rc);+		return 0;+	}+	rc = nvs_read(&fs, ID_USER_ID, &out->tracker_user_id, sizeof(out->tracker_user_id));+	if (rc != sizeof(out->tracker_user_id)) {+		/* A secret without a user id can't be reported against, so treat the+		 * pair as absent rather than half-provisioned. */+		LOG_WRN("secret present but user id missing; ignoring provisioning");+		memset(out->secret, 0, FF_SECRET_LEN);+		return 0;+	}+	out->provisioned = true;++	rc = nvs_read(&fs, ID_UNIX, &out->unix_at_base, sizeof(out->unix_at_base));+	if (rc == sizeof(out->unix_at_base)) {+		out->uptime_at_base_ms = k_uptime_get();+	} else {+		out->unix_at_base = 0;+		LOG_WRN("no time base stored; beacon stays off until re-provisioned");+	}+	return 0;+}++int ff_store_save_provisioning(uint64_t tracker_user_id, const uint8_t *secret,+			       uint64_t unix_seconds)+{+	ssize_t rc;++	if (!initialized) {+		return -EINVAL;+	}+	rc = nvs_write(&fs, ID_SECRET, secret, FF_SECRET_LEN);+	if (rc < 0) {+		return (int)rc;+	}+	rc = nvs_write(&fs, ID_USER_ID, &tracker_user_id, sizeof(tracker_user_id));+	if (rc < 0) {+		return (int)rc;+	}+	if (unix_seconds != 0U) {+		rc = nvs_write(&fs, ID_UNIX, &unix_seconds, sizeof(unix_seconds));+		if (rc < 0) {+			return (int)rc;+		}+	}+	return 0;+}++int ff_store_save_time(uint64_t unix_seconds)+{+	ssize_t rc;++	if (!initialized) {+		return -EINVAL;+	}+	rc = nvs_write(&fs, ID_UNIX, &unix_seconds, sizeof(unix_seconds));+	return rc < 0 ? (int)rc : 0;+}++int ff_store_clear(void)+{+	if (!initialized) {+		return -EINVAL;+	}+	(void)nvs_delete(&fs, ID_SECRET);+	(void)nvs_delete(&fs, ID_USER_ID);+	(void)nvs_delete(&fs, ID_UNIX);+	return 0;+}
firmware/findfamily-tracker/src/tracker_sts.c
diff --git a/firmware/findfamily-tracker/src/tracker_sts.c b/firmware/findfamily-tracker/src/tracker_sts.cnew file mode 100644index 0000000000..aaad0870ad--- /dev/null+++ b/firmware/findfamily-tracker/src/tracker_sts.c@@ -0,0 +1,103 @@+/*+ * HKDF-SHA256 derivation of the FiRa session material, mirroring+ * findfamily/src/main/java/com/vayunmathur/findfamily/tracker/TrackerUwbKeys.kt.+ *+ * The phone never sends the STS key or our UWB address: the GATT link is unbonded and+ * unencrypted, so anything on it could be supplied by a stranger standing nearby. Both+ * sides derive from the bind-time beacon secret instead, and the per-find write carries+ * only channel/slot params.+ *+ * A mismatch of a single byte against the Kotlin side shows up as a FiRa session that+ * never converges, with nothing in any log to say why — TrackerUwbKeysTest holds the+ * fixed vectors this must reproduce.+ */+#include "ff_tracker.h"++#include <zephyr/kernel.h>+#include <zephyr/logging/log.h>+#include <psa/crypto.h>++#include <string.h>++LOG_MODULE_REGISTER(ff_sts, LOG_LEVEL_INF);++#define STS_KEY_LEN 8+#define UWB_ADDR_LEN 2++static const char sts_info[] = "com.vayunmathur.findfamily/uwb-sts";+static const char addr_info[] = "com.vayunmathur.findfamily/uwb-addr";++/*+ * Hkdf.kt defaults the salt to 32 zero bytes rather than omitting it. RFC 5869 makes an+ * absent salt equivalent to a zero-filled one of HashLen, so this matches, but PSA needs+ * it passed explicitly.+ */+static const uint8_t zero_salt[32];++static int hkdf_sha256(const uint8_t *ikm, size_t ikm_len, const uint8_t *info,+		       size_t info_len, uint8_t *out, size_t out_len)+{+	psa_status_t status;+	psa_key_derivation_operation_t op = PSA_KEY_DERIVATION_OPERATION_INIT;++	status = psa_key_derivation_setup(&op, PSA_ALG_HKDF(PSA_ALG_SHA_256));+	if (status != PSA_SUCCESS) {+		goto err;+	}+	status = psa_key_derivation_input_bytes(&op, PSA_KEY_DERIVATION_INPUT_SALT,+					       zero_salt, sizeof(zero_salt));+	if (status != PSA_SUCCESS) {+		goto err;+	}+	status = psa_key_derivation_input_bytes(&op, PSA_KEY_DERIVATION_INPUT_SECRET,+					       ikm, ikm_len);+	if (status != PSA_SUCCESS) {+		goto err;+	}+	status = psa_key_derivation_input_bytes(&op, PSA_KEY_DERIVATION_INPUT_INFO,+					       info, info_len);+	if (status != PSA_SUCCESS) {+		goto err;+	}+	status = psa_key_derivation_output_bytes(&op, out, out_len);+	if (status != PSA_SUCCESS) {+		goto err;+	}+	(void)psa_key_derivation_abort(&op);+	return 0;++err:+	LOG_ERR("HKDF failed: %d", (int)status);+	(void)psa_key_derivation_abort(&op);+	return -EIO;+}++int ff_sts_key(const uint8_t *secret, uint32_t session_id, uint8_t *out)+{+	/* info = "…/uwb-sts" || u32_be(sessionId); the trailing NUL is not part of it. */+	uint8_t info[sizeof(sts_info) - 1 + 4];++	memcpy(info, sts_info, sizeof(sts_info) - 1);+	info[sizeof(sts_info) - 1 + 0] = (uint8_t)(session_id >> 24);+	info[sizeof(sts_info) - 1 + 1] = (uint8_t)(session_id >> 16);+	info[sizeof(sts_info) - 1 + 2] = (uint8_t)(session_id >> 8);+	info[sizeof(sts_info) - 1 + 3] = (uint8_t)session_id;++	return hkdf_sha256(secret, FF_SECRET_LEN, info, sizeof(info), out, STS_KEY_LEN);+}++int ff_uwb_address(const uint8_t *secret, uint8_t *out)+{+	int rc = hkdf_sha256(secret, FF_SECRET_LEN, (const uint8_t *)addr_info,+			     sizeof(addr_info) - 1, out, UWB_ADDR_LEN);++	if (rc) {+		return rc;+	}+	/* 0x0000 and 0xFFFF are reserved by FiRa. Nudge exactly as TrackerUwbKeys does,+	 * or the two sides would disagree on the address for those secrets. */+	if ((out[0] == 0x00 && out[1] == 0x00) || (out[0] == 0xFF && out[1] == 0xFF)) {+		out[1] = 0x01;+	}+	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.cnew file mode 100644index 0000000000..4ef382669a--- /dev/null+++ b/firmware/findfamily-tracker/src/tracker_uwb.c@@ -0,0 +1,150 @@+/*+ * FiRa responder/controlee session on the DW3110.+ *+ * NOT COMPILED BY DEFAULT — see CONFIG_FF_TRACKER_UWB in Kconfig and the "UWB" section+ * of README.md. The DW3xxx driver is licensed and not vendored here, so the calls into+ * it below are written against Qorvo's documented API but have never been built or run.+ * Treat every dwt_* call as unverified.+ *+ * Roles: the phone is the controller/initiator (it mints session id, channel, preamble+ * and its own address, and starts ranging); this device is the controlee/responder. The+ * phone's stack uses UwbRangingParams.CONFIG_UNICAST_DS_TWR with static STS, which is+ * what the configuration below aims at:+ *+ *   - double-sided two-way ranging, one initiator and one responder+ *   - static STS, key from ff_sts_key() (FiRa reads those 8 bytes as+ *     [2B VendorID][6B STATIC_STS_IV])+ *   - channel 9, preamble index 10 (UwbController.DEFAULT_CHANNEL / DEFAULT_PREAMBLE)+ *+ * Aligning the ranging-round and block timing with what Android's stack picks is the+ * genuinely uncertain part of this and should be expected to need iteration on real+ * hardware.+ */+#include "ff_tracker.h"++#include <zephyr/kernel.h>+#include <zephyr/logging/log.h>+#include <zephyr/sys/byteorder.h>++/* Provided by the Qorvo DW3xxx driver; see README.md for dropping it in. */+#include <deca_device_api.h>+#include <deca_regs.h>++#include <string.h>++LOG_MODULE_REGISTER(ff_uwb, LOG_LEVEL_INF);++#define STS_KEY_LEN 8++static bool session_active;++int ff_uwb_init(void)+{+	/*+	 * Bring up the DW3110 over SPI. The devicetree overlay names the SPI bus, IRQ,+	 * reset and wakeup lines (see boards/ in this directory).+	 */+	if (dwt_probe(NULL) != DWT_SUCCESS) {+		LOG_ERR("dwt_probe failed: DW3110 not responding on SPI");+		return -ENODEV;+	}+	if (dwt_initialise(DWT_DW_INIT) != DWT_SUCCESS) {+		LOG_ERR("dwt_initialise failed");+		return -EIO;+	}+	LOG_INF("DW3110 initialised");+	return 0;+}++int ff_uwb_start(const struct ff_uwb_params *params, const uint8_t *secret)+{+	uint8_t sts_key[STS_KEY_LEN];+	uint8_t own_address[2];+	int rc;++	if (session_active) {+		ff_uwb_stop();+	}++	rc = ff_sts_key(secret, params->session_id, sts_key);+	if (rc) {+		return rc;+	}+	rc = ff_uwb_address(secret, own_address);+	if (rc) {+		return rc;+	}++	LOG_INF("starting FiRa responder: session=%08x ch=%u preamble=%u peer=%02x%02x own=%02x%02x",+		params->session_id, params->channel, params->preamble_index,+		params->peer_address[0], params->peer_address[1],+		own_address[0], own_address[1]);++	/*+	 * Static STS: the 8 derived bytes are the vendor id + IV, and the FiRa layer+	 * expands them into the STS. Both ends must load identical bytes here — this is+	 * where a Kotlin/firmware HKDF mismatch would silently break ranging.+	 */+	dwt_configurestskey((dwt_sts_cp_key_t *)sts_key);+	dwt_configurestsiv((dwt_sts_cp_iv_t *)sts_key);+	dwt_configurestsloadiv();++	{+		dwt_config_t cfg = {+			.chan = params->channel,+			.txPreambLength = DWT_PLEN_128,+			.rxPAC = DWT_PAC8,+			.txCode = params->preamble_index,+			.rxCode = params->preamble_index,+			.sfdType = DWT_SFD_IEEE_4Z,+			.dataRate = DWT_BR_6M8,+			.phrMode = DWT_PHRMODE_STD,+			.phrRate = DWT_PHRRATE_STD,+			.sfdTO = (129 + 8 - 8),+			.stsMode = DWT_STS_MODE_1,+			.stsLength = DWT_STS_LEN_64,+			.pdoaMode = DWT_PDOA_M0,+		};++		if (dwt_configure(&cfg) != DWT_SUCCESS) {+			LOG_ERR("dwt_configure failed");+			return -EIO;+		}+	}++	/* Responder: sit in receive and reply to the initiator's poll. The FiRa MAC+	 * timing (ranging round/block) is driven by the initiator. */+	dwt_setrxaftertxdelay(0);+	dwt_setrxtimeout(0);+	dwt_rxenable(DWT_START_RX_IMMEDIATE);++	session_active = true;+	return 0;+}++void ff_uwb_stop(void)+{+	if (!session_active) {+		return;+	}+	dwt_forcetrxoff();+	session_active = false;+	LOG_INF("FiRa session stopped");+}++int ff_uwb_on_params(const uint8_t *data, size_t len, const uint8_t *secret)+{+	struct ff_uwb_params params;++	if (len != FF_UWB_PARAMS_LEN) {+		return -EINVAL;+	}+	/* TrackerUwbGatt.encodeSessionParams: [2B addr][4B sessionId BE][1B ch][1B pre] */+	params.peer_address[0] = data[0];+	params.peer_address[1] = data[1];+	params.session_id = sys_get_be32(&data[2]);+	params.channel = data[6];+	params.preamble_index = data[7];++	return ff_uwb_start(&params, secret);+}
firmware/findfamily-tracker/tools/bench_provision.py
diff --git a/firmware/findfamily-tracker/tools/bench_provision.py b/firmware/findfamily-tracker/tools/bench_provision.pynew file mode 100644index 0000000000..b56c22b498--- /dev/null+++ b/firmware/findfamily-tracker/tools/bench_provision.py@@ -0,0 +1,88 @@+"""+Bench-provision a FindFamily tracker from a PC and verify its beacon.++Stands in for the phone so the firmware's crypto and mode switch can be checked+independently of the app: an epoch id that doesn't match what this script computes is a+firmware bug, whereas a matching id the phone can't see is a scanning problem. Those two+look identical from inside the app.++Not part of the firmware build. Run with a BLE-capable PC:+    python tools/bench_provision.py+"""++import asyncio+import hashlib+import hmac+import struct+import sys+import time++from bleak import BleakClient, BleakScanner++UNPROVISIONED_SVC = "6b1d2f01-4b3a-4c7e-9a10-1f2e3d4c5b6a"+BEACON_SVC = "6b1d2f00-4b3a-4c7e-9a10-1f2e3d4c5b6a"+PROVISION_CHR = "6b1d2f02-4b3a-4c7e-9a10-1f2e3d4c5b6a"++EPOCH_SECONDS = 900+TRACKER_USER_ID = 0x0123456789ABCDEF+SECRET = bytes(range(32))+++def epoch_id(secret: bytes, epoch: int) -> bytes:+    """Mirror of TrackerProtocol.epochId / ff_epoch_id."""+    return hmac.new(secret, b"fftrk1" + struct.pack(">Q", epoch), hashlib.sha256).digest()[:16]+++async def main() -> int:+    print(f"scanning for an unprovisioned tracker ({UNPROVISIONED_SVC})...")+    device = await BleakScanner.find_device_by_filter(+        lambda d, ad: UNPROVISIONED_SVC.lower() in [u.lower() for u in ad.service_uuids],+        timeout=15.0,+    )+    if device is None:+        print("no tracker in pairing mode found (long-press the button and retry)")+        return 1+    print(f"found {device.address}")++    now = int(time.time())+    blob = struct.pack(">Q", TRACKER_USER_ID) + SECRET + struct.pack(">Q", now)+    assert len(blob) == 48, len(blob)++    async with BleakClient(device) as client:+        print(f"writing {len(blob)}-byte provisioning blob (unix={now})")+        await client.write_gatt_char(PROVISION_CHR, blob, response=True)+    print("write acknowledged")++    expected = epoch_id(SECRET, now // EPOCH_SECONDS)+    print(f"expected epochId = {expected.hex()}")++    print(f"scanning for the beacon ({BEACON_SVC})...")+    seen: dict = {}++    def on_adv(dev, ad):+        data = ad.service_data.get(BEACON_SVC.lower())+        if data:+            seen[dev.address] = data++    scanner = BleakScanner(detection_callback=on_adv)+    await scanner.start()+    await asyncio.sleep(15.0)+    await scanner.stop()++    if not seen:+        print("no beacon heard. The firmware log is the tiebreaker: if it prints an")+        print("epoch id, the firmware is fine and this PC's adapter is not reporting")+        print("extended advertisements (many Windows adapters do not).")+        return 1++    ok = False+    for addr, data in seen.items():+        got, battery = data[:16], data[16] if len(data) > 16 else -1+        match = "MATCH" if got == expected else "MISMATCH"+        print(f"{addr}: epochId={got.hex()} battery={battery}% -> {match}")+        ok = ok or got == expected+    return 0 if ok else 1+++if __name__ == "__main__":+    sys.exit(asyncio.run(main()))