Open a new connection to an MQTT broker
The URL of the MQTT broker
Client identifier passed to the broker when the client connects
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. A runtime error 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:
|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 a runtime error when mqttclient.connect() is called on it. Calling connect() on the mqttclient object that is already connected will have no effect.
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.