A comprehensive backend system for managing IoT devices, energy monitoring, automation, and real-time data processing.
- Device & Entity Management: Manage IoT devices and their entities (sensors, actuators)
- Real-time Communication: MQTT integration for IoT device communication
- WebSocket Support: Real-time updates via Socket.IO
- User Authentication: JWT-based authentication system
- Energy Monitoring: Comprehensive energy meter data collection and aggregation
- Automation: Rule-based automation for IoT devices
- Air Conditioner Control: AC unit management and monitoring
- Water Management System (WMS): Water flow monitoring and motor control
- Hourly Aggregation: Automatic hourly energy consumption calculation
- Daily Aggregation: Daily energy summaries
- Monthly Aggregation: Monthly energy reports
- Yearly Aggregation: Annual energy statistics
- Accurate Calculations: Handles meter resets and missing data gracefully
- Node.js (v16 or higher)
- MongoDB database
- MQTT broker (for IoT device communication)
- Environment variables configured (see
.envsetup)
-
Clone the repository
git clone <repository-url> cd iot-backend
-
Install dependencies
npm install
-
Configure environment variables Create a
.envfile in the root directory:MONGO_URI=mongodb://localhost:27017/iot-db PORT=5000 JWT_SECRET=your-secret-key MQTT_BROKER_URL=mqtt://your-mqtt-broker:1883 MQTT_USERNAME=your-mqtt-username MQTT_PASSWORD=your-mqtt-password
-
Start the server
npm start # or for development with auto-reload nodemon index.js
iot-backend/
βββ controllers/ # Request handlers
β βββ device.controller.js
β βββ entity.controller.js
β βββ energyHistory.controller.js
β βββ airConditioner.controller.js
β βββ automation.controller.js
β βββ wms.controller.js
βββ models/ # MongoDB models
β βββ Device.model.js
β βββ entity.model.js
β βββ energyMeterModels/
β β βββ energyHourly.model.js
β β βββ energyDaily.model.js
β β βββ energyMonthly.model.js
β β βββ energyYearly.model.js
β βββ ...
βββ routes/ # API routes
β βββ devices.route.js
β βββ entity.route.js
β βββ history.route.js
β βββ ...
βββ DbScheduling/ # Scheduled tasks
β βββ energyAggregator.js
β βββ testEnergyCalculations.js
βββ services/ # Business logic services
β βββ mqttSubscriptionService.js
β βββ acHistoricData.js
βββ middleware/ # Express middleware
β βββ auth.js
βββ mqtt/ # MQTT client configuration
β βββ mqttClient.js
βββ db/ # Database connection
β βββ connect.js
βββ index.js # Application entry point
The system includes automated scheduled tasks for energy data aggregation:
- Hourly Aggregation: Runs at minute 1 of every hour
- Daily Aggregation: Runs at 00:01 AM daily
- Monthly Aggregation: Runs at 00:20 AM daily
- Yearly Aggregation: Runs at 00:30 AM daily
These tasks automatically calculate:
totalValue: Energy consumption during the periodtotalEnergyConsumption: Cumulative meter reading at end of period
Run comprehensive tests to verify energy aggregation calculations:
npm run test:energyThis will test:
- β Hourly calculations accuracy
- β Daily aggregation sums
- β Monthly aggregation sums
- β Yearly aggregation sums
- β Data consistency
- β Edge cases (meter resets, missing data)
The system supports multiple MongoDB connection methods:
-
Direct URI (recommended):
MONGO_URI=mongodb://username:password@host:port/database
-
Environment Variables:
MONGO_HOST=localhost MONGO_PORT=27017 MONGO_DB=iot-db MONGO_USER=username MONGO_PASSWORD=password
Configure MQTT broker connection:
MQTT_BROKER_URL=mqtt://broker-url:1883
MQTT_USERNAME=your-username
MQTT_PASSWORD=your-passwordHourly:
totalValue= Current hour's last reading - Previous hour's last readingtotalEnergyConsumption= Last raw reading of the hour
Daily:
totalValue= Sum of all hourlytotalValuefor the daytotalEnergyConsumption= Last hour (23:00) of the day'stotalEnergyConsumption
Monthly:
totalValue= Sum of all dailytotalValuefor the monthtotalEnergyConsumption= Last day of the month'stotalEnergyConsumption
Yearly:
totalValue= Sum of all monthlytotalValuefor the yeartotalEnergyConsumption= December'stotalEnergyConsumption
- β Handles meter resets automatically
- β Falls back to raw history if aggregated data unavailable
- β Validates all calculations
- β Prevents negative consumption values
The project includes Docker configuration:
# Build and run with Docker Compose
docker-compose up -d
# Or build Docker image
docker build -t iot-backend .
docker run -p 5000:5000 iot-backend- JWT-based authentication
- Password hashing with bcrypt
- CORS configuration
- Input validation
- Protected routes with middleware
Required environment variables:
# Database
MONGO_URI=mongodb://localhost:27017/iot-db
# Server
PORT=5000
# Authentication
JWT_SECRET=your-secret-key-here
# MQTT
MQTT_BROKER_URL=mqtt://localhost:1883
MQTT_USERNAME=your-username
MQTT_PASSWORD=your-password- Set environment variables on your hosting platform
- Install dependencies:
npm install --production - Start the server:
npm start
- Energy Aggregation: See
DbScheduling/energyAggregator.jsfor detailed aggregation logic - Testing Guide: Run
npm run test:energyand review test output - API Documentation: Check individual route files in
routes/directory
- Fork the repository
- Create a feature branch
- Make your changes
- Run tests:
npm run test:energy - Submit a pull request
See LICENSE file for details.
- Ahmad - Initial work
-
MongoDB Connection Failed
- Check
MONGO_URIin.env - Verify MongoDB is running
- Check network connectivity
- Check
-
MQTT Connection Issues
- Verify MQTT broker URL and credentials
- Check firewall settings
- Ensure MQTT broker is accessible
-
Energy Calculations Incorrect
- Run tests:
npm run test:energy - Check aggregation logs
- Verify raw data exists in database
- Run tests:
-
WebSocket Not Working
- Check CORS configuration
- Verify Socket.IO client connection
- Check server logs for errors
For issues and questions, please open an issue on the repository.
Version: 1.0.0