@mysetup/mqtt
v2.0.1
Published
A utility for managing MQTT connections, subscriptions, publishing, and client caching, built on top of the [mqtt](https://www.npmjs.com/package/mqtt) library.
Downloads
32
Readme
@mysetup/mqtt-client
A utility for managing MQTT connections, subscriptions, publishing, and client caching, built on top of the mqtt library.
Features
- Connect to MQTT brokers with custom configuration
- Subscribe and unsubscribe to topics
- Publish messages to topics
- Handle connection events (connect, error, reconnect, close, offline)
- Cache and reuse MQTT clients by
clientId - Custom message callbacks
- Integration with a logger and cache system
Installation
npm install @mysetup/mqtt-clientUsage
import { mqttCreateConnection, mqttSub, mqttPublish, mqttDisconnect } from "@mysetup/mqtt-client";
const clientId = "myClientId";
const config = {
protocol: "mqtt",
host: "localhost",
port: 1883,
path: "",
username: "user",
password: "pass",
};
const topicList = ["my/topic"];
mqttCreateConnection({
clientId,
config,
topicList,
messageCallback: (topic, message) => {
console.log(`Received on ${topic}: ${message}`);
},
environment: "development", // Optional: enables verbose logging
});
// Subscribe to topics
mqttSub(topicList, clientId, (topic, message) => {
console.log(`Received: ${message} on ${topic}`);
});
// Publish a message
mqttPublish("my/topic", { hello: "world" }, clientId);
// Disconnect
mqttDisconnect({ clientId, config, topicList }, false);Functions
mqttCreateConnection(props: ConnectionProps): MqttClient Creates or retrieves a cached MQTT client and connects to the broker.
mqttSub(topicList, clientId, messageCallback?, environment?) Subscribes to the given topics for the specified client.
mqttUnSub(topicList, clientId, environment?) Unsubscribes from the given topics for the specified client.
mqttPublish(topic, message, clientId, environment?) Publishes a message to a topic.
mqttDisconnect(props, reinit, environment?) Disconnects the client and optionally reinitializes the connection.
getMqttClient(clientId) Retrieves the cached MQTT client by ID.
License
MIT
