Frequently Asked Questions
This section addresses common questions about the Energy Manager IoT library.
General Questions
What is Energy Manager IoT?
Energy Manager IoT is a Node.js library for efficient energy management in IoT devices through the MQTT protocol. It provides device management, group organization, power state control, and status monitoring capabilities.
What makes Energy Manager IoT different from other IoT libraries?
Energy Manager IoT focuses specifically on energy optimization with features like:
- Power mode management (sleep/wake commands)
- Battery level monitoring
- Group-based energy management
- Comprehensive logging and diagnostics
- Strong TypeScript typing and structured error handling
What are the system requirements?
- Node.js 14.0 or higher
- An MQTT broker (like Mosquitto, HiveMQ, or AWS IoT Core)
- Operating Systems: Windows, Linux, macOS, or any system that supports Node.js
Is Energy Manager IoT suitable for production use?
Yes, Energy Manager IoT is designed for both development and production environments. It includes robust error handling, reconnection support, and extensive logging capabilities which are essential for production deployments.
Installation and Setup
How do I install Energy Manager IoT?
Install using npm or yarn:
Do I need to set up an MQTT broker?
Yes, you need an MQTT broker as Energy Manager IoT communicates with IoT devices via MQTT. You can use:
- Mosquitto (recommended for development)
- HiveMQ
- EMQ X
- Cloud services like AWS IoT Core, Azure IoT Hub (with MQTT support), or CloudMQTT
How do I connect to an MQTT broker?
import { EnergyManager } from 'energy-manager-iot';
const manager = new EnergyManager();
// Connect to local broker
await manager.connect('mqtt://localhost:1883');
// Connect with authentication
await manager.connect('mqtt://broker.example.com', {
username: 'user',
password: 'password'
});
// Connect with TLS
await manager.connect('mqtts://secure-broker.example.com:8883');
What MQTT protocol versions are supported?
Energy Manager IoT supports MQTT 3.1, 3.1.1, and 5.0 through its underlying MQTT client library.
Device Management
How many devices can I manage with Energy Manager IoT?
There's no hard limit in the library itself. The practical limit depends on your MQTT broker's capacity and system resources. The library has been tested with hundreds of devices without issues.
Can I register devices that aren't yet connected?
Yes, you can pre-register devices that will connect later. The library stores device information and will begin receiving status updates once the physical device connects to the MQTT broker.
How do I handle device authentication?
Device authentication is handled at the MQTT broker level. Energy Manager IoT supports passing username, password, and TLS certificates to the MQTT broker for secure communication.
How can I monitor device status?
Use the statusUpdate
event:
manager.on('statusUpdate', (deviceId, status) => {
console.log(`Status update from ${deviceId}:`, status);
console.log(`Battery level: ${status.batteryLevel}%`);
console.log(`Power mode: ${status.powerMode}`);
});
What happens if a device goes offline?
When a device doesn't report its status within the configured interval (default: twice the status interval), it's marked as offline and the deviceOffline
event is triggered:
Groups and Organization
What's the difference between device types and groups?
- Device Types are classifications based on device function (sensor, actuator, etc.)
- Groups are custom organizational units you create (like "living-room", "temperature-sensors")
You can put different types of devices in the same group, or the same type of devices in different groups.
Can a device belong to multiple groups?
Yes, a device can be a member of any number of groups. This allows for flexible organization (e.g., a temperature sensor can be in both "sensors" and "living-room" groups).
Is there a limit to how many groups I can create?
There's no practical limit to the number of groups you can create.
How do I get statistics for a group of devices?
Use the getGroupStatistics
method:
const stats = manager.getGroupStatistics('living-room');
console.log(`Average battery level: ${stats.averageBatteryLevel}%`);
console.log(`Online devices: ${stats.onlineCount}/${stats.totalDevices}`);
console.log('Power mode distribution:', stats.powerModeDistribution);
Power Management
How does sleep mode work?
Sleep mode is a power-saving state where devices reduce their functionality to conserve energy. When you send a sleep command:
The device is expected to: 1. Reduce its sensor reading frequency 2. Minimize network communications 3. Optionally turn off non-essential hardware 4. Wake up after the specified duration (if provided)
Can I specify different sleep behaviors?
Yes, you can include custom parameters in the sleep command:
await manager.sendCommand(
'device-id',
CommandType.SLEEP,
{
duration: 3600, // Sleep for 1 hour
mode: 'light', // Custom sleep mode (depends on device firmware)
keepAlive: true // Custom parameter to maintain minimal connection
}
);
The supported parameters depend on your IoT device's firmware implementation.
What's the difference between sleep and low power modes?
- Sleep mode is a deep power saving mode with minimal functionality
- Low power mode is a moderate power saving mode with reduced functionality
The exact behavior depends on the device implementation.
Communication
What MQTT QoS levels are supported?
Energy Manager IoT supports all MQTT QoS levels (0, 1, and 2). By default:
- Commands are sent with QoS 1 (at least once delivery)
- Status updates are received with the QoS level set by the device
What happens if the connection to the MQTT broker is lost?
The library automatically attempts to reconnect based on the reconnectPeriod
setting (default: 5 seconds). During disconnection:
- The
disconnected
event is emitted - Attempts to send commands will throw errors
- Upon reconnection, the
connected
event is emitted - The library resubscribes to all required topics
How do I format device status messages?
Devices should publish status in JSON format:
{
"batteryLevel": 75,
"powerMode": "normal",
"connectionStatus": "online",
"firmwareVersion": "1.2.3",
"signalStrength": -67
}
How do I format commands sent to devices?
Commands are automatically formatted by the library:
{
"type": "sleep",
"payload": { "duration": 3600 },
"timestamp": 1634567890123,
"requestId": "req_1634567890123_abc123"
}
Error Handling and Troubleshooting
How do I handle errors?
Use try/catch blocks and the specialized EnergyManagerError
class:
try {
await manager.sendCommand('device-id', CommandType.SET_REPORTING, { interval: 60 });
} catch (error) {
if (error instanceof EnergyManagerError) {
console.error(`Error type: ${error.type}, code: ${error.code}`);
console.error(`Severity: ${error.severity}`);
console.error(`Message: ${error.message}`);
} else {
console.error('Unexpected error:', error);
}
}
How do I debug connection issues?
-
Enable debug logging:
-
Check for connection events:
-
Verify MQTT broker settings:
- Check URL, port, username, and password
- Verify TLS certificates if using secure connection
- Ensure the broker is running and accessible
Why am I not receiving status updates?
Possible causes: 1. Device is not publishing to the correct topic 2. Topic prefix doesn't match between manager and device 3. Status message format is incorrect 4. MQTT broker connection or permission issues
Check that your devices are publishing to {topicPrefix}{deviceId}/status
and that the message format matches the expected structure.
How do I increase logging verbosity?
Set the LOG_LEVEL
environment variable:
You can also use the logger directly:
import { Logger } from 'energy-manager-iot';
Logger.debug('Detailed information', { contextData: 'value' });
Security
Is MQTT communication secure?
MQTT can be secured using:
1. TLS/SSL encryption (using mqtts://
URLs)
2. Username and password authentication
3. Client certificates
Always use mqtts://
with proper authentication in production environments.
How do I implement device authentication?
- Configure your MQTT broker with authentication
- Connect with credentials:
Are there any security best practices I should follow?
- Always use TLS/SSL (
mqtts://
) in production - Implement strong authentication
- Validate all command payloads before processing
- Use unique client IDs
- Apply the principle of least privilege for MQTT access control
- Enable logging in production for security audit trails
- Keep your Energy Manager IoT library updated
Advanced Usage
Can I extend or customize the library?
Yes, you can extend the library by: 1. Creating wrapper classes that add additional functionality 2. Using event listeners to implement custom behaviors 3. Using composition to add features without modification
How do I implement custom commands?
Define your own command types and integrate them:
// Define custom command type
const enum CustomCommandType {
CALIBRATE = 'calibrate',
RUN_DIAGNOSTIC = 'run_diagnostic'
}
// Send custom command
await manager.sendCommand('device-id', CustomCommandType.CALIBRATE as any, {
calibrationFactor: 1.05
});
Can I integrate with other messaging systems?
Yes, you can integrate with other messaging systems by: 1. Creating adapter classes that translate between MQTT and your system 2. Using the library's events to bridge communications 3. Implementing custom protocols over MQTT
How do I simulate devices for testing?
Check out the device-simulator.ts
example in the library repository or create your own:
import * as mqtt from 'mqtt';
async function simulateDevice(deviceId, broker) {
const client = mqtt.connect(broker);
client.on('connect', () => {
console.log(`Device ${deviceId} connected`);
// Subscribe to command topic
client.subscribe(`device/${deviceId}/command`);
// Publish status periodically
setInterval(() => {
const status = {
deviceId,
batteryLevel: Math.round(70 + Math.random() * 20),
powerMode: 'normal',
connectionStatus: 'online',
lastSeen: Date.now()
};
client.publish(`device/${deviceId}/status`, JSON.stringify(status));
}, 10000);
});
// Handle commands
client.on('message', (topic, message) => {
console.log(`Command received: ${message.toString()}`);
// Implement command handling logic here
});
}
// Simulate multiple devices
simulateDevice('temp-sensor-01', 'mqtt://localhost:1883');
simulateDevice('light-01', 'mqtt://localhost:1883');
Support and Community
How do I report bugs or suggest features?
Please open an issue on our GitHub repository with:
- Detailed description of the issue or feature request
- Steps to reproduce (for bugs)
- Expected vs. actual behavior
- Library version
- Node.js version
- Operating system
Is there commercial support available?
For commercial support options, please contact Jonh Alex Paz de Lima.
How do I contribute to the library?
Contributions are welcome! To contribute:
- Fork the repository
- Create a feature branch
- Make your changes
- Add tests for new functionality
- Ensure all tests pass
- Submit a pull request
Please follow our coding standards and include appropriate documentation.
Where can I find more examples?
Check the examples directory in the repository for additional examples including:
- Basic usage
- Device group management
- Device simulation
- Advanced logging