Class MqttClient

  • All Implemented Interfaces:
    AutoCloseable, IMqttClient

    public class MqttClient
    extends Object
    implements IMqttClient
    Lightweight client for talking to an MQTT server using methods that block until an operation completes.

    This class implements the blocking IMqttClient client interface where all actions block until they have completed (or timed out). This implementation is compatible with MicroEJ runtime.

    An application can connect to an MQTT server using any kind of underlying transport layer that can be created from a SocketFactory (i.e. bi-directional lossless stream), which is likely one of:

    • A plain TCP socket
    • A secure SSL/TLS socket
    See Also:
    IMqttClient
    • Field Summary

      Fields 
      Modifier and Type Field Description
      protected long lastOutboundActivityMillis
      Client lock must be owned before reading or writing this field.
      protected static String MQTT
      The "MQTT" String constant.
      protected static int MQTT_QOS0
      MQTT QoS 0.
      protected static int MQTT_QOS1
      MQTT QoS 1.
      protected MqttException pendingMessageAckException
      The pending message acknowledgment exception returned by the server, or null if is there is no pending message or if the acknowledgment returned without error.
    • Constructor Summary

      Constructors 
      Constructor Description
      MqttClient​(String serverURI, String clientId)
      Create an MqttClient that can be used to communicate with an MQTT server.
    • Field Detail

      • pendingMessageAckException

        @Nullable
        protected MqttException pendingMessageAckException
        The pending message acknowledgment exception returned by the server, or null if is there is no pending message or if the acknowledgment returned without error.
      • lastOutboundActivityMillis

        protected long lastOutboundActivityMillis
        Client lock must be owned before reading or writing this field.
    • Constructor Detail

      • MqttClient

        public MqttClient​(String serverURI,
                          String clientId)
                   throws MqttException
        Create an MqttClient that can be used to communicate with an MQTT server.

        The address of a server can be specified on the constructor.

        The serverURI parameter is typically used with the the clientId parameter to form a key. The key is used to store and reference messages while they are being delivered. Hence the serverURI specified on the constructor must still be specified even if a list of servers is specified on an MqttConnectOptions object. The serverURI on the constructor must remain the same across restarts of the client for delivery of messages to be maintained from a given client to a given server or set of servers.

        The address of the server to connect to is specified as a URI. Two types of connection are supported tcp:// for a TCP connection and ssl:// for a TCP connection secured by SSL/TLS. For example:

        • tcp://localhost:1883
        • ssl://localhost:8883

        If the port is not specified, it will default to 1883 for tcp://" URIs, and 8883 for ssl:// URIs.

        A client identifier clientId must be specified and be less that 65535 characters. It must be unique across all clients connecting to the same server. The clientId is used by the server to store data related to the client, hence it is important that the clientId remain the same when connecting to a server if durable subscriptions or reliable messaging are required.

        SSL can be configured by supplying an javax.net.ssl.SSLSocketFactory - applications can use MqttConnectOptions.setSocketFactory(SocketFactory) to supply a factory with the appropriate SSL settings.

        Parameters:
        serverURI - the address of the server to connect to, specified as a URI.
        clientId - a client identifier that is unique on the server being connected to
        Throws:
        IllegalArgumentException - if the URI does not start with "tcp://" or "ssl://" or is invalid
        MqttException - if any other problem was encountered
    • Method Detail

      • connect

        public void connect​(MqttConnectOptions options)
                     throws MqttException
        Description copied from interface: IMqttClient
        Connects to an MQTT server using the specified options.

        The server to connect to is specified on the constructor. It is recommended to call IMqttClient.setCallback(MqttCallback) prior to connecting in order that messages destined for the client can be accepted as soon as the client is connected.

        This is a blocking method that returns once connect completes

        Specified by:
        connect in interface IMqttClient
        Parameters:
        options - a set of connection parameters that override the defaults.
        Throws:
        MqttException - for non security related problems including communication errors
      • disconnect

        public void disconnect()
                        throws MqttException
        Description copied from interface: IMqttClient
        Disconnects from the server.

        This is a blocking method that returns once disconnect completes

        Specified by:
        disconnect in interface IMqttClient
        Throws:
        MqttException - if a problem is encountered while disconnecting
      • subscribe

        public void subscribe​(String topicFilter)
                       throws MqttException
        Description copied from interface: IMqttClient
        Subscribe to a topic, which may include wildcards using a QoS of 1.
        Specified by:
        subscribe in interface IMqttClient
        Parameters:
        topicFilter - the topic to subscribe to, which can include wildcards.
        Throws:
        MqttException - if there was an error registering the subscription.
      • subscribe

        public void subscribe​(String topicFilter,
                              int qos)
                       throws MqttException
        Description copied from interface: IMqttClient
        Subscribe to a topic, which may include wildcards.
        Specified by:
        subscribe in interface IMqttClient
        Parameters:
        topicFilter - the topic to subscribe to, which can include wildcards.
        qos - the maximum quality of service at which to subscribe. Messages published at a lower quality of service will be received at the published QoS. Messages published at a higher quality of service will be received using the QoS specified on the subscribe.
        Throws:
        MqttException - if there was an error registering the subscription.
      • unsubscribe

        public void unsubscribe​(String topicFilter)
                         throws MqttException
        Description copied from interface: IMqttClient
        Requests the server unsubscribe the client from a topic.
        Specified by:
        unsubscribe in interface IMqttClient
        Parameters:
        topicFilter - the topic to unsubscribe from. It must match a topicFilter specified on the subscribe.
        Throws:
        MqttException - if there was an error unregistering the subscription.
      • publish

        public void publish​(String topic,
                            byte[] payload,
                            int qos,
                            boolean retained)
                     throws MqttException
        Description copied from interface: IMqttClient
        Publishes a message to a topic on the server and return once it is delivered.

        This is a convenience method, which will create a new MqttMessage object with a byte array payload and the specified QoS, and then publish it. All other values in the message will be set to the defaults.

        Specified by:
        publish in interface IMqttClient
        Parameters:
        topic - to deliver the message to, for example "finance/stock/ibm".
        payload - the byte array to use as the payload
        qos - the Quality of Service to deliver the message at. Valid values are 0, 1 or 2.
        retained - whether or not this message should be retained by the server.
        Throws:
        MqttException - for other errors encountered while publishing the message. For instance client not connected.
        See Also:
        IMqttClient.publish(String, MqttMessage), MqttMessage.setQos(int), MqttMessage.setRetained(boolean)
      • publish

        public void publish​(String topic,
                            MqttMessage message)
                     throws MqttException
        Description copied from interface: IMqttClient
        Publishes a message to a topic on the server.

        Delivers a message to the server at the requested quality of service and returns control once the message has been delivered.

        This is a blocking method that returns once publish completes

        Specified by:
        publish in interface IMqttClient
        Parameters:
        topic - to deliver the message to, for example "finance/stock/ibm".
        message - to delivery to the server
        Throws:
        MqttException - for other errors encountered while publishing the message. For instance client not connected.
      • close

        public void close()
                   throws MqttException
        Description copied from interface: IMqttClient
        Close the client Releases all resource associated with the client. After the client has been closed it cannot be reused. For instance attempts to connect will fail.
        Specified by:
        close in interface AutoCloseable
        Specified by:
        close in interface IMqttClient
        Throws:
        MqttException - if the client is not disconnected.
      • getClientId

        public String getClientId()
        Description copied from interface: IMqttClient
        Returns the client ID used by this client.

        All clients connected to the same server or server farm must have a unique ID.

        Specified by:
        getClientId in interface IMqttClient
        Returns:
        the client ID used by this client.
      • getServerURI

        public String getServerURI()
        Description copied from interface: IMqttClient
        Returns the address of the server used by this client, as a URI.

        The format is the same as specified on the constructor.

        Specified by:
        getServerURI in interface IMqttClient
        Returns:
        the server's address, as a URI String.
        See Also:
        MqttClient(String, String)
      • isConnected

        public boolean isConnected()
        Description copied from interface: IMqttClient
        Determines if this client is currently connected to the server.
        Specified by:
        isConnected in interface IMqttClient
        Returns:
        true if connected, false otherwise.
      • setCallback

        public void setCallback​(MqttCallback callback)
        Description copied from interface: IMqttClient
        Sets the callback listener to use for events that happen asynchronously.

        There are a number of events that listener will be notified about. These include:

        • A new message has arrived and is ready to be processed
        • The connection to the server has been lost
        • Delivery of a message to the server has completed.
        Specified by:
        setCallback in interface IMqttClient
        Parameters:
        callback - the class to callback when for events related to the client
        See Also:
        MqttCallback