Java Code Examples for org.eclipse.paho.client.mqttv3.MqttAsyncClient#isConnected()

The following examples show how to use org.eclipse.paho.client.mqttv3.MqttAsyncClient#isConnected() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: MqttBrokerConnection.java    From smarthome with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Add a new message consumer to this connection. Multiple subscribers with the same
 * topic are allowed. This method will not protect you from adding a subscriber object
 * multiple times!
 *
 * If there is a retained message for the topic, you are guaranteed to receive a callback
 * for each new subscriber, even for the same topic.
 *
 * @param topic The topic to subscribe to.
 * @param subscriber The callback listener for received messages for the given topic.
 * @return Completes with true if successful. Completes with false if not connected yet. Exceptionally otherwise.
 */
public CompletableFuture<Boolean> subscribe(String topic, MqttMessageSubscriber subscriber) {
    CompletableFuture<Boolean> future = new CompletableFuture<Boolean>();
    synchronized (subscribers) {
        TopicSubscribers subscriberList = subscribers.getOrDefault(topic, new TopicSubscribers(topic));
        subscribers.put(topic, subscriberList);
        subscriberList.add(subscriber);
    }
    final MqttAsyncClient client = this.client;
    if (client == null) {
        future.completeExceptionally(new Exception("No MQTT client"));
        return future;
    }
    if (client.isConnected()) {
        try {
            client.subscribe(topic, qos, future, actionCallback);
        } catch (org.eclipse.paho.client.mqttv3.MqttException e) {
            future.completeExceptionally(e);
        }
    } else {
        // The subscription will be performed on connecting.
        future.complete(false);
    }
    return future;
}
 
Example 2
Source File: MqttBrokerConnection.java    From smarthome with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Subscribes to a topic on the given connection, but does not alter the subscriber list.
 *
 * @param topic The topic to subscribe to.
 * @return Completes with true if successful. Exceptionally otherwise.
 */
protected CompletableFuture<Boolean> subscribeRaw(String topic) {
    logger.trace("subscribeRaw message consumer for topic '{}' from broker '{}'", topic, host);
    CompletableFuture<Boolean> future = new CompletableFuture<Boolean>();
    try {
        MqttAsyncClient client = this.client;
        if (client != null && client.isConnected()) {
            client.subscribe(topic, qos, future, actionCallback);
        } else {
            future.complete(false);
        }
    } catch (org.eclipse.paho.client.mqttv3.MqttException e) {
        logger.info("Error subscribing to topic {}", topic, e);
        future.completeExceptionally(e);
    }
    return future;
}
 
Example 3
Source File: MqttBrokerConnection.java    From smarthome with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Unsubscribes from a topic on the given connection, but does not alter the subscriber list.
 *
 * @param client The client connection
 * @param topic The topic to unsubscribe from
 * @return Completes with true if successful. Completes with false if no broker connection is established.
 *         Exceptionally otherwise.
 */
protected CompletableFuture<Boolean> unsubscribeRaw(MqttAsyncClient client, String topic) {
    logger.trace("Unsubscribing message consumer for topic '{}' from broker '{}'", topic, host);
    CompletableFuture<Boolean> future = new CompletableFuture<Boolean>();
    try {
        if (client.isConnected()) {
            client.unsubscribe(topic, future, actionCallback);
        } else {
            future.complete(false);
        }
    } catch (org.eclipse.paho.client.mqttv3.MqttException e) {
        logger.info("Error unsubscribing topic from broker", e);
        future.completeExceptionally(e);
    }
    return future;
}
 
Example 4
Source File: MqttBrokerConnection.java    From smarthome with Eclipse Public License 2.0 4 votes vote down vote up
/**
 * Unsubscribes from all subscribed topics, stops the reconnect strategy, disconnect and close the client.
 *
 * You can re-establish a connection calling {@link #start()} again. Do not call start, before the closing process
 * has finished completely.
 *
 * @return Returns a future that completes as soon as the disconnect process has finished.
 */
public CompletableFuture<Boolean> stop() {
    MqttAsyncClient client = this.client;
    if (client == null) {
        return CompletableFuture.completedFuture(true);
    }

    logger.trace("Closing the MQTT broker connection '{}'", host);

    // Abort a connection attempt
    isConnecting = false;

    // Cancel the timeout future. If stop is called we can safely assume there is no interest in a connection
    // anymore.
    cancelTimeoutFuture();

    // Stop the reconnect strategy
    if (reconnectStrategy != null) {
        reconnectStrategy.stop();
    }

    CompletableFuture<Boolean> future = new CompletableFuture<Boolean>();
    // Close connection
    if (client.isConnected()) {
        // We need to thread change here. Because paho does not allow to disconnect within a callback method
        unsubscribeAll().thenRunAsync(() -> {
            try {
                client.disconnect(100).waitForCompletion(100);
                if (client.isConnected()) {
                    client.disconnectForcibly();
                }
                future.complete(true);
            } catch (org.eclipse.paho.client.mqttv3.MqttException e) {
                logger.debug("Error while closing connection to broker", e);
                future.complete(false);
            }
        });
    } else {
        future.complete(true);
    }

    return future.thenApply(this::finalizeStopAfterDisconnect);
}