MQTT - mosquitto & 통신 실습
Eclipse Mosquitto
Eclipse Mosquitto is an open source (EPL/EDL licensed) message broker that implements the MQTT protocol versions 5.0, 3.1.1 and 3.1. Mosquitto is lightweight and is suitable for use on all devices
mosquitto.org
MQTT 프로토콜을 구현하는 오픈소스 기반 메시지 브로커. 이클립스 재단에 의해 관리되고 있다.
- mosquitto: MQTT 브로커
- mosquitto_pub: MQTT 메시지를 게시하는 클라이언트
- mosquitto_sub: MQTT 메시지를 구독하는 클라이언트
mosquitto -d
MQTT 브로커를 백그라운드에서 실행한다.
mosquitto_sub -h localhost -p 1883 -t /hello/#
localhost 1883 포트로 열려 있는 브로커로부터 /hello/~ 토픽을 구독한다.
mosquitto_pub -h localhost -t /hello -m "hello, world!"
localhost의 브로커에게 /hello 토픽으로 hello, world 메시지를 보낸다.
로컬 환경이 아니더라도 브로커만 있다면 통신이 가능하다. 아래 코드에서 node.js 프로그램은 pc에서, python 코드는 라즈베리 파이에서 동작했다. mosquitto = 브로커는 실행되고 있는 상황이다.
import time
import paho.mqtt.client as mqtt
from paho.mqtt.enums import CallbackAPIVersion
broker_address="192.168.137.147"
client = mqtt.Client(callback_api_version=CallbackAPIVersion.VERSION2)
client.connect(broker_address)
count = 0
while True:
count = count + 1
client.publish("hello", str(count))
print(count)
time.sleep(2.0)
import mqtt from 'mqtt';
const broker_url = "mqtt://192.168.137.147";
const client = mqtt.connect(broker_url,{
port: 1883
});
client.on("connect", () => {
// hello 토픽을 구독
client.subscribe("hello", (err) => {
if(!err) {
client.publish("/test/topic", "hello mqtt!");
}
});
});
// 구독한 메시지에 대한 응답이 온다.
client.on("message", (topic, message) => {
console.log("topic: ", topic, "message: ", message.toString());
});
MQTT over Websocket
한편, mosquitto는 websocket 기반의 통신도 지원한다. 기존의 설정을 일부 변경해보자
# in /etc/mosquitto/mosquitto.conf
listener 9001
protocol websockets
listener 1883
protocol mqtt
mosquitto 설정 파일의 내용을 수정, 브로커가 웹소켓 통신도 지원할 수 있도록 구성한다.
systemctl restart mosquitto
이후 변경된 설정을 적용할 수 있도록 mosquitto 서비스를 재시작한다. 이렇게 하면 mosquitto는 websocket 기반 통신도 지원하게 된다. 프로토콜과 관계 없이 토픽은 공유되므로 클라이언트에 따라 다른 프로토콜을 이용해도 상관 없다.
broker_address="192.168.137.147"
client = mqtt.Client(callback_api_version=CallbackAPIVersion.VERSION2, transport='websockets')
client.connect(broker_address, 9001)
const broker_url = "ws://192.168.137.147/ws"
const client = mqtt.connect(broker_url,{
clientId: "testuser",
port: 9001
});