npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

energy-manager-iot

v1.1.1

Published

Library for energy management in IoT devices via MQTT protocol. Documentation: https://jonhvmp.github.io/energy-manager-iot-docs/

Readme

Test Coverage npm version NPM Downloads

Energy Manager IoT

A Node.js library for efficient energy management in IoT devices through MQTT protocol.

📚 Full Documentation

Features

  • Robust MQTT connectivity with automatic reconnection support
  • Device management with unique IDs and flexible grouping
  • Send commands to individual devices or groups (e.g., "sleep", "wake")
  • Receive and store device status (e.g., battery level, power mode)
  • Group analytics, such as average battery level and power mode distribution
  • Full TypeScript support with strong typing
  • Professional logging system with contextual tracking and correlation IDs
  • Comprehensive error handling with categorized errors and severity levels

Installation

npm install energy-manager-iot

Usage Guide

Initial Setup

  1. Import the library:
    import { EnergyManager, DeviceType, CommandType } from 'energy-manager-iot';
  2. Create a manager instance:
    const manager = new EnergyManager({
      topicPrefix: 'home/devices/', // Prefix for MQTT topics
      mqttOptions: { clientId: 'my-application' },
      statusInterval: 60000 // Status check every 60 seconds
    });
  3. Connect to the MQTT broker:
    await manager.connect('mqtt://localhost:1883', { username: 'user', password: 'password' });

Device Registration and Management

  • Register devices:
    manager.registerDevice('sensor1', 'Temperature Sensor', DeviceType.SENSOR, {
      reportingInterval: 60, // In seconds
      sleepThreshold: 20     // Enter sleep mode when battery below 20%
    });
  • Create groups and add devices:
    manager.createGroup('living-room');
    manager.addDeviceToGroup('sensor1', 'living-room');
  • Send commands to a device or group:
    await manager.sendCommand('sensor1', CommandType.SET_REPORTING, { interval: 300 });
    await manager.sleepGroup('living-room', 3600); // Hibernate the group for 1 hour

Monitoring and Events

The library emits useful events for monitoring:

// Listen to events:
manager.on('connected', () => console.log('Connected to MQTT broker'));
manager.on('statusUpdate', (deviceId, status) => console.log(`Status for ${deviceId}:`, status));
manager.on('deviceOffline', (deviceId) => console.log(`Device ${deviceId} went offline`));
manager.on('commandSent', (deviceId, command) => console.log(`Command sent to ${deviceId}:`, command));
  • To finalize, disconnect:
    await manager.disconnect();

Examples

Check the /examples folder for detailed usage examples:

  • basic-usage.ts: Basic usage example.
  • group-management.ts: Advanced group management.
  • device-simulator.ts: IoT device simulator.
  • advanced-usage.ts: Advanced example with monitoring and group commands.

Additional Examples

  • Run npm run example:simulator to simulate devices and see EnergyManager in action.

API

Main Class

EnergyManager

The main entry point of the library.

// Create instance
const manager = new EnergyManager(options);

// Available options:
interface EnergyManagerOptions {
  topicPrefix?: string;        // MQTT topic prefix (default: 'device/')
  mqttOptions?: MqttHandlerOptions; // MQTT client options
  autoReconnect?: boolean;     // Auto reconnection (default: true)
  statusInterval?: number;     // Status check interval (ms) (default: 60000)
}

Main Methods

| Method | Description | |--------|-------------| | connect(brokerUrl, options?) | Connect to the MQTT broker | | disconnect() | Disconnect from the MQTT broker | | registerDevice(id, name, type, config?, groups?) | Register a new device | | sendCommand(deviceId, command, payload?) | Send command to a device | | sendCommandToGroup(groupName, command, payload?) | Send command to a group | | getDevice(id) | Get information about a device | | createGroup(name) | Create a device group | | addDeviceToGroup(deviceId, groupName) | Add a device to a group | | getGroupStatistics(groupName) | Get group statistics |

Convenience Methods

| Method | Description | |--------|-------------| | sleepDevice(deviceId, duration?) | Put device in energy saving mode | | wakeDevice(deviceId) | Wake device from energy saving mode | | sleepGroup(groupName, duration?) | Put group in energy saving mode | | wakeGroup(groupName) | Wake group from energy saving mode |

Events

The EnergyManager class extends EventEmitter, allowing you to receive notifications:

// Listen to events
manager.on('connected', () => console.log('Connected'));
manager.on('disconnected', () => console.log('Disconnected'));
manager.on('statusUpdate', (deviceId, status) => console.log(`Status: ${deviceId}`, status));
manager.on('deviceOffline', (deviceId) => console.log(`Device offline: ${deviceId}`));
manager.on('commandSent', (deviceId, command) => console.log(`Command sent: ${deviceId}`, command));

Protocols and Standards

Status Format

Devices should publish their status in JSON format:

{
  "batteryLevel": 75,
  "powerMode": "normal",
  "connectionStatus": "online",
  "firmwareVersion": "1.2.3",
  "signalStrength": -67
}

Command Format

Commands are sent in the format:

{
  "type": "sleep",
  "payload": { "duration": 3600 },
  "timestamp": 1634567890123,
  "requestId": "req_1634567890123_abc123"
}

Advanced Logging

The library includes a professional logging system that helps with debugging, monitoring, and diagnostics.

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

// Module-specific logger
const deviceLogger = Logger.child('devices');

// Log with correlation ID for tracking related operations
const operationLogger = deviceLogger.withCorrelationId('op-123456');
operationLogger.info('Starting device registration');

// Different log levels
deviceLogger.debug('Detailed information for troubleshooting');
deviceLogger.info('Normal operational messages');
deviceLogger.warn('Warning condition');
deviceLogger.error('Error condition', errorObject);

Advanced Logging Documentation

Error Handling

The library provides a comprehensive error handling system:

import { EnergyManagerError, ErrorType, ErrorSeverity } from 'energy-manager-iot';

try {
  // Some operation
} catch (error) {
  throw new EnergyManagerError(
    'Failed to connect to device',
    ErrorType.CONNECTION,
    { deviceId: 'temp-01' },
    ErrorSeverity.HIGH
  );
}

Security Considerations

  • Use TLS/SSL (mqtts://) in production environments.
  • Configure authentication and access control in the MQTT broker.
  • Validate command payloads to prevent malicious information.
  • Enable logging in production for security audit trails.

Developer

Jonh Alex Paz de Lima