]> git.basschouten.com Git - openhab-addons.git/blob
fdddc6f64795f7e30499b264d70d3bb8958c36bc
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2022 Contributors to the openHAB project
3  *
4  * See the NOTICE file(s) distributed with this work for additional
5  * information.
6  *
7  * This program and the accompanying materials are made available under the
8  * terms of the Eclipse Public License 2.0 which is available at
9  * http://www.eclipse.org/legal/epl-2.0
10  *
11  * SPDX-License-Identifier: EPL-2.0
12  */
13 package org.openhab.binding.bluetooth;
14
15 import java.util.UUID;
16 import java.util.concurrent.CompletableFuture;
17 import java.util.concurrent.CompletionException;
18 import java.util.concurrent.ExecutionException;
19 import java.util.concurrent.Future;
20 import java.util.concurrent.ScheduledExecutorService;
21 import java.util.concurrent.ScheduledThreadPoolExecutor;
22 import java.util.concurrent.TimeUnit;
23 import java.util.concurrent.TimeoutException;
24 import java.util.function.Function;
25
26 import org.eclipse.jdt.annotation.NonNullByDefault;
27 import org.eclipse.jdt.annotation.Nullable;
28 import org.openhab.binding.bluetooth.BluetoothDevice.ConnectionState;
29 import org.openhab.binding.bluetooth.notification.BluetoothConnectionStatusNotification;
30 import org.openhab.binding.bluetooth.util.RetryFuture;
31 import org.openhab.core.common.NamedThreadFactory;
32 import org.openhab.core.thing.Thing;
33 import org.openhab.core.thing.ThingStatus;
34 import org.openhab.core.thing.ThingStatusDetail;
35 import org.openhab.core.util.HexUtils;
36 import org.slf4j.Logger;
37 import org.slf4j.LoggerFactory;
38
39 /**
40  * This is a base implementation for more specific thing handlers that require constant connection to bluetooth devices.
41  *
42  * @author Kai Kreuzer - Initial contribution and API
43  */
44 @NonNullByDefault
45 public class ConnectedBluetoothHandler extends BeaconBluetoothHandler {
46
47     private final Logger logger = LoggerFactory.getLogger(ConnectedBluetoothHandler.class);
48     private @Nullable Future<?> reconnectJob;
49     private @Nullable Future<?> pendingDisconnect;
50
51     private boolean alwaysConnected;
52     private int idleDisconnectDelay = 1000;
53
54     // we initially set the to scheduler so that we can keep this field non-null
55     private ScheduledExecutorService connectionTaskExecutor = scheduler;
56
57     public ConnectedBluetoothHandler(Thing thing) {
58         super(thing);
59     }
60
61     @Override
62     public void initialize() {
63
64         // super.initialize adds callbacks that might require the connectionTaskExecutor to be present, so we initialize
65         // the connectionTaskExecutor first
66         ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(1,
67                 new NamedThreadFactory("bluetooth-connection" + thing.getThingTypeUID(), true));
68         executor.setExecuteExistingDelayedTasksAfterShutdownPolicy(false);
69         executor.setRemoveOnCancelPolicy(true);
70         connectionTaskExecutor = executor;
71
72         super.initialize();
73
74         if (thing.getStatus() == ThingStatus.OFFLINE) {
75             // something went wrong in super.initialize() so we shouldn't initialize further here either
76             return;
77         }
78
79         Object alwaysConnectRaw = getConfig().get(BluetoothBindingConstants.CONFIGURATION_ALWAYS_CONNECTED);
80         alwaysConnected = !Boolean.FALSE.equals(alwaysConnectRaw);
81
82         Object idleDisconnectDelayRaw = getConfig().get(BluetoothBindingConstants.CONFIGURATION_IDLE_DISCONNECT_DELAY);
83         idleDisconnectDelay = 1000;
84         if (idleDisconnectDelayRaw instanceof Number) {
85             idleDisconnectDelay = ((Number) idleDisconnectDelayRaw).intValue();
86         }
87
88         if (alwaysConnected) {
89             reconnectJob = connectionTaskExecutor.scheduleWithFixedDelay(() -> {
90                 try {
91                     if (device.getConnectionState() != ConnectionState.CONNECTED) {
92                         if (!device.connect()) {
93                             logger.debug("Failed to connect to {}", address);
94                         }
95                         // we do not set the Thing status here, because we will anyhow receive a call to
96                         // onConnectionStateChange
97                     } else {
98                         // just in case it was already connected to begin with
99                         updateStatus(ThingStatus.ONLINE);
100                         if (!device.isServicesDiscovered() && !device.discoverServices()) {
101                             logger.debug("Error while discovering services");
102                         }
103                     }
104                 } catch (RuntimeException ex) {
105                     logger.warn("Unexpected error occurred", ex);
106                 }
107             }, 0, 30, TimeUnit.SECONDS);
108         }
109     }
110
111     @Override
112     @SuppressWarnings("PMD.CompareObjectsWithEquals")
113     public void dispose() {
114         cancel(reconnectJob, true);
115         reconnectJob = null;
116         cancel(pendingDisconnect, true);
117         pendingDisconnect = null;
118
119         super.dispose();
120
121         // just in case something goes really wrong in the core and it tries to dispose a handler before initializing it
122         if (scheduler != connectionTaskExecutor) {
123             connectionTaskExecutor.shutdownNow();
124         }
125     }
126
127     private static void cancel(@Nullable Future<?> future, boolean interrupt) {
128         if (future != null) {
129             future.cancel(interrupt);
130         }
131     }
132
133     public void connect() {
134         connectionTaskExecutor.execute(() -> {
135             if (!device.connect()) {
136                 logger.debug("Failed to connect to {}", address);
137             }
138         });
139     }
140
141     public void disconnect() {
142         connectionTaskExecutor.execute(device::disconnect);
143     }
144
145     private void scheduleDisconnect() {
146         cancel(pendingDisconnect, false);
147         pendingDisconnect = connectionTaskExecutor.schedule(device::disconnect, idleDisconnectDelay,
148                 TimeUnit.MILLISECONDS);
149     }
150
151     private void connectAndWait() throws ConnectionException, TimeoutException, InterruptedException {
152         if (device.getConnectionState() == ConnectionState.CONNECTED) {
153             return;
154         }
155         if (device.getConnectionState() != ConnectionState.CONNECTING) {
156             if (!device.connect()) {
157                 throw new ConnectionException("Failed to start connecting");
158             }
159         }
160         if (!device.awaitConnection(1, TimeUnit.SECONDS)) {
161             throw new TimeoutException("Connection attempt timeout.");
162         }
163         if (!device.isServicesDiscovered()) {
164             device.discoverServices();
165             if (!device.awaitServiceDiscovery(10, TimeUnit.SECONDS)) {
166                 throw new TimeoutException("Service discovery timeout");
167             }
168         }
169     }
170
171     private BluetoothCharacteristic connectAndGetCharacteristic(UUID serviceUUID, UUID characteristicUUID)
172             throws BluetoothException, TimeoutException, InterruptedException {
173         connectAndWait();
174         BluetoothService service = device.getServices(serviceUUID);
175         if (service == null) {
176             throw new BluetoothException("Service with uuid " + serviceUUID + " could not be found");
177         }
178         BluetoothCharacteristic characteristic = service.getCharacteristic(characteristicUUID);
179         if (characteristic == null) {
180             throw new BluetoothException("Characteristic with uuid " + characteristicUUID + " could not be found");
181         }
182         return characteristic;
183     }
184
185     @SuppressWarnings("PMD.CompareObjectsWithEquals")
186     private <T> CompletableFuture<T> executeWithConnection(UUID serviceUUID, UUID characteristicUUID,
187             Function<BluetoothCharacteristic, CompletableFuture<T>> callable) {
188         if (connectionTaskExecutor == scheduler) {
189             return CompletableFuture
190                     .failedFuture(new IllegalStateException("connectionTaskExecutor has not been initialized"));
191         }
192         if (connectionTaskExecutor.isShutdown()) {
193             return CompletableFuture.failedFuture(new IllegalStateException("connectionTaskExecutor is shut down"));
194         }
195         // we use a RetryFuture because it supports running Callable instances
196         return RetryFuture.callWithRetry(() -> {
197             // we block for completion here so that we keep the lock on the connectionTaskExecutor active.
198             return callable.apply(connectAndGetCharacteristic(serviceUUID, characteristicUUID)).get();
199         }, connectionTaskExecutor)// we make this completion async so that operations chained off the returned future
200                                   // will not run on the connectionTaskExecutor
201                 .whenCompleteAsync((r, th) -> {
202                     // we us a while loop here in case the exceptions get nested
203                     while (th instanceof CompletionException || th instanceof ExecutionException) {
204                         th = th.getCause();
205                     }
206                     if (th instanceof InterruptedException) {
207                         // we don't want to schedule anything if we receive an interrupt
208                         return;
209                     }
210                     if (th instanceof TimeoutException) {
211                         updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, th.getMessage());
212                     }
213                     if (!alwaysConnected) {
214                         scheduleDisconnect();
215                     }
216                 }, scheduler);
217     }
218
219     public CompletableFuture<@Nullable Void> enableNotifications(UUID serviceUUID, UUID characteristicUUID) {
220         return executeWithConnection(serviceUUID, characteristicUUID, device::enableNotifications);
221     }
222
223     public CompletableFuture<@Nullable Void> writeCharacteristic(UUID serviceUUID, UUID characteristicUUID, byte[] data,
224             boolean enableNotification) {
225         var future = executeWithConnection(serviceUUID, characteristicUUID, characteristic -> {
226             if (enableNotification) {
227                 return device.enableNotifications(characteristic)
228                         .thenCompose((v) -> device.writeCharacteristic(characteristic, data));
229             } else {
230                 return device.writeCharacteristic(characteristic, data);
231             }
232         });
233         if (logger.isDebugEnabled()) {
234             future = future.whenComplete((v, t) -> {
235                 if (t == null) {
236                     logger.debug("Characteristic {} from {} has written value {}", characteristicUUID, address,
237                             HexUtils.bytesToHex(data));
238                 }
239             });
240         }
241         return future;
242     }
243
244     public CompletableFuture<byte[]> readCharacteristic(UUID serviceUUID, UUID characteristicUUID) {
245         var future = executeWithConnection(serviceUUID, characteristicUUID, device::readCharacteristic);
246         if (logger.isDebugEnabled()) {
247             future = future.whenComplete((data, t) -> {
248                 if (t == null) {
249                     if (logger.isDebugEnabled()) {
250                         logger.debug("Characteristic {} from {} has been read - value {}", characteristicUUID, address,
251                                 HexUtils.bytesToHex(data));
252                     }
253                 }
254             });
255         }
256         return future;
257     }
258
259     @Override
260     protected void updateStatusBasedOnRssi(boolean receivedSignal) {
261         // if there is no signal, we can be sure we are OFFLINE, but if there is a signal, we also have to check whether
262         // we are connected.
263         if (receivedSignal) {
264             if (alwaysConnected) {
265                 if (device.getConnectionState() == ConnectionState.CONNECTED) {
266                     updateStatus(ThingStatus.ONLINE);
267                 } else {
268                     updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.NONE, "Device is not connected.");
269                 }
270             }
271         } else {
272             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR);
273         }
274     }
275
276     @Override
277     public void onConnectionStateChange(BluetoothConnectionStatusNotification connectionNotification) {
278         super.onConnectionStateChange(connectionNotification);
279         switch (connectionNotification.getConnectionState()) {
280             case DISCOVERED:
281                 // The device is now known on the Bluetooth network, so we can do something...
282                 if (alwaysConnected) {
283                     connectionTaskExecutor.submit(() -> {
284                         if (device.getConnectionState() != ConnectionState.CONNECTED) {
285                             if (!device.connect()) {
286                                 logger.debug("Error connecting to device after discovery.");
287                             }
288                         }
289                     });
290                 }
291                 break;
292             case CONNECTED:
293                 if (alwaysConnected) {
294                     connectionTaskExecutor.submit(() -> {
295                         if (!device.isServicesDiscovered() && !device.discoverServices()) {
296                             logger.debug("Error while discovering services");
297                         }
298                     });
299                 }
300                 break;
301             case DISCONNECTED:
302                 cancel(pendingDisconnect, false);
303                 if (alwaysConnected) {
304                     updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR);
305                 }
306                 break;
307             default:
308                 break;
309         }
310     }
311
312     @Override
313     public void onCharacteristicUpdate(BluetoothCharacteristic characteristic, byte[] value) {
314         super.onCharacteristicUpdate(characteristic, value);
315         if (logger.isDebugEnabled()) {
316             logger.debug("Recieved update {} to characteristic {} of device {}", HexUtils.bytesToHex(value),
317                     characteristic.getUuid(), address);
318         }
319     }
320
321     @Override
322     public void onDescriptorUpdate(BluetoothDescriptor descriptor, byte[] value) {
323         super.onDescriptorUpdate(descriptor, value);
324         if (logger.isDebugEnabled()) {
325             logger.debug("Received update {} to descriptor {} of device {}", HexUtils.bytesToHex(value),
326                     descriptor.getUuid(), address);
327         }
328     }
329 }