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 
test_tick(bs_time_t HW_device_time)250 void test_tick(bs_time_t HW_device_time)
251 {
252 	if (bst_result != Passed) {
253 		FAIL("test failed (not passed after %i seconds)\n", WAIT_SECONDS);
254 	}
255 }
256 
test_init(void)257 void test_init(void)
258 {
259 	bst_ticker_set_next_tick_absolute(WAIT_TIME);
260 	bst_result = In_progress;
261 }
262 
263 #define SYNC_MSG_SIZE 1
264 static int32_t dev_cnt;
265 static uint backchannel_nums[255];
266 static uint chan_cnt;
267 
register_more_cmd_args(void)268 static void register_more_cmd_args(void)
269 {
270 	static bs_args_struct_t args_struct_toadd[] = {
271 		{
272 			.option = "D",
273 			.name = "number_devices",
274 			.type = 'i',
275 			.dest = (void *)&dev_cnt,
276 			.descript = "Number of devices which will connect in this phy",
277 			.is_mandatory = true,
278 		},
279 		ARG_TABLE_ENDMARKER,
280 	};
281 
282 	bs_add_extra_dynargs(args_struct_toadd);
283 }
284 NATIVE_TASK(register_more_cmd_args, PRE_BOOT_1, 100);
285 
get_dev_cnt(void)286 uint16_t get_dev_cnt(void)
287 {
288 	return (uint16_t)dev_cnt;
289 }
290 
291 /**
292  * @brief Get the channel id based on remote device ID
293  *
294  * The is effectively a very simple hashing function to generate unique channel IDs from device IDs
295  *
296  * @param dev 16-bit device ID
297  *
298  * @return uint 32-bit channel ID
299  */
get_chan_num(uint16_t dev)300 static uint get_chan_num(uint16_t dev)
301 {
302 	uint16_t self = (uint16_t)bsim_args_get_global_device_nbr();
303 	uint channel_id;
304 
305 	if (self < dev) {
306 		channel_id = (dev << 16) | self;
307 	} else {
308 		channel_id = (self << 16) | dev;
309 	}
310 
311 	return channel_id;
312 }
313 
314 /**
315  * @brief Calculate the sync timeout based on the PA interval
316  *
317  * Calculates the sync timeout, based on the PA interval and a pre-defined ratio.
318  * The return value is in N*10ms, conform the parameter for bt_le_per_adv_sync_create
319  *
320  * @param pa_interval PA interval
321  *
322  * @return uint16_t synchronization timeout (N * 10 ms)
323  */
interval_to_sync_timeout(uint16_t pa_interval)324 uint16_t interval_to_sync_timeout(uint16_t pa_interval)
325 {
326 	uint16_t pa_timeout;
327 
328 	if (pa_interval == BT_BAP_PA_INTERVAL_UNKNOWN) {
329 		/* Use maximum value to maximize chance of success */
330 		pa_timeout = BT_GAP_PER_ADV_MAX_TIMEOUT;
331 	} else {
332 		uint32_t interval_us;
333 		uint32_t timeout;
334 
335 		/* Add retries and convert to unit in 10's of ms */
336 		interval_us = BT_GAP_PER_ADV_INTERVAL_TO_US(pa_interval);
337 		timeout = BT_GAP_US_TO_PER_ADV_SYNC_TIMEOUT(interval_us) *
338 			  PA_SYNC_INTERVAL_TO_TIMEOUT_RATIO;
339 
340 		/* Enforce restraints */
341 		pa_timeout = CLAMP(timeout, BT_GAP_PER_ADV_MIN_TIMEOUT, BT_GAP_PER_ADV_MAX_TIMEOUT);
342 	}
343 
344 	return pa_timeout;
345 }
346 
347 /**
348  * @brief Set up the backchannels between each pair of device
349  *
350  * Each pair of devices will get a unique channel
351  */
setup_backchannels(void)352 static void setup_backchannels(void)
353 {
354 	__ASSERT_NO_MSG(dev_cnt > 0 && dev_cnt < ARRAY_SIZE(backchannel_nums));
355 	const uint self = bsim_args_get_global_device_nbr();
356 	uint device_numbers[dev_cnt];
357 	uint *channels;
358 
359 	for (int32_t i = 0; i < dev_cnt; i++) {
360 		backchannel_nums[chan_cnt] = get_chan_num((uint16_t)i);
361 		device_numbers[chan_cnt++] = i;
362 	}
363 
364 	channels = bs_open_back_channel(self, device_numbers, backchannel_nums, chan_cnt);
365 	__ASSERT_NO_MSG(channels != NULL);
366 }
367 NATIVE_TASK(setup_backchannels, PRE_BOOT_3, 100);
368 
get_chan_id_from_chan_num(uint chan_num)369 static uint get_chan_id_from_chan_num(uint chan_num)
370 {
371 	for (uint i = 0; i < ARRAY_SIZE(backchannel_nums); i++) {
372 		if (backchannel_nums[i] == chan_num) {
373 			return i;
374 		}
375 	}
376 
377 	return 0;
378 }
379 
backchannel_sync_send(uint dev)380 void backchannel_sync_send(uint dev)
381 {
382 	const uint chan_id = get_chan_id_from_chan_num(get_chan_num((uint16_t)dev));
383 	uint8_t sync_msg[SYNC_MSG_SIZE] = {0};
384 
385 	printk("Sending sync to %u\n", chan_id);
386 	bs_bc_send_msg(chan_id, sync_msg, ARRAY_SIZE(sync_msg));
387 }
388 
backchannel_sync_send_all(void)389 void backchannel_sync_send_all(void)
390 {
391 	for (int32_t i = 0; i < dev_cnt; i++) {
392 		const uint self = bsim_args_get_global_device_nbr();
393 
394 		if (i != self) { /* skip ourselves*/
395 			backchannel_sync_send(i);
396 		}
397 	}
398 }
399 
backchannel_sync_wait(uint dev)400 void backchannel_sync_wait(uint dev)
401 {
402 	const uint chan_id = get_chan_id_from_chan_num(get_chan_num((uint16_t)dev));
403 
404 	printk("Waiting for sync to %u\n", chan_id);
405 
406 	while (true) {
407 		if (bs_bc_is_msg_received(chan_id) > 0) {
408 			uint8_t sync_msg[SYNC_MSG_SIZE];
409 
410 			bs_bc_receive_msg(chan_id, sync_msg, ARRAY_SIZE(sync_msg));
411 			/* We don't really care about the content of the message */
412 			break;
413 		}
414 
415 		k_sleep(K_MSEC(1));
416 	}
417 }
418 
backchannel_sync_wait_all(void)419 void backchannel_sync_wait_all(void)
420 {
421 	for (int32_t i = 0; i < dev_cnt; i++) {
422 		const uint self = bsim_args_get_global_device_nbr();
423 
424 		if (i != self) { /* skip ourselves*/
425 			backchannel_sync_wait(i);
426 		}
427 	}
428 }
429 
backchannel_sync_wait_any(void)430 void backchannel_sync_wait_any(void)
431 {
432 	while (true) {
433 		for (int32_t i = 0; i < dev_cnt; i++) {
434 			const uint self = bsim_args_get_global_device_nbr();
435 
436 			if (i != self) { /* skip ourselves*/
437 				const uint chan_id =
438 					get_chan_id_from_chan_num(get_chan_num((uint16_t)i));
439 
440 				if (bs_bc_is_msg_received(chan_id) > 0) {
441 					uint8_t sync_msg[SYNC_MSG_SIZE];
442 
443 					bs_bc_receive_msg(chan_id, sync_msg, ARRAY_SIZE(sync_msg));
444 					/* We don't really care about the content of the message */
445 
446 					return;
447 				}
448 			}
449 		}
450 
451 		k_sleep(K_MSEC(100));
452 	}
453 }
454 
backchannel_sync_clear(uint dev)455 void backchannel_sync_clear(uint dev)
456 {
457 	const uint chan_id = get_chan_id_from_chan_num(get_chan_num((uint16_t)dev));
458 
459 	while (bs_bc_is_msg_received(chan_id)) {
460 		uint8_t sync_msg[SYNC_MSG_SIZE];
461 
462 		bs_bc_receive_msg(chan_id, sync_msg, ARRAY_SIZE(sync_msg));
463 		/* We don't really care about the content of the message */
464 	}
465 }
466 
backchannel_sync_clear_all(void)467 void backchannel_sync_clear_all(void)
468 {
469 	for (int32_t i = 0; i < dev_cnt; i++) {
470 		const uint self = bsim_args_get_global_device_nbr();
471 
472 		if (i != self) { /* skip ourselves*/
473 			backchannel_sync_clear(i);
474 		}
475 	}
476 }
477