Node.js에서 MQTT 프로토콜을 사용한 것을 기록하고자 한다.
Mosca는 Node.js mqtt broker로 널리 쓰이는 모듈이다. 하지만 Moscajs github을 보면 더 이상 유지 보수하지 않으니 Aedes 모듈을 쓰라고 공지해놓았다. 때문에 Mosca.js는 쓰지 않는다.
이 글에 기록해 놓을 모듈이다. 간단하게 사용하는 법은 아래와 같다.
const aedes = require('aedes')();
const mqttBroker = require('net').createServer(aedes.handle);
const mqttPort = 1883
mqttBroker.listen(mqttPort, () => {
console.log("MQTT broker listening", mqttPort);
});
더 자세한 사용법은 Aedes Docs 참고
mqtt client로 mqtt.js 모듈이 있다.
해당 모듈의 connect되는 것을 보장하고 싶어서 promise를 써서 한단계 덮어줬다.
//mqttClientFactory.js
const mqtt = require('mqtt');
const createMqttClient = ({ host, onconnect }) => new Promise((resolve, reject) => {
const client = mqtt.connect(host);
client.on('connect', () => {
if(onconnect) onconnect();
resolve(client);
});
});
const createSubscriber = async({ host, topic, onconnect=null, onerr, onmessage }) => {
const client = await createMqttClient({ host, onconnect });
client.subscribe(topic, onerr);
client.on('message', onmessage);
return client;
}
const createPublisher = async({ host, topic, onconnect=null, message, close = true }) => {
const client = await createMqttClient({ host, onconnect });
client.publish(topic, message);
if(close) client.end();
return client;
}
module.exports = {
createMqttClient,
createSubscriber,
createPublisher
};