1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
|
// Copyright (C) 2018 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only
#include "configuration.h"
#include <QCoreApplication>
#include <QMqttClient>
#include <QSslSocket>
#include <QTimer>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QCoreApplication::setApplicationName(QStringLiteral("qtmqtt_pub"));
QCoreApplication::setApplicationVersion(QStringLiteral("1.0"));
// Create the client
Configuration description;
auto *client = createClientWithConfiguration(&a, &description, true);
if (!client)
return -1;
a.connect(client, &QMqttClient::errorChanged, [&client](const QMqttClient::ClientError e) {
if (e == QMqttClient::NoError)
return;
qWarning() << "Error Occurred:" << e << " Client state:" << client->state();
client->disconnectFromHost();
});
a.connect(client, &QMqttClient::messageSent, [&client] (quint32 id) {
qInfo() << "Message with ID:" << id << " sent";
client->disconnectFromHost();
});
a.connect(client, &QMqttClient::stateChanged, [&client] (QMqttClient::ClientState s) {
if (s == QMqttClient::Disconnected) {
client->deleteLater();
qApp->quit();
}
});
a.connect(client, &QMqttClient::connected, [&client, description]() {
qInfo() << "Message:";
qInfo() << " Topic:" << description.topic << " QoS:" << description.qos
<< " Retain:" << description.retain;
qInfo() << " Content: " << description.content.left(50);
client->publish(description.topic,
description.content,
description.qos,
description.retain);
if (description.qos == 0)// 0 has no acknowledgment
QTimer::singleShot(500, client, &QMqttClient::disconnectFromHost);
});
#ifndef QT_NO_SSL
if (description.useEncryption)
client->connectToHostEncrypted(description.sslConfiguration);
else
#endif
client->connectToHost();
return a.exec();
}
|