UNPKG

homebridge-plugin-utils

Version:

Opinionated utilities to provide common capabilities and create rich configuration webUI experiences for Homebridge plugins.

179 lines (178 loc) 6.7 kB
/** * MQTT connectivity and topic management for Homebridge plugins. * * @module */ import type { HomebridgePluginLogging } from "./util.js"; /** * MQTT connectivity and topic management class for Homebridge plugins. * * This class manages connection, publishing, subscription, and message handling for an MQTT broker, and provides convenience methods for Homebridge accessories to * interact with MQTT topics using a standard topic prefix. * * @example * * ```ts * const mqtt = new MqttClient("mqtt://localhost:1883", "homebridge", log); * * // Publish a message to a topic. * mqtt.publish("device1", "status", "on"); * * // Subscribe to a topic. * mqtt.subscribe("device1", "status", (msg) => { * * console.log(msg.toString()); * }); * * // Subscribe to a 'get' topic and automatically publish a value in response. * mqtt.subscribeGet("device1", "temperature", "Temperature", () => "21.5"); * * // Subscribe to a 'set' topic and handle value changes. * mqtt.subscribeSet("device1", "switch", "Switch", (value) => { * * console.log("Switch set to", value); * }); * * // Unsubscribe from a topic. * mqtt.unsubscribe("device1", "status"); * ``` */ export declare class MqttClient { private brokerUrl; private isConnected; private reconnectInterval; private log; private mqtt; private subscriptions; private topicPrefix; /** * Creates a new MQTT client for connecting to a broker and managing topics with a given prefix. * * @param brokerUrl - The MQTT broker URL (e.g., "mqtt://localhost:1883"). * @param topicPrefix - Prefix to use for all MQTT topics (e.g., "homebridge"). * @param log - Logger for debug and info messages. * @param reconnectInterval - Optional. Interval (in seconds) to wait between reconnection attempts. Defaults to 60 seconds. * * @example * * ```ts * const mqtt = new MqttClient("mqtt://localhost", "homebridge", log); * ``` * * @remarks URL must conform to formats supported by {@link https://github.com/mqttjs/MQTT.js | MQTT.js}. */ constructor(brokerUrl: string, topicPrefix: string, log: HomebridgePluginLogging, reconnectInterval?: number); /** * Initializes and connects the MQTT client to the broker, setting up event handlers for connection, messages, and errors. * * Catches invalid broker URLs and logs errors. Handles all major MQTT client events internally. */ private configure; /** * Publishes a message to a topic for a specific device. * * Expands the topic using the topic prefix and device ID, then publishes the provided message string. * * @param id - The device or accessory identifier. * @param topic - The topic name to publish to. * @param message - The message payload to publish. * * @example * * ```ts * mqtt.publish("device1", "status", "on"); * ``` */ publish(id: string, topic: string, message: string): void; /** * Subscribes to a topic for a specific device and registers a handler for incoming messages. * * The topic is expanded using the prefix and device ID, and the callback will be called for each message received. * * @param id - The device or accessory identifier. * @param topic - The topic name to subscribe to. * @param callback - Handler function called with the message buffer. * * @example * * ```ts * mqtt.subscribe("device1", "status", (msg) => { * * console.log(msg.toString()); * }); * ``` */ subscribe(id: string, topic: string, callback: (cbBuffer: Buffer) => void): void; /** * Subscribes to a '<topic>/get' topic and publishes a value in response to "true" messages. * * When a message "true" is received on the '<topic>/get' topic, this method will publish the result of `getValue()` on the main topic. The log will record each status * publication event. * * @param id - The device or accessory identifier. * @param topic - The topic name to use. * @param type - A human-readable label for log messages (e.g., "Temperature"). * @param getValue - Function to get the value to publish as a string. * @param log - Optional logger for status output. Defaults to the class logger. * * @example * * ```ts * mqtt.subscribeGet("device1", "temperature", "Temperature", () => "21.5"); * ``` */ subscribeGet(id: string, topic: string, type: string, getValue: () => string, log?: HomebridgePluginLogging): void; /** * Subscribes to a '<topic>/set' topic and calls a setter when a message is received. * * The `setValue` function is called with both a normalized value and the raw string. Handles both synchronous and promise-based setters. Logs when set messages are * received and when errors occur. * * @param id - The device or accessory identifier. * @param topic - The topic name to use. * @param type - A human-readable label for log messages (e.g., "Switch"). * @param setValue - Function to call when a value is set. Can be synchronous or return a Promise. * @param log - Optional logger for status output. Defaults to the class logger. * * @example * * ```ts * mqtt.subscribeSet("device1", "switch", "Switch", (value) => { * * console.log("Switch set to", value); * }); * ``` */ subscribeSet(id: string, topic: string, type: string, setValue: (value: string, rawValue: string) => Promise<void> | void, log?: HomebridgePluginLogging): void; /** * Unsubscribes from a topic for a specific device, removing its message handler. * * @param id - The device or accessory identifier. * @param topic - The topic name to unsubscribe from. * * @example * * ```ts * mqtt.unsubscribe("device1", "status"); * ``` */ unsubscribe(id: string, topic: string): void; /** * Expands a topic string into a fully-formed topic path including the prefix and device ID. * * Returns `null` if the device ID is missing or empty. * * @param id - The device or accessory identifier. * @param topic - The topic name to expand. * * @returns The expanded topic string, or `null` if the ID is missing. * * @example * * ```ts * const topic = mqtt['expandTopic']("device1", "status"); * // topic = "homebridge/device1/status" * ``` */ private expandTopic; }