Smart Building Heat Automation

Smart Building Heat Automation

Personal Project

Duration: N/A

Location: N/A

Project Details

A single-zone smart thermostat simulation system demonstrating IoT architecture patterns using Python, MQTT messaging, and real-time web dashboards. The system simulates temperature sensors, implements weather-aware heating control logic, and provides a live monitoring interface with historical data visualization. This project showcases decoupled microservices architecture, event-driven communication, and cloud-ready IoT deployment patterns. (GitHub)

Architecture Overview

The system follows a publish-subscribe architecture with three independent Python components communicating via MQTT:

1. Sensor Simulator (sensor/sensor.py)

  • Purpose: Generates realistic room temperature data using a random-walk algorithm
  • Functionality:
    • Simulates temperature fluctuations (e.g., 18-24°C range)
    • Publishes JSON temperature readings to MQTT topic home/1/temperature
    • Configurable publishing interval (default: every few seconds)
    • Uses Python logging for debugging and monitoring
  • MQTT Client: Eclipse Paho MQTT Python client library
  • Output Format: {"temperature": 21.5} JSON messages

2. Controller Service (controller/controller.py)

  • Purpose: Intelligent heating control with weather-based setpoint adjustment
  • Functionality:
    • Subscribes to command topic smart_thermostat/controller/command for location updates
    • Fetches real-time weather data from WeatherAPI.com for specified location
    • Adaptive Setpoint Logic:
      • If outside temperature < 5°C: Decreases heating setpoint (energy conservation)
      • If outside temperature > 18°C: Increases setpoint (comfort optimization)
      • Default setpoint: 20°C
    • Publishes comprehensive status to smart_thermostat/controller/status_feed:
      • Current weather location
      • Current setpoint temperature
      • Last fetched outside temperature
      • Timestamp
  • Weather Integration: WeatherAPI.com REST API (requires API key)
  • Update Frequency: Periodic weather fetches and status updates (configurable interval)

3. Web Dashboard & Data Hub (app.py)

  • Framework: Flask web application serving as central data aggregation point
  • MQTT Subscriber:
    • Subscribes to sensor temperature data (home/1/temperature)
    • Subscribes to controller status feed (smart_thermostat/controller/status_feed)
  • Data Processing Logic:
    • Compares indoor temperature against latest setpoint from controller
    • Determines heating action: "HEATER ON" if temp < setpoint, "HEATER OFF" otherwise
    • Logs all events (sensor readings, controller status, heating actions) to SQLite
  • Real-Time Dashboard (templates/index.html):
    • Server-Sent Events (SSE): Live updates without page refresh
    • Displayed Metrics:
      • Current indoor temperature (from sensor)
      • Current setpoint (from controller)
      • Heater action status (ON/OFF)
      • Outside temperature and weather location
    • Interactive Chart: Plotly time-series visualization of daily temperature trends
    • Location Update Form: Allows users to change weather location, which triggers MQTT command to controller
  • Data Persistence:
    • Daily SQLite databases: database/temperature_log_YYYY-MM-DD.db
    • Stores: timestamp, indoor temp, setpoint, heater action, outside temp, location
    • Enables historical analysis and trend visualization
  • MQTT Publisher: Publishes location update commands to controller

4. MQTT Broker

  • Implementation: Eclipse Mosquitto (industry-standard MQTT broker)
  • Role: Central message bus for all component communication
  • Default Port: 1883 (standard MQTT port)
  • Topics Used:
    • home/1/temperature - Sensor temperature readings
    • smart_thermostat/controller/status_feed - Controller status updates
    • smart_thermostat/controller/command - Commands to controller

Technology Stack

Core Technologies

  • Python 3: Primary programming language for all components
  • MQTT Protocol: Lightweight messaging protocol for IoT communication
  • Eclipse Paho MQTT Client: Python library for MQTT publish/subscribe operations
  • Eclipse Mosquitto: MQTT message broker (can run locally or on cloud)

Web Framework & Real-Time

  • Flask: Lightweight Python web framework for dashboard and API
  • Server-Sent Events (SSE): One-way real-time data streaming from server to browser
  • Jinja2 Templates: Server-side templating for HTML rendering

Data Visualization

  • Plotly Python: Interactive charting library for time-series temperature graphs
  • JavaScript: Client-side interactivity and SSE event handling

Data Storage

  • SQLite: Embedded database for daily temperature logs
  • File-based Logging: Python logging module for component-level debugging

External Services

  • WeatherAPI.com: REST API for real-time weather data (free tier available)
  • Requests Library: HTTP client for weather API calls

Configuration Management

  • python-dotenv: Environment variable management via .env files
  • Secure API Key Storage: Weather API key stored in .env (gitignored)

System Workflow

1. Initialization Phase

  • MQTT broker (Mosquitto) starts and listens on port 1883
  • Sensor simulator starts, begins publishing temperature readings
  • Controller service starts, subscribes to commands, fetches initial weather
  • Flask app starts, subscribes to sensor and controller topics

2. Continuous Operation

  • Sensor Loop: Publishes temperature every N seconds
  • Controller Loop:
    • Periodically fetches weather (e.g., every minute)
    • Adjusts setpoint based on outside temperature
    • Publishes status update
  • Dashboard Loop:
    • Receives sensor and controller messages via MQTT
    • Determines heating action (ON/OFF)
    • Logs to SQLite database
    • Pushes updates to connected browsers via SSE

3. User Interaction

  • User opens dashboard at http://127.0.0.1:5001
  • Dashboard displays live data via SSE
  • User updates weather location via form
  • Flask app publishes location command to MQTT
  • Controller receives command, updates location, fetches new weather

Setup & Configuration

Prerequisites

  • Python 3.x and pip
  • Git for cloning repository
  • MQTT broker (Mosquitto) - can install via Homebrew (macOS) or package manager

Installation Steps

# Clone repository
git clone https://github.com/padawanabhi/smart_heat_automation.git
cd smart_heat_automation

# Create virtual environment
python3 -m venv my_env
source my_env/bin/activate  # Windows: my_env\Scripts\activate

# Install dependencies
pip install -r requirements.txt

# Install and start Mosquitto MQTT broker
# macOS (Homebrew):
brew install mosquitto
brew services start mosquitto

# Create .env file with WeatherAPI key
echo "WEATHER_API_KEY=your_api_key_here" > .env

Running the System

Run each component in a separate terminal:

# Terminal 1: Sensor Simulator
python sensor/sensor.py

# Terminal 2: Controller Service
python controller/controller.py

# Terminal 3: Flask Dashboard
python app.py

Access dashboard at: http://127.0.0.1:5001

Potential Improvements & Enhancements

1. Hardware Integration

  • Real Sensors: Replace simulation with actual temperature sensors (DS18B20, DHT22)
  • Raspberry Pi Deployment: Deploy sensor and controller on edge devices
  • GPIO Control: Direct hardware control for actual heating systems
  • Sensor Fusion: Combine multiple sensor types (temperature, humidity, occupancy)

2. Advanced Control Algorithms

  • PID Control: Implement Proportional-Integral-Derivative controller for smoother temperature regulation
  • Machine Learning: Train models to predict optimal setpoints based on historical patterns
  • Reinforcement Learning: Learn optimal heating strategies through trial and error
  • Schedule-Based Control: Time-of-day and day-of-week scheduling
  • Occupancy Detection: Adjust heating based on room occupancy (PIR sensors, smart home integration)

3. Multi-Zone Support

  • Zone Management: Extend to multiple rooms/zones with independent control
  • Zone Coordination: Optimize heating across zones to minimize energy consumption
  • Zone Prioritization: Heat occupied zones first, reduce heating in unoccupied areas

4. Enhanced Dashboard Features

  • User Authentication: Secure access with login system
  • Mobile Responsive Design: Optimize for smartphone/tablet viewing
  • Historical Analysis: Multi-day/week/month trend analysis
  • Energy Consumption Tracking: Calculate and display estimated energy usage
  • Alert System: Notifications for temperature anomalies or system failures
  • Export Functionality: Download historical data as CSV/JSON

5. Cloud Integration

  • Cloud MQTT Broker: Use AWS IoT Core, Azure IoT Hub, or Google Cloud IoT
  • Time-Series Database: Migrate from SQLite to InfluxDB or TimescaleDB for better scalability
  • Cloud Dashboard: Deploy Flask app to cloud (Heroku, AWS, Azure)
  • Remote Access: Enable secure remote monitoring and control
  • Backup & Sync: Cloud backup of historical data

6. Advanced Protocols & Standards

  • MQTT over TLS: Secure MQTT communication with SSL/TLS encryption
  • MQTT 5.0: Upgrade to latest MQTT protocol version for enhanced features
  • CoAP Alternative: Implement Constrained Application Protocol for resource-constrained devices
  • OPC UA Integration: Industrial protocol support for building automation systems

7. Energy Optimization

  • Demand Response: Integrate with utility demand response programs
  • Time-of-Use Optimization: Adjust heating based on electricity pricing
  • Predictive Preheating: Pre-heat rooms before occupancy based on schedules
  • Energy Cost Tracking: Real-time cost calculation and budget alerts

8. Integration & Interoperability

  • Home Assistant Integration: Connect to popular home automation platforms
  • IFTTT/Zapier: Trigger actions based on temperature events
  • Smart Home APIs: Integration with Google Home, Amazon Alexa
  • REST API: Expose control endpoints for third-party integrations

9. Monitoring & Observability

  • Structured Logging: JSON-formatted logs for better parsing
  • Metrics Collection: Prometheus metrics for system health monitoring
  • Distributed Tracing: Track requests across components
  • Alerting: Email/SMS alerts for system failures or anomalies
  • Health Checks: Automated system health monitoring

10. Security Enhancements

  • MQTT Authentication: Username/password or certificate-based authentication
  • API Security: JWT tokens for dashboard access
  • Network Security: VPN or secure tunnel for remote access
  • Data Encryption: Encrypt sensitive data at rest
  • Rate Limiting: Prevent abuse and DoS attacks

Use Cases

  • IoT Learning Project: Understand MQTT, event-driven architecture, and IoT patterns
  • Home Automation Prototype: Foundation for smart home heating system
  • Energy Management: Monitor and optimize heating energy consumption
  • Building Automation: Extendable to commercial building HVAC systems
  • Educational Tool: Teaching IoT concepts, MQTT, and microservices
  • Research Platform: Test control algorithms and optimization strategies

Key Learnings & Outcomes

  • Decoupled Architecture: Demonstrates microservices pattern with independent, scalable components
  • Event-Driven Design: MQTT pub/sub enables loose coupling and real-time communication
  • Real-Time UX: SSE provides seamless live updates without polling
  • Data-Driven Insights: Historical logging enables trend analysis and optimization
  • Cloud-Ready Design: Environment-based configuration and standard protocols enable easy cloud migration
  • Production Patterns: Logging, error handling, and configuration management follow best practices

(View on GitHub)

Follow Me