Skip to content

RiturajSingh2004/HVAC-Optimization-Sys

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

7 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

HVAC-Optimization-Sys - AI-Powered Climate Control System

Smart HVAC Logo

Python 3.8+ Streamlit License: MIT OpenCV PyTorch YOLOv5

AI-powered HVAC optimization system that automatically adjusts climate control based on real-time occupancy detection, environmental conditions, and intelligent energy management algorithms.

🌟 Features

  • Real-time Occupancy Detection: Computer vision-based people counting using YOLOv5n
  • Environmental Monitoring: Integration with indoor sensors and weather APIs for comprehensive climate data
  • AI-Powered Optimization: Machine learning models for intelligent HVAC control decisions
  • Energy Efficiency: Dynamic temperature and fan speed adjustments based on occupancy patterns
  • Interactive Dashboard: Real-time monitoring and control via Streamlit web interface
  • Historical Analytics: Data logging and trend analysis for performance insights
  • Location Intelligence: Automatic location detection for accurate weather data
  • Simulation Mode: Complete testing environment with simulated sensors and weather data
  • Multi-modal Control: Supports heating, cooling, fan speed, and humidity control

πŸš€ Quick Start

Prerequisites

  • Python 3.8 or higher
  • Webcam or IP camera for occupancy detection
  • pip for package installation

Installation

  1. Clone the repository:
git clone https://github.com/RiturajSingh2004/HVAC-Optimization-Sys.git
cd HVAC-Optimization-Sys
  1. Create and activate a virtual environment (recommended):
python -m venv venv
source venv/bin/activate  # On Windows, use: venv\Scripts\activate
  1. Install dependencies:
pip install -r requirements.txt
  1. Set up configuration (optional):
cp config.py config_local.py
# Edit config_local.py with your API keys and settings
  1. Run the dashboard:
python main.py --dashboard

or

streamlit run dashboard.py
  1. Open your browser and navigate to http://localhost:8501

Headless Operation

For deployment without the dashboard interface:

python main.py --headless

πŸ—οΈ Project Structure

smart-hvac/
β”œβ”€β”€ main.py                  # Main application entry point
β”œβ”€β”€ config.py               # Configuration settings
β”œβ”€β”€ requirements.txt        # Python dependencies
β”œβ”€β”€ LICENSE                 # MIT License
β”œβ”€β”€ detection.py            # Computer vision occupancy detection
β”œβ”€β”€ sensing.py              # Environmental data collection
β”œβ”€β”€ optimizer.py            # AI-powered HVAC optimization
β”œβ”€β”€ data_logger.py          # Data logging and persistence
└── dashboard.py            # Streamlit web dashboard

βš™οΈ Core Components

OccupancyDetector (detection.py)

Implements real-time people detection using computer vision.

Key Functions:

  • load_model(): Initializes YOLOv5n model for person detection
  • detect_people(): Processes video frames to count occupants
  • get_occupancy(): Captures frames and returns occupancy count with annotated visualization

Benefits:

  • Uses lightweight YOLOv5n model for fast inference
  • Automatic GPU acceleration when available
  • Real-time video processing with annotated output
  • COCO dataset pre-trained model for accurate person detection

EnvironmentalDataCollector (sensing.py)

Manages environmental data collection from multiple sources.

Key Functions:

  • detect_location(): Automatic location detection using IP geolocation
  • get_outdoor_weather(): Fetches weather data from OpenWeatherMap API
  • get_indoor_conditions(): Reads from indoor temperature/humidity sensors
  • get_all_environmental_data(): Aggregates all environmental parameters

Benefits:

  • Automatic location detection for accurate weather data
  • Robust error handling with simulation fallbacks
  • Support for multiple sensor types
  • Real-time weather integration

HVACOptimizer (optimizer.py)

AI-powered optimization engine for HVAC control decisions.

Key Functions:

  • load_pretrained_model(): Loads transformer-based models for decision making
  • preprocess_data(): Converts environmental data to model-compatible format
  • determine_optimal_settings(): Calculates optimal HVAC parameters
  • rule_based_settings(): Fallback algorithm for robust operation
  • apply_hvac_settings(): Sends control commands to HVAC systems

Benefits:

  • Hybrid AI and rule-based approach for reliability
  • Occupancy-aware temperature management
  • Energy-efficient operation modes
  • Support for heating, cooling, and humidity control

DataLogger (data_logger.py)

Comprehensive logging system for system monitoring and analysis.

Key Functions:

  • initialize_log(): Creates structured CSV logging files
  • log_data(): Records timestamped system state data
  • get_recent_logs(): Retrieves historical data for analysis

Benefits:

  • Structured data storage for trend analysis
  • Configurable retention periods
  • CSV format for easy data analysis
  • Real-time logging of all system parameters

SmartHVACSystem (main.py)

Central orchestration class that integrates all components.

Key Functions:

  • run_once(): Single iteration of the complete system cycle
  • run_continuous(): Background thread for continuous operation
  • get_system_status(): Real-time system state reporting
  • start() / stop(): System lifecycle management

Benefits:

  • Thread-safe operation for continuous monitoring
  • Comprehensive error handling and recovery
  • Modular component integration
  • Real-time status reporting

πŸ“Š How It Works

System Workflow

  1. Occupancy Detection:

    • Camera captures frames at configurable intervals (default: 5 seconds)
    • YOLOv5n model processes frames to detect and count people
    • Annotated frames are generated for dashboard visualization
    • Occupancy count is used for energy optimization decisions
  2. Environmental Monitoring:

    • System automatically detects location using IP geolocation
    • Weather data is fetched from OpenWeatherMap API
    • Indoor sensors provide temperature and humidity readings
    • Simulation mode generates realistic data for testing
  3. AI-Powered Optimization:

    • Environmental data and occupancy are processed by ML models
    • Transformer-based models analyze conditions for optimal settings
    • Rule-based fallback ensures reliable operation
    • Energy efficiency algorithms adjust settings based on occupancy patterns
  4. HVAC Control:

    • Optimized settings are calculated for mode, temperature, and fan speed
    • Commands are sent to HVAC systems via API or simulation
    • Humidity control is managed based on comfort thresholds
    • System supports heating, cooling, and ventilation modes
  5. Data Logging and Analytics:

    • All system parameters are logged with timestamps
    • Historical trends are tracked for performance analysis
    • Dashboard provides real-time visualization of system state
    • CSV logs enable detailed post-analysis

Optimization Algorithm

The system uses a multi-layered approach for HVAC optimization:

  1. Occupancy-Based Adjustment:

    • No occupancy: Energy-saving mode (24Β°C cooling / 20Β°C heating)
    • Low occupancy (1-3 people): Comfort mode (22Β°C target)
    • High occupancy (4+ people): Enhanced cooling (21Β°C target)
  2. Environmental Adaptation:

    • Extreme outdoor temperatures trigger compensatory adjustments
    • Weather conditions influence indoor climate control decisions
    • Humidity levels are managed for optimal comfort
  3. Energy Efficiency:

    • Fan speeds are adjusted based on occupancy and outdoor conditions
    • Time-of-day considerations for different usage patterns
    • Gradual temperature adjustments to minimize energy spikes

πŸ› οΈ Configuration

Basic Configuration (config.py)

CONFIG = {
    "video_source": 0,  # 0 for webcam, or path to video file
    "detection_interval": 5,  # seconds between detection runs
    "weather_api_key": "YOUR_API_KEY",  # OpenWeatherMap API key
    "location": {
        "city": "New York",
        "country": "US"
    },
    "simulation_mode": True,  # Enable for testing without hardware
    "hvac_control_api": "http://localhost:8000/api/hvac/control"
}

Weather API Setup

  1. Register for a free API key at OpenWeatherMap
  2. Replace YOUR_API_KEY in config.py with your actual API key
  3. The system will automatically detect your location, or use the configured default

Hardware Integration

For production deployment with actual HVAC systems:

  1. Set simulation_mode = False in configuration
  2. Configure your HVAC control API endpoint
  3. Integrate indoor temperature/humidity sensors
  4. Set up camera for occupancy detection

πŸ’» Usage Examples

Dashboard Mode

Launch the interactive web dashboard:

python main.py --dashboard

Features include:

  • Real-time occupancy detection visualization
  • Environmental conditions monitoring
  • HVAC settings display and control
  • Historical data trends and analytics
  • System start/stop controls

Headless Mode

For production deployment or server installations:

python main.py --headless

The system will run continuously in the background, logging all data and controlling HVAC systems automatically.

Programmatic Usage

from main import SmartHVACSystem
from config import CONFIG

# Initialize the system
system = SmartHVACSystem(CONFIG)

# Run a single optimization cycle
system.run_once()

# Get current system status
status = system.get_system_status()
print(f"Occupancy: {status['occupancy']}")
print(f"Indoor Temp: {status['environmental_data']['indoor_temperature']}Β°C")

# Start continuous operation
system.start()

# Stop the system
system.stop()

πŸ“ˆ Performance and Analytics

Energy Efficiency Metrics

The system provides comprehensive analytics for energy optimization:

  • Occupancy Patterns: Track usage patterns to optimize schedules
  • Temperature Trends: Monitor indoor/outdoor temperature relationships
  • Energy Usage: Analyze HVAC operational efficiency
  • Comfort Metrics: Ensure optimal comfort while minimizing energy consumption

Dashboard Analytics

The Streamlit dashboard includes:

  • Real-time environmental condition displays
  • Historical temperature and occupancy trends
  • HVAC operation mode tracking
  • System performance metrics

Data Export

All system data is logged in CSV format for external analysis:

import pandas as pd

# Load system logs
df = pd.read_csv('hvac_system_log.csv')

# Analyze occupancy patterns
occupancy_trends = df.groupby('timestamp')['occupancy'].mean()

# Calculate energy efficiency metrics
efficiency_metrics = df[['indoor_temperature', 'target_temperature', 'hvac_mode']]

πŸ”§ Advanced Features

Custom Models

Replace the default optimization model with custom implementations:

class CustomHVACOptimizer(HVACOptimizer):
    def load_pretrained_model(self):
        # Load your custom model here
        return your_custom_model
    
    def determine_optimal_settings(self, env_data, occupancy):
        # Implement your optimization logic
        return custom_settings

Sensor Integration

Add support for additional sensors:

class CustomSensorCollector(EnvironmentalDataCollector):
    def get_indoor_conditions(self):
        # Integrate with your sensor hardware
        temperature = your_temp_sensor.read()
        humidity = your_humidity_sensor.read()
        return {"temperature": temperature, "humidity": humidity}

HVAC System Integration

Connect to your specific HVAC control system:

def apply_hvac_settings(self, settings):
    # Send commands to your HVAC system
    your_hvac_api.set_temperature(settings['target_temperature'])
    your_hvac_api.set_mode(settings['mode'])
    your_hvac_api.set_fan_speed(settings['fan_speed'])

πŸš€ Deployment

Local Development

  1. Clone the repository and install dependencies
  2. Configure your API keys and settings
  3. Run in simulation mode for testing
  4. Use the dashboard for interactive development

Production Deployment

  1. Set up a dedicated server or edge device
  2. Configure hardware sensors and HVAC integration
  3. Set simulation_mode = False
  4. Run in headless mode as a system service

Docker Deployment

FROM python:3.8

WORKDIR /app
COPY requirements.txt .
RUN pip install -r requirements.txt

COPY . .

EXPOSE 8501

CMD ["streamlit", "run", "dashboard.py"]

Cloud Deployment

The system can be deployed on cloud platforms like:

  • AWS EC2 for compute resources
  • Google Cloud Platform for ML model hosting
  • Azure IoT for sensor data integration

⚠️ Important Considerations

Safety and Compliance

  • HVAC Safety: Ensure all temperature and humidity settings are within safe operating ranges
  • System Redundancy: Implement fallback controls for critical environments
  • Compliance: Verify compatibility with local building codes and regulations
  • Monitoring: Continuous monitoring of system performance and safety parameters

Privacy and Security

  • Camera Privacy: Occupancy detection processes video locally without storing personal data
  • Data Security: All sensor data and logs are stored locally by default
  • API Security: Use secure connections and authentication for HVAC control APIs
  • Access Control: Implement proper authentication for dashboard access in production

Performance Optimization

  • Model Optimization: Consider quantized models for edge deployment
  • Caching: Implement caching for weather data and model predictions
  • Resource Management: Monitor CPU and memory usage for continuous operation
  • Network Resilience: Handle network interruptions gracefully

πŸ›£οΈ Roadmap

Immediate Enhancements

  • Mobile App: Native mobile application for remote monitoring
  • Advanced Analytics: Machine learning-based predictive maintenance
  • Multi-Zone Control: Support for multiple HVAC zones
  • Voice Control: Integration with voice assistants

Medium-term Goals

  • Edge AI: Optimize models for edge devices and offline operation
  • Energy Forecasting: Predict energy usage patterns and costs
  • Occupancy Prediction: Learn patterns to pre-condition spaces
  • Integration APIs: Connect with smart home and building management systems

Long-term Vision

  • Federated Learning: Share insights across installations while maintaining privacy
  • Carbon Footprint Tracking: Environmental impact monitoring and reporting
  • Predictive Maintenance: AI-powered equipment health monitoring
  • Smart Grid Integration: Dynamic pricing and demand response capabilities

πŸ“„ License

Smart HVAC System is licensed under the MIT License - see the LICENSE file for details.

🀝 Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

Areas for Contribution

  • Additional Sensors: Support for air quality, CO2, and other environmental sensors
  • HVAC Protocols: Integration with popular HVAC control protocols (BACnet, Modbus)
  • Mobile Applications: Native iOS and Android applications
  • Cloud Services: Integration with cloud-based analytics and control platforms
  • Documentation: Improve installation guides and API documentation
  • Testing: Add comprehensive unit and integration tests

Development Setup

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/amazing-feature)
  3. Install development dependencies (pip install -r requirements-dev.txt)
  4. Make your changes
  5. Add tests for new functionality
  6. Commit your changes (git commit -m 'Add amazing feature')
  7. Push to the branch (git push origin feature/amazing-feature)
  8. Open a Pull Request

πŸ‘ Acknowledgements


Β© 2025 Smart HVAC Project | GitHub | LinkedIn | Documentation

About

HVAC optimization system with OpenWeather API , DistilBERT model, OpenCV and dashboard using Streamlit

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages