MQTT Client¶
Requires AMC 2.5.2+.
MqttClient connects a plugin to an MQTT broker. It speaks MQTT 3.1.1. Over TLS it can present a client certificate, so the broker and AMC verify each other (mutual TLS).
While active, the client keeps the connection up by itself: it reconnects after failures, subscribes again after every reconnect, and reports how the link stands in state. You list topic filters in subscriptions, receive messages through messageReceived, and send with publish().
Import: import QGroundControl.SecureConnections
Certificates, the LinkState values and the rules shared with HttpsClient and GrpcClient are described in Secure Connections.
Creating a client¶
pragma Singleton
import QtQuick
import QGroundControl.SecureConnections
Item {
id: root
property string lastOrder: ""
MqttClient {
id: mqtt
url: "mqtts://broker.example.com:8883"
subscriptions: ["dispatch/orders/#"]
active: true
onMessageReceived: (topic, text, data) => {
root.lastOrder = text
}
}
}
- The client does nothing until
activeistrue. - A client disconnects when it is destroyed. Declare it in your data singleton, as above, so the connection does not depend on a view being open.
- Property order does not matter. The client connects once its component is complete, and changes made together cause a single reconnect.
Properties¶
Connection¶
Changing any of these sets the connection up again: the client disconnects, then connects with the new settings if active is true. Until it is connected again, publish() returns false.
| Property | Type | Default | Description |
|---|---|---|---|
active |
bool |
false |
Connects while true. Setting it to false disconnects and sets state to Off. |
url |
QUrl |
empty | The broker, e.g. mqtts://broker.example.com:8883. The port defaults to 8883. mqtt:// connects without TLS, to port 1883 by default. Only the host and port are used. Another scheme, a malformed url, a url without a host or with port 0, or one with a user name or password is a ConfigError. |
certificateId |
QString |
"" |
The id of a certificate the operator imported (see Certificates). Empty presents no client certificate and trusts the system CAs. If the entry has CA certificates, they replace the system CAs. Ignored with mqtt://. |
expectedHostName |
QString |
"" |
The name the broker's certificate must carry instead of the url's host, e.g. when the url uses an IP address. Empty checks the url's host. Ignored with mqtt://. |
clientId |
QString |
"" |
The MQTT client ID. Empty uses a random 23-character ID, made once per client object. A broker drops the older connection when another one connects with the same ID, so keep IDs unique. IDs of up to 23 letters and digits work with every broker. |
keepAlive |
int |
60 |
Seconds between keep-alive pings. After two unanswered pings, the client drops the connection (Unreachable, "The broker is unavailable.") and reconnects. Clamped to 0–65535. 0 turns keep-alive off: the client sends no pings and the broker never drops it for being quiet, but a connection that dies silently can go unnoticed for a long time. |
Subscriptions¶
These do not reconnect.
| Property | Type | Default | Description |
|---|---|---|---|
subscriptions |
QStringList |
[] |
Topic filters to subscribe to; the + and # wildcards are allowed. Changing the list while connected subscribes and unsubscribes only the difference. Assign a new list to change it. |
subscriptionQos |
int |
0 |
The QoS of every subscription. Clamped to 0–2. Changing it while connected subscribes every filter again. |
An invalid filter, such as dispatch/#/orders, is skipped and logged. It does not change state.
Publishing¶
| Property | Type | Default | Description |
|---|---|---|---|
clearRetainedOnDisconnect |
bool |
false |
Deletes the retained messages this client published when it disconnects cleanly. See Retained messages. Does not reconnect. |
Status¶
Read-only.
| Property | Type | Default | Description |
|---|---|---|---|
state |
LinkState |
Off |
How the link stands. See States and errors. |
errorString |
QString |
"" |
Explains state. Empty while Connecting or Connected, and while active is false. |
Methods¶
| Method | Parameters | Returns | Description |
|---|---|---|---|
publish(topic, payload, qos, retain) |
QString topic, QVariant payload, int qos = 0, bool retain = false |
bool |
Sends one message. true if the connection took it. |
topicis a topic name, without wildcards.qosis 0, 1 or 2. Other values are clamped.retainasks the broker to keep the message for later subscribers.
The payload is converted like this:
| You pass | The broker gets |
|---|---|
An ArrayBuffer |
The bytes as they are |
| A JS object or array | Compact JSON, e.g. {"id":7} |
null or undefined |
An empty payload |
| Anything else (string, number, bool) | Its text, as UTF-8 |
Binary data must be an ArrayBuffer. For a typed array, pass its buffer. The whole buffer is sent, so for a view on part of one, pass view.slice().buffer.
publish() returns false and sends nothing when:
- the MQTT connection is not up;
- a connection property changed and the new connection is not up yet. This starts with the change itself, so a handler that sets
urland then publishes getsfalse; - the topic is not a valid topic name, e.g. it is empty or contains
+or#; - the connection does not take the message.
Nothing is queued. Publish again once state is Connected.
true does not confirm delivery, also with QoS 1 or 2. The client reports no acknowledgement, and a message not yet acknowledged when the connection drops is not sent again.
Signals¶
| Signal | Arguments | Description |
|---|---|---|
messageReceived |
QString topic, QString text, QByteArray data |
A message arrived on one of the subscriptions. text is the payload decoded as UTF-8. data is the raw payload, an ArrayBuffer in QML. |
stateChanged |
-- | state changed. |
errorStringChanged |
-- | errorString changed. |
activeChanged |
-- | active changed. |
configurationChanged |
-- | url, certificateId, expectedHostName, clientId or keepAlive changed. |
subscriptionsChanged |
-- | subscriptions or subscriptionQos changed. |
clearRetainedOnDisconnectChanged |
-- | clearRetainedOnDisconnect changed. |
messageReceived carries the messages of all subscriptions. It does not say which subscription matched, whether the message was retained, or its QoS.
configurationChanged is the notify signal of all five of its properties, so a handler such as onUrlChanged also runs when keepAlive changes.
Connection behaviour¶
Connecting¶
- The broker must accept each attempt within 10 seconds, counting the connection, the TLS handshake and the broker's answer. Otherwise the client gives up the attempt with
Unreachableand tries again. mqtts://uses TLS 1.2 or later and always checks the broker's certificate chain and host name.mqtt://connects without TLS.- The client speaks MQTT 3.1.1 only. A broker that refuses it gives
ConfigError, which is not retried.
Reconnecting¶
After a failed attempt or a lost connection, the client waits and tries again. The wait doubles each time, up to 30 seconds: 1, 2, 4, 8, 16, then 30 s. It comes on top of the attempt itself, which takes up to 10 s when the broker does not answer.
- The wait drops back to 1 s after a successful connection, and after a connection property changes.
- Every connection failure except a
ConfigErroris retried, also a broker that refused the client (AuthError) or a failed TLS handshake (TlsError). - A client certificate that cannot be loaded or is not valid now (
TlsError) is tried again at most once a minute. A refused keychain prompt is not repeated: the client stays inTlsErroruntil a connection property changes, unless another client has loaded the certificate in the meantime. - A
ConfigError(a url that cannot work, a deleted certificate entry, or a broker that refuses MQTT 3.1.1) and a missing url (Off) are not retried. Change the settings, or turnactiveoff and on. - Reconnects reuse the client certificate loaded at setup. It is loaded and checked again only when the client is set up again, for example when
activeis turned off and on.
After every connect, the client subscribes to all subscriptions again.
Connected comes before the subscriptions
stateChanged fires for Connected before the client subscribes. A message you publish from that handler goes out before the subscriptions do.
Sessions¶
Sessions are always clean. The broker keeps nothing for the client between connections: no subscriptions, and no messages published while it was offline.
Retained messages are the exception. The broker sends a topic's retained message with every new subscription, so retained messages arrive again after each reconnect and when subscriptionQos changes. Make your messageReceived handler safe to run twice for the same message.
Disconnecting¶
The client disconnects when:
activebecomesfalse;- a connection property changes (it then connects again);
- its certificate entry is deleted (
statebecomesConfigError); - the client is destroyed;
- AMC quits.
These are clean disconnects, which can clear retained messages. A lost connection is not.
Retained messages¶
Publish with retain set to true to have the broker keep a message for later subscribers. To delete a topic's retained message, publish an empty payload with retain:
The client remembers the topics it published retained messages to. With clearRetainedOnDisconnect: true, it deletes those messages on a clean disconnect, which includes every connection property change. So publish retained state again whenever state becomes Connected.
- Clearing is best effort: nothing is cleared when the connection is lost.
- The remembered topics are forgotten when the client connects to a different host or port.
States and errors¶
state is a LinkState value; errorString says why. The text is translated, so show it to the operator but branch on state.
state |
When | errorString, for example |
|---|---|---|
Off |
active is false, or url is empty |
"No server is set." Empty while active is false. |
Connecting |
The connection is being set up, or an attempt is under way | Empty |
Connected |
The broker accepted the connection | Empty |
Unreachable |
No connection, no answer within 10 s, a lost connection, unanswered keep-alive pings, a broker that reported itself unavailable, or a protocol error | "The broker did not answer within 10 seconds.", "The broker is unavailable.", or the network error, e.g. "Connection refused" |
TlsError |
The TLS handshake failed, or the client certificate cannot be loaded or is not valid now | "TLS handshake failed: …", "The client certificate expired on …" |
AuthError |
The broker rejected the client or its ID, or refused a subscription | "The broker rejected the client ID.", "The broker did not authorize this client. Check the client certificate.", "The broker refused the subscription to …" |
ConfigError |
The url cannot work, the certificate entry was deleted, or the broker does not accept MQTT 3.1.1 | "The server URL must look like mqtts://host:port or mqtt://host:port.", "The server URL must not contain credentials.", "The selected certificate no longer exists.", "The broker does not accept MQTT 3.1.1." |
Each attempt sets state to Connecting and clears errorString. While the broker stays down, both keep switching between the attempt and the error.
A refused subscription leaves the connection up
When the broker refuses a subscription, state becomes AuthError and errorString names the filter. The client keeps the connection up: other subscriptions keep delivering, and publish() still works.
The client does not retry the subscription by itself. Changing subscriptionQos, or removing the filter from subscriptions and adding it back, subscribes again. state returns to Connected once no filter in subscriptions is refused: when you remove the refused filter, or when subscribing to it again succeeds. If several are refused, errorString names them all.
AMC logs connection events, errors, invalid topics and skipped filters under the MqttClientLog category.
What MqttClient does not do¶
- MQTT 5. It speaks MQTT 3.1.1 only.
- WebSockets. Only
mqtts://andmqtt://urls work. - User names and passwords. Use a client certificate. A url with credentials is a
ConfigError. - Persistent sessions. Sessions are always clean.
- A last-will message.
- Delivery confirmation.
publish()only says whether the connection took the message. - A QoS per subscription.
subscriptionQosapplies to all of them.
Examples¶
Receive work orders and report status as JSON¶
An inspection plugin receives work orders from a dispatcher and reports progress back. The broker checks AMC's client certificate (mutual TLS). The operator imports the certificate under Settings → Certificates and picks it in the plugin's settings panel.
InspectionData.qml:
pragma Singleton
import QtQuick
import QtCore
import QGroundControl
import QGroundControl.Plugin
import QGroundControl.SecureConnections
Item {
id: root
property bool enabled: false
property string certificateId: ""
property var currentOrder: null
readonly property int linkState: mqtt.state
readonly property string linkError: mqtt.errorString
Settings {
category: "Inspection"
property alias enabled: root.enabled
property alias certificateId: root.certificateId
}
MqttClient {
id: mqtt
url: "mqtts://broker.example.com:8883"
certificateId: root.certificateId
active: root.enabled
subscriptions: ["inspection/orders/+"]
subscriptionQos: 1
onMessageReceived: (topic, text, data) => {
try {
root.currentOrder = JSON.parse(text)
} catch (e) {
PluginManager.log("Inspection: ignored a message on " + topic + " that is not JSON")
}
}
onStateChanged: {
if (mqtt.state === LinkState.Connected) {
PluginManager.log("Inspection: connected to the broker")
}
}
}
// Returns false if the status was not sent. Nothing is queued.
function reportStatus(orderId, status) {
const vehicle = QGroundControl.multiVehicleManager.activeVehicle
return mqtt.publish("inspection/status/" + orderId, {
orderId: orderId,
status: status,
vehicleId: vehicle ? vehicle.id : null,
time: new Date().toISOString()
}, 1)
}
}
reportStatus("WO-1042", "started") publishes {"orderId":"WO-1042","status":"started","time":"…","vehicleId":1} to inspection/status/WO-1042. Object keys come out sorted.
In InspectionSettings.qml, below the standard header bar, let the operator pick the certificate with CertificateComboBox:
import QtQuick
import QtQuick.Layouts
import QGroundControl.Controls
import QGroundControl.Plugin
import QGroundControl.SecureConnections
RowLayout {
QGCLabel { text: qsTr("Client certificate") }
CertificateComboBox {
certificateId: InspectionData.certificateId
onCertificateIdChanged: InspectionData.certificateId = certificateId
}
}
Show the link state¶
import QtQuick
import QGroundControl.Controls
import QGroundControl.Palette
import QGroundControl.Plugin
import QGroundControl.SecureConnections
QGCLabel {
text: {
switch (InspectionData.linkState) {
case LinkState.Connected:
return qsTr("Broker: connected")
case LinkState.Connecting:
return qsTr("Broker: connecting…")
case LinkState.Off:
return qsTr("Broker: off")
default:
return qsTr("Broker: %1").arg(InspectionData.linkError)
}
}
color: InspectionData.linkState === LinkState.Connected ? qgcPal.text : qgcPal.colorOrange
}
Keep a retained status on the broker¶
A variant of the client in the data singleton above:
MqttClient {
id: mqtt
url: "mqtts://broker.example.com:8883"
certificateId: root.certificateId
active: root.enabled
clearRetainedOnDisconnect: true
// A clean disconnect deletes the status, so publish it again after every connect.
onStateChanged: {
if (mqtt.state === LinkState.Connected) {
mqtt.publish("inspection/stations/ground-1/status", { online: true }, 1, true)
}
}
}
Send and receive binary payloads¶
MqttClient {
id: mqtt
url: "mqtts://broker.example.com:8883"
subscriptions: ["dispatch/raw/in"]
active: true
onMessageReceived: (topic, text, data) => {
const bytes = new Uint8Array(data)
if (bytes.length > 0 && bytes[0] === 0x01) {
// Answer with three raw bytes.
mqtt.publish("dispatch/raw/out", new Uint8Array([0x02, 0x00, 0x2a]).buffer)
}
}
}
See also¶
- Secure Connections: certificates,
LinkState, and the rules all clients share. - HTTPS Client and gRPC Client: the other two clients.
- Mission Requests: offer a mission to the operator, e.g. one built from a received work order.
- Data Singleton: where to declare the client.