From e304f3876781b4a215356f77bfbc983a0f027afc Mon Sep 17 00:00:00 2001 From: Peter Rosenberg Date: Sat, 19 Feb 2022 15:57:09 +1100 Subject: [PATCH] [bluetooth] temporarily connect the device for Service discovery Signed-off-by: Peter Rosenberg --- .../bluetooth/ConnectedBluetoothHandler.java | 24 +++++++++++++++++-- 1 file changed, 22 insertions(+), 2 deletions(-) diff --git a/bundles/org.openhab.binding.bluetooth/src/main/java/org/openhab/binding/bluetooth/ConnectedBluetoothHandler.java b/bundles/org.openhab.binding.bluetooth/src/main/java/org/openhab/binding/bluetooth/ConnectedBluetoothHandler.java index fdddc6f64795f..36bbf6fc0f27f 100644 --- a/bundles/org.openhab.binding.bluetooth/src/main/java/org/openhab/binding/bluetooth/ConnectedBluetoothHandler.java +++ b/bundles/org.openhab.binding.bluetooth/src/main/java/org/openhab/binding/bluetooth/ConnectedBluetoothHandler.java @@ -85,11 +85,21 @@ public void initialize() { idleDisconnectDelay = ((Number) idleDisconnectDelayRaw).intValue(); } - if (alwaysConnected) { + // Start the recurrent job if the device is always connected + // or if the Services where not yet discovered. + // If the device is not always connected, the job will be terminated + // after successful connection and the device disconnected after Service + // discovery in `onServicesDiscovered()`. + if (alwaysConnected || !device.isServicesDiscovered()) { reconnectJob = connectionTaskExecutor.scheduleWithFixedDelay(() -> { try { if (device.getConnectionState() != ConnectionState.CONNECTED) { - if (!device.connect()) { + if (device.connect()) { + if (!alwaysConnected) { + cancel(reconnectJob, false); + reconnectJob = null; + } + } else { logger.debug("Failed to connect to {}", address); } // we do not set the Thing status here, because we will anyhow receive a call to @@ -326,4 +336,14 @@ public void onDescriptorUpdate(BluetoothDescriptor descriptor, byte[] value) { descriptor.getUuid(), address); } } + + @Override + public void onServicesDiscovered() { + super.onServicesDiscovered(); + + if (!alwaysConnected && device.getConnectionState() == ConnectionState.CONNECTED) { + // disconnect when the device was only connected to discover the Services. + disconnect(); + } + } }