MQTT.Client

Description

This class allows you to create client connections to an MQTT broker.

A client is capable of publishing messages to the broker. A client is also capable of subscribing one or more topics, enabling it to receive messages that other clients publish on those topics.
This class uses the mosquitto client library. See mosquitto.org and mosquitto.h for more information.
To use this class, you'll complete the following steps:
  1. Construct
  2. Configure
  3. Connect
  4. Communicate
  5. Disconnect
  6. Destroy

Construct

You can construct a client by specifying an id, a version, and a clean start flag:
MQTT.Client c = MQTT.Client("my-client-id", MQTT.Version.v31, 1);
You can also choose to use the default arguments:
MQTT.Client c = MQTT.Client("");
Note that a blank ID implies that the client will generate a random ID.

In the above cases, the client you create will be destroyed automatically when the FlexScript function finishes running. To create a more persistant connection, you can specify a treenode for the client:
treenode holder = Model.find("path/to/target/node");
MQTT.Client c = MQTT.Client("my-client-id", MQTT.Version.v31, 1, holder);
When you supply a node this way, the data for the client is stored on the node. You can access this client later as follows:
treenode holder = Model.find("path/to/target/node");
MQTT.Client c = holder;
// OR
MQTT.Client c = MQTT.Client(holder);
It is an error to create a client from a node that does not have client data on it.

Configure

Once the client is constructed, you can configure the client:
  • If desired, setting a will message with setWill(). The will message is optional and is published only if the client disconnects unexpectedly.
  • If the broker requires, setting a username and password with setUsernamePassword().
  • If the broker requires, setting SSL options with setSSL().
You must also decide how FlexSim will receive messages from the broker. There are two options:
  • You can either wait for messages with getMessage(), or
  • You can specify a node to use as a callback with setDefaultCallback(). The callback will be called any time a message is received.

Configuration is Irreversible

Most configuration functions make changes that can't be reversed on the client. For example, once you set a username and password, you can't remove the username and password. If you need to change the client's configuration, create a new client.

If you are making a persistent client, first create a non-presistant client that successfully connects to ensure your configuration is correct.

Connect

To connect to a broker, specify a host, a port, and a keep-alive interval:
int code = c.connect("localhost", 1883, 60);
Once connected, you can then communicate with the broker. When you finish communications, be sure to disconnect.

Once you have disconnected, you can reconnect the client with the exact same settings as were used before:
int code = c.connect();
Note that in order to use this simple version of connect, you must meet the following conditions:
  1. The client has successfully connected in the past and you haven't called any configuration functions, or
  2. The client is bound to a node and all member node values are set correctly (intended for developer use).

Communicate

In MQTT, clients do not communicate with each other directly. Instead, they publish messages. A message includes a topic and a payload. Any client can subscribe to a topic. Once a client has subscribed, they will receive all messages that are published on that topic.

The broker's main role is to distribute published messages to any client subscribed to the correct topic. Only connected clients receive messages. The broker does not store messages for later. The only exception is retained messages. If a message is retained, the broker will keep the latest message for that topic. As soon as a client subscribes, the broker will send the retained message, if any.

Once connected, a client can subscribe to one or more topics:
int rc = c.subscribe("some-topic");
If a callback node is set, then it will be evaulated whenver a message arrives. Otherwise, the client will store incoming messages in a queue until they are retrieved:
MQTT.Message msg = c.getMessage(5.0);
// Check if the message was received
if (msg) {
    // use the message
    print(msg.topic, msg.payload);
}
To publish a message, create an MQTT.Message object and publish it:
MQTT.Message msg = Message("some-topic", "some-message");
int rc = c.publish(msg);
        

Disconnect

You can disconnect the client as follows:
int rc = c.disconect();
Once disconnected, the client will no longer receive messages from the broker.

Destroy

If you don't bind the client to a node, the client will be destroyed automatically at the end of the FlexScript function where it was created. If the client is bound to a node, it will be destroyed when the node is destroyed or when the the node's data changes.

Properties

Properties are an advanced feature that most users can safely ignore.

MQTT 5.0 introduced Properties. Properties can be passed to most of the methods in the client, and can be part of a message. The MQTT.Client class represents properties with a Map. The client attempts to convert all keys and values in the map to valid MQTT properties. If a key is text and is not a valid property name, the client will use the key and value as a user property.

A full list of properties is included in the MQTT 5.0 specification, along with which properties are valid for a particular API call: https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901027

Properties

isConnected Returns whether the client is currently connected to the broker.
settings Returns the set of all construction, configuration, and connection values.

Methods

connect Connects the client to a broker.
disconnect Disconnects the client from the broker.
getMessage Waits for the client to receive a message.
publish Publishes a message.
setDefaultCallback Specifies a node to evaluate when a message is received.
setSSL Specifies options to use for TLS/SSL.
setUsernamePassword Specifies a username and password for the client.
setWill Sets a will message for the client.
subscribe Subscribes the client to a topic.
unsubscribe Unsubscribe from a topic.

Constructor

MQTT.Client

Operators

= Accesses a client stored on the given node.

Details

Do no remove, this fixes the anchor on doc.flexsim.com

MQTT.Client.isConnected

readonly int isConnected

Description

Returns whether the client is currently connected to the broker.

If the connection is unexpectely lost, the client will automatically try to reconnect. This value will report true even during those disconnections.
Do no remove, this fixes the anchor on doc.flexsim.com

MQTT.Client.settings

readonly settings

Description

Returns the set of all construction, configuration, and connection values.

This property allows you to read any of the settings applied during construction, configuration, or connection. For example, to see the current host value:
MQTT.Client c = MQTT.Client();
//... configure/connect
string host = c.settings.host;
All arguments to the constructor, configuration methods, and the connect call are available on the settings obuect.
Do no remove, this fixes the anchor on doc.flexsim.com

MQTT.Client.connect()

int connect( string host , string bindAddr , Map properties , int port = 1883 , int keepAlive = 60 )
int connect( string host , int port = 1883 , int keepAlive = 60 )
int connect( )

Parameters

host The hostname or IP address of the broker.
bindAddr Only for use with MQTT 5.0. Restricts network traffic to the specified interface.
properties Only for use with MQTT 5.0. Properties to send with the connect request.
port The port the broker is listening on.
keepAlive The ping interval in seconds used for this connection.

Returns

int Zero if the connection is successful. Otherwise, returns an error code.

Description

Connects the client to a broker.

Once connected, the client can communicate with the broker by subscribing and publishing. Possible values for version are:
MQTT.Version.v31 /*MQTT Protocol 3.1*/
MQTT.Version.v311 /*MQTT Protocol 3.1.1*/
MQTT.Version.v5 /*MQTT Protocol 5.0*/
Do no remove, this fixes the anchor on doc.flexsim.com

MQTT.Client.disconnect()

int disconnect( int reasonCode = 0 )
int disconnect( int reasonCode , Map disconnectProps )

Parameters

reasonCode A reason code to send with the disconnect message.
disconnectProps For use with MQTT 5.0. Properties to send with the disconnect message.

Returns

int Zero or an error code.

Description

Disconnects the client from the broker.

This method first finishes sending or receiving any messages that are in progress. Then it disconnects from the broker. The connection is disconnected, even if an error code is present.
Do no remove, this fixes the anchor on doc.flexsim.com

MQTT.Client.getMessage()

MQTT.Message getMessage( double maxSeconds )

Parameters

maxSeconds The maximum amount of time to wait for a message.

Returns

MQTT.Message If a message is received, a valid message. If the timeout expires, an invalid message.

Description

Waits for the client to receive a message.

If the client has set a callback, the callback consumes the message and this function will always wait for the specified timeout and return an invalid message. Otherwise, this method waits for a message to appear in the client's internal message queue. If a message is already present or appears before the timeout occurs, the message is removed from the internal queue and returned.
Do no remove, this fixes the anchor on doc.flexsim.com

MQTT.Client.publish()

int publish( MQTT.Message msg )

Parameters

msg The message to publish.

Returns

int Zero if publishing was successful or an error code.

Description

Publishes a message.

All settings of the message are used to complete publishing, including the topic, payload, QOS (quality of service) parameter, the retain flag. Properties are only sent if using MQTT 5.0.
Do no remove, this fixes the anchor on doc.flexsim.com

MQTT.Client.setDefaultCallback()

setDefaultCallback( treenode callback )

Parameters

callback The callback node.

Description

Specifies a node to evaluate when a message is received.

The callback node should have the following header:
MQTT.Message msg = param(1);
This node is called for every message received by the client. See MQTT.Message for more information about the message.
Do no remove, this fixes the anchor on doc.flexsim.com

MQTT.Client.setSSL()

int setSSL( string cafile , string capath , string certfile , string keyfile , string keypassword , string ciphers = 0 )
int setSSL( string psk , string identity , string ciphers = 0 )

Parameters

cafile The certificate authority file in PEM format.
capath A directory containing certificate authority files in PEM format.
certfile The client certificate file in PEM format.
keyfile The client key file in PEM format.
keypassword If the client key is encrypted, the key for that file.
ciphers A list of OpenSSL ciphers to use for encryption or decryption.
psk The pre-shared-key in hex format with no leading “0x”.
identity The identity of this client. May be used as the username depending on the server settings.

Returns

int Zero if successful, or an error code.

Description

Specifies options to use for TLS/SSL.

If the broker expects the client to use TLS/SSL, this method configures the client appropriately. If these values are incorrect, the client won't be able to connect.
Do no remove, this fixes the anchor on doc.flexsim.com

MQTT.Client.setUsernamePassword()

int setUsernamePassword( string username , string pwd )

Parameters

username The client's username.
pwd The client's password.

Returns

int Zero if successful, or an error code.

Description

Specifies a username and password for the client.

If a broker requires a username and password, this method sets those values for the client. If the values are incorrect, the client won't be able to connect.
Do no remove, this fixes the anchor on doc.flexsim.com

MQTT.Client.setWill()

int setWill( MQTT.Message msg )

Parameters

msg The will message.

Returns

int Zero if successful, or an error code.

Description

Sets a will message for the client.

A will message is published by the broker if the client disconnects unexpectedly. A will message is not required.
Do no remove, this fixes the anchor on doc.flexsim.com

MQTT.Client.subscribe()

int subscribe( string topic , int qos , int options = 0 )
int subscribe( string topic , int qos , int options , Map subscribeProps )

Parameters

topic The topic to subscribe to.
qos The requested quality of service for this subscription.
options For use with MQTT 5.0. OR'd option values to send with the subscription request.
subscribeProps For use with MQTT 5.0. Properties to send with the subscription request.

Returns

int Zero if successful, or an error code.

Description

Subscribes the client to a topic.

Once subscribed, the client will receive all messages published on the specified topic. Those messages are sent to the callback node, if defined. Otherwise, they accumulate in an internal queue which can be read via getMessage(). The broker will provide up to the maximum quality of service if available for this subscription.

It is possible to subscribe to multiple topics at the same or lower level using wildcards. See the MQTT specification for more information.

Valid option values are described here:
0x04With this option set, if this client publishes to a topic to which it is subscribed, the broker will not publish the message back to the client.
0x08With this option set, messages published for this subscription will keep the retain flag as was set by the publishing client. The default behaviour without this option set has the retain flag indicating whether a message is fresh/stale.
0x10With this option set, pre-existing retained messages for this subscription will be sent when the subscription is made, but only if the subscription does not already exist.
0x20With this option set, pre-existing retained messages will never be sent for this subscription
Do no remove, this fixes the anchor on doc.flexsim.com

MQTT.Client.unsubscribe()

int unsubscribe( string topic )
int unsubscribe( string topic , Map unsubscribeProps )

Parameters

topic The topic to unsubscribe from.
unsubscribeProps For use with MQTT 5.0. Properties to send with the unsubscribe request.

Returns

int Zero if successful or an error code.

Description

Unsubscribe from a topic.

Once unsubscribed, the client will no longer receive new messages from the broker on this topic. However, any existing messages in the client's internal queue will remain unchanged.
Do no remove, this fixes the anchor on doc.flexsim.com

MQTT.Client Constructor

MQTT.Client( string client , int version = 3 , int cleanStart = 1 , treenode holder = 0 )
MQTT.Client( treenode holder )

Parameters

client The ID of the client.
version The MQTT protocol version for the client.
cleanStart The clean start flag.
holder The node that either has client data or will be initalized to hold client data.

Description

The first version of the constructor creates a new client and optionally binds the client to a node. The second version accesses client data that already exists on the given node.

If the client ID is blank, the client will connect with a random ID.

If the client ID is not blank and the clean start flag is set to zero, then the broker will remember the subscriptions made by this client. If a client with the same client ID connects again, it will automatically begin receiving messages for those subscriptions.
Do no remove, this fixes the anchor on doc.flexsim.com

MQTT.Client.operator =

MQTT.Client operator =( treenode holder )

Parameters

holder The node containing client data.

Returns

MQTT.Client

Description

Accesses a client stored on the given node.

If you create a client and bind it to a node, you can access that client with this operator. It is an error to use a node that does not have client data.