Basic Examples
This section provides practical examples demonstrating how to use the Energy Manager IoT library in common scenarios.
Basic Setup and Device Management
This example shows how to initialize the Energy Manager, connect to an MQTT broker, register devices, and monitor their status.
import {
EnergyManager,
DeviceType,
CommandType,
PowerMode,
Logger
} from 'energy-manager-iot';
async function basicExample() {
// Initialize the Energy Manager
const manager = new EnergyManager({
topicPrefix: 'home/devices/',
statusInterval: 60000 // Check device status every 60 seconds
});
try {
// Connect to the MQTT broker
console.log('Connecting to MQTT broker...');
await manager.connect('mqtt://localhost:1883');
console.log('Connected successfully');
// Register devices
console.log('Registering devices...');
manager.registerDevice(
'temp-sensor-01',
'Living Room Temperature Sensor',
DeviceType.SENSOR,
{
reportingInterval: 60, // Report status every 60 seconds
sleepThreshold: 15 // Enter sleep mode when battery below 15%
}
);
manager.registerDevice(
'light-01',
'Smart Light',
DeviceType.ACTUATOR
);
// Set up event listeners
manager.on('statusUpdate', (deviceId, status) => {
console.log(`Status update from ${deviceId}:`, status);
});
manager.on('deviceOffline', (deviceId) => {
console.log(`Device ${deviceId} is offline`);
});
// Keep app running for a while to receive events
console.log('Monitoring devices. Press Ctrl+C to exit.');
// When you're done
// await manager.disconnect();
} catch (error) {
console.error('Error:', error);
}
}
// Run the example
basicExample();
Creating and Managing Groups
This example demonstrates how to create device groups and send commands to multiple devices at once.
import { EnergyManager, DeviceType, CommandType } from 'energy-manager-iot';
async function groupManagementExample() {
const manager = new EnergyManager();
try {
// Connect to MQTT broker
await manager.connect('mqtt://localhost:1883');
// Register devices
manager.registerDevice('sensor1', 'Temperature Sensor', DeviceType.SENSOR);
manager.registerDevice('sensor2', 'Humidity Sensor', DeviceType.SENSOR);
manager.registerDevice('light1', 'Living Room Light', DeviceType.ACTUATOR);
manager.registerDevice('light2', 'Kitchen Light', DeviceType.ACTUATOR);
// Create groups
manager.createGroup('sensors');
manager.createGroup('lights');
manager.createGroup('living-room');
// Add devices to groups
manager.addDeviceToGroup('sensor1', 'sensors');
manager.addDeviceToGroup('sensor2', 'sensors');
manager.addDeviceToGroup('light1', 'lights');
manager.addDeviceToGroup('light2', 'lights');
// Add devices to location-based group
manager.addDeviceToGroup('sensor1', 'living-room');
manager.addDeviceToGroup('light1', 'living-room');
// Send command to all sensors
await manager.sendCommandToGroup('sensors', CommandType.SET_REPORTING, {
interval: 120 // Set all sensors to report every 2 minutes
});
// Put living room devices in low-power mode
await manager.sleepGroup('living-room', 3600); // Sleep for 1 hour
// Check group statistics
const sensorStats = manager.getGroupStatistics('sensors');
console.log('Sensor group statistics:', sensorStats);
// Clean up
await manager.disconnect();
} catch (error) {
console.error('Error:', error);
}
}
groupManagementExample();
Advanced Logging Example
This example shows how to use the advanced logging features of the Energy Manager IoT library.
import { EnergyManager, Logger, DeviceType } from 'energy-manager-iot';
async function loggingExample() {
// Create a module-specific logger
const moduleLogger = Logger.child('example-module');
// Create a logger with correlation ID for tracking operations
const operationId = 'op-' + Math.random().toString(36).substring(2, 10);
const opLogger = moduleLogger.withCorrelationId(operationId);
opLogger.info('Starting energy manager operation', {
timestamp: new Date().toISOString(),
operation: 'device-registration'
});
const manager = new EnergyManager();
try {
// Log connection attempt
opLogger.debug('Connecting to MQTT broker');
await manager.connect('mqtt://localhost:1883');
opLogger.info('Successfully connected to MQTT broker');
// Register device with detailed logging
opLogger.debug('Registering new temperature sensor');
const device = manager.registerDevice(
'temp-sensor-01',
'Living Room Temperature',
DeviceType.SENSOR,
{ reportingInterval: 60 }
);
opLogger.info('Device registered successfully', {
deviceId: device.id,
deviceType: device.type,
config: device.config
});
// Demonstrate different log levels
opLogger.debug('This is a debug message with details', { details: 'For troubleshooting' });
opLogger.info('This is an informational message');
opLogger.warn('This is a warning message', { reason: 'Low battery detected' });
try {
// Simulate an error
throw new Error('Device communication timeout');
} catch (error) {
opLogger.error('Failed to communicate with device', error);
}
// Clean up
await manager.disconnect();
opLogger.info('Operation completed');
} catch (error) {
opLogger.error('Operation failed', error);
}
}
loggingExample();
Error Handling Example
This example demonstrates how to handle errors properly using the Energy Manager IoT error system.
import {
EnergyManager,
EnergyManagerError,
ErrorType,
ErrorSeverity,
createErrorHandler
} from 'energy-manager-iot';
async function errorHandlingExample() {
// Create a module-specific error handler
const handleError = createErrorHandler('example-module');
const manager = new EnergyManager();
try {
// Try to connect with invalid URL
await manager.connect('invalid-url');
} catch (error) {
try {
// Log and rethrow with additional context
handleError(error, 'connection phase');
} catch (rethrown) {
console.error('Connection failed, please check broker settings');
}
}
// Example of creating and handling custom errors
try {
// Simulate device lookup
const deviceId = 'non-existent-device';
// Throw a custom error when device not found
throw new EnergyManagerError(
`Device ${deviceId} not found`,
ErrorType.DEVICE_NOT_FOUND,
{ deviceId }, // Additional context data
ErrorSeverity.MEDIUM
);
} catch (error) {
if (error instanceof EnergyManagerError) {
// Access error properties for handling
console.error(`Error [${error.type}]: ${error.message}`);
console.error(`Severity: ${error.severity}`);
console.error(`Error code: ${error.code}`);
// Handle specific error types
switch(error.type) {
case ErrorType.DEVICE_NOT_FOUND:
console.log('Please register the device first');
break;
case ErrorType.CONNECTION:
console.log('Please check your connection settings');
break;
default:
console.log('An unexpected error occurred');
}
}
}
}
errorHandlingExample();
Complete Application Example
This example shows a more complete application using the Energy Manager IoT library to monitor and control IoT devices.
import {
EnergyManager,
DeviceType,
CommandType,
PowerMode,
ConnectionStatus,
Logger
} from 'energy-manager-iot';
class IoTMonitoringApp {
private manager: EnergyManager;
private logger = Logger.child('MonitoringApp');
constructor() {
// Initialize the Energy Manager
this.manager = new EnergyManager({
topicPrefix: 'home/energy/',
statusInterval: 30000 // Check status every 30 seconds
});
// Set up event listeners
this.setupEventListeners();
}
private setupEventListeners() {
this.manager.on('connected', () => {
this.logger.info('Connected to MQTT broker');
});
this.manager.on('disconnected', () => {
this.logger.warn('Disconnected from MQTT broker');
});
this.manager.on('statusUpdate', (deviceId, status) => {
this.logger.info(`Status update from ${deviceId}`, { status });
// Auto-actions based on status
this.handleStatusUpdate(deviceId, status);
});
this.manager.on('deviceOffline', (deviceId) => {
this.logger.warn(`Device ${deviceId} is offline`);
// Could send notifications or alerts here
});
this.manager.on('commandSent', (deviceId, command) => {
this.logger.debug(`Command sent to ${deviceId}`, { command });
});
}
private handleStatusUpdate(deviceId: string, status: any) {
// Example: Auto-sleep devices with low battery
if (status.batteryLevel < 20 && status.powerMode === PowerMode.NORMAL) {
this.logger.info(`Device ${deviceId} has low battery, putting to sleep`);
this.manager.sleepDevice(deviceId).catch(err => {
this.logger.error(`Failed to put device ${deviceId} to sleep`, err);
});
}
}
public async start() {
try {
// Connect to MQTT broker
this.logger.info('Starting IoT monitoring application');
await this.manager.connect('mqtt://localhost:1883');
// Register devices
this.registerDevices();
// Create groups
this.createGroups();
// Periodic status check
setInterval(() => this.checkSystemStatus(), 60000);
this.logger.info('Application started successfully');
} catch (error) {
this.logger.error('Failed to start application', error);
throw error;
}
}
private registerDevices() {
// Register various devices
const devices = [
{ id: 'temp-living', name: 'Living Room Temperature', type: DeviceType.SENSOR },
{ id: 'temp-bedroom', name: 'Bedroom Temperature', type: DeviceType.SENSOR },
{ id: 'light-living', name: 'Living Room Light', type: DeviceType.ACTUATOR },
{ id: 'light-bedroom', name: 'Bedroom Light', type: DeviceType.ACTUATOR }
];
for (const device of devices) {
this.manager.registerDevice(device.id, device.name, device.type);
this.logger.debug(`Registered device: ${device.name}`);
}
}
private createGroups() {
// Create and populate groups
this.manager.createGroup('living-room');
this.manager.addDeviceToGroup('temp-living', 'living-room');
this.manager.addDeviceToGroup('light-living', 'living-room');
this.manager.createGroup('bedroom');
this.manager.addDeviceToGroup('temp-bedroom', 'bedroom');
this.manager.addDeviceToGroup('light-bedroom', 'bedroom');
this.manager.createGroup('all-sensors');
this.manager.addDeviceToGroup('temp-living', 'all-sensors');
this.manager.addDeviceToGroup('temp-bedroom', 'all-sensors');
this.logger.info('Device groups created');
}
private async checkSystemStatus() {
this.logger.debug('Running system status check');
// Get statistics for each room
const rooms = ['living-room', 'bedroom'];
for (const room of rooms) {
const stats = this.manager.getGroupStatistics(room);
this.logger.info(`${room} statistics`, { stats });
// Example: If all devices in a room are in low power, wake them
if (stats.powerModeDistribution[PowerMode.LOW_POWER] === stats.totalDevices) {
this.logger.info(`All devices in ${room} are in low power mode, waking up`);
await this.manager.wakeGroup(room);
}
}
}
public async stop() {
this.logger.info('Stopping application');
await this.manager.disconnect();
this.logger.info('Application stopped');
}
}
// Usage
async function run() {
const app = new IoTMonitoringApp();
try {
await app.start();
// Keep running until terminated
console.log('Application running. Press Ctrl+C to stop.');
// Handle graceful shutdown
process.on('SIGINT', async () => {
console.log('Shutting down...');
await app.stop();
process.exit(0);
});
} catch (error) {
console.error('Failed to run application:', error);
}
}
run();
These examples demonstrate various aspects of the Energy Manager IoT library, from basic device management to more advanced features like group control, logging, and error handling.