Basic Usage
This guide covers the fundamental usage patterns of the Energy Manager IoT library.
Installation
Before you begin, make sure you've installed the library:
Importing the Library
The first step is to import the required components from the library:
Initializing the Energy Manager
Create an instance of the EnergyManager
class, which is the main entry point for the library:
const manager = new EnergyManager({
topicPrefix: 'home/devices/', // Prefix used for all MQTT topics
statusInterval: 60000 // Check device status every 60 seconds
});
Connecting to MQTT Broker
Connect to your MQTT broker to start sending and receiving messages:
try {
await manager.connect('mqtt://localhost:1883', {
username: 'user', // Optional
password: 'password', // Optional
clientId: 'my-app-123' // Optional
});
console.log('Connected to MQTT broker');
} catch (error) {
console.error('Failed to connect to MQTT broker:', error);
}
Working with Devices
Registering Devices
Register IoT devices that you want to manage:
// Register a temperature sensor
manager.registerDevice(
'temp-sensor-01', // Unique device ID
'Living Room Temperature', // Human-readable name
DeviceType.SENSOR, // Type of device
{ // Optional configuration
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 Light',
DeviceType.ACTUATOR
);
Getting Device Information
Access information about registered devices:
try {
const device = manager.getDevice('temp-sensor-01');
console.log('Device information:', device);
// Check if device exists
if (manager.hasDevice('some-device')) {
console.log('Device exists');
}
} catch (error) {
console.error('Error retrieving device:', error);
}
Updating Devices
Update device properties:
const updatedDevice = manager.updateDevice('temp-sensor-01', {
name: 'Kitchen Temperature', // Change device name
config: {
reportingInterval: 30 // Update reporting interval
}
});
Removing Devices
Remove a device when it's no longer needed:
const removed = manager.removeDevice('temp-sensor-01');
if (removed) {
console.log('Device removed successfully');
}
Working with Groups
Groups allow you to organize devices and send commands to multiple devices at once.
Creating Groups
Create logical groups for your devices:
// Create location-based groups
manager.createGroup('living-room');
manager.createGroup('kitchen');
// Create type-based groups
manager.createGroup('sensors');
manager.createGroup('lights');
Adding Devices to Groups
Associate devices with groups:
// Add devices to location groups
manager.addDeviceToGroup('temp-sensor-01', 'living-room');
manager.addDeviceToGroup('light-01', 'kitchen');
// Add devices to type groups
manager.addDeviceToGroup('temp-sensor-01', 'sensors');
manager.addDeviceToGroup('light-01', 'lights');
Getting Devices in a Group
Retrieve all devices in a specific group:
try {
const livingRoomDevices = manager.getDevicesInGroup('living-room');
console.log(`Found ${livingRoomDevices.length} devices in living room`);
} catch (error) {
console.error('Error retrieving group devices:', error);
}
Removing Devices from Groups
Remove a device from a group:
Removing Groups
Remove an entire group (doesn't remove the devices, just the group):
Working with Commands
Sending Commands to Devices
Send commands to control individual devices:
// Set reporting interval
await manager.sendCommand(
'temp-sensor-01', // Device ID
CommandType.SET_REPORTING, // Command type
{ interval: 120 } // Command payload
);
// Put device to sleep mode
await manager.sleepDevice('temp-sensor-01', 3600); // Sleep for 1 hour
// Wake device from sleep mode
await manager.wakeDevice('temp-sensor-01');
Sending Commands to Groups
Send commands to all devices in a group:
// Set reporting interval for all sensors
await manager.sendCommandToGroup(
'sensors', // Group name
CommandType.SET_REPORTING, // Command type
{ interval: 60 } // Command payload
);
// Put all devices in a room to sleep mode
await manager.sleepGroup('living-room', 28800); // Sleep for 8 hours
// Wake all devices in a group
await manager.wakeGroup('sensors');
Handling Events
The Energy Manager library is event-based, allowing you to respond to various events:
// Listen for device status updates
manager.on('statusUpdate', (deviceId, status) => {
console.log(`Status update from device ${deviceId}:`, status);
if (status.batteryLevel < 20) {
console.log(`Warning: ${deviceId} has low battery!`);
}
});
// Listen for connection events
manager.on('connected', () => {
console.log('Connected to MQTT broker');
});
manager.on('disconnected', () => {
console.log('Disconnected from MQTT broker');
});
// Listen for device offline events
manager.on('deviceOffline', (deviceId) => {
console.log(`Device ${deviceId} is offline`);
// You might want to send an alert or notification
});
Getting Analytics
Get statistical information about device groups:
// Get statistics for all sensors
const sensorStats = manager.getGroupStatistics('sensors');
console.log('Sensor group statistics:', sensorStats);
// Example output:
// {
// averageBatteryLevel: 68.5,
// powerModeDistribution: {
// normal: 3,
// low_power: 2,
// sleep: 1,
// critical: 0
// },
// onlineCount: 5,
// offlineCount: 1,
// totalDevices: 6
// }
Disconnecting
Always disconnect properly when your application is shutting down:
Complete Basic Example
Here's a complete example that demonstrates the basic usage of the library:
import { EnergyManager, DeviceType, CommandType } from 'energy-manager-iot';
async function main() {
// Create manager instance
const manager = new EnergyManager();
try {
// Connect to MQTT broker
await manager.connect('mqtt://localhost:1883');
console.log('Connected to MQTT broker');
// Register devices
manager.registerDevice('temp-sensor-01', 'Living Room Temperature', DeviceType.SENSOR);
manager.registerDevice('light-01', 'Living Room Light', DeviceType.ACTUATOR);
console.log('Devices registered');
// 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`);
});
// Create a group
manager.createGroup('living-room');
manager.addDeviceToGroup('temp-sensor-01', 'living-room');
manager.addDeviceToGroup('light-01', 'living-room');
console.log('Group created and devices added');
// Send a command to a device
await manager.sendCommand('temp-sensor-01', CommandType.SET_REPORTING, { interval: 30 });
console.log('Command sent to temperature sensor');
// Get group statistics
const stats = manager.getGroupStatistics('living-room');
console.log('Living room statistics:', stats);
// Keep the application running
console.log('Monitoring devices. Press Ctrl+C to exit.');
// Handle graceful shutdown
process.on('SIGINT', async () => {
console.log('Disconnecting...');
await manager.disconnect();
process.exit(0);
});
} catch (error) {
console.error('Error:', error);
}
}
main();
Next Steps
Now that you understand the basics, you might want to explore:
- Device Management for more advanced device operations
- Group Management for more details on working with device groups
- Advanced Usage for advanced features and patterns