2 * Copyright (c) 2010-2023 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.handler;
15 import java.util.concurrent.CompletableFuture;
17 import org.eclipse.jdt.annotation.NonNullByDefault;
18 import org.openhab.core.io.transport.mqtt.MqttBrokerConnection;
19 import org.openhab.core.io.transport.mqtt.MqttMessageSubscriber;
20 import org.openhab.core.thing.ChannelUID;
23 * Subscribes to a state topic and calls {@link AbstractBrokerHandler#triggerChannel(ChannelUID, String)} if a value got
26 * @author David Graeff - Initial contribution
29 public class PublishTriggerChannel implements MqttMessageSubscriber {
30 private final MqttBrokerConnection connection;
31 private final PublishTriggerChannelConfig config;
32 private final ChannelUID uid;
33 private final AbstractBrokerHandler handler;
35 PublishTriggerChannel(PublishTriggerChannelConfig config, ChannelUID uid, MqttBrokerConnection connection,
36 AbstractBrokerHandler handler) {
39 this.connection = connection;
40 this.handler = handler;
43 CompletableFuture<Boolean> start() {
44 return stop().thenCompose(b -> connection.subscribe(config.stateTopic, this));
48 public void processMessage(String topic, byte[] payload) {
49 String value = new String(payload);
51 String expectedPayload = config.payload;
52 if (expectedPayload != null && !value.equals(expectedPayload)) {
55 if (config.separator.isEmpty()) {
56 handler.triggerChannel(uid, value);
58 handler.triggerChannel(uid, topic + config.separator + value);
62 public CompletableFuture<Boolean> stop() {
63 return connection.unsubscribe(config.stateTopic, this);