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) {
82 this.channelStateUpdateListener = channelStateUpdateListener;
83 this.channelUID = channelUID;
84 this.cachedValue = cachedValue;
85 this.readOnly = config.commandTopic.isBlank();
86 this.incomingTransformation = new ChannelTransformation(config.transformationPattern);
87 this.outgoingTransformation = new ChannelTransformation(config.transformationPatternOut);
90 public boolean isReadOnly() {
95 * Returns the cached value state object of this message subscriber.
97 * MQTT only notifies us once about a value, during the subscribe.
98 * The channel state therefore needs a cache for the current value.
99 * If MQTT has not yet published a value, the cache might still be in UNDEF state.
102 public Value getCache() {
107 * Return the channelUID
109 public ChannelUID channelUID() {
114 * Incoming message from the MqttBrokerConnection
116 * @param topic The topic. Is the same as the field stateTopic.
117 * @param payload The byte payload. Must be UTF8 encoded text or binary data.
120 public void processMessage(String topic, byte[] payload) {
121 final ChannelStateUpdateListener channelStateUpdateListener = this.channelStateUpdateListener;
122 if (channelStateUpdateListener == null) {
123 logger.warn("MQTT message received for topic {}, but MessageSubscriber object hasn't been started!", topic);
127 if (cachedValue.isBinary()) {
128 cachedValue.update(payload);
129 channelStateUpdateListener.updateChannelState(channelUID, cachedValue.getChannelState());
134 // String value: Apply transformations
135 String strValue = new String(payload, StandardCharsets.UTF_8);
136 if (incomingTransformation.isPresent()) {
137 Optional<String> transformedValue = incomingTransformation.apply(strValue);
138 if (transformedValue.isEmpty()) {
139 logger.debug("Transformation '{}' returned null on '{}', discarding message", strValue,
140 incomingTransformation);
144 strValue = transformedValue.get();
147 // Is trigger?: Special handling
148 if (config.trigger) {
149 channelStateUpdateListener.triggerChannel(channelUID, strValue);
154 Command command = TypeParser.parseCommand(cachedValue.getSupportedCommandTypes(), strValue);
155 if (command == null) {
156 logger.warn("Incoming payload '{}' on '{}' not supported by type '{}'", strValue, topic,
157 cachedValue.getClass().getSimpleName());
163 // Map the string to a command, update the cached value and post the command to the framework
165 parsedType = cachedValue.parseMessage(command);
166 } catch (IllegalArgumentException | IllegalStateException e) {
167 logger.warn("Command '{}' from channel '{}' not supported by type '{}': {}", strValue, channelUID,
168 cachedValue.getClass().getSimpleName(), e.getMessage());
173 if (parsedType instanceof State parsedState) {
174 cachedValue.update(parsedState);
176 // things that are only Commands _must_ be posted as a command (like STOP)
177 channelStateUpdateListener.postChannelCommand(channelUID, (Command) parsedType);
182 State newState = cachedValue.getChannelState();
183 // If the user explicitly wants a command sent, not an update, do that. But
184 // we have to check that the state is even possible to send as a command
186 if (config.postCommand && newState instanceof Command newCommand) {
187 channelStateUpdateListener.postChannelCommand(channelUID, newCommand);
189 channelStateUpdateListener.updateChannelState(channelUID, newState);
195 * Returns the state topic. Might be an empty string if this is a stateless channel (TRIGGER kind channel).
197 public String getStateTopic() {
198 return config.stateTopic;
202 * Return the command topic. Might be an empty string, if this is a read-only channel.
204 public String getCommandTopic() {
205 return config.commandTopic;
209 * Returns the channelType ID which also happens to be an item-type
211 public String getItemType() {
212 return cachedValue.getItemType();
216 * Returns true if this is a stateful channel.
218 public boolean isStateful() {
219 return config.retained;
223 * Removes the subscription to the state topic and resets the channelStateUpdateListener.
225 * @return A future that completes with true if unsubscribing from the state topic succeeded.
226 * It completes with false if no connection is established and completes exceptionally otherwise.
228 public CompletableFuture<@Nullable Void> stop() {
229 final MqttBrokerConnection connection = this.connection;
230 if (connection != null && !config.stateTopic.isBlank()) {
231 return connection.unsubscribe(config.stateTopic, this).thenRun(this::internalStop);
234 return CompletableFuture.completedFuture(null);
238 private void internalStop() {
239 logger.debug("Unsubscribed channel {} from topic: {}", this.channelUID, config.stateTopic);
240 this.connection = null;
241 this.channelStateUpdateListener = null;
242 hasSubscribed = false;
243 cachedValue.resetState();
246 private void receivedOrTimeout() {
247 final ScheduledFuture<?> scheduledFuture = this.scheduledFuture;
248 if (scheduledFuture != null) { // Cancel timeout
249 scheduledFuture.cancel(false);
250 this.scheduledFuture = null;
252 future.complete(null);
255 private @Nullable Void subscribeFail(Throwable e) {
256 final ScheduledFuture<?> scheduledFuture = this.scheduledFuture;
257 if (scheduledFuture != null) { // Cancel timeout
258 scheduledFuture.cancel(false);
259 this.scheduledFuture = null;
261 future.completeExceptionally(e);
266 * Subscribes to the state topic on the given connection and informs about updates on the given listener.
268 * @param connection A broker connection
269 * @param scheduler A scheduler to realize the timeout
270 * @param timeout A timeout in milliseconds. Can be 0 to disable the timeout and let the future return earlier.
271 * @return A future that completes with true if the subscribing worked, with false if the stateTopic is not set
272 * and exceptionally otherwise.
274 public CompletableFuture<@Nullable Void> start(MqttBrokerConnection connection, ScheduledExecutorService scheduler,
276 synchronized (futureLock) {
277 // if the connection is still the same, the subscription is still present, otherwise we need to renew
278 if ((hasSubscribed || !future.isDone()) && connection.equals(this.connection)) {
281 hasSubscribed = false;
283 this.connection = connection;
285 if (config.stateTopic.isBlank()) {
286 return CompletableFuture.completedFuture(null);
289 this.future = new CompletableFuture<>();
291 connection.subscribe(config.stateTopic, this).thenRun(() -> {
292 hasSubscribed = true;
293 logger.debug("Subscribed channel {} to topic: {}", this.channelUID, config.stateTopic);
294 if (timeout > 0 && !future.isDone()) {
295 this.scheduledFuture = scheduler.schedule(this::receivedOrTimeout, timeout, TimeUnit.MILLISECONDS);
299 }).exceptionally(this::subscribeFail);
304 * Return true if this channel has subscribed to its MQTT topics.
305 * You need to call {@link #start(MqttBrokerConnection, ScheduledExecutorService, int)} and
306 * have a stateTopic set, to subscribe this channel.
308 public boolean hasSubscribed() {
309 return this.hasSubscribed;
313 * Publishes a value on MQTT. A command topic needs to be set in the configuration.
315 * @param command The command to send
316 * @return A future that completes with true if the publishing worked and false if it is a readonly topic
317 * and exceptionally otherwise.
319 public CompletableFuture<Boolean> publishValue(Command command) {
320 final MqttBrokerConnection connection = this.connection;
322 if (connection == null) {
323 CompletableFuture<Boolean> f = new CompletableFuture<>();
324 f.completeExceptionally(new IllegalStateException(
325 "The connection object has not been set. start() should have been called!"));
329 Command mqttCommandValue = cachedValue.parseCommand(command);
330 Value mqttFormatter = cachedValue;
334 "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.",
335 mqttCommandValue, config.commandTopic);
336 return CompletableFuture.completedFuture(false);
339 // Outgoing transformations
340 if (outgoingTransformation.isPresent()) {
341 Command cValue = mqttCommandValue;
342 // Only pass numeric value for QuantityType.
343 if (mqttCommandValue instanceof QuantityType<?> qtCommandValue) {
344 cValue = new DecimalType(qtCommandValue.toBigDecimal());
347 String commandString = mqttFormatter.getMQTTpublishValue(cValue, "%s");
348 Optional<String> transformedValue = outgoingTransformation.apply(commandString);
349 if (transformedValue.isEmpty()) {
350 logger.debug("Transformation '{}' returned null on '{}', discarding message", outgoingTransformation,
352 return CompletableFuture.completedFuture(false);
355 mqttFormatter = new TextValue();
356 mqttCommandValue = new StringType(transformedValue.get());
359 String commandString;
361 // Formatter: Applied before the channel state value is published to the MQTT broker.
362 if (config.formatBeforePublish.length() > 0) {
364 Command cValue = mqttCommandValue;
365 // Only pass numeric value for QuantityType of format pattern is %s.
366 if ((mqttCommandValue instanceof QuantityType<?> qtCommandValue)
367 && ("%s".equals(config.formatBeforePublish) || "%S".equals(config.formatBeforePublish))) {
368 cValue = new DecimalType(qtCommandValue.toBigDecimal());
370 commandString = mqttFormatter.getMQTTpublishValue(cValue, config.formatBeforePublish);
371 } catch (IllegalFormatException e) {
372 logger.debug("Format pattern incorrect for {}", channelUID, e);
373 commandString = mqttFormatter.getMQTTpublishValue(mqttCommandValue, null);
376 commandString = mqttFormatter.getMQTTpublishValue(mqttCommandValue, null);
379 int qos = (config.qos != null) ? config.qos : connection.getQos();
382 if (command.equals(StopMoveType.STOP) && !config.stopCommandTopic.isEmpty()) {
383 commandTopic = config.stopCommandTopic;
385 commandTopic = config.commandTopic;
387 return connection.publish(commandTopic, commandString.getBytes(), qos, config.retained);
391 * @return The channelStateUpdateListener
393 public @Nullable ChannelStateUpdateListener getChannelStateUpdateListener() {
394 return channelStateUpdateListener;
398 * @param channelStateUpdateListener The channelStateUpdateListener to set
400 public void setChannelStateUpdateListener(ChannelStateUpdateListener channelStateUpdateListener) {
401 this.channelStateUpdateListener = channelStateUpdateListener;
404 public @Nullable MqttBrokerConnection getConnection() {
409 * This is for tests only to inject a broker connection. Use
410 * {@link #start(MqttBrokerConnection, ScheduledExecutorService, int)} instead.
412 * @param connection MQTT Broker connection
414 public void setConnection(MqttBrokerConnection connection) {
415 this.connection = connection;