Skip to content

cloudservicesiot/iot-backend

Repository files navigation

IoT Backend System

A comprehensive backend system for managing IoT devices, energy monitoring, automation, and real-time data processing.

πŸš€ Features

Core Functionality

  • 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

Energy Aggregation System

  • 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

πŸ“‹ Prerequisites

  • Node.js (v16 or higher)
  • MongoDB database
  • MQTT broker (for IoT device communication)
  • Environment variables configured (see .env setup)

πŸ› οΈ Installation

  1. Clone the repository

    git clone <repository-url>
    cd iot-backend
  2. Install dependencies

    npm install
  3. Configure environment variables Create a .env file 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
  4. Start the server

    npm start
    # or for development with auto-reload
    nodemon index.js

πŸ“ Project Structure

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

⏰ Scheduled Tasks

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 period
  • totalEnergyConsumption: Cumulative meter reading at end of period

πŸ§ͺ Testing

Energy Calculation Tests

Run comprehensive tests to verify energy aggregation calculations:

npm run test:energy

This will test:

  • βœ… Hourly calculations accuracy
  • βœ… Daily aggregation sums
  • βœ… Monthly aggregation sums
  • βœ… Yearly aggregation sums
  • βœ… Data consistency
  • βœ… Edge cases (meter resets, missing data)

πŸ”§ Configuration

MongoDB Connection

The system supports multiple MongoDB connection methods:

  1. Direct URI (recommended):

    MONGO_URI=mongodb://username:password@host:port/database
  2. Environment Variables:

    MONGO_HOST=localhost
    MONGO_PORT=27017
    MONGO_DB=iot-db
    MONGO_USER=username
    MONGO_PASSWORD=password

MQTT Configuration

Configure MQTT broker connection:

MQTT_BROKER_URL=mqtt://broker-url:1883
MQTT_USERNAME=your-username
MQTT_PASSWORD=your-password

πŸ“Š Energy Aggregation Details

Calculation Logic

Hourly:

  • totalValue = Current hour's last reading - Previous hour's last reading
  • totalEnergyConsumption = Last raw reading of the hour

Daily:

  • totalValue = Sum of all hourly totalValue for the day
  • totalEnergyConsumption = Last hour (23:00) of the day's totalEnergyConsumption

Monthly:

  • totalValue = Sum of all daily totalValue for the month
  • totalEnergyConsumption = Last day of the month's totalEnergyConsumption

Yearly:

  • totalValue = Sum of all monthly totalValue for the year
  • totalEnergyConsumption = December's totalEnergyConsumption

Features

  • βœ… Handles meter resets automatically
  • βœ… Falls back to raw history if aggregated data unavailable
  • βœ… Validates all calculations
  • βœ… Prevents negative consumption values

🐳 Docker Support

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

πŸ” Security

  • JWT-based authentication
  • Password hashing with bcrypt
  • CORS configuration
  • Input validation
  • Protected routes with middleware

πŸ“ Environment Variables

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

Manual Deployment

  1. Set environment variables on your hosting platform
  2. Install dependencies: npm install --production
  3. Start the server: npm start

πŸ“š Additional Documentation

  • Energy Aggregation: See DbScheduling/energyAggregator.js for detailed aggregation logic
  • Testing Guide: Run npm run test:energy and review test output
  • API Documentation: Check individual route files in routes/ directory

🀝 Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Run tests: npm run test:energy
  5. Submit a pull request

πŸ“„ License

See LICENSE file for details.

πŸ‘₯ Authors

  • Ahmad - Initial work

πŸ› Troubleshooting

Common Issues

  1. MongoDB Connection Failed

    • Check MONGO_URI in .env
    • Verify MongoDB is running
    • Check network connectivity
  2. MQTT Connection Issues

    • Verify MQTT broker URL and credentials
    • Check firewall settings
    • Ensure MQTT broker is accessible
  3. Energy Calculations Incorrect

    • Run tests: npm run test:energy
    • Check aggregation logs
    • Verify raw data exists in database
  4. WebSocket Not Working

    • Check CORS configuration
    • Verify Socket.IO client connection
    • Check server logs for errors

πŸ“ž Support

For issues and questions, please open an issue on the repository.


Version: 1.0.0

About

No description, website, or topics provided.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Contributors 2

  •  
  •