2 * Copyright (c) 2010-2020 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.mqtt.homeassistant.internal;
15 import java.lang.ref.WeakReference;
16 import java.util.HashSet;
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;
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;
36 import com.google.gson.Gson;
39 * Responsible for subscribing to the HomeAssistant MQTT components wildcard topic, either
40 * in a time limited discovery mode or as a background discovery.
42 * @author David Graeff - Initial contribution
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;
53 protected final CompletableFuture<@Nullable Void> discoverFinishedFuture = new CompletableFuture<>();
54 private final Gson gson;
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<>();
63 * Implement this to get notified of new components
65 public static interface ComponentDiscovered {
66 void componentDiscovered(HaID homeAssistantTopicID, AbstractComponent<?> component);
70 * Create a new discovery object.
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.
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;
83 this.tracker = tracker;
84 this.transformationServiceProvider = transformationServiceProvider;
88 public void processMessage(String topic, byte[] payload) {
89 if (!topic.endsWith("/config")) {
93 HaID haID = new HaID(topic);
94 String config = new String(payload);
96 AbstractComponent<?> component = null;
98 if (config.length() > 0) {
99 component = CFactory.createComponent(thingUID, haID, config, updateListener, tracker, gson,
100 transformationServiceProvider);
102 if (component != null) {
103 component.setConfigSeen();
105 logger.trace("Found HomeAssistant thing {} component {}", haID.objectID, haID.component);
106 if (discoveredListener != null) {
107 discoveredListener.componentDiscovered(haID, component);
110 logger.debug("Configuration of HomeAssistant thing {} invalid: {}", haID.objectID, config);
115 * Start a components discovery.
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.
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
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.
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);
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);
143 return discoverFinishedFuture;
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);
157 // No timeout -> complete immediately
158 discoverFinishedFuture.complete(null);
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;
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();
174 discoverFinishedFuture.completeExceptionally(e);
179 * Stops an ongoing discovery or do nothing if no discovery is running.
181 * @param connection A MQTT broker connection
183 public void stopDiscovery() {
184 subscribeFail(new Throwable("Stopped"));