]> git.basschouten.com Git - openhab-addons.git/blob
07204fe088304a74a11fe8b010229bacf36e0806
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2020 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.mqtt.homeassistant.internal;
14
15 import java.lang.ref.WeakReference;
16 import java.util.HashSet;
17 import java.util.Set;
18 import java.util.concurrent.CompletableFuture;
19 import java.util.concurrent.ScheduledExecutorService;
20 import java.util.concurrent.ScheduledFuture;
21 import java.util.concurrent.TimeUnit;
22 import java.util.stream.Collectors;
23
24 import org.eclipse.jdt.annotation.NonNullByDefault;
25 import org.eclipse.jdt.annotation.Nullable;
26 import org.openhab.binding.mqtt.generic.AvailabilityTracker;
27 import org.openhab.binding.mqtt.generic.ChannelStateUpdateListener;
28 import org.openhab.binding.mqtt.generic.TransformationServiceProvider;
29 import org.openhab.binding.mqtt.generic.utils.FutureCollector;
30 import org.openhab.core.io.transport.mqtt.MqttBrokerConnection;
31 import org.openhab.core.io.transport.mqtt.MqttMessageSubscriber;
32 import org.openhab.core.thing.ThingUID;
33 import org.slf4j.Logger;
34 import org.slf4j.LoggerFactory;
35
36 import com.google.gson.Gson;
37
38 /**
39  * Responsible for subscribing to the HomeAssistant MQTT components wildcard topic, either
40  * in a time limited discovery mode or as a background discovery.
41  *
42  * @author David Graeff - Initial contribution
43  */
44 @NonNullByDefault
45 public class DiscoverComponents implements MqttMessageSubscriber {
46     private final Logger logger = LoggerFactory.getLogger(DiscoverComponents.class);
47     private final ThingUID thingUID;
48     private final ScheduledExecutorService scheduler;
49     private final ChannelStateUpdateListener updateListener;
50     private final AvailabilityTracker tracker;
51     private final TransformationServiceProvider transformationServiceProvider;
52
53     protected final CompletableFuture<@Nullable Void> discoverFinishedFuture = new CompletableFuture<>();
54     private final Gson gson;
55
56     private @Nullable ScheduledFuture<?> stopDiscoveryFuture;
57     private WeakReference<@Nullable MqttBrokerConnection> connectionRef = new WeakReference<>(null);
58     protected @NonNullByDefault({}) ComponentDiscovered discoveredListener;
59     private int discoverTime;
60     private Set<String> topics = new HashSet<>();
61
62     /**
63      * Implement this to get notified of new components
64      */
65     public static interface ComponentDiscovered {
66         void componentDiscovered(HaID homeAssistantTopicID, AbstractComponent<?> component);
67     }
68
69     /**
70      * Create a new discovery object.
71      *
72      * @param thingUID The Thing UID to perform the discovery for.
73      * @param scheduler A scheduler for timeouts
74      * @param channelStateUpdateListener Channel update listener. Usually the handler.
75      */
76     public DiscoverComponents(ThingUID thingUID, ScheduledExecutorService scheduler,
77             ChannelStateUpdateListener channelStateUpdateListener, AvailabilityTracker tracker, Gson gson,
78             TransformationServiceProvider transformationServiceProvider) {
79         this.thingUID = thingUID;
80         this.scheduler = scheduler;
81         this.updateListener = channelStateUpdateListener;
82         this.gson = gson;
83         this.tracker = tracker;
84         this.transformationServiceProvider = transformationServiceProvider;
85     }
86
87     @Override
88     public void processMessage(String topic, byte[] payload) {
89         if (!topic.endsWith("/config")) {
90             return;
91         }
92
93         HaID haID = new HaID(topic);
94         String config = new String(payload);
95
96         AbstractComponent<?> component = null;
97
98         if (config.length() > 0) {
99             component = CFactory.createComponent(thingUID, haID, config, updateListener, tracker, scheduler, gson,
100                     transformationServiceProvider);
101         }
102         if (component != null) {
103             component.setConfigSeen();
104
105             logger.trace("Found HomeAssistant thing {} component {}", haID.objectID, haID.component);
106             if (discoveredListener != null) {
107                 discoveredListener.componentDiscovered(haID, component);
108             }
109         } else {
110             logger.debug("Configuration of HomeAssistant thing {} invalid: {}", haID.objectID, config);
111         }
112     }
113
114     /**
115      * Start a components discovery.
116      *
117      * <p>
118      * We need to consider the case that the remote client is using node IDs
119      * and also the case that no node IDs are used.
120      * </p>
121      *
122      * @param connection A MQTT broker connection
123      * @param discoverTime The time in milliseconds for the discovery to run. Can be 0 to disable the
124      *            timeout.
125      *            You need to call {@link #stopDiscovery(MqttBrokerConnection)} at some
126      *            point in that case.
127      * @param topicDescription Contains the object-id (=device id) and potentially a node-id as well.
128      * @param componentsDiscoveredListener Listener for results
129      * @return A future that completes normally after the given time in milliseconds or exceptionally on any error.
130      *         Completes immediately if the timeout is disabled.
131      */
132     public CompletableFuture<@Nullable Void> startDiscovery(MqttBrokerConnection connection, int discoverTime,
133             Set<HaID> topicDescriptions, ComponentDiscovered componentsDiscoveredListener) {
134         this.topics = topicDescriptions.stream().map(id -> id.getTopic("config")).collect(Collectors.toSet());
135         this.discoverTime = discoverTime;
136         this.discoveredListener = componentsDiscoveredListener;
137         this.connectionRef = new WeakReference<>(connection);
138
139         // Subscribe to the wildcard topic and start receive MQTT retained topics
140         this.topics.parallelStream().map(t -> connection.subscribe(t, this)).collect(FutureCollector.allOf())
141                 .thenRun(this::subscribeSuccess).exceptionally(this::subscribeFail);
142
143         return discoverFinishedFuture;
144     }
145
146     private void subscribeSuccess() {
147         final MqttBrokerConnection connection = connectionRef.get();
148         // Set up a scheduled future that will stop the discovery after the given time
149         if (connection != null && discoverTime > 0) {
150             this.stopDiscoveryFuture = scheduler.schedule(() -> {
151                 this.stopDiscoveryFuture = null;
152                 this.topics.parallelStream().forEach(t -> connection.unsubscribe(t, this));
153                 this.discoveredListener = null;
154                 discoverFinishedFuture.complete(null);
155             }, discoverTime, TimeUnit.MILLISECONDS);
156         } else {
157             // No timeout -> complete immediately
158             discoverFinishedFuture.complete(null);
159         }
160     }
161
162     private @Nullable Void subscribeFail(Throwable e) {
163         final ScheduledFuture<?> scheduledFuture = this.stopDiscoveryFuture;
164         if (scheduledFuture != null) { // Cancel timeout
165             scheduledFuture.cancel(false);
166             this.stopDiscoveryFuture = null;
167         }
168         this.discoveredListener = null;
169         final MqttBrokerConnection connection = connectionRef.get();
170         if (connection != null) {
171             this.topics.parallelStream().forEach(t -> connection.unsubscribe(t, this));
172             connectionRef.clear();
173         }
174         discoverFinishedFuture.completeExceptionally(e);
175         return null;
176     }
177
178     /**
179      * Stops an ongoing discovery or do nothing if no discovery is running.
180      *
181      * @param connection A MQTT broker connection
182      */
183     public void stopDiscovery() {
184         subscribeFail(new Throwable("Stopped"));
185     }
186 }