2 * Copyright (c) 2010-2023 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.velux.internal.discovery;
15 import static org.openhab.binding.velux.internal.VeluxBindingConstants.*;
17 import java.util.HashSet;
19 import java.util.concurrent.ScheduledFuture;
20 import java.util.concurrent.TimeUnit;
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;
48 * The {@link VeluxDiscoveryService} is responsible for discovering actuators and scenes on the current Velux Bridge.
50 * @author Guenther Schreiner - Initial contribution.
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);
59 private static final int DISCOVER_TIMEOUT_SECONDS = 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<>();
67 private ScheduledFuture<?> backgroundTask = null;
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);
82 * Initializes the {@link VeluxDiscoveryService} without any further information.
84 public VeluxDiscoveryService() {
85 super(VeluxBindingConstants.DISCOVERABLE_THINGS, DISCOVER_TIMEOUT_SECONDS);
86 logger.trace("VeluxDiscoveryService(without Bridge) just initialized.");
90 protected void setLocaleProvider(final LocaleProvider givenLocaleProvider) {
91 logger.trace("setLocaleProvider(): provided locale={}.", givenLocaleProvider);
92 localeProvider = givenLocaleProvider;
97 protected void setTranslationProvider(TranslationProvider givenI18nProvider) {
98 logger.trace("setTranslationProvider(): provided translation={}.", givenI18nProvider);
99 i18nProvider = givenI18nProvider;
100 updateLocalization();
106 * Initializes the {@link VeluxDiscoveryService} with a reference to the well-prepared environment with a
107 * {@link VeluxBridgeHandler}.
109 * @param localizationHandler Initialized localization handler.
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;
120 * Initializes the {@link VeluxDiscoveryService} with a reference to the well-prepared environment with a
121 * {@link VeluxBridgeHandler}.
123 * @param locationProvider Provider for a location.
124 * @param localeProvider Provider for a locale.
125 * @param i18nProvider Provider for the internationalization.
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);
134 public void deactivate() {
135 logger.trace("deactivate() called.");
140 protected synchronized void startScan() {
141 logger.trace("startScan() called.");
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);
153 scheduler.execute(() -> {
157 if (bridgeHandlers.isEmpty()) {
158 logger.debug("startScan(): VeluxDiscoveryService cannot proceed due to missing Velux bridge(s).");
160 logger.debug("startScan(): Starting Velux discovery scan for scenes and actuators.");
164 logger.trace("startScan() done.");
168 public synchronized void stopScan() {
169 logger.trace("stopScan() called.");
171 logger.trace("stopScan() done.");
176 logger.trace("run() called.");
180 * Discover the gateway-defined scenes.
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);
191 String label = sceneName.replaceAll("\\P{Alnum}", "_");
192 logger.trace("discoverScenes(): using label {}.", label);
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);
204 logger.trace("discoverScenes() finished.");
208 * Discover the gateway-defined products/actuators.
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);
220 if (serialNumber.equals(VeluxProductSerialNo.UNKNOWN)) {
221 identifier = actuatorName;
223 identifier = serialNumber;
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()) {
232 logger.trace("discoverProducts(): creating window.");
233 thingTypeUID = THING_TYPE_VELUX_WINDOW;
238 logger.trace("discoverProducts(): creating rollershutter.");
239 thingTypeUID = THING_TYPE_VELUX_ROLLERSHUTTER;
243 logger.trace("discoverProducts(): creating actuator.");
244 thingTypeUID = THING_TYPE_VELUX_ACTUATOR;
246 ThingUID thingUID = new ThingUID(thingTypeUID, bridgeUID, label);
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);
258 logger.trace("discoverProducts() finished.");
262 * Add a {@link VeluxBridgeHandler} to the {@link VeluxDiscoveryService}
264 * @param bridge Velux bridge handler.
265 * @return true if the bridge was added, or false if it was already present
267 public boolean addBridge(VeluxBridgeHandler bridge) {
268 if (!bridgeHandlers.contains(bridge)) {
269 logger.trace("VeluxDiscoveryService(): registering bridge {} for discovery.", bridge);
270 bridgeHandlers.add(bridge);
273 logger.trace("VeluxDiscoveryService(): bridge {} already registered for discovery.", bridge);
278 * Remove a {@link VeluxBridgeHandler} from the {@link VeluxDiscoveryService}
280 * @param bridge Velux bridge handler.
281 * @return true if the bridge was removed, or false if it was not present
283 public boolean removeBridge(VeluxBridgeHandler bridge) {
284 return bridgeHandlers.remove(bridge);
288 * Check if the {@link VeluxDiscoveryService} list of {@link VeluxBridgeHandler} is empty
290 * @return true if empty
292 public boolean isEmpty() {
293 return bridgeHandlers.isEmpty();
297 * Discover any bridges on the network that are not yet instantiated.
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);
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);
323 protected void stopBackgroundDiscovery() {
324 logger.trace("stopBackgroundDiscovery() called.");
325 ScheduledFuture<?> task = this.backgroundTask;