]> git.basschouten.com Git - openhab-addons.git/blob
e467a507b45fd8bfe99c4fbef1ac10e5d477502b
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2024 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.bluez.internal;
14
15 import java.util.concurrent.CompletableFuture;
16 import java.util.concurrent.ScheduledExecutorService;
17 import java.util.concurrent.TimeUnit;
18 import java.util.concurrent.atomic.AtomicInteger;
19
20 import org.eclipse.jdt.annotation.NonNullByDefault;
21 import org.eclipse.jdt.annotation.Nullable;
22 import org.freedesktop.dbus.exceptions.DBusException;
23 import org.openhab.binding.bluetooth.util.RetryException;
24 import org.openhab.binding.bluetooth.util.RetryFuture;
25 import org.openhab.core.common.ThreadPoolManager;
26 import org.osgi.service.component.annotations.Activate;
27 import org.osgi.service.component.annotations.Component;
28 import org.osgi.service.component.annotations.Deactivate;
29 import org.slf4j.Logger;
30 import org.slf4j.LoggerFactory;
31
32 import com.github.hypfvieh.bluetooth.DeviceManager;
33
34 /**
35  * This service handles the lifecycle of the {@link DeviceManager} singleton instance.
36  * In addition, this class is responsible for managing the BlueZPropertiesChangedHandler instance
37  * used by the binding for listening and dispatching dbus events from the DeviceManager.
38  *
39  * Creation of the DeviceManagerWrapper is asynchronous and thus attempts to retrieve the
40  * DeviceManagerWrapper through 'getDeviceManager' may initially fail.
41  *
42  * @author Connor Petty - Initial Contribution
43  *
44  */
45 @NonNullByDefault
46 @Component(service = DeviceManagerFactory.class)
47 public class DeviceManagerFactory {
48
49     private final Logger logger = LoggerFactory.getLogger(DeviceManagerFactory.class);
50     private final ScheduledExecutorService scheduler = ThreadPoolManager.getScheduledPool("bluetooth");
51
52     private final BlueZPropertiesChangedHandler changeHandler = new BlueZPropertiesChangedHandler();
53
54     private @Nullable CompletableFuture<@Nullable DeviceManager> deviceManagerFuture;
55     private @Nullable CompletableFuture<DeviceManagerWrapper> deviceManagerWrapperFuture;
56
57     public BlueZPropertiesChangedHandler getPropertiesChangedHandler() {
58         return changeHandler;
59     }
60
61     public @Nullable DeviceManagerWrapper getDeviceManager() {
62         // we can cheat the null checker with casting here
63         var future = (CompletableFuture<@Nullable DeviceManagerWrapper>) deviceManagerWrapperFuture;
64         if (future != null) {
65             return future.getNow(null);
66         }
67         return null;
68     }
69
70     @Activate
71     public void initialize() {
72         logger.debug("initializing DeviceManagerFactory");
73
74         var stage1 = this.deviceManagerFuture = RetryFuture.callWithRetry(() -> {
75             try {
76                 // if this is the first call to the library, this call
77                 // should throw an exception (that we are catching)
78                 return DeviceManager.getInstance();
79                 // Experimental - seems reuse does not work
80             } catch (IllegalStateException e) {
81                 // Exception caused by first call to the library
82                 try {
83                     return DeviceManager.createInstance(false);
84                 } catch (DBusException ex) {
85                     // we might be on a system without DBus, such as macOS or Windows
86                     logger.debug("Failed to initialize DeviceManager: {}", ex.getMessage());
87                     return null;
88                 }
89             }
90         }, scheduler);
91
92         this.deviceManagerWrapperFuture = stage1.thenCompose(devManager -> {
93             // lambdas can't modify outside variables due to scoping, so instead we use an AtomicInteger.
94             AtomicInteger tryCount = new AtomicInteger();
95             return RetryFuture.callWithRetry(() -> {
96                 int count = tryCount.incrementAndGet();
97                 try {
98                     logger.debug("Registering property handler attempt: {}", count);
99                     if (devManager != null) {
100                         devManager.registerPropertyHandler(changeHandler);
101                         logger.debug("Successfully registered property handler");
102                     }
103                     return new DeviceManagerWrapper(devManager);
104                 } catch (DBusException e) {
105                     if (count < 3) {
106                         throw new RetryException(5, TimeUnit.SECONDS);
107                     } else {
108                         throw e;
109                     }
110                 }
111             }, scheduler);
112         }).whenComplete((devManagerWrapper, th) -> {
113             if (th != null) {
114                 if (th.getCause() instanceof DBusException) {
115                     // we might be on a system without DBus, such as macOS or Windows
116                     logger.debug("Failed to initialize DeviceManager: {}", th.getMessage());
117                 } else {
118                     logger.warn("Failed to initialize DeviceManager: {}", th.getMessage());
119                 }
120             }
121         });
122     }
123
124     @Deactivate
125     public void dispose() {
126         var stage1 = this.deviceManagerFuture;
127         if (stage1 != null) {
128             if (!stage1.cancel(true)) {
129                 // a failure to cancel means that the stage completed normally
130                 stage1.thenAccept(devManager -> {
131                     if (devManager != null) {
132                         devManager.closeConnection();
133                     }
134                 });
135             }
136         }
137         this.deviceManagerFuture = null;
138
139         var stage2 = this.deviceManagerWrapperFuture;
140         if (stage2 != null) {
141             stage2.cancel(true);
142         }
143         this.deviceManagerWrapperFuture = null;
144     }
145 }