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.generic;
15 import java.util.HashSet;
17 import java.util.Optional;
19 import java.util.concurrent.CompletableFuture;
20 import java.util.concurrent.ConcurrentHashMap;
21 import java.util.concurrent.ExecutionException;
22 import java.util.concurrent.TimeUnit;
23 import java.util.concurrent.TimeoutException;
24 import java.util.concurrent.atomic.AtomicBoolean;
26 import org.eclipse.jdt.annotation.NonNullByDefault;
27 import org.eclipse.jdt.annotation.Nullable;
28 import org.openhab.binding.mqtt.generic.utils.FutureCollector;
29 import org.openhab.binding.mqtt.generic.values.OnOffValue;
30 import org.openhab.binding.mqtt.generic.values.Value;
31 import org.openhab.binding.mqtt.handler.AbstractBrokerHandler;
32 import org.openhab.core.io.transport.mqtt.MqttBrokerConnection;
33 import org.openhab.core.library.types.OnOffType;
34 import org.openhab.core.thing.Bridge;
35 import org.openhab.core.thing.ChannelGroupUID;
36 import org.openhab.core.thing.ChannelUID;
37 import org.openhab.core.thing.Thing;
38 import org.openhab.core.thing.ThingStatus;
39 import org.openhab.core.thing.ThingStatusDetail;
40 import org.openhab.core.thing.ThingStatusInfo;
41 import org.openhab.core.thing.binding.BaseThingHandler;
42 import org.openhab.core.types.Command;
43 import org.openhab.core.types.RefreshType;
44 import org.openhab.core.types.State;
45 import org.openhab.core.types.UnDefType;
46 import org.openhab.core.util.UIDUtils;
47 import org.slf4j.Logger;
48 import org.slf4j.LoggerFactory;
51 * Base class for MQTT thing handlers. If you are going to implement an MQTT convention, you probably
52 * want to inherit from here.
55 * This base class will make sure you get a working {@link MqttBrokerConnection}, you will be informed
56 * when to start your subscriptions ({@link #start(MqttBrokerConnection)}) and when to free your resources
57 * because of a lost connection ({@link AbstractMQTTThingHandler#stop()}).
60 * If you inherit from this base class, you must use {@link ChannelState} to (a) keep a cached channel value,
61 * (b) to link a MQTT topic value to a channel value ("MQTT state topic") and (c) to have a secondary MQTT topic
62 * where any changes to the {@link ChannelState} are send to ("MQTT command topic").
65 * You are expected to keep your channel data structure organized in a way, to resolve a {@link ChannelUID} to
66 * the corresponding {@link ChannelState} in {@link #getChannelState(ChannelUID)}.
69 * To inform the framework of changed values, received via MQTT, a {@link ChannelState} calls a listener callback.
70 * While setting up your {@link ChannelState} you would set the callback to your thing handler,
71 * because this base class implements {@link ChannelStateUpdateListener}.
73 * @author David Graeff - Initial contribution
76 public abstract class AbstractMQTTThingHandler extends BaseThingHandler
77 implements ChannelStateUpdateListener, AvailabilityTracker {
78 private final Logger logger = LoggerFactory.getLogger(AbstractMQTTThingHandler.class);
79 // Timeout for the entire tree parsing and subscription
80 private final int subscribeTimeout;
82 protected @Nullable MqttBrokerConnection connection;
84 private AtomicBoolean messageReceived = new AtomicBoolean(false);
85 private Map<String, @Nullable ChannelState> availabilityStates = new ConcurrentHashMap<>();
87 public AbstractMQTTThingHandler(Thing thing, int subscribeTimeout) {
89 this.subscribeTimeout = subscribeTimeout;
93 * Return the channel state for the given channelUID.
95 * @param channelUID The channelUID
96 * @return A channel state. May be null.
98 public abstract @Nullable ChannelState getChannelState(ChannelUID channelUID);
101 * Start the topic discovery and subscribe to all channel state topics on all {@link ChannelState}s.
102 * Put the thing ONLINE on success otherwise complete the returned future exceptionally.
104 * @param connection A started broker connection
105 * @return A future that completes normal on success and exceptionally on any errors.
107 protected CompletableFuture<@Nullable Void> start(MqttBrokerConnection connection) {
108 return availabilityStates.values().stream().map(cChannel -> {
109 final CompletableFuture<@Nullable Void> fut = cChannel == null ? CompletableFuture.completedFuture(null)
110 : cChannel.start(connection, scheduler, 0);
112 }).collect(FutureCollector.allOf());
116 * Called when the MQTT connection disappeared.
117 * You should clean up all resources that depend on a working connection.
119 protected void stop() {
120 clearAllAvailabilityTopics();
121 resetMessageReceived();
125 public void handleCommand(ChannelUID channelUID, Command command) {
126 if (connection == null) {
130 final @Nullable ChannelState data = getChannelState(channelUID);
133 logger.warn("Channel {} not supported!", channelUID);
137 if (command instanceof RefreshType) {
138 State state = data.getCache().getChannelState();
139 if (state instanceof UnDefType) {
140 logger.debug("Channel {} received REFRESH but no value cached, ignoring", channelUID);
142 updateState(channelUID, state);
147 if (data.isReadOnly()) {
148 logger.trace("Channel {} is a read-only channel, ignoring command {}", channelUID, command);
152 final CompletableFuture<Boolean> future = data.publishValue(command);
153 future.handle((v, ex) -> {
155 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, ex.getLocalizedMessage());
156 logger.debug("Failed publishing value {} to topic {}: {}", command, data.getCommandTopic(),
159 logger.debug("Successfully published value {} to topic {}", command, data.getCommandTopic());
166 public void bridgeStatusChanged(ThingStatusInfo bridgeStatusInfo) {
167 if (bridgeStatusInfo.getStatus() == ThingStatus.OFFLINE) {
168 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.BRIDGE_OFFLINE);
173 if (bridgeStatusInfo.getStatus() != ThingStatus.ONLINE) {
174 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR);
179 AbstractBrokerHandler h = getBridgeHandler();
181 resetMessageReceived();
182 logger.warn("Bridge handler not found!");
186 final MqttBrokerConnection connection;
188 connection = h.getConnectionAsync().get(500, TimeUnit.MILLISECONDS);
189 } catch (InterruptedException | ExecutionException | TimeoutException ignored) {
190 resetMessageReceived();
191 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.BRIDGE_UNINITIALIZED,
192 "Bridge handler has no valid broker connection!");
195 this.connection = connection;
197 // Start up (subscribe to MQTT topics). Limit with a timeout and catch exceptions.
198 // We do not set the thing to ONLINE here in the AbstractBase, that is the responsibility of a derived
201 start(connection).get(subscribeTimeout, TimeUnit.MILLISECONDS);
202 } catch (InterruptedException | ExecutionException | TimeoutException ignored) {
203 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
204 "Did not receive all required topics");
209 * Return the bride handler. The bridge is from the "MQTT" bundle.
211 public @Nullable AbstractBrokerHandler getBridgeHandler() {
212 Bridge bridge = getBridge();
213 if (bridge == null) {
216 return (AbstractBrokerHandler) bridge.getHandler();
220 * Return the bridge status.
222 public ThingStatusInfo getBridgeStatus() {
223 Bridge b = getBridge();
225 return b.getStatusInfo();
227 return new ThingStatusInfo(ThingStatus.OFFLINE, ThingStatusDetail.BRIDGE_OFFLINE, null);
232 public void initialize() {
233 bridgeStatusChanged(getBridgeStatus());
237 public void handleRemoval() {
239 super.handleRemoval();
243 public void dispose() {
246 unsubscribeAll().get(500, TimeUnit.MILLISECONDS);
247 } catch (InterruptedException | ExecutionException | TimeoutException e) {
248 logger.warn("unsubscription on disposal failed for {}: ", thing.getUID(), e);
255 * this method must unsubscribe all topics used by this thing handler
259 public abstract CompletableFuture<Void> unsubscribeAll();
262 public void updateChannelState(ChannelUID channelUID, State value) {
263 if (messageReceived.compareAndSet(false, true)) {
264 calculateThingStatus();
266 super.updateState(channelUID, value);
270 public void triggerChannel(ChannelUID channelUID, String event) {
271 if (messageReceived.compareAndSet(false, true)) {
272 calculateThingStatus();
274 super.triggerChannel(channelUID, event);
278 public void postChannelCommand(ChannelUID channelUID, Command command) {
279 postCommand(channelUID, command);
282 public @Nullable MqttBrokerConnection getConnection() {
287 * This is for tests only to inject a broker connection.
289 * @param connection MQTT Broker connection
291 public void setConnection(MqttBrokerConnection connection) {
292 this.connection = connection;
296 public void addAvailabilityTopic(String availability_topic, String payload_available,
297 String payload_not_available) {
298 addAvailabilityTopic(availability_topic, payload_available, payload_not_available, null, null);
302 public void addAvailabilityTopic(String availability_topic, String payload_available, String payload_not_available,
303 @Nullable String transformation_pattern,
304 @Nullable TransformationServiceProvider transformationServiceProvider) {
305 availabilityStates.computeIfAbsent(availability_topic, topic -> {
306 Value value = new OnOffValue(payload_available, payload_not_available);
307 ChannelGroupUID groupUID = new ChannelGroupUID(getThing().getUID(), "availability");
308 ChannelUID channelUID = new ChannelUID(groupUID, UIDUtils.encode(topic));
309 ChannelState state = new ChannelState(ChannelConfigBuilder.create().withStateTopic(topic).build(),
310 channelUID, value, new ChannelStateUpdateListener() {
312 public void updateChannelState(ChannelUID channelUID, State value) {
313 calculateThingStatus();
317 public void triggerChannel(ChannelUID channelUID, String eventPayload) {
321 public void postChannelCommand(ChannelUID channelUID, Command value) {
324 if (transformation_pattern != null && transformationServiceProvider != null) {
325 state.addTransformation(transformation_pattern, transformationServiceProvider);
327 MqttBrokerConnection connection = getConnection();
328 if (connection != null) {
329 state.start(connection, scheduler, 0);
337 public void removeAvailabilityTopic(String availabilityTopic) {
338 availabilityStates.computeIfPresent(availabilityTopic, (topic, state) -> {
339 if (connection != null && state != null) {
347 public void clearAllAvailabilityTopics() {
348 Set<String> topics = new HashSet<>(availabilityStates.keySet());
349 topics.forEach(this::removeAvailabilityTopic);
353 public void resetMessageReceived() {
354 if (messageReceived.compareAndSet(true, false)) {
355 calculateThingStatus();
359 protected void calculateThingStatus() {
360 final Optional<Boolean> availabilityTopicsSeen;
362 if (availabilityStates.isEmpty()) {
363 availabilityTopicsSeen = Optional.empty();
365 availabilityTopicsSeen = Optional.of(availabilityStates.values().stream().allMatch(
366 c -> c != null && OnOffType.ON.equals(c.getCache().getChannelState().as(OnOffType.class))));
368 updateThingStatus(messageReceived.get(), availabilityTopicsSeen);
371 protected abstract void updateThingStatus(boolean messageReceived, Optional<Boolean> availabilityTopicsSeen);