MQTT (Message Queuing Telemetery Transport)

H.GOO·2024년 5월 21일
0

MQTT

목록 보기
1/2

🪴 MQTT(Message Queuing Telemetery Transport)

사물인터넷(IoT)을 위한 표준 메시징 프로토콜

  • Publish / Subscribe 구조
  • 디바이스의 리소스를 적게 사용하도록 설계되어 오버헤드가 적게 발생
  • device와 cloud 간의 양방향 통신 지원
  • 수백만 개의 IoT 장치와 연결하도록 확장 가능
  • connection 생성 시간이 짧아서 불안정한 네트워크 구간에서도 사용 가능

MQTT Broker 비교

server support




🪴 mosquitto 세팅

구조, 설치, 사용이 간단하고 이식성이 좋음, 가벼움, 사용자 많음

GitHub - eclipse/mosquitto: Eclipse Mosquitto - An open source MQTT broker

1. 파일 구조

mosquitto
├── config
│    ├── mosquitto.conf
│    └── pwfile
│
├── data
│    └── mosquitto.db
│
├── log
└── docker-compose.yml

2. docker-compose.yml

version: "3.7"

services:
  mosquitto:
    image: eclipse-mosquitto
    container_name: mosquitto
    restart: always
    ports:
      - "1883:1883"
      - "9001:9001"
    volumes:
      - ./config:/mosquitto/config:rw
      - ./data:/mosquitto/data:rw
      - ./log:/mosquitto/log:rw

3. config

mosquitto.conf

mosquitto/mosquitto.conf at master · eclipse/mosquitto

allow_anonymous false
listener 1883
listener 9001
protocol websockets
persistence true
password_file /mosquitto/config/pwfile
persistence_file mosquitto.db
persistence_location /mosquitto/data/

log_dest file /mosquitto/log/mosquitto.log
log_type all
connection_messages true
log_timestamp true
  • log 설정 설명
    • log_dest file /mosquitto/log/mosquitto.log 로그의 목적지를 설정, 이 설정은 로그를 파일로 저장하도록 함.
    • log_type all 로그에 포함할 로그의 유형을 설정
      • none: 로그 기록 없음
      • information: 일반 정보 로그
      • notice: 중요하지 않은 로그
      • warning: 경고 로그
      • error: 오류 로그
      • debug: 디버그 정보 로그
      • all: 모든 로그 유형 기록
    • connection_messages true 클라이언트 연결 및 연결 해제 메시지를 포함할지 여부
      • true: 포함
      • false: 미포함
    • log_timestamp true 로그에 타임 스탬프 포함할지 여부
      • true: 포함
      • false: 미포함

pwfile

$ touch config/pwfile

4. create and run docker container

$ docker-compose up -d --build

5. create a user/password in the pwfile

# login interactively into the mqtt container
$ docker exec -it mosquitto sh

# Create new password file and add user and it will prompt for password
$ mosquitto_passwd -c /mosquitto/config/pwfile user1

# Add additional users (remove the -c option) and it will prompt for password
$ mosquitto_passwd /mosquitto/config/pwfile user2

# delete user command format
$ mosquitto_passwd -D /mosquitto/config/pwfile <user-name-to-delete>

# type 'exit' to exit out of docker container prompt
$ docker restart mosquitto



🪴 MQTT Explorer

download

MQTT Explorer

conection




🪴 React mqtt.js

MQTT.js

1. Install

$ npm install mqtt --save
# or
$ yarn add mqtt

2. Connecting

let mqttWS = useRef();

const connectMqtt = () => {
  mqttWS.current = mqtt.connect("mqtt://192.168.0.200:9001", {
    clientId: `web_${Math.random().toString(16).substr(2, 8)}`,
    username: "user1",
    password: "1234"
  });

  mqttWS.current.on("connect", () => {
    console.log("Connected");
  });

  mqttWS.current.on("error", (err) => {
    console.error("Connection error: ", err);
    mqttWS.current.end();
  });

  mqttWS.current.on("reconnect", () => {
    console.log("Reconnecting");
  });

  mqttWS.current.on("offline", () => {
    console.log("Went offline");
  });

  mqttWS.current.on("close", () => {
    console.log("Connection closed");
  });
  
  mqttWS.current.subscribe(`TOPIC/${streamId}`, 0, (error) => {
    if (error) {
      console.log("Subscribe to topics error", error);
      return;
    } else {
      console.log(`Subscribe ${streamId}`);
    }
  });
  
  mqttWS.current.on("message", (topic, message) => {
    const payload = { topic, message: JSON.parse(message) };

    if (payload.message) {
      if (payload.topic === `ZONE1/CAM${streamId}`) {
        const { bAlarmOccur, draw_info } = payload.message;
        setDrawInfo(draw_info);
      }
    } else {
      alert(JSON.parse(payload.message).error);
    }
  });
};

useEffect(() => {
  connectMqtt();
  return () => {
    if (mqttWS.current)
      mqttWS.current.end(() => {
        console.log("Disconnected");
      });
  }
}, [])

3. Unsubscribe

mqttWS.current.unsubscribe(`TOPIC/${streamId}`, (error) => {
  if (error) {
    console.log("Unsubscribe error", error);
  } else {
    console.log(`Unsubscribe ${streamId}`);
  }
});

4. Disconnecting

mqttWS.current.end(() => {
  console.log("Disconnected");
});

0개의 댓글