1 /*
2  * Copyright (c) 2021-2022 Nordic Semiconductor ASA
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  */
6 
7 #include <stdbool.h>
8 #include <stddef.h>
9 #include <stdint.h>
10 #include <string.h>
11 
12 #include <zephyr/autoconf.h>
13 #include <zephyr/bluetooth/addr.h>
14 #include <zephyr/bluetooth/audio/audio.h>
15 #include <zephyr/bluetooth/audio/bap.h>
16 #include <zephyr/bluetooth/bluetooth.h>
17 #include <zephyr/bluetooth/byteorder.h>
18 #include <zephyr/bluetooth/gap.h>
19 #include <zephyr/bluetooth/iso.h>
20 #include <zephyr/bluetooth/uuid.h>
21 #include <zephyr/kernel.h>
22 #include <zephyr/net/buf.h>
23 #include <zephyr/sys/byteorder.h>
24 #include <zephyr/sys/printk.h>
25 #include <zephyr/sys/util.h>
26 #include <zephyr/sys/util_macro.h>
27 
28 #include "bstests.h"
29 #include "common.h"
30 
31 #ifdef CONFIG_BT_BAP_SCAN_DELEGATOR
32 extern enum bst_result_t bst_result;
33 
34 #define PA_SYNC_INTERVAL_TO_TIMEOUT_RATIO 20 /* Set the timeout relative to interval */
35 #define PA_SYNC_SKIP              5
36 
37 CREATE_FLAG(flag_pa_synced);
38 CREATE_FLAG(flag_pa_terminated);
39 CREATE_FLAG(flag_broadcast_code_received);
40 CREATE_FLAG(flag_recv_state_updated);
41 CREATE_FLAG(flag_bis_sync_requested);
42 CREATE_FLAG(flag_bis_sync_term_requested);
43 static volatile uint32_t g_broadcast_id;
44 
45 struct sync_state {
46 	uint8_t src_id;
47 	const struct bt_bap_scan_delegator_recv_state *recv_state;
48 	bool pa_syncing;
49 	struct k_work_delayable pa_timer;
50 	struct bt_le_per_adv_sync *pa_sync;
51 	uint8_t broadcast_code[BT_AUDIO_BROADCAST_CODE_SIZE];
52 	uint32_t bis_sync_req[CONFIG_BT_BAP_BASS_MAX_SUBGROUPS];
53 } sync_states[CONFIG_BT_BAP_SCAN_DELEGATOR_RECV_STATE_COUNT];
54 
sync_state_get(const struct bt_bap_scan_delegator_recv_state * recv_state)55 static struct sync_state *sync_state_get(const struct bt_bap_scan_delegator_recv_state *recv_state)
56 {
57 	for (size_t i = 0U; i < ARRAY_SIZE(sync_states); i++) {
58 		if (sync_states[i].recv_state == recv_state) {
59 			return &sync_states[i];
60 		}
61 	}
62 
63 	return NULL;
64 }
65 
sync_state_get_or_new(const struct bt_bap_scan_delegator_recv_state * recv_state)66 static struct sync_state *sync_state_get_or_new(
67 	const struct bt_bap_scan_delegator_recv_state *recv_state)
68 {
69 	struct sync_state *free_state = NULL;
70 
71 	for (size_t i = 0U; i < ARRAY_SIZE(sync_states); i++) {
72 		if (sync_states[i].recv_state == NULL &&
73 		    free_state == NULL) {
74 			free_state = &sync_states[i];
75 
76 			if (recv_state == NULL) {
77 				return free_state;
78 			}
79 		}
80 
81 		if (sync_states[i].recv_state == recv_state) {
82 			return &sync_states[i];
83 		}
84 	}
85 
86 	return free_state;
87 }
88 
sync_state_get_by_pa(struct bt_le_per_adv_sync * sync)89 static struct sync_state *sync_state_get_by_pa(struct bt_le_per_adv_sync *sync)
90 {
91 	for (size_t i = 0U; i < ARRAY_SIZE(sync_states); i++) {
92 		if (sync_states[i].pa_sync == sync) {
93 			return &sync_states[i];
94 		}
95 	}
96 
97 	return NULL;
98 }
99 
sync_state_get_by_src_id(uint8_t src_id)100 static struct sync_state *sync_state_get_by_src_id(uint8_t src_id)
101 {
102 	for (size_t i = 0U; i < ARRAY_SIZE(sync_states); i++) {
103 		if (sync_states[i].src_id == src_id) {
104 			return &sync_states[i];
105 		}
106 	}
107 
108 	return NULL;
109 }
110 
interval_to_sync_timeout(uint16_t pa_interval)111 static uint16_t interval_to_sync_timeout(uint16_t pa_interval)
112 {
113 	uint16_t pa_timeout;
114 
115 	if (pa_interval == BT_BAP_PA_INTERVAL_UNKNOWN) {
116 		/* Use maximum value to maximize chance of success */
117 		pa_timeout = BT_GAP_PER_ADV_MAX_TIMEOUT;
118 	} else {
119 		uint32_t interval_ms;
120 		uint32_t timeout;
121 
122 		/* Add retries and convert to unit in 10's of ms */
123 		interval_ms = BT_GAP_PER_ADV_INTERVAL_TO_MS(pa_interval);
124 		timeout = (interval_ms * PA_SYNC_INTERVAL_TO_TIMEOUT_RATIO) / 10;
125 
126 		/* Enforce restraints */
127 		pa_timeout = CLAMP(timeout, BT_GAP_PER_ADV_MIN_TIMEOUT, BT_GAP_PER_ADV_MAX_TIMEOUT);
128 	}
129 
130 	return pa_timeout;
131 }
132 
pa_timer_handler(struct k_work * work)133 static void pa_timer_handler(struct k_work *work)
134 {
135 	struct k_work_delayable *dwork = k_work_delayable_from_work(work);
136 	struct sync_state *state = CONTAINER_OF(dwork, struct sync_state, pa_timer);
137 
138 	state->pa_syncing = false;
139 
140 	if (state->recv_state != NULL) {
141 		enum bt_bap_pa_state pa_state;
142 
143 		if (state->recv_state->pa_sync_state == BT_BAP_PA_STATE_INFO_REQ) {
144 			pa_state = BT_BAP_PA_STATE_NO_PAST;
145 		} else {
146 			pa_state = BT_BAP_PA_STATE_FAILED;
147 		}
148 
149 		bt_bap_scan_delegator_set_pa_state(state->recv_state->src_id,
150 						   pa_state);
151 	}
152 
153 	FAIL("PA timeout\n");
154 }
155 
pa_sync_past(struct bt_conn * conn,struct sync_state * state,uint16_t pa_interval)156 static int pa_sync_past(struct bt_conn *conn,
157 			struct sync_state *state,
158 			uint16_t pa_interval)
159 {
160 	struct bt_le_per_adv_sync_transfer_param param = { 0 };
161 	int err;
162 
163 	param.skip = PA_SYNC_SKIP;
164 	param.timeout = interval_to_sync_timeout(pa_interval);
165 
166 	err = bt_le_per_adv_sync_transfer_subscribe(conn, &param);
167 	if (err != 0) {
168 		printk("Could not do PAST subscribe: %d\n", err);
169 	} else {
170 		printk("Syncing with PAST: %d\n", err);
171 		state->pa_syncing = true;
172 		k_work_init_delayable(&state->pa_timer, pa_timer_handler);
173 		(void)k_work_reschedule(&state->pa_timer,
174 					K_MSEC(param.timeout * 10));
175 	}
176 
177 	return err;
178 }
179 
pa_sync_no_past(struct sync_state * state,uint16_t pa_interval)180 static int pa_sync_no_past(struct sync_state *state,
181 			    uint16_t pa_interval)
182 {
183 	const struct bt_bap_scan_delegator_recv_state *recv_state;
184 	struct bt_le_per_adv_sync_param param = { 0 };
185 	int err;
186 
187 	recv_state = state->recv_state;
188 	state->src_id = recv_state->src_id;
189 
190 	bt_addr_le_copy(&param.addr, &recv_state->addr);
191 	param.sid = recv_state->adv_sid;
192 	param.skip = PA_SYNC_SKIP;
193 	param.timeout = interval_to_sync_timeout(pa_interval);
194 
195 	/* TODO: Validate that the advertise is broadcasting the same
196 	 * broadcast_id that the receive state has
197 	 */
198 	err = bt_le_per_adv_sync_create(&param, &state->pa_sync);
199 	if (err != 0) {
200 		printk("Could not sync per adv: %d\n", err);
201 	} else {
202 		char addr_str[BT_ADDR_LE_STR_LEN];
203 
204 		bt_addr_le_to_str(&recv_state->addr, addr_str, sizeof(addr_str));
205 		printk("PA sync pending for addr %s\n", addr_str);
206 		state->pa_syncing = true;
207 		k_work_init_delayable(&state->pa_timer, pa_timer_handler);
208 		(void)k_work_reschedule(&state->pa_timer,
209 					K_MSEC(param.timeout * 10));
210 	}
211 
212 	return err;
213 }
214 
pa_sync_term(struct sync_state * state)215 static int pa_sync_term(struct sync_state *state)
216 {
217 	int err;
218 
219 	(void)k_work_cancel_delayable(&state->pa_timer);
220 
221 	if (state->pa_sync == NULL) {
222 		return -1;
223 	}
224 
225 	printk("Deleting PA sync\n");
226 
227 	err = bt_le_per_adv_sync_delete(state->pa_sync);
228 	if (err != 0) {
229 		FAIL("Could not delete per adv sync: %d\n", err);
230 	} else {
231 		state->pa_syncing = false;
232 		state->pa_sync = NULL;
233 	}
234 
235 	return err;
236 }
237 
recv_state_updated_cb(struct bt_conn * conn,const struct bt_bap_scan_delegator_recv_state * recv_state)238 static void recv_state_updated_cb(struct bt_conn *conn,
239 				  const struct bt_bap_scan_delegator_recv_state *recv_state)
240 {
241 	struct sync_state *state;
242 
243 	printk("Receive state with ID %u updated\n", recv_state->src_id);
244 
245 	state = sync_state_get_by_src_id(recv_state->src_id);
246 	if (state == NULL) {
247 		FAIL("Could not get state");
248 		return;
249 	}
250 
251 	if (state->recv_state != NULL) {
252 		if (state->recv_state != recv_state) {
253 			FAIL("Sync state receive state mismatch: %p - %p",
254 			     state->recv_state, recv_state);
255 			return;
256 		}
257 	} else {
258 		state->recv_state = recv_state;
259 	}
260 
261 	SET_FLAG(flag_recv_state_updated);
262 }
263 
pa_sync_req_cb(struct bt_conn * conn,const struct bt_bap_scan_delegator_recv_state * recv_state,bool past_avail,uint16_t pa_interval)264 static int pa_sync_req_cb(struct bt_conn *conn,
265 			  const struct bt_bap_scan_delegator_recv_state *recv_state,
266 			  bool past_avail, uint16_t pa_interval)
267 {
268 	struct sync_state *state;
269 	int err;
270 
271 	printk("PA Sync request: past_avail %u, pa_interval 0x%04x\n: %p",
272 	       past_avail, pa_interval, recv_state);
273 
274 	state = sync_state_get_or_new(recv_state);
275 	if (state == NULL) {
276 		FAIL("Could not get state");
277 		return -1;
278 	}
279 
280 	state->recv_state = recv_state;
281 	state->src_id = recv_state->src_id;
282 
283 	if (recv_state->pa_sync_state == BT_BAP_PA_STATE_SYNCED ||
284 	    recv_state->pa_sync_state == BT_BAP_PA_STATE_INFO_REQ) {
285 		/* Already syncing */
286 		/* TODO: Terminate existing sync and then sync to new?*/
287 		return -1;
288 	}
289 
290 	if (past_avail) {
291 		err = pa_sync_past(conn, state, pa_interval);
292 	} else {
293 		err = pa_sync_no_past(state, pa_interval);
294 	}
295 
296 	return err;
297 }
298 
pa_sync_term_req_cb(struct bt_conn * conn,const struct bt_bap_scan_delegator_recv_state * recv_state)299 static int pa_sync_term_req_cb(struct bt_conn *conn,
300 			       const struct bt_bap_scan_delegator_recv_state *recv_state)
301 {
302 	struct sync_state *state;
303 
304 	printk("PA Sync term request for %p\n", recv_state);
305 
306 	state = sync_state_get(recv_state);
307 	if (state == NULL) {
308 		FAIL("Could not get state\n");
309 		return -1;
310 	}
311 
312 	return pa_sync_term(state);
313 }
314 
broadcast_code_cb(struct bt_conn * conn,const struct bt_bap_scan_delegator_recv_state * recv_state,const uint8_t broadcast_code[BT_AUDIO_BROADCAST_CODE_SIZE])315 static void broadcast_code_cb(struct bt_conn *conn,
316 			      const struct bt_bap_scan_delegator_recv_state *recv_state,
317 			      const uint8_t broadcast_code[BT_AUDIO_BROADCAST_CODE_SIZE])
318 {
319 	struct sync_state *state;
320 
321 	printk("Broadcast code received for %p\n", recv_state);
322 
323 	state = sync_state_get(recv_state);
324 	if (state == NULL) {
325 		FAIL("Could not get state\n");
326 		return;
327 	}
328 
329 	(void)memcpy(state->broadcast_code, broadcast_code, BT_AUDIO_BROADCAST_CODE_SIZE);
330 
331 	SET_FLAG(flag_broadcast_code_received);
332 }
333 
bis_sync_req_cb(struct bt_conn * conn,const struct bt_bap_scan_delegator_recv_state * recv_state,const uint32_t bis_sync_req[CONFIG_BT_BAP_BASS_MAX_SUBGROUPS])334 static int bis_sync_req_cb(struct bt_conn *conn,
335 			   const struct bt_bap_scan_delegator_recv_state *recv_state,
336 			   const uint32_t bis_sync_req[CONFIG_BT_BAP_BASS_MAX_SUBGROUPS])
337 {
338 	struct sync_state *state;
339 	bool sync_bis;
340 
341 	printk("BIS sync request received for %p\n", recv_state);
342 	for (int i = 0; i < CONFIG_BT_BAP_BASS_MAX_SUBGROUPS; i++) {
343 		if (bis_sync_req[i]) {
344 			sync_bis = true;
345 		}
346 
347 		printk("  [%d]: 0x%08x\n", i, bis_sync_req[i]);
348 	}
349 
350 	state = sync_state_get(recv_state);
351 	if (state == NULL) {
352 		FAIL("Could not get state\n");
353 		return -1;
354 	}
355 
356 	(void)memcpy(state->bis_sync_req, bis_sync_req,
357 		     sizeof(state->bis_sync_req));
358 
359 	if (sync_bis) {
360 		SET_FLAG(flag_bis_sync_requested);
361 	} else {
362 		SET_FLAG(flag_bis_sync_term_requested);
363 	}
364 
365 	return 0;
366 }
367 
368 static struct bt_bap_scan_delegator_cb scan_delegator_cb = {
369 	.recv_state_updated = recv_state_updated_cb,
370 	.pa_sync_req = pa_sync_req_cb,
371 	.pa_sync_term_req = pa_sync_term_req_cb,
372 	.broadcast_code = broadcast_code_cb,
373 	.bis_sync_req = bis_sync_req_cb,
374 };
375 
pa_synced_cb(struct bt_le_per_adv_sync * sync,struct bt_le_per_adv_sync_synced_info * info)376 static void pa_synced_cb(struct bt_le_per_adv_sync *sync,
377 			 struct bt_le_per_adv_sync_synced_info *info)
378 {
379 	struct sync_state *state;
380 
381 	printk("PA %p synced\n", sync);
382 
383 	state = sync_state_get_by_pa(sync);
384 	if (state == NULL) {
385 		FAIL("Could not get sync state from PA sync %p\n", sync);
386 		return;
387 	}
388 
389 	k_work_cancel_delayable(&state->pa_timer);
390 
391 	SET_FLAG(flag_pa_synced);
392 }
393 
pa_term_cb(struct bt_le_per_adv_sync * sync,const struct bt_le_per_adv_sync_term_info * info)394 static void pa_term_cb(struct bt_le_per_adv_sync *sync,
395 		       const struct bt_le_per_adv_sync_term_info *info)
396 {
397 	struct sync_state *state;
398 
399 	printk("PA %p sync terminated\n", sync);
400 
401 	state = sync_state_get_by_pa(sync);
402 	if (state == NULL) {
403 		FAIL("Could not get sync state from PA sync %p\n", sync);
404 		return;
405 	}
406 
407 	k_work_cancel_delayable(&state->pa_timer);
408 
409 	SET_FLAG(flag_pa_terminated);
410 }
411 
412 static struct bt_le_per_adv_sync_cb pa_sync_cb =  {
413 	.synced = pa_synced_cb,
414 	.term = pa_term_cb,
415 };
416 
broadcast_source_found(struct bt_data * data,void * user_data)417 static bool broadcast_source_found(struct bt_data *data, void *user_data)
418 {
419 	struct bt_le_per_adv_sync_param sync_create_param = { 0 };
420 	const struct bt_le_scan_recv_info *info = user_data;
421 	char addr_str[BT_ADDR_LE_STR_LEN];
422 	struct bt_uuid_16 adv_uuid;
423 	struct sync_state *state;
424 	int err;
425 
426 
427 	if (data->type != BT_DATA_SVC_DATA16) {
428 		return true;
429 	}
430 
431 	if (data->data_len < BT_UUID_SIZE_16 + BT_AUDIO_BROADCAST_ID_SIZE) {
432 		return true;
433 	}
434 
435 	if (!bt_uuid_create(&adv_uuid.uuid, data->data, BT_UUID_SIZE_16)) {
436 		return true;
437 	}
438 
439 	if (bt_uuid_cmp(&adv_uuid.uuid, BT_UUID_BROADCAST_AUDIO) != 0) {
440 		return true;
441 	}
442 
443 	g_broadcast_id = sys_get_le24(data->data + BT_UUID_SIZE_16);
444 	bt_addr_le_to_str(info->addr, addr_str, sizeof(addr_str));
445 
446 	printk("Found BAP broadcast source with address %s and ID 0x%06X\n",
447 	       addr_str, g_broadcast_id);
448 
449 	state = sync_state_get_or_new(NULL);
450 	if (state == NULL) {
451 		FAIL("Failed to get sync state");
452 		return true;
453 	}
454 
455 	printk("Creating Periodic Advertising Sync\n");
456 	bt_addr_le_copy(&sync_create_param.addr, info->addr);
457 	sync_create_param.sid = info->sid;
458 	sync_create_param.timeout = 0xa;
459 
460 	err = bt_le_per_adv_sync_create(&sync_create_param,
461 					&state->pa_sync);
462 	if (err != 0) {
463 		FAIL("Could not create PA sync (err %d)\n", err);
464 		return true;
465 	}
466 
467 	state->pa_syncing = true;
468 
469 	return false;
470 }
471 
scan_recv_cb(const struct bt_le_scan_recv_info * info,struct net_buf_simple * ad)472 static void scan_recv_cb(const struct bt_le_scan_recv_info *info,
473 			 struct net_buf_simple *ad)
474 {
475 	/* We are only interested in non-connectable periodic advertisers */
476 	if ((info->adv_props & BT_GAP_ADV_PROP_CONNECTABLE) != 0 ||
477 	    info->interval == 0) {
478 		return;
479 	}
480 
481 	bt_data_parse(ad, broadcast_source_found, (void *)info);
482 }
483 
484 static struct bt_le_scan_cb scan_cb = {
485 	.recv = scan_recv_cb
486 };
487 
add_source(struct sync_state * state)488 static int add_source(struct sync_state *state)
489 {
490 	struct bt_bap_scan_delegator_add_src_param param;
491 	struct bt_le_per_adv_sync_info sync_info;
492 	int res;
493 
494 	UNSET_FLAG(flag_recv_state_updated);
495 
496 	res = bt_le_per_adv_sync_get_info(state->pa_sync, &sync_info);
497 	if (res != 0) {
498 		FAIL("Failed to get PA sync info: %d)\n", res);
499 		return true;
500 	}
501 
502 	bt_addr_le_copy(&param.addr, &sync_info.addr);
503 	param.sid = sync_info.sid;
504 	param.encrypt_state = BT_BAP_BIG_ENC_STATE_NO_ENC;
505 	param.broadcast_id = g_broadcast_id;
506 	param.num_subgroups = 1U;
507 
508 	for (uint8_t i = 0U; i < param.num_subgroups; i++) {
509 		struct bt_bap_bass_subgroup *subgroup_param = &param.subgroups[i];
510 
511 		subgroup_param->bis_sync = BT_BAP_BIS_SYNC_NO_PREF;
512 		subgroup_param->metadata_len = 0U;
513 		(void)memset(subgroup_param->metadata, 0, sizeof(subgroup_param->metadata));
514 	}
515 
516 	res = bt_bap_scan_delegator_add_src(&param);
517 	if (res < 0) {
518 		return res;
519 	}
520 
521 	state->src_id = (uint8_t)res;
522 
523 	WAIT_FOR_FLAG(flag_recv_state_updated);
524 
525 	return res;
526 }
527 
add_all_sources(void)528 static void add_all_sources(void)
529 {
530 	for (size_t i = 0U; i < ARRAY_SIZE(sync_states); i++) {
531 		struct sync_state *state = &sync_states[i];
532 
533 		if (state->pa_sync != NULL) {
534 			int res;
535 
536 			printk("[%zu]: Adding source\n", i);
537 
538 			res = add_source(state);
539 			if (res < 0) {
540 				FAIL("[%zu]: Add source failed (err %d)\n", i, res);
541 				return;
542 			}
543 
544 			printk("[%zu]: Source added with id %u\n",
545 			       i, state->src_id);
546 		}
547 	}
548 }
549 
mod_source(struct sync_state * state)550 static int mod_source(struct sync_state *state)
551 {
552 	const uint16_t pref_context = BT_AUDIO_CONTEXT_TYPE_CONVERSATIONAL;
553 	struct bt_bap_scan_delegator_mod_src_param param;
554 	const uint8_t pref_context_metadata[] = {
555 		BT_AUDIO_CODEC_DATA(BT_AUDIO_METADATA_TYPE_PREF_CONTEXT,
556 				    BT_BYTES_LIST_LE16(pref_context)),
557 	};
558 	int err;
559 
560 	UNSET_FLAG(flag_recv_state_updated);
561 
562 	param.src_id = state->src_id;
563 	param.encrypt_state = BT_BAP_BIG_ENC_STATE_NO_ENC;
564 	param.broadcast_id = g_broadcast_id;
565 	param.num_subgroups = 1U;
566 
567 	for (uint8_t i = 0U; i < param.num_subgroups; i++) {
568 		struct bt_bap_bass_subgroup *subgroup_param = &param.subgroups[i];
569 
570 		subgroup_param->bis_sync = 0U;
571 		subgroup_param->metadata_len = sizeof(pref_context_metadata);
572 		(void)memcpy(subgroup_param->metadata, pref_context_metadata,
573 			     subgroup_param->metadata_len);
574 	}
575 
576 	err = bt_bap_scan_delegator_mod_src(&param);
577 	if (err < 0) {
578 		return err;
579 	}
580 
581 	WAIT_FOR_FLAG(flag_recv_state_updated);
582 
583 	return 0;
584 }
585 
mod_all_sources(void)586 static void mod_all_sources(void)
587 {
588 	for (size_t i = 0U; i < ARRAY_SIZE(sync_states); i++) {
589 		struct sync_state *state = &sync_states[i];
590 
591 		if (state->pa_sync != NULL) {
592 			int err;
593 
594 			printk("[%zu]: Modifying source\n", i);
595 
596 			err = mod_source(state);
597 			if (err < 0) {
598 				FAIL("[%zu]: Modify source failed (err %d)\n", i, err);
599 				return;
600 			}
601 
602 			printk("[%zu]: Source id modifed %u\n",
603 			       i, state->src_id);
604 		}
605 	}
606 }
607 
remove_source(struct sync_state * state)608 static int remove_source(struct sync_state *state)
609 {
610 	int err;
611 
612 	UNSET_FLAG(flag_recv_state_updated);
613 
614 	/* We don't actually need to sync to the BIG/BISes */
615 	err = bt_bap_scan_delegator_rem_src(state->src_id);
616 	if (err) {
617 		return err;
618 	}
619 
620 	WAIT_FOR_FLAG(flag_recv_state_updated);
621 
622 	return 0;
623 }
624 
remove_all_sources(void)625 static void remove_all_sources(void)
626 {
627 	for (size_t i = 0U; i < ARRAY_SIZE(sync_states); i++) {
628 		struct sync_state *state = &sync_states[i];
629 
630 		if (state->recv_state != NULL) {
631 			int err;
632 
633 			printk("[%zu]: Removing source\n", i);
634 
635 			err = remove_source(state);
636 			if (err) {
637 				FAIL("[%zu]: Remove source failed (err %d)\n", err);
638 				return;
639 			}
640 
641 			printk("[%zu]: Source removed with id %u\n",
642 			       i, state->src_id);
643 
644 			printk("Terminating PA sync\n");
645 			err = pa_sync_term(state);
646 			if (err) {
647 				FAIL("[%zu]: PA sync term failed (err %d)\n", err);
648 				return;
649 			}
650 		}
651 	}
652 }
653 
sync_broadcast(struct sync_state * state)654 static int sync_broadcast(struct sync_state *state)
655 {
656 	int err;
657 
658 	UNSET_FLAG(flag_recv_state_updated);
659 
660 	/* We don't actually need to sync to the BIG/BISes */
661 	err = bt_bap_scan_delegator_set_bis_sync_state(state->src_id,
662 						       (uint32_t[]){BT_ISO_BIS_INDEX_BIT(1)});
663 	if (err) {
664 		return err;
665 	}
666 
667 	WAIT_FOR_FLAG(flag_recv_state_updated);
668 
669 	return 0;
670 }
671 
sync_all_broadcasts(void)672 static void sync_all_broadcasts(void)
673 {
674 	for (size_t i = 0U; i < ARRAY_SIZE(sync_states); i++) {
675 		struct sync_state *state = &sync_states[i];
676 
677 		if (state->pa_sync != NULL) {
678 			int res;
679 
680 			printk("[%zu]: Setting broadcast sync state\n", i);
681 
682 			res = sync_broadcast(state);
683 			if (res < 0) {
684 				FAIL("[%zu]: Broadcast sync state set failed (err %d)\n", i, res);
685 				return;
686 			}
687 
688 			printk("[%zu]: Broadcast sync state set\n", i);
689 		}
690 	}
691 }
692 
common_init(void)693 static int common_init(void)
694 {
695 	int err;
696 
697 	err = bt_enable(NULL);
698 	if (err) {
699 		FAIL("Bluetooth init failed (err %d)\n", err);
700 		return err;
701 	}
702 
703 	printk("Bluetooth initialized\n");
704 
705 	bt_bap_scan_delegator_register_cb(&scan_delegator_cb);
706 	bt_le_per_adv_sync_cb_register(&pa_sync_cb);
707 
708 	err = bt_le_adv_start(BT_LE_ADV_CONN_ONE_TIME, ad, AD_SIZE, NULL, 0);
709 	if (err) {
710 		FAIL("Advertising failed to start (err %d)\n", err);
711 		return err;
712 	}
713 
714 	printk("Advertising successfully started\n");
715 
716 	WAIT_FOR_FLAG(flag_connected);
717 
718 	return 0;
719 }
720 
test_main_client_sync(void)721 static void test_main_client_sync(void)
722 {
723 	int err;
724 
725 	err = common_init();
726 	if (err) {
727 		FAIL("common init failed (err %d)\n", err);
728 		return;
729 	}
730 
731 	/* Wait for broadcast assistant to request us to sync to PA */
732 	WAIT_FOR_FLAG(flag_pa_synced);
733 
734 	/* Wait for broadcast assistant to send us broadcast code */
735 	WAIT_FOR_FLAG(flag_broadcast_code_received);
736 
737 	/* Mod all sources by modifying the metadata */
738 	mod_all_sources();
739 
740 	/* Wait for broadcast assistant to tell us to BIS sync */
741 	WAIT_FOR_FLAG(flag_bis_sync_requested);
742 
743 	/* Set the BIS sync state */
744 	sync_all_broadcasts();
745 
746 	/* Wait for broadcast assistant to remove source and terminate PA sync */
747 	WAIT_FOR_FLAG(flag_pa_terminated);
748 
749 	PASS("BAP Scan Delegator Client Sync passed\n");
750 }
751 
test_main_server_sync_client_rem(void)752 static void test_main_server_sync_client_rem(void)
753 {
754 	int err;
755 
756 	err = common_init();
757 	if (err) {
758 		FAIL("common init failed (err %d)\n", err);
759 		return;
760 	}
761 
762 	bt_le_scan_cb_register(&scan_cb);
763 
764 	err = bt_le_scan_start(BT_LE_SCAN_PASSIVE, NULL);
765 	if (err != 0) {
766 		FAIL("Could not start scan (%d)", err);
767 		return;
768 	}
769 
770 	/* Wait for PA to sync */
771 	WAIT_FOR_FLAG(flag_pa_synced);
772 
773 	/* Add PAs as receive state sources */
774 	add_all_sources();
775 
776 	/* Wait for broadcast assistant to send us broadcast code */
777 	WAIT_FOR_FLAG(flag_broadcast_code_received);
778 
779 	/* Mod all sources by modifying the metadata */
780 	mod_all_sources();
781 
782 	/* Set the BIS sync state */
783 	sync_all_broadcasts();
784 
785 	/* For for client to remove source and thus terminate the PA */
786 	WAIT_FOR_FLAG(flag_pa_terminated);
787 
788 	PASS("BAP Scan Delegator Server Sync Client Remove passed\n");
789 }
790 
test_main_server_sync_server_rem(void)791 static void test_main_server_sync_server_rem(void)
792 {
793 	int err;
794 
795 	err = common_init();
796 	if (err) {
797 		FAIL("common init failed (err %d)\n", err);
798 		return;
799 	}
800 
801 	bt_le_scan_cb_register(&scan_cb);
802 
803 	err = bt_le_scan_start(BT_LE_SCAN_PASSIVE, NULL);
804 	if (err != 0) {
805 		FAIL("Could not start scan (%d)", err);
806 		return;
807 	}
808 
809 	/* Wait for PA to sync */
810 	WAIT_FOR_FLAG(flag_pa_synced);
811 
812 	/* Add PAs as receive state sources */
813 	add_all_sources();
814 
815 	/* Wait for broadcast assistant to send us broadcast code */
816 	WAIT_FOR_FLAG(flag_broadcast_code_received);
817 
818 	/* Mod all sources by modifying the metadata */
819 	mod_all_sources();
820 
821 	/* Set the BIS sync state */
822 	sync_all_broadcasts();
823 
824 	/* Remote all sources, causing PA sync term request to trigger */
825 	remove_all_sources();
826 
827 	/* Wait for PA sync to be terminated */
828 	WAIT_FOR_FLAG(flag_pa_terminated);
829 
830 	PASS("BAP Scan Delegator Server Sync Server Remove passed\n");
831 }
832 
833 static const struct bst_test_instance test_scan_delegator[] = {
834 	{
835 		.test_id = "bap_scan_delegator_client_sync",
836 		.test_pre_init_f = test_init,
837 		.test_tick_f = test_tick,
838 		.test_main_f = test_main_client_sync,
839 	},
840 	{
841 		.test_id = "bap_scan_delegator_server_sync_client_rem",
842 		.test_pre_init_f = test_init,
843 		.test_tick_f = test_tick,
844 		.test_main_f = test_main_server_sync_client_rem,
845 	},
846 	{
847 		.test_id = "bap_scan_delegator_server_sync_server_rem",
848 		.test_pre_init_f = test_init,
849 		.test_tick_f = test_tick,
850 		.test_main_f = test_main_server_sync_server_rem,
851 	},
852 	BSTEST_END_MARKER
853 };
854 
test_scan_delegator_install(struct bst_test_list * tests)855 struct bst_test_list *test_scan_delegator_install(struct bst_test_list *tests)
856 {
857 	return bst_add_tests(tests, test_scan_delegator);
858 }
859 #else
test_scan_delegator_install(struct bst_test_list * tests)860 struct bst_test_list *test_scan_delegator_install(struct bst_test_list *tests)
861 {
862 	return tests;
863 }
864 
865 #endif /* CONFIG_BT_BAP_SCAN_DELEGATOR */
866