Skip to contentSkip to conversation

Bearer.LE1: Add ReadRSSI

PATCH In review Kevin Dewald 2 participants 6 messages Nov 16 Bluetooth drivers

lore
Share & tools
lore
#0 lore raw

v4 cover Bearer.LE1: Add ReadRSSI

This adds ReadRSSI to Bearer.LE1 as a testing method, for diagnostics and production testing, as discussed on v1 [1]. It is only available when D-Bus testing interfaces are enabled, with bluetoothd -T or Testing = true in main.conf.

Each call sends Get Connection Information, which the kernel answers from the controller or with the value it read in the last 1 to 3 seconds. A call made right after Connect returns fails with NotReady until the kernel has read the remote features.

Changes in v4, from the automated review of v3 [2]:
- Don't cancel a Get Connection Information request that is still pending when the bearer is destroyed. The kernel replies to it anyway, and shared/mgmt would take that reply for the reply to the next request. The request now has its own state, freed by a destroy callback btd_adapter_get_conn_info takes, and btd_adapter_cancel_request is removed.
- Allocate the queue of pending calls with the request, so it does not leak if the bearer interface fails to register.

Changes in v3, from the review of v2 [3]:
- Retry ReadRSSI in the functional test while it fails with NotReady.
- Check that the RSSI is between -127 and 20 dBm instead of the -1 dBm of the emulated controller, so the test also passes with real controllers.

Changes in v2:
- Make ReadRSSI a testing method and mark it [testing] in the documentation.
- Enable testing interfaces on one host in the functional test, and check that the other host does not export ReadRSSI.
- Rebase on master.

Tested with the functional test on bluetooth-next 3f425f95ba39, and on an RTL8761BU connected to an nRF52840: with -T, ReadRSSI returned -49 dBm; without it, the method was not exported.

The v3 issue was reproduced with three emulated hosts and an emulator that answers Read RSSI after 1.5 seconds: host0 reads the RSSI of host1, host1 powers off, host0 removes it and then reads the RSSI of host2. With v3 that read got the RSSI of host1, and its own reply was dropped; with v4 it got the RSSI of host2. The reproducer is not included as it needs the delay in the emulator, but I can send it if it is useful.

[1] https://lore.kernel.org/linux-bluetooth/[email protected]/
[2] https://github.com/bluez/bluez/pull/2825
[3] https://lore.kernel.org/linux-bluetooth/[email protected]/

Kevin Dewald (4):
org.bluez.Bearer: Add ReadRSSI method
adapter: Add btd_adapter_get_conn_info
bearer: Add ReadRSSI method
test: functional: add bearer ReadRSSI test

 doc/org.bluez.Bearer.LE.rst    |  19 +++++
 src/adapter.c                  |  18 +++++
 src/adapter.h                  |   7 ++
 src/bearer.c                   | 132 ++++++++++++++++++++++++++++++++-
 test/functional/test_bearer.py |  58 +++++++++++++++
 5 files changed, 232 insertions(+), 2 deletions(-)

base-commit: 20ffd285b58facfd1f2478d159a5f941b09d5be1

Signature · 1 line
2.54.0 (Apple Git-157)
#1 lore raw

PATCH v4 1/4 org.bluez.Bearer: Add ReadRSSI method

Add a testing method to read the RSSI of the current connection on LE bearer, for diagnostics and production testing. It is only available when D-Bus testing interfaces are enabled.

Assisted-by Claude:claude-opus-5.5
---
 doc/org.bluez.Bearer.LE.rst | 19 +++++++++++++++++++
 1 file changed, 19 insertions(+)
doc/org.bluez.Bearer.LE.rst +19 -0
index 3db5237b4..803adb401 100644
@@ -57,6 +57,25 @@ Possible errors:
 
 :org.bluez.Error.NotConnected:
 
+int16 ReadRSSI() [testing]
+``````````````````````````
+
+Reads the Received Signal Strength Indicator of the current connection on LE
+bearer from the controller, in dBm, for diagnostics and production testing.
+
+Available only when D-Bus testing interfaces are enabled.
+
+The kernel caches the value for a few seconds, so calls made in quick succession
+may return the same value. Right after the connection is established, while it
+is still being set up, the method fails with org.bluez.Error.NotReady.
+
+Possible errors:
+
+:org.bluez.Error.NotConnected:
+:org.bluez.Error.NotReady:
+:org.bluez.Error.NotAvailable:
+:org.bluez.Error.Failed:
+
 Signals
 -------
 
Signature · 1 line
2.54.0 (Apple Git-157)
#2 lore raw

This is automated email and please do not reply to this email!

Dear submitter,

Thank you for submitting the patches to the linux bluetooth mailing list. This is a CI test results with your patch series:
PW Link:https://patchwork.kernel.org/series/1212358/

---Test result---

Test Summary:

CheckPatch                    PASS      1.49 seconds
GitLint                       PASS      1.01 seconds
BuildEll                      PASS      13.06 seconds
BluezMake                     PASS      170.23 seconds
MakeCheck                     PASS      12.77 seconds
MakeDistcheck                 PASS      95.77 seconds
CheckValgrind                 PASS      218.50 seconds
CheckSmatch                   PASS      176.02 seconds
bluezmakeextell               PASS      60.31 seconds
TestFunctional                PASS      895.05 seconds
IncrementalBuild              PASS      194.47 seconds
ScanBuild                     PASS      595.52 seconds

https://github.com/bluez/bluez/pull/2832

---
Regards,
Linux Bluetooth

#3 lore raw

PATCH v4 2/4 adapter: Add btd_adapter_get_conn_info

In reply to Kevin Dewald

Add a function to send Get Connection Information for a connection.

Assisted-by Claude:claude-opus-5.5
---
 src/adapter.c | 18 ++++++++++++++++++
 src/adapter.h |  7 +++++++
 2 files changed, 25 insertions(+)
src/adapter.c +18 -0
index ea438375c..7c40a0460 100644
@@ -11628,3 +11628,21 @@ unsigned int btd_adapter_send_cmd_event_sync(struct btd_adapter *adapter,
 				adapter->dev_id, sizeof(pkt.cp) + length,
 				&pkt, callback, user_data, destroy);
 }
+
+unsigned int btd_adapter_get_conn_info(struct btd_adapter *adapter,
+					const bdaddr_t *bdaddr,
+					uint8_t bdaddr_type,
+					btd_adapter_reply_event_t callback,
+					void *user_data,
+					btd_adapter_destroy_func_t destroy)
+{
+	struct mgmt_cp_get_conn_info cp;
+
+	memset(&cp, 0, sizeof(cp));
+	bacpy(&cp.addr.bdaddr, bdaddr);
+	cp.addr.type = bdaddr_type;
+
+	return mgmt_send(adapter->mgmt, MGMT_OP_GET_CONN_INFO,
+				adapter->dev_id, sizeof(cp), &cp,
+				callback, user_data, destroy);
+}
src/adapter.h +7 -0
index 583168f4b..18e6eaa78 100644
@@ -328,3 +328,10 @@ unsigned int btd_adapter_send_cmd_event_sync(struct btd_adapter *adapter,
 					void *user_data,
 					btd_adapter_destroy_func_t destroy,
 					uint8_t timeout);
+
+unsigned int btd_adapter_get_conn_info(struct btd_adapter *adapter,
+					const bdaddr_t *bdaddr,
+					uint8_t bdaddr_type,
+					btd_adapter_reply_event_t callback,
+					void *user_data,
+					btd_adapter_destroy_func_t destroy);
Signature · 1 line
2.54.0 (Apple Git-157)
#4 lore raw

PATCH v4 3/4 bearer: Add ReadRSSI method

In reply to Kevin Dewald

Implement Bearer.LE1.ReadRSSI with Get Connection Information, as a testing method. The kernel reads the RSSI from the controller, or returns the value it read last if that is recent enough (conn_info_min_age and conn_info_max_age, 1 to 3 seconds by default).

The kernel reports a connection as soon as it is established but only answers Get Connection Information once it has set it up, so a call made right after Connect returns fails with NotReady rather than NotConnected.

Calls made while a request is pending get its result rather than sending another one, as the kernel would answer that with its cached value, which a new connection does not have yet.

A request still pending when the bearer is destroyed is left to complete rather than cancelled, as the kernel replies to it anyway and the reply would be taken for the reply to the next request.

The method is only on Bearer.LE1, as the RSSI of a BR/EDR connection is relative to the golden receive power range rather than in dBm.

Assisted-by Claude:claude-opus-5.5
---
 src/bearer.c | 132 ++++++++++++++++++++++++++++++++++++++++++++++++++-
 1 file changed, 130 insertions(+), 2 deletions(-)
src/bearer.c +130 -2
index ebcdc2b4c..779f6ea3c 100644
@@ -44,6 +44,12 @@
 
 #define DISCONNECT_TIMER	2
 
+/* Get Connection Information request of ReadRSSI */
+struct rssi_req {
+	struct btd_bearer *bearer; /* NULL once the bearer is destroyed */
+	struct queue *msgs; /* ReadRSSI calls waiting for the reply */
+};
+
 struct btd_bearer {
 	struct btd_device *device;
 	uint8_t type;
@@ -57,6 +63,8 @@ struct btd_bearer {
 	 */
 	DBusMessage *connect; /* connect message */
 
+	struct rssi_req *rssi_req;
+
 	/* LE connection parameters, only valid while connected */
 	bool conn_params;
 	uint32_t interval; /* in microseconds */
@@ -213,13 +221,117 @@ static DBusMessage *bearer_disconnect(DBusConnection *conn, DBusMessage *msg,
 	return NULL;
 }
 
-static const GDBusMethodTable bearer_methods[] = {
+static DBusMessage *rssi_reply(struct btd_bearer *bearer, DBusMessage *msg,
+					uint8_t status, uint16_t length,
+					const struct mgmt_rp_get_conn_info *rp)
+{
+	dbus_int16_t rssi;
+
+	/* The kernel reports the connection as soon as it is established, but
+	 * only answers once it has set it up, e.g. read the remote features.
+	 */
+	if (status == MGMT_STATUS_NOT_CONNECTED) {
+		if (btd_device_bdaddr_type_connected(bearer->device,
+							bearer->type))
+			return btd_error_not_ready(msg);
+
+		return btd_error_not_connected(msg);
+	}
+
+	if (status != MGMT_STATUS_SUCCESS)
+		return btd_error_failed(msg, mgmt_errstr(status));
+
+	if (length < sizeof(*rp))
+		return btd_error_failed(msg, "Invalid response");
+
+	/* 127 means the controller has no RSSI for the connection */
+	if (rp->rssi == 127)
+		return btd_error_not_available(msg);
+
+	rssi = rp->rssi;
+
+	return g_dbus_create_reply(msg, DBUS_TYPE_INT16, &rssi,
+							DBUS_TYPE_INVALID);
+}
+
+static void rssi_req_complete(uint8_t status, uint16_t length,
+					const void *param, void *user_data)
+{
+	struct rssi_req *req = user_data;
+	struct btd_bearer *bearer = req->bearer;
+	DBusMessage *msg;
+
+	if (!bearer)
+		return;
+
+	while ((msg = queue_pop_head(req->msgs))) {
+		g_dbus_send_message(btd_get_dbus_connection(),
+				rssi_reply(bearer, msg, status, length, param));
+		dbus_message_unref(msg);
+	}
+}
+
+static void rssi_req_free(void *data)
+{
+	struct rssi_req *req = data;
+
+	if (req->bearer)
+		req->bearer->rssi_req = NULL;
+
+	queue_destroy(req->msgs, bearer_free_dbus_message);
+	free(req);
+}
+
+static DBusMessage *bearer_read_rssi(DBusConnection *conn, DBusMessage *msg,
+							void *user_data)
+{
+	struct btd_bearer *bearer = user_data;
+	struct btd_device *device = bearer->device;
+	struct rssi_req *req;
+
+	if (!btd_device_bdaddr_type_connected(device, bearer->type))
+		return btd_error_not_connected(msg);
+
+	/* Calls made while a read is pending get the same result */
+	if (!bearer->rssi_req) {
+		req = new0(struct rssi_req, 1);
+		req->bearer = bearer;
+		req->msgs = queue_new();
+
+		if (!btd_adapter_get_conn_info(device_get_adapter(device),
+					device_get_address(device),
+					device_get_le_address_type(device),
+					rssi_req_complete, req,
+					rssi_req_free)) {
+			rssi_req_free(req);
+			return btd_error_failed(msg, "Unable to read RSSI");
+		}
+
+		bearer->rssi_req = req;
+	}
+
+	queue_push_tail(bearer->rssi_req->msgs, dbus_message_ref(msg));
+
+	return NULL;
+}
+
+static const GDBusMethodTable bearer_bredr_methods[] = {
 	{ GDBUS_ASYNC_METHOD("Connect", NULL, NULL, bearer_connect) },
 	{ GDBUS_ASYNC_METHOD("Disconnect", NULL, NULL,
 						bearer_disconnect) },
 	{}
 };
 
+static const GDBusMethodTable bearer_le_methods[] = {
+	{ GDBUS_ASYNC_METHOD("Connect", NULL, NULL, bearer_connect) },
+	{ GDBUS_ASYNC_METHOD("Disconnect", NULL, NULL,
+						bearer_disconnect) },
+	{ GDBUS_TESTING_ASYNC_METHOD("ReadRSSI", NULL,
+					GDBUS_ARGS({ "rssi", "n" }),
+					bearer_read_rssi) },
+	{}
+};
+
 static gboolean bearer_get_adapter(const GDBusPropertyTable *property,
 					DBusMessageIter *iter, void *data)
 {
@@ -404,6 +516,14 @@ static const char *bearer_interface(uint8_t type)
 		return BTD_BEARER_LE_INTERFACE;
 }
 
+static const GDBusMethodTable *bearer_methods(uint8_t type)
+{
+	if (type == BDADDR_BREDR)
+		return bearer_bredr_methods;
+	else
+		return bearer_le_methods;
+}
+
 struct btd_bearer *btd_bearer_new(struct btd_device *device, uint8_t type)
 {
 	struct btd_bearer *bearer;
@@ -429,7 +549,7 @@ struct btd_bearer *btd_bearer_new(struct btd_device *device, uint8_t type)
 
 	if (!g_dbus_register_interface(btd_get_dbus_connection(),
 					bearer->path, bearer_interface(type),
-					bearer_methods, bearer_signals,
+					bearer_methods(type), bearer_signals,
 					bearer_properties,
 					bearer, bearer_free)) {
 		error("Unable to register BREDR interface");
@@ -459,6 +579,14 @@ void btd_bearer_destroy(struct btd_bearer *bearer)
 		bearer->connect = NULL;
 	}
 
+	/* Let a pending request complete rather than cancel it, as the kernel
+	 * replies to it anyway and the reply would complete the next request.
+	 */
+	if (bearer->rssi_req) {
+		bearer->rssi_req->bearer = NULL;
+		bearer->rssi_req = NULL;
+	}
+
 	g_dbus_unregister_interface(btd_get_dbus_connection(), bearer->path,
 					bearer_interface(bearer->type));
 }
Signature · 1 line
2.54.0 (Apple Git-157)
#5 lore raw

PATCH v4 4/4 test: functional: add bearer ReadRSSI test

In reply to Kevin Dewald

Read the RSSI of the LE connection from a host with testing interfaces enabled, check ReadRSSI fails with NotConnected once disconnected, and check a host without testing interfaces does not expose it.

Assisted-by Claude:claude-opus-5.5
---
 test/functional/test_bearer.py | 58 ++++++++++++++++++++++++++++++++++
 1 file changed, 58 insertions(+)
test/functional/test_bearer.py +58 -0
index 59ce8ef7d..3f1033b35 100644
@@ -54,6 +54,9 @@ UPDATE_CONF = LE_CONF + "[LE]\nMinConnectionInterval = 80\nMaxConnectionInterval
 
 CONN_PARAMS = ("Interval", "Latency", "SupervisionTimeout", "Subrate")
 
+# ReadRSSI is a testing method
+TESTING_CONF = LE_CONF + "Testing = true\n"
+
 
 class Bearers(HostPlugin, EventPluginMixin):
     """
@@ -206,6 +209,22 @@ def conn_params(host, remote):
     return dict(zip(CONN_PARAMS, map(int, values)))
 
 
+def read_rssi(host, remote):
+    """
+    The RSSI ReadRSSI returns for the LE bearer host has for remote, or
+    None if the kernel has not finished setting up the connection yet.
+    """
+    host.bearers.call(remote.bdaddr, LE_INTERFACE, "ReadRSSI")
+    event = host.bearers.expect(
+        (f"{LE_INTERFACE}.ReadRSSI:reply", f"{LE_INTERFACE}.ReadRSSI:error")
+    )
+    if event.kind.endswith(":error"):
+        assert event.error.get_dbus_name() == "org.bluez.Error.NotReady"
+        return None
+
+    return int(event.values[0])
+
+
 def connect_le(host0, host1):
     discover(host0, host1)
 
@@ -283,6 +302,45 @@ def test_bearer_le_conn_params(hosts):
             assert host.bearers.get(remote.bdaddr, LE_INTERFACE, name) is None
 
 
+@host_config(
+    [
+        Bluetoothd(conf=TESTING_CONF, args=ARGS),
+        Agent(capability="NoInputNoOutput"),
+        Bearers(),
+    ],
+    [
+        Bluetoothd(conf=LE_CONF, args=ARGS),
+        LeAdvertiser(),
+        Agent(capability="NoInputNoOutput"),
+        Bearers(),
+    ],
+)
+def test_bearer_le_read_rssi(hosts):
+    host0, host1 = hosts
+
+    connect_le(host0, host1)
+
+    for host, remote in peers(host0, host1):
+        wait_until(
+            lambda: host.bearers.get(remote.bdaddr, LE_INTERFACE, "Connected") is True
+        )
+
+    wait_until(lambda: read_rssi(host0, host1) is not None)
+
+    # Controllers report the RSSI of a connection from -127 to 20 dBm
+    assert -127 <= read_rssi(host0, host1) <= 20
+
+    host1.bearers.call(host0.bdaddr, LE_INTERFACE, "ReadRSSI")
+    error = host1.bearers.expect(f"{LE_INTERFACE}.ReadRSSI:error").error
+    assert error.get_dbus_name() == "org.freedesktop.DBus.Error.UnknownMethod"
+
+    disconnect(host0, host1, LE_INTERFACE)
+
+    host0.bearers.call(host1.bdaddr, LE_INTERFACE, "ReadRSSI")
+    error = host0.bearers.expect(f"{LE_INTERFACE}.ReadRSSI:error").error
+    assert error.get_dbus_name() == "org.bluez.Error.NotConnected"
+
+
 @host_config(
     [
         Bluetoothd(conf=LE_CONF, args=ARGS),
Signature · 1 line
2.54.0 (Apple Git-157)