Skip to content

Device Management

This guide explains how to effectively manage IoT devices with the Energy Manager IoT library.

Understanding Device Types

Energy Manager IoT categorizes devices using the DeviceType enum:

enum DeviceType {
  SENSOR = 'sensor',       // Devices that collect data (temperature, humidity)
  CAMERA = 'camera',       // Devices that capture visual data
  ACTUATOR = 'actuator',   // Devices that control elements (lights, switches)
  GATEWAY = 'gateway',     // Devices that connect and bridge other devices
  GENERIC = 'generic'      // General purpose devices
}

Choose the appropriate type when registering a device to enable proper categorization and optimized handling.

The Device Interface

The core Device interface represents an IoT device in the system:

interface Device {
  id: string;              // Unique identifier
  name: string;            // Human-readable name
  type: DeviceType;        // Device classification
  status?: DeviceStatus;   // Current operational status
  groups: string[];        // Groups this device belongs to
  config: DeviceConfig;    // Device configuration settings
  createdAt: number;       // Registration timestamp
  updatedAt: number;       // Last update timestamp
}

This structure serves as a blueprint for all device operations in the library.

Registering Devices

To add a device to the Energy Manager system, use the registerDevice method:

const device = manager.registerDevice(
  'temp-sensor-01',                // Unique ID
  'Living Room Temperature',       // Descriptive name
  DeviceType.SENSOR,               // Device type
  {                                // Optional configuration
    reportingInterval: 60,         // Status reporting frequency in seconds
    sleepThreshold: 15,            // Battery level to trigger sleep mode
    autoWake: true,                // Auto wake after sleep period
    securityLevel: 3               // Security level from 1-5
  },
  ['living-room', 'sensors']       // Optional initial groups
);

Device ID Guidelines

When creating device IDs: - Use 3-50 characters - Only use alphanumeric characters, hyphens, and underscores - Choose descriptive but concise identifiers - Be consistent with your naming scheme - Consider including type/location in the ID

Good examples: temp-bedroom-01, light-kitchen-main, motion-entrance

Device Configuration Options

The DeviceConfig interface provides configuration parameters for devices:

Parameter Type Description Default
reportingInterval number Status reporting frequency in seconds 60
sleepThreshold number Battery level (0-100) to enter sleep mode 20
autoWake boolean Whether to auto wake after sleep period false
securityLevel number Security level from 1 (low) to 5 (high) 3

Example configuration:

const config: DeviceConfig = {
  reportingInterval: 120,    // Report status every 2 minutes
  sleepThreshold: 10,        // Enter sleep mode at 10% battery
  autoWake: true,            // Automatically wake after sleep period
  securityLevel: 4           // Higher than default security
};

Managing Device Lifecycles

Updating Device Properties

Update a device's properties with the updateDevice method:

const updatedDevice = manager.updateDevice('temp-sensor-01', {
  name: 'Updated Sensor Name',
  config: {
    reportingInterval: 300,     // Update to 5 minutes
    sleepThreshold: 25          // Change sleep threshold
  }
});

Note

You cannot update a device's ID or creation timestamp.

Getting Device Information

Retrieve device information using the getDevice method:

try {
  const device = manager.getDevice('temp-sensor-01');
  console.log('Device details:', device);

  // Access specific properties
  console.log(`Name: ${device.name}`);
  console.log(`Type: ${device.type}`);
  console.log(`Last updated: ${new Date(device.updatedAt).toISOString()}`);

  // Get current status if available
  if (device.status) {
    console.log(`Battery level: ${device.status.batteryLevel}%`);
    console.log(`Power mode: ${device.status.powerMode}`);
  }
} catch (error) {
  console.error('Device not found');
}

Checking if a Device Exists

Use the hasDevice method to check if a device exists without throwing an error:

if (manager.hasDevice('temp-sensor-01')) {
  console.log('Device exists, proceeding with operation...');
} else {
  console.log('Device not found, creating it now...');
  manager.registerDevice('temp-sensor-01', 'Temperature Sensor', DeviceType.SENSOR);
}

Removing Devices

Remove a device from the system with the removeDevice method:

const wasRemoved = manager.removeDevice('temp-sensor-01');

if (wasRemoved) {
  console.log('Device successfully removed');
} else {
  console.log('Device not found or could not be removed');
}

When a device is removed: - It's removed from all its groups - The manager stops listening for its status updates - Any stored status information is deleted

Working with Device Status

Understanding Device Status

The DeviceStatus interface represents a device's current operational state:

interface DeviceStatus {
  deviceId: string;             // ID of the device
  batteryLevel: number;         // Battery percentage (0-100)
  powerMode: PowerMode;         // Current power saving mode
  connectionStatus: ConnectionStatus; // Online/offline status
  lastSeen: number;             // Last status update timestamp
  firmwareVersion?: string;     // Optional firmware version
  signalStrength?: number;      // Optional signal strength in dBm
  errors?: string[];            // Optional array of error messages
  additionalInfo?: Record<string, any>; // Optional custom data
}

Power Modes

The PowerMode enum represents different energy consumption states:

enum PowerMode {
  NORMAL = 'normal',       // Full functionality
  LOW_POWER = 'low_power', // Reduced functionality to save power
  SLEEP = 'sleep',         // Minimal power consumption mode
  CRITICAL = 'critical'    // Emergency mode due to low battery
}

Connection Status

The ConnectionStatus enum represents connectivity state:

enum ConnectionStatus {
  ONLINE = 'online',           // Connected and responsive
  OFFLINE = 'offline',         // Disconnected or unresponsive
  INTERMITTENT = 'intermittent' // Unstable connection
}

Monitoring Device Status

To receive updates when a device's status changes, use the statusUpdate event:

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

  // Take actions based on status
  if (status.batteryLevel < 20 && status.powerMode !== PowerMode.SLEEP) {
    console.log(`${deviceId} has low battery, putting to sleep mode`);
    manager.sleepDevice(deviceId).catch(console.error);
  }

  // Check connection status
  if (status.connectionStatus === ConnectionStatus.INTERMITTENT) {
    console.log(`${deviceId} has an unstable connection`);
  }
});

// Listen for devices going offline
manager.on('deviceOffline', (deviceId) => {
  console.log(`Device ${deviceId} is offline`);
  // Send alert or notification
});

Power Management

Energy Manager IoT provides methods for controlling a device's power state:

Sleep Mode

Put a device into sleep mode to conserve energy:

// Put device to sleep indefinitely
await manager.sleepDevice('temp-sensor-01');

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

Wake Mode

Wake a device from sleep mode:

await manager.wakeDevice('temp-sensor-01');

Advanced Device Operations

Setting Custom Reporting Intervals

Adjust how often a device reports its status:

await manager.sendCommand(
  'temp-sensor-01',
  CommandType.SET_REPORTING,
  { interval: 300 } // Report every 5 minutes (300 seconds)
);

Requesting Immediate Status Update

Request an immediate status update from a device:

await manager.sendCommand('temp-sensor-01', CommandType.GET_STATUS);

Updating Device Firmware

Initiate a firmware update for a device:

await manager.sendCommand(
  'temp-sensor-01',
  CommandType.UPDATE,
  {
    version: '1.2.0',
    url: 'https://firmware-server.com/temp-sensor/v1.2.0.bin'
  }
);

Restarting a Device

Send a command to restart a device:

await manager.sendCommand('temp-sensor-01', CommandType.RESTART);

Best Practices

  1. Use descriptive IDs and names: Choose clear, systematic identifiers that help with organization.

  2. Set appropriate reporting intervals: Balance between timely data and energy consumption.

  3. Group related devices: Use groups to organize devices by location, function, or other criteria.

  4. Monitor battery levels: Set up alerts for low battery devices to prevent unexpected failures.

  5. Handle status events: Always listen for status updates to keep your application synchronized.

  6. Respect device capabilities: Consider the device type when sending commands and evaluating performance.

  7. Clean up unused devices: Remove devices that are no longer active to keep your system tidy.

Example: Complete Device Management Workflow

Here's a comprehensive example demonstrating a complete device management workflow:

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

async function deviceManagementExample() {
  // Create manager
  const manager = new EnergyManager();

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

    // Register a new temperature sensor
    const tempSensor = manager.registerDevice(
      'temp-living',
      'Living Room Temperature',
      DeviceType.SENSOR,
      {
        reportingInterval: 60,
        sleepThreshold: 15,
        autoWake: true
      }
    );
    console.log('Registered new device:', tempSensor.id);

    // Check if another device exists, register if not
    if (!manager.hasDevice('humidity-living')) {
      manager.registerDevice(
        'humidity-living',
        'Living Room Humidity',
        DeviceType.SENSOR
      );
      console.log('Registered humidity sensor');
    }

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

      // Log battery level
      console.log(`Battery level: ${status.batteryLevel}%`);

      // Implement adaptive power management
      if (status.batteryLevel < 30 && status.powerMode === PowerMode.NORMAL) {
        console.log('Battery below 30%, switching to low power mode');
        manager.sendCommand(deviceId, CommandType.SLEEP, {
          duration: 3600, // Sleep for an hour
          mode: 'light'   // Custom light sleep mode
        }).catch(console.error);
      }
    });

    // Listen for offline events
    manager.on('deviceOffline', async (deviceId) => {
      console.log(`Device ${deviceId} went offline`);

      try {
        // Try to get the device information
        const device = manager.getDevice(deviceId);
        console.log(`Last seen: ${new Date(device.status?.lastSeen || 0).toISOString()}`);

        // Try to wake the device
        await manager.wakeDevice(deviceId);
        console.log(`Attempted to wake ${deviceId}`);
      } catch (err) {
        console.error(`Error handling offline device ${deviceId}:`, err);
      }
    });

    // Update device configuration
    const updatedDevice = manager.updateDevice('temp-living', {
      config: {
        reportingInterval: 120, // Change to every 2 minutes
      }
    });
    console.log('Updated device configuration:', updatedDevice.config);

    // Send command to device
    await manager.sendCommand('temp-living', CommandType.GET_STATUS);
    console.log('Requested immediate status update');

    // Keep application running to receive status updates
    console.log('Device management example running. Press Ctrl+C to exit.');

    // Set up exit handler
    process.on('SIGINT', async () => {
      // Clean up before exit
      const devices = manager.getAllDevices();
      console.log(`Cleaning up ${devices.length} devices...`);

      // Disconnect from MQTT broker
      await manager.disconnect();
      console.log('Disconnected from MQTT broker');
      process.exit(0);
    });

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

deviceManagementExample();

This comprehensive guide should help you effectively manage IoT devices using the Energy Manager IoT library. For more advanced scenarios, explore the group management and advanced usage sections.