[HC3, HC3L, YH] Quick Apps – MQTT client

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:


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:


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:

Quality of Service

Possible QoS values.

mqtt.Client.connect(uri, options)

Asynchronously creates a connection with the broker. When connection is made, onconnected event is triggered.

Parameters

  • uri – (of type string) the address of the broker. Either full URI with mqtt/mqtts scheme or just a host part. URI Scheme Specification
  • options(optional) (of type table) attributes (all are optional):
      • port – (of type number) the port to use for TCP connection. Defaults to 1883 (8883 for TLS).
      • tls – (of type table) TLS options (explained below).

     

  • keepAlivePeriod – (of type number) 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 and password – (of type string) containing user credentials for client authentication.
    • clientId – (of type string) an identifier of each MQTT client connecting to an MQTT broker. If no ID is given, a random ID will be generated.
    • cleanSession – (of type bool) indication of the broker, whether the client wants to establish a persistent session or not. Defaults to false.
    • callbackfunction that will be called when the connection attempt is complete.
    • lastWill – (of type table) used for notifying other clients, when a client disconnects ungracefully. lastWill members:
    • topic – a field of type table containing topic name,
    • payload – a field of type string with the content of the last will,
    • qos(optional) QoS of the last will,
    • retain(optional) a field of type bool.

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 type string) client certificate in PEM format.
  • allowUnauthorized – (of type bool) if you are using a self-signed certificate, pass true. 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 type string) 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:

  • sessionPresentboolean that indicates, whether the broker already has a persistent session of the client from previous interactions.
  • returnCodenumber that signals the client, if the connection attempt was successful and otherwise what the issue is. See also ConnectReturnCode enum.

Example

mqtt.Client.disconnect(options)

Disconnects client from the broker.

  • options(optional) is a table with the following members (all are optional):
    • callbackfunction 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 type string) a topic to subscribe to.
  • options(optional) is a table with following members (all are optional):
    • qos – (of type number) the desired quality of service level for the subscription. Defaults to 0. See also QoS enum.
    • callbackfunction 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 by subscribe().
    • results – (of type table) The broker sends one return code for each topic/QoS-pair it received in the SUBSCRIBE message. If the SUBSCRIBE 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

mqtt.Client.subscribe can also accept many topics, i.e. mqtt.Client.subscribe(topics, options)

Parameters

      • topics – (of type table) each item must be of either type:
        • {string topic, int qos} pair
        • string topic (qos defaults to the one passed in the options)
      • options(optional) is a table with following members (all are optional):
        • qos – (of type number) the desired quality of service level for subscription. Defaults to 0. See also QoS enum.
        • callbackfunction 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 by subscribe().
      • results – (of type table) the broker sends one return code for each topic/QoS-pair it received in the SUBSCRIBE message. So if the SUBSCRIBE 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 by unsubscribe().

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 by unsubscribe().

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 type string) the topic name
      • payload – (of type string) the actual content of the message
      • options(optional) (of type table) members (all are optional):
        • qos – (of type number) the desired quality of service level for this message. Defaults to 0. See also QoS enum.
        • retain – (of type bolean) determines if the message will be saved by the broker for the specified topic as last known good value.
        • callbackfunction called when the disconnect attempt is complete.

onpublished event – triggered when PUBACK is received from the server.

      • packetId – packet ID as returned by publish().

Example

Message Event

message event is triggered when broker forwards a message published by one of the clients to this client. Event arguments:

      • topic – (of type string) topic name
      • payload – (of type string) the actual content of the message
      • packetId:int (nil for QoS=0)
      • qos – (of type number) the desired quality of service level for this message. Defaults to 0.
      • retain – (of type bool) determines if the message was saved by the broker for the specified topic as last known good value.
      • dup – (of type bool) 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:

      • codenumber with error code

MQTT 101 – How to Get Started with the lightweight IoT Protocol

MQTT Essentials

Online client for quick testing

Quality of Service levels explained

MQTT Specification v3.1.1

April 9, 2020   16981    Tutorials    
Total 10 Votes:
0

Tell us how can we improve this post?

+ = Verify Human or Spambot ?

Comments are closed.