]> git.basschouten.com Git - openhab-addons.git/blob
c6b72da0e0076c0d6b7a2dd36ddc1c4e587de26f
[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.handler;
14
15 import java.util.concurrent.CompletableFuture;
16
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;
21
22 /**
23  * Subscribes to a state topic and calls {@link AbstractBrokerHandler#triggerChannel(ChannelUID, String)} if a value got
24  * received.
25  *
26  * @author David Graeff - Initial contribution
27  */
28 @NonNullByDefault
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;
34
35     PublishTriggerChannel(PublishTriggerChannelConfig config, ChannelUID uid, MqttBrokerConnection connection,
36             AbstractBrokerHandler handler) {
37         this.config = config;
38         this.uid = uid;
39         this.connection = connection;
40         this.handler = handler;
41     }
42
43     CompletableFuture<Boolean> start() {
44         return stop().thenCompose(b -> connection.subscribe(config.stateTopic, this));
45     }
46
47     @Override
48     public void processMessage(String topic, byte[] payload) {
49         String value = new String(payload);
50         // Check condition
51         String expectedPayload = config.payload;
52         if (expectedPayload != null && !value.equals(expectedPayload)) {
53             return;
54         }
55         if (config.separator.isEmpty()) {
56             handler.triggerChannel(uid, value);
57         } else {
58             handler.triggerChannel(uid, topic + config.separator + value);
59         }
60     }
61
62     public CompletableFuture<Boolean> stop() {
63         return connection.unsubscribe(config.stateTopic, this);
64     }
65 }