]> git.basschouten.com Git - openhab-addons.git/blob
2e7ccfc065620eb199ebf855fa0658e557355f62
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2023 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().stream().map(cChannel -> {
109             final CompletableFuture<@Nullable Void> fut = cChannel == null ? CompletableFuture.completedFuture(null)
110                     : cChannel.start(connection, scheduler, 0);
111             return fut;
112         }).collect(FutureCollector.allOf());
113     }
114
115     /**
116      * Called when the MQTT connection disappeared.
117      * You should clean up all resources that depend on a working connection.
118      */
119     protected void stop() {
120         clearAllAvailabilityTopics();
121         resetMessageReceived();
122     }
123
124     @Override
125     public void handleCommand(ChannelUID channelUID, Command command) {
126         if (connection == null) {
127             return;
128         }
129
130         final @Nullable ChannelState data = getChannelState(channelUID);
131
132         if (data == null) {
133             logger.warn("Channel {} not supported!", channelUID);
134             return;
135         }
136
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);
141             } else {
142                 updateState(channelUID, state);
143             }
144             return;
145         }
146
147         if (data.isReadOnly()) {
148             logger.trace("Channel {} is a read-only channel, ignoring command {}", channelUID, command);
149             return;
150         }
151
152         final CompletableFuture<Boolean> future = data.publishValue(command);
153         future.handle((v, ex) -> {
154             if (ex != null) {
155                 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, ex.getLocalizedMessage());
156                 logger.debug("Failed publishing value {} to topic {}: {}", command, data.getCommandTopic(),
157                         ex.getMessage());
158             } else {
159                 logger.debug("Successfully published value {} to topic {}", command, data.getCommandTopic());
160             }
161             return null;
162         });
163     }
164
165     @Override
166     public void bridgeStatusChanged(ThingStatusInfo bridgeStatusInfo) {
167         if (bridgeStatusInfo.getStatus() == ThingStatus.OFFLINE) {
168             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.BRIDGE_OFFLINE);
169             stop();
170             connection = null;
171             return;
172         }
173         if (bridgeStatusInfo.getStatus() != ThingStatus.ONLINE) {
174             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR);
175             stop();
176             return;
177         }
178
179         AbstractBrokerHandler h = getBridgeHandler();
180         if (h == null) {
181             resetMessageReceived();
182             logger.warn("Bridge handler not found!");
183             return;
184         }
185
186         final MqttBrokerConnection connection;
187         try {
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!");
193             return;
194         }
195         this.connection = connection;
196
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
199         // class.
200         try {
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");
205         }
206     }
207
208     /**
209      * Return the bride handler. The bridge is from the "MQTT" bundle.
210      */
211     public @Nullable AbstractBrokerHandler getBridgeHandler() {
212         Bridge bridge = getBridge();
213         if (bridge == null) {
214             return null;
215         }
216         return (AbstractBrokerHandler) bridge.getHandler();
217     }
218
219     /**
220      * Return the bridge status.
221      */
222     public ThingStatusInfo getBridgeStatus() {
223         Bridge b = getBridge();
224         if (b != null) {
225             return b.getStatusInfo();
226         } else {
227             return new ThingStatusInfo(ThingStatus.OFFLINE, ThingStatusDetail.BRIDGE_OFFLINE, null);
228         }
229     }
230
231     @Override
232     public void initialize() {
233         bridgeStatusChanged(getBridgeStatus());
234     }
235
236     @Override
237     public void handleRemoval() {
238         stop();
239         super.handleRemoval();
240     }
241
242     @Override
243     public void dispose() {
244         stop();
245         try {
246             unsubscribeAll().get(500, TimeUnit.MILLISECONDS);
247         } catch (InterruptedException | ExecutionException | TimeoutException e) {
248             logger.warn("unsubscription on disposal failed for {}: ", thing.getUID(), e);
249         }
250         connection = null;
251         super.dispose();
252     }
253
254     /**
255      * this method must unsubscribe all topics used by this thing handler
256      *
257      * @return
258      */
259     public abstract CompletableFuture<Void> unsubscribeAll();
260
261     @Override
262     public void updateChannelState(ChannelUID channelUID, State value) {
263         if (messageReceived.compareAndSet(false, true)) {
264             calculateThingStatus();
265         }
266         super.updateState(channelUID, value);
267     }
268
269     @Override
270     public void triggerChannel(ChannelUID channelUID, String event) {
271         if (messageReceived.compareAndSet(false, true)) {
272             calculateThingStatus();
273         }
274         super.triggerChannel(channelUID, event);
275     }
276
277     @Override
278     public void postChannelCommand(ChannelUID channelUID, Command command) {
279         postCommand(channelUID, command);
280     }
281
282     public @Nullable MqttBrokerConnection getConnection() {
283         return connection;
284     }
285
286     /**
287      * This is for tests only to inject a broker connection.
288      *
289      * @param connection MQTT Broker connection
290      */
291     public void setConnection(MqttBrokerConnection connection) {
292         this.connection = connection;
293     }
294
295     @Override
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);
299     }
300
301     @Override
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() {
311                         @Override
312                         public void updateChannelState(ChannelUID channelUID, State value) {
313                             calculateThingStatus();
314                         }
315
316                         @Override
317                         public void triggerChannel(ChannelUID channelUID, String eventPayload) {
318                         }
319
320                         @Override
321                         public void postChannelCommand(ChannelUID channelUID, Command value) {
322                         }
323                     });
324             if (transformation_pattern != null && transformationServiceProvider != null) {
325                 state.addTransformation(transformation_pattern, transformationServiceProvider);
326             }
327             MqttBrokerConnection connection = getConnection();
328             if (connection != null) {
329                 state.start(connection, scheduler, 0);
330             }
331
332             return state;
333         });
334     }
335
336     @Override
337     public void removeAvailabilityTopic(String availabilityTopic) {
338         availabilityStates.computeIfPresent(availabilityTopic, (topic, state) -> {
339             if (connection != null && state != null) {
340                 state.stop();
341             }
342             return null;
343         });
344     }
345
346     @Override
347     public void clearAllAvailabilityTopics() {
348         Set<String> topics = new HashSet<>(availabilityStates.keySet());
349         topics.forEach(this::removeAvailabilityTopic);
350     }
351
352     @Override
353     public void resetMessageReceived() {
354         if (messageReceived.compareAndSet(true, false)) {
355             calculateThingStatus();
356         }
357     }
358
359     protected void calculateThingStatus() {
360         final Optional<Boolean> availabilityTopicsSeen;
361
362         if (availabilityStates.isEmpty()) {
363             availabilityTopicsSeen = Optional.empty();
364         } else {
365             availabilityTopicsSeen = Optional.of(availabilityStates.values().stream().allMatch(
366                     c -> c != null && OnOffType.ON.equals(c.getCache().getChannelState().as(OnOffType.class))));
367         }
368         updateThingStatus(messageReceived.get(), availabilityTopicsSeen);
369     }
370
371     protected abstract void updateThingStatus(boolean messageReceived, Optional<Boolean> availabilityTopicsSeen);
372 }