]> git.basschouten.com Git - openhab-addons.git/blob
87e6843614beb0fa9865a42f136ef47a38a1e9f2
[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.velux.internal.discovery;
14
15 import static org.openhab.binding.velux.internal.VeluxBindingConstants.*;
16
17 import java.util.HashSet;
18 import java.util.Set;
19 import java.util.concurrent.ScheduledFuture;
20 import java.util.concurrent.TimeUnit;
21
22 import org.eclipse.jdt.annotation.NonNullByDefault;
23 import org.eclipse.jdt.annotation.Nullable;
24 import org.openhab.binding.velux.internal.VeluxBindingConstants;
25 import org.openhab.binding.velux.internal.VeluxBindingProperties;
26 import org.openhab.binding.velux.internal.config.VeluxBridgeConfiguration;
27 import org.openhab.binding.velux.internal.handler.VeluxBridgeHandler;
28 import org.openhab.binding.velux.internal.things.VeluxProduct;
29 import org.openhab.binding.velux.internal.things.VeluxProductSerialNo;
30 import org.openhab.binding.velux.internal.things.VeluxScene;
31 import org.openhab.binding.velux.internal.utils.Localization;
32 import org.openhab.binding.velux.internal.utils.ManifestInformation;
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.i18n.LocaleProvider;
38 import org.openhab.core.i18n.LocationProvider;
39 import org.openhab.core.i18n.TranslationProvider;
40 import org.openhab.core.thing.ThingTypeUID;
41 import org.openhab.core.thing.ThingUID;
42 import org.osgi.service.component.annotations.Component;
43 import org.osgi.service.component.annotations.Reference;
44 import org.slf4j.Logger;
45 import org.slf4j.LoggerFactory;
46
47 /**
48  * The {@link VeluxDiscoveryService} is responsible for discovering actuators and scenes on the current Velux Bridge.
49  *
50  * @author Guenther Schreiner - Initial contribution.
51  */
52 @NonNullByDefault
53 @Component(service = DiscoveryService.class, configurationPid = "discovery.velux")
54 public class VeluxDiscoveryService extends AbstractDiscoveryService implements Runnable {
55     private final Logger logger = LoggerFactory.getLogger(VeluxDiscoveryService.class);
56
57     // Class internal
58
59     private static final int DISCOVER_TIMEOUT_SECONDS = 60;
60
61     private @NonNullByDefault({}) LocaleProvider localeProvider;
62     private @NonNullByDefault({}) TranslationProvider i18nProvider;
63     private Localization localization = Localization.UNKNOWN;
64     private final Set<VeluxBridgeHandler> bridgeHandlers = new HashSet<>();
65
66     @Nullable
67     private ScheduledFuture<?> backgroundTask = null;
68
69     // Private
70
71     private void updateLocalization() {
72         if (Localization.UNKNOWN.equals(localization) && (localeProvider != null) && (i18nProvider != null)) {
73             logger.trace("updateLocalization(): creating Localization based on locale={},translation={}).",
74                     localeProvider, i18nProvider);
75             localization = new Localization(localeProvider, i18nProvider);
76         }
77     }
78
79     /**
80      * Constructor
81      * <P>
82      * Initializes the {@link VeluxDiscoveryService} without any further information.
83      */
84     public VeluxDiscoveryService() {
85         super(VeluxBindingConstants.DISCOVERABLE_THINGS, DISCOVER_TIMEOUT_SECONDS);
86         logger.trace("VeluxDiscoveryService(without Bridge) just initialized.");
87     }
88
89     @Reference
90     protected void setLocaleProvider(final LocaleProvider givenLocaleProvider) {
91         logger.trace("setLocaleProvider(): provided locale={}.", givenLocaleProvider);
92         localeProvider = givenLocaleProvider;
93         updateLocalization();
94     }
95
96     @Reference
97     protected void setTranslationProvider(TranslationProvider givenI18nProvider) {
98         logger.trace("setTranslationProvider(): provided translation={}.", givenI18nProvider);
99         i18nProvider = givenI18nProvider;
100         updateLocalization();
101     }
102
103     /**
104      * Constructor
105      * <P>
106      * Initializes the {@link VeluxDiscoveryService} with a reference to the well-prepared environment with a
107      * {@link VeluxBridgeHandler}.
108      *
109      * @param localizationHandler Initialized localization handler.
110      */
111     public VeluxDiscoveryService(Localization localizationHandler) {
112         super(VeluxBindingConstants.DISCOVERABLE_THINGS, DISCOVER_TIMEOUT_SECONDS);
113         logger.trace("VeluxDiscoveryService(locale={},i18n={}) just initialized.", localeProvider, i18nProvider);
114         localization = localizationHandler;
115     }
116
117     /**
118      * Constructor
119      * <P>
120      * Initializes the {@link VeluxDiscoveryService} with a reference to the well-prepared environment with a
121      * {@link VeluxBridgeHandler}.
122      *
123      * @param locationProvider Provider for a location.
124      * @param localeProvider Provider for a locale.
125      * @param i18nProvider Provider for the internationalization.
126      */
127     public VeluxDiscoveryService(LocationProvider locationProvider, LocaleProvider localeProvider,
128             TranslationProvider i18nProvider) {
129         this(new Localization(localeProvider, i18nProvider));
130         logger.trace("VeluxDiscoveryService(locale={},i18n={}) finished.", localeProvider, i18nProvider);
131     }
132
133     @Override
134     public void deactivate() {
135         logger.trace("deactivate() called.");
136         super.deactivate();
137     }
138
139     @Override
140     protected synchronized void startScan() {
141         logger.trace("startScan() called.");
142
143         logger.debug("startScan(): creating a thing of type binding.");
144         ThingUID thingUID = new ThingUID(THING_TYPE_BINDING, "org_openhab_binding_velux");
145         DiscoveryResult discoveryResult = DiscoveryResultBuilder.create(thingUID)
146                 .withProperty(VeluxBindingProperties.PROPERTY_BINDING_BUNDLEVERSION,
147                         ManifestInformation.getBundleVersion())
148                 .withRepresentationProperty(VeluxBindingProperties.PROPERTY_BINDING_BUNDLEVERSION)
149                 .withLabel(localization.getText("discovery.velux.binding...label")).build();
150         logger.debug("startScan(): registering new thing {}.", discoveryResult);
151         thingDiscovered(discoveryResult);
152
153         scheduler.execute(() -> {
154             discoverBridges();
155         });
156
157         if (bridgeHandlers.isEmpty()) {
158             logger.debug("startScan(): VeluxDiscoveryService cannot proceed due to missing Velux bridge(s).");
159         } else {
160             logger.debug("startScan(): Starting Velux discovery scan for scenes and actuators.");
161             discoverScenes();
162             discoverProducts();
163         }
164         logger.trace("startScan() done.");
165     }
166
167     @Override
168     public synchronized void stopScan() {
169         logger.trace("stopScan() called.");
170         super.stopScan();
171         logger.trace("stopScan() done.");
172     }
173
174     @Override
175     public void run() {
176         logger.trace("run() called.");
177     }
178
179     /**
180      * Discover the gateway-defined scenes.
181      */
182     private void discoverScenes() {
183         logger.trace("discoverScenes() called.");
184         for (VeluxBridgeHandler bridgeHandlerX : bridgeHandlers) {
185             ThingUID bridgeUID = bridgeHandlerX.getThing().getUID();
186             logger.debug("discoverScenes(): discovering all scenes on bridge {}.", bridgeUID);
187             for (VeluxScene scene : bridgeHandlerX.existingScenes().values()) {
188                 String sceneName = scene.getName().toString();
189                 logger.trace("discoverScenes(): found scene {}.", sceneName);
190
191                 String label = sceneName.replaceAll("\\P{Alnum}", "_");
192                 logger.trace("discoverScenes(): using label {}.", label);
193
194                 ThingTypeUID thingTypeUID = THING_TYPE_VELUX_SCENE;
195                 ThingUID thingUID = new ThingUID(thingTypeUID, bridgeUID, label);
196                 DiscoveryResult discoveryResult = DiscoveryResultBuilder.create(thingUID).withThingType(thingTypeUID)
197                         .withProperty(VeluxBindingProperties.PROPERTY_SCENE_NAME, sceneName)
198                         .withRepresentationProperty(VeluxBindingProperties.PROPERTY_SCENE_NAME).withBridge(bridgeUID)
199                         .withLabel(label).build();
200                 logger.debug("discoverScenes(): registering new thing {}.", discoveryResult);
201                 thingDiscovered(discoveryResult);
202             }
203         }
204         logger.trace("discoverScenes() finished.");
205     }
206
207     /**
208      * Discover the gateway-defined products/actuators.
209      */
210     private void discoverProducts() {
211         logger.trace("discoverProducts() called.");
212         for (VeluxBridgeHandler bridgeHandlerX : bridgeHandlers) {
213             ThingUID bridgeUID = bridgeHandlerX.getThing().getUID();
214             logger.debug("discoverProducts(): discovering all actuators on bridge {}.", bridgeUID);
215             for (VeluxProduct product : bridgeHandlerX.existingProducts().values()) {
216                 String serialNumber = product.getSerialNumber();
217                 String actuatorName = product.getProductName().toString();
218                 logger.trace("discoverProducts() found actuator {} (name {}).", serialNumber, actuatorName);
219                 String identifier;
220                 if (serialNumber.equals(VeluxProductSerialNo.UNKNOWN)) {
221                     identifier = actuatorName;
222                 } else {
223                     identifier = serialNumber;
224                 }
225                 String label = actuatorName.replaceAll("\\P{Alnum}", "_");
226                 logger.trace("discoverProducts(): using label {}.", label);
227                 ThingTypeUID thingTypeUID;
228                 boolean isInverted = false;
229                 logger.trace("discoverProducts() dealing with {} (type {}).", product, product.getProductType());
230                 switch (product.getProductType()) {
231                     case SLIDER_WINDOW:
232                         logger.trace("discoverProducts(): creating window.");
233                         thingTypeUID = THING_TYPE_VELUX_WINDOW;
234                         isInverted = true;
235                         break;
236
237                     case SLIDER_SHUTTER:
238                         logger.trace("discoverProducts(): creating rollershutter.");
239                         thingTypeUID = THING_TYPE_VELUX_ROLLERSHUTTER;
240                         break;
241
242                     default:
243                         logger.trace("discoverProducts(): creating actuator.");
244                         thingTypeUID = THING_TYPE_VELUX_ACTUATOR;
245                 }
246                 ThingUID thingUID = new ThingUID(thingTypeUID, bridgeUID, label);
247
248                 DiscoveryResult discoveryResult = DiscoveryResultBuilder.create(thingUID).withThingType(thingTypeUID)
249                         .withProperty(VeluxBindingProperties.CONFIG_ACTUATOR_SERIALNUMBER, identifier)
250                         .withProperty(VeluxBindingProperties.PROPERTY_ACTUATOR_NAME, actuatorName)
251                         .withProperty(VeluxBindingProperties.PROPERTY_ACTUATOR_INVERTED, isInverted)
252                         .withRepresentationProperty(VeluxBindingProperties.CONFIG_ACTUATOR_SERIALNUMBER)
253                         .withBridge(bridgeUID).withLabel(actuatorName).build();
254                 logger.debug("discoverProducts(): registering new thing {}.", discoveryResult);
255                 thingDiscovered(discoveryResult);
256             }
257         }
258         logger.trace("discoverProducts() finished.");
259     }
260
261     /**
262      * Add a {@link VeluxBridgeHandler} to the {@link VeluxDiscoveryService}
263      *
264      * @param bridge Velux bridge handler.
265      * @return true if the bridge was added, or false if it was already present
266      */
267     public boolean addBridge(VeluxBridgeHandler bridge) {
268         if (!bridgeHandlers.contains(bridge)) {
269             logger.trace("VeluxDiscoveryService(): registering bridge {} for discovery.", bridge);
270             bridgeHandlers.add(bridge);
271             return true;
272         }
273         logger.trace("VeluxDiscoveryService(): bridge {} already registered for discovery.", bridge);
274         return false;
275     }
276
277     /**
278      * Remove a {@link VeluxBridgeHandler} from the {@link VeluxDiscoveryService}
279      *
280      * @param bridge Velux bridge handler.
281      * @return true if the bridge was removed, or false if it was not present
282      */
283     public boolean removeBridge(VeluxBridgeHandler bridge) {
284         return bridgeHandlers.remove(bridge);
285     }
286
287     /**
288      * Check if the {@link VeluxDiscoveryService} list of {@link VeluxBridgeHandler} is empty
289      *
290      * @return true if empty
291      */
292     public boolean isEmpty() {
293         return bridgeHandlers.isEmpty();
294     }
295
296     /**
297      * Discover any bridges on the network that are not yet instantiated.
298      */
299     private void discoverBridges() {
300         // discover the list of IP addresses of bridges on the network
301         Set<String> foundBridgeIpAddresses = VeluxBridgeFinder.discoverIpAddresses(scheduler);
302         // publish discovery results
303         for (String ipAddr : foundBridgeIpAddresses) {
304             ThingUID thingUID = new ThingUID(THING_TYPE_BRIDGE, ipAddr.replace(".", "_"));
305             DiscoveryResult result = DiscoveryResultBuilder.create(thingUID).withThingType(THING_TYPE_BRIDGE)
306                     .withProperty(VeluxBridgeConfiguration.BRIDGE_IPADDRESS, ipAddr)
307                     .withRepresentationProperty(VeluxBridgeConfiguration.BRIDGE_IPADDRESS)
308                     .withLabel(String.format("Velux Bridge (%s)", ipAddr)).build();
309             thingDiscovered(result);
310         }
311     }
312
313     @Override
314     protected void startBackgroundDiscovery() {
315         logger.trace("startBackgroundDiscovery() called.");
316         ScheduledFuture<?> task = this.backgroundTask;
317         if (task == null || task.isCancelled()) {
318             this.backgroundTask = scheduler.scheduleWithFixedDelay(this::startScan, 10, 600, TimeUnit.SECONDS);
319         }
320     }
321
322     @Override
323     protected void stopBackgroundDiscovery() {
324         logger.trace("stopBackgroundDiscovery() called.");
325         ScheduledFuture<?> task = this.backgroundTask;
326         if (task != null) {
327             task.cancel(true);
328         }
329     }
330 }