한국어
Qt
 

Qt MQTT 를 사용해보기 위해 우분투 데스크탑에 빌드환경을 구축하고 예제를 실행해본다. Qt MQTT는 커머셜 라이센스 및 GPL 로 사용할 수 있으며 커머셜 라이센스를 보유하고 있다면 MaintenanceTool 을 통해 간단하게 설치할 수 있다.

여기서는 오픈소스 라이센스하에서 사용할 것이므로 직접 소스코드를 빌드하여 빌드환경을 구축한다. 기본적으로 Qt가 설치되어 있어야하며 여기서는 이 과정 (Qt 설치)을 생략한다.
 

Qt MQTT 구축

다음은 git저장소를 클론하고 빌드하는 과정을 보여준다.
$ git clone https://code.qt.io/qt/qtmqtt.git
$ cd qtmqtt
$ git checkout 5.12.9
$ ~/Qt/5.12.5/gcc_64/bin/qmake
$ make
$ make install
 
이제 프로젝트 파일(.pro)에 다음 줄을 추가하면 mqtt 모듈을 사용할 수 있다.
QT    += mqtt
 
클래스를 사용하기 위해 관련 (클라이언트)헤더를 포함한다.
#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");

 

pub/sub 예제

이제 간단한 pus/sub예제를 실행 해본다.
브로커는 라즈베리파이4에 mosquitto 를 설치하여 구축한다. 다음의 명령줄로 간단하게 설치할 수 있다.
pi@raspberrypi:~ $ sudo apt install mosquitto
 
다음은 우분투 데스크탑에서 실행되는 간단한 클라이언트 예제를 보여준다.
#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();
}
실행결과:
qtmqtt.png
번호 제목 글쓴이 날짜 조회 수
공지 Qt프로그래밍(QtQuick) Beginner를 위한 글 읽는 순서 운영자 2019.01.05 86057
139 멀티 스레드환경, 스레드에 안전한 이벤트처리 makersweb 2016.10.27 5029
138 C++로 구현된 모델을 QML의 ListView에서 참조 file makersweb 2019.09.07 4933
137 Qml 기본 컴포넌트 강좌 (3) - 배치(positioning) 컴포넌트 file 운영자 2019.02.10 4886
136 Qt 멀티 스레드 프로그래밍 시 유의해야 할 몇 가지 makersweb 2020.01.13 4882
135 QNetworkAccessManager를 통해 HTTP POST 하는 예제 makersweb 2019.01.17 4790
134 Windows에서 Qt D-Bus를 사용하여 프로세스간 통신(IPC) file makersweb 2019.05.02 4495
133 Qt응용프로그램 실행 시 콘솔창(터미널)같이 띄우기 file makersweb 2019.01.16 4495
132 라즈베리파이4에 대한 Qt 5.14.1 크로스컴파일 [1] file makersweb 2020.02.12 4452
131 QML에서 동적으로 텍스트 다국어 처리 file makersweb 2018.11.04 4225
130 Qt기반의 오픈소스 프로젝트들 - 2 운영자 2019.07.21 4015
129 QPA 플러그인과 EGLFS file makersweb 2017.11.21 3935
128 열거형(enum)을 QML에서 사용하는 방법과 문자열(QString)로 얻기 makersweb 2019.08.20 3896
127 QML에서 앵커(anchors)로 위치 지정 file makersweb 2021.10.05 3858
126 Qt 를 사용하거나 기반으로 하는 응용프로그램 file makersweb 2021.01.30 3834
125 Qt 3D Studio 시작하기 file makersweb 2018.01.11 3829
124 Qt Logging Rule, Qt 프레임워크 로그 출력 makersweb 2017.01.13 3707
123 Qml에서 키보드 입력 이벤트 핸들링 file makersweb 2018.08.09 3600
122 Qt Bluetooth를 이용한 시리얼(Serial) 통신 file makersweb 2019.02.17 3584
121 Qt Version확인 방법 makersweb 2018.03.29 3524
120 QML, 이미지, 폰트등을 바이너리 리소스로 만들기 makersweb 2019.06.24 3522