AI-powered HVAC optimization system that automatically adjusts climate control based on real-time occupancy detection, environmental conditions, and intelligent energy management algorithms.
- 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
- Python 3.8 or higher
- Webcam or IP camera for occupancy detection
- pip for package installation
- Clone the repository:
git clone https://github.com/RiturajSingh2004/HVAC-Optimization-Sys.git
cd HVAC-Optimization-Sys- Create and activate a virtual environment (recommended):
python -m venv venv
source venv/bin/activate # On Windows, use: venv\Scripts\activate- Install dependencies:
pip install -r requirements.txt- Set up configuration (optional):
cp config.py config_local.py
# Edit config_local.py with your API keys and settings- Run the dashboard:
python main.py --dashboardor
streamlit run dashboard.py- Open your browser and navigate to
http://localhost:8501
For deployment without the dashboard interface:
python main.py --headlesssmart-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
Implements real-time people detection using computer vision.
Key Functions:
load_model(): Initializes YOLOv5n model for person detectiondetect_people(): Processes video frames to count occupantsget_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
Manages environmental data collection from multiple sources.
Key Functions:
detect_location(): Automatic location detection using IP geolocationget_outdoor_weather(): Fetches weather data from OpenWeatherMap APIget_indoor_conditions(): Reads from indoor temperature/humidity sensorsget_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
AI-powered optimization engine for HVAC control decisions.
Key Functions:
load_pretrained_model(): Loads transformer-based models for decision makingpreprocess_data(): Converts environmental data to model-compatible formatdetermine_optimal_settings(): Calculates optimal HVAC parametersrule_based_settings(): Fallback algorithm for robust operationapply_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
Comprehensive logging system for system monitoring and analysis.
Key Functions:
initialize_log(): Creates structured CSV logging fileslog_data(): Records timestamped system state dataget_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
Central orchestration class that integrates all components.
Key Functions:
run_once(): Single iteration of the complete system cyclerun_continuous(): Background thread for continuous operationget_system_status(): Real-time system state reportingstart()/stop(): System lifecycle management
Benefits:
- Thread-safe operation for continuous monitoring
- Comprehensive error handling and recovery
- Modular component integration
- Real-time status reporting
-
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
-
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
-
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
-
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
-
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
The system uses a multi-layered approach for HVAC optimization:
-
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)
-
Environmental Adaptation:
- Extreme outdoor temperatures trigger compensatory adjustments
- Weather conditions influence indoor climate control decisions
- Humidity levels are managed for optimal comfort
-
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
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"
}- Register for a free API key at OpenWeatherMap
- Replace
YOUR_API_KEYinconfig.pywith your actual API key - The system will automatically detect your location, or use the configured default
For production deployment with actual HVAC systems:
- Set
simulation_mode = Falsein configuration - Configure your HVAC control API endpoint
- Integrate indoor temperature/humidity sensors
- Set up camera for occupancy detection
Launch the interactive web dashboard:
python main.py --dashboardFeatures include:
- Real-time occupancy detection visualization
- Environmental conditions monitoring
- HVAC settings display and control
- Historical data trends and analytics
- System start/stop controls
For production deployment or server installations:
python main.py --headlessThe system will run continuously in the background, logging all data and controlling HVAC systems automatically.
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()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
The Streamlit dashboard includes:
- Real-time environmental condition displays
- Historical temperature and occupancy trends
- HVAC operation mode tracking
- System performance metrics
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']]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_settingsAdd 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}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'])- Clone the repository and install dependencies
- Configure your API keys and settings
- Run in simulation mode for testing
- Use the dashboard for interactive development
- Set up a dedicated server or edge device
- Configure hardware sensors and HVAC integration
- Set
simulation_mode = False - Run in headless mode as a system service
FROM python:3.8
WORKDIR /app
COPY requirements.txt .
RUN pip install -r requirements.txt
COPY . .
EXPOSE 8501
CMD ["streamlit", "run", "dashboard.py"]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
- 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
- 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
- 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
- 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
- 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
- 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
Smart HVAC System is licensed under the MIT License - see the LICENSE file for details.
Contributions are welcome! Please feel free to submit a Pull Request.
- 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
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature) - Install development dependencies (
pip install -r requirements-dev.txt) - Make your changes
- Add tests for new functionality
- Commit your changes (
git commit -m 'Add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
- YOLOv5 for real-time object detection
- OpenWeatherMap for weather data API
- Streamlit for the interactive dashboard framework
- OpenCV for computer vision capabilities
- PyTorch for deep learning inference
- Transformers for ML model integration
- Pandas for data analysis and logging
Β© 2025 Smart HVAC Project | GitHub | LinkedIn | Documentation
