Skip to main content

mqttclient.connect(url, clientID, options)

Open a new connection to an MQTT broker




Name Type Description
url String The URL of the MQTT broker
clientID String Client identifier passed to the broker when the client connects
options Table An optional table of connection options




This method opens a new MQTT connection to the specified broker. The connection is made asynchronously, and any function registered with mqttclient.onconnect() will be called whether the attempt succeeds or fails.

The MQTT broker’s Internet address is passed into the url parameter. You must include in the URL the scheme, which must be tcp:// for unencrypted connections, or ssl:// for encrypted connections.

The string passed into the clientID parameter must contain at least one character and no more than 255 characters. An exception will be thrown if the string’s length is out of range.

The connection can be modified by passing a table of values into the options parameter. It may include any of the following keys:

Name Type Notes
username String or blob Must be valid UTF-8
password String or blob Must be valid UTF-8
keepalive Integer Connection maintenance time in seconds in the range 30 to 65535, or 0 to disable. Default: 60
willtopic String or blob Must be valid UTF-8. See below
willmessage String or blob Ignored if present but willtopic is not. See below

While you can create as many mqttclient objects as you like, memory permitting, you can only connect to one of these objects at a time. Attempting to connect to a second mqttclient object will throw an exception when connect() is called on it.

Note Inbound and Outbound MQTT requests and messages are subject to rate limits.

An exception will be thrown if you call connect() on an mqttclient instance that is not disconnected, or if you perform an operation that requires a connection — eg. subscribe, unsubscribe or send a message — on a disconnected mqttclient.

MQTT Wills

The options keys willtopic and willmessage form a pair. Upon connection, they will be sent to the MQTT broker, which stores them for the duration of the connection. If the mqttclient disconnects unexpectedly — for example, the agent undergoes a server migration or a manual restart caused by a code deploy — the broker will deliver willmessage to willtopic where it will be received by other clients subscribing to that topic. This allows clients to be informed that the agent (and, by extension, the device that it represents), is now unavailable. When the agent restarts, it may, if it is so coded, post a message to willtopic (or to some other topic) to indicate it is back online.