Skip to content

Quick Start Guide

This guide will help you get started with Energy Manager IoT by walking through the basic usage scenarios.

Basic Setup

First, import the required components from the library:

import {
  EnergyManager,
  DeviceType,
  CommandType,
  Logger
} from 'energy-manager-iot';

Creating a Manager Instance

Create an instance of the Energy Manager:

const manager = new EnergyManager({
  topicPrefix: 'home/devices/', // Prefix for MQTT topics
  mqttOptions: {
    clientId: 'my-app-client'
  },
  statusInterval: 30000 // Status check every 30 seconds
});

Connecting to MQTT Broker

Connect to your MQTT broker:

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

Registering Devices

Register some IoT devices:

// Register a temperature sensor
manager.registerDevice(
  'temp-sensor-01',              // Device ID
  'Living Room Temperature',     // Human-readable name
  DeviceType.SENSOR,             // Device type
  {
    reportingInterval: 60,       // Report status every 60 seconds
    sleepThreshold: 15           // Enter sleep mode when battery below 15%
  }
);

// Register a smart light
manager.registerDevice(
  'light-01',
  'Kitchen Smart Light',
  DeviceType.ACTUATOR
);

Creating Device Groups

Create groups to organize devices:

// Create groups
manager.createGroup('living-room');
manager.createGroup('kitchen');

// Add devices to groups
manager.addDeviceToGroup('temp-sensor-01', 'living-room');
manager.addDeviceToGroup('light-01', 'kitchen');

Sending Commands to Devices

Send commands to individual devices:

// Send command to set reporting interval for a device
await manager.sendCommand(
  'temp-sensor-01',                    // Device ID
  CommandType.SET_REPORTING,           // Command type
  { interval: 300 }                   // Command payload
);

// Put a device to sleep for 1 hour
await manager.sleepDevice('temp-sensor-01', 3600);

// Wake up a device
await manager.wakeDevice('temp-sensor-01');

Working with Groups

Send commands to all devices in a group:

// Send a command to all devices in the living room
await manager.sendCommandToGroup(
  'living-room',                 // Group name
  CommandType.SET_REPORTING,     // Command type
  { interval: 120 }              // Command payload
);

// Put all devices in a group to sleep mode
await manager.sleepGroup('kitchen', 7200); // Sleep for 2 hours

// Wake all devices in a group
await manager.wakeGroup('kitchen');

Monitoring Device Status

Listen for status updates from devices:

// Monitor status updates
manager.on('statusUpdate', (deviceId, status) => {
  console.log(`Status update from ${deviceId}:`, status);

  // Check battery level
  if (status.batteryLevel < 20) {
    console.log(`Warning: ${deviceId} has low battery!`);
  }
});

// Monitor devices going offline
manager.on('deviceOffline', (deviceId) => {
  console.log(`Device ${deviceId} is offline`);
});

Getting Group Statistics

Calculate statistics for a group of devices:

// Get statistics for a group
const stats = manager.getGroupStatistics('living-room');
console.log('Living room statistics:', stats);

// Example output:
// {
//   averageBatteryLevel: 72.5,
//   powerModeDistribution: {
//     normal: 3,
//     low_power: 1,
//     sleep: 0,
//     critical: 0
//   },
//   onlineCount: 4,
//   offlineCount: 0,
//   totalDevices: 4
// }

Clean Shutdown

Always disconnect properly when shutting down:

// When your application is shutting down
await manager.disconnect();
console.log('Disconnected from MQTT broker');

Complete Example

Here's a complete basic example:

import { EnergyManager, DeviceType, CommandType } from 'energy-manager-iot';

async function main() {
  // Initialize
  const manager = new EnergyManager({ topicPrefix: 'home/devices/' });

  try {
    // Connect
    await manager.connect('mqtt://localhost:1883');

    // Register devices
    manager.registerDevice('sensor1', 'Temperature Sensor', DeviceType.SENSOR);
    manager.registerDevice('light1', 'Smart Light', DeviceType.ACTUATOR);

    // Create a group
    manager.createGroup('bedroom');
    manager.addDeviceToGroup('sensor1', 'bedroom');
    manager.addDeviceToGroup('light1', 'bedroom');

    // Monitor status
    manager.on('statusUpdate', (deviceId, status) => {
      console.log(`Status update from ${deviceId}:`, status);
    });

    // Send a command to the group
    await manager.sendCommandToGroup('bedroom', CommandType.SET_REPORTING, { interval: 300 });

    // Keep the application running for a while
    console.log('Monitoring devices. Press Ctrl+C to exit.');

    // Clean up when you're done (e.g., when the app is shutting down)
    // await manager.disconnect();

  } catch (error) {
    console.error('Error:', error);
  }
}

main();

What's Next?

Now that you understand the basics, dive deeper into: