{"id":21838263,"url":"https://github.com/pera-swarm/mqtt-router","last_synced_at":"2025-04-14T10:21:31.054Z","repository":{"id":55001798,"uuid":"311357363","full_name":"Pera-Swarm/mqtt-router","owner":"Pera-Swarm","description":"An easy-to-use and flexible routing library for MQTT.","archived":false,"fork":false,"pushed_at":"2023-09-08T16:17:40.000Z","size":69,"stargazers_count":2,"open_issues_count":0,"forks_count":4,"subscribers_count":0,"default_branch":"main","last_synced_at":"2025-04-14T07:54:54.319Z","etag":null,"topics":["iot","mqtt","mqtt-client","mqtt-router","pera-swarm"],"latest_commit_sha":null,"homepage":"","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"lgpl-2.1","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/Pera-Swarm.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2020-11-09T14:03:34.000Z","updated_at":"2023-11-10T02:40:17.000Z","dependencies_parsed_at":"2024-11-26T14:42:40.829Z","dependency_job_id":null,"html_url":"https://github.com/Pera-Swarm/mqtt-router","commit_stats":{"total_commits":45,"total_committers":1,"mean_commits":45.0,"dds":0.0,"last_synced_commit":"8dcefc4f608e768b0f1b33b68adbe5db1100c895"},"previous_names":[],"tags_count":9,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Pera-Swarm%2Fmqtt-router","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Pera-Swarm%2Fmqtt-router/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Pera-Swarm%2Fmqtt-router/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Pera-Swarm%2Fmqtt-router/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/Pera-Swarm","download_url":"https://codeload.github.com/Pera-Swarm/mqtt-router/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248860006,"owners_count":21173344,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["iot","mqtt","mqtt-client","mqtt-router","pera-swarm"],"created_at":"2024-11-27T21:09:40.414Z","updated_at":"2025-04-14T10:21:31.029Z","avatar_url":"https://github.com/Pera-Swarm.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"[![npm (scoped)](https://img.shields.io/npm/v/@pera-swarm/mqtt-router.svg)](https://github.com/Pera-Swarm/mqtt-router/) [![License: LGPL v3](https://img.shields.io/badge/License-LGPL_v2.1-blue.svg)](https://www.gnu.org/licenses/lgpl-2.1)\n# mqtt-router \n\nAn easy-to-use and flexible routing library for MQTT.\n\n## Overview\n@pera-swarm/mqtt-router is a library for handling MQTT publish/subscribe capabilities with a straight forward routing architecture. \n\nThis is a [Node.js](https://nodejs.org/en/) library available on both npm registry and GitHub package registry.\n\n### Usage\n\n#### 1. Installation \nInstallation done using `npm install` command:\n\n```bash\nnpm i --save @pera-swarm/mqtt-router\n```\n\nAlso, you need to install [`mqtt`](https://www.npmjs.com/package/mqtt) library as well.\n\n```bash\nnpm i --save mqtt\n```\n\n#### 2. Set up Routes\n\nCreate routes for subscribe and publish:\n\n##### routes.js\n\n```js\n// Sample dynamic route list with handler functions\nconst SAMPLE_ROUTES = [\n    {\n        topic: 'v1/sample',\n        allowRetained: true,\n        subscribe: true,\n        publish: false,\n        handler: (msg) =\u003e {\n            const data = JSON.parse(msg);\n            console.log('Sample subscription picked up the topic', data);\n        }\n    }\n];\n\nmodule.exports = SAMPLE_ROUTES;\n```\n\n#### 3. Start the Router\n\nYou should configure your own mqttOptions according to your mqtt broker and application settings.\n\n##### index.js\n\n```js\n// Configure mqttClient\nconst mqttClient = require('mqtt');\nconst mqttOptions = {\n    port: 1883,\n    clientId: process.env.MQTT_CLIENT,\n    username: process.env.MQTT_USER || '',\n    password: process.env.MQTT_PASS || ''\n};\nconst mqtt = mqttClient.connect(process.env.MQTT_HOST, mqttOptions);\n\n// Import MQTTRouter from mqtt-router\nconst { MQTTRouter } = require('@pera-swarm/mqtt-router');\nconst routes = require('./routes');\n\nvar router;\n\n// Sample MQTT Message Options\nconst SAMPLE_OPTIONS = { qos: 2, rap: true, rh: true };\n\n// Sample setup function that runs on connect\nconst SAMPLE_SETUP_FN = () =\u003e {\n    console.log('sample setup fn');\n};\n\n// Sample MQTT Error handler function\nconst SAMPLE_ON_ERROR_FN = (err) =\u003e {\n    console.log('error: mqtt');\n    console.log(err);\n};\n\nrouter = new MQTTRouter(\n    mqtt,\n    routes,\n    SAMPLE_OPTIONS,\n    SAMPLE_SETUP_FN,\n    SAMPLE_ON_ERROR_FN\n);\n\nrouter.start();\n```\n\n`router.start()` will listen to the subscribed routes that are specified as `subscribed: true` in the route \nspecification and then if the subscriber picked up a message for the associated topic, the MQTTRouter will call the relevant `handler` funtion.\n\nYou can also wrap the routes using `wrapper` function to include additional higher level attribute to the handler function as well.\n\n##### index.js\n\n```js\n// Import MQTTRouter and wrapper from mqtt-router\nconst { MQTTRouter, wrapper } = require('@pera-swarm/mqtt-router');\nconst routes = require('./routes');\n\nvar router;\n\n// Sample MQTT Message Options\nconst SAMPLE_OPTIONS = { qos: 2, rap: true, rh: true };\n\n// Sample setup function that runs on connect\nconst SAMPLE_SETUP_FN = () =\u003e {\n    console.log('sample setup fn');\n};\n\n// Sample MQTT Error handler function\nconst SAMPLE_ON_ERROR_FN = (err) =\u003e {\n    console.log('error: mqtt');\n    console.log(err);\n};\n\n// Sample higher level attribute for the handler function\nconst sampleAttrib = {\n    time: Date.now()\n};\n\nrouter = new MQTTRouter(\n    mqtt,\n    wrapper(routes, sampleAttrib),\n    SAMPLE_OPTIONS,\n    SAMPLE_SETUP_FN,\n    SAMPLE_ON_ERROR_FN\n);\n\nrouter.start();\n```\n\n##### routes.js\n\n```js\n// Sample dynamic route list with handler functions.\n// sampleAttrib will be added to the handler function as the second parameter.\nconst SAMPLE_ROUTES = [\n    {\n        topic: 'v1/sample',\n        allowRetained: true,\n        subscribe: true,\n        publish: false,\n        handler: (msg, attrib) =\u003e {\n            const data = JSON.parse(msg);\n            // console.log(attrib);\n            console.log('Sample subscription picked up the topic', data);\n        }\n    }\n];\n\nmodule.exports = SAMPLE_ROUTES;\n```\n\n### Useful\n\n\u003e Note: You can also configure a topic prefix by configuring an environment variable *`MQTT_CHANNEL`*. \n(example: `MQTT_CHANNEL=beta` in a .env file locally)\n\n\n### Contribute\n\n#### 1. Install dependencies\n\nInstall project dependencies.\n\n```bash\nnpm install\n```\n\n#### 2. Testing\n\n\u003e Note: Before running the test cases, you should configure environment variables `MQTT_HOST`,`MQTT_USER`, `MQTT_PASS`, \nand `MQTT_CLIENT`. Please refer `sample.nodemon.json` file for nodemon environment variable configuration.\n\nManually run the test cases.\n\n```bash\nnode test/index.js\n```\n\nor you can use nodemon script once environment variables configured correctly.\n\n```bash\nnpm run client\n```\n\n\u003chr/\u003e\n\n## Documentation\n\n* \u003ca href=\"#route\"\u003e\u003ccode\u003e\u003cb\u003eRoute\u003c/b\u003e\u003c/code\u003e\u003c/a\u003e\n* \u003ca href=\"#mqttrouter\"\u003e\u003ccode\u003e\u003cb\u003eMQTTRouter\u003c/b\u003e\u003c/code\u003e\u003c/a\u003e\n  * \u003ca href=\"#mqttrouter-start\"\u003e\u003ccode\u003emqttRouter.\u003cb\u003estart()\u003c/b\u003e\u003c/code\u003e\u003c/a\u003e\n  * \u003ca href=\"#mqttrouter-pushToPublishQueue\"\u003e\u003ccode\u003emqttRouter.\u003cb\u003epushToPublishQueue()\u003c/b\u003e\u003c/code\u003e\u003c/a\u003e\n  * \u003ca href=\"#mqttrouter-addRoute\"\u003e\u003ccode\u003emqttRouter.\u003cb\u003eaddRoute()\u003c/b\u003e\u003c/code\u003e\u003c/a\u003e\n  * \u003ca href=\"#mqttrouter-removeRoute\"\u003e\u003ccode\u003emqttRouter.\u003cb\u003eremoveRoute()\u003c/b\u003e\u003c/code\u003e\u003c/a\u003e\n* \u003ca href=\"#wrapper\"\u003e\u003ccode\u003e\u003cb\u003ewrapper\u003c/b\u003e\u003c/code\u003e\u003c/a\u003e\n* \u003ca href=\"#queue\"\u003e\u003ccode\u003e\u003cb\u003eQueue\u003c/b\u003e\u003c/code\u003e\u003c/a\u003e\n  * \u003ca href=\"#queue-begin\"\u003e\u003ccode\u003equeue.\u003cb\u003ebegin()\u003c/b\u003e\u003c/code\u003e\u003c/a\u003e\n  * \u003ca href=\"#queue-add\"\u003e\u003ccode\u003equeue.\u003cb\u003eadd()\u003c/b\u003e\u003c/code\u003e\u003c/a\u003e\n  * \u003ca href=\"#queue-remove\"\u003e\u003ccode\u003equeue.\u003cb\u003eremove()\u003c/b\u003e\u003c/code\u003e\u003c/a\u003e\n  * \u003ca href=\"#queue-findByTopic\"\u003e\u003ccode\u003equeue.\u003cb\u003efindByTopic()\u003c/b\u003e\u003c/code\u003e\u003c/a\u003e\n* \u003ca href=\"#subscribeToTopic\"\u003e\u003ccode\u003e\u003cb\u003esubscribeToTopic\u003c/b\u003e\u003c/code\u003e\u003c/a\u003e\n* \u003ca href=\"#publishToTopic\"\u003e\u003ccode\u003e\u003cb\u003epublishToTopic\u003c/b\u003e\u003c/code\u003e\u003c/a\u003e\n* \u003ca href=\"#secondsInterval\"\u003e\u003ccode\u003e\u003cb\u003esecondsInterval\u003c/b\u003e\u003c/code\u003e\u003c/a\u003e\n* \u003ca href=\"#minutesInterval\"\u003e\u003ccode\u003e\u003cb\u003eminutesInterval\u003c/b\u003e\u003c/code\u003e\u003c/a\u003e\n\n\u003chr /\u003e\n\n\u003ca name=\"route\"\u003e\u003c/a\u003e\n### Route\n\nA route definition for handling route subscription logic. Following are the properties supported on the `Route` definition:\n\n- `topic: string`\n  The Route topic\n\n- `type: 'String' | 'JSON'`\n  Payload type (default:String)\n  \n- `allowRetained: boolean`\n  Retain allowance\n  \n- `subscribe: boolean`\n  Subscribe flag\n\n- `publish: boolean`\n  Publish flag\n\n- `handler: Function`\n  The default subscribe handler function, called when subscribe:true, packet.retain:true|false and allowRetained:true.\n  Retained messages and new messages will be handled by default.\n\n- `fallbackRetainHandler?: Function`\n  Subscribe handler function only for retained messages, but for route specific custom logic. called when subscribe:true, \n  packet.retain:true and allowRetained:false.\n\u003e Note: If specified, `fallbackRetainHandler` function will be called. If not specified, retained messages will be discarded.\n\n\u003chr /\u003e\n\n\u003ca name=\"mqttrouter\"\u003e\u003c/a\u003e\n\n### MQTTRouter (mqttConnection, routes, options, setup, onError)\n\nThe main entrypoint of [mqtt-router](https://github.com/Pera-Swarm/mqtt-router/) that defines the router logic. \nYou have to import the `MQTTRouter` class and instantiate with a mqtt client. \nParameters supported in the constructor:\n  * `mqttConnection {MqttClient}` : mqtt [connection](https://github.com/mqttjs/MQTT.js/blob/master/README.md#client)\n  * `routes {Route[]}` : routes with mqtt topic, handler and allowRetained properties\n  * `options {IClientSubscribeOptions}` : mqtt message [options](https://github.com/mqttjs/MQTT.js/blob/master/README.md#mqttconnecturl-options)\n  * `setup {Function}` : setup function that runs on successful connection\n  * `onError {Function}` : error handler function\n  \n\u003chr /\u003e\n\n\u003ca name=\"mqttrouter-start\"\u003e\u003c/a\u003e\n\n### mqttRouter.start()\n\nThe method for starting the mqtt router. \n\u003e You must call this method once, a MQTTRouter object instantiated.\n\n\u003chr /\u003e\n\n\u003ca name=\"mqttrouter-pushToPublishQueue\"\u003e\u003c/a\u003e\n\n### mqttRouter.pushToPublishQueue(topic, data)\n\nAdd a message to the [publish queue](https://github.com/Pera-Swarm/mqtt-router/blob/master/README.md/#queue) that to be \nscheduled to publish.\nParameters supported:\n  * `topic {string}` : message topic\n  * `data {string|Buffer}` : message data\n\n\u003chr /\u003e\n\n\u003ca name=\"mqttrouter-addRoute\"\u003e\u003c/a\u003e\n### mqttRouter.addRoute(route)\n\nAdd a route to the subscriber routes list.\nParameter supported:\n  * `route {Route}` : route object to be added to the subscriber list\n\n\u003chr /\u003e\n\n\u003ca name=\"mqttrouter-removeRoute\"\u003e\u003c/a\u003e\n\n### mqttRouter.removeRoute(topic)\n\nRemove a route from the subscriber routes list.\nParameter supported:\n  * `topic {string}` : route topic\n\n\u003chr /\u003e\n\n\u003ca name=\"wrapper\"\u003e\u003c/a\u003e\n\n### wrapper(routes, property)\n\nWrap an array of `Route` objects with a higher order property (ex: property can be`this` from the callee class) or \na separate attribute to the `handler` function as a second parameter, in each route object.\nParameters supported:\n  * `routes {Route[]}` : routes array\n  * `property {any}` : property that required to be wrapped with\n\n\u003chr /\u003e\n\n\u003ca name=\"queue\"\u003e\u003c/a\u003e\n\n### Queue\n\nA Queue implementation for the `mqtt-router` with a scheduler that acts as a \"Publish Queue\".\nParameters supported in the constructor:\n  * `mqttClient {MqttClient}` : mqtt [connection](https://github.com/mqttjs/MQTT.js/blob/master/README.md#client)\n  * `options {IClientSubscribeOptions}` : mqtt message [options](https://github.com/mqttjs/MQTT.js/blob/master/README.md#mqttconnecturl-options)\n  * `number {number}` : interval\n\n\u003chr /\u003e\n\n\u003ca name=\"queue-begin\"\u003e\u003c/a\u003e\n\n### queue.begin()\n\nBegin the queue processing (scheduler).\n\u003e Note: You must call this method once, a Queue object instantiated.\n\n\u003chr /\u003e\n\n\u003ca name=\"queue-add\"\u003e\u003c/a\u003e\n### queue.add(topic, data)\n\nAdd a message to the publish queue. This message will be published by the scheduler.\nParameters supported:\n  * `topic {string}` : message topic\n  * `data {string|Buffer}` : message data\n\n\u003chr /\u003e\n\n\u003ca name=\"queue-remove\"\u003e\u003c/a\u003e\n### queue.remove(topic)\n\nRemove a message in the queue by a given topic.\nParameter supported:\n  * `topic {string}` : message topic\n\n\u003chr /\u003e\n\n\u003ca name=\"queue-findByTopic\"\u003e\u003c/a\u003e\n### queue.findByTopic(topic)\n\nFind a message with the given topic in the queue. Returns `-1` if not found on the queue.\nParameter supported:\n  * `topic {string}` : message topic\n\n\u003chr /\u003e\n\n\u003ca name=\"subscribeToTopic\"\u003e\u003c/a\u003e\n### subscribeToTopic(mqtt, topic, options)\n\nSubscribe to a given topic with options.\nParameters supported:\n  * `mqtt {MqttClient}` : mqtt [connection](https://github.com/mqttjs/MQTT.js/blob/master/README.md#client)\n  * `topic {string}` : message topic\n  * `options {IClientSubscribeOptions}` : mqtt message [options](https://github.com/mqttjs/MQTT.js/blob/master/README.md#mqttconnecturl-options)\n\n\u003chr /\u003e\n\n\u003ca name=\"publishToTopic\"\u003e\u003c/a\u003e\n### publishToTopic(mqtt, topic, message, options, callback)\n\nPublish a message to a given message topic with options and a callback function.\nParameters supported:\n  * `mqtt {MqttClient}` : mqtt [connection](https://github.com/mqttjs/MQTT.js/blob/master/README.md#client)\n  * `topic {string}` : message topic\n  * `message {string}` : message data\n  * `options {IClientSubscribeOptions}` : mqtt message [options](https://github.com/mqttjs/MQTT.js/blob/master/README.md#mqttconnecturl-options)\n  * `callback {Function}` : callback function\n\n\u003chr /\u003e\n\n\u003ca name=\"secondsInterval\"\u003e\u003c/a\u003e\n### secondsInterval(interval)\n\nGenerates a cron interval called in given seconds\nParameter supported:\n  * `interval {number}` : interval in seconds\n\n\u003chr /\u003e\n\n\u003ca name=\"minutesInterval\"\u003e\u003c/a\u003e\n### minutesInterval(interval)\n\nGenerates a cron interval called in given minutes\nParameter supported:\n  * `interval {number}` : interval in minutes\n\n\u003chr /\u003e\n\n### To-Do\n\n- Fix duplicate topic support for routing.\n\n### Licence\n\nThis project is licensed under [LGPL-2.1 Licence](https://github.com/Pera-Swarm/mqtt-router/blob/main/LICENSE).\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fpera-swarm%2Fmqtt-router","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fpera-swarm%2Fmqtt-router","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fpera-swarm%2Fmqtt-router/lists"}