This library provides a connector for sending and receiving messages using MQTT. It leverages the mqtt and eventemitter3 libraries to handle MQTT communication and event handling.
To install the library, you can use any package manager you want. But, Bun is preferred:
bun install commlibTo install dependencies:
bun installIf you are using Bun, you don't have to build them. To build the library into library ready Javascript:
bun run buildTo run the example chat app that use broker.hivemq.com as a public broker. You can run:
bun run ./example/chat.tsIf you aren't using Bun, you need to build them first, then:
node ./dist/example/chat.jsFirst, import the necessary modules and types:
import mqtt from "mqtt";
import EventEmitter from "eventemitter3";
import type { Payload } from "./parser";
import { parse, stringify, ParseError } from "./parser";
import { Connector, ConnectorEvent, ConnectorError } from "./connector";To create a connector, instantiate the Connector class with the required options:
const connector = new Connector({
host: "broker.hivemq.com",
port: 1883,
topic: "test",
selfAddress: 1,
});You can listen for message and broadcast events using the on method:
connector.on("message", (event: ConnectorEvent) => {
console.log(`[message from ${event.src}]: `, event.data);
});
connector.on("broadcast", (event: ConnectorEvent) => {
console.log("broadcast", event);
});To send a message, use the send method:
connector.send(2, { message: "Hello, World!" });The library provides a custom ConnectorError class for handling errors:
try {
// Your code here
} catch (error) {
if (error instanceof ConnectorError) {
console.error("Connector error:", error.message);
} else {
console.error("Unknown error:", error);
}
}options: An object containing the following properties:host: The MQTT broker host.port: The MQTT broker port.topic: The MQTT topic to subscribe to.selfAddress: The address of the client.
on(event: "message" | "broadcast", listener: (event: ConnectorEvent) => void): Registers an event listener for the specified event.send(dst: number, data: any): Sends a message to the specified destination.
A type representing an event emitted by the connector. It extends the Payload type and includes the following properties:
data: The data of the event.topic: The topic of the event.raw: The raw message string.
A custom error class for handling connector errors.
This library is licensed under the MIT License.