Create a message
Agent
Name | Type | Description |
---|---|---|
topic | String or blob |
The topic the message will be published to. Must be valid UTF-8
|
message | String or blob |
The message to publish
|
options | Table |
Optional table of publishing parameters
|
An mqttmessage object
This method allows you to create a message that can subsequently be posted to the specified topic. The method does not publish the message.
The maximum size of a message (as passed into the message parameter) is currently 256KB. An exception will be thrown if you attempt to create a message larger than this.
The options parameter can take a table of message-publishing settings. These are listed in the table below.
Key | Type | Description |
---|---|---|
qos | Integer | Set the Quality of Service (Qos) level: see QoS, below. Default: mqtt.AT_MOST_ONCE |
retain | Boolean | Instruct the broker to retain messages for future subscribers (true ), or send to current subscribers only (false ). Default: false |
An exception will be thrown if you attempt to send a message (using mqttmessage.sendasync()) when the parent mqttclient instance on which you called createmessage() is currently disconnected. You can safely create messages using a disconnected mqttclient instance, but you must call mqttclient.connect() before you send those messages.
The value of qos can be any of the following:
Constant | Value | Description |
---|---|---|
mqtt.AT_MOST_ONCE | 0 | The message is sent but receipt is not confirmed by the recipient so there is no guarantee of delivery. The message is not stored and re-transmitted by the sender |
mqtt.AT_LEAST_ONCE | 1 | The message may be delivered more than once. The sender stores and periodically re-transmits the message until the receiver acknowledges receipt of the message |
mqtt.EXACTLY_ONCE | 2 | The message is delivered only once. The sender stores and periodically re-transmits the message until the receiver acknowledges receipt of the message, but subsequent sends mark the message as a duplicate, allowing the receiver to process the message only once. This also utilizes multiple acknowledge messages transmitted by sender and recipient. It is the safest but slowest QoS level |
Note The higher the QoS level you select, the more acknowledge and re-acknowledge messages may be sent between agent and broker. This may be impacted by Electric Imp’s MQTT rate limits.
If no qos is included in the options table, the default value mqtt.AT_MOST_ONCE is applied.
The following code generates a message (using an mqttclient instance, client) and sends it to the broker referenced when client was created.
server.log("Posting a message...");
local message = client.createmessage("imp.mqtt.test.pings",
"this is a test",
{"qos": mqtt.AT_LEAST_ONCE} );
message.sendasync(function(result) {
server.log("The message was " + (result != 0 ? "not " : "") + "published");
});