]> git.basschouten.com Git - openhab-addons.git/blob
ca71350ca7a4800a8e0456cc579c09a805ca7ba9
[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.pilight.internal.discovery;
14
15 import static org.openhab.binding.pilight.internal.PilightBindingConstants.*;
16
17 import java.util.Date;
18 import java.util.HashMap;
19 import java.util.List;
20 import java.util.Map;
21 import java.util.Optional;
22 import java.util.Set;
23 import java.util.concurrent.CompletableFuture;
24 import java.util.concurrent.ScheduledFuture;
25 import java.util.concurrent.TimeUnit;
26
27 import org.eclipse.jdt.annotation.NonNullByDefault;
28 import org.eclipse.jdt.annotation.Nullable;
29 import org.openhab.binding.pilight.internal.PilightHandlerFactory;
30 import org.openhab.binding.pilight.internal.dto.Config;
31 import org.openhab.binding.pilight.internal.dto.DeviceType;
32 import org.openhab.binding.pilight.internal.dto.Status;
33 import org.openhab.binding.pilight.internal.handler.PilightBridgeHandler;
34 import org.openhab.core.config.discovery.AbstractDiscoveryService;
35 import org.openhab.core.config.discovery.DiscoveryResult;
36 import org.openhab.core.config.discovery.DiscoveryResultBuilder;
37 import org.openhab.core.config.discovery.DiscoveryService;
38 import org.openhab.core.thing.ThingTypeUID;
39 import org.openhab.core.thing.ThingUID;
40 import org.openhab.core.thing.binding.ThingHandler;
41 import org.openhab.core.thing.binding.ThingHandlerService;
42 import org.slf4j.Logger;
43 import org.slf4j.LoggerFactory;
44
45 /**
46  * The {@link PilightDeviceDiscoveryService} discovers pilight devices after a bridge thing has been created and
47  * connected to the pilight daemon. Things are discovered periodically in the background or after a manual trigger.
48  *
49  * @author Niklas Dörfler - Initial contribution
50  */
51 @NonNullByDefault
52 public class PilightDeviceDiscoveryService extends AbstractDiscoveryService implements ThingHandlerService {
53
54     private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = PilightHandlerFactory.SUPPORTED_THING_TYPES_UIDS;
55
56     private static final int AUTODISCOVERY_SEARCH_TIME_SEC = 10;
57     private static final int AUTODISCOVERY_BACKGROUND_SEARCH_INTERVAL_SEC = 60 * 10;
58
59     private final Logger logger = LoggerFactory.getLogger(PilightDeviceDiscoveryService.class);
60
61     private @Nullable PilightBridgeHandler pilightBridgeHandler;
62     private @Nullable ThingUID bridgeUID;
63
64     private @Nullable ScheduledFuture<?> backgroundDiscoveryJob;
65     private CompletableFuture<Config> configFuture;
66     private CompletableFuture<List<Status>> statusFuture;
67
68     public PilightDeviceDiscoveryService() {
69         super(SUPPORTED_THING_TYPES_UIDS, AUTODISCOVERY_SEARCH_TIME_SEC);
70         configFuture = new CompletableFuture<>();
71         statusFuture = new CompletableFuture<>();
72     }
73
74     @Override
75     protected void startScan() {
76         if (pilightBridgeHandler != null) {
77             configFuture = new CompletableFuture<>();
78             statusFuture = new CompletableFuture<>();
79
80             configFuture.thenAcceptBoth(statusFuture, (config, allStatus) -> {
81                 removeOlderResults(getTimestampOfLastScan(), bridgeUID);
82                 config.getDevices().forEach((deviceId, device) -> {
83                     if (this.pilightBridgeHandler != null) {
84                         final Optional<Status> status = allStatus.stream()
85                                 .filter(s -> s.getDevices().contains(deviceId)).findFirst();
86
87                         final ThingTypeUID thingTypeUID;
88                         final String typeString;
89
90                         if (status.isPresent()) {
91                             if (status.get().getType().equals(DeviceType.SWITCH)) {
92                                 thingTypeUID = new ThingTypeUID(BINDING_ID, THING_TYPE_SWITCH.getId());
93                                 typeString = "Switch";
94                             } else if (status.get().getType().equals(DeviceType.DIMMER)) {
95                                 thingTypeUID = new ThingTypeUID(BINDING_ID, THING_TYPE_DIMMER.getId());
96                                 typeString = "Dimmer";
97                             } else if (status.get().getType().equals(DeviceType.VALUE)) {
98                                 thingTypeUID = new ThingTypeUID(BINDING_ID, THING_TYPE_GENERIC.getId());
99                                 typeString = "Generic";
100                             } else if (status.get().getType().equals(DeviceType.CONTACT)) {
101                                 thingTypeUID = new ThingTypeUID(BINDING_ID, THING_TYPE_CONTACT.getId());
102                                 typeString = "Contact";
103                             } else {
104                                 thingTypeUID = new ThingTypeUID(BINDING_ID, THING_TYPE_GENERIC.getId());
105                                 typeString = "Generic";
106                             }
107                         } else {
108                             thingTypeUID = new ThingTypeUID(BINDING_ID, THING_TYPE_GENERIC.getId());
109                             typeString = "Generic";
110                         }
111
112                         final @Nullable PilightBridgeHandler pilightBridgeHandler = this.pilightBridgeHandler;
113                         if (pilightBridgeHandler != null) {
114                             final ThingUID thingUID = new ThingUID(thingTypeUID,
115                                     pilightBridgeHandler.getThing().getUID(), deviceId);
116
117                             final Map<String, Object> properties = new HashMap<>();
118                             properties.put(PROPERTY_NAME, deviceId);
119
120                             DiscoveryResult discoveryResult = DiscoveryResultBuilder.create(thingUID)
121                                     .withThingType(thingTypeUID).withProperties(properties).withBridge(bridgeUID)
122                                     .withRepresentationProperty(PROPERTY_NAME)
123                                     .withLabel("Pilight " + typeString + " Device '" + deviceId + "'").build();
124
125                             thingDiscovered(discoveryResult);
126                         }
127                     }
128                 });
129             });
130
131             final @Nullable PilightBridgeHandler pilightBridgeHandler = this.pilightBridgeHandler;
132             if (pilightBridgeHandler != null) {
133                 pilightBridgeHandler.refreshConfigAndStatus();
134             }
135         }
136     }
137
138     @Override
139     protected synchronized void stopScan() {
140         super.stopScan();
141         configFuture.cancel(true);
142         statusFuture.cancel(true);
143         if (bridgeUID != null) {
144             removeOlderResults(getTimestampOfLastScan(), bridgeUID);
145         }
146     }
147
148     @Override
149     protected void startBackgroundDiscovery() {
150         logger.debug("Start Pilight device background discovery");
151         final @Nullable ScheduledFuture<?> backgroundDiscoveryJob = this.backgroundDiscoveryJob;
152         if (backgroundDiscoveryJob == null || backgroundDiscoveryJob.isCancelled()) {
153             this.backgroundDiscoveryJob = scheduler.scheduleWithFixedDelay(this::startScan, 20,
154                     AUTODISCOVERY_BACKGROUND_SEARCH_INTERVAL_SEC, TimeUnit.SECONDS);
155         }
156     }
157
158     @Override
159     protected void stopBackgroundDiscovery() {
160         logger.debug("Stop Pilight device background discovery");
161         final @Nullable ScheduledFuture<?> backgroundDiscoveryJob = this.backgroundDiscoveryJob;
162         if (backgroundDiscoveryJob != null) {
163             backgroundDiscoveryJob.cancel(true);
164             this.backgroundDiscoveryJob = null;
165         }
166     }
167
168     @Override
169     public void setThingHandler(final ThingHandler handler) {
170         if (handler instanceof PilightBridgeHandler pilightBridgeHandler) {
171             this.pilightBridgeHandler = pilightBridgeHandler;
172             bridgeUID = pilightBridgeHandler.getThing().getUID();
173         }
174     }
175
176     @Override
177     public @Nullable ThingHandler getThingHandler() {
178         return pilightBridgeHandler;
179     }
180
181     @Override
182     public void activate() {
183         final @Nullable PilightBridgeHandler pilightBridgeHandler = this.pilightBridgeHandler;
184         boolean discoveryEnabled = false;
185         if (pilightBridgeHandler != null) {
186             removeOlderResults(new Date().getTime(), pilightBridgeHandler.getThing().getUID());
187             discoveryEnabled = pilightBridgeHandler.isBackgroundDiscoveryEnabled();
188             pilightBridgeHandler.registerDiscoveryListener(this);
189         }
190         super.activate(Map.of(DiscoveryService.CONFIG_PROPERTY_BACKGROUND_DISCOVERY, discoveryEnabled));
191     }
192
193     @Override
194     public void deactivate() {
195         if (bridgeUID != null) {
196             removeOlderResults(getTimestampOfLastScan(), bridgeUID);
197         }
198
199         final @Nullable PilightBridgeHandler pilightBridgeHandler = this.pilightBridgeHandler;
200         if (pilightBridgeHandler != null) {
201             pilightBridgeHandler.unregisterDiscoveryListener();
202         }
203
204         super.deactivate();
205     }
206
207     /**
208      * Method used to get pilight device config into the discovery class.
209      *
210      * @param config config to get
211      */
212     public void setConfig(Config config) {
213         configFuture.complete(config);
214     }
215
216     /**
217      * Method used to get pilight device status list into the discovery class.
218      *
219      * @param status list of status objects
220      */
221     public void setStatus(List<Status> status) {
222         statusFuture.complete(status);
223     }
224
225     @Override
226     public Set<ThingTypeUID> getSupportedThingTypes() {
227         return SUPPORTED_THING_TYPES_UIDS;
228     }
229 }