Class MqttBrokerConnection


  • @NonNullByDefault
    public class MqttBrokerConnection
    extends Object
    An MQTTBrokerConnection represents a single client connection to a MQTT broker. When a connection to an MQTT broker is lost, it will try to reconnect every 60 seconds.
    Author:
    Davy Vanherbergen - Initial contribution, David Graeff - All operations are async now. More flexible sslContextProvider and reconnectStrategy added., Markus Rathgeb - added connection state callback, Jan N. Klug - changed from PAHO to HiveMQ client
    • Constructor Detail

      • MqttBrokerConnection

        public MqttBrokerConnection​(String host,
                                    @Nullable Integer port,
                                    boolean secure,
                                    @Nullable String clientId)
        Create a new TCP MQTT3 client connection to a server with the given host and port.
        Parameters:
        host - A host name or address
        port - A port or null to select the default port for a secure or insecure connection
        secure - A secure connection
        clientId - Client id. Each client on a MQTT server has a unique client id. Sometimes client ids are used for access restriction implementations. If none is specified, a default is generated. The client id cannot be longer than 65535 characters.
        Throws:
        IllegalArgumentException - If the client id or port is not valid.
      • MqttBrokerConnection

        @Deprecated
        public MqttBrokerConnection​(MqttBrokerConnection.Protocol protocol,
                                    String host,
                                    @Nullable Integer port,
                                    boolean secure,
                                    @Nullable String clientId)
        Deprecated.
        Create a new MQTT3 client connection to a server with the given protocol, mqtt client version, host and port.
        Parameters:
        protocol - The transport protocol
        host - A host name or address
        port - A port or null to select the default port for a secure or insecure connection
        secure - A secure connection
        clientId - Client id. Each client on a MQTT server has a unique client id. Sometimes client ids are used for access restriction implementations. If none is specified, a default is generated. The client id cannot be longer than 65535 characters.
        Throws:
        IllegalArgumentException - If the client id or port is not valid.
      • MqttBrokerConnection

        public MqttBrokerConnection​(MqttBrokerConnection.Protocol protocol,
                                    MqttBrokerConnection.MqttVersion mqttVersion,
                                    String host,
                                    @Nullable Integer port,
                                    boolean secure,
                                    @Nullable String clientId)
        Create a new MQTT client connection to a server with the given protocol, host and port.
        Parameters:
        protocol - The transport protocol
        mqttVersion - The version of the MQTT client (v3 or v5)
        host - A host name or address
        port - A port or null to select the default port for a secure or insecure connection
        secure - A secure connection
        clientId - Client id. Each client on a MQTT server has a unique client id. Sometimes client ids are used for access restriction implementations. If none is specified, a default is generated. The client id cannot be longer than 65535 characters.
        Throws:
        IllegalArgumentException - If the client id or port is not valid.
    • Method Detail

      • setReconnectStrategy

        public void setReconnectStrategy​(AbstractReconnectStrategy reconnectStrategy)
        Set the reconnect strategy. The implementor will be called when the connection state to the MQTT broker changed. The reconnect strategy will not be informed if the initial connection to the broker timed out. You need a timeout executor additionally, see setTimeoutExecutor(ScheduledExecutorService, int).
        Parameters:
        reconnectStrategy - The reconnect strategy. May not be null.
      • getReconnectStrategy

        public @Nullable AbstractReconnectStrategy getReconnectStrategy()
        Returns:
        Return the reconnect strategy
      • setTimeoutExecutor

        public void setTimeoutExecutor​(@Nullable ScheduledExecutorService executor,
                                       int timeoutInMS)
        Set a timeout executor. If none is set, you will not be notified of connection timeouts, this also includes a non-firing reconnect strategy. The default executor is none.
        Parameters:
        executor - One timer will be created when a connection attempt happens
        timeoutInMS - Timeout in milliseconds
      • setTrustManagers

        public void setTrustManagers​(TrustManager[] trustManagers)
      • getTrustManagers

        public TrustManager[] getTrustManagers()
      • getHost

        public String getHost()
        Get the MQTT broker host
      • getPort

        public int getPort()
        Get the MQTT broker port
      • isSecure

        public boolean isSecure()
        Return true if this is or will be an encrypted connection to the broker
      • setCredentials

        public void setCredentials​(@Nullable String user,
                                   @Nullable String password)
        Set the optional user name and optional password to use when connecting to the MQTT broker. The connection needs to be restarted for the new settings to take effect.
        Parameters:
        user - Name to use for connection.
        password - The password
      • getPassword

        public @Nullable String getPassword()
        Returns:
        connection password.
      • getUser

        public @Nullable String getUser()
        Returns:
        optional user name for the MQTT connection.
      • getQos

        public int getQos()
        Returns:
        quality of service level.
      • setQos

        public void setQos​(int qos)
        Set quality of service. Valid values are 0, 1, 2 and mean "at most once", "at least once" and "exactly once" respectively. The connection needs to be restarted for the new settings to take effect.
        Parameters:
        qos - level.
      • isRetain

        @Deprecated
        public boolean isRetain()
        Deprecated.
        use retain flags on message publish instead
        Returns:
        true if newly messages sent to the broker should be retained by the broker.
      • setRetain

        @Deprecated
        public void setRetain​(boolean retain)
        Deprecated.
        Set whether newly published messages should be retained by the broker. use retain flags on message publish instead
        Parameters:
        retain - true to retain.
      • getLastWill

        public @Nullable MqttWillAndTestament getLastWill()
        Return the last will object or null if there is none.
      • setLastWill

        public void setLastWill​(@Nullable MqttWillAndTestament lastWill,
                                boolean applyImmediately)
                         throws org.osgi.service.cm.ConfigurationException,
                                MqttException
        Set the last will object.
        Parameters:
        lastWill - The last will object or null.
        applyImmediately - If true, the connection will stopped and started for the new last-will to take effect immediately.
        Throws:
        MqttException
        org.osgi.service.cm.ConfigurationException
      • setLastWill

        public void setLastWill​(@Nullable MqttWillAndTestament lastWill)
        Set the last will object. The connection needs to be restarted for the new settings to take effect.
        Parameters:
        lastWill - The last will object or null.
      • setPersistencePath

        @Deprecated
        public void setPersistencePath​(@Nullable Path persistencePath)
        Deprecated.
        Sets the path for the persistence storage. A persistence mechanism is necessary to enable reliable messaging. For messages sent at qualities of service (QoS) 1 or 2 to be reliably delivered, messages must be stored (on both the client and server) until the delivery of the message is complete. If messages are not safely stored when being delivered then a failure in the client or server can result in lost messages. A file persistence storage is used that uses the given path. If the path does not exist it will be created on runtime (if possible). If it is set to null a implementation specific default path is used.
        Parameters:
        persistencePath - the path that should be used to store persistent data
      • getClientId

        public String getClientId()
        Get client id to use when connecting to the broker.
        Returns:
        value clientId to use.
      • setKeepAliveInterval

        public void setKeepAliveInterval​(int keepAliveInterval)
        Set the keep alive interval. The default interval is 60 seconds. If no heartbeat is received within this timeframe, the connection will be considered dead. Set this to a higher value on systems which may not always be able to process the heartbeat in time.
        Parameters:
        keepAliveInterval - interval in seconds
      • getKeepAliveInterval

        public int getKeepAliveInterval()
        Return the keep alive internal in seconds
      • setSSLContextProvider

        @Deprecated
        public void setSSLContextProvider​(SSLContextProvider sslContextProvider)
        Deprecated.
        Set the ssl context provider. The default provider is {@see AcceptAllCertifcatesSSLContext}.
      • subscribe

        public CompletableFuture<Boolean> subscribe​(String topic,
                                                    MqttMessageSubscriber subscriber)
        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.
        Parameters:
        topic - The topic to subscribe to.
        subscriber - The callback listener for received messages for the given topic.
        Returns:
        Completes with true if successful. Completes with false if not connected yet. Exceptionally otherwise.
      • subscribeRaw

        protected CompletableFuture<Boolean> subscribeRaw​(String topic)
        Subscribes to a topic on the given connection, but does not alter the subscriber list.
        Parameters:
        topic - The topic to subscribe to.
        Returns:
        Completes with true if successful. Exceptionally otherwise.
      • unsubscribe

        public CompletableFuture<Boolean> unsubscribe​(String topic,
                                                      MqttMessageSubscriber subscriber)
        Remove a previously registered consumer from this connection. If no more consumers are registered for a topic, the topic will be unsubscribed from.
        Parameters:
        topic - The topic to unsubscribe from.
        subscriber - The callback listener to remove.
        Returns:
        Completes with true if successful. Exceptionally otherwise.
      • unsubscribeRaw

        protected CompletableFuture<Boolean> unsubscribeRaw​(org.eclipse.smarthome.io.transport.mqtt.internal.client.MqttAsyncClientWrapper client,
                                                            String topic)
        Unsubscribes from a topic on the given connection, but does not alter the subscriber list.
        Parameters:
        client - The client connection
        topic - The topic to unsubscribe from
        Returns:
        Completes with true if successful. Completes with false if no broker connection is established. Exceptionally otherwise.
      • addConnectionObserver

        public void addConnectionObserver​(MqttConnectionObserver connectionObserver)
        Add a new connection observer to this connection.
        Parameters:
        connectionObserver - The connection observer that should be added.
      • removeConnectionObserver

        public void removeConnectionObserver​(MqttConnectionObserver connectionObserver)
        Remove a previously registered connection observer from this connection.
        Parameters:
        connectionObserver - The connection observer that should be removed.
      • hasConnectionObservers

        public boolean hasConnectionObservers()
        Return true if there are connection observers registered via addConnectionObserver().
      • start

        public CompletableFuture<Boolean> start()
        This will establish a connection to the MQTT broker and if successful, notify all publishers and subscribers that the connection has become active. This method will do nothing if there is already an active connection.
        Returns:
        Returns a future that completes with true if already connected or connecting, completes with false if a connection timeout has happened and completes exceptionally otherwise.
      • createClient

        protected org.eclipse.smarthome.io.transport.mqtt.internal.client.MqttAsyncClientWrapper createClient()
      • finalizeStopAfterDisconnect

        protected boolean finalizeStopAfterDisconnect​(boolean v)
        After a successful disconnect, the underlying library objects need to be closed and connection observers want to be notified.
        Parameters:
        v - A passthrough boolean value
        Returns:
        Returns the value of the parameter v.
      • unsubscribeAll

        public CompletableFuture<Void> unsubscribeAll()
        Unsubscribe from all topics
        Returns:
        Returns a future that completes as soon as all subscriptions have been canceled.
      • stop

        public CompletableFuture<Boolean> stop()
        Unsubscribes from all subscribed topics, stops the reconnect strategy, disconnect and close the client. You can re-establish a connection calling start() again. Do not call start, before the closing process has finished completely.
        Returns:
        Returns a future that completes as soon as the disconnect process has finished.
      • publish

        @Deprecated
        public void publish​(String topic,
                            byte[] payload,
                            MqttActionCallback listener)
        Deprecated.
        Publish a message to the broker.
        Parameters:
        topic - The topic
        payload - The message payload
        listener - A listener to be notified of success or failure of the delivery.
      • publish

        @Deprecated
        public void publish​(String topic,
                            byte[] payload,
                            int qos,
                            boolean retain,
                            MqttActionCallback listener)
        Deprecated.
        Publish a message to the broker with the given QoS and retained flag.
        Parameters:
        topic - The topic
        payload - The message payload
        qos - The quality of service for this message
        retain - Set to true to retain the message on the broker
        listener - A listener to be notified of success or failure of the delivery.
      • publish

        public CompletableFuture<Boolean> publish​(String topic,
                                                  byte[] payload)
        Publish a message to the broker.
        Parameters:
        topic - The topic
        payload - The message payload
        Returns:
        Returns a future that completes with a result of true if the publishing succeeded and completes exceptionally on an error or with a result of false if no broker connection is established.
      • publish

        public CompletableFuture<Boolean> publish​(String topic,
                                                  byte[] payload,
                                                  int qos,
                                                  boolean retain)
        Publish a message to the broker with the given QoS and retained flag.
        Parameters:
        topic - The topic
        payload - The message payload
        qos - The quality of service for this message
        retain - Set to true to retain the message on the broker
        Returns:
        Returns a future that completes with a result of true if the publishing succeeded and completes exceptionally on an error or with a result of false if no broker connection is established.
      • cancelTimeoutFuture

        protected void cancelTimeoutFuture()
        The connection process is limited by a timeout, realized with a CompletableFuture. Cancel that future now, if it exists.