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.generic;
15 import java.util.HashSet;
16 import java.util.List;
18 import java.util.Optional;
20 import java.util.concurrent.CompletableFuture;
21 import java.util.concurrent.ConcurrentHashMap;
22 import java.util.concurrent.ExecutionException;
23 import java.util.concurrent.TimeUnit;
24 import java.util.concurrent.TimeoutException;
25 import java.util.concurrent.atomic.AtomicBoolean;
27 import org.eclipse.jdt.annotation.NonNullByDefault;
28 import org.eclipse.jdt.annotation.Nullable;
29 import org.openhab.binding.mqtt.generic.utils.FutureCollector;
30 import org.openhab.binding.mqtt.generic.values.OnOffValue;
31 import org.openhab.binding.mqtt.generic.values.Value;
32 import org.openhab.binding.mqtt.handler.AbstractBrokerHandler;
33 import org.openhab.core.io.transport.mqtt.MqttBrokerConnection;
34 import org.openhab.core.library.types.OnOffType;
35 import org.openhab.core.thing.Bridge;
36 import org.openhab.core.thing.ChannelGroupUID;
37 import org.openhab.core.thing.ChannelUID;
38 import org.openhab.core.thing.Thing;
39 import org.openhab.core.thing.ThingStatus;
40 import org.openhab.core.thing.ThingStatusDetail;
41 import org.openhab.core.thing.ThingStatusInfo;
42 import org.openhab.core.thing.binding.BaseThingHandler;
43 import org.openhab.core.types.Command;
44 import org.openhab.core.types.RefreshType;
45 import org.openhab.core.types.State;
46 import org.openhab.core.types.UnDefType;
47 import org.openhab.core.util.UIDUtils;
48 import org.slf4j.Logger;
49 import org.slf4j.LoggerFactory;
52 * Base class for MQTT thing handlers. If you are going to implement an MQTT convention, you probably
53 * want to inherit from here.
56 * This base class will make sure you get a working {@link MqttBrokerConnection}, you will be informed
57 * when to start your subscriptions ({@link #start(MqttBrokerConnection)}) and when to free your resources
58 * because of a lost connection ({@link AbstractMQTTThingHandler#stop()}).
61 * If you inherit from this base class, you must use {@link ChannelState} to (a) keep a cached channel value,
62 * (b) to link a MQTT topic value to a channel value ("MQTT state topic") and (c) to have a secondary MQTT topic
63 * where any changes to the {@link ChannelState} are send to ("MQTT command topic").
66 * You are expected to keep your channel data structure organized in a way, to resolve a {@link ChannelUID} to
67 * the corresponding {@link ChannelState} in {@link #getChannelState(ChannelUID)}.
70 * To inform the framework of changed values, received via MQTT, a {@link ChannelState} calls a listener callback.
71 * While setting up your {@link ChannelState} you would set the callback to your thing handler,
72 * because this base class implements {@link ChannelStateUpdateListener}.
74 * @author David Graeff - Initial contribution
77 public abstract class AbstractMQTTThingHandler extends BaseThingHandler
78 implements ChannelStateUpdateListener, AvailabilityTracker {
79 private final Logger logger = LoggerFactory.getLogger(AbstractMQTTThingHandler.class);
80 // Timeout for the entire tree parsing and subscription
81 private final int subscribeTimeout;
83 protected @Nullable MqttBrokerConnection connection;
85 private AtomicBoolean messageReceived = new AtomicBoolean(false);
86 private Map<String, @Nullable ChannelState> availabilityStates = new ConcurrentHashMap<>();
87 private AvailabilityMode availabilityMode = AvailabilityMode.ALL;
89 public AbstractMQTTThingHandler(Thing thing, int subscribeTimeout) {
91 this.subscribeTimeout = subscribeTimeout;
95 * Return the channel state for the given channelUID.
97 * @param channelUID The channelUID
98 * @return A channel state. May be null.
100 public abstract @Nullable ChannelState getChannelState(ChannelUID channelUID);
103 * Start the topic discovery and subscribe to all channel state topics on all {@link ChannelState}s.
104 * Put the thing ONLINE on success otherwise complete the returned future exceptionally.
106 * @param connection A started broker connection
107 * @return A future that completes normal on success and exceptionally on any errors.
109 protected CompletableFuture<@Nullable Void> start(MqttBrokerConnection connection) {
110 return availabilityStates.values().stream().map(cChannel -> {
111 final CompletableFuture<@Nullable Void> fut = cChannel == null ? CompletableFuture.completedFuture(null)
112 : cChannel.start(connection, scheduler, 0);
114 }).collect(FutureCollector.allOf());
118 * Called when the MQTT connection disappeared.
119 * You should clean up all resources that depend on a working connection.
121 protected void stop() {
122 clearAllAvailabilityTopics();
123 resetMessageReceived();
127 public void handleCommand(ChannelUID channelUID, Command command) {
128 if (connection == null) {
132 final @Nullable ChannelState data = getChannelState(channelUID);
135 logger.warn("Channel {} not supported!", channelUID);
139 if (command instanceof RefreshType) {
140 State state = data.getCache().getChannelState();
141 if (state instanceof UnDefType) {
142 logger.debug("Channel {} received REFRESH but no value cached, ignoring", channelUID);
144 updateState(channelUID, state);
149 if (data.isReadOnly()) {
150 logger.trace("Channel {} is a read-only channel, ignoring command {}", channelUID, command);
154 final CompletableFuture<Boolean> future = data.publishValue(command);
155 future.handle((v, ex) -> {
157 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, ex.getLocalizedMessage());
158 logger.debug("Failed publishing value {} to topic {}: {}", command, data.getCommandTopic(),
161 logger.debug("Successfully published value {} to topic {}", command, data.getCommandTopic());
168 public void bridgeStatusChanged(ThingStatusInfo bridgeStatusInfo) {
169 if (bridgeStatusInfo.getStatus() == ThingStatus.OFFLINE) {
170 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.BRIDGE_OFFLINE);
175 if (bridgeStatusInfo.getStatus() != ThingStatus.ONLINE) {
176 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR);
181 AbstractBrokerHandler h = getBridgeHandler();
183 resetMessageReceived();
184 logger.warn("Bridge handler not found!");
188 final MqttBrokerConnection connection;
190 connection = h.getConnectionAsync().get(500, TimeUnit.MILLISECONDS);
191 } catch (InterruptedException | ExecutionException | TimeoutException ignored) {
192 resetMessageReceived();
193 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.BRIDGE_UNINITIALIZED,
194 "Bridge handler has no valid broker connection!");
197 this.connection = connection;
199 // Start up (subscribe to MQTT topics). Limit with a timeout and catch exceptions.
200 // We do not set the thing to ONLINE here in the AbstractBase, that is the responsibility of a derived
203 start(connection).get(subscribeTimeout, TimeUnit.MILLISECONDS);
204 } catch (InterruptedException | ExecutionException | TimeoutException ignored) {
205 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
206 "Did not receive all required topics");
211 * Return the bride handler. The bridge is from the "MQTT" bundle.
213 public @Nullable AbstractBrokerHandler getBridgeHandler() {
214 Bridge bridge = getBridge();
215 if (bridge == null) {
218 return (AbstractBrokerHandler) bridge.getHandler();
222 * Return the bridge status.
224 public ThingStatusInfo getBridgeStatus() {
225 Bridge b = getBridge();
227 return b.getStatusInfo();
229 return new ThingStatusInfo(ThingStatus.OFFLINE, ThingStatusDetail.BRIDGE_OFFLINE, null);
234 public void initialize() {
235 bridgeStatusChanged(getBridgeStatus());
239 public void handleRemoval() {
241 super.handleRemoval();
245 public void dispose() {
248 unsubscribeAll().get(500, TimeUnit.MILLISECONDS);
249 } catch (InterruptedException | ExecutionException | TimeoutException e) {
250 logger.warn("unsubscription on disposal failed for {}: ", thing.getUID(), e);
257 * this method must unsubscribe all topics used by this thing handler
261 public abstract CompletableFuture<Void> unsubscribeAll();
264 public void updateChannelState(ChannelUID channelUID, State value) {
265 if (messageReceived.compareAndSet(false, true)) {
266 calculateAndUpdateThingStatus(true);
268 super.updateState(channelUID, value);
272 public void triggerChannel(ChannelUID channelUID, String event) {
273 if (messageReceived.compareAndSet(false, true)) {
274 calculateAndUpdateThingStatus(true);
276 super.triggerChannel(channelUID, event);
280 public void postChannelCommand(ChannelUID channelUID, Command command) {
281 postCommand(channelUID, command);
284 public @Nullable MqttBrokerConnection getConnection() {
289 * This is for tests only to inject a broker connection.
291 * @param connection MQTT Broker connection
293 public void setConnection(MqttBrokerConnection connection) {
294 this.connection = connection;
298 public void setAvailabilityMode(AvailabilityMode mode) {
299 this.availabilityMode = mode;
303 public void addAvailabilityTopic(String availability_topic, String payload_available,
304 String payload_not_available) {
305 addAvailabilityTopic(availability_topic, payload_available, payload_not_available, List.of());
309 public void addAvailabilityTopic(String availability_topic, String payload_available, String payload_not_available,
310 List<String> transformation_pattern) {
311 availabilityStates.computeIfAbsent(availability_topic, topic -> {
312 Value value = new OnOffValue(payload_available, payload_not_available);
313 ChannelGroupUID groupUID = new ChannelGroupUID(getThing().getUID(), "availability");
314 ChannelUID channelUID = new ChannelUID(groupUID, UIDUtils.encode(topic));
315 ChannelState state = new ChannelState(
316 ChannelConfigBuilder.create().withStateTopic(topic)
317 .withTransformationPattern(transformation_pattern).build(),
318 channelUID, value, new ChannelStateUpdateListener() {
320 public void updateChannelState(ChannelUID channelUID, State value) {
321 boolean online = value.equals(OnOffType.ON);
322 calculateAndUpdateThingStatus(online);
326 public void triggerChannel(ChannelUID channelUID, String eventPayload) {
330 public void postChannelCommand(ChannelUID channelUID, Command value) {
333 MqttBrokerConnection connection = getConnection();
334 if (connection != null) {
335 state.start(connection, scheduler, 0);
343 public void removeAvailabilityTopic(String availabilityTopic) {
344 availabilityStates.computeIfPresent(availabilityTopic, (topic, state) -> {
345 if (connection != null && state != null) {
353 public void clearAllAvailabilityTopics() {
354 Set<String> topics = new HashSet<>(availabilityStates.keySet());
355 topics.forEach(this::removeAvailabilityTopic);
359 public void resetMessageReceived() {
360 if (messageReceived.compareAndSet(true, false)) {
361 calculateAndUpdateThingStatus(false);
365 protected void calculateAndUpdateThingStatus(boolean lastValue) {
366 final Optional<Boolean> availabilityTopicsSeen;
368 if (availabilityStates.isEmpty()) {
369 availabilityTopicsSeen = Optional.empty();
371 availabilityTopicsSeen = switch (availabilityMode) {
372 case ALL -> Optional.of(availabilityStates.values().stream().allMatch(
373 c -> c != null && OnOffType.ON.equals(c.getCache().getChannelState().as(OnOffType.class))));
374 case ANY -> Optional.of(availabilityStates.values().stream().anyMatch(
375 c -> c != null && OnOffType.ON.equals(c.getCache().getChannelState().as(OnOffType.class))));
376 case LATEST -> Optional.of(lastValue);
379 updateThingStatus(messageReceived.get(), availabilityTopicsSeen);
382 protected abstract void updateThingStatus(boolean messageReceived, Optional<Boolean> availabilityTopicsSeen);