Commit c84c9bee authored by Aleksander Wasaznik's avatar Aleksander Wasaznik Committed by Carles Cufi
Browse files

Bluetooth: testlib: Add `bt_testlib_conn_unindex`

This function obtains a reference to a connection object by its index.

Signed-off-by: default avatarAleksander Wasaznik <aleksander.wasaznik@nordicsemi.no>
parent dd038b44
Loading
Loading
Loading
Loading
+33 −0
Changes for tests/bluetooth/common/testlib/include/testlib/conn.h: 33 added lines, 0 removed lines.
Original line number Diff line number Diff line
@@ -72,4 +72,37 @@ int bt_testlib_wait_disconnected(struct bt_conn *conn);
 */
void bt_testlib_conn_unref(struct bt_conn **connp);

/** @brief Obtain a reference to a connection object by its
 *  index
 *
 *  This is an inverse of @ref bt_conn_index during the lifetime
 *  of the original  @ref bt_conn reference.
 *
 *  This function can be used instead of @ref bt_conn_foreach to
 *  loop over all connections.
 *
 *  @note The ranges of conn_index overlap for different
 *  connection types. They all range from 0 up to their
 *  respective capacities, tabulated below.
 *
 *    @p conn_type     | Capacity
 *   ------------------|------------------------
 *    BT_CONN_TYPE_LE  | CONFIG_BT_MAX_CONN
 *    BT_CONN_TYPE_SCO | CONFIG_BT_MAX_SCO_CONN
 *    BT_CONN_TYPE_ISO | CONFIG_BT_ISO_MAX_CHAN
 *
 * Internal details that cannot be relied on:
 *  - The memory addresses returned point into an array.
 *  - The same index and type always yields the same memory
 *    address.
 *
 * Guarantees:
 *  - Looping over the whole range is equivalent to @ref
 *    bt_conn_foreach.
 *
 *  @retval NULL if the reference is dead
 *  @retval conn a reference to the found connection object
 */
struct bt_conn *bt_testlib_conn_unindex(enum bt_conn_type conn_type, uint8_t conn_index);

#endif /* ZEPHYR_TESTS_BLUETOOTH_COMMON_TESTLIB_INCLUDE_TESTLIB_CONN_H_ */
+30 −1
Changes for tests/bluetooth/common/testlib/src/conn_ref.c: 30 added lines, 1 removed line.
Original line number Diff line number Diff line
@@ -3,9 +3,12 @@
 */

#include <stddef.h>
#include <testlib/conn.h>

#include <zephyr/bluetooth/conn.h>
#include <zephyr/sys/atomic_builtin.h>

#include <testlib/conn.h>

/**
 * @file
 * @brief Reified connection reference counting.
@@ -36,3 +39,29 @@ void bt_testlib_conn_unref(struct bt_conn **connp)
	__ASSERT_NO_MSG(conn);
	bt_conn_unref(conn);
}

struct find_by_index_data {
	uint8_t wanted_index;
	struct bt_conn *found_conn;
};

static void find_by_index(struct bt_conn *conn, void *user_data)
{
	struct find_by_index_data *data = user_data;
	uint8_t index = bt_conn_index(conn);

	if (index == data->wanted_index) {
		data->found_conn = bt_conn_ref(conn);
	}
}

struct bt_conn *bt_testlib_conn_unindex(enum bt_conn_type conn_type, uint8_t conn_index)
{
	struct find_by_index_data data = {
		.wanted_index = conn_index,
	};

	bt_conn_foreach(conn_type, find_by_index, &data);

	return data.found_conn;
}