UNPKG

@robot.com/better-mqtt

Version:

A modern, TypeScript-first MQTT client library that provides a better developer experience with async iterators, shared subscriptions, and React hooks. Better MQTT is a wrapper around the excellent [mqtt.js](https://github.com/mqttjs/MQTT.js) library, enh

67 lines (63 loc) 2.87 kB
import { EventEmitter } from 'ee-ts'; import { IClientOptions, ErrorWithReasonCode, MqttClient } from 'mqtt'; /** biome-ignore-all lint/suspicious/noExplicitAny: I'm sure it is fine */ type ConnectArgs = [brokerUrl: string] | [brokerUrl: string, opts?: IClientOptions] | [opts: IClientOptions]; interface BetterMQTTEvents { status(status: 'online' | 'offline'): void; error(error: Error | ErrorWithReasonCode): void; end(): void; } type MessageParser<T = string> = (message: Buffer) => T; declare function stringParser(message: Buffer): string; declare function jsonParser<T = unknown>(message: Buffer): T; declare function binaryParser(message: Buffer): Buffer; declare class BetterMQTT extends EventEmitter<BetterMQTTEvents> { readonly client: MqttClient; error: Error | ErrorWithReasonCode | null; get status(): "online" | "offline"; private sharedMqttSubscriptions; constructor(client: MqttClient); publish(topic: string, message: string | Buffer, opts?: { qos?: 0 | 1 | 2; }): void; publishAsync(topic: string, message: string | Buffer): Promise<void>; publishJson<T>(topic: string, message: T): void; publishJsonAsync<T>(topic: string, message: T): Promise<void>; unsubscribe(sub: Subscription<unknown>): void; subscribe<T>(topic: string, parser: MessageParser<T>): Subscription<T>; subscribeString(topic: string): Subscription<string>; subscribeJson<T>(topic: string): Subscription<T>; subscribeBinary(topic: string): Subscription<Buffer>; subscribeAsync<T>(topic: string, parser: MessageParser<T>): Promise<Subscription<T>>; subscribeStringAsync(topic: string): Promise<Subscription<string>>; subscribeJsonAsync<T>(topic: string): Promise<Subscription<T>>; subscribeBinaryAsync(topic: string): Promise<Subscription<Buffer>>; static connectAsync(...args: ConnectArgs): Promise<BetterMQTT>; static connect(...args: ConnectArgs): BetterMQTT; end(): void; } interface BetterMQTTMessage<T> { topic: string; content: T; params: string[]; } interface SubscriptionEvents<T> { message(message: BetterMQTTMessage<T>): void; end(): void; error(error: Error): void; } declare class Subscription<T = string> extends EventEmitter<SubscriptionEvents<T>> { private mqtt; private generator; topic: string; parser: (message: Buffer) => T; constructor(opts: { mqtt: BetterMQTT; topic: string; parser: (message: Buffer) => T; }); handleMessage(message: Buffer<ArrayBufferLike>, topic: string, params: string[]): void; [Symbol.asyncIterator](): AsyncGenerator<BetterMQTTMessage<T>>; end(): void; } export { BetterMQTT, type BetterMQTTEvents, type BetterMQTTMessage, type ConnectArgs, type MessageParser, Subscription, type SubscriptionEvents, binaryParser, jsonParser, stringParser };