findfamily: fix tracker bind MTU, long writes and beacon start
- Commit
d993a494ac625412bf9728fe2093a4f5b203698f- Author
- vayun-mathur <[email protected]>
- When
- 2026-08-21 22:47 UTC (3 months ago)
- Parents
4a2a62b
Diff
findfamily/src/main/java/com/vayunmathur/findfamily/tracker/TrackerProvisioner.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/tracker/TrackerProvisioner.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/tracker/TrackerProvisioner.ktindex 56a7611fe3..3d7979f122 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/tracker/TrackerProvisioner.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/tracker/TrackerProvisioner.kt@@ -102,23 +102,46 @@ class TrackerProvisioner(private val context: Context) { val callback = object : BluetoothGattCallback() { override fun onConnectionStateChange(g: BluetoothGatt, status: Int, newState: Int) { if (newState == BluetoothProfile.STATE_CONNECTED) {- runCatching { g.discoverServices() }+ /*+ * Ask for an MTU big enough to carry the whole blob in one ATT+ * write. On the default 23-byte MTU only 20 bytes fit, so the+ * stack would fall back to a long write — which works, but only+ * if the peer reassembles chunked offsets, and it is slower.+ * Service discovery waits for the MTU result.+ */+ if (!runCatching { g.requestMtu(PREFERRED_MTU) }.getOrDefault(false)) {+ Log.w(TAG, "requestMtu failed; continuing on default MTU")+ runCatching { g.discoverServices() }+ } } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {+ Log.i(TAG, "disconnected before the write completed (status=$status)") finish(false) } } + override fun onMtuChanged(g: BluetoothGatt, mtu: Int, status: Int) {+ Log.i(TAG, "MTU now $mtu (status=$status); discovering services")+ runCatching { g.discoverServices() }+ }+ override fun onServicesDiscovered(g: BluetoothGatt, status: Int) {- if (status != BluetoothGatt.GATT_SUCCESS) { finish(false); return }+ if (status != BluetoothGatt.GATT_SUCCESS) {+ Log.w(TAG, "service discovery failed: $status")+ finish(false); return+ } val ch = g.getService(TrackerBle.UNPROVISIONED_SERVICE_UUID) ?.getCharacteristic(TrackerBle.PROVISION_CHARACTERISTIC_UUID)- if (ch == null) { finish(false); return }+ if (ch == null) {+ Log.w(TAG, "provisioning characteristic not found on this device")+ finish(false); return+ } val ok = writeChar(g, ch, blob) if (!ok) finish(false) } @Deprecated("compat shim for API < 33") override fun onCharacteristicWrite(g: BluetoothGatt, ch: BluetoothGattCharacteristic, status: Int) {+ Log.i(TAG, "provisioning write completed with status=$status") finish(status == BluetoothGatt.GATT_SUCCESS) } }@@ -151,5 +174,11 @@ class TrackerProvisioner(private val context: Context) { companion object { private const val TAG = "TrackerProvisioner"++ /**+ * Enough for `[TrackerBle.PROVISION_BLOB_LEN]` plus the 3-byte ATT write header,+ * with room to spare. Keeps the blob in a single write instead of a long write.+ */+ private const val PREFERRED_MTU = 64 } }
firmware/findfamily-tracker/prj.conf
diff --git a/firmware/findfamily-tracker/prj.conf b/firmware/findfamily-tracker/prj.confindex 7d6c0124b4..d5ffcbeb4e 100644--- a/firmware/findfamily-tracker/prj.conf+++ b/firmware/findfamily-tracker/prj.conf@@ -10,6 +10,10 @@ CONFIG_BT=y CONFIG_BT_PERIPHERAL=y CONFIG_BT_DEVICE_NAME="FF Tracker" CONFIG_BT_DEVICE_APPEARANCE=0+# Two connection slots, not one. The switch to beacon mode happens while the binding+# phone is still attached, and starting a *connectable* advertisement needs a free slot —+# with a single slot it fails with -ENOMEM and the tracker ends up advertising nothing.+CONFIG_BT_MAX_CONN=2 # 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@@ -20,8 +24,11 @@ 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.+# A client on the default 23-byte ATT MTU sends the 48-byte provisioning blob as a long+# write in ~20-byte chunks, so there must be room to queue at least three of them.+CONFIG_BT_ATT_PREPARE_COUNT=6+# Must fit the 48-byte provisioning write in a single ATT operation when the client does+# negotiate a larger MTU (the app asks for one). CONFIG_BT_BUF_ACL_RX_SIZE=69 CONFIG_BT_L2CAP_TX_MTU=65
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 53fdd4c086..b9307bf87a 100644--- a/firmware/findfamily-tracker/src/ff_tracker.h+++ b/firmware/findfamily-tracker/src/ff_tracker.h@@ -103,6 +103,16 @@ 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); +/*+ * 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.+ */+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);+ /* 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 d1e2e1bfaa..f97f5b277a 100644--- a/firmware/findfamily-tracker/src/main.c+++ b/firmware/findfamily-tracker/src/main.c@@ -153,10 +153,18 @@ int main(void) 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);+ /* Expected while the phone is still connected: a connectable+ * advertisement needs a free connection slot. The disconnect+ * handler asks us to retry. */+ LOG_INF("beacon will start once the phone disconnects"); } } + if (ff_ble_take_readvertise_event()) {+ LOG_INF("connection slot free: re-applying advertising mode");+ (void)ff_ble_set_mode(ff_ble_desired_mode());+ }+ { uint8_t uwb_params[FF_UWB_PARAMS_LEN];
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 ec80cef71c..5f63971e81 100644--- a/firmware/findfamily-tracker/src/tracker_ble.c+++ b/firmware/findfamily-tracker/src/tracker_ble.c@@ -49,6 +49,13 @@ 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;+/*+ * The mode we want to be in, as distinct from the one we managed to start. Starting a+ * connectable advertisement needs a spare connection slot, so a mode switch requested+ * while a phone is still connected can fail; this lets the main loop retry once the+ * connection drops.+ */+static enum ff_ble_mode desired_mode = FF_BLE_MODE_IDLE; static struct bt_le_ext_adv *pairing_adv; static struct bt_le_ext_adv *beacon_adv;@@ -76,8 +83,74 @@ static struct bt_data beacon_ad[] = { */ static atomic_t pending_provision; static atomic_t pending_uwb;+static atomic_t pending_readvertise; static uint8_t pending_uwb_params[FF_UWB_PARAMS_LEN]; +/*+ * Reassembly buffer for the provisioning blob. A client that hasn't negotiated a larger+ * ATT MTU delivers it as a long write in ~20-byte chunks.+ */+static uint8_t provision_staging[FF_PROVISION_BLOB_LEN];++/* ---- Connection tracking (bring-up visibility) ------------------------- */++static void on_connected(struct bt_conn *conn, uint8_t err)+{+ struct bt_conn_info info;++ if (err) {+ LOG_WRN("connection failed: 0x%02x", err);+ return;+ }+ if (bt_conn_get_info(conn, &info) == 0) {+ LOG_INF("connected (interval=%uus latency=%u timeout=%u)",+ info.le.interval_us, info.le.latency, info.le.timeout);+ } else {+ LOG_INF("connected");+ }+}++static void on_disconnected(struct bt_conn *conn, uint8_t reason)+{+ ARG_UNUSED(conn);+ /*+ * Worth logging the reason: 0x08 is a supervision timeout (out of range or the+ * phone stopped responding) and 0x13/0x16 are a deliberate disconnect by peer or+ * host, which is what a completed or abandoned bind looks like.+ */+ 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.+ */+ if (desired_mode != current_mode) {+ atomic_set(&pending_readvertise, 1);+ }+}++BT_CONN_CB_DEFINE(conn_callbacks) = {+ .connected = on_connected,+ .disconnected = on_disconnected,+};++static void on_mtu_updated(struct bt_conn *conn, uint16_t tx, uint16_t rx)+{+ ARG_UNUSED(conn);+ /*+ * The provisioning blob is FF_PROVISION_BLOB_LEN bytes and an ATT write carries+ * MTU-3, so anything below 51 means the client has to use a long write.+ */+ LOG_INF("ATT MTU updated: tx=%u rx=%u (%u needed to write the blob in one go)", tx,+ rx, FF_PROVISION_BLOB_LEN + 3);+}++static struct bt_gatt_cb gatt_callbacks = {+ .att_mtu_updated = on_mtu_updated,+};+ /* ---- GATT -------------------------------------------------------------- */ static ssize_t on_provision_write(struct bt_conn *conn, const struct bt_gatt_attr *attr,@@ -86,23 +159,41 @@ static ssize_t on_provision_write(struct bt_conn *conn, const struct bt_gatt_att const uint8_t *data = buf; uint64_t user_id; uint64_t unix_seconds = 0U;+ uint16_t total; int rc; ARG_UNUSED(conn); ARG_UNUSED(attr);- ARG_UNUSED(flags); - if (offset != 0U) {- return BT_GATT_ERR(BT_ATT_ERR_INVALID_OFFSET);+ /*+ * 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.+ *+ * 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.+ */+ if (flags & BT_GATT_WRITE_FLAG_PREPARE) {+ return 0; }- 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);++ if (offset + len > sizeof(provision_staging)) {+ LOG_WRN("provisioning write past end of blob (offset=%u len=%u)", offset, len); return BT_GATT_ERR(BT_ATT_ERR_INVALID_ATTRIBUTE_LEN); }+ memcpy(&provision_staging[offset], data, len);+ total = offset + len;++ if (total != FF_PROVISION_BLOB_LEN && total != 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;+ }+ data = provision_staging; user_id = sys_get_be64(data);- if (len == FF_PROVISION_BLOB_LEN) {+ if (total == FF_PROVISION_BLOB_LEN) { unix_seconds = sys_get_be64(&data[8 + FF_SECRET_LEN]); } @@ -118,7 +209,7 @@ static ssize_t on_provision_write(struct bt_conn *conn, const struct bt_gatt_att 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,+ LOG_INF("provisioned: userId=%llu, %u-byte blob, unix=%llu", user_id, total, unix_seconds); if (unix_seconds == 0U) { LOG_WRN("no timestamp in blob: epoch ids will not resolve for the owner");@@ -168,6 +259,16 @@ bool ff_ble_take_uwb_params(uint8_t *out) return true; } +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,@@ -251,6 +352,7 @@ int ff_ble_init(struct ff_tracker_state *st) LOG_ERR("bt_enable: %d", rc); return rc; }+ bt_gatt_cb_register(&gatt_callbacks); LOG_INF("Bluetooth initialised"); return create_adv_sets(); }@@ -278,11 +380,12 @@ int ff_ble_refresh_beacon(uint8_t battery_percent) 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%%",+ LOG_INF("epoch=%llu id=%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x batt=%u%% %s", 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);+ epoch_id[15], battery_percent,+ current_mode == FF_BLE_MODE_BEACON ? "(on air)" : "(NOT advertising)"); if (current_mode != FF_BLE_MODE_BEACON) { return 0;@@ -298,6 +401,8 @@ int ff_ble_set_mode(enum ff_ble_mode mode) { int rc; + desired_mode = mode;+ if (mode == current_mode) { return 0; }
firmware/findfamily-tracker/tools/bench_provision.py
diff --git a/firmware/findfamily-tracker/tools/bench_provision.py b/firmware/findfamily-tracker/tools/bench_provision.pyindex b56c22b498..ac9666fae0 100644--- a/firmware/findfamily-tracker/tools/bench_provision.py+++ b/firmware/findfamily-tracker/tools/bench_provision.py@@ -70,9 +70,10 @@ async def main() -> int: 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).")+ print("no beacon heard. Check the firmware log first: it prints the live epoch id")+ print("every second and marks whether it is '(on air)' or '(NOT advertising)'.")+ print("If it says NOT advertising, the tracker never started the beacon and this")+ print("is a firmware problem, not a reception one.") return 1 ok = False