2 * Copyright (c) 2010-2024 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.utils.FutureCollector;
29 import org.openhab.binding.mqtt.homeassistant.internal.component.AbstractComponent;
30 import org.openhab.binding.mqtt.homeassistant.internal.component.ComponentFactory;
31 import org.openhab.binding.mqtt.homeassistant.internal.exception.ConfigurationException;
32 import org.openhab.binding.mqtt.homeassistant.internal.exception.UnsupportedComponentException;
33 import org.openhab.core.io.transport.mqtt.MqttBrokerConnection;
34 import org.openhab.core.io.transport.mqtt.MqttMessageSubscriber;
35 import org.openhab.core.thing.ThingUID;
36 import org.slf4j.Logger;
37 import org.slf4j.LoggerFactory;
39 import com.google.gson.Gson;
42 * Responsible for subscribing to the HomeAssistant MQTT components wildcard topic, either
43 * in a time limited discovery mode or as a background discovery.
45 * @author David Graeff - Initial contribution
48 public class DiscoverComponents implements MqttMessageSubscriber {
49 private final Logger logger = LoggerFactory.getLogger(DiscoverComponents.class);
50 private final ThingUID thingUID;
51 private final ScheduledExecutorService scheduler;
52 private final ChannelStateUpdateListener updateListener;
53 private final AvailabilityTracker tracker;
54 private final boolean newStyleChannels;
56 protected final CompletableFuture<@Nullable Void> discoverFinishedFuture = new CompletableFuture<>();
57 private final Gson gson;
59 private @Nullable ScheduledFuture<?> stopDiscoveryFuture;
60 private WeakReference<@Nullable MqttBrokerConnection> connectionRef = new WeakReference<>(null);
61 protected @Nullable ComponentDiscovered discoveredListener;
62 private int discoverTime;
63 private Set<String> topics = new HashSet<>();
66 * Implement this to get notified of new components
68 public static interface ComponentDiscovered {
69 void componentDiscovered(HaID homeAssistantTopicID, AbstractComponent<?> component);
73 * Create a new discovery object.
75 * @param thingUID The Thing UID to perform the discovery for.
76 * @param scheduler A scheduler for timeouts
77 * @param channelStateUpdateListener Channel update listener. Usually the handler.
79 public DiscoverComponents(ThingUID thingUID, ScheduledExecutorService scheduler,
80 ChannelStateUpdateListener channelStateUpdateListener, AvailabilityTracker tracker, Gson gson,
81 boolean newStyleChannels) {
82 this.thingUID = thingUID;
83 this.scheduler = scheduler;
84 this.updateListener = channelStateUpdateListener;
86 this.tracker = tracker;
87 this.newStyleChannels = newStyleChannels;
91 public void processMessage(String topic, byte[] payload) {
92 if (!topic.endsWith("/config")) {
96 HaID haID = new HaID(topic);
97 String config = new String(payload);
98 AbstractComponent<?> component = null;
100 if (config.length() > 0) {
102 component = ComponentFactory.createComponent(thingUID, haID, config, updateListener, tracker, scheduler,
103 gson, newStyleChannels);
104 component.setConfigSeen();
106 logger.trace("Found HomeAssistant component {}", haID);
108 if (discoveredListener != null) {
109 discoveredListener.componentDiscovered(haID, component);
111 } catch (UnsupportedComponentException e) {
112 logger.warn("HomeAssistant discover error: thing {} component type is unsupported: {}", haID.objectID,
114 } catch (ConfigurationException e) {
115 logger.warn("HomeAssistant discover error: invalid configuration of thing {} component {}: {}",
116 haID.objectID, haID.component, e.getMessage());
117 } catch (Exception e) {
118 logger.warn("HomeAssistant discover error: {}", e.getMessage());
121 logger.warn("Configuration of HomeAssistant thing {} is empty", haID.objectID);
126 * Start a components discovery.
129 * We need to consider the case that the remote client is using node IDs
130 * and also the case that no node IDs are used.
133 * @param connection A MQTT broker connection
134 * @param discoverTime The time in milliseconds for the discovery to run. Can be 0 to disable the
136 * You need to call {@link #stopDiscovery()} at some
137 * point in that case.
138 * @param topicDescriptions Contains the object-id (=device id) and potentially a node-id as well.
139 * @param componentsDiscoveredListener Listener for results
140 * @return A future that completes normally after the given time in milliseconds or exceptionally on any error.
141 * Completes immediately if the timeout is disabled.
143 public CompletableFuture<@Nullable Void> startDiscovery(MqttBrokerConnection connection, int discoverTime,
144 Set<HaID> topicDescriptions, ComponentDiscovered componentsDiscoveredListener) {
145 this.topics = topicDescriptions.stream().map(id -> id.getTopic("config")).collect(Collectors.toSet());
146 this.discoverTime = discoverTime;
147 this.discoveredListener = componentsDiscoveredListener;
148 this.connectionRef = new WeakReference<>(connection);
150 // Subscribe to the wildcard topic and start receive MQTT retained topics
151 this.topics.stream().map(t -> connection.subscribe(t, this)).collect(FutureCollector.allOf())
152 .thenRun(this::subscribeSuccess).exceptionally(this::subscribeFail);
154 return discoverFinishedFuture;
157 private void subscribeSuccess() {
158 final MqttBrokerConnection connection = connectionRef.get();
159 // Set up a scheduled future that will stop the discovery after the given time
160 if (connection != null && discoverTime > 0) {
161 this.stopDiscoveryFuture = scheduler.schedule(() -> {
162 this.stopDiscoveryFuture = null;
163 this.topics.stream().forEach(t -> connection.unsubscribe(t, this));
164 this.discoveredListener = null;
165 discoverFinishedFuture.complete(null);
166 }, discoverTime, TimeUnit.MILLISECONDS);
168 // No timeout -> complete immediately
169 discoverFinishedFuture.complete(null);
173 private @Nullable Void subscribeFail(Throwable e) {
174 final ScheduledFuture<?> scheduledFuture = this.stopDiscoveryFuture;
175 if (scheduledFuture != null) { // Cancel timeout
176 scheduledFuture.cancel(false);
177 this.stopDiscoveryFuture = null;
179 this.discoveredListener = null;
180 final MqttBrokerConnection connection = connectionRef.get();
181 if (connection != null) {
182 this.topics.stream().forEach(t -> connection.unsubscribe(t, this));
183 connectionRef.clear();
185 discoverFinishedFuture.completeExceptionally(e);
190 * Stops an ongoing discovery or do nothing if no discovery is running.
192 public void stopDiscovery() {
193 subscribeFail(new Throwable("Stopped"));