Quick Apps — MQTT client
Home Center 3, Home Center 3 Lite and Yubii Home can act as an MQTT client.
MQTT features and concept
This document focuses on the implementation of MQTT client. To find out more about MQTT, its features and concept, please check out the links section.
Callback vs. Event
The parameter options gives the ability to pass a callback. This callback indicates the operation completion but does NOT indicate the message has been received by the broker. The callback must be of the following pattern:
1function callback(int errorCode);
Events signal the availability of packet received from the broker. E.g. onmessage event is signaled when the client receives PUBLISH packet from the broker. All events handlers must be of usual signature:
1function callback(table args)
args parameter is a table and its values depend on the type of event.
Use EventTarget API to register for an event, for example, registering for onmessage event:
1function myCallback(event) 2 print('Received message: ' .. event.payload); 3end 4-- NOTE: 'on' prefix omitted 5client.addEventListener('message', myCallback);
Quality of Service
Possible QoS values.
1QoS = { 2 AT_MOST_ONCE = 0, 3 AT_LEAST_ONCE = 1, 4 EXACTLY_ONCE = 2, 5} 6-- can be used: `QoS.AT_LEAST_ONCE`
mqtt.Client.connect(uri, options)
Asynchronously creates a connection with the broker. When connection is made, onconnected event is triggered.
Parameters
uri- (of typestring) the address of the broker. Either full URI withmqtt/mqttsscheme or just a host part. URI Scheme Specificationoptions- (optional) (of typetable) attributes (all are optional):port- (of typenumber) the port to use for TCP connection. Defaults to 1883 (8883 for TLS).tls- (of typetable) TLS options (explained below).keepAlivePeriod- (of typenumber) maximum time interval that is permitted between the point at which the Client finishes transmitting one Control Packet and the point it starts sending the next. It allows both sides to determine if the other one is still alive and reachable. Defaults to zero - keep-alive mechanism is deactivated.usernameandpassword- (of typestring) containing user credentials for client authentication.clientId- (of typestring) an identifier of each MQTT client connecting to an MQTT broker. If no ID is given, a random ID will be generated.cleanSession- (of typebool) indication of the broker, whether the client wants to establish a persistent session or not. Defaults tofalse.callback-functionthat will be called when the connection attempt is complete.lastWill- (of typetable) used for notifying other clients, when a client disconnects ungracefully.lastWillmembers:topic- a field of typetablecontaining topic name,payload- a field of typestringwith the content of the last will,qos- (optional) QoS of the last will,retain- (optional) a field of typebool.
Returns a new client object of MqttClient class.
In case mqtts (mqtt over tls) is required, the options.tls must be provided (may be an empty table). If mqtts scheme is used in URL, TLS usage is also enabled. Following members can be provided within tls.options:
clientCertificate- (of typestring) client certificate in PEM format.allowUnauthorized- (of typebool) if you are using a self-signed certificate, passtrue. Beware that you are exposing yourself to man in the middle attacks, so it is a configuration that is not recommended for production environments.certificateAuthority- (of typestring) a trusted certificate used for server verification. The certificate must use the PEM format.
connected event - triggered when CONNACK is received from the server. Event arguments:
sessionPresent-booleanthat indicates, whether the broker already has a persistent session of the client from previous interactions.returnCode-numberthat signals the client, if the connection attempt was successful and otherwise what the issue is. See alsoConnectReturnCodeenum.
Example
1function QuickApp:connect() 2 self.client = mqtt.Client.connect(self:getVariable("brokerURI")) 3 self.client:addEventListener('connected', function(event) self:onConnected(event) end) 4end
mqtt.Client.disconnect(options)
Disconnects client from the broker.
options- (optional) is atablewith the following members (all are optional):callback-functioncalled when the disconnect attempt is complete.
Parameters
onclosed event - triggered when the connection is closed or broken by other means. Arguments are empty for this event.
mqtt.Client.subscribe(topic, options)
Registers the client in the broker to listen for messages on the given topic. Messages can be filtered with pattern matching as specified in MQTT documentation, i.e. use '#' and '+' characters. Once the client is subscribed, the messages are received through onmessage event.
Parameters
topic- (of typestring) a topic to subscribe to.options- (optional) is atablewith following members (all are optional):qos- (of typenumber) the desired quality of service level for the subscription. Defaults to0. See alsoQoSenum.callback-functioncalled when the disconnect attempt is complete.
Returns packet ID - a unique identifier used to identify the message.
subscribed event - triggered when SUBACK is received from the server. Event arguments:
packetId- packet ID as returned bysubscribe().results- (of typetable) The broker sends one return code for each topic/QoS-pair it received in theSUBSCRIBEmessage. If theSUBSCRIBEmessage had 5 subscriptions, there will be 5 return codes to acknowledge each topic with the QoS level granted by the broker. If the subscription was prohibited by the broker (e.g. if the client was not allowed to subscribe to this topic due to insufficient permission or if the topic was malformed), the broker will respond with a failure return code for that specific topic.Return Code Return Code Response 0 Success – Maximum QoS 0 1 Success – Maximum QoS 1 2 Success – Maximum QoS 2 -1 Failure
Example
1function QuickApp:subscribe() 2 self.client:addEventListener('message', function(event) self:onMessage(event) end) 3 self.client:addEventListener('subscribed', function(event) self:onSubscribed(event) end) 4 5 self.client:subscribe("lights/#", { qos = mqtt.QoS.EXACTLY_ONCE }); 6end 7 8function QuickApp:onSubscribed(event) 9 print("onSubscribed:", json.encode(event)) 10end 11 12function QuickApp:onMessage(event) 13 print("onMessage:", json.encode(event)) 14 15 if event.payload == "ON" then 16 self:updateProperty("value", true) 17 elseif event.payload == "OFF" then 18 self:updateProperty("value", false) 19 end 20end
mqtt.Client.subscribe can also accept many topics, i.e. mqtt.Client.subscribe(topics, options)
Parameters
topics- (of typetable) each item must be of either type:{string topic, int qos}pairstring topic(qosdefaults to the one passed in theoptions)
options- (optional) is atablewith following members (all are optional):qos- (of typenumber) the desired quality of service level for subscription. Defaults to0. See alsoQoSenum.callback-functioncalled when the disconnect attempt is complete.
Returns packet ID - a unique identifier used to identify a message.
subscribed event - triggered when SUBACK is received from the server. Event arguments:
packetId- packet ID as returned bysubscribe().results- (of typetable) the broker sends one return code for each topic/QoS-pair it received in theSUBSCRIBEmessage. So if theSUBSCRIBEmessage had 5 subscriptions, there will be 5 return codes to acknowledge each topic with the QoS level granted by the broker. If the subscription was prohibited by the broker (e.g. if the client was not allowed to subscribe to this topic due to insufficient permission or if the topic was malformed), the broker will respond with a failure return code for that specific topic.Return Code Return Code Response 0 Success – Maximum QoS 0 1 Success – Maximum QoS 1 2 Success – Maximum QoS 2 -1 Failure
mqtt.Client.unsubscribe(topics, options)
Unscubscribes from the topic(s).
Parameters
unsubscribed event - triggered when UNSUBACK is received from the server. Event arguments:
packetId- packet ID as returned byunsubscribe().
Returns packet ID - a unique identifier used to identify a message.
mqtt.Client.unsubscribe(topics, options)
Same as above but accepts multiple topics (array of strings).
Parameters
unsubscribed event - triggered when UNSUBACK is received from the server. Event arguments:
packetId- packet ID as returned byunsubscribe().
Returns packet ID - a unique identifier used to identify a message.
mqtt.Client.publish(topic, payload, options)
Publishes a message, the broker forwards the message to the interested clients (topic filtering).
Parameters
topic- (of typestring) the topic namepayload- (of typestring) the actual content of the messageoptions- (optional) (of typetable) members (all are optional):qos- (of typenumber) the desired quality of service level for this message. Defaults to0. See alsoQoSenum.retain- (of typebolean) determines if the message will be saved by the broker for the specified topic as last known good value.callback-functioncalled when the disconnect attempt is complete.
onpublished event - triggered when PUBACK is received from the server.
packetId- packet ID as returned bypublish().
Example
1function QuickApp:publishTurnedOn(id) 2 self.client:addEventListener('published', function(event) self:onPublished(event) end) 3 self.client:publish("lights/" .. tostring(id), "ON") 4end 5 6function QuickApp:onPublished(event) 7 print("onPublished:", json.encode(event)) 8end
Message Event
message event is triggered when broker forwards a message published by one of the clients to this client. Event arguments:
topic- (of typestring) topic namepayload- (of typestring) the actual content of the messagepacketId:int(nil for QoS=0)qos- (of typenumber) the desired quality of service level for this message. Defaults to0.retain- (of typebool) determines if the message was saved by the broker for the specified topic as last known good value.dup- (of typebool) indicates if the message is a duplicate and is re-sent because the other end didn’t acknowledge the original message.
Error Event
error event is triggered when an error occurred in the channel. Event arguments:
code-numberwith error code
Links
MQTT 101 – How to Get Started with the lightweight IoT Protocol
Online client for quick testing