MQTT 적용

김형우·2024년 2월 28일
0

실무

목록 보기
1/1

우분투 mqtt 적용

1. mosquitto 설치 및 환경설정

1-1. mosquitto 설치

  • sudo apt-get update
    : apt 업데이트
  • sudo apt-get install mosquitto mosquitto-clients
    : mosquitto 및 mosquitto클라이언트 설치

1-2. mosquitto 환경설정

  • sudo vim /etc/mosquitto/mosquitto.conf 또는 sudo vim /etc/mosquitto/conf.d/[임의의설정파일명].conf
    : 임의의 설정파일을 만들어서 기본적인 설정을 할수 있다.
    : mosquitto가 실행될때 먼저 읽는다.

1) mosquitto 사용자 설정

  • sudo mosquitto_passwd -c /etc/mosquitto/passwd [username]
    : mosquitto 사용자 추가 -> 명령어 실행 이후 password 두번 입력해야함
  • 환경설정 파일에 아래의 코드를 추가한다.
    allow_anonymous false : 익명의 사용자 거부.
    password_file /etc/mosquitto/passwd : 추가한 사용자 정보를 사용하도록 설정.

2) mosquitto 포트 설정

  • 기본적으로 mosquitto는 localhost:1883 포트를 사용한다.
  • 외부의 접속을 허용하기 위해서는 설정에 아래의 코드를 추가한다.
    listener 1883 : 외부의 1883(브로커) 포트 접근을 허용한다.
    listener 11884 : 외부의 11884(웹소켓) 포트 접근을 허용한다.
    protocol websockets : 웹소켓 프로토콜을 사용한다.

2. 실행

  • sudo systemctl start mosquitto
    : mosquitto 서비스 시작.
  • sudo systemctl enable mosquitto
    : mosquitto가 시스템 부팅 시 자동으로 시작되도록 설정.
  • sudo systemctl status mosquitto
    : mosquitto 상태 조회 -> active (running) 이라고 나와야함.

3. 테스트

3-1. 우분투 터미널 테스트

  • 터미널창을 2개 연다.
  • 1번 터미널창에 아래와같이 입력한다.
    mosquitto_sub -h localhost -t "test/topic" -u "username" -P "password"
    : username과 userpassword는 사용자 설정에서 추가한 사용자의 아이디, 패스워드
    : 실행하면 메세지를 받을 준비를 한다.
  • 2번 터미널 창에 아래와같이 입력한다.
    mosquitto_pub -h localhost -t "test/topic" -m "Hello World" -u "username" -P "password"
    : username과 userpassword는 사용자 설정에서 추가한 사용자의 아이디, 패스워드
    : 실행하면 1번 터미널창에 Hello World가 출력된다.

3-2. php 테스트

  • mosquitto와 php 소스는 같은 서버일 필요가 없다.
  • mosquitto는 브로커의 역할만 하기때문.
  • 테스트를 위한 php 파일은 총 세개를 준비한다.
    : publisher, client, mqttlibrary

1) publisher

<?php

require_once("phpMQTT.php");

if ($_SERVER['REQUEST_METHOD'] === 'POST' && !empty($_POST['message'])) {
    $server   = '8.8.8.12';   		// MQTT 브로커 주소
    $port     = 1883;         		// MQTT 포트 번호
    $username = '[사용자이름]';       // MQTT 사용자 이름
    $password = '[사용자비밀번호]';   // MQTT 비밀번호
    $client_id = uniqid();    		// 클라이언트 ID

    // MQTT 클라이언트 인스턴스 생성
    $mqtt = new Bluerhinos\phpMQTT($server, $port, $client_id);

    // MQTT 서버에 연결
    if ($mqtt->connect(true, NULL, $username, $password)) {
        $topic = "test/topic";
        $message = strip_tags($_POST['message']);

        // 메시지 발행
        $mqtt->publish($topic, $message, 0);
        $mqtt->close();
        $feedback = "Message published to {$topic}";
    } else {
        $feedback = "Could not connect to the MQTT server.";
    }
} else {
    $feedback = "";
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>MQTT Message Publisher</title>
</head>
<body>
<h1>MQTT Message Publisher</h1>
<form action="index.php" method="post">
    <label for="message">Message:</label><br>
    <input type="text" id="message" name="message" required><br><br>
    <input type="submit" value="Publish">
    <a href="client.php">client</a>
</form>
<p><?php echo $feedback; ?></p>
<script>
    document.getElementById("message").focus();
</script>
</body>
</html>
  • $server = '8.8.8.12'
    : mosquitto(브로커)가 설치 된 서버 아이피
  • $port = 1883
    : mosquitto(브로커) 포트
  • $topic = "test/topic"
    : 구독 할 topic

2) client

<!DOCTYPE html>
<html>
<head>
    <title>MQTT WebSocket Example with PHP</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/paho-mqtt/1.1.0/paho-mqtt.min.js"></script>
    <script>
        function MQTTconnect() {
            const client = new Paho.Client("ws://mqtt.themomos.co.kr:11884/", "clientId" + new Date().getTime());

            client.onConnectionLost = function (responseObject) {
                console.log("Connection Lost: "+responseObject.errorMessage);
            };

            client.onMessageArrived = function (message) {
                console.log("Message Arrived: "+message.payloadString);
                document.getElementById("messages").innerHTML += '<p>' + message.payloadString + '</p>';
            };

            client.connect({
                onSuccess:function(){
                    console.log("Connected");
                    client.subscribe("test/topic");
                },
                userName: "[사용자이름]",
                password: "[사용자비밀번호]"
            });
        }
    </script>
</head>
<body onload="MQTTconnect();">
<h2>MQTT over WebSockets Example</h2>
<div id="messages"></div>
</body>
</html>

3) library

https://github.com/bluerhinos/phpMQTT
: phpMQTT.php 파일을 다운받아서 사용한다.

profile
The best

0개의 댓글