{"id":26947290,"url":"https://github.com/jonhvmp/energy-manager-iot","last_synced_at":"2025-10-16T11:26:14.216Z","repository":{"id":284244470,"uuid":"954280077","full_name":"Jonhvmp/energy-manager-iot","owner":"Jonhvmp","description":"A Node.js library for efficient energy management in IoT devices through MQTT protocol.","archived":false,"fork":false,"pushed_at":"2025-08-05T05:57:27.000Z","size":163,"stargazers_count":2,"open_issues_count":1,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-09-17T05:28:34.452Z","etag":null,"topics":["iot"],"latest_commit_sha":null,"homepage":"https://jonhvmp.github.io/energy-manager-iot-docs/","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/Jonhvmp.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":".github/FUNDING.yml","license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null},"funding":{"github":["Jonhvmp"],"patreon":null,"open_collective":null,"ko_fi":null,"tidelift":null,"community_bridge":null,"liberapay":null,"issuehunt":null,"lfx_crowdfunding":null,"polar":null,"buy_me_a_coffee":null,"thanks_dev":null,"custom":null}},"created_at":"2025-03-24T20:51:31.000Z","updated_at":"2025-06-17T01:26:19.000Z","dependencies_parsed_at":"2025-03-24T23:19:15.741Z","dependency_job_id":"282d7e8c-50e7-40aa-bde4-1bab4f149964","html_url":"https://github.com/Jonhvmp/energy-manager-iot","commit_stats":null,"previous_names":["jonhvmp/energy-manager-iot"],"tags_count":2,"template":false,"template_full_name":null,"purl":"pkg:github/Jonhvmp/energy-manager-iot","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Jonhvmp%2Fenergy-manager-iot","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Jonhvmp%2Fenergy-manager-iot/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Jonhvmp%2Fenergy-manager-iot/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Jonhvmp%2Fenergy-manager-iot/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/Jonhvmp","download_url":"https://codeload.github.com/Jonhvmp/energy-manager-iot/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Jonhvmp%2Fenergy-manager-iot/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":279183324,"owners_count":26121377,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","status":"online","status_checked_at":"2025-10-16T02:00:06.019Z","response_time":53,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["iot"],"created_at":"2025-04-02T20:18:56.515Z","updated_at":"2025-10-16T11:26:14.211Z","avatar_url":"https://github.com/Jonhvmp.png","language":"TypeScript","funding_links":["https://github.com/sponsors/Jonhvmp"],"categories":[],"sub_categories":[],"readme":"\u003c!-- Badges --\u003e\r\n![Test Coverage](https://img.shields.io/badge/coverage-85.15%25-brightgreen)\r\n![npm version](https://img.shields.io/npm/v/energy-manager-iot)\r\n![NPM Downloads](https://img.shields.io/npm/dw/energy-manager-iot)\r\n\r\n# Energy Manager IoT\r\n\r\nA Node.js library for efficient energy management in IoT devices through MQTT protocol.\r\n\r\n**[📚 Full Documentation](https://jonhvmp.github.io/energy-manager-iot-docs)**\r\n\r\n## Features\r\n\r\n- Robust MQTT connectivity with automatic reconnection support\r\n- Device management with unique IDs and flexible grouping\r\n- Send commands to individual devices or groups (e.g., \"sleep\", \"wake\")\r\n- Receive and store device status (e.g., battery level, power mode)\r\n- Group analytics, such as average battery level and power mode distribution\r\n- Full TypeScript support with strong typing\r\n- Professional logging system with contextual tracking and correlation IDs\r\n- Comprehensive error handling with categorized errors and severity levels\r\n\r\n## Installation\r\n\r\n```bash\r\nnpm install energy-manager-iot\r\n```\r\n\r\n## Usage Guide\r\n\r\n### Initial Setup\r\n1. Import the library:\r\n   ```typescript\r\n   import { EnergyManager, DeviceType, CommandType } from 'energy-manager-iot';\r\n   ```\r\n2. Create a manager instance:\r\n   ```typescript\r\n   const manager = new EnergyManager({\r\n     topicPrefix: 'home/devices/', // Prefix for MQTT topics\r\n     mqttOptions: { clientId: 'my-application' },\r\n     statusInterval: 60000 // Status check every 60 seconds\r\n   });\r\n   ```\r\n3. Connect to the MQTT broker:\r\n   ```typescript\r\n   await manager.connect('mqtt://localhost:1883', { username: 'user', password: 'password' });\r\n   ```\r\n\r\n### Device Registration and Management\r\n- Register devices:\r\n   ```typescript\r\n   manager.registerDevice('sensor1', 'Temperature Sensor', DeviceType.SENSOR, {\r\n     reportingInterval: 60, // In seconds\r\n     sleepThreshold: 20     // Enter sleep mode when battery below 20%\r\n   });\r\n   ```\r\n- Create groups and add devices:\r\n   ```typescript\r\n   manager.createGroup('living-room');\r\n   manager.addDeviceToGroup('sensor1', 'living-room');\r\n   ```\r\n- Send commands to a device or group:\r\n   ```typescript\r\n   await manager.sendCommand('sensor1', CommandType.SET_REPORTING, { interval: 300 });\r\n   await manager.sleepGroup('living-room', 3600); // Hibernate the group for 1 hour\r\n   ```\r\n\r\n### Monitoring and Events\r\nThe library emits useful events for monitoring:\r\n   ```typescript\r\n   // Listen to events:\r\n   manager.on('connected', () =\u003e console.log('Connected to MQTT broker'));\r\n   manager.on('statusUpdate', (deviceId, status) =\u003e console.log(`Status for ${deviceId}:`, status));\r\n   manager.on('deviceOffline', (deviceId) =\u003e console.log(`Device ${deviceId} went offline`));\r\n   manager.on('commandSent', (deviceId, command) =\u003e console.log(`Command sent to ${deviceId}:`, command));\r\n   ```\r\n- To finalize, disconnect:\r\n   ```typescript\r\n   await manager.disconnect();\r\n   ```\r\n\r\n## Examples\r\n\r\nCheck the `/examples` folder for detailed usage examples:\r\n- `basic-usage.ts`: Basic usage example.\r\n- `group-management.ts`: Advanced group management.\r\n- `device-simulator.ts`: IoT device simulator.\r\n- `advanced-usage.ts`: Advanced example with monitoring and group commands.\r\n\r\n**Additional Examples**\r\n- Run `npm run example:simulator` to simulate devices and see EnergyManager in action.\r\n\r\n## API\r\n\r\n### Main Class\r\n\r\n#### `EnergyManager`\r\n\r\nThe main entry point of the library.\r\n\r\n```typescript\r\n// Create instance\r\nconst manager = new EnergyManager(options);\r\n\r\n// Available options:\r\ninterface EnergyManagerOptions {\r\n  topicPrefix?: string;        // MQTT topic prefix (default: 'device/')\r\n  mqttOptions?: MqttHandlerOptions; // MQTT client options\r\n  autoReconnect?: boolean;     // Auto reconnection (default: true)\r\n  statusInterval?: number;     // Status check interval (ms) (default: 60000)\r\n}\r\n```\r\n\r\n### Main Methods\r\n\r\n| Method | Description |\r\n|--------|-------------|\r\n| `connect(brokerUrl, options?)` | Connect to the MQTT broker |\r\n| `disconnect()` | Disconnect from the MQTT broker |\r\n| `registerDevice(id, name, type, config?, groups?)` | Register a new device |\r\n| `sendCommand(deviceId, command, payload?)` | Send command to a device |\r\n| `sendCommandToGroup(groupName, command, payload?)` | Send command to a group |\r\n| `getDevice(id)` | Get information about a device |\r\n| `createGroup(name)` | Create a device group |\r\n| `addDeviceToGroup(deviceId, groupName)` | Add a device to a group |\r\n| `getGroupStatistics(groupName)` | Get group statistics |\r\n\r\n### Convenience Methods\r\n\r\n| Method | Description |\r\n|--------|-------------|\r\n| `sleepDevice(deviceId, duration?)` | Put device in energy saving mode |\r\n| `wakeDevice(deviceId)` | Wake device from energy saving mode |\r\n| `sleepGroup(groupName, duration?)` | Put group in energy saving mode |\r\n| `wakeGroup(groupName)` | Wake group from energy saving mode |\r\n\r\n### Events\r\n\r\nThe `EnergyManager` class extends `EventEmitter`, allowing you to receive notifications:\r\n\r\n```typescript\r\n// Listen to events\r\nmanager.on('connected', () =\u003e console.log('Connected'));\r\nmanager.on('disconnected', () =\u003e console.log('Disconnected'));\r\nmanager.on('statusUpdate', (deviceId, status) =\u003e console.log(`Status: ${deviceId}`, status));\r\nmanager.on('deviceOffline', (deviceId) =\u003e console.log(`Device offline: ${deviceId}`));\r\nmanager.on('commandSent', (deviceId, command) =\u003e console.log(`Command sent: ${deviceId}`, command));\r\n```\r\n\r\n## Protocols and Standards\r\n\r\n### Status Format\r\n\r\nDevices should publish their status in JSON format:\r\n\r\n```json\r\n{\r\n  \"batteryLevel\": 75,\r\n  \"powerMode\": \"normal\",\r\n  \"connectionStatus\": \"online\",\r\n  \"firmwareVersion\": \"1.2.3\",\r\n  \"signalStrength\": -67\r\n}\r\n```\r\n\r\n### Command Format\r\n\r\nCommands are sent in the format:\r\n\r\n```json\r\n{\r\n  \"type\": \"sleep\",\r\n  \"payload\": { \"duration\": 3600 },\r\n  \"timestamp\": 1634567890123,\r\n  \"requestId\": \"req_1634567890123_abc123\"\r\n}\r\n```\r\n\r\n## Advanced Logging\r\n\r\nThe library includes a professional logging system that helps with debugging, monitoring, and diagnostics.\r\n\r\n```typescript\r\nimport { Logger } from 'energy-manager-iot';\r\n\r\n// Module-specific logger\r\nconst deviceLogger = Logger.child('devices');\r\n\r\n// Log with correlation ID for tracking related operations\r\nconst operationLogger = deviceLogger.withCorrelationId('op-123456');\r\noperationLogger.info('Starting device registration');\r\n\r\n// Different log levels\r\ndeviceLogger.debug('Detailed information for troubleshooting');\r\ndeviceLogger.info('Normal operational messages');\r\ndeviceLogger.warn('Warning condition');\r\ndeviceLogger.error('Error condition', errorObject);\r\n```\r\n\r\n[Advanced Logging Documentation](./docs/logging.md)\r\n\r\n## Error Handling\r\n\r\nThe library provides a comprehensive error handling system:\r\n\r\n```typescript\r\nimport { EnergyManagerError, ErrorType, ErrorSeverity } from 'energy-manager-iot';\r\n\r\ntry {\r\n  // Some operation\r\n} catch (error) {\r\n  throw new EnergyManagerError(\r\n    'Failed to connect to device',\r\n    ErrorType.CONNECTION,\r\n    { deviceId: 'temp-01' },\r\n    ErrorSeverity.HIGH\r\n  );\r\n}\r\n```\r\n\r\n## Security Considerations\r\n\r\n- Use TLS/SSL (mqtts://) in production environments.\r\n- Configure authentication and access control in the MQTT broker.\r\n- Validate command payloads to prevent malicious information.\r\n- Enable logging in production for security audit trails.\r\n\r\n## Developer\r\n\r\n[Jonh Alex Paz de Lima](https://www.linkedin.com/in/jonhvmp)\r\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fjonhvmp%2Fenergy-manager-iot","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fjonhvmp%2Fenergy-manager-iot","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fjonhvmp%2Fenergy-manager-iot/lists"}