]> git.basschouten.com Git - openhab-addons.git/blob
62361348d26aa746313b8464715e5271b1ba808f
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2024 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.nio.charset.StandardCharsets;
16 import java.util.IllegalFormatException;
17 import java.util.Optional;
18 import java.util.concurrent.CompletableFuture;
19 import java.util.concurrent.ScheduledExecutorService;
20 import java.util.concurrent.ScheduledFuture;
21 import java.util.concurrent.TimeUnit;
22
23 import org.eclipse.jdt.annotation.NonNullByDefault;
24 import org.eclipse.jdt.annotation.Nullable;
25 import org.openhab.binding.mqtt.generic.values.TextValue;
26 import org.openhab.binding.mqtt.generic.values.Value;
27 import org.openhab.core.io.transport.mqtt.MqttBrokerConnection;
28 import org.openhab.core.io.transport.mqtt.MqttMessageSubscriber;
29 import org.openhab.core.library.types.DecimalType;
30 import org.openhab.core.library.types.QuantityType;
31 import org.openhab.core.library.types.StopMoveType;
32 import org.openhab.core.library.types.StringType;
33 import org.openhab.core.thing.ChannelUID;
34 import org.openhab.core.thing.binding.generic.ChannelTransformation;
35 import org.openhab.core.types.Command;
36 import org.openhab.core.types.State;
37 import org.openhab.core.types.Type;
38 import org.openhab.core.types.TypeParser;
39 import org.slf4j.Logger;
40 import org.slf4j.LoggerFactory;
41
42 /**
43  * This object consists of a {@link Value}, which is updated on the respective MQTT topic change.
44  * Updates to the value are propagated via the {@link ChannelStateUpdateListener}.
45  *
46  * @author David Graeff - Initial contribution
47  */
48 @NonNullByDefault
49 public class ChannelState implements MqttMessageSubscriber {
50     private final Logger logger = LoggerFactory.getLogger(ChannelState.class);
51
52     // Immutable channel configuration
53     protected final boolean readOnly;
54     protected final ChannelUID channelUID;
55     protected final ChannelConfig config;
56
57     /** Channel value **/
58     protected final Value cachedValue;
59
60     // Runtime variables
61     private @Nullable MqttBrokerConnection connection;
62     protected final ChannelTransformation incomingTransformation;
63     protected final ChannelTransformation outgoingTransformation;
64     private @Nullable ChannelStateUpdateListener channelStateUpdateListener;
65     protected boolean hasSubscribed = false;
66     private @Nullable ScheduledFuture<?> scheduledFuture;
67     private CompletableFuture<@Nullable Void> future = CompletableFuture.completedFuture(null);
68     private final Object futureLock = new Object();
69
70     /**
71      * Creates a new channel state.
72      *
73      * @param config The channel configuration
74      * @param channelUID The channelUID is used for the {@link ChannelStateUpdateListener} to notify about value changes
75      * @param cachedValue MQTT only notifies us once about a value, during the subscribe. The channel state therefore
76      *            needs a cache for the current value.
77      * @param channelStateUpdateListener A channel state update listener
78      */
79     public ChannelState(ChannelConfig config, ChannelUID channelUID, Value cachedValue,
80             @Nullable ChannelStateUpdateListener channelStateUpdateListener) {
81         this(config, channelUID, cachedValue, channelStateUpdateListener,
82                 new ChannelTransformation(config.transformationPattern),
83                 new ChannelTransformation(config.transformationPatternOut));
84     }
85
86     /**
87      * Creates a new channel state.
88      *
89      * @param config The channel configuration
90      * @param channelUID The channelUID is used for the {@link ChannelStateUpdateListener} to notify about value changes
91      * @param cachedValue MQTT only notifies us once about a value, during the subscribe. The channel state therefore
92      *            needs a cache for the current value.
93      * @param channelStateUpdateListener A channel state update listener
94      * @param incomingTransformation A transformation to apply to incoming values
95      * @param outgoingTransformation A transformation to apply to outgoing values
96      */
97     public ChannelState(ChannelConfig config, ChannelUID channelUID, Value cachedValue,
98             @Nullable ChannelStateUpdateListener channelStateUpdateListener,
99             @Nullable ChannelTransformation incomingTransformation,
100             @Nullable ChannelTransformation outgoingTransformation) {
101         this.config = config;
102         this.channelStateUpdateListener = channelStateUpdateListener;
103         this.channelUID = channelUID;
104         this.cachedValue = cachedValue;
105         this.readOnly = config.commandTopic.isBlank();
106         this.incomingTransformation = incomingTransformation == null ? new ChannelTransformation((String) null)
107                 : incomingTransformation;
108         this.outgoingTransformation = outgoingTransformation == null ? new ChannelTransformation((String) null)
109                 : outgoingTransformation;
110     }
111
112     public boolean isReadOnly() {
113         return this.readOnly;
114     }
115
116     /**
117      * Returns the cached value state object of this message subscriber.
118      * <p>
119      * MQTT only notifies us once about a value, during the subscribe.
120      * The channel state therefore needs a cache for the current value.
121      * If MQTT has not yet published a value, the cache might still be in UNDEF state.
122      * </p>
123      */
124     public Value getCache() {
125         return cachedValue;
126     }
127
128     /**
129      * Return the channelUID
130      */
131     public ChannelUID channelUID() {
132         return channelUID;
133     }
134
135     /**
136      * Incoming message from the MqttBrokerConnection
137      *
138      * @param topic The topic. Is the same as the field stateTopic.
139      * @param payload The byte payload. Must be UTF8 encoded text or binary data.
140      */
141     @Override
142     public void processMessage(String topic, byte[] payload) {
143         final ChannelStateUpdateListener channelStateUpdateListener = this.channelStateUpdateListener;
144         if (channelStateUpdateListener == null) {
145             logger.warn("MQTT message received for topic {}, but MessageSubscriber object hasn't been started!", topic);
146             return;
147         }
148
149         if (cachedValue.isBinary()) {
150             cachedValue.update(payload);
151             channelStateUpdateListener.updateChannelState(channelUID, cachedValue.getChannelState());
152             receivedOrTimeout();
153             return;
154         }
155
156         // String value: Apply transformations
157         String strValue = new String(payload, StandardCharsets.UTF_8);
158         if (incomingTransformation.isPresent()) {
159             Optional<String> transformedValue = incomingTransformation.apply(strValue);
160             if (transformedValue.isEmpty()) {
161                 logger.debug("Transformation '{}' returned null on '{}', discarding message", strValue,
162                         incomingTransformation);
163                 receivedOrTimeout();
164                 return;
165             }
166             strValue = transformedValue.get();
167         }
168
169         // Is trigger?: Special handling
170         if (config.trigger) {
171             channelStateUpdateListener.triggerChannel(channelUID, strValue);
172             receivedOrTimeout();
173             return;
174         }
175
176         Command command = TypeParser.parseCommand(cachedValue.getSupportedCommandTypes(), strValue);
177         if (command == null) {
178             logger.warn("Incoming payload '{}' on '{}' not supported by type '{}'", strValue, topic,
179                     cachedValue.getClass().getSimpleName());
180             receivedOrTimeout();
181             return;
182         }
183
184         Type parsedType;
185         // Map the string to a command, update the cached value and post the command to the framework
186         try {
187             parsedType = cachedValue.parseMessage(command);
188         } catch (IllegalArgumentException | IllegalStateException e) {
189             logger.warn("Command '{}' from channel '{}' not supported by type '{}': {}", strValue, channelUID,
190                     cachedValue.getClass().getSimpleName(), e.getMessage());
191             receivedOrTimeout();
192             return;
193         }
194
195         if (parsedType instanceof State parsedState) {
196             cachedValue.update(parsedState);
197         } else {
198             // things that are only Commands _must_ be posted as a command (like STOP)
199             channelStateUpdateListener.postChannelCommand(channelUID, (Command) parsedType);
200             receivedOrTimeout();
201             return;
202         }
203
204         State newState = cachedValue.getChannelState();
205         // If the user explicitly wants a command sent, not an update, do that. But
206         // we have to check that the state is even possible to send as a command
207         // (i.e. not UNDEF)
208         if (config.postCommand && newState instanceof Command newCommand) {
209             channelStateUpdateListener.postChannelCommand(channelUID, newCommand);
210         } else {
211             channelStateUpdateListener.updateChannelState(channelUID, newState);
212         }
213         receivedOrTimeout();
214     }
215
216     /**
217      * Returns the state topic. Might be an empty string if this is a stateless channel (TRIGGER kind channel).
218      */
219     public String getStateTopic() {
220         return config.stateTopic;
221     }
222
223     /**
224      * Return the command topic. Might be an empty string, if this is a read-only channel.
225      */
226     public String getCommandTopic() {
227         return config.commandTopic;
228     }
229
230     /**
231      * Returns the channelType ID which also happens to be an item-type
232      */
233     public String getItemType() {
234         return cachedValue.getItemType();
235     }
236
237     /**
238      * Returns true if this is a stateful channel.
239      */
240     public boolean isStateful() {
241         return config.retained;
242     }
243
244     /**
245      * Removes the subscription to the state topic and resets the channelStateUpdateListener.
246      *
247      * @return A future that completes with true if unsubscribing from the state topic succeeded.
248      *         It completes with false if no connection is established and completes exceptionally otherwise.
249      */
250     public CompletableFuture<@Nullable Void> stop() {
251         final MqttBrokerConnection connection = this.connection;
252         if (connection != null && !config.stateTopic.isBlank()) {
253             return connection.unsubscribe(config.stateTopic, this).thenRun(this::internalStop);
254         } else {
255             internalStop();
256             return CompletableFuture.completedFuture(null);
257         }
258     }
259
260     private void internalStop() {
261         logger.debug("Unsubscribed channel {} from topic: {}", this.channelUID, config.stateTopic);
262         this.connection = null;
263         this.channelStateUpdateListener = null;
264         hasSubscribed = false;
265         cachedValue.resetState();
266     }
267
268     private void receivedOrTimeout() {
269         final ScheduledFuture<?> scheduledFuture = this.scheduledFuture;
270         if (scheduledFuture != null) { // Cancel timeout
271             scheduledFuture.cancel(false);
272             this.scheduledFuture = null;
273         }
274         future.complete(null);
275     }
276
277     private @Nullable Void subscribeFail(Throwable e) {
278         final ScheduledFuture<?> scheduledFuture = this.scheduledFuture;
279         if (scheduledFuture != null) { // Cancel timeout
280             scheduledFuture.cancel(false);
281             this.scheduledFuture = null;
282         }
283         future.completeExceptionally(e);
284         return null;
285     }
286
287     /**
288      * Subscribes to the state topic on the given connection and informs about updates on the given listener.
289      *
290      * @param connection A broker connection
291      * @param scheduler A scheduler to realize the timeout
292      * @param timeout A timeout in milliseconds. Can be 0 to disable the timeout and let the future return earlier.
293      * @return A future that completes with true if the subscribing worked, with false if the stateTopic is not set
294      *         and exceptionally otherwise.
295      */
296     public CompletableFuture<@Nullable Void> start(MqttBrokerConnection connection, ScheduledExecutorService scheduler,
297             int timeout) {
298         synchronized (futureLock) {
299             // if the connection is still the same, the subscription is still present, otherwise we need to renew
300             if ((hasSubscribed || !future.isDone()) && connection.equals(this.connection)) {
301                 return future;
302             }
303             hasSubscribed = false;
304
305             this.connection = connection;
306
307             if (config.stateTopic.isBlank()) {
308                 return CompletableFuture.completedFuture(null);
309             }
310
311             this.future = new CompletableFuture<>();
312         }
313         connection.subscribe(config.stateTopic, this).thenRun(() -> {
314             hasSubscribed = true;
315             logger.debug("Subscribed channel {} to topic: {}", this.channelUID, config.stateTopic);
316             if (timeout > 0 && !future.isDone()) {
317                 this.scheduledFuture = scheduler.schedule(this::receivedOrTimeout, timeout, TimeUnit.MILLISECONDS);
318             } else {
319                 receivedOrTimeout();
320             }
321         }).exceptionally(this::subscribeFail);
322         return future;
323     }
324
325     /**
326      * Return true if this channel has subscribed to its MQTT topics.
327      * You need to call {@link #start(MqttBrokerConnection, ScheduledExecutorService, int)} and
328      * have a stateTopic set, to subscribe this channel.
329      */
330     public boolean hasSubscribed() {
331         return this.hasSubscribed;
332     }
333
334     /**
335      * Publishes a value on MQTT. A command topic needs to be set in the configuration.
336      *
337      * @param command The command to send
338      * @return A future that completes with true if the publishing worked and false if it is a readonly topic
339      *         and exceptionally otherwise.
340      */
341     public CompletableFuture<Boolean> publishValue(Command command) {
342         final MqttBrokerConnection connection = this.connection;
343
344         if (connection == null) {
345             CompletableFuture<Boolean> f = new CompletableFuture<>();
346             f.completeExceptionally(new IllegalStateException(
347                     "The connection object has not been set. start() should have been called!"));
348             return f;
349         }
350
351         Command mqttCommandValue = cachedValue.parseCommand(command);
352         Value mqttFormatter = cachedValue;
353
354         if (readOnly) {
355             logger.debug(
356                     "You have tried to publish {} to the mqtt topic '{}' that was marked read-only. You can't 'set' anything on a sensor state topic for example.",
357                     mqttCommandValue, config.commandTopic);
358             return CompletableFuture.completedFuture(false);
359         }
360
361         // Outgoing transformations
362         if (outgoingTransformation.isPresent()) {
363             Command cValue = mqttCommandValue;
364             // Only pass numeric value for QuantityType.
365             if (mqttCommandValue instanceof QuantityType<?> qtCommandValue) {
366                 cValue = new DecimalType(qtCommandValue.toBigDecimal());
367             }
368             String commandString = mqttFormatter.getMQTTpublishValue(cValue, "%s");
369             Optional<String> transformedValue = outgoingTransformation.apply(commandString);
370             if (transformedValue.isEmpty()) {
371                 logger.debug("Transformation '{}' returned null on '{}', discarding message", outgoingTransformation,
372                         commandString);
373                 return CompletableFuture.completedFuture(false);
374             }
375
376             mqttFormatter = new TextValue();
377             mqttCommandValue = new StringType(transformedValue.get());
378         }
379
380         String commandString;
381
382         // Formatter: Applied before the channel state value is published to the MQTT broker.
383         if (config.formatBeforePublish.length() > 0) {
384             try {
385                 Command cValue = mqttCommandValue;
386                 // Only pass numeric value for QuantityType of format pattern is %s.
387                 if ((mqttCommandValue instanceof QuantityType<?> qtCommandValue)
388                         && ("%s".equals(config.formatBeforePublish) || "%S".equals(config.formatBeforePublish))) {
389                     cValue = new DecimalType(qtCommandValue.toBigDecimal());
390                 }
391                 commandString = mqttFormatter.getMQTTpublishValue(cValue, config.formatBeforePublish);
392             } catch (IllegalFormatException e) {
393                 logger.debug("Format pattern incorrect for {}", channelUID, e);
394                 commandString = mqttFormatter.getMQTTpublishValue(mqttCommandValue, null);
395             }
396         } else {
397             commandString = mqttFormatter.getMQTTpublishValue(mqttCommandValue, null);
398         }
399
400         int qos = (config.qos != null) ? config.qos : connection.getQos();
401
402         String commandTopic;
403         if (command.equals(StopMoveType.STOP) && !config.stopCommandTopic.isEmpty()) {
404             commandTopic = config.stopCommandTopic;
405         } else {
406             commandTopic = config.commandTopic;
407         }
408         return connection.publish(commandTopic, commandString.getBytes(), qos, config.retained);
409     }
410
411     /**
412      * @return The channelStateUpdateListener
413      */
414     public @Nullable ChannelStateUpdateListener getChannelStateUpdateListener() {
415         return channelStateUpdateListener;
416     }
417
418     /**
419      * @param channelStateUpdateListener The channelStateUpdateListener to set
420      */
421     public void setChannelStateUpdateListener(ChannelStateUpdateListener channelStateUpdateListener) {
422         this.channelStateUpdateListener = channelStateUpdateListener;
423     }
424
425     public @Nullable MqttBrokerConnection getConnection() {
426         return connection;
427     }
428
429     /**
430      * This is for tests only to inject a broker connection. Use
431      * {@link #start(MqttBrokerConnection, ScheduledExecutorService, int)} instead.
432      *
433      * @param connection MQTT Broker connection
434      */
435     public void setConnection(MqttBrokerConnection connection) {
436         this.connection = connection;
437     }
438 }