MqttClient

Description

The MqttClient object represents the central access communicating with an MQTT broker. An MQTT client is a program or device that uses MQTT to create a network connection to an MQTT server, also called a broker. The connection request must contain a unique client identifier. Optionally, it can contain a Will Topic, Will Message, user name, and password.

Once a connection is created, a client can subscribe to topics via MqttSubscription or publish own topics via MqttPublication.

› Inherits:ObjectArray

Properties

autoConnect

This property holds whether the MQTT client should connect to the MQTT broker automatically. Keeping this option enabled will also make the client reconnect on connection errors.

› Type:Boolean
› Default:true
› Signal:autoConnectChanged()
› Attributes:Writable

cleanSession

This property holds whether a persistent session is used or not. When the clean session flag is set to true, the client does not request a persistent session. If the client reconnects after disconnecting for any reason all information and messages that are queued from a previous session are lost.

› Type:Boolean
› Default:true
› Signal:cleanSessionChanged()
› Attributes:Writable

clientId

This property holds the client’s identifier value. Each client needs to have a unique ID to be able to connect to an MQTT broker. If no client ID is specified it will be generated automatically when a connection is established.

› Type:String
› Signal:clientIdChanged()
› Attributes:Writable

encryptConnection

This property holds whether to open SSL/TLS connections only. If disabled all traffic between MQTT client and broker is transmitted unencrypted and can be read or manipulated by an attacker easily.

› Type:Boolean
› Default:false
› Signal:encryptConnectionChanged()
› Attributes:Writable

error

This property holds the most recent error occurred while connecting to an MQTT broker.

› Type:Error
› Default:MqttClient.NoError
› Signal:errorChanged()
› Attributes:Readonly

errorString

This property holds the current human readable error string corresponding to the current value in the error property. It may include additional information such as failure reasons or locations.

› Type:String
› Signal:errorStringChanged()
› Attributes:Readonly

hostname

This property holds the hostname of the MQTT broker to connect to.

› Type:String
› Signal:hostnameChanged()
› Attributes:Writable

keepAlive

This property holds the interval at which regular ping messages are sent to the broker. Once a connection to a broker is established, the client needs to send frequent updates to propagate it can still be reached. The interval between those updates is specified by this property. The interval is specified in milliseconds. The minimum value is 1000.

› Type:SignedInteger
› Default:60000
› Signal:keepAliveChanged()
› Attributes:Writable

password

This property holds the password used for authenticating to a broker.

› Type:String
› Signal:passwordChanged()
› Attributes:Writable

port

This property holds the port to connect to the MQTT broker.

› Type:SignedInteger
› Default:0
› Signal:portChanged()
› Attributes:Writable

protocolVersion

This property holds the MQTT standard version to use for connections.

› Type:ProtocolVersion
› Default:MqttClient.MQTT_3_1_1
› Signal:protocolVersionChanged()
› Attributes:Writable

state

This property holds the current state of the MQTT client connection. See the State enumeration for more details.

› Type:State
› Default:MqttClient.Disconnected
› Signal:stateChanged()
› Attributes:Readonly

useWebSockets

This property holds whether to use WebSockets for connecting to an MQTT broker supporting WebSockets connections.

This property was introduced in InCore 2.3.

› Type:Boolean
› Default:false
› Signal:useWebSocketsChanged()
› Attributes:Writable

username

This property holds the username used for authenticating to a broker.

› Type:String
› Signal:usernameChanged()
› Attributes:Writable

willMessage

This property holds the payload of a Will Message. See mosquitto.org for more information on Will Messages.

› Type:ArrayBuffer
› Signal:willMessageChanged()
› Attributes:Writable

willQoS

This property holds the QoS (Quality of Service) level for sending the Will Message stored in in the willMessage property.

› Type:SignedInteger
› Default:0
› Signal:willQoSChanged()
› Attributes:Writable, Optional

willRetain

This property holds whether the Will Message should be retained on the broker for future subscribers to receive.

› Type:Boolean
› Default:false
› Signal:willRetainChanged()
› Attributes:Writable

willTopic

This property holds the name of the topic to which to publish the Will Message.

› Type:String
› Signal:willTopicChanged()
› Attributes:Writable

Methods

connectToHost()

This method initiates a connection to the MQTT broker. This method usually should not be called manually in favor of setting the autoConnect property.

connectToHostEncrypted()

This method initiates an encrypted connection to the MQTT broker. This method usually should not be called manually in favor of setting the autoConnect property.

disconnectFromHost()

This method disconnects from the MQTT broker. This method usually should not be called manually in favor of setting the autoConnect property.

publish(String topicName, ArrayBuffer data, UnsignedChar qos, Boolean retain)

This method manually publishes the given data for a given topic. This can be used e.g. to publish a series of topics in a loop. In most cases MqttPublication should be used instead.

This method was introduced in InCore 2.6.

requestPing()

This method Sends a ping message to the broker and expects a reply. If the connection is active, the MQTT client will automatically send a ping message at keepAlive intervals. To check whether the ping is successful, connect to the pingResponseReceived() signal. Returns true if the ping request could be sent.

› Returns:Boolean

Signals

brokerSessionRestored()

This signal is emitted after a client has successfully connected to a broker with the cleanSession property set to false, and the broker has restored the session. Sessions can be restored if a client has connected previously using the same clientId.

connected()

This signal is emitted when a connection has been established.

disconnected()

This signal is emitted when a connection has been closed. A connection may be closed when disconnectFromHost() is called or when the broker disconnects.

errorOccurred()

This signal is emitted whenever an error has occurred, regardless of whether the error property has changed or not. In contrast to the change notification signal of the error property this signal is also emitted several times if a certain error occurs several times in succession.

pingResponseReceived()

This signal is emitted after the broker responds to a requestPing() call or a keepAlive ping message, and the connection is still valid.

Enumerations

Error

This enumeration describes all the possible errors which can occur when connecting to an MQTT broker.

Name Value Description
MqttClient.NoError 0 No error occurred or was detected.
MqttClient.InvalidProtocolVersion 1 Invalid protocol version: the broker does not accept a connection using the specified protocol version.
MqttClient.IdRejected 2 ID rejected: the client ID is malformed. This might be related to its length.
MqttClient.ServerUnavailable 3 Server unavailable: the network connection has been established, but the service is unavailable on the broker side.
MqttClient.BadUsernameOrPassword 4 Bad username or password: the data in the username or password is malformed.
MqttClient.NotAuthorized 5 Not authorized: the client is not authorized to connect.
MqttClient.TransportInvalid 256 Invalid transport: the underlying transport caused an error. For example, the connection might have been interrupted unexpectedly.
MqttClient.ProtocolViolation 257 Protocol violation: the client encountered a protocol violation, and therefore closed the connection.
MqttClient.UnknownError 258 Unknown error: an unknown error occurred.
MqttClient.Mqtt5SpecificError 259 The error is related to MQTT protocol level 5. A reason code might provide more details.

ProtocolVersion

This enumeration describes The protocol version of the MQTT standard to use during communication with a broker.

Name Value Description
MqttClient.MQTT_3_1 3 MQTT Standard 3.1.
MqttClient.MQTT_3_1_1 4 MQTT Standard 3.1.1, publicly referred to as version 4.
MqttClient.MQTT_5_0 5 MQTT Standard 5.0.

State

This enumeration describes specifies the states a client can enter.

Name Value Description
MqttClient.Disconnected 0 The client is disconnected from the broker.
MqttClient.Connecting 1 A connection request has been made, but the broker has not approved the connection yet.
MqttClient.Connected 2 The client is connected to the broker.

Example

import InCore.Foundation 2.5
import InCore.Mqtt 2.5

Application {
    // create an MQTT client which subscribes a topic
    MqttClient {
        clientId: "MqttClientExample"

        // configure broker host parameters
        hostname: "mqtt.inhub.de"
        port: 1883
        username: "inhub"
        password: "mqtt"
        encryptConnection: true
        autoConnect: true

        // use MQTT 5 protocol
        protocolVersion: MqttClient.MQTT_5_0

        // send keepalive messages to broker every 5 seconds
        keepAlive: 5000

        willTopic: "incore/lastWords"
        willMessage: "Good bye!"

        // define example subscription
        MqttSubscription {
            MqttTopic {
                name: "livingRoom/temperature"
                onDataChanged: console.log(name, data)
            }
        }
    }
}