ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • MQTT 브로커 (mosquitto) 설치 및 테스트 (1)
    DevOps 2023. 7. 18. 13:22

    MQTT(MQ Telemetry Transport)는 경량의 메시징 프로토콜로, 네트워크 상에서 작은 디바이스들 사이에서 데이터를 교환하는 데 사용됩니다. MQTT는 특히 제한된 대역폭과 신뢰성이 낮은 네트워크 환경에서 동작하는 IoT(Internet of Things) 장치들 간의 통신에 많이 사용됩니다. 

     

    저는 IoT 기기들이 MQTT 프로토콜을 이용해 전송하는 공기질 측정데이터를 받기위해 MQTT 브로커를 설치하려고합니다.

     

    MQTT란?

    MQTT는 클라이언트-브로커(Broker) 모델을 기반으로 동작합니다.

    • 클라이언트 : 메세지 생성
    • 브로커 : 클라이언트로부터 받은 메세지를 다른 클라이언트에게 전달

    브로커는 중간 매개체 역할을 담당하고, 클라이언트는 직접 메세지를 전달하는 클라이언트에 통신하지않고, 브로커를 통해 메세지를 전달받습니다.

     

    MQTT 프로토콜은 메세지를 전달할때, pub(publisth)/sub(subscribe) 패턴을 사용합니다.

    메세지를 특정 주제(topic)에 발행(publish)하고 해당 주제(topic)을 구독(subscribe)하는 클라이언트들이 메시지를 수신할수 있게 합니다.

    Broker , Publisher, Subscriber 구조로 되어있습니다.

     

    장비는 mqtt 브로커에 publish을 하여 센서데이터를 특정토픽을 생성하여 보내고,

    수신자는 mqtt 브로커에 센서데이터의 토픽을 구독하여 데이터를 받으려고합니다

     

    저는 MQTT 프토콜을 이용해 메세지를 수신받기도 하고, 전송도 할 예정입니다.

     

    MQTT 브로커는 mosquitto라는 라이브러리를 주로 사용합니다.

    mosquitto를 설치해보겠습니다.

    1. mosquitto 설치

    [user01@test ~]$ yum search mosquitto
    Loaded plugins: fastestmirror, langpacks
    Repodata is over 2 weeks old. Install yum-cron? Or run: yum makecache fast
    Determining fastest mirrors
    Warning: No matches found for: mosquitto
    No matches found

    이렇게 했을떄 No matche found 오류가 발생한다면, epql-relase를 다운받아야합니다.

    [user01@test ~]$ sudo yum install -y epel-release
    [sudo] password for user01:
    Loaded plugins: fastestmirror, langpacks
    Determining fastest mirrors
    local                                                                                                                                                 | 3.6 kB  00:00:00
    No package epel-release available.
    Error: Nothing to do

    다운을 받으려고하는데도 오류가 발생한다면, mirror 사이트를 설정해줘야합니다.

     

    [user01@test /]# cd /etc/yum.repos.d
    [user01@test yum.repos.d]# ls
    Daum.repo  epel.repo  epel-testing.repo  local.repo  repo
    [user01@test yum.repos.d]# sudo vi Daum.repo

    yum.reposd.d 하위에 Daum.repo를 생성합니다. (저는 미리 생성하였습니다)

     

    생성한 후 아래와같이 입력을 해주시고 저장을 해주시면 됩니다.

    [base]
    name=CentOS-$releasever - Base
    baseurl=http://ftp.daumkakao.com/centos/$releasever/os/$basearch/
    gpgcheck=0
    
    [updates]
    name=CentOS-$releasever - Updates
    baseurl=http://ftp.daumkakao.com/centos/$releasever/updates/$basearch/
    gpgcheck=0
    
    [extras]
    name=CentOS-$releasever - Extras
    baseurl=http://ftp.daumkakao.com/centos/$releasever/extras/$basearch/
    gpgcheck=0

     

    그리고 다시 epel-release를 다운받습니다.

    [user01@test yum.repos.d]$ sudo yum -y install epel-release
    Loaded plugins: fastestmirror, langpacks
    Loading mirror speeds from cached hostfile
    Resolving Dependencies
    --> Running transaction check
    ---> Package epel-release.noarch 0:7-11 will be installed
    --> Finished Dependency Resolution
    
    Dependencies Resolved
    
    =============================================================================================================================================================================
     Package                                       Arch                                    Version                                 Repository                               Size
    =============================================================================================================================================================================
    Installing:
     epel-release                                  noarch                                  7-11                                    extras                                   15 k
    
    Transaction Summary
    =============================================================================================================================================================================
    Install  1 Package
    
    Total download size: 15 k
    Installed size: 24 k
    Downloading packages:
    epel-release-7-11.noarch.rpm                                                                                                                          |  15 kB  00:00:00
    Running transaction check
    Running transaction test
    Transaction test succeeded
    Running transaction
      Installing : epel-release-7-11.noarch                                                                                                                                  1/1
      Verifying  : epel-release-7-11.noarch                                                                                                                                  1/1
    
    Installed:
      epel-release.noarch 0:7-11
    
    Complete!

    epel 설치 후 mosquitto를 설치합니다.

     

    [user01@test yum.repos.d]$ sudo yum install mosquitto
    Loaded plugins: fastestmirror, langpacks
    Loading mirror speeds from cached hostfile
    epel/x86_64/metalink                                                                                                                                  | 6.1 kB  00:00:00
     * epel: mirror-icn.yuki.net.uk
    epel                                                                                                                                                  | 4.7 kB  00:00:00
    (1/3): epel/x86_64/group_gz                                                                                                                           |  99 kB  00:00:00
    (2/3): epel/x86_64/updateinfo                                                                                                                         | 1.0 MB  00:00:00
    (3/3): epel/x86_64/primary_db                                                                                                                         | 7.0 MB  00:00:01
    Resolving Dependencies
    --> Running transaction check
    ---> Package mosquitto.x86_64 0:1.6.10-1.el7 will be installed
    --> Processing Dependency: libwebsockets.so.13()(64bit) for package: mosquitto-1.6.10-1.el7.x86_64
    --> Running transaction check
    ---> Package libwebsockets.x86_64 0:3.0.1-2.el7 will be installed
    --> Processing Dependency: libuv.so.1()(64bit) for package: libwebsockets-3.0.1-2.el7.x86_64
    --> Running transaction check
    ---> Package libuv.x86_64 1:1.44.2-1.el7 will be installed
    --> Finished Dependency Resolution
    
    Dependencies Resolved
    
    =============================================================================================================================================================================
     Package                                      Arch                                  Version                                        Repository                           Size
    =============================================================================================================================================================================
    Installing:
     mosquitto                                    x86_64                                1.6.10-1.el7                                   epel                                287 k
    Installing for dependencies:
     libuv                                        x86_64                                1:1.44.2-1.el7                                 epel                                145 k
     libwebsockets                                x86_64                                3.0.1-2.el7                                    epel                                118 k
    
    Transaction Summary
    =============================================================================================================================================================================
    Install  1 Package (+2 Dependent packages)
    
    Total download size: 549 k
    Installed size: 1.4 M
    Is this ok [y/d/N]: y
    Downloading packages:
    warning: /var/cache/yum/x86_64/7/epel/packages/libuv-1.44.2-1.el7.x86_64.rpm: Header V4 RSA/SHA256 Signature, key ID 352c64e5: NOKEY
    Public key for libuv-1.44.2-1.el7.x86_64.rpm is not installed
    (1/3): libuv-1.44.2-1.el7.x86_64.rpm                                                                                                                  | 145 kB  00:00:00
    (2/3): mosquitto-1.6.10-1.el7.x86_64.rpm                                                                                                              | 287 kB  00:00:00
    (3/3): libwebsockets-3.0.1-2.el7.x86_64.rpm                                                                                                           | 118 kB  00:00:00
    -----------------------------------------------------------------------------------------------------------------------------------------------------------------------------
    Total                                                                                                                                        812 kB/s | 549 kB  00:00:00
    Retrieving key from file:///etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL-7
    Importing GPG key 0x352C64E5:
     Userid     : "Fedora EPEL (7) <epel@fedoraproject.org>"
     Fingerprint: 91e9 7d7c 4a5e 96f1 7f3e 888f 6a2f aea2 352c 64e5
     Package    : epel-release-7-11.noarch (@extras)
     From       : /etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL-7
    Is this ok [y/N]: y
    Running transaction check
    Running transaction test
    Transaction test succeeded
    Running transaction
      Installing : 1:libuv-1.44.2-1.el7.x86_64                                                                                                                               1/3
      Installing : libwebsockets-3.0.1-2.el7.x86_64                                                                                                                          2/3
      Installing : mosquitto-1.6.10-1.el7.x86_64                                                                                                                             3/3
      Verifying  : libwebsockets-3.0.1-2.el7.x86_64                                                                                                                          1/3
      Verifying  : mosquitto-1.6.10-1.el7.x86_64                                                                                                                             2/3
      Verifying  : 1:libuv-1.44.2-1.el7.x86_64                                                                                                                               3/3
    
    Installed:
      mosquitto.x86_64 0:1.6.10-1.el7
    
    Dependency Installed:
      libuv.x86_64 1:1.44.2-1.el7                                                       libwebsockets.x86_64 0:3.0.1-2.el7
    
    Complete!

     

    mosquttio 가 설치가 되었으면, 한번 실행해봅니다.

     

    [user01@test yum.repos.d]$ service mosquitto start
    Redirecting to /bin/systemctl start mosquitto.service
    ==== AUTHENTICATING FOR org.freedesktop.systemd1.manage-units ===
    Authentication is required to manage system services or units.
    Authenticating as: user01
    Password:
    ==== AUTHENTICATION COMPLETE ===

    정상적으로 실행이 된것을 확인 할수있습니다.

     

    [user01@test yum.repos.d]$ service mosquitto status
    Redirecting to /bin/systemctl status mosquitto.service
    ● mosquitto.service - Mosquitto MQTT v3.1/v3.1.1 Broker
       Loaded: loaded (/usr/lib/systemd/system/mosquitto.service; disabled; vendor preset: disabled)
       Active: active (running) since Mon 2023-07-17 17:37:13 KST; 3s ago
         Docs: man:mosquitto.conf(5)
               man:mosquitto(8)
     Main PID: 41601 (mosquitto)
       CGroup: /system.slice/mosquitto.service
               └─41601 /usr/sbin/mosquitto -c /etc/mosquitto/mosquitto.conf
    
    Jul 17 17:37:13 communication2 systemd[1]: Starting Mosquitto MQTT v3.1/v3.1.1 Broker...
    Jul 17 17:37:13 communication2 mosquitto[41601]: 1689583033: mosquitto version 1.6.10 starting
    Jul 17 17:37:13 communication2 mosquitto[41601]: 1689583033: Config loaded from /etc/mosquitto/mosquitto.conf.
    Jul 17 17:37:13 communication2 mosquitto[41601]: 1689583033: Opening ipv4 listen socket on port 1883.
    Jul 17 17:37:13 communication2 mosquitto[41601]: 1689583033: Opening ipv6 listen socket on port 1883.
    Jul 17 17:37:13 communication2 systemd[1]: Started Mosquitto MQTT v3.1/v3.1.1 Broker.

    상태를 확인하여 실행 여부를 확인 할수있습니다.

     

    mosquitto는 1883 포트를 기본으로 사용하고있습니다.

    프로세스까지 정상적으로 실행되고있는지 확인해보겠습니다.

    [user01@test yum.repos.d]$ netstat -nap | grep LISTEN
    (Not all processes could be identified, non-owned process info
     will not be shown, you would have to be root to see it all.)
    tcp        0      0 0.0.0.0:8039            0.0.0.0:*               LISTEN      -
    tcp        0      0 0.0.0.0:111             0.0.0.0:*               LISTEN      -
    tcp        0      0 0.0.0.0:6000            0.0.0.0:*               LISTEN      -
    tcp        0      0 127.0.0.1:631           0.0.0.0:*               LISTEN      -
    tcp        0      0 127.0.0.1:25            0.0.0.0:*               LISTEN      -
    tcp        0      0 127.0.0.1:9050          0.0.0.0:*               LISTEN      338371/./bin/tor
    tcp        0      0 0.0.0.0:1883            0.0.0.0:*               LISTEN      -
    tcp6       0      0 :::8039                 :::*                    LISTEN      -
    tcp6       0      0 :::111                  :::*                    LISTEN      -
    tcp6       0      0 :::6000                 :::*                    LISTEN      -
    tcp6       0      0 ::1:631                 :::*                    LISTEN      -
    tcp6       0      0 ::1:25                  :::*                    LISTEN      -
    tcp6       0      0 :::1883                 :::*                    LISTEN      -

    1883 포트가 정상적으로 프로세스에 등록된것을 확인할 수 있습니다

     

    2. 게시, 구독 테스트

    실행된 후 로컬내부에서 간단하게 테스트를 할수있습니다. (localhost 만 가능합니다!)

    일단 mosquitto가 설치된 터미널 창을 두개 띄웁니다.

     

    mosquiito도 물론 실행이 되어있는 상태여야합니다.

     

    첫번째 창에서는 publish(게시)을 진행합니다.

    [user01@test ~]$ mosquitto_pub -h localhost -p 1883 -t firsttest -m "hello, happy day"
    • -h localhost(ip주소) : 게시를 하려는 ip 주소 입력 
    • -p 1883 : 포트 (명시하지않으면 디폴트 포트인 1883을 사용합니다)
    • -t firsttest : 토픽(주제) , 게시를 하려는 토픽을 입력합니다.
    • -m "hello, happy day" : 메세지, 게시를 통해 전달하려는 메세지입니다.

    두번째 창에는 subscribe(구독)을 진행합니다. 

    [user01@test ~]$ mosquitto_sub -h localhost -p 1883 -t firsttest
    • -h localhost(ip주소) : 게시가 되고있는(구독하고싶은) 기기의 ip주소를 입력합니다. 
    • -p 1883 : 게시가 되고있는 기기의 포트 (명시하지않으면 디폴트 포트인 1883을 사용합니다)
    • -t firsttest : 토픽(주제), 구독하고싶은 토픽을 입력합니다.

    이렇게 입력하면, 두번째 구독 창은 특정 토픽으로 게시를 할때까지 대기 상태가됩니다.

     

    첫번째 창에서 게시를 진행하고 계속 메세지를 보내면

    [user01@test ~]$ mosquitto_pub -h localhost -p 1883 -t firsttest -m "hello, happy day"
    [user01@test ~]$ mosquitto_pub -h localhost -p 1883 -t firsttest -m "테스트 입니다."
    [user01@test ~]$ mosquitto_pub -h localhost -p 1883 -t firsttest -m "mosquitto 테스트입."

    두번째 창에서는 구독한 토픽인 firsttest에 대한 메세지를 받게 됩니다.

    [user01@test ~]$ mosquitto_sub -h localhost -p 1883 -t firsttest
    hello, happy day
    테스트 입니다.
    mosquitto 테스트입.

     

    이렇게 하면 mqtt 브로커인 mosquitto의 기본적인 설치 및 테스트는 끝입니다.

     

    다음글에서는 외부에서 mqtt프로토콜로 게시되고 있는 데이터를 받기 위한 과정을 작성하겠습니다! 

Designed by Tistory.