2 * Copyright (c) 2010-2020 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.Collection;
16 import java.util.HashSet;
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;
25 import java.util.stream.Collectors;
27 import org.eclipse.jdt.annotation.NonNull;
28 import org.eclipse.jdt.annotation.NonNullByDefault;
29 import org.eclipse.jdt.annotation.Nullable;
30 import org.openhab.binding.mqtt.generic.utils.FutureCollector;
31 import org.openhab.binding.mqtt.generic.values.OnOffValue;
32 import org.openhab.binding.mqtt.generic.values.Value;
33 import org.openhab.binding.mqtt.handler.AbstractBrokerHandler;
34 import org.openhab.core.io.transport.mqtt.MqttBrokerConnection;
35 import org.openhab.core.library.types.OnOffType;
36 import org.openhab.core.thing.Bridge;
37 import org.openhab.core.thing.ChannelGroupUID;
38 import org.openhab.core.thing.ChannelUID;
39 import org.openhab.core.thing.Thing;
40 import org.openhab.core.thing.ThingStatus;
41 import org.openhab.core.thing.ThingStatusDetail;
42 import org.openhab.core.thing.ThingStatusInfo;
43 import org.openhab.core.thing.binding.BaseThingHandler;
44 import org.openhab.core.types.Command;
45 import org.openhab.core.types.RefreshType;
46 import org.openhab.core.types.State;
47 import org.openhab.core.types.UnDefType;
48 import org.openhab.core.util.UIDUtils;
49 import org.slf4j.Logger;
50 import org.slf4j.LoggerFactory;
53 * Base class for MQTT thing handlers. If you are going to implement an MQTT convention, you probably
54 * want to inherit from here.
57 * This base class will make sure you get a working {@link MqttBrokerConnection}, you will be informed
58 * when to start your subscriptions ({@link #start(MqttBrokerConnection)}) and when to free your resources
59 * because of a lost connection ({@link AbstractMQTTThingHandler#stop()}).
62 * If you inherit from this base class, you must use {@link ChannelState} to (a) keep a cached channel value,
63 * (b) to link a MQTT topic value to a channel value ("MQTT state topic") and (c) to have a secondary MQTT topic
64 * where any changes to the {@link ChannelState} are send to ("MQTT command topic").
67 * You are expected to keep your channel data structure organized in a way, to resolve a {@link ChannelUID} to
68 * the corresponding {@link ChannelState} in {@link #getChannelState(ChannelUID)}.
71 * To inform the framework of changed values, received via MQTT, a {@link ChannelState} calls a listener callback.
72 * While setting up your {@link ChannelState} you would set the callback to your thing handler,
73 * because this base class implements {@link ChannelStateUpdateListener}.
75 * @author David Graeff - Initial contribution
78 public abstract class AbstractMQTTThingHandler extends BaseThingHandler
79 implements ChannelStateUpdateListener, AvailabilityTracker {
80 private final Logger logger = LoggerFactory.getLogger(AbstractMQTTThingHandler.class);
81 // Timeout for the entire tree parsing and subscription
82 private final int subscribeTimeout;
84 protected @Nullable MqttBrokerConnection connection;
86 private AtomicBoolean messageReceived = new AtomicBoolean(false);
87 private Map<String, @Nullable ChannelState> availabilityStates = new ConcurrentHashMap<>();
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 abstract CompletableFuture<@Nullable Void> start(MqttBrokerConnection connection);
112 * Called when the MQTT connection disappeared.
113 * You should clean up all resources that depend on a working connection.
115 protected void stop() {
116 clearAllAvailabilityTopics();
117 resetMessageReceived();
121 public void handleCommand(ChannelUID channelUID, Command command) {
122 if (connection == null) {
126 final @Nullable ChannelState data = getChannelState(channelUID);
129 logger.warn("Channel {} not supported!", channelUID);
133 if (command instanceof RefreshType) {
134 State state = data.getCache().getChannelState();
135 if (state instanceof UnDefType) {
136 logger.debug("Channel {} received REFRESH but no value cached, ignoring", channelUID);
138 updateState(channelUID, state);
143 if (data.isReadOnly()) {
144 logger.trace("Channel {} is a read-only channel, ignoring command {}", channelUID, command);
148 final CompletableFuture<Boolean> future = data.publishValue(command);
149 future.handle((v, ex) -> {
151 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, ex.getLocalizedMessage());
152 logger.debug("Failed publishing value {} to topic {}: {}", command, data.getCommandTopic(),
155 logger.debug("Successfully published value {} to topic {}", command, data.getCommandTopic());
162 public void bridgeStatusChanged(ThingStatusInfo bridgeStatusInfo) {
163 if (bridgeStatusInfo.getStatus() == ThingStatus.OFFLINE) {
164 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.BRIDGE_OFFLINE);
169 if (bridgeStatusInfo.getStatus() != ThingStatus.ONLINE) {
170 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR);
175 AbstractBrokerHandler h = getBridgeHandler();
177 resetMessageReceived();
178 logger.warn("Bridge handler not found!");
182 final MqttBrokerConnection connection;
184 connection = h.getConnectionAsync().get(500, TimeUnit.MILLISECONDS);
185 } catch (InterruptedException | ExecutionException | TimeoutException ignored) {
186 resetMessageReceived();
187 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.BRIDGE_UNINITIALIZED,
188 "Bridge handler has no valid broker connection!");
191 this.connection = connection;
193 // Start up (subscribe to MQTT topics). Limit with a timeout and catch exceptions.
194 // We do not set the thing to ONLINE here in the AbstractBase, that is the responsibility of a derived
197 Collection<CompletableFuture<@Nullable Void>> futures = availabilityStates.values().stream().map(s -> {
199 return s.start(connection, scheduler, 0);
201 return CompletableFuture.allOf();
202 }).collect(Collectors.toList());
204 futures.add(start(connection));
206 futures.stream().collect(FutureCollector.allOf()).exceptionally(e -> {
207 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, e.getLocalizedMessage());
209 }).get(subscribeTimeout, TimeUnit.MILLISECONDS);
210 } catch (InterruptedException | ExecutionException | TimeoutException ignored) {
211 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
212 "Did not receive all required topics");
217 * Return the bride handler. The bridge is from the "MQTT" bundle.
219 public @Nullable AbstractBrokerHandler getBridgeHandler() {
220 Bridge bridge = getBridge();
221 if (bridge == null) {
224 return (AbstractBrokerHandler) bridge.getHandler();
228 * Return the bridge status.
230 public ThingStatusInfo getBridgeStatus() {
231 Bridge b = getBridge();
233 return b.getStatusInfo();
235 return new ThingStatusInfo(ThingStatus.OFFLINE, ThingStatusDetail.BRIDGE_OFFLINE, null);
240 public void initialize() {
241 bridgeStatusChanged(getBridgeStatus());
245 public void handleRemoval() {
247 super.handleRemoval();
251 public void dispose() {
254 unsubscribeAll().get(500, TimeUnit.MILLISECONDS);
255 } catch (InterruptedException | ExecutionException | TimeoutException e) {
256 logger.warn("unsubscription on disposal failed for {}: ", thing.getUID(), e);
263 * this method must unsubscribe all topics used by this thing handler
267 public abstract CompletableFuture<Void> unsubscribeAll();
270 public void updateChannelState(ChannelUID channelUID, State value) {
271 if (messageReceived.compareAndSet(false, true)) {
272 calculateThingStatus();
274 super.updateState(channelUID, value);
278 public void triggerChannel(ChannelUID channelUID, String event) {
279 if (messageReceived.compareAndSet(false, true)) {
280 calculateThingStatus();
282 super.triggerChannel(channelUID, event);
286 public void postChannelCommand(ChannelUID channelUID, Command command) {
287 postCommand(channelUID, command);
290 public @Nullable MqttBrokerConnection getConnection() {
295 * This is for tests only to inject a broker connection.
297 * @param connection MQTT Broker connection
299 public void setConnection(MqttBrokerConnection connection) {
300 this.connection = connection;
304 public void addAvailabilityTopic(String availability_topic, String payload_available,
305 String payload_not_available) {
306 availabilityStates.computeIfAbsent(availability_topic, topic -> {
307 Value value = new OnOffValue(payload_available, payload_not_available);
308 ChannelGroupUID groupUID = new ChannelGroupUID(getThing().getUID(), "availablility");
309 ChannelUID channelUID = new ChannelUID(groupUID, UIDUtils.encode(topic));
310 ChannelState state = new ChannelState(ChannelConfigBuilder.create().withStateTopic(topic).build(),
311 channelUID, value, new ChannelStateUpdateListener() {
313 public void updateChannelState(ChannelUID channelUID, State value) {
314 calculateThingStatus();
318 public void triggerChannel(ChannelUID channelUID, String eventPayload) {
322 public void postChannelCommand(ChannelUID channelUID, Command value) {
325 MqttBrokerConnection connection = getConnection();
326 if (connection != null) {
327 state.start(connection, scheduler, 0);
335 public void removeAvailabilityTopic(@NonNull String availability_topic) {
336 availabilityStates.computeIfPresent(availability_topic, (topic, state) -> {
337 if (connection != null && state != null) {
345 public void clearAllAvailabilityTopics() {
346 Set<String> topics = new HashSet<>(availabilityStates.keySet());
347 topics.forEach(this::removeAvailabilityTopic);
351 public void resetMessageReceived() {
352 if (messageReceived.compareAndSet(true, false)) {
353 calculateThingStatus();
357 protected void calculateThingStatus() {
358 final boolean availabilityTopicsSeen;
360 if (availabilityStates.isEmpty()) {
361 availabilityTopicsSeen = true;
363 availabilityTopicsSeen = availabilityStates.values().stream().allMatch(
364 c -> c != null && OnOffType.ON.equals(c.getCache().getChannelState().as(OnOffType.class)));
366 updateThingStatus(messageReceived.get(), availabilityTopicsSeen);
369 protected abstract void updateThingStatus(boolean messageReceived, boolean availabilityTopicsSeen);