2 * Copyright (c) 2010-2020 Contributors to the openHAB project
4 * See the NOTICE file(s) distributed with this work for additional
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
11 * SPDX-License-Identifier: EPL-2.0
13 package org.openhab.binding.bluetooth.discovery.internal;
15 import java.util.HashMap;
16 import java.util.HashSet;
18 import java.util.Optional;
20 import java.util.concurrent.CompletableFuture;
21 import java.util.concurrent.ConcurrentHashMap;
22 import java.util.concurrent.CopyOnWriteArraySet;
23 import java.util.function.BiConsumer;
25 import org.eclipse.jdt.annotation.NonNullByDefault;
26 import org.eclipse.jdt.annotation.Nullable;
27 import org.openhab.binding.bluetooth.BluetoothAdapter;
28 import org.openhab.binding.bluetooth.BluetoothAddress;
29 import org.openhab.binding.bluetooth.BluetoothBindingConstants;
30 import org.openhab.binding.bluetooth.BluetoothDevice;
31 import org.openhab.binding.bluetooth.BluetoothDiscoveryListener;
32 import org.openhab.binding.bluetooth.discovery.BluetoothDiscoveryParticipant;
33 import org.openhab.core.config.discovery.AbstractDiscoveryService;
34 import org.openhab.core.config.discovery.DiscoveryResult;
35 import org.openhab.core.config.discovery.DiscoveryResultBuilder;
36 import org.openhab.core.config.discovery.DiscoveryService;
37 import org.openhab.core.thing.ThingTypeUID;
38 import org.openhab.core.thing.ThingUID;
39 import org.osgi.service.component.annotations.Activate;
40 import org.osgi.service.component.annotations.Component;
41 import org.osgi.service.component.annotations.Deactivate;
42 import org.osgi.service.component.annotations.Modified;
43 import org.osgi.service.component.annotations.Reference;
44 import org.osgi.service.component.annotations.ReferenceCardinality;
45 import org.osgi.service.component.annotations.ReferencePolicy;
46 import org.slf4j.Logger;
47 import org.slf4j.LoggerFactory;
50 * The {@link BluetoothDiscoveryService} handles searching for BLE devices.
52 * @author Chris Jackson - Initial Contribution
53 * @author Kai Kreuzer - Introduced BluetoothAdapters and BluetoothDiscoveryParticipants
54 * @author Connor Petty - Introduced connection based discovery and added roaming support
57 @Component(service = DiscoveryService.class, configurationPid = "discovery.bluetooth")
58 public class BluetoothDiscoveryService extends AbstractDiscoveryService implements BluetoothDiscoveryListener {
60 private final Logger logger = LoggerFactory.getLogger(BluetoothDiscoveryService.class);
62 private static final int SEARCH_TIME = 15;
64 private final Set<BluetoothAdapter> adapters = new CopyOnWriteArraySet<>();
65 private final Set<BluetoothDiscoveryParticipant> participants = new CopyOnWriteArraySet<>();
67 private final Map<BluetoothAddress, DiscoveryCache> discoveryCaches = new ConcurrentHashMap<>();
69 private final Set<ThingTypeUID> supportedThingTypes = new CopyOnWriteArraySet<>();
71 public BluetoothDiscoveryService() {
73 supportedThingTypes.add(BluetoothBindingConstants.THING_TYPE_BEACON);
78 protected void activate(@Nullable Map<String, @Nullable Object> configProperties) {
79 logger.debug("Activating Bluetooth discovery service");
80 super.activate(configProperties);
85 protected void modified(@Nullable Map<String, @Nullable Object> configProperties) {
86 super.modified(configProperties);
91 public void deactivate() {
92 logger.debug("Deactivating Bluetooth discovery service");
95 @Reference(cardinality = ReferenceCardinality.MULTIPLE, policy = ReferencePolicy.DYNAMIC)
96 protected void addBluetoothAdapter(BluetoothAdapter adapter) {
97 this.adapters.add(adapter);
98 adapter.addDiscoveryListener(this);
101 protected void removeBluetoothAdapter(BluetoothAdapter adapter) {
102 this.adapters.remove(adapter);
103 adapter.removeDiscoveryListener(this);
106 @Reference(cardinality = ReferenceCardinality.MULTIPLE, policy = ReferencePolicy.DYNAMIC)
107 protected void addBluetoothDiscoveryParticipant(BluetoothDiscoveryParticipant participant) {
108 this.participants.add(participant);
109 supportedThingTypes.addAll(participant.getSupportedThingTypeUIDs());
112 protected void removeBluetoothDiscoveryParticipant(BluetoothDiscoveryParticipant participant) {
113 supportedThingTypes.removeAll(participant.getSupportedThingTypeUIDs());
114 this.participants.remove(participant);
118 public Set<ThingTypeUID> getSupportedThingTypes() {
119 return supportedThingTypes;
123 public void startScan() {
124 for (BluetoothAdapter adapter : adapters) {
130 public void stopScan() {
131 for (BluetoothAdapter adapter : adapters) {
134 removeOlderResults(getTimestampOfLastScan());
138 public void deviceRemoved(BluetoothDevice device) {
139 discoveryCaches.computeIfPresent(device.getAddress(), (addr, cache) -> cache.removeDiscoveries(device));
143 public void deviceDiscovered(BluetoothDevice device) {
144 logger.debug("Discovered bluetooth device '{}': {}", device.getName(), device);
146 DiscoveryCache cache = discoveryCaches.computeIfAbsent(device.getAddress(), addr -> new DiscoveryCache());
147 cache.handleDiscovery(device);
150 private static ThingUID createThingUIDWithBridge(DiscoveryResult result, BluetoothAdapter adapter) {
151 return new ThingUID(result.getThingTypeUID(), adapter.getUID(), result.getThingUID().getId());
154 private static DiscoveryResult copyWithNewBridge(DiscoveryResult result, BluetoothAdapter adapter) {
155 String label = result.getLabel();
156 String adapterLabel = adapter.getLabel();
157 if (adapterLabel != null) {
158 label = adapterLabel + " - " + label;
161 return DiscoveryResultBuilder.create(createThingUIDWithBridge(result, adapter))//
162 .withBridge(adapter.getUID())//
163 .withProperties(result.getProperties())//
164 .withRepresentationProperty(result.getRepresentationProperty())//
165 .withTTL(result.getTimeToLive())//
170 private class DiscoveryCache {
172 private final Map<BluetoothAdapter, SnapshotFuture> discoveryFutures = new HashMap<>();
173 private final Map<BluetoothAdapter, @Nullable Set<DiscoveryResult>> discoveryResults = new ConcurrentHashMap<>();
175 private @Nullable BluetoothDeviceSnapshot latestSnapshot;
178 * This is meant to be used as part of a Map.compute function
180 * @param device the device to remove from this cache
181 * @return this DiscoveryCache if there are still snapshots, null otherwise
183 public synchronized @Nullable DiscoveryCache removeDiscoveries(final BluetoothDevice device) {
184 // we remove any discoveries that have been published for this device
185 BluetoothAdapter adapter = device.getAdapter();
186 if (discoveryFutures.containsKey(adapter)) {
187 discoveryFutures.remove(adapter).future.thenAccept(result -> retractDiscoveryResult(adapter, result));
189 if (discoveryFutures.isEmpty()) {
195 public synchronized void handleDiscovery(BluetoothDevice device) {
196 if (!discoveryFutures.isEmpty()) {
198 // we have an ongoing futures so lets create our discovery after they all finish
199 .allOf(discoveryFutures.values().stream().map(sf -> sf.future)
200 .toArray(CompletableFuture[]::new))
201 .thenRun(() -> createDiscoveryFuture(device));
203 createDiscoveryFuture(device);
207 private synchronized void createDiscoveryFuture(BluetoothDevice device) {
208 BluetoothAdapter adapter = device.getAdapter();
209 CompletableFuture<DiscoveryResult> future = null;
211 BluetoothDeviceSnapshot snapshot = new BluetoothDeviceSnapshot(device);
212 BluetoothDeviceSnapshot latestSnapshot = this.latestSnapshot;
213 if (latestSnapshot != null) {
214 snapshot.merge(latestSnapshot);
216 if (snapshot.equals(latestSnapshot)) {
217 // this means that snapshot has no newer fields than the latest snapshot
218 if (discoveryFutures.containsKey(adapter)
219 && discoveryFutures.get(adapter).snapshot.equals(latestSnapshot)) {
220 // This adapter has already produced the most up-to-date result, so no further processing is
226 * This isn't a new snapshot, but an up-to-date result from this adapter has not been produced yet.
227 * Since a result must have been produced for this snapshot, we search the results of the other
228 * adapters to find the future for the latest snapshot, then we modify it to make it look like it
229 * came from this adapter. This way we don't need to recompute the DiscoveryResult.
231 Optional<CompletableFuture<DiscoveryResult>> otherFuture = discoveryFutures.values().stream()
232 // make sure that we only get futures for the current snapshot
233 .filter(sf -> sf.snapshot.equals(latestSnapshot)).findAny().map(sf -> sf.future);
234 if (otherFuture.isPresent()) {
235 future = otherFuture.get();
239 this.latestSnapshot = snapshot;
241 if (future == null) {
242 // we pass in the snapshot since it acts as a delegate for the device. It will also retain any new
243 // fields added to the device as part of the discovery process.
244 future = startDiscoveryProcess(snapshot);
247 if (discoveryFutures.containsKey(adapter)) {
248 // now we need to make sure that we remove the old discovered result if it is different from the new
250 SnapshotFuture oldSF = discoveryFutures.get(adapter);
251 future = oldSF.future.thenCombine(future, (oldResult, newResult) -> {
252 logger.trace("\n old: {}\n new: {}", oldResult, newResult);
253 if (!oldResult.getThingUID().equals(newResult.getThingUID())) {
254 retractDiscoveryResult(adapter, oldResult);
260 * this appends a post-process to any ongoing or completed discoveries with this device's address.
261 * If this discoveryFuture is ongoing then this post-process will run asynchronously upon the future's
263 * If this discoveryFuture is already completed then this post-process will run in the current thread.
264 * We need to make sure that this is part of the future chain so that the call to 'thingRemoved'
265 * in the 'removeDiscoveries' method above can be sure that it is running after the 'thingDiscovered'
267 future = future.thenApply(result -> {
268 publishDiscoveryResult(adapter, result);
270 }).whenComplete((r, t) -> {
272 logger.warn("Error occured during discovery of {}", device.getAddress(), t);
276 // now save this snapshot for later
277 discoveryFutures.put(adapter, new SnapshotFuture(snapshot, future));
280 private void publishDiscoveryResult(BluetoothAdapter adapter, DiscoveryResult result) {
281 Set<DiscoveryResult> results = new HashSet<>();
282 BiConsumer<BluetoothAdapter, DiscoveryResult> publisher = (a, r) -> {
283 results.add(copyWithNewBridge(r, a));
286 publisher.accept(adapter, result);
287 for (BluetoothDiscoveryParticipant participant : participants) {
288 participant.publishAdditionalResults(result, publisher);
290 results.forEach(BluetoothDiscoveryService.this::thingDiscovered);
291 discoveryResults.put(adapter, results);
294 private void retractDiscoveryResult(BluetoothAdapter adapter, DiscoveryResult result) {
295 Set<DiscoveryResult> results = discoveryResults.remove(adapter);
296 if (results != null) {
297 for (DiscoveryResult r : results) {
298 thingRemoved(r.getThingUID());
303 private CompletableFuture<DiscoveryResult> startDiscoveryProcess(BluetoothDeviceSnapshot device) {
304 return CompletableFuture.supplyAsync(new BluetoothDiscoveryProcess(device, participants, adapters),
309 private static class SnapshotFuture {
310 public final BluetoothDeviceSnapshot snapshot;
311 public final CompletableFuture<DiscoveryResult> future;
313 public SnapshotFuture(BluetoothDeviceSnapshot snapshot, CompletableFuture<DiscoveryResult> future) {
314 this.snapshot = snapshot;
315 this.future = future;