Qt MQTT 를 사용해보기 위해 우분투 데스크탑에 빌드환경을 구축하고 예제를 실행해본다. Qt MQTT는 커머셜 라이센스 및 GPL 로 사용할 수 있으며 커머셜 라이센스를 보유하고 있다면 MaintenanceTool 을 통해 간단하게 설치할 수 있다.
#include <QtMqtt/QMqttClient>
#include <QtMqtt/QMqttMessage>
#include <QtMqtt/QMqttSubscription>
QMqttClient *client = new QMqttClient();
client->setHostname("Host Name");
client->setPort(1883);
QMqttClient::stateChanged
QMqttClient::disconnected
QMqttClient::messageReceived
QMqttClient::pingResponseReceived
if(client->state() == QMqttClient::Disconnected)
client->connectToHost();
int qos = 0;
QMqttSubscription *subscription = client->subscribe(QMqttTopicFilter("topic"), qos);
구독이 성공하면 다음 시그널에 연결하여 메세지를 수신할 수 있다.
QMqttSubscription::messageReceived
QMqttSubscription::stateChanged
QMqttSubscription::qosChanged
subscription->unsubscribe();
client->publish(QMqttTopicName("topic"), "message");
#include <QCoreApplication>
#include <QtMqtt/QMqttClient>
#include <QtMqtt/QMqttMessage>
#include <QtMqtt/QMqttSubscription>
#include <QDebug>
void subscribe(QMqttClient *client){
QString topic("sensors/house/temperature");
int qos = 0;
QMqttSubscription *subscription = client->subscribe(QMqttTopicFilter(topic), qos);
QObject::connect(subscription, &QMqttSubscription::messageReceived, [subscription](const QMqttMessage &msg){
qDebug() << "topic: " << msg.topic().name() << ", temperature: " << msg.payload().toInt() << "°C";
subscription->unsubscribe();
qApp->exit();
});
// publish message
client->publish(topic, "15");
}
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QMqttClient client;
client.setHostname("10.10.10.102"); // Raspberry pi4 IP Address.
client.setPort(1883);
QObject::connect(&client, &QMqttClient::stateChanged, [&client](){
if(client.state() == QMqttClient::Connected){
qDebug() << "Client Connected.";
subscribe(&client);
}
});
if(client.state() == QMqttClient::Disconnected){
// connect to broker
client.connectToHost();
}
return a.exec();
}