Modern Apps git
git clone https://git.maproj.org/Modern-Apps.git
cov/c3 ▾

Modern-Apps.git / firmware / findfamily-tracker / src / tracker_ble.c

tracker_ble.c584 lines · 19.6 KiBRaw
1/*
2 * Advertising (two modes) and the GATT server.
3 *
4 * Two advertising modes on one state machine, chosen so only the phone's beacon
5 * scanner needs a change:
6 *
7 * - Pairing: LEGACY connectable adv of the unprovisioned service. Flags + a 128-bit
8 * service UUID is 21 bytes, well inside the 31-byte legacy budget, so
9 * TrackerProvisioner.unprovisioned() keeps working with default (legacy-only)
10 * ScanSettings.
11 *
12 * - Beacon: EXTENDED NON-connectable adv of [16B epochId][1B battery] as service data.
13 * That AD structure is 18B of overhead + 17B of payload = 35 bytes, past the legacy
14 * limit, and the full 16-byte UUID has to be on air because the phone reads it back
15 * with ScanRecord.getServiceData(ParcelUuid). Secondary PHY is pinned to 1M so the
16 * phone needs no coded-PHY scan configuration. Connectability runs on a third, legacy,
17 * dataless set alongside it — see beacon_param for why it cannot live on the beacon
18 * set itself.
19 *
20 * Both characteristics stay registered under the "unprovisioned" service for the
21 * device's whole life; provisioning only stops that service being advertised.
22 */
23#include "ff_tracker.h"
24
25#include <zephyr/kernel.h>
26#include <zephyr/logging/log.h>
27#include <zephyr/bluetooth/bluetooth.h>
28#include <zephyr/bluetooth/conn.h>
29#include <zephyr/bluetooth/gatt.h>
30#include <zephyr/bluetooth/uuid.h>
31#include <zephyr/sys/byteorder.h>
32
33#include <string.h>
34
35LOG_MODULE_REGISTER(ff_ble, LOG_LEVEL_INF);
36
37/* TrackerBle UUIDs, little-endian byte order as bt_uuid_128 wants them. */
38#define FF_UUID_BEACON_SVC \
39 BT_UUID_128_ENCODE(0x6b1d2f00, 0x4b3a, 0x4c7e, 0x9a10, 0x1f2e3d4c5b6a)
40#define FF_UUID_PROV_SVC \
41 BT_UUID_128_ENCODE(0x6b1d2f01, 0x4b3a, 0x4c7e, 0x9a10, 0x1f2e3d4c5b6a)
42#define FF_UUID_PROV_CHR \
43 BT_UUID_128_ENCODE(0x6b1d2f02, 0x4b3a, 0x4c7e, 0x9a10, 0x1f2e3d4c5b6a)
44#define FF_UUID_UWB_CHR \
45 BT_UUID_128_ENCODE(0x6b1d2f03, 0x4b3a, 0x4c7e, 0x9a10, 0x1f2e3d4c5b6a)
46
47static const struct bt_uuid_128 uuid_prov_svc = BT_UUID_INIT_128(FF_UUID_PROV_SVC);
48static const struct bt_uuid_128 uuid_prov_chr = BT_UUID_INIT_128(FF_UUID_PROV_CHR);
49static const struct bt_uuid_128 uuid_uwb_chr = BT_UUID_INIT_128(FF_UUID_UWB_CHR);
50
51static struct ff_tracker_state *state;
52static enum ff_ble_mode current_mode = FF_BLE_MODE_IDLE;
53/*
54 * The mode we want to be in, as distinct from the one we managed to start. Starting a
55 * connectable advertisement needs a spare connection slot, so a mode switch requested
56 * while a phone is still connected can fail; this lets the main loop retry once the
57 * connection drops.
58 */
59static enum ff_ble_mode desired_mode = FF_BLE_MODE_IDLE;
60
61static struct bt_le_ext_adv *pairing_adv;
62static struct bt_le_ext_adv *beacon_adv;
63/* Runs alongside beacon_adv so the owner can connect while crowd-finding. */
64static struct bt_le_ext_adv *connect_adv;
65
66/*
67 * Service-data AD payload: the 16-byte UUID followed by [16B epochId][1B battery].
68 * Held in a static buffer because bt_le_ext_adv_set_data() does not copy — the
69 * controller reads it back when it refreshes the advertisement.
70 */
71static uint8_t beacon_sd[16 + FF_BEACON_DATA_LEN] = { FF_UUID_BEACON_SVC };
72
73static const struct bt_data pairing_ad[] = {
74 BT_DATA_BYTES(BT_DATA_FLAGS, (BT_LE_AD_GENERAL | BT_LE_AD_NO_BREDR)),
75 BT_DATA_BYTES(BT_DATA_UUID128_ALL, FF_UUID_PROV_SVC),
76};
77
78static struct bt_data beacon_ad[] = {
79 /*
80 * The service UUID must be advertised as its own AD field, not just implied by the
81 * service data below. Android's ScanFilter.setServiceUuid() matches against the
82 * Service UUID AD types (0x06/0x07) and ignores service data, so a beacon carrying
83 * only 0x21 is invisible to a filtered scan no matter how correct its payload is.
84 * Costs 18 bytes, which extended advertising has room for.
85 */
86 BT_DATA_BYTES(BT_DATA_UUID128_ALL, FF_UUID_BEACON_SVC),
87 BT_DATA(BT_DATA_SVC_DATA128, beacon_sd, sizeof(beacon_sd)),
88};
89
90/*
91 * Work handed from the Bluetooth RX thread to the main loop. The RX thread's stack
92 * cannot absorb PSA crypto plus bt_le_ext_adv_start(); doing either inline in a write
93 * callback faults with a stack overflow.
94 */
95static atomic_t pending_provision;
96static atomic_t pending_uwb;
97static atomic_t pending_readvertise;
98static uint8_t pending_uwb_params[FF_UWB_PARAMS_LEN];
99
100/*
101 * Reassembly buffer for the provisioning blob. A client that hasn't negotiated a larger
102 * ATT MTU delivers it as a long write in ~20-byte chunks.
103 */
104static uint8_t provision_staging[FF_PROVISION_BLOB_LEN];
105
106/* ---- Connection tracking (bring-up visibility) ------------------------- */
107
108static void on_connected(struct bt_conn *conn, uint8_t err)
109{
110 struct bt_conn_info info;
111
112 if (err) {
113 LOG_WRN("connection failed: 0x%02x", err);
114 return;
115 }
116 if (bt_conn_get_info(conn, &info) == 0) {
117 LOG_INF("connected (interval=%uus latency=%u timeout=%u)",
118 info.le.interval_us, info.le.latency, info.le.timeout);
119 } else {
120 LOG_INF("connected");
121 }
122}
123
124static void on_disconnected(struct bt_conn *conn, uint8_t reason)
125{
126 ARG_UNUSED(conn);
127 /*
128 * Worth logging the reason: 0x08 is a supervision timeout (out of range or the
129 * phone stopped responding) and 0x13/0x16 are a deliberate disconnect by peer or
130 * host, which is what a completed or abandoned bind looks like.
131 */
132 LOG_INF("disconnected (reason=0x%02x)", reason);
133
134 /*
135 * Always ask the main loop to re-apply advertising, not just when the mode we
136 * wanted differs from the one we got. The controller stops a connectable set when
137 * it yields a connection and Zephyr does not restart it, so after one owner
138 * connection connect_adv is down with both modes still BEACON — and the tracker is
139 * unreachable for every later find, which is what made each bring-up iteration need
140 * a power cycle.
141 */
142 atomic_set(&pending_readvertise, 1);
143}
144
145BT_CONN_CB_DEFINE(conn_callbacks) = {
146 .connected = on_connected,
147 .disconnected = on_disconnected,
148};
149
150static void on_mtu_updated(struct bt_conn *conn, uint16_t tx, uint16_t rx)
151{
152 ARG_UNUSED(conn);
153 /*
154 * The provisioning blob is FF_PROVISION_BLOB_LEN bytes and an ATT write carries
155 * MTU-3, so anything below 51 means the client has to use a long write.
156 */
157 LOG_INF("ATT MTU updated: tx=%u rx=%u (%u needed to write the blob in one go)", tx,
158 rx, FF_PROVISION_BLOB_LEN + 3);
159}
160
161static struct bt_gatt_cb gatt_callbacks = {
162 .att_mtu_updated = on_mtu_updated,
163};
164
165/* ---- GATT -------------------------------------------------------------- */
166
167static ssize_t on_provision_write(struct bt_conn *conn, const struct bt_gatt_attr *attr,
168 const void *buf, uint16_t len, uint16_t offset, uint8_t flags)
169{
170 const uint8_t *data = buf;
171 uint64_t user_id;
172 uint64_t unix_seconds = 0U;
173 uint16_t total;
174 int rc;
175
176 ARG_UNUSED(conn);
177 ARG_UNUSED(attr);
178
179 /*
180 * The blob is 48 bytes, well past the 20 usable bytes of a default 23-byte ATT
181 * MTU, so a client that hasn't negotiated a larger MTU sends it as a long write:
182 * several Prepare Writes at increasing offsets, then one Execute Write. Zephyr
183 * reassembles contiguous fragments itself and calls this once with the first
184 * fragment's offset (att.c exec_write_reassemble), but a client is also free to
185 * write at explicit offsets, so chunks are staged here either way.
186 *
187 * The PREPARE flag only ever arrives for an attribute carrying
188 * BT_GATT_PERM_PREPARE_WRITE (att.c:2262), which this one does not; handling it is
189 * kept so that adding the permission cannot silently commit a half blob.
190 */
191 if (flags & BT_GATT_WRITE_FLAG_PREPARE) {
192 return 0;
193 }
194
195 /*
196 * Provisioning is only meaningful while unprovisioned. Refusing it once bound also
197 * surfaces a misdirected write: an 8-byte UWB session-params write landing here
198 * instead of on the UWB characteristic would otherwise be silently accepted as a
199 * partial chunk of a long write, and reported to the phone as success.
200 */
201 if (state->provisioned) {
202 LOG_WRN("provisioning write of %u bytes at offset %u refused: already "
203 "provisioned (misdirected UWB write?)", len, offset);
204 return BT_GATT_ERR(BT_ATT_ERR_WRITE_NOT_PERMITTED);
205 }
206
207 if (offset + len > sizeof(provision_staging)) {
208 LOG_WRN("provisioning write past end of blob (offset=%u len=%u)", offset, len);
209 return BT_GATT_ERR(BT_ATT_ERR_INVALID_ATTRIBUTE_LEN);
210 }
211 memcpy(&provision_staging[offset], data, len);
212 total = offset + len;
213
214 /*
215 * 40 counts as a complete blob only when it arrived in one piece. A 48-byte blob
216 * written at offsets 0/20/40 passes through total == 40 on its way, and treating
217 * that as complete committed provisioning with unix_seconds = 0, set `provisioned`,
218 * and then rejected its own final chunk at the guard above — leaving a tracker with
219 * no time base that can never beacon and can never be re-provisioned. Nothing can
220 * tell the two apart mid-write, so the 40-byte form has to arrive whole; every
221 * producer sends it that way (TrackerBle, tools/bench_provision.py), and it fits a
222 * single write at the MTU this build asks for.
223 */
224 if (total != FF_PROVISION_BLOB_LEN &&
225 !(offset == 0U && len == FF_PROVISION_BLOB_LEN_NO_TIME)) {
226 /* A partial chunk: acknowledge it and wait for the rest. */
227 LOG_DBG("provisioning chunk: offset=%u len=%u", offset, len);
228 return len;
229 }
230 data = provision_staging;
231
232 user_id = sys_get_be64(data);
233 if (total == FF_PROVISION_BLOB_LEN) {
234 unix_seconds = sys_get_be64(&data[8 + FF_SECRET_LEN]);
235 }
236
237 rc = ff_store_save_provisioning(user_id, &data[8], unix_seconds);
238 if (rc) {
239 LOG_ERR("persisting provisioning failed: %d", rc);
240 return BT_GATT_ERR(BT_ATT_ERR_UNLIKELY);
241 }
242
243 state->tracker_user_id = user_id;
244 memcpy(state->secret, &data[8], FF_SECRET_LEN);
245 state->provisioned = true;
246 state->unix_at_base = unix_seconds;
247 state->uptime_at_base_ms = k_uptime_get();
248
249 LOG_INF("provisioned: userId=%llu, %u-byte blob, unix=%llu", user_id, total,
250 unix_seconds);
251 if (unix_seconds == 0U) {
252 LOG_WRN("no timestamp in blob: epoch ids will not resolve for the owner");
253 }
254
255 /* The main loop stops offering to be claimed and starts crowd-finding. */
256 atomic_set(&pending_provision, 1);
257 return len;
258}
259
260static ssize_t on_uwb_write(struct bt_conn *conn, const struct bt_gatt_attr *attr,
261 const void *buf, uint16_t len, uint16_t offset, uint8_t flags)
262{
263 ARG_UNUSED(conn);
264 ARG_UNUSED(attr);
265 ARG_UNUSED(flags);
266
267 LOG_INF("UWB params write: len=%u offset=%u", len, offset);
268
269 if (offset != 0U) {
270 LOG_WRN("UWB params write rejected: offset=%u (expected 0)", offset);
271 return BT_GATT_ERR(BT_ATT_ERR_INVALID_OFFSET);
272 }
273 if (len != FF_UWB_PARAMS_LEN) {
274 LOG_WRN("UWB params write rejected: %u bytes (expected %d)", len,
275 FF_UWB_PARAMS_LEN);
276 return BT_GATT_ERR(BT_ATT_ERR_INVALID_ATTRIBUTE_LEN);
277 }
278 if (!state->provisioned) {
279 /* Without the secret there is no session key, so there is nothing to
280 * start - and an unprovisioned tracker has no owner to be ranged by. */
281 LOG_WRN("UWB params write rejected: not provisioned");
282 return BT_GATT_ERR(BT_ATT_ERR_WRITE_NOT_PERMITTED);
283 }
284 /* Deriving the STS key is PSA work; hand it to the main loop. */
285 memcpy(pending_uwb_params, buf, FF_UWB_PARAMS_LEN);
286 atomic_set(&pending_uwb, 1);
287 return len;
288}
289
290bool ff_ble_take_provision_event(void)
291{
292 return atomic_cas(&pending_provision, 1, 0);
293}
294
295bool ff_ble_take_uwb_params(uint8_t *out)
296{
297 if (!atomic_cas(&pending_uwb, 1, 0)) {
298 return false;
299 }
300 memcpy(out, pending_uwb_params, FF_UWB_PARAMS_LEN);
301 return true;
302}
303
304bool ff_ble_take_readvertise_event(void)
305{
306 return atomic_cas(&pending_readvertise, 1, 0);
307}
308
309BT_GATT_SERVICE_DEFINE(ff_tracker_svc,
310 BT_GATT_PRIMARY_SERVICE(&uuid_prov_svc),
311 BT_GATT_CHARACTERISTIC(&uuid_prov_chr.uuid,
312 BT_GATT_CHRC_WRITE,
313 BT_GATT_PERM_WRITE,
314 NULL, on_provision_write, NULL),
315 BT_GATT_CHARACTERISTIC(&uuid_uwb_chr.uuid,
316 BT_GATT_CHRC_WRITE | BT_GATT_CHRC_NOTIFY,
317 BT_GATT_PERM_WRITE,
318 NULL, on_uwb_write, NULL),
319 BT_GATT_CCC(NULL, BT_GATT_PERM_READ | BT_GATT_PERM_WRITE),
320);
321
322#ifndef CONFIG_FF_TRACKER_UWB
323int ff_uwb_on_params(const uint8_t *data, size_t len, const uint8_t *secret)
324{
325 ARG_UNUSED(data);
326 ARG_UNUSED(len);
327 ARG_UNUSED(secret);
328 /* Accepted and logged so the phone-side GATT write can be exercised on a
329 * BLE-only image; ranging itself needs CONFIG_FF_TRACKER_UWB. */
330 LOG_INF("UWB session params received but CONFIG_FF_TRACKER_UWB=n; ignoring");
331 return 0;
332}
333#endif
334
335/* ---- Advertising ------------------------------------------------------- */
336
337static int create_adv_sets(void)
338{
339 /* Legacy connectable+scannable, so a default-settings scanner sees it. */
340 const struct bt_le_adv_param pairing_param = {
341 .id = BT_ID_DEFAULT,
342 .options = BT_LE_ADV_OPT_CONN,
343 .interval_min = BT_GAP_ADV_FAST_INT_MIN_2,
344 .interval_max = BT_GAP_ADV_FAST_INT_MAX_2,
345 };
346 /*
347 * Beacon data set: extended, NON-connectable.
348 *
349 * BT_LE_ADV_OPT_EXT_ADV without OPT_CODED pins the secondary PHY to 1M, so a phone
350 * scanning with setLegacy(false) on the default PHY sees it.
351 *
352 * Deliberately NOT connectable. A connectable extended advertising set cannot carry
353 * advertising data at all in BLE 5 — ask for both and the controller keeps the data
354 * and quietly drops connectability, so the tracker beacons perfectly while being
355 * impossible to connect to. That cost an evening: the phone timed out with GATT
356 * status 147 while Android's stale service cache kept reporting success from a
357 * previous session. Connectability now lives on its own set below.
358 */
359 const struct bt_le_adv_param beacon_param = {
360 .id = BT_ID_DEFAULT,
361 .options = BT_LE_ADV_OPT_EXT_ADV,
362 .interval_min = BT_GAP_MS_TO_ADV_INTERVAL(CONFIG_FF_TRACKER_BEACON_INTERVAL_MS),
363 .interval_max = BT_GAP_MS_TO_ADV_INTERVAL(CONFIG_FF_TRACKER_BEACON_INTERVAL_MS + 100),
364 .secondary_max_skip = 0,
365 };
366 /*
367 * Connectable set, run alongside the beacon so the owner can still write UWB session
368 * params while crowd-finding. Legacy connectable and carries no data: finders locate
369 * the tracker by the beacon's rotating id, and the owner already knows its address,
370 * so advertising anything identifiable here would only leak a stable identifier.
371 */
372 const struct bt_le_adv_param connect_param = {
373 .id = BT_ID_DEFAULT,
374 .options = BT_LE_ADV_OPT_CONN,
375 .interval_min = BT_GAP_ADV_SLOW_INT_MIN,
376 .interval_max = BT_GAP_ADV_SLOW_INT_MAX,
377 };
378 int rc;
379
380 rc = bt_le_ext_adv_create(&pairing_param, NULL, &pairing_adv);
381 if (rc) {
382 LOG_ERR("creating pairing adv set: %d", rc);
383 return rc;
384 }
385 rc = bt_le_ext_adv_set_data(pairing_adv, pairing_ad, ARRAY_SIZE(pairing_ad), NULL, 0);
386 if (rc) {
387 LOG_ERR("setting pairing adv data: %d", rc);
388 return rc;
389 }
390
391 rc = bt_le_ext_adv_create(&beacon_param, NULL, &beacon_adv);
392 if (rc) {
393 LOG_ERR("creating beacon adv set: %d", rc);
394 return rc;
395 }
396
397 /* No data on this one, deliberately — see connect_param. */
398 rc = bt_le_ext_adv_create(&connect_param, NULL, &connect_adv);
399 if (rc) {
400 LOG_ERR("creating connectable adv set: %d", rc);
401 return rc;
402 }
403 return 0;
404}
405
406int ff_ble_init(struct ff_tracker_state *st)
407{
408 int rc;
409
410 state = st;
411
412 rc = bt_enable(NULL);
413 if (rc) {
414 LOG_ERR("bt_enable: %d", rc);
415 return rc;
416 }
417 bt_gatt_cb_register(&gatt_callbacks);
418 LOG_INF("Bluetooth initialised");
419 return create_adv_sets();
420}
421
422int ff_ble_refresh_beacon(uint8_t battery_percent)
423{
424 uint8_t epoch_id[FF_EPOCH_ID_LEN];
425 uint64_t epoch;
426 int rc;
427
428 if (!state->provisioned) {
429 return -EPERM;
430 }
431 epoch = ff_current_epoch(state);
432 if (epoch == 0U) {
433 /* No time base: any id we produced would fall outside the owner's search
434 * window, so stay quiet rather than fill the air with unresolvable ids. */
435 return -EAGAIN;
436 }
437 rc = ff_epoch_id(state->secret, epoch, epoch_id);
438 if (rc) {
439 return rc;
440 }
441
442 memcpy(&beacon_sd[16], epoch_id, FF_EPOCH_ID_LEN);
443 beacon_sd[16 + FF_EPOCH_ID_LEN] = battery_percent;
444
445 LOG_INF("epoch=%llu id=%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x batt=%u%% %s",
446 epoch, epoch_id[0], epoch_id[1], epoch_id[2], epoch_id[3], epoch_id[4],
447 epoch_id[5], epoch_id[6], epoch_id[7], epoch_id[8], epoch_id[9],
448 epoch_id[10], epoch_id[11], epoch_id[12], epoch_id[13], epoch_id[14],
449 epoch_id[15], battery_percent,
450 current_mode == FF_BLE_MODE_BEACON ? "(on air)" : "(NOT advertising)");
451
452 if (current_mode != FF_BLE_MODE_BEACON) {
453 return 0;
454 }
455 rc = bt_le_ext_adv_set_data(beacon_adv, beacon_ad, ARRAY_SIZE(beacon_ad), NULL, 0);
456 if (rc) {
457 LOG_ERR("refreshing beacon adv data: %d", rc);
458 }
459 return rc;
460}
461
462int ff_ble_set_mode(enum ff_ble_mode mode)
463{
464 int rc;
465
466 desired_mode = mode;
467
468 if (mode == current_mode) {
469 return 0;
470 }
471
472 /* Stopping a set that isn't running returns -EALREADY, which is not a failure
473 * here — mode changes can arrive from the button and from a GATT write. */
474 if (current_mode == FF_BLE_MODE_PAIRING) {
475 rc = bt_le_ext_adv_stop(pairing_adv);
476 if (rc && rc != -EALREADY) {
477 LOG_WRN("stopping pairing adv: %d", rc);
478 }
479 } else if (current_mode == FF_BLE_MODE_BEACON) {
480 rc = bt_le_ext_adv_stop(beacon_adv);
481 if (rc && rc != -EALREADY) {
482 LOG_WRN("stopping beacon adv: %d", rc);
483 }
484 rc = bt_le_ext_adv_stop(connect_adv);
485 if (rc && rc != -EALREADY) {
486 LOG_WRN("stopping connectable adv: %d", rc);
487 }
488 }
489 current_mode = FF_BLE_MODE_IDLE;
490
491 switch (mode) {
492 case FF_BLE_MODE_IDLE:
493 LOG_INF("advertising off");
494 return 0;
495
496 case FF_BLE_MODE_PAIRING:
497 rc = bt_le_ext_adv_start(pairing_adv, BT_LE_EXT_ADV_START_DEFAULT);
498 if (rc) {
499 LOG_ERR("starting pairing adv: %d", rc);
500 return rc;
501 }
502 current_mode = FF_BLE_MODE_PAIRING;
503 LOG_INF("pairing mode: advertising unprovisioned service (legacy)");
504 return 0;
505
506 case FF_BLE_MODE_BEACON:
507 if (!state->provisioned) {
508 LOG_WRN("cannot beacon: not provisioned");
509 return -EPERM;
510 }
511 /* Fill in service data before the first start, or the controller would
512 * advertise a zeroed epoch id for one interval. */
513 current_mode = FF_BLE_MODE_BEACON;
514 rc = ff_ble_refresh_beacon(100);
515 if (rc == -EAGAIN) {
516 current_mode = FF_BLE_MODE_IDLE;
517 LOG_WRN("cannot beacon: no time base");
518 return rc;
519 }
520 if (rc) {
521 current_mode = FF_BLE_MODE_IDLE;
522 return rc;
523 }
524 rc = bt_le_ext_adv_start(beacon_adv, BT_LE_EXT_ADV_START_DEFAULT);
525 if (rc) {
526 current_mode = FF_BLE_MODE_IDLE;
527 LOG_ERR("starting beacon adv: %d", rc);
528 return rc;
529 }
530 /*
531 * Connectability is a separate set. Failing to start it is not fatal — the
532 * tracker is still findable, it just can't be ranged until the next attempt
533 * — so log and carry on rather than dropping out of beacon mode.
534 */
535 rc = bt_le_ext_adv_start(connect_adv, BT_LE_EXT_ADV_START_DEFAULT);
536 if (rc) {
537 LOG_WRN("starting connectable adv: %d (UWB handover unavailable)", rc);
538 }
539 LOG_INF("beacon mode: rotating epoch id (extended) + connectable set");
540 return 0;
541 }
542 return -EINVAL;
543}
544
545enum ff_ble_mode ff_ble_mode(void)
546{
547 return current_mode;
548}
549
550int ff_ble_readvertise(void)
551{
552 struct bt_le_ext_adv *adv;
553 int rc;
554
555 if (desired_mode != current_mode) {
556 /* The mode we wanted never started — usually beacon mode attempted while
557 * the binding phone still held the connection slot. */
558 return ff_ble_set_mode(desired_mode);
559 }
560 /*
561 * Otherwise the mode is already current, so ff_ble_set_mode() would return early
562 * and restart nothing — yet the connectable set of that mode is down, because the
563 * controller stops a connectable advertisement when it yields a connection and
564 * nothing in the host restarts an extended-API set. Left alone, the tracker takes
565 * exactly one connection per mode change: one UWB handover, or one attempt at a
566 * bind.
567 */
568 if (current_mode == FF_BLE_MODE_BEACON) {
569 adv = connect_adv;
570 } else if (current_mode == FF_BLE_MODE_PAIRING) {
571 adv = pairing_adv;
572 } else {
573 return 0;
574 }
575
576 /* -EALREADY means it is still running, which is not a failure. */
577 rc = bt_le_ext_adv_start(adv, BT_LE_EXT_ADV_START_DEFAULT);
578 if (rc && rc != -EALREADY) {
579 LOG_WRN("restarting connectable adv: %d (not reachable until the next mode "
580 "change)", rc);
581 return rc;
582 }
583 return 0;
584}