]> git.basschouten.com Git - openhab-addons.git/blob
129873f0e75fc48153de431b2a94e8cd863a94d4
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2023 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.discovery.internal;
14
15 import java.time.Duration;
16 import java.util.HashMap;
17 import java.util.HashSet;
18 import java.util.Map;
19 import java.util.Optional;
20 import java.util.Set;
21 import java.util.concurrent.CompletableFuture;
22 import java.util.concurrent.ConcurrentHashMap;
23 import java.util.concurrent.CopyOnWriteArraySet;
24 import java.util.function.BiConsumer;
25
26 import org.eclipse.jdt.annotation.NonNullByDefault;
27 import org.eclipse.jdt.annotation.Nullable;
28 import org.openhab.binding.bluetooth.BluetoothAdapter;
29 import org.openhab.binding.bluetooth.BluetoothAddress;
30 import org.openhab.binding.bluetooth.BluetoothBindingConstants;
31 import org.openhab.binding.bluetooth.BluetoothDevice;
32 import org.openhab.binding.bluetooth.BluetoothDiscoveryListener;
33 import org.openhab.binding.bluetooth.discovery.BluetoothDiscoveryParticipant;
34 import org.openhab.core.cache.ExpiringCache;
35 import org.openhab.core.config.discovery.AbstractDiscoveryService;
36 import org.openhab.core.config.discovery.DiscoveryResult;
37 import org.openhab.core.config.discovery.DiscoveryResultBuilder;
38 import org.openhab.core.config.discovery.DiscoveryService;
39 import org.openhab.core.thing.ThingTypeUID;
40 import org.openhab.core.thing.ThingUID;
41 import org.osgi.service.component.annotations.Activate;
42 import org.osgi.service.component.annotations.Component;
43 import org.osgi.service.component.annotations.Deactivate;
44 import org.osgi.service.component.annotations.Modified;
45 import org.osgi.service.component.annotations.Reference;
46 import org.osgi.service.component.annotations.ReferenceCardinality;
47 import org.osgi.service.component.annotations.ReferencePolicy;
48 import org.slf4j.Logger;
49 import org.slf4j.LoggerFactory;
50
51 /**
52  * The {@link BluetoothDiscoveryService} handles searching for BLE devices.
53  *
54  * @author Chris Jackson - Initial Contribution
55  * @author Kai Kreuzer - Introduced BluetoothAdapters and BluetoothDiscoveryParticipants
56  * @author Connor Petty - Introduced connection based discovery and added roaming support
57  */
58 @NonNullByDefault
59 @Component(service = DiscoveryService.class, configurationPid = "discovery.bluetooth")
60 public class BluetoothDiscoveryService extends AbstractDiscoveryService implements BluetoothDiscoveryListener {
61
62     private final Logger logger = LoggerFactory.getLogger(BluetoothDiscoveryService.class);
63
64     private static final int SEARCH_TIME = 15;
65
66     private final Set<BluetoothAdapter> adapters = new CopyOnWriteArraySet<>();
67     private final Set<BluetoothDiscoveryParticipant> participants = new CopyOnWriteArraySet<>();
68     @NonNullByDefault({})
69     private final Map<BluetoothAddress, DiscoveryCache> discoveryCaches = new ConcurrentHashMap<>();
70
71     private final Set<ThingTypeUID> supportedThingTypes = new CopyOnWriteArraySet<>();
72
73     public BluetoothDiscoveryService() {
74         super(SEARCH_TIME);
75         supportedThingTypes.add(BluetoothBindingConstants.THING_TYPE_BEACON);
76     }
77
78     @Override
79     @Activate
80     protected void activate(@Nullable Map<String, Object> configProperties) {
81         logger.debug("Activating Bluetooth discovery service");
82         super.activate(configProperties);
83     }
84
85     @Override
86     @Modified
87     protected void modified(@Nullable Map<String, Object> configProperties) {
88         super.modified(configProperties);
89     }
90
91     @Override
92     @Deactivate
93     public void deactivate() {
94         logger.debug("Deactivating Bluetooth discovery service");
95     }
96
97     @Reference(cardinality = ReferenceCardinality.MULTIPLE, policy = ReferencePolicy.DYNAMIC)
98     protected void addBluetoothAdapter(BluetoothAdapter adapter) {
99         this.adapters.add(adapter);
100         adapter.addDiscoveryListener(this);
101     }
102
103     protected void removeBluetoothAdapter(BluetoothAdapter adapter) {
104         this.adapters.remove(adapter);
105         adapter.removeDiscoveryListener(this);
106     }
107
108     @Reference(cardinality = ReferenceCardinality.MULTIPLE, policy = ReferencePolicy.DYNAMIC)
109     protected void addBluetoothDiscoveryParticipant(BluetoothDiscoveryParticipant participant) {
110         this.participants.add(participant);
111         supportedThingTypes.addAll(participant.getSupportedThingTypeUIDs());
112     }
113
114     protected void removeBluetoothDiscoveryParticipant(BluetoothDiscoveryParticipant participant) {
115         supportedThingTypes.removeAll(participant.getSupportedThingTypeUIDs());
116         this.participants.remove(participant);
117     }
118
119     @Override
120     public Set<ThingTypeUID> getSupportedThingTypes() {
121         return supportedThingTypes;
122     }
123
124     @Override
125     public void startScan() {
126         for (BluetoothAdapter adapter : adapters) {
127             adapter.scanStart();
128         }
129     }
130
131     @Override
132     public void stopScan() {
133         for (BluetoothAdapter adapter : adapters) {
134             adapter.scanStop();
135         }
136
137         // The method `removeOlderResults()` removes the Things from listeners like `Inbox`.
138         // We therefore need to reset `latestSnapshot` so that the Things are notified again next time.
139         // Results newer than `getTimestampOfLastScan()` will also be notified again but do not lead to duplicates.
140         discoveryCaches.values().forEach(discoveryCache -> {
141             discoveryCache.latestSnapshot.putValue(null);
142         });
143         removeOlderResults(getTimestampOfLastScan());
144     }
145
146     @Override
147     public void deviceRemoved(BluetoothDevice device) {
148         discoveryCaches.computeIfPresent(device.getAddress(), (addr, cache) -> cache.removeDiscoveries(device));
149     }
150
151     @Override
152     public void deviceDiscovered(BluetoothDevice device) {
153         logger.debug("Discovered bluetooth device '{}': {}", device.getName(), device);
154
155         DiscoveryCache cache = discoveryCaches.computeIfAbsent(device.getAddress(), addr -> new DiscoveryCache());
156         cache.handleDiscovery(device);
157     }
158
159     private static ThingUID createThingUIDWithBridge(DiscoveryResult result, BluetoothAdapter adapter) {
160         return new ThingUID(result.getThingTypeUID(), adapter.getUID(), result.getThingUID().getId());
161     }
162
163     private static DiscoveryResult copyWithNewBridge(DiscoveryResult result, BluetoothAdapter adapter) {
164         String label = result.getLabel();
165
166         return DiscoveryResultBuilder.create(createThingUIDWithBridge(result, adapter))//
167                 .withBridge(adapter.getUID())//
168                 .withProperties(result.getProperties())//
169                 .withRepresentationProperty(result.getRepresentationProperty())//
170                 .withTTL(result.getTimeToLive())//
171                 .withLabel(label)//
172                 .build();
173     }
174
175     private class DiscoveryCache {
176
177         private final Map<BluetoothAdapter, SnapshotFuture> discoveryFutures = new HashMap<>();
178         private final Map<BluetoothAdapter, Set<DiscoveryResult>> discoveryResults = new ConcurrentHashMap<>();
179
180         private ExpiringCache<BluetoothDeviceSnapshot> latestSnapshot = new ExpiringCache<>(Duration.ofMinutes(1),
181                 () -> null);
182
183         /**
184          * This is meant to be used as part of a Map.compute function
185          *
186          * @param device the device to remove from this cache
187          * @return this DiscoveryCache if there are still snapshots, null otherwise
188          */
189         public synchronized @Nullable DiscoveryCache removeDiscoveries(final BluetoothDevice device) {
190             // we remove any discoveries that have been published for this device
191             BluetoothAdapter adapter = device.getAdapter();
192             if (discoveryFutures.containsKey(adapter)) {
193                 @Nullable
194                 SnapshotFuture ssFuture = discoveryFutures.remove(adapter);
195                 if (ssFuture != null) {
196                     ssFuture.future.thenAccept(result -> retractDiscoveryResult(adapter, result));
197                 }
198             }
199             if (discoveryFutures.isEmpty()) {
200                 return null;
201             }
202             return this;
203         }
204
205         public synchronized void handleDiscovery(BluetoothDevice device) {
206             if (!discoveryFutures.isEmpty()) {
207                 CompletableFuture
208                         // we have an ongoing futures so lets create our discovery after they all finish
209                         .allOf(discoveryFutures.values().stream().map(sf -> sf.future)
210                                 .toArray(CompletableFuture[]::new))
211                         .thenRun(() -> createDiscoveryFuture(device));
212             } else {
213                 createDiscoveryFuture(device);
214             }
215         }
216
217         private synchronized void createDiscoveryFuture(BluetoothDevice device) {
218             BluetoothAdapter adapter = device.getAdapter();
219             CompletableFuture<DiscoveryResult> future = null;
220
221             BluetoothDeviceSnapshot snapshot = new BluetoothDeviceSnapshot(device);
222             BluetoothDeviceSnapshot latestSnapshot = this.latestSnapshot.getValue();
223             if (latestSnapshot != null) {
224                 snapshot.merge(latestSnapshot);
225
226                 if (snapshot.equals(latestSnapshot)) {
227                     // this means that snapshot has no newer fields than the latest snapshot
228                     if (discoveryFutures.containsKey(adapter)
229                             && discoveryFutures.get(adapter).snapshot.equals(latestSnapshot)) {
230                         // This adapter has already produced the most up-to-date result, so no further processing is
231                         // necessary
232                         return;
233                     }
234
235                     /*
236                      * This isn't a new snapshot, but an up-to-date result from this adapter has not been produced yet.
237                      * Since a result must have been produced for this snapshot, we search the results of the other
238                      * adapters to find the future for the latest snapshot, then we modify it to make it look like it
239                      * came from this adapter. This way we don't need to recompute the DiscoveryResult.
240                      */
241                     Optional<CompletableFuture<DiscoveryResult>> otherFuture = discoveryFutures.values().stream()
242                             // make sure that we only get futures for the current snapshot
243                             .filter(sf -> sf.snapshot.equals(latestSnapshot)).findAny().map(sf -> sf.future);
244                     if (otherFuture.isPresent()) {
245                         future = otherFuture.get();
246                     }
247                 }
248             }
249             this.latestSnapshot.putValue(snapshot);
250
251             if (future == null) {
252                 // we pass in the snapshot since it acts as a delegate for the device. It will also retain any new
253                 // fields added to the device as part of the discovery process.
254                 future = startDiscoveryProcess(snapshot);
255             }
256
257             if (discoveryFutures.containsKey(adapter)) {
258                 // now we need to make sure that we remove the old discovered result if it is different from the new
259                 // one.
260
261                 @Nullable
262                 SnapshotFuture oldSF = discoveryFutures.get(adapter);
263                 future = oldSF.future.thenCombine(future, (oldResult, newResult) -> {
264                     logger.trace("\n old: {}\n new: {}", oldResult, newResult);
265                     if (!oldResult.getThingUID().equals(newResult.getThingUID())) {
266                         retractDiscoveryResult(adapter, oldResult);
267                     }
268                     return newResult;
269                 });
270             }
271             /*
272              * this appends a post-process to any ongoing or completed discoveries with this device's address.
273              * If this discoveryFuture is ongoing then this post-process will run asynchronously upon the future's
274              * completion.
275              * If this discoveryFuture is already completed then this post-process will run in the current thread.
276              * We need to make sure that this is part of the future chain so that the call to 'thingRemoved'
277              * in the 'removeDiscoveries' method above can be sure that it is running after the 'thingDiscovered'
278              */
279             future = future.thenApply(result -> {
280                 publishDiscoveryResult(adapter, result);
281                 return result;
282             }).whenComplete((r, t) -> {
283                 if (t != null) {
284                     logger.warn("Error occured during discovery of {}", device.getAddress(), t);
285                 }
286             });
287
288             // now save this snapshot for later
289             discoveryFutures.put(adapter, new SnapshotFuture(snapshot, future));
290         }
291
292         private void publishDiscoveryResult(BluetoothAdapter adapter, DiscoveryResult result) {
293             Set<DiscoveryResult> results = new HashSet<>();
294             BiConsumer<BluetoothAdapter, DiscoveryResult> publisher = (a, r) -> {
295                 results.add(copyWithNewBridge(r, a));
296             };
297
298             publisher.accept(adapter, result);
299             for (BluetoothDiscoveryParticipant participant : participants) {
300                 participant.publishAdditionalResults(result, publisher);
301             }
302             results.forEach(BluetoothDiscoveryService.this::thingDiscovered);
303             discoveryResults.put(adapter, results);
304         }
305
306         /**
307          * Called when a new discovery is published and thus requires the old discovery to be removed first.
308          *
309          * @param adapter to get the results to be removed
310          * @param result unused
311          */
312         private void retractDiscoveryResult(BluetoothAdapter adapter, DiscoveryResult result) {
313             Set<DiscoveryResult> results = discoveryResults.remove(adapter);
314             if (results != null) {
315                 for (DiscoveryResult r : results) {
316                     thingRemoved(r.getThingUID());
317                 }
318             }
319         }
320
321         private CompletableFuture<DiscoveryResult> startDiscoveryProcess(BluetoothDeviceSnapshot device) {
322             return CompletableFuture.supplyAsync(new BluetoothDiscoveryProcess(device, participants, adapters),
323                     scheduler);
324         }
325     }
326
327     private static class SnapshotFuture {
328         public final BluetoothDeviceSnapshot snapshot;
329         public final CompletableFuture<DiscoveryResult> future;
330
331         public SnapshotFuture(BluetoothDeviceSnapshot snapshot, CompletableFuture<DiscoveryResult> future) {
332             this.snapshot = snapshot;
333             this.future = future;
334         }
335     }
336 }