A Node.js library for efficient energy management in IoT devices through MQTT protocol.
- 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
- Robust error handling and detailed logging
npm install energy-manager-iot
- Import the library:
import { EnergyManager, DeviceType, CommandType } from 'energy-manager-iot';
- 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 });
- Connect to the MQTT broker:
await manager.connect('mqtt://localhost:1883', { username: 'user', password: 'password' });
- 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
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();
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.
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)
}
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 |
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 |
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));
Devices should publish their status in JSON format:
{
"batteryLevel": 75,
"powerMode": "normal",
"connectionStatus": "online",
"firmwareVersion": "1.2.3",
"signalStrength": -67
}
Commands are sent in the format:
{
"type": "sleep",
"payload": { "duration": 3600 },
"timestamp": 1634567890123,
"requestId": "req_1634567890123_abc123"
}
- Use TLS/SSL (mqtts://) in production environments.
- Configure authentication and access control in the MQTT broker.
- Validate command payloads to prevent malicious information.