Skip to content

MqttHandler Class

The MqttHandler class provides a wrapper around the MQTT client library with additional features for connection management, topic subscription, and message handling.

Class Overview

MqttHandler extends EventEmitter to provide notification of connection state changes and received messages.

import { MqttHandler } from 'energy-manager-iot';

const mqtt = new MqttHandler(options);

Constructor

constructor(options: MqttHandlerOptions = {})

Creates a new MQTT handler instance.

Parameters

  • options (optional): Configuration options for the MQTT connection.

Configuration Options

interface MqttHandlerOptions {
  /** Optional client ID for MQTT connection */
  clientId?: string;

  /** Whether to create a clean session, defaults to true */
  clean?: boolean;

  /** Keepalive interval in seconds, defaults to 60 */
  keepalive?: number;

  /** Reconnection period in milliseconds, defaults to 5000 */
  reconnectPeriod?: number;

  /** Connection timeout in milliseconds, defaults to 30000 */
  connectTimeout?: number;

  /** Username for MQTT authentication */
  username?: string;

  /** Password for MQTT authentication */
  password?: string;

  /** Whether to use SSL connection, defaults to false */
  ssl?: boolean;

  /** Last Will and Testament message configuration */
  will?: {
    topic: string;
    payload: string;
    qos?: 0 | 1 | 2;
    retain?: boolean;
  };
}

Connection Methods

connect

public connect(
  brokerUrl: string,
  options?: MqttHandlerOptions
): Promise<void>

Connects to the MQTT broker.

Parameters

  • brokerUrl: URL of the MQTT broker
  • options (optional): Additional connection options to override defaults

Returns

Promise that resolves when connected or rejects on error.

Example

try {
  await mqtt.connect('mqtt://localhost:1883', {
    username: 'user',
    password: 'password'
  });
  console.log('Connected to MQTT broker');
} catch (error) {
  console.error('Failed to connect:', error);
}

disconnect

public disconnect(): Promise<void>

Disconnects from the MQTT broker.

Returns

Promise that resolves when disconnected or rejects on error.

Example

await mqtt.disconnect();

isClientConnected

public isClientConnected(): boolean

Checks if connected to the MQTT broker.

Returns

true if connected to the broker.

Example

if (mqtt.isClientConnected()) {
  console.log('Connected and ready to send messages');
}

Messaging Methods

publish

public publish(
  topic: string,
  message: string | object,
  options?: mqtt.IClientPublishOptions
): Promise<void>

Publishes a message to an MQTT topic.

Parameters

  • topic: MQTT topic to publish to
  • message: Message content (string or object that will be JSON stringified)
  • options: Publish options like QoS level and retain flag

Returns

Promise that resolves when published or rejects on error.

Example

await mqtt.publish('device/status', {
  deviceId: 'temp-01',
  batteryLevel: 85,
  timestamp: Date.now()
}, { qos: 1 });

subscribe

public subscribe(
  topic: string,
  callback?: (topic: string, payload: Buffer) => void
): Promise<void>

Subscribes to an MQTT topic.

Parameters

  • topic: MQTT topic to subscribe to
  • callback (optional): Callback function for this specific topic

Returns

Promise that resolves when subscribed or rejects on error.

Example

await mqtt.subscribe('device/+/status', (topic, payload) => {
  const deviceId = topic.split('/')[1];
  console.log(`Received status from ${deviceId}:`, payload.toString());
});

unsubscribe

public unsubscribe(topic: string): Promise<void>

Unsubscribes from an MQTT topic.

Parameters

  • topic: MQTT topic to unsubscribe from

Returns

Promise that resolves when unsubscribed or rejects on error.

Example

await mqtt.unsubscribe('device/+/status');

Events

MqttHandler extends EventEmitter and emits the following events:

Event Data Description
connect - Emitted when connected to the broker
reconnect - Emitted when attempting to reconnect
offline - Emitted when disconnected from the broker
error Error Emitted when an error occurs
message (topic: string, payload: Buffer) Emitted when a message is received

Example of using events

mqtt.on('connect', () => {
  console.log('Connected to MQTT broker');
});

mqtt.on('message', (topic, payload) => {
  console.log('Received message:', topic, payload.toString());
});

mqtt.on('error', (err) => {
  console.error('MQTT error:', err);
});

Advanced Usage

Secure connection with TLS

import fs from 'fs';

await mqtt.connect('mqtts://secure-broker.example.com:8883', {
  username: 'user',
  password: 'password',
  // Additional TLS options
  rejectUnauthorized: true,
  ca: fs.readFileSync('ca-certificate.pem')
});

Using Last Will and Testament (LWT)

await mqtt.connect('mqtt://localhost:1883', {
  will: {
    topic: 'device/status',
    payload: JSON.stringify({
      deviceId: 'manager',
      status: 'offline',
      timestamp: Date.now()
    }),
    qos: 1,
    retain: true
  }
});

Topic-specific message handling

// Global handler
mqtt.on('message', (topic, payload) => {
  console.log('Global message handler:', topic);
});

// Topic-specific handler
await mqtt.subscribe('device/temp-01/status', (topic, payload) => {
  console.log('Temperature sensor status update:', JSON.parse(payload.toString()));
});