Search in sources :

Example 1 with MqttBrokerConnection

use of org.openhab.core.io.transport.mqtt.MqttBrokerConnection in project openhab-addons by openhab.

the class IRobotConnectionHandler method disconnect.

public synchronized void disconnect() {
    Future<?> reconnect = this.reconnect;
    if (reconnect != null) {
        reconnect.cancel(false);
        this.reconnect = null;
    }
    MqttBrokerConnection connection = this.connection;
    if (connection != null) {
        connection.unsubscribe("#", this);
        CompletableFuture<Boolean> future = connection.stop();
        try {
            future.get(10, TimeUnit.SECONDS);
            if (logger.isTraceEnabled()) {
                logger.trace("MQTT disconnect successful");
            }
        } catch (InterruptedException | ExecutionException | TimeoutException exception) {
            logger.warn("MQTT disconnect failed: {}", exception.getMessage());
        }
        this.connection = null;
    }
}
Also used : MqttBrokerConnection(org.openhab.core.io.transport.mqtt.MqttBrokerConnection) ExecutionException(java.util.concurrent.ExecutionException) TimeoutException(java.util.concurrent.TimeoutException)

Example 2 with MqttBrokerConnection

use of org.openhab.core.io.transport.mqtt.MqttBrokerConnection in project openhab-addons by openhab.

the class IRobotConnectionHandler method connectionStateChanged.

@Override
public void connectionStateChanged(MqttConnectionState state, @Nullable Throwable error) {
    if (state == MqttConnectionState.CONNECTED) {
        MqttBrokerConnection connection = this.connection;
        // This would be very strange, but Eclipse forces us to do the check
        if (connection != null) {
            reconnect = null;
            // Roomba sends us two topics:
            // "wifistat" - reports signal strength and current robot position
            // "$aws/things/<BLID>/shadow/update" - the rest of messages
            // Subscribe to everything since we're interested in both
            connection.subscribe("#", this).exceptionally(exception -> {
                logger.warn("MQTT subscription failed: {}", exception.getMessage());
                return false;
            }).thenAccept(successful -> {
                if (successful && logger.isTraceEnabled()) {
                    logger.trace("MQTT subscription successful");
                } else {
                    logger.warn("MQTT subscription failed: Timeout");
                }
            });
        } else {
            logger.warn("Established connection without broker pointer");
        }
    } else {
        String message = (error != null) ? error.getMessage() : "Unknown reason";
        logger.warn("MQTT connection failed: {}", message);
    }
}
Also used : MqttBrokerConnection(org.openhab.core.io.transport.mqtt.MqttBrokerConnection) NonNullByDefault(org.eclipse.jdt.annotation.NonNullByDefault) Logger(org.slf4j.Logger) MqttConnectionObserver(org.openhab.core.io.transport.mqtt.MqttConnectionObserver) UTF_8(java.nio.charset.StandardCharsets.UTF_8) LoggerFactory(org.slf4j.LoggerFactory) TimeoutException(java.util.concurrent.TimeoutException) PeriodicReconnectStrategy(org.openhab.core.io.transport.mqtt.reconnect.PeriodicReconnectStrategy) IOException(java.io.IOException) CompletableFuture(java.util.concurrent.CompletableFuture) UnknownHostException(java.net.UnknownHostException) TRUST_MANAGERS(org.openhab.binding.irobot.internal.IRobotBindingConstants.TRUST_MANAGERS) InetAddress(java.net.InetAddress) ExecutionException(java.util.concurrent.ExecutionException) TimeUnit(java.util.concurrent.TimeUnit) Future(java.util.concurrent.Future) MqttConnectionState(org.openhab.core.io.transport.mqtt.MqttConnectionState) Nullable(org.eclipse.jdt.annotation.Nullable) MQTT_PORT(org.openhab.binding.irobot.internal.IRobotBindingConstants.MQTT_PORT) MqttMessageSubscriber(org.openhab.core.io.transport.mqtt.MqttMessageSubscriber) MqttBrokerConnection(org.openhab.core.io.transport.mqtt.MqttBrokerConnection)

Example 3 with MqttBrokerConnection

use of org.openhab.core.io.transport.mqtt.MqttBrokerConnection in project openhab-addons by openhab.

the class NhcMqttConnection2 method startConnection.

/**
 * Start a secure MQTT connection and subscribe to all topics.
 *
 * @param subscriber MqttMessageSubscriber that will handle received messages
 * @param cocoAddress IP Address of the Niko Connected Controller
 * @param port Port for MQTT communication with the Niko Connected Controller
 * @param token JWT token for the hobby profile
 * @throws MqttException
 */
synchronized void startConnection(String cocoAddress, int port, String profile, String token) throws MqttException {
    CompletableFuture<Boolean> future = stoppedFuture;
    if (future != null) {
        try {
            future.get(5000, TimeUnit.MILLISECONDS);
            logger.debug("finished stopping connection");
        } catch (InterruptedException | ExecutionException | TimeoutException ignore) {
            logger.debug("error stopping connection");
        }
        stoppedFuture = null;
    }
    logger.debug("starting connection...");
    this.cocoAddress = cocoAddress;
    this.port = port;
    this.profile = profile;
    this.token = token;
    MqttBrokerConnection connection = createMqttConnection();
    connection.addConnectionObserver(connectionObserver);
    mqttConnection = connection;
    try {
        if (connection.start().get(5000, TimeUnit.MILLISECONDS)) {
            if (subscribedFuture == null) {
                subscribedFuture = connection.subscribe("#", messageSubscriber);
            }
        } else {
            logger.debug("error connecting");
            throw new MqttException("Connection execution exception");
        }
    } catch (InterruptedException e) {
        logger.debug("connection interrupted exception");
        throw new MqttException("Connection interrupted exception");
    } catch (ExecutionException e) {
        logger.debug("connection execution exception", e.getCause());
        throw new MqttException("Connection execution exception");
    } catch (TimeoutException e) {
        logger.debug("connection timeout exception");
        throw new MqttException("Connection timeout exception");
    }
}
Also used : MqttBrokerConnection(org.openhab.core.io.transport.mqtt.MqttBrokerConnection) MqttException(org.openhab.core.io.transport.mqtt.MqttException) ExecutionException(java.util.concurrent.ExecutionException) TimeoutException(java.util.concurrent.TimeoutException)

Example 4 with MqttBrokerConnection

use of org.openhab.core.io.transport.mqtt.MqttBrokerConnection in project openhab-addons by openhab.

the class HomeAssistantMQTTImplementationTest method reconnectTest.

@Test
public void reconnectTest() throws InterruptedException, ExecutionException, TimeoutException {
    connection.removeConnectionObserver(failIfChange);
    connection.stop().get(2, TimeUnit.SECONDS);
    connection = new MqttBrokerConnection(embeddedConnection.getHost(), embeddedConnection.getPort(), embeddedConnection.isSecure(), "ha_mqtt");
    connection.start().get(2, TimeUnit.SECONDS);
}
Also used : MqttBrokerConnection(org.openhab.core.io.transport.mqtt.MqttBrokerConnection) Test(org.junit.jupiter.api.Test) JavaOSGiTest(org.openhab.core.test.java.JavaOSGiTest)

Example 5 with MqttBrokerConnection

use of org.openhab.core.io.transport.mqtt.MqttBrokerConnection in project openhab-addons by openhab.

the class HomeAssistantMQTTImplementationTest method beforeEach.

@BeforeEach
public void beforeEach() throws Exception {
    registerVolatileStorageService();
    configurationAdmin = getService(ConfigurationAdmin.class);
    mqttService = getService(MqttService.class);
    // Wait for the EmbeddedBrokerService internal connection to be connected
    embeddedConnection = new EmbeddedBrokerTools(configurationAdmin, mqttService).waitForConnection();
    connection = new MqttBrokerConnection(embeddedConnection.getHost(), embeddedConnection.getPort(), embeddedConnection.isSecure(), "ha_mqtt");
    connection.start().get(2, TimeUnit.SECONDS);
    assertThat(connection.connectionState(), is(MqttConnectionState.CONNECTED));
    // If the connection state changes in between -> fail
    connection.addConnectionObserver(failIfChange);
    // Create topic string and config for one example HA component (a Switch)
    final String config = "{'name':'testname','state_topic':'" + testObjectTopic + "/state','command_topic':'" + testObjectTopic + "/set'}";
    // Publish component configurations and component states to MQTT
    List<CompletableFuture<Boolean>> futures = new ArrayList<>();
    futures.add(embeddedConnection.publish(testObjectTopic + "/config", config.getBytes(), 0, true));
    futures.add(embeddedConnection.publish(testObjectTopic + "/state", "ON".getBytes(), 0, true));
    registeredTopics = futures.size();
    CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).get(2, TimeUnit.SECONDS);
    failure = null;
    doReturn(null).when(transformationServiceProvider).getTransformationService(any());
}
Also used : CompletableFuture(java.util.concurrent.CompletableFuture) MqttBrokerConnection(org.openhab.core.io.transport.mqtt.MqttBrokerConnection) ArrayList(java.util.ArrayList) MqttService(org.openhab.core.io.transport.mqtt.MqttService) ConfigurationAdmin(org.osgi.service.cm.ConfigurationAdmin) BeforeEach(org.junit.jupiter.api.BeforeEach)

Aggregations

MqttBrokerConnection (org.openhab.core.io.transport.mqtt.MqttBrokerConnection)32 Nullable (org.eclipse.jdt.annotation.Nullable)9 CompletableFuture (java.util.concurrent.CompletableFuture)8 TimeoutException (java.util.concurrent.TimeoutException)7 NonNullByDefault (org.eclipse.jdt.annotation.NonNullByDefault)7 ExecutionException (java.util.concurrent.ExecutionException)6 Logger (org.slf4j.Logger)6 LoggerFactory (org.slf4j.LoggerFactory)6 ArrayList (java.util.ArrayList)5 MqttConnectionState (org.openhab.core.io.transport.mqtt.MqttConnectionState)5 MqttService (org.openhab.core.io.transport.mqtt.MqttService)5 TimeUnit (java.util.concurrent.TimeUnit)4 MqttConnectionObserver (org.openhab.core.io.transport.mqtt.MqttConnectionObserver)4 IOException (java.io.IOException)3 List (java.util.List)3 Collectors (java.util.stream.Collectors)3 AbstractBrokerHandler (org.openhab.binding.mqtt.handler.AbstractBrokerHandler)3 MqttException (org.openhab.core.io.transport.mqtt.MqttException)3 Channel (org.openhab.core.thing.Channel)3 ConfigurationAdmin (org.osgi.service.cm.ConfigurationAdmin)3