Interface: MqttClient

MqttClient

Interface to be used for communicating with an MQTT broker. An MqttClient instance actually acts as MQTT client.

MqttClient enables a virtual end-to-end connection to the broker as if there was a direct link between the two end points. A virtual end-to-end connection comprises the following two distinct links:

  • MQTT channel, which is the logical channel established over the physical MQTT.Cool connection, between MqttClient and the MQTT.Cool server.
  • broker connection, which is the physical MQTT connection between the MQTT.Cool server and the MQTT broker.
In an end-to-end connection, MQTT.Cool takes the role of a real MQTT server proxy, as it acts as an intermediary for the MQTT Control Packets wrapped into MQTT.Cool Protocol messages and transported over the MQTT channel, as well as for the MQTT Control Packets transported as is over the broker connection.

Once obtained by invoking the MQTTCoolSession#createClient method, an MqttClient object is already configured to open a connection to the target MQTT broker.

Based on the way a broker connection is managed on the server side, an end-to-end connection can be of two types, dedicated or shared:

  • Dedicated End-to-End Connection.

    For each MqttClient that is provided with a valid client identifier at the time of creation through MQTTCoolSession, MQTT.Cool establishes on the server side a dedicated broker connection devoted to carrying all the messages to be exchanged with the target MQTT server. As a first consequence, if another MqttClient object or any other generic external MQTT client connects to the same MQTT broker using an identical client identifier, the connection will be closed as per the MQTT Protocol Specifications.

    A dedicated end-to-end connection guarantees full support of the following features:

    • QoS Levels 0,1, and 2
    • persistence of the Session state
    • Will Message

    Note that the MQTT.Cool server does not take any active role in the management of the Session state, which is, on the contrary, maintained exclusively by the two ends of the connection: the MQTT broker and the MqttClient instance.

    In a dedicated end-to-end connection, the life-cycle events relative to MqttClient, MQTT channel, and dedicated broker connection are tied together, namely:

    • A connection request initiated by MqttClient (which means a newly created MQTT channel) will be propagated up to the MQTT broker through the establishment of a new dedicated broker connection.
    • A disconnection request initiated by MqttClient (which means the closure of the MQTT channel) will be propagated up to the MQTT broker, which in turn will close the dedicated broker connection.
    • An interruption of the dedicated broker connection (due to any network issue or to a problem in the MQTT broker process) will be propagated back to MqttClient, which in turn will disconnect from MQTT.cool by closing the MQTT channel.
    • An interruption of the MQTT.Cool connection on the client side (due to any network issue or to an explicit MQTTCoolSession closing) will be propagated up to the MQTT broker by shutting down the dedicated broker connection.
    • Any MQTT.Cool server failure will cause interruption of both the dedicated broker connection on the server side and the MQTT.Cool connection on the client
    • side.
    Note that any issue on the MQTT.Cool connection detected on the client side will cause the MqttClient instance to try a reconnection (see MqttClient#onReconnectionStart).
  • Shared End-to-End Connection

    A shared end-to-end connection is realized when MQTT.Cool holds a single broker connection that will be shared among all those MqttClient instances (even hosted on different network locations) with the following common characteristics:

    1. No client identifier has been passed at the time of creation from MQTTCoolSession.
    2. Connect to the same MQTT broker, along with identical username and password, if any.

    By exploiting this mechanism, MQTT.Cool drastically reduces the number of newly created MQTT connections to the broker, with the purpose of optimizing the server side resources.

    Futhermore, all the subscriptions to the same topic filter requested by the sharing clients will be logically merged into one single MQTT subscription, which is actually activated on the shared broker connection. This enables offloading the fan out to MQTT.Cool, as it will be responsible for propagating messages flowing on the MQTT channel up to all subscribing clients.

    The following constraints apply to shared connections:

    • QoS levels 1 and 2 are only partially supported.
    • The ClientId cannot be specified explicitly; on the contrary, it will be generated by appending a random string to the clientid_prefix parameter to be configured in mqtt_master_connector_conf.xml.
    • Session persistence is not supported, which means that the Clean Session flag must be set to true (or left unchanged).
    • Will Message cannot be specified explicitly on the client side, but only globally and for all clients sharing a connection, once again through the mqtt_master_connector_conf.xml file.

    In a shared end-to-end connection, the life-cycle events relative to MqttClient, MQTT channel, and shared broker connection are only partially tied together, namely:

    • A connection request initiated by MqttClient implies that the newly created MQTT channel will be logically joined to an already active shared broker connection; the shared MQTT connection will be established only the very first time that an MqttClient instance connects to the broker.
    • A disconnection request initiated by MqttClient (which means closure of the MQTT channel) will cause only a logical detaching from the shared broker connection, which will be closed gracefully (that is, via an explicit DISCONNECT Control Packet) only the very last time that an MqttClient instance disconnects from the broker.
    • An interruption of the shared broker connection (due to any network issue or to a problem in the MQTT broker process) will be propagated back to all sharing MqttClient instances, which in turn will disconnect from MQTT.Cool by closing the relative MQTT channels.
    • An interruption of the MQTT.Cool connection on the client side (due to any network issue or to an explicit MQTTCoolSession closing) will be managed by MQTT.Cool as a logical detaching of all the engaged MQTT channels from the shared broker connection, which will be closed gracefully only when no more MQTT channels are attached.
    • Any MQTT.Cool server failure will cause the interruption of the shared broker connection on the server side a well as all the engaged MQTT.cool connections on the client side.
    Note that any issue on the MQTT.Cool connection detected on the client side will cause the MqttClient instance to try a reconnection (see MqttClient#onReconnectionStart).

Members

onConnectionLost :OnConnectionLost

The property to be bound to the callback function which will be invoked when the end-to-end connection is lost.

The end-to-end connection is lost when one of the followings condition occurs:

  • A regular disconnection initiated on the client side, through invocation of the MqttClient#disconnect method.
  • A disconnection from MQTT.Cool triggered on the client side, through invocation of the MQTTCoolSession#close method on the same MQTTCoolSession instance that originated this MqttClient object.
  • An interruption of the broker connection.
  • Stop of the reconnection attempts that follow an interruption of the MQTT.Cool connection.

After losing the connection, the MqttClient instance switches to the disconnected status, from which it would be possible to start a new connection.

When setting this property, an Error is thrown if the provided value is not of function type.

Type:

onMessageArrived :OnMessageArrived

The property to be bound to the callback function invoked upon receiving an Application Message sent by the MQTT broker.

An Application Message is sent by the MQTT broker to MQTT.Cool, which then forwards it to the MqttClient instance after appropriate processing.

On the client side, the message handling is based on the following factors:

  • The QoS level at which the MQTT broker sends the message.
  • The current end-to-end connection type (shared or dedicated).
  • Whether the session is persistent, which is allowed only in the case of dedicated connection.

In particular:

  • For a shared connection and a dedicated connection without session persistence, the invocation occurs when MQTT.Cool forwards the message to the client as soon as the delivery of the Control Packets exchanged on the server side and relative to the delivery protocol for the specified QoS level, has been completed.

    Furthermore, for a shared connection the same message is forwarded to all the other MqttClient instances that share the broker connection and have subscribed to the same topic filter, even specifying a different QoS level. As consequence of this, it could be possible that the Message#qos value of the received Message instance gets downgraded from the value actually granted by the MQTT broker because the sole existing subscription on the server side has been submitted with the maximum QoS level among the ones of the shared subscriptions requested by the clients.

  • For a dedicated connection with session persistence, invocation occurs in accordance with the flow of the Control Packets exchanged between MqttClient and the MQTT broker and relative to the aforementioned delivery protocol. More specifically:
    • Upon receiving a QoS 0 message, the callback is invoked immediately without any further elaboration.
    • Upon receiving a QoS 1 message, a PUBACK Control Packet is sent back and then the callback is invoked.
    • Upon receiving a QoS 2 message, it is stored immediately and then a PUBREC Control Packet is sent back; upon receiving the PUBREL Control Packet, the message is finally removed from the local storage, the callback is invoked and then the PUBCOMP Control Packet is sent back.

When setting this property, an Error is thrown if the provided value is not of function type.

Type:

onMessageDelivered :OnMessageDelivered

The property to be bound to the callback function invoked when the delivery process of an Application Message is complete.

An invocation of the MqttClient#send method initiates the delivery process, whose successful completion depends on the following factors:

  • The QoS level used to deliver the Application Message.
  • The current end-to-end connection type (shared or dedicated).
  • Whether the session is persistent, which is allowed only in the case of a dedicated connection.

In the case of QoS 0 message, the callback is invoked once the message has been delivered to the underlying MQTT.Cool channel (irrespective of the connection type), and before any possible authorization issue which could be raised when the message is actually received by MQTT.Cool (see MqttClient#onMessageNotAuthorized).

In the case of QoS > 0 message, the callback is invoked on the basis of the connection type as follows:

  • For a shared connection and a dedicated connection without session persistence, the invocation occurs when MQTT.Cool sends back the acknowledgement that the flow of the Control Packets exchanged on the server side and relative to the delivery protocol for the specified QoS level has been completed.
  • For a dedicated connection with session persistence, the invocation occurs in accordance wih the flow of the Control Packets exchanged between MqttClient and the MQTT broker and relative to the aforementioned delivery protocol. More specifically:
    • For QoS 1 message, upon receiving the PUBACK Control Packet, the callback is invoked and then the message is removed from the local storage.
    • For QoS 2 message, upon receiving the PUBREC Control Packet, the message state is updated on the local storage and then the PUBREL Control Packet is sent back; upon receiving the PUBCOMP Control Packet, the callback is invoked and then the message is finally removed from the local storage.

Note that for QoS > 0 message, the callback will be never invoked in the case of any authorization issue raised by the plugged Hook (see MqttClient#onMessageNotAuthorized). In such scenario, the message is also removed from the local storage if session persistence is active.

When setting this property, an Error is thrown if the provided value is not of function type.

Type:

onMessageNotAuthorized :OnMessageNotAuthorized

The property to be bound to the callback function invoked when the plugged Hook denies the authorization for publishing, or raises an issue while performing its checking activities.

The authorization phase is triggered once the message received by MQTT.Cool is passed to the Hook, before being sent to the target MQTT broker. In the case of authorization failure, the message is rejected immediately and a specific error is sent back by MQTT.Cool to MqttClient. As consequence of this, MqttClient#onMessageDelivered will never be called for this message, unless its QoS value is 0, which on the contrary causes an instant invocation of the callback.

When setting this property, an Error is thrown if the provided value is not of function type.

Type:

onReconnectionComplete :OnReconnectionComplete

The property to be bound to the callback function invoked upon a successful restoration of the end-to-end connection, which has been interrupted because of an issue between MqttClient and MQTT.Cool.

More specifically, as soon as the underlying MQTT.Cool connection is restored, the MqttClient instance and the MQTT.Cool server cooperate silently in order to fully restore the whole end-to-end connection, whereupon the session state (as defined in MqttClient#onReconnectionStart) will be resumed as follows:

  • For a shared connection and a dedicated connection without session persistence:
    • All the active subscriptions will be resubmitted silently.
    • Sent QoS 0 messages, not yet acknowledged by the MQTT.Cool server, will be be redelivered, although the MqttClient#onMessageDelivered notification will no longer take place.
    • Sent QoS > 0 messages, not yet acknowledged by the MQTT.Cool server, will be redelivered; in this case, the flow of notification will prosecute as if the messages had been sent for the first time, which means that MqttClient#onMessageDelivered will be invoked as expected.

      Furthermore, message redelivery triggered on the client side could cause duplicates because on the server side, the same message may be sent and acknowledged completely before the end-to-end is interrupted: this specific condition represents a concern in the case of QoS 2 messages as the MQTT Protocol Specifications do not allow duplicates.

  • For a dedicated connection with session persistence:
    • Sent QoS 0 messages, not yet acknowledged by the MQTT.Cool server, will be redelivered, although the MqttClient#onMessageDelivered notification will no longer take place.
    • Sent QoS 1 and 2 messages, not yet completely acknowledged, will be reprocessed as per the reached level of acknowledgement.
    • Received QoS 2 messages, not yet completely acknowledged to the MQTT broker, will be reprocessed as per the reached level of acknowledgement.

When setting this property, an Error is thrown if the provided value is not of function type.

Type:

onReconnectionStart :OnReconnectionStart

The property to be bound to the callback function invoked when an attempt to re-establish the current end-to-end connection, which has been interrupted because of an issue between MqttClient and MQTT.Cool, has started.

More specifically, the callback is called in case of interruption of the underlying MQTT.Cool connection (due to network issue or to problems in the MQTT.Cool server process) while the MqttClient instance is currently in the connected status. If the connection was interrupted just before MqttClient connects through the MqttClient#connect method, then a connection failure will be immediately triggered: see OnConnectionFailure, errorCode=10.

The provided reconnection feature allows to try to transparently re-establish the connection to the MQTT.Cool server while also preserving the current session state, which could be resumed once the connection has been restored.

The session state depends on the current end-to-end connection type:

  • For a shared connection and a dedicated connection without session persistence, the session state consists of:
    1. QoS 0 messages sent to the MQTT broker, but not yet acknowledged by the MQTT.Cool server.
    2. QoS > 0 messages sent to the MQTT broker, but not yet acknowledged by the MQTT.Cool server.
    3. All the current active subscriptions.
  • For a dedicated connection with session persistence, the session state consists of:
    1. QoS 0 messages sent to the MQTT broker, but not yet acknowledged by the MQTT.Cool server.
    2. QoS 1 and QoS 2 messages sent to the MQTT broker, but not completely acknowledged.
    3. QoS 2 messages received from the MQTT broker, but not completely acknowledged.
    Note that points 2 and 3 are compliant with the definition of Session state in the Client as stated in the MQTT Protocol Specifications; instead, point 1 goes beyond such definition as no recovery action is normally required for QoS 0 messages.

The callback will be invoked indefinitely until one of the following events occurs:

  • The underlying MQTT.Cool connection has been restored.
  • An explicit invocation of the MqttClient#disconnect method has been performed in the body of the provided callback (recommended way to stop definitively any reconnection attempt).
The latter point also implies that there will not be any further chances to resume the state of MqttClient that is without a persistent session.

When setting this property, an Error is thrown if the provided value is not of function type.

Type:

Method Summary

connect
Opens an end-to-end connection to the target MQTT broker.
disconnect
Disconnects from the target MQTT broker.
send
Sends an Application Message to be published to a topic.
Subscribes to the topic(s) indicated by the given topicFilter.
unsubscribe
Unsubscribes from the topic(s) indicated by the given topicFilter .

Method Detail

connect(connectOptionsopt)

Opens an end-to-end connection to the target MQTT broker.

The ways through which the connection to the broker has to be established have been specified by the parameters supplied to the MQTTCoolSession#createClient method, which is invoked to create this MqttClient instance.
Upon successful acknowledgement of the connection request (notified through the OnConnectionSuccess callback if properly set) the MqttClient instance switches to the connected status.

Parameters:
Name Type Argument Description
connectOptions ConnectOptions <optional>
The object whose properties specify the options to be used for controlling the connection to the target MQTT broker. If not supplied (or null), then its default values apply.
Throws:
If MqttClient is currently in the connected status or the provided argument is invalid.
Type
Error

disconnect()

Disconnects from the target MQTT broker.

After sending the DISCONNECT Control Packet, MqttClient immediately switches to the disconnected status and closes the underlying MQTT channel, which provokes MqttClient#onConnectionLost to be fired.
The MQTT.Cool connection remains up as it may serve the MQTT channels owned by the other connected MqttClient objects that share the same parent MQTTCoolSession instance.

Note that from the disconnected status, an MqttClient is allowed to open a new connection through the MqttClient#connect method.

Throws:
If MqttClient is currently in the disconnected status.
Type
Error

send(topicnon-null, payloadopt, non-null, qosopt, retainedopt)

Sends an Application Message to be published to a topic.

The method can be used in two different ways, on the basis of the number and the type of the provided arguments:

  • Single Argument Form
  • The method takes just one argument, which is a Message instance wrapping the Application Message (and related details) to be published.
    For example:
      // Prepare the Message instance
      var msg = new Message('My Message!')
      msg.destinationName = 'my/topic';
      msg.qos = 1;
      msg.retained = false;
    
      // Send the prepared message (client is an already connected MqttClient object).
      client.send(msg);
      
  • Multiple Arguments Form
  • The method takes up to four arguments that specify the Application Message (and the related details) to be published.
    For example:
      // Send the message specified by means of the provided arguments.
      client.send('my/topic', 'My Message!', 1, false);
      
    Note also that it is not allowed to provide arguments in a mixed form; if this is the case, then an exception will be thrown.
Parameters:
Name Type Argument Default Description
topic string | Message In the case of a Message instance, the Application Message (and related details) to be published.

In the case of a string value, the name of the topic to which the Application Message is to be published as specified in Message#destinationName.

payload string | ArrayBuffer | Int8Array | Uint8Array | Int16Array | Uint16Array | Int32Array | Uint32Array | Float32Array | Float64Array <optional>
The payload of the Application Message, as it was provided to the Message constructor.

Note that in the case of Multiple arguments, this parameter is mandatory.

qos number <optional>
0 The Quality of Service level for delivery of the Application Message as specified in Message#qos.

Note that any provided value different from 0, 1 and 2 will provoke an exception.

retained boolean <optional>
false The retained flag as specified in Message#retained.
Throws:
if MqttClient is currently in the disconnected status or the provided arguments are invalid.
Type
Error

subscribe(topicFilter, subscribeOptionsopt)

Subscribes to the topic(s) indicated by the given topicFilter.

Because the provided topicFiler may contain wildcards, it allows to subscribe to multiple topics at once.

Parameters:
Name Type Argument Description
topicFilter string The topic filter, which indicates one or more topics to subscribe to.
subscribeOptions SubscribeOptions <optional>
The object whose properties specify the options to be used for controlling the subscription. If not supplied (or null), then its default values apply.
Throws:
If MqttClient is currently in the disconnected status or the provided arguments are invalid.
Type
Error

unsubscribe(topicFilter, unsubscribeOptionsopt)

Unsubscribes from the topic(s) indicated by the given topicFilter .

Because the provided topicFiler may contain wildcards, it can allow unsubscriptions from multiple topics at once.

Parameters:
Name Type Argument Description
topicFilter string The topic filter, which indicates one or more topics to unsubscribe from.
unsubscribeOptions UnsubscribeOptions <optional>
The object whose properties specify the options to be used for controlling the unsubscription.
Throws:
If MqttClient is in the disconnected status or the provided arguments are invalid.
Type
Error