Table of contents
- MQTT features and concept
- Callback vs. Event
- Quality of Service
- mqtt.Client.connect(uri, options)
- mqtt.Client.disconnect(options)
- mqtt.Client.subscribe(topic, options)
- mqtt.Client.unsubscribe(topics, options)
- mqtt.Client.unsubscribe(topics, options)
- mqtt.Client.publish(topic, payload, options)
- Message Event
- Error Event
- Links
FIBARO Home Center 3 can act as an MQTT client.
WARNING: this function is available only on Home Center 3, Home Center 3 Lite and Yubii Home with firmware 5.030 or higher.
MQTT features and concept
This document focuses on the implementation of MQTT in Home Center 3, Home Center 3 Lite and Yubii Home.
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:
1 |
function 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:
1 |
function 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:
1 2 3 4 5 |
function myCallback(event) print('Received message: ' .. event.payload); end -- NOTE: 'on' prefix omitted client.addEventListener('message', myCallback); |
Quality of Service
Possible QoS values.
1 2 3 4 5 6 |
QoS = { AT_MOST_ONCE = 0, AT_LEAST_ONCE = 1, EXACTLY_ONCE = 2, } -- 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
/mqtts
scheme 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.-
username
andpassword
– (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
–function
that will be called when the connection attempt is complete.lastWill
– (of typetable
) used for notifying other clients, when a client disconnects ungracefully.lastWill
members:topic
– a field of typetable
containing topic name,payload
– a field of typestring
with 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
–boolean
that indicates, whether the broker already has a persistent session of the client from previous interactions.returnCode
–number
that signals the client, if the connection attempt was successful and otherwise what the issue is. See alsoConnectReturnCode
enum.
Example
1 2 3 4 |
function QuickApp:connect() self.client = mqtt.Client.connect(self:getVariable("brokerURI")) self.client:addEventListener('connected', function(event) self:onConnected(event) end) end |
mqtt.Client.disconnect(options)
Disconnects client from the broker.
options
– (optional) is atable
with the following members (all are optional):callback
–function
called 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 atable
with following members (all are optional):qos
– (of typenumber
) the desired quality of service level for the subscription. Defaults to0
. See alsoQoS
enum.callback
–function
called 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 theSUBSCRIBE
message. If theSUBSCRIBE
message 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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
function QuickApp:subscribe() self.client:addEventListener('message', function(event) self:onMessage(event) end) self.client:addEventListener('subscribed', function(event) self:onSubscribed(event) end) self.client:subscribe("lights/#", { qos = mqtt.QoS.EXACTLY_ONCE }); end function QuickApp:onSubscribed(event) print("onSubscribed:", json.encode(event)) end function QuickApp:onMessage(event) print("onMessage:", json.encode(event)) if event.payload == "ON" then self:updateProperty("value", true) elseif event.payload == "OFF" then self:updateProperty("value", false) end end |
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
(qos
defaults to the one passed in theoptions
)
options
– (optional) is atable
with following members (all are optional):qos
– (of typenumber
) the desired quality of service level for subscription. Defaults to0
. See alsoQoS
enum.callback
–function
called 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 theSUBSCRIBE
message. So if theSUBSCRIBE
message 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 alsoQoS
enum.retain
– (of typebolean
) determines if the message will be saved by the broker for the specified topic as last known good value.callback
–function
called when the disconnect attempt is complete.
-
onpublished
event – triggered when PUBACK
is received from the server.
-
-
packetId
– packet ID as returned bypublish()
.
-
Example
1 2 3 4 5 6 7 8 |
function QuickApp:publishTurnedOn(id) self.client:addEventListener('published', function(event) self:onPublished(event) end) self.client:publish("lights/" .. tostring(id), "ON") end function QuickApp:onPublished(event) print("onPublished:", json.encode(event)) end |
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
–number
with error code
-
Links
MQTT 101 – How to Get Started with the lightweight IoT Protocol
Online client for quick testing
Quality of Service levels explained