1 /*
2  * Copyright (c) 2019 Bose Corporation
3  * Copyright (c) 2020-2025 Nordic Semiconductor ASA
4  *
5  * SPDX-License-Identifier: Apache-2.0
6  */
7 
8 #include <stdbool.h>
9 #include <stddef.h>
10 #include <stdint.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/audio/csip.h>
17 #include <zephyr/bluetooth/audio/tmap.h>
18 #include <zephyr/bluetooth/bluetooth.h>
19 #include <zephyr/bluetooth/byteorder.h>
20 #include <zephyr/bluetooth/conn.h>
21 #include <zephyr/bluetooth/gap.h>
22 #include <zephyr/bluetooth/uuid.h>
23 #include <zephyr/kernel.h>
24 #include <zephyr/net_buf.h>
25 #include <zephyr/sys/__assert.h>
26 #include <zephyr/sys/atomic_types.h>
27 #include <zephyr/sys/printk.h>
28 #include <zephyr/sys/util.h>
29 #include <zephyr/sys/util_macro.h>
30 
31 #include "bs_cmd_line.h"
32 #include "bs_dynargs.h"
33 #include "bs_pc_backchannel.h"
34 #include "posix_native_task.h"
35 #include "bs_types.h"
36 #include "bsim_args_runner.h"
37 #include "bstests.h"
38 #include "common.h"
39 
40 extern enum bst_result_t bst_result;
41 struct bt_conn *default_conn;
42 atomic_t flag_connected;
43 atomic_t flag_disconnected;
44 atomic_t flag_conn_updated;
45 atomic_t flag_audio_received;
46 volatile bt_security_t security_level;
47 #if defined(CONFIG_BT_CSIP_SET_MEMBER)
48 uint8_t csip_rsi[BT_CSIP_RSI_SIZE];
49 #endif /* CONFIG_BT_CSIP_SET_MEMBER */
50 
51 static const struct bt_data connectable_ad[] = {
52 	BT_DATA_BYTES(BT_DATA_FLAGS, (BT_LE_AD_GENERAL | BT_LE_AD_NO_BREDR)),
53 	BT_DATA(BT_DATA_NAME_COMPLETE, CONFIG_BT_DEVICE_NAME, sizeof(CONFIG_BT_DEVICE_NAME) - 1),
54 	BT_DATA_BYTES(BT_DATA_UUID16_SOME, BT_UUID_16_ENCODE(BT_UUID_ASCS_VAL),
55 		      BT_UUID_16_ENCODE(BT_UUID_CAS_VAL)),
56 	BT_DATA_BYTES(BT_DATA_UUID16_ALL, BT_UUID_16_ENCODE(BT_UUID_BASS_VAL),
57 		      BT_UUID_16_ENCODE(BT_UUID_PACS_VAL)),
58 #if defined(CONFIG_BT_CAP_ACCEPTOR)
59 	BT_DATA_BYTES(BT_DATA_SVC_DATA16, BT_UUID_16_ENCODE(BT_UUID_CAS_VAL),
60 		      BT_AUDIO_UNICAST_ANNOUNCEMENT_TARGETED),
61 #endif /* CONFIG_BT_CAP_ACCEPTOR */
62 #if defined(CONFIG_BT_BAP_UNICAST_SERVER)
63 	BT_DATA_BYTES(BT_DATA_SVC_DATA16, BT_UUID_16_ENCODE(BT_UUID_ASCS_VAL),
64 		      BT_AUDIO_UNICAST_ANNOUNCEMENT_TARGETED, BT_BYTES_LIST_LE16(SINK_CONTEXT),
65 		      BT_BYTES_LIST_LE16(SOURCE_CONTEXT), 0x00,
66 		      /* Metadata length */),
67 #endif /* CONFIG_BT_BAP_UNICAST_SERVER */
68 #if defined(CONFIG_BT_BAP_SCAN_DELEGATOR)
69 	BT_DATA_BYTES(BT_DATA_SVC_DATA16, BT_UUID_16_ENCODE(BT_UUID_BASS_VAL)),
70 #endif /* CONFIG_BT_BAP_SCAN_DELEGATOR */
71 #if defined(CONFIG_BT_CSIP_SET_MEMBER)
72 	BT_DATA(BT_DATA_CSIS_RSI, csip_rsi, BT_CSIP_RSI_SIZE),
73 #endif /* CONFIG_BT_CSIP_SET_MEMBER */
74 #if defined(CONFIG_BT_TMAP)
75 	BT_DATA_BYTES(BT_DATA_SVC_DATA16, BT_UUID_16_ENCODE(BT_UUID_TMAS_VAL),
76 		      BT_UUID_16_ENCODE(TMAP_ROLE_SUPPORTED)),
77 #endif /* CONFIG_BT_TMAP */
78 };
79 
device_found(const struct bt_le_scan_recv_info * info,struct net_buf_simple * ad_buf)80 static void device_found(const struct bt_le_scan_recv_info *info, struct net_buf_simple *ad_buf)
81 {
82 	char addr_str[BT_ADDR_LE_STR_LEN];
83 	int err;
84 
85 	if (default_conn) {
86 		return;
87 	}
88 
89 	/* We're only interested in extended advertising connectable events */
90 	if (((info->adv_props & BT_GAP_ADV_PROP_EXT_ADV) == 0U ||
91 	     (info->adv_props & BT_GAP_ADV_PROP_CONNECTABLE) == 0U)) {
92 		return;
93 	}
94 
95 	bt_addr_le_to_str(info->addr, addr_str, sizeof(addr_str));
96 	printk("Device found: %s (RSSI %d)\n", addr_str, info->rssi);
97 
98 	/* connect only to devices in close proximity */
99 	if (info->rssi < -70) {
100 		FAIL("RSSI too low");
101 		return;
102 	}
103 
104 	printk("Stopping scan\n");
105 	if (bt_le_scan_stop()) {
106 		FAIL("Could not stop scan");
107 		return;
108 	}
109 
110 	err = bt_conn_le_create(info->addr, BT_CONN_LE_CREATE_CONN, BT_BAP_CONN_PARAM_RELAXED,
111 				&default_conn);
112 	if (err) {
113 		FAIL("Could not connect to peer: %d", err);
114 	}
115 }
116 
117 struct bt_le_scan_cb common_scan_cb = {
118 	.recv = device_found,
119 };
120 
connected(struct bt_conn * conn,uint8_t err)121 static void connected(struct bt_conn *conn, uint8_t err)
122 {
123 	char addr[BT_ADDR_LE_STR_LEN];
124 
125 	(void)bt_addr_le_to_str(bt_conn_get_dst(conn), addr, sizeof(addr));
126 
127 	if (default_conn == NULL) {
128 		default_conn = bt_conn_ref(conn);
129 	}
130 
131 	if (err != 0) {
132 		bt_conn_unref(default_conn);
133 		default_conn = NULL;
134 
135 		FAIL("Failed to connect to %s (0x%02x)\n", addr, err);
136 		return;
137 	}
138 
139 	printk("Connected to %s (%p)\n", addr, conn);
140 	SET_FLAG(flag_connected);
141 }
142 
disconnected(struct bt_conn * conn,uint8_t reason)143 void disconnected(struct bt_conn *conn, uint8_t reason)
144 {
145 	char addr[BT_ADDR_LE_STR_LEN];
146 
147 	if (conn != default_conn) {
148 		return;
149 	}
150 
151 	bt_addr_le_to_str(bt_conn_get_dst(conn), addr, sizeof(addr));
152 
153 	printk("Disconnected: %s (reason 0x%02x)\n", addr, reason);
154 
155 	bt_conn_unref(default_conn);
156 	default_conn = NULL;
157 	UNSET_FLAG(flag_connected);
158 	UNSET_FLAG(flag_conn_updated);
159 	SET_FLAG(flag_disconnected);
160 
161 	security_level = BT_SECURITY_L1;
162 }
163 
conn_param_updated_cb(struct bt_conn * conn,uint16_t interval,uint16_t latency,uint16_t timeout)164 static void conn_param_updated_cb(struct bt_conn *conn, uint16_t interval, uint16_t latency,
165 				  uint16_t timeout)
166 {
167 	printk("Connection parameter updated: %p 0x%04X (%u us), 0x%04X, 0x%04X\n", conn, interval,
168 	       BT_CONN_INTERVAL_TO_US(interval), latency, timeout);
169 
170 	SET_FLAG(flag_conn_updated);
171 }
172 
security_changed_cb(struct bt_conn * conn,bt_security_t level,enum bt_security_err err)173 static void security_changed_cb(struct bt_conn *conn, bt_security_t level, enum bt_security_err err)
174 {
175 	printk("Security changed: %p level %d err %d\n", conn, level, err);
176 
177 	if (err == BT_SECURITY_ERR_SUCCESS) {
178 		security_level = level;
179 	}
180 }
181 
182 BT_CONN_CB_DEFINE(conn_callbacks) = {
183 	.connected = connected,
184 	.disconnected = disconnected,
185 	.le_param_updated = conn_param_updated_cb,
186 	.security_changed = security_changed_cb,
187 };
188 
189 
setup_connectable_adv(struct bt_le_ext_adv ** ext_adv)190 void setup_connectable_adv(struct bt_le_ext_adv **ext_adv)
191 {
192 	int err;
193 
194 	/* Create a non-connectable advertising set */
195 	err = bt_le_ext_adv_create(BT_BAP_ADV_PARAM_CONN_QUICK, NULL, ext_adv);
196 	if (err != 0) {
197 		FAIL("Unable to create extended advertising set: %d\n", err);
198 		return;
199 	}
200 
201 	err = bt_le_ext_adv_set_data(*ext_adv, connectable_ad, ARRAY_SIZE(connectable_ad), NULL, 0);
202 	if (err != 0) {
203 		FAIL("Unable to set extended advertising data: %d\n", err);
204 
205 		bt_le_ext_adv_delete(*ext_adv);
206 
207 		return;
208 	}
209 
210 	err = bt_le_ext_adv_start(*ext_adv, BT_LE_EXT_ADV_START_DEFAULT);
211 	if (err != 0) {
212 		FAIL("Failed to start advertising set (err %d)\n", err);
213 
214 		bt_le_ext_adv_delete(*ext_adv);
215 
216 		return;
217 	}
218 
219 	printk("Advertising started\n");
220 }
221 
setup_broadcast_adv(struct bt_le_ext_adv ** adv)222 void setup_broadcast_adv(struct bt_le_ext_adv **adv)
223 {
224 	struct bt_le_adv_param ext_adv_param = *BT_BAP_ADV_PARAM_BROADCAST_SLOW;
225 	int err;
226 
227 	/* Zephyr Controller works best while Extended Advertising interval is a multiple
228 	 * of the ISO Interval minus 10 ms (max. advertising random delay). This is
229 	 * required to place the AUX_ADV_IND PDUs in a non-overlapping interval with the
230 	 * Broadcast ISO radio events.
231 	 */
232 	ext_adv_param.interval_min -= BT_GAP_MS_TO_ADV_INTERVAL(10U);
233 	ext_adv_param.interval_max -= BT_GAP_MS_TO_ADV_INTERVAL(10U);
234 
235 	/* Create a non-connectable advertising set */
236 	err = bt_le_ext_adv_create(&ext_adv_param, NULL, adv);
237 	if (err != 0) {
238 		FAIL("Unable to create extended advertising set: %d\n", err);
239 		return;
240 	}
241 
242 	/* Set periodic advertising parameters */
243 	err = bt_le_per_adv_set_param(*adv, BT_BAP_PER_ADV_PARAM_BROADCAST_SLOW);
244 	if (err) {
245 		FAIL("Failed to set periodic advertising parameters: %d\n", err);
246 		return;
247 	}
248 }
249 
start_broadcast_adv(struct bt_le_ext_adv * adv)250 void start_broadcast_adv(struct bt_le_ext_adv *adv)
251 {
252 	char addr_str[BT_ADDR_LE_STR_LEN];
253 	struct bt_le_ext_adv_info info;
254 	int err;
255 
256 	err = bt_le_ext_adv_get_info(adv, &info);
257 	if (err != 0) {
258 		FAIL("Failed to get adv info: %d\n", err);
259 		return;
260 	}
261 
262 	if (info.per_adv_state == BT_LE_PER_ADV_STATE_NONE) {
263 		FAIL("Cannot start periodic advertising for non-periodic advertising set");
264 		return;
265 	}
266 
267 	if (info.ext_adv_state == BT_LE_EXT_ADV_STATE_DISABLED) {
268 		/* Start extended advertising */
269 		err = bt_le_ext_adv_start(adv, BT_LE_EXT_ADV_START_DEFAULT);
270 		if (err != 0) {
271 			FAIL("Failed to start extended advertising: %d\n", err);
272 			return;
273 		}
274 	}
275 
276 	if (info.per_adv_state == BT_LE_PER_ADV_STATE_DISABLED) {
277 		/* Enable Periodic Advertising */
278 		err = bt_le_per_adv_start(adv);
279 		if (err != 0) {
280 			FAIL("Failed to enable periodic advertising: %d\n", err);
281 			return;
282 		}
283 	}
284 
285 	bt_addr_le_to_str(info.addr, addr_str, sizeof(addr_str));
286 	printk("Started advertising with addr %s\n", addr_str);
287 }
288 
test_tick(bs_time_t HW_device_time)289 void test_tick(bs_time_t HW_device_time)
290 {
291 	if (bst_result != Passed) {
292 		FAIL("test failed (not passed after %i seconds)\n", WAIT_SECONDS);
293 	}
294 }
295 
test_init(void)296 void test_init(void)
297 {
298 	bst_ticker_set_next_tick_absolute(WAIT_TIME);
299 	bst_result = In_progress;
300 }
301 
302 #define SYNC_MSG_SIZE 1
303 static int32_t dev_cnt;
304 static uint backchannel_nums[255];
305 static uint chan_cnt;
306 
register_more_cmd_args(void)307 static void register_more_cmd_args(void)
308 {
309 	static bs_args_struct_t args_struct_toadd[] = {
310 		{
311 			.option = "D",
312 			.name = "number_devices",
313 			.type = 'i',
314 			.dest = (void *)&dev_cnt,
315 			.descript = "Number of devices which will connect in this phy",
316 			.is_mandatory = true,
317 		},
318 		ARG_TABLE_ENDMARKER,
319 	};
320 
321 	bs_add_extra_dynargs(args_struct_toadd);
322 }
323 NATIVE_TASK(register_more_cmd_args, PRE_BOOT_1, 100);
324 
get_dev_cnt(void)325 uint16_t get_dev_cnt(void)
326 {
327 	return (uint16_t)dev_cnt;
328 }
329 
330 /**
331  * @brief Get the channel id based on remote device ID
332  *
333  * The is effectively a very simple hashing function to generate unique channel IDs from device IDs
334  *
335  * @param dev 16-bit device ID
336  *
337  * @return uint 32-bit channel ID
338  */
get_chan_num(uint16_t dev)339 static uint get_chan_num(uint16_t dev)
340 {
341 	uint16_t self = (uint16_t)bsim_args_get_global_device_nbr();
342 	uint channel_id;
343 
344 	if (self < dev) {
345 		channel_id = (dev << 16) | self;
346 	} else {
347 		channel_id = (self << 16) | dev;
348 	}
349 
350 	return channel_id;
351 }
352 
353 /**
354  * @brief Calculate the sync timeout based on the PA interval
355  *
356  * Calculates the sync timeout, based on the PA interval and a pre-defined ratio.
357  * The return value is in N*10ms, conform the parameter for bt_le_per_adv_sync_create
358  *
359  * @param pa_interval PA interval
360  *
361  * @return uint16_t synchronization timeout (N * 10 ms)
362  */
interval_to_sync_timeout(uint16_t pa_interval)363 uint16_t interval_to_sync_timeout(uint16_t pa_interval)
364 {
365 	uint16_t pa_timeout;
366 
367 	if (pa_interval == BT_BAP_PA_INTERVAL_UNKNOWN) {
368 		/* Use maximum value to maximize chance of success */
369 		pa_timeout = BT_GAP_PER_ADV_MAX_TIMEOUT;
370 	} else {
371 		uint32_t interval_us;
372 		uint32_t timeout;
373 
374 		/* Add retries and convert to unit in 10's of ms */
375 		interval_us = BT_GAP_PER_ADV_INTERVAL_TO_US(pa_interval);
376 		timeout = BT_GAP_US_TO_PER_ADV_SYNC_TIMEOUT(interval_us) *
377 			  PA_SYNC_INTERVAL_TO_TIMEOUT_RATIO;
378 
379 		/* Enforce restraints */
380 		pa_timeout = CLAMP(timeout, BT_GAP_PER_ADV_MIN_TIMEOUT, BT_GAP_PER_ADV_MAX_TIMEOUT);
381 	}
382 
383 	return pa_timeout;
384 }
385 
386 /**
387  * @brief Set up the backchannels between each pair of device
388  *
389  * Each pair of devices will get a unique channel
390  */
setup_backchannels(void)391 static void setup_backchannels(void)
392 {
393 	__ASSERT_NO_MSG(dev_cnt > 0 && dev_cnt < ARRAY_SIZE(backchannel_nums));
394 	const uint self = bsim_args_get_global_device_nbr();
395 	uint device_numbers[dev_cnt];
396 	uint *channels;
397 
398 	for (int32_t i = 0; i < dev_cnt; i++) {
399 		backchannel_nums[chan_cnt] = get_chan_num((uint16_t)i);
400 		device_numbers[chan_cnt++] = i;
401 	}
402 
403 	channels = bs_open_back_channel(self, device_numbers, backchannel_nums, chan_cnt);
404 	__ASSERT_NO_MSG(channels != NULL);
405 }
406 NATIVE_TASK(setup_backchannels, PRE_BOOT_3, 100);
407 
get_chan_id_from_chan_num(uint chan_num)408 static uint get_chan_id_from_chan_num(uint chan_num)
409 {
410 	for (uint i = 0; i < ARRAY_SIZE(backchannel_nums); i++) {
411 		if (backchannel_nums[i] == chan_num) {
412 			return i;
413 		}
414 	}
415 
416 	return 0;
417 }
418 
backchannel_sync_send(uint dev)419 void backchannel_sync_send(uint dev)
420 {
421 	const uint chan_id = get_chan_id_from_chan_num(get_chan_num((uint16_t)dev));
422 	uint8_t sync_msg[SYNC_MSG_SIZE] = {0};
423 
424 	printk("Sending sync to %u\n", chan_id);
425 	bs_bc_send_msg(chan_id, sync_msg, ARRAY_SIZE(sync_msg));
426 }
427 
backchannel_sync_send_all(void)428 void backchannel_sync_send_all(void)
429 {
430 	for (int32_t i = 0; i < dev_cnt; i++) {
431 		const uint self = bsim_args_get_global_device_nbr();
432 
433 		if (i != self) { /* skip ourselves*/
434 			backchannel_sync_send(i);
435 		}
436 	}
437 }
438 
backchannel_sync_wait(uint dev)439 void backchannel_sync_wait(uint dev)
440 {
441 	const uint chan_id = get_chan_id_from_chan_num(get_chan_num((uint16_t)dev));
442 
443 	printk("Waiting for sync to %u\n", chan_id);
444 
445 	while (true) {
446 		if (bs_bc_is_msg_received(chan_id) > 0) {
447 			uint8_t sync_msg[SYNC_MSG_SIZE];
448 
449 			bs_bc_receive_msg(chan_id, sync_msg, ARRAY_SIZE(sync_msg));
450 			/* We don't really care about the content of the message */
451 			break;
452 		}
453 
454 		k_sleep(K_MSEC(1));
455 	}
456 }
457 
backchannel_sync_wait_all(void)458 void backchannel_sync_wait_all(void)
459 {
460 	for (int32_t i = 0; i < dev_cnt; i++) {
461 		const uint self = bsim_args_get_global_device_nbr();
462 
463 		if (i != self) { /* skip ourselves*/
464 			backchannel_sync_wait(i);
465 		}
466 	}
467 }
468 
backchannel_sync_wait_any(void)469 void backchannel_sync_wait_any(void)
470 {
471 	while (true) {
472 		for (int32_t i = 0; i < dev_cnt; i++) {
473 			const uint self = bsim_args_get_global_device_nbr();
474 
475 			if (i != self) { /* skip ourselves*/
476 				const uint chan_id =
477 					get_chan_id_from_chan_num(get_chan_num((uint16_t)i));
478 
479 				if (bs_bc_is_msg_received(chan_id) > 0) {
480 					uint8_t sync_msg[SYNC_MSG_SIZE];
481 
482 					bs_bc_receive_msg(chan_id, sync_msg, ARRAY_SIZE(sync_msg));
483 					/* We don't really care about the content of the message */
484 
485 					return;
486 				}
487 			}
488 		}
489 
490 		k_sleep(K_MSEC(100));
491 	}
492 }
493 
backchannel_sync_clear(uint dev)494 void backchannel_sync_clear(uint dev)
495 {
496 	const uint chan_id = get_chan_id_from_chan_num(get_chan_num((uint16_t)dev));
497 
498 	while (bs_bc_is_msg_received(chan_id)) {
499 		uint8_t sync_msg[SYNC_MSG_SIZE];
500 
501 		bs_bc_receive_msg(chan_id, sync_msg, ARRAY_SIZE(sync_msg));
502 		/* We don't really care about the content of the message */
503 	}
504 }
505 
backchannel_sync_clear_all(void)506 void backchannel_sync_clear_all(void)
507 {
508 	for (int32_t i = 0; i < dev_cnt; i++) {
509 		const uint self = bsim_args_get_global_device_nbr();
510 
511 		if (i != self) { /* skip ourselves*/
512 			backchannel_sync_clear(i);
513 		}
514 	}
515 }
516