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.mqtt.handler;
15 import java.util.Collection;
16 import java.util.HashMap;
19 import java.util.concurrent.CompletableFuture;
20 import java.util.concurrent.TimeoutException;
22 import org.eclipse.jdt.annotation.NonNullByDefault;
23 import org.eclipse.jdt.annotation.Nullable;
24 import org.openhab.binding.mqtt.discovery.MQTTTopicDiscoveryParticipant;
25 import org.openhab.binding.mqtt.discovery.TopicSubscribe;
26 import org.openhab.binding.mqtt.internal.action.MQTTActions;
27 import org.openhab.core.io.transport.mqtt.MqttBrokerConnection;
28 import org.openhab.core.io.transport.mqtt.MqttConnectionObserver;
29 import org.openhab.core.io.transport.mqtt.MqttConnectionState;
30 import org.openhab.core.thing.Bridge;
31 import org.openhab.core.thing.Channel;
32 import org.openhab.core.thing.ChannelUID;
33 import org.openhab.core.thing.ThingStatus;
34 import org.openhab.core.thing.ThingStatusDetail;
35 import org.openhab.core.thing.binding.BaseBridgeHandler;
36 import org.openhab.core.thing.binding.ThingHandlerService;
37 import org.openhab.core.types.Command;
38 import org.slf4j.Logger;
39 import org.slf4j.LoggerFactory;
42 * This base implementation handles connection changes of the {@link MqttBrokerConnection}
43 * and puts the Thing on or offline. It also provides a basic dispose() implementation.
45 * @author David Graeff - Initial contribution
48 public abstract class AbstractBrokerHandler extends BaseBridgeHandler implements MqttConnectionObserver {
49 public static final int TIMEOUT_DEFAULT = 1200; /* timeout in milliseconds */
50 private final Logger logger = LoggerFactory.getLogger(AbstractBrokerHandler.class);
52 final Map<ChannelUID, PublishTriggerChannel> channelStateByChannelUID = new HashMap<>();
53 private final Map<String, @Nullable Map<MQTTTopicDiscoveryParticipant, @Nullable TopicSubscribe>> discoveryTopics = new HashMap<>();
55 protected @Nullable MqttBrokerConnection connection;
56 protected CompletableFuture<MqttBrokerConnection> connectionFuture = new CompletableFuture<>();
58 public AbstractBrokerHandler(Bridge thing) {
63 public Collection<Class<? extends ThingHandlerService>> getServices() {
64 return Set.of(MQTTActions.class);
68 * Returns the underlying {@link MqttBrokerConnection} either immediately or after {@link #initialize()} has
71 public CompletableFuture<MqttBrokerConnection> getConnectionAsync() {
72 return connectionFuture;
76 * Returns the underlying {@link MqttBrokerConnection}.
78 public @Nullable MqttBrokerConnection getConnection() {
83 * Does nothing in the base implementation.
86 public void handleCommand(ChannelUID channelUID, Command command) {
87 // No commands to handle
91 * Registers a connection status listener and attempts a connection if there is none so far.
94 public void initialize() {
95 final MqttBrokerConnection connection = this.connection;
96 if (connection == null) {
97 logger.warn("Trying to initialize {} but connection is null. This is most likely a bug.", thing.getUID());
100 for (Channel channel : thing.getChannels()) {
101 final PublishTriggerChannelConfig channelConfig = channel.getConfiguration()
102 .as(PublishTriggerChannelConfig.class);
103 PublishTriggerChannel c = new PublishTriggerChannel(channelConfig, channel.getUID(), connection, this);
104 channelStateByChannelUID.put(channel.getUID(), c);
107 connection.addConnectionObserver(this);
109 connection.start().exceptionally(e -> {
110 connectionStateChanged(MqttConnectionState.DISCONNECTED, e);
114 connectionStateChanged(MqttConnectionState.DISCONNECTED, new TimeoutException("Timeout"));
117 connectionFuture.complete(connection);
119 discoveryTopics.forEach((topic, listenerMap) -> {
120 listenerMap.replaceAll((listener, oldTopicSubscribe) -> {
121 if (oldTopicSubscribe.isStarted()) {
122 oldTopicSubscribe.stop();
125 TopicSubscribe topicSubscribe = new TopicSubscribe(connection, topic, listener, thing.getUID());
126 if (discoveryEnabled()) {
127 topicSubscribe.start().handle((result, ex) -> {
129 logger.warn("Failed to subscribe {} to discovery topic {} on broker {}", listener, topic,
132 logger.trace("Subscribed {} to discovery topic {} on broker {}", listener, topic,
138 return topicSubscribe;
144 public void connectionStateChanged(MqttConnectionState state, @Nullable Throwable error) {
145 if (state == MqttConnectionState.CONNECTED) {
146 updateStatus(ThingStatus.ONLINE);
147 channelStateByChannelUID.values().forEach(PublishTriggerChannel::start);
149 channelStateByChannelUID.values().forEach(PublishTriggerChannel::stop);
151 updateStatus(ThingStatus.OFFLINE);
153 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, error.getMessage());
159 protected void triggerChannel(ChannelUID channelUID, String event) {
160 super.triggerChannel(channelUID, event);
164 * Removes listeners to the {@link MqttBrokerConnection}.
167 public void dispose() {
168 channelStateByChannelUID.values().forEach(PublishTriggerChannel::stop);
169 channelStateByChannelUID.clear();
171 // keep topics, but stop subscriptions
172 discoveryTopics.forEach((topic, listenerMap) -> {
173 listenerMap.forEach((listener, topicSubscribe) -> {
174 topicSubscribe.stop();
178 if (connection != null) {
179 connection.removeConnectionObserver(this);
181 logger.warn("Trying to dispose handler {} but connection is already null. Most likely this is a bug.",
184 this.connection = null;
185 connectionFuture = new CompletableFuture<>();
190 * register a discovery listener to a specified topic on this broker (used by the handler factory)
192 * @param listener the discovery participant that wishes to be notified about this topic
193 * @param topic the topic (wildcards supported)
195 public final void registerDiscoveryListener(MQTTTopicDiscoveryParticipant listener, String topic) {
196 Map<MQTTTopicDiscoveryParticipant, @Nullable TopicSubscribe> topicListeners = discoveryTopics
197 .computeIfAbsent(topic, t -> new HashMap<>());
198 topicListeners.compute(listener, (k, v) -> {
200 logger.warn("Duplicate subscription for {} to discovery topic {} on broker {}. Check discovery logic!",
201 listener, topic, thing.getUID());
205 TopicSubscribe topicSubscribe = new TopicSubscribe(connection, topic, listener, thing.getUID());
206 if (discoveryEnabled()) {
207 topicSubscribe.start().handle((result, ex) -> {
209 logger.warn("Failed to subscribe {} to discovery topic {} on broker {}", listener, topic,
212 logger.trace("Subscribed {} to discovery topic {} on broker {}", listener, topic,
218 return topicSubscribe;
223 * unregisters a discovery listener from a specified topic on this broker (used by the handler factory)
225 * @param listener the discovery participant that wishes no notifications about this topic
226 * @param topic the topic (as specified during registration)
228 public final void unregisterDiscoveryListener(MQTTTopicDiscoveryParticipant listener, String topic) {
229 discoveryTopics.compute(topic, (k, v) -> {
232 "Tried to unsubscribe {} from discovery topic {} on broker {} but topic not registered at all. Check discovery logic!",
233 listener, topic, thing.getUID());
236 v.compute(listener, (l, w) -> {
239 "Tried to unsubscribe {} from discovery topic {} on broker {} but topic not registered for listener. Check discovery logic!",
240 listener, topic, thing.getUID());
243 logger.trace("Unsubscribed {} from discovery topic {} on broker {}", listener, topic,
248 return v.isEmpty() ? null : v;
253 * check whether discovery is disabled on this broker
255 * @return true if discovery disabled
257 public abstract boolean discoveryEnabled();