# MQTTHandler Library

The MQTTHandler library is a lightweight, static TypeScript-based MQTT broker utility designed to simplify the use of the MQTT protocol for IoT and real-time messaging. The library adopts a static approach, removing the need for repeated instantiation, ensuring a single, streamlined connection across your application, and offering robust event-driven communication via EventEmitter. Unlike traditional protocols such as HTTP, which operate on a request-response model and can introduce latency due to their synchronous nature, MQTT is built for efficiency in constrained environments. It uses a publish-subscribe model, enabling lightweight and reliable message exchange even on low-bandwidth networks.While protocols like WebSocket also support real-time communication, MQTT stands out due to its simplicity, efficiency, and design tailored for resource-constrained environments. MQTT uses much smaller packet sizes compared to WebSocket, which means it requires less bandwidth and processes data faster—an important advantage for devices with limited power or connectivity. One of MQTT’s key strengths is its built-in Quality of Service (QoS) levels, which ensure messages are delivered reliably, even in cases where the network is unstable or interrupted. This makes it ideal for IoT devices, which often operate in environments with inconsistent connectivity, such as remote sensors, smart home devices, or industrial systems. Additionally, MQTT’s publish-subscribe model simplifies communication between devices by allowing them to focus only on the messages they need, further reducing unnecessary data exchange and processing overhead. I am using MQTT for IoT applications and also with microservices to publish messages that will be consumed but other listening services. I have written a library for anyone to use or extend the code base i did. the library can be installed from the link below https://www.npmjs.com/package/vmind_mqtt on the npm home page there is also the link to the github repo https://github.com/EmiRoberti77/vmind_mqtt I have used mosquitto as a broker for the messages brew install mosquitto Features Static Design: Simplifies usage by managing a single shared MQTT client instance. Event-Driven: Uses EventEmitter to handle message events seamlessly. Ease of Use: Intuitive APIs for connecting, publishing, and subscribing to MQTT topics. Error Handling: Provides detailed error messages for debugging. Scalable: Designed for lightweight, efficient message handling. Installation Install the library from npm: npm i vmind_mqtt Methods The MQTTHandler library provides the following methods: initialize(mqttUrl: string): void Initializes the MQTT client with the specified broker URL. Example: MQTTHandler.initialize("mqtt://broker.hivemq.com"); publish(topic: string, message: string): void Publishes a message to the specified topic. Example: MQTTHandler.publish( "test/topic", JSON.stringify({ message: "hello, MQTT!" }) ); listen(topic: string): void Subscribes to a topic and listens for incoming messages. Example: MQTTHandler.listen("test/topic"); onMessage(callback: (data: { topic: string; message: any }) => void): void Registers a callback to handle incoming messages from subscribed topics. Example: MQTTHandler.onMessage((data) => { console.log(`Received message from ${data.topic}:`, data.message); }); stopListening(topic: string): void Unsubscribes from a specific topic, stopping the library from receiving messages from it. Example: MQTTHandler.stopListening("test/topic"); close(): void Gracefully closes the MQTT connection. Example: MQTTHandler.close(); Usage Initialize the MQTT Client Before using the library, initialize the MQTT client with the broker URL: MQTTHandler.initialize("mqtt://broker.hivemq.com"); Publish a Message Send a message to a specific topic: MQTTHandler.publish("test/topic", JSON.stringify({ message: "hello, MQTT!" })); Subscribe and Listen to a Topic Listen for messages from a subscribed topic: MQTTHandler.listen("test/topic"); MQTTHandler.onMessage((data) => { console.log(`Received message from ${data.topic}:`, data.message); }); Stop Listening to a Topic Unsubscribe from a topic to stop receiving messages: MQTTHandler.stopListening("test/topic"); Close the MQTT Connection Gracefully close the MQTT connection when done: MQTTHandler.close(); Example import { MQTTHandler } from "vmind_mqtt/dist"; // Initialize the client MQTTHandler.initialize("mqtt://broker.hivemq.com"); // Subscribe and listen to a topic MQTTHandler.listen("example/topic"); MQTTHandler.onMessage((data) => { console.log(`Received message on topic ${data.topic}:`, data.message); }); // Publish a message MQTTHandler.publish( "e

Jan 19, 2025 - 14:36
# MQTTHandler Library

The MQTTHandler library is a lightweight, static TypeScript-based MQTT broker utility designed to simplify the use of the MQTT protocol for IoT and real-time messaging. The library adopts a static approach, removing the need for repeated instantiation, ensuring a single, streamlined connection across your application, and offering robust event-driven communication via EventEmitter.

Unlike traditional protocols such as HTTP, which operate on a request-response model and can introduce latency due to their synchronous nature, MQTT is built for efficiency in constrained environments. It uses a publish-subscribe model, enabling lightweight and reliable message exchange even on low-bandwidth networks.While protocols like WebSocket also support real-time communication, MQTT stands out due to its simplicity, efficiency, and design tailored for resource-constrained environments. MQTT uses much smaller packet sizes compared to WebSocket, which means it requires less bandwidth and processes data faster—an important advantage for devices with limited power or connectivity.

One of MQTT’s key strengths is its built-in Quality of Service (QoS) levels, which ensure messages are delivered reliably, even in cases where the network is unstable or interrupted. This makes it ideal for IoT devices, which often operate in environments with inconsistent connectivity, such as remote sensors, smart home devices, or industrial systems. Additionally, MQTT’s publish-subscribe model simplifies communication between devices by allowing them to focus only on the messages they need, further reducing unnecessary data exchange and processing overhead.

I am using MQTT for IoT applications and also with microservices to publish messages that will be consumed but other listening services. I have written a library for anyone to use or extend the code base i did.

the library can be installed from the link below

https://www.npmjs.com/package/vmind_mqtt

on the npm home page there is also the link to the github repo

https://github.com/EmiRoberti77/vmind_mqtt

I have used mosquitto as a broker for the messages

brew install mosquitto

Features

  • Static Design: Simplifies usage by managing a single shared MQTT client instance.
  • Event-Driven: Uses EventEmitter to handle message events seamlessly.
  • Ease of Use: Intuitive APIs for connecting, publishing, and subscribing to MQTT topics.
  • Error Handling: Provides detailed error messages for debugging.
  • Scalable: Designed for lightweight, efficient message handling.

Installation

Install the library from npm:

npm i vmind_mqtt

Methods

The MQTTHandler library provides the following methods:

  1. initialize(mqttUrl: string): void Initializes the MQTT client with the specified broker URL. Example:
   MQTTHandler.initialize("mqtt://broker.hivemq.com");
  1. publish(topic: string, message: string): void Publishes a message to the specified topic. Example:
   MQTTHandler.publish(
     "test/topic",
     JSON.stringify({ message: "hello, MQTT!" })
   );
  1. listen(topic: string): void Subscribes to a topic and listens for incoming messages. Example:
   MQTTHandler.listen("test/topic");
  1. onMessage(callback: (data: { topic: string; message: any }) => void): void Registers a callback to handle incoming messages from subscribed topics. Example:
   MQTTHandler.onMessage((data) => {
     console.log(`Received message from ${data.topic}:`, data.message);
   });
  1. stopListening(topic: string): void Unsubscribes from a specific topic, stopping the library from receiving messages from it. Example:
   MQTTHandler.stopListening("test/topic");
  1. close(): void Gracefully closes the MQTT connection. Example:
   MQTTHandler.close();

Usage

Initialize the MQTT Client

Before using the library, initialize the MQTT client with the broker URL:

MQTTHandler.initialize("mqtt://broker.hivemq.com");

Publish a Message

Send a message to a specific topic:

MQTTHandler.publish("test/topic", JSON.stringify({ message: "hello, MQTT!" }));

Subscribe and Listen to a Topic

Listen for messages from a subscribed topic:

MQTTHandler.listen("test/topic");

MQTTHandler.onMessage((data) => {
  console.log(`Received message from ${data.topic}:`, data.message);
});

Stop Listening to a Topic

Unsubscribe from a topic to stop receiving messages:

MQTTHandler.stopListening("test/topic");

Close the MQTT Connection

Gracefully close the MQTT connection when done:

MQTTHandler.close();

Example

import { MQTTHandler } from "vmind_mqtt/dist";

// Initialize the client
MQTTHandler.initialize("mqtt://broker.hivemq.com");

// Subscribe and listen to a topic
MQTTHandler.listen("example/topic");
MQTTHandler.onMessage((data) => {
  console.log(`Received message on topic ${data.topic}:`, data.message);
});

// Publish a message
MQTTHandler.publish(
  "example/topic",
  JSON.stringify({ message: "Hello, World!" })
);

// Stop listening to the topic
MQTTHandler.stopListening("example/topic");

// Close the client after some time
setTimeout(() => {
  MQTTHandler.close();
}, 5000);

Advantages of the Static Approach

  1. Singleton Pattern:

    Ensures a single MQTT connection instance across your application, reducing overhead and connection management issues.

  2. Simplified API:

    No need to instantiate the client repeatedly; directly use static methods to interact with the broker.

  3. Event-Driven Communication:

    Uses EventEmitter to handle messages, enabling clean, modular, and decoupled code.

  4. Lightweight:

    Avoids dependencies on frameworks like Express, making it ideal for small services or microservices.

  5. Flexibility:

    Easily integrates into any TypeScript or Node.js project.

License

This library is licensed under the MIT License. See the LICENSE file for details.

Contributing

Contributions are welcome! If you find a bug or want to add features, feel free to submit a pull request or open an issue on the GitHub repository.

Support

If you encounter any issues or have questions, feel free to contact us or open a support ticket.

Emi Roberti - Happy Coding