]> git.basschouten.com Git - openhab-addons.git/blob
9f7cc39be4d9ae59b22f38126e19173cfe8dfd4d
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2022 Contributors to the openHAB project
3  *
4  * See the NOTICE file(s) distributed with this work for additional
5  * information.
6  *
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
10  *
11  * SPDX-License-Identifier: EPL-2.0
12  */
13 package org.openhab.binding.mqtt.generic;
14
15 import java.util.HashSet;
16 import java.util.Map;
17 import java.util.Optional;
18 import java.util.Set;
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
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;
49
50 /**
51  * Base class for MQTT thing handlers. If you are going to implement an MQTT convention, you probably
52  * want to inherit from here.
53  *
54  * <p>
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()}).
58  *
59  * <p>
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").
63  *
64  * <p>
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)}.
67  *
68  * <p>
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}.
72  *
73  * @author David Graeff - Initial contribution
74  */
75 @NonNullByDefault
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;
81
82     protected @Nullable MqttBrokerConnection connection;
83
84     private AtomicBoolean messageReceived = new AtomicBoolean(false);
85     private Map<String, @Nullable ChannelState> availabilityStates = new ConcurrentHashMap<>();
86
87     public AbstractMQTTThingHandler(Thing thing, int subscribeTimeout) {
88         super(thing);
89         this.subscribeTimeout = subscribeTimeout;
90     }
91
92     /**
93      * Return the channel state for the given channelUID.
94      *
95      * @param channelUID The channelUID
96      * @return A channel state. May be null.
97      */
98     public abstract @Nullable ChannelState getChannelState(ChannelUID channelUID);
99
100     /**
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.
103      *
104      * @param connection A started broker connection
105      * @return A future that completes normal on success and exceptionally on any errors.
106      */
107     protected CompletableFuture<@Nullable Void> start(MqttBrokerConnection connection) {
108         return availabilityStates.values().parallelStream().map(cChannel -> cChannel.start(connection, scheduler, 0))
109                 .collect(FutureCollector.allOf());
110     }
111
112     /**
113      * Called when the MQTT connection disappeared.
114      * You should clean up all resources that depend on a working connection.
115      */
116     protected void stop() {
117         clearAllAvailabilityTopics();
118         resetMessageReceived();
119     }
120
121     @Override
122     public void handleCommand(ChannelUID channelUID, Command command) {
123         if (connection == null) {
124             return;
125         }
126
127         final @Nullable ChannelState data = getChannelState(channelUID);
128
129         if (data == null) {
130             logger.warn("Channel {} not supported!", channelUID);
131             return;
132         }
133
134         if (command instanceof RefreshType) {
135             State state = data.getCache().getChannelState();
136             if (state instanceof UnDefType) {
137                 logger.debug("Channel {} received REFRESH but no value cached, ignoring", channelUID);
138             } else {
139                 updateState(channelUID, state);
140             }
141             return;
142         }
143
144         if (data.isReadOnly()) {
145             logger.trace("Channel {} is a read-only channel, ignoring command {}", channelUID, command);
146             return;
147         }
148
149         final CompletableFuture<Boolean> future = data.publishValue(command);
150         future.handle((v, ex) -> {
151             if (ex != null) {
152                 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, ex.getLocalizedMessage());
153                 logger.debug("Failed publishing value {} to topic {}: {}", command, data.getCommandTopic(),
154                         ex.getMessage());
155             } else {
156                 logger.debug("Successfully published value {} to topic {}", command, data.getCommandTopic());
157             }
158             return null;
159         });
160     }
161
162     @Override
163     public void bridgeStatusChanged(ThingStatusInfo bridgeStatusInfo) {
164         if (bridgeStatusInfo.getStatus() == ThingStatus.OFFLINE) {
165             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.BRIDGE_OFFLINE);
166             stop();
167             connection = null;
168             return;
169         }
170         if (bridgeStatusInfo.getStatus() != ThingStatus.ONLINE) {
171             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR);
172             stop();
173             return;
174         }
175
176         AbstractBrokerHandler h = getBridgeHandler();
177         if (h == null) {
178             resetMessageReceived();
179             logger.warn("Bridge handler not found!");
180             return;
181         }
182
183         final MqttBrokerConnection connection;
184         try {
185             connection = h.getConnectionAsync().get(500, TimeUnit.MILLISECONDS);
186         } catch (InterruptedException | ExecutionException | TimeoutException ignored) {
187             resetMessageReceived();
188             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.BRIDGE_UNINITIALIZED,
189                     "Bridge handler has no valid broker connection!");
190             return;
191         }
192         this.connection = connection;
193
194         // Start up (subscribe to MQTT topics). Limit with a timeout and catch exceptions.
195         // We do not set the thing to ONLINE here in the AbstractBase, that is the responsibility of a derived
196         // class.
197         try {
198             start(connection).get(subscribeTimeout, TimeUnit.MILLISECONDS);
199         } catch (InterruptedException | ExecutionException | TimeoutException ignored) {
200             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
201                     "Did not receive all required topics");
202         }
203     }
204
205     /**
206      * Return the bride handler. The bridge is from the "MQTT" bundle.
207      */
208     public @Nullable AbstractBrokerHandler getBridgeHandler() {
209         Bridge bridge = getBridge();
210         if (bridge == null) {
211             return null;
212         }
213         return (AbstractBrokerHandler) bridge.getHandler();
214     }
215
216     /**
217      * Return the bridge status.
218      */
219     public ThingStatusInfo getBridgeStatus() {
220         Bridge b = getBridge();
221         if (b != null) {
222             return b.getStatusInfo();
223         } else {
224             return new ThingStatusInfo(ThingStatus.OFFLINE, ThingStatusDetail.BRIDGE_OFFLINE, null);
225         }
226     }
227
228     @Override
229     public void initialize() {
230         bridgeStatusChanged(getBridgeStatus());
231     }
232
233     @Override
234     public void handleRemoval() {
235         stop();
236         super.handleRemoval();
237     }
238
239     @Override
240     public void dispose() {
241         stop();
242         try {
243             unsubscribeAll().get(500, TimeUnit.MILLISECONDS);
244         } catch (InterruptedException | ExecutionException | TimeoutException e) {
245             logger.warn("unsubscription on disposal failed for {}: ", thing.getUID(), e);
246         }
247         connection = null;
248         super.dispose();
249     }
250
251     /**
252      * this method must unsubscribe all topics used by this thing handler
253      *
254      * @return
255      */
256     public abstract CompletableFuture<Void> unsubscribeAll();
257
258     @Override
259     public void updateChannelState(ChannelUID channelUID, State value) {
260         if (messageReceived.compareAndSet(false, true)) {
261             calculateThingStatus();
262         }
263         super.updateState(channelUID, value);
264     }
265
266     @Override
267     public void triggerChannel(ChannelUID channelUID, String event) {
268         if (messageReceived.compareAndSet(false, true)) {
269             calculateThingStatus();
270         }
271         super.triggerChannel(channelUID, event);
272     }
273
274     @Override
275     public void postChannelCommand(ChannelUID channelUID, Command command) {
276         postCommand(channelUID, command);
277     }
278
279     public @Nullable MqttBrokerConnection getConnection() {
280         return connection;
281     }
282
283     /**
284      * This is for tests only to inject a broker connection.
285      *
286      * @param connection MQTT Broker connection
287      */
288     public void setConnection(MqttBrokerConnection connection) {
289         this.connection = connection;
290     }
291
292     @Override
293     public void addAvailabilityTopic(String availability_topic, String payload_available,
294             String payload_not_available) {
295         addAvailabilityTopic(availability_topic, payload_available, payload_not_available, null, null);
296     }
297
298     @Override
299     public void addAvailabilityTopic(String availability_topic, String payload_available, String payload_not_available,
300             @Nullable String transformation_pattern,
301             @Nullable TransformationServiceProvider transformationServiceProvider) {
302         availabilityStates.computeIfAbsent(availability_topic, topic -> {
303             Value value = new OnOffValue(payload_available, payload_not_available);
304             ChannelGroupUID groupUID = new ChannelGroupUID(getThing().getUID(), "availability");
305             ChannelUID channelUID = new ChannelUID(groupUID, UIDUtils.encode(topic));
306             ChannelState state = new ChannelState(ChannelConfigBuilder.create().withStateTopic(topic).build(),
307                     channelUID, value, new ChannelStateUpdateListener() {
308                         @Override
309                         public void updateChannelState(ChannelUID channelUID, State value) {
310                             calculateThingStatus();
311                         }
312
313                         @Override
314                         public void triggerChannel(ChannelUID channelUID, String eventPayload) {
315                         }
316
317                         @Override
318                         public void postChannelCommand(ChannelUID channelUID, Command value) {
319                         }
320                     });
321             if (transformation_pattern != null && transformationServiceProvider != null) {
322                 state.addTransformation(transformation_pattern, transformationServiceProvider);
323             }
324             MqttBrokerConnection connection = getConnection();
325             if (connection != null) {
326                 state.start(connection, scheduler, 0);
327             }
328
329             return state;
330         });
331     }
332
333     @Override
334     public void removeAvailabilityTopic(String availabilityTopic) {
335         availabilityStates.computeIfPresent(availabilityTopic, (topic, state) -> {
336             if (connection != null && state != null) {
337                 state.stop();
338             }
339             return null;
340         });
341     }
342
343     @Override
344     public void clearAllAvailabilityTopics() {
345         Set<String> topics = new HashSet<>(availabilityStates.keySet());
346         topics.forEach(this::removeAvailabilityTopic);
347     }
348
349     @Override
350     public void resetMessageReceived() {
351         if (messageReceived.compareAndSet(true, false)) {
352             calculateThingStatus();
353         }
354     }
355
356     protected void calculateThingStatus() {
357         final Optional<Boolean> availabilityTopicsSeen;
358
359         if (availabilityStates.isEmpty()) {
360             availabilityTopicsSeen = Optional.empty();
361         } else {
362             availabilityTopicsSeen = Optional.of(availabilityStates.values().stream().allMatch(
363                     c -> c != null && OnOffType.ON.equals(c.getCache().getChannelState().as(OnOffType.class))));
364         }
365         updateThingStatus(messageReceived.get(), availabilityTopicsSeen);
366     }
367
368     protected abstract void updateThingStatus(boolean messageReceived, Optional<Boolean> availabilityTopicsSeen);
369 }