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.eclipse.jdt.annotation.Nullable;
19 import org.openhab.core.io.transport.mqtt.MqttConnectionState;
20 import org.openhab.core.io.transport.mqtt.MqttWillAndTestament;
21 import org.openhab.core.io.transport.mqtt.internal.Subscription;
22 import org.openhab.core.io.transport.mqtt.internal.client.MqttAsyncClientWrapper;
24 import com.hivemq.client.mqtt.MqttClientState;
27 * We need an extended MqttAsyncClientWrapper, that will, in respect to the success flags of the connection, immediately
28 * succeed or fail with publish, subscribe, unsubscribe, connect, disconnect.
30 * @author Jochen Klein - Initial contribution
33 public class MqttAsyncClientWrapperEx extends MqttAsyncClientWrapper {
35 private final MqttBrokerConnectionEx connection;
37 public MqttAsyncClientWrapperEx(MqttBrokerConnectionEx connection) {
39 this.connection = connection;
43 public CompletableFuture<?> connect(@Nullable MqttWillAndTestament lwt, int keepAliveInterval,
44 @Nullable String username, @Nullable String password) {
45 if (!connection.connectTimeout) {
46 connection.getCallback().onConnected(null);
47 connection.connectionStateOverwrite = MqttConnectionState.CONNECTED;
48 return CompletableFuture.completedFuture(null);
50 return new CompletableFuture<>();
54 public CompletableFuture<@Nullable Void> disconnect() {
55 if (connection.disconnectSuccess) {
56 connection.getCallback().onDisconnected(new Throwable("disconnect called"));
57 connection.connectionStateOverwrite = MqttConnectionState.DISCONNECTED;
58 return CompletableFuture.completedFuture(null);
60 return new CompletableFuture<>();
64 public MqttClientState getState() {
65 return MqttClientState.CONNECTED;
69 public CompletableFuture<?> publish(String topic, byte[] payload, boolean retain, int qos) {
70 return CompletableFuture.completedFuture(null);
74 public CompletableFuture<?> subscribe(String topic, int qos, Subscription subscription) {
75 if (connection.subscribeSuccess) {
76 return CompletableFuture.completedFuture(null);
78 return CompletableFuture.failedFuture(new Throwable("subscription failed"));
82 public CompletableFuture<?> unsubscribe(String topic) {
83 if (connection.unsubscribeSuccess) {
84 return CompletableFuture.completedFuture(null);
86 return CompletableFuture.failedFuture(new Throwable("unsubscription failed"));