2 * Copyright (c) 2010-2024 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.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;
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;
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}.
46 * @author David Graeff - Initial contribution
49 public class ChannelState implements MqttMessageSubscriber {
50 private final Logger logger = LoggerFactory.getLogger(ChannelState.class);
52 // Immutable channel configuration
53 protected final boolean readOnly;
54 protected final ChannelUID channelUID;
55 protected final ChannelConfig config;
58 protected final Value cachedValue;
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();
71 * Creates a new channel state.
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
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));
87 * Creates a new channel state.
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
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;
112 public boolean isReadOnly() {
113 return this.readOnly;
117 * Returns the cached value state object of this message subscriber.
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.
124 public Value getCache() {
129 * Return the channelUID
131 public ChannelUID channelUID() {
136 * Incoming message from the MqttBrokerConnection
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.
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);
149 if (cachedValue.isBinary()) {
150 cachedValue.update(payload);
151 channelStateUpdateListener.updateChannelState(channelUID, cachedValue.getChannelState());
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);
166 strValue = transformedValue.get();
169 // Is trigger?: Special handling
170 if (config.trigger) {
171 channelStateUpdateListener.triggerChannel(channelUID, strValue);
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());
185 // Map the string to a command, update the cached value and post the command to the framework
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());
195 if (parsedType instanceof State parsedState) {
196 cachedValue.update(parsedState);
198 // things that are only Commands _must_ be posted as a command (like STOP)
199 channelStateUpdateListener.postChannelCommand(channelUID, (Command) parsedType);
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
208 if (config.postCommand && newState instanceof Command newCommand) {
209 channelStateUpdateListener.postChannelCommand(channelUID, newCommand);
211 channelStateUpdateListener.updateChannelState(channelUID, newState);
217 * Returns the state topic. Might be an empty string if this is a stateless channel (TRIGGER kind channel).
219 public String getStateTopic() {
220 return config.stateTopic;
224 * Return the command topic. Might be an empty string, if this is a read-only channel.
226 public String getCommandTopic() {
227 return config.commandTopic;
231 * Returns the channelType ID which also happens to be an item-type
233 public String getItemType() {
234 return cachedValue.getItemType();
238 * Returns true if this is a stateful channel.
240 public boolean isStateful() {
241 return config.retained;
245 * Removes the subscription to the state topic and resets the channelStateUpdateListener.
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.
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);
256 return CompletableFuture.completedFuture(null);
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();
268 private void receivedOrTimeout() {
269 final ScheduledFuture<?> scheduledFuture = this.scheduledFuture;
270 if (scheduledFuture != null) { // Cancel timeout
271 scheduledFuture.cancel(false);
272 this.scheduledFuture = null;
274 future.complete(null);
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;
283 future.completeExceptionally(e);
288 * Subscribes to the state topic on the given connection and informs about updates on the given listener.
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.
296 public CompletableFuture<@Nullable Void> start(MqttBrokerConnection connection, ScheduledExecutorService scheduler,
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)) {
303 hasSubscribed = false;
305 this.connection = connection;
307 if (config.stateTopic.isBlank()) {
308 return CompletableFuture.completedFuture(null);
311 this.future = new CompletableFuture<>();
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);
321 }).exceptionally(this::subscribeFail);
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.
330 public boolean hasSubscribed() {
331 return this.hasSubscribed;
335 * Publishes a value on MQTT. A command topic needs to be set in the configuration.
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.
341 public CompletableFuture<Boolean> publishValue(Command command) {
342 final MqttBrokerConnection connection = this.connection;
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!"));
351 Command mqttCommandValue = cachedValue.parseCommand(command);
352 Value mqttFormatter = cachedValue;
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);
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());
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,
373 return CompletableFuture.completedFuture(false);
376 mqttFormatter = new TextValue();
377 mqttCommandValue = new StringType(transformedValue.get());
380 String commandString;
382 // Formatter: Applied before the channel state value is published to the MQTT broker.
383 if (config.formatBeforePublish.length() > 0) {
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());
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);
397 commandString = mqttFormatter.getMQTTpublishValue(mqttCommandValue, null);
400 int qos = (config.qos != null) ? config.qos : connection.getQos();
403 if (command.equals(StopMoveType.STOP) && !config.stopCommandTopic.isEmpty()) {
404 commandTopic = config.stopCommandTopic;
406 commandTopic = config.commandTopic;
408 return connection.publish(commandTopic, commandString.getBytes(), qos, config.retained);
412 * @return The channelStateUpdateListener
414 public @Nullable ChannelStateUpdateListener getChannelStateUpdateListener() {
415 return channelStateUpdateListener;
419 * @param channelStateUpdateListener The channelStateUpdateListener to set
421 public void setChannelStateUpdateListener(ChannelStateUpdateListener channelStateUpdateListener) {
422 this.channelStateUpdateListener = channelStateUpdateListener;
425 public @Nullable MqttBrokerConnection getConnection() {
430 * This is for tests only to inject a broker connection. Use
431 * {@link #start(MqttBrokerConnection, ScheduledExecutorService, int)} instead.
433 * @param connection MQTT Broker connection
435 public void setConnection(MqttBrokerConnection connection) {
436 this.connection = connection;