2 * Copyright (c) 2010-2022 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.NonNull;
27 import org.eclipse.jdt.annotation.NonNullByDefault;
28 import org.eclipse.jdt.annotation.Nullable;
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 abstract CompletableFuture<@Nullable Void> start(MqttBrokerConnection connection);
110 * Called when the MQTT connection disappeared.
111 * You should clean up all resources that depend on a working connection.
113 protected void stop() {
114 clearAllAvailabilityTopics();
115 resetMessageReceived();
119 public void handleCommand(ChannelUID channelUID, Command command) {
120 if (connection == null) {
124 final @Nullable ChannelState data = getChannelState(channelUID);
127 logger.warn("Channel {} not supported!", channelUID);
131 if (command instanceof RefreshType) {
132 State state = data.getCache().getChannelState();
133 if (state instanceof UnDefType) {
134 logger.debug("Channel {} received REFRESH but no value cached, ignoring", channelUID);
136 updateState(channelUID, state);
141 if (data.isReadOnly()) {
142 logger.trace("Channel {} is a read-only channel, ignoring command {}", channelUID, command);
146 final CompletableFuture<Boolean> future = data.publishValue(command);
147 future.handle((v, ex) -> {
149 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, ex.getLocalizedMessage());
150 logger.debug("Failed publishing value {} to topic {}: {}", command, data.getCommandTopic(),
153 logger.debug("Successfully published value {} to topic {}", command, data.getCommandTopic());
160 public void bridgeStatusChanged(ThingStatusInfo bridgeStatusInfo) {
161 if (bridgeStatusInfo.getStatus() == ThingStatus.OFFLINE) {
162 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.BRIDGE_OFFLINE);
167 if (bridgeStatusInfo.getStatus() != ThingStatus.ONLINE) {
168 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR);
173 AbstractBrokerHandler h = getBridgeHandler();
175 resetMessageReceived();
176 logger.warn("Bridge handler not found!");
180 final MqttBrokerConnection connection;
182 connection = h.getConnectionAsync().get(500, TimeUnit.MILLISECONDS);
183 } catch (InterruptedException | ExecutionException | TimeoutException ignored) {
184 resetMessageReceived();
185 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.BRIDGE_UNINITIALIZED,
186 "Bridge handler has no valid broker connection!");
189 this.connection = connection;
191 // Start up (subscribe to MQTT topics). Limit with a timeout and catch exceptions.
192 // We do not set the thing to ONLINE here in the AbstractBase, that is the responsibility of a derived
195 start(connection).get(subscribeTimeout, TimeUnit.MILLISECONDS);
196 } catch (InterruptedException | ExecutionException | TimeoutException ignored) {
197 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
198 "Did not receive all required topics");
203 * Return the bride handler. The bridge is from the "MQTT" bundle.
205 public @Nullable AbstractBrokerHandler getBridgeHandler() {
206 Bridge bridge = getBridge();
207 if (bridge == null) {
210 return (AbstractBrokerHandler) bridge.getHandler();
214 * Return the bridge status.
216 public ThingStatusInfo getBridgeStatus() {
217 Bridge b = getBridge();
219 return b.getStatusInfo();
221 return new ThingStatusInfo(ThingStatus.OFFLINE, ThingStatusDetail.BRIDGE_OFFLINE, null);
226 public void initialize() {
227 bridgeStatusChanged(getBridgeStatus());
231 public void handleRemoval() {
233 super.handleRemoval();
237 public void dispose() {
240 unsubscribeAll().get(500, TimeUnit.MILLISECONDS);
241 } catch (InterruptedException | ExecutionException | TimeoutException e) {
242 logger.warn("unsubscription on disposal failed for {}: ", thing.getUID(), e);
249 * this method must unsubscribe all topics used by this thing handler
253 public abstract CompletableFuture<Void> unsubscribeAll();
256 public void updateChannelState(ChannelUID channelUID, State value) {
257 if (messageReceived.compareAndSet(false, true)) {
258 calculateThingStatus();
260 super.updateState(channelUID, value);
264 public void triggerChannel(ChannelUID channelUID, String event) {
265 if (messageReceived.compareAndSet(false, true)) {
266 calculateThingStatus();
268 super.triggerChannel(channelUID, event);
272 public void postChannelCommand(ChannelUID channelUID, Command command) {
273 postCommand(channelUID, command);
276 public @Nullable MqttBrokerConnection getConnection() {
281 * This is for tests only to inject a broker connection.
283 * @param connection MQTT Broker connection
285 public void setConnection(MqttBrokerConnection connection) {
286 this.connection = connection;
290 public void addAvailabilityTopic(String availability_topic, String payload_available,
291 String payload_not_available) {
292 availabilityStates.computeIfAbsent(availability_topic, topic -> {
293 Value value = new OnOffValue(payload_available, payload_not_available);
294 ChannelGroupUID groupUID = new ChannelGroupUID(getThing().getUID(), "availablility");
295 ChannelUID channelUID = new ChannelUID(groupUID, UIDUtils.encode(topic));
296 ChannelState state = new ChannelState(ChannelConfigBuilder.create().withStateTopic(topic).build(),
297 channelUID, value, new ChannelStateUpdateListener() {
299 public void updateChannelState(ChannelUID channelUID, State value) {
300 calculateThingStatus();
304 public void triggerChannel(ChannelUID channelUID, String eventPayload) {
308 public void postChannelCommand(ChannelUID channelUID, Command value) {
311 MqttBrokerConnection connection = getConnection();
312 if (connection != null) {
313 state.start(connection, scheduler, 0);
321 public void removeAvailabilityTopic(@NonNull String availability_topic) {
322 availabilityStates.computeIfPresent(availability_topic, (topic, state) -> {
323 if (connection != null && state != null) {
331 public void clearAllAvailabilityTopics() {
332 Set<String> topics = new HashSet<>(availabilityStates.keySet());
333 topics.forEach(this::removeAvailabilityTopic);
337 public void resetMessageReceived() {
338 if (messageReceived.compareAndSet(true, false)) {
339 calculateThingStatus();
343 protected void calculateThingStatus() {
344 final Optional<Boolean> availabilityTopicsSeen;
346 if (availabilityStates.isEmpty()) {
347 availabilityTopicsSeen = Optional.empty();
349 availabilityTopicsSeen = Optional.of(availabilityStates.values().stream().allMatch(
350 c -> c != null && OnOffType.ON.equals(c.getCache().getChannelState().as(OnOffType.class))));
352 updateThingStatus(messageReceived.get(), availabilityTopicsSeen);
355 protected abstract void updateThingStatus(boolean messageReceived, Optional<Boolean> availabilityTopicsSeen);