WebSockets MQTT Subscription▲
Sélectionnez
// Copyright (C) 2017 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
#include
"clientsubscription.h"
#include <QtCore/QCoreApplication>
#include <QtCore/QLoggingCategory>
Q_LOGGING_CATEGORY(lcWebSocketMqtt, "qtdemo.websocket.mqtt"
)
ClientSubscription::
ClientSubscription(QObject *
parent) : QObject(parent)
{
connect(this
, &
amp;ClientSubscription::
errorOccured, qApp, &
amp;QCoreApplication::
quit);
}
void
ClientSubscription::
setUrl(const
QUrl &
amp;url)
{
m_url =
url;
}
void
ClientSubscription::
setTopic(const
QString &
amp;topic)
{
m_topic =
topic;
}
void
ClientSubscription::
setVersion(int
v)
{
m_version =
v;
}
void
ClientSubscription::
connectAndSubscribe()
{
qCDebug(lcWebSocketMqtt) &
lt;&
lt; "Connecting to broker at "
&
lt;&
lt; m_url;
m_device.setUrl(m_url);
m_device.setProtocol(m_version ==
3
? "mqttv3.1"
: "mqtt"
);
connect(&
amp;m_device, &
amp;WebSocketIODevice::
socketConnected, this
, [this
]() {
qCDebug(lcWebSocketMqtt) &
lt;&
lt; "WebSocket connected, initializing MQTT connection."
;
m_client.setProtocolVersion(m_version ==
3
? QMqttClient::
MQTT_3_1 : QMqttClient::
MQTT_3_1_1);
m_client.setTransport(&
amp;m_device, QMqttClient::
IODevice);
connect(&
amp;m_client, &
amp;QMqttClient::
connected, this
, [this
]() {
qCDebug(lcWebSocketMqtt) &
lt;&
lt; "MQTT connection established"
;
m_subscription =
m_client.subscribe(m_topic);
if
(!
m_subscription) {
qDebug() &
lt;&
lt; "Failed to subscribe to "
&
lt;&
lt; m_topic;
emit errorOccured();
}
connect(m_subscription, &
amp;QMqttSubscription::
stateChanged,
[](QMqttSubscription::
SubscriptionState s) {
qCDebug(lcWebSocketMqtt) &
lt;&
lt; "Subscription state changed:"
&
lt;&
lt; s;
}
);
connect(m_subscription, &
amp;QMqttSubscription::
messageReceived,
[this
](QMqttMessage msg) {
handleMessage(msg.payload());
}
);
}
);
m_client.connectToHost();
}
);
if
(!
m_device.open(QIODevice::
ReadWrite))
qDebug() &
lt;&
lt; "Could not open socket device"
;
}
void
ClientSubscription::
handleMessage(const
QByteArray &
amp;msgContent)
{
// Should happen when the internal device has ready read?
qInfo() &
lt;&
lt; "New message:"
&
lt;&
lt; msgContent;
}