Skip to content

Tidaly-IO/adonisjs-mqtt

Repository files navigation

@tidaly/mqtt

Download Version License

@tidaly/mqtt is a mqtt client based on Async-Mqtt for AdonisJS.

Note

You must have a Mqtt broker running to use this package. If you don't have one, you can use EMQX.


Getting Started

This package is available in the npm registry.

npm install @tidaly/mqtt

Next, configure the package by running the following command.

node ace configure @tidaly/mqtt

Usage

Subscribe to a topic

To subscribe to a topic you can simply add the topic to the topics array in the config/mqtt.ts file.

subscriber: {
    topics: ["my/topic"],
},

Or you can use the subscribe method.

import { MqttClient } from "@ioc:Tidaly/Mqtt";

await MqttClient.subscribe('my/topic');

// or subscribe to multiple topics

await MqttClient.subscribe(['my/topic', 'my/other-topic']);

Then, when a message is received the mqtt:message event will be emitted.

Create a event listener to handle the message.

import Event from '@ioc:Adonis/Core/Event';
import Logger from '@ioc:Adonis/Core/Logger';

Event.on('mqtt:message', (topic: string, message: string) => {
	Logger.info(`Message received on topic ${topic}: ${message}`);
});

Publish to a topic

To publish to a topic you can use the publish method.

import { MqttClient } from "@ioc:Tidaly/Mqtt";

class MyController {
	public async publish({ request }: HttpContextContract) {
		const { topic, message } = request.only(['topic', 'message']);

		await MqttClient.publish(topic, message);
	}
}

Command line

Subscribe to a topic

To subscribe to a topic you can use the mqtt:sub command. The command will subscribe to all topics in the topics array in the config/mqtt.ts file.

node ace mqtt:sub

Messages will be logged to the console.

Publish to a topic

To publish to a topic you can use the mqtt:pub command and pass the topic and message as arguments.

node ace mqtt:pub my/topic "Hello World"

Releases

No releases published

Packages

No packages published