mqtt-dispatcher
Version:
Node.js message dispatcher for MQTT
77 lines (56 loc) • 3.33 kB
Markdown
MQTT dispatcher is a library that extends MQTT.js and allows to route incoming messages on a specific handler, according to defined routing rules.
[](https://chrvadala.github.io)
[](https://www.paypal.com/paypalme/chrvadala/15)
[](https://github.com/chrvadala/mqtt-dispatcher/actions)
[](https://coveralls.io/github/chrvadala/mqtt-dispatcher)
[](https://www.npmjs.com/package/mqtt-dispatcher)
[](https://www.npmjs.com/package/mqtt-dispatcher)
The implementation for **MQTT** in Javascript is [MQTT.js](https://github.com/mqttjs/MQTT.js). It is able to handle MQTT messages but it doesn't have
a built-in message dispatcher. You can subscribe different topics, but all messages are handled by a single event listener `on('message', cb)`.
This library provides a dispatch system that connects a **subscribe** operation with a specific callback. A callback is called only when an incoming message matches the provided pattern.
- [APIs](https://github.com/chrvadala/mqtt-dispatcher/blob/main/docs/api.md)
````
npm install mqtt-dispatcher
````
```javascript
const mqtt = require('mqtt')
const MqttDispatcher = require('mqtt-dispatcher')
const client = mqtt.connect('mqtt://broker.hivemq.com:1883')
const dispatcher = new MqttDispatcher(client)
client.on('connect', () => console.log('connected'));
(async () => {
await dispatcher.addRule('mqtt-dispatcher/command/logout', (topic, message) => {
console.log('RECEIVED MESSAGE', message.toString())
})
await dispatcher.addRule('mqtt-dispatcher/command/restart', (topic, message) => {
console.log('RECEIVED MESSAGE', message.toString())
})
await dispatcher.addRule('mqtt-dispatcher/command/shutdown', (topic, message) => {
console.log('RECEIVED MESSAGE', message.toString())
})
client.publish('mqtt-dispatcher/command/logout', 'logout command')
client.publish('mqtt-dispatcher/command/restart', 'restart command')
client.publish('mqtt-dispatcher/command/shutdown', 'shutdown command')
await new Promise(resolve => setTimeout(resolve, 5000))
await dispatcher.removeRule('mqtt-dispatcher/command/logout')
await dispatcher.removeRule('mqtt-dispatcher/command/restart')
await dispatcher.removeRule('mqtt-dispatcher/command/shutdown')
client.end(() => console.log('end'))
})()
```
- **0.x** - Preview version
- **1.0** - First stable version
- **1.1** - Upgrades libraries
- **1.2** - Migrates to codecov
- **2.0** - Upgrades deps; migrates to npm, [chrvadala/github-actions](https://github.com/chrvadala/github-actions) and coveralls; improves documentation
- **2.1** - Deprecated nodejs 16,18 and adds 22; Upgrades deps and github actions
- [chrvadala](https://github.com/chrvadala) (author)
- [mqtt-router](https://www.npmjs.com/package/mqtt-router)