Opening Chat
Do you often find yourself in situations where you come home in the summer to find the indoor environment unbearably hot, or shivering from the cold in the winter? Wouldn't it be great if your air conditioner could know when you're coming home and automatically adjust to a comfortable temperature? Today, I’ll share an interesting project with you—creating a smart temperature control system using Python.
System Design
Let's talk about what features this system needs to implement. The core is threefold: automatically collect indoor temperature data, intelligently control the air conditioner based on the data, and monitor and adjust remotely via a smartphone. Does it sound complicated? Don't worry, we'll take it step by step.
First, let's look at the overall architecture: the temperature sensor is responsible for data collection, the Raspberry Pi runs a Python program to process the data and control the air conditioner, then communicates with the cloud via the MQTT protocol, and finally uses the Flask framework to build a beautiful webpage to display data.
Code Implementation
Let's start with the most basic temperature collection:
import Adafruit_DHT
import time
from datetime import datetime
class TemperatureSensor:
def __init__(self, sensor_type=Adafruit_DHT.DHT22, pin=4):
self.sensor = sensor_type
self.pin = pin
def get_temperature(self):
humidity, temperature = Adafruit_DHT.read_retry(self.sensor, self.pin)
if temperature is not None:
return round(temperature, 2)
return None
def monitor_temperature(self, interval=300):
while True:
temp = self.get_temperature()
if temp:
print(f"Current time: {datetime.now()}, Temperature: {temp}°C")
time.sleep(interval)
if __name__ == "__main__":
sensor = TemperatureSensor()
sensor.monitor_temperature()
Data Processing
With temperature data, we need to analyze and process the data. For example, we can calculate the temperature trend throughout the day, allowing us to predict when to turn on the air conditioner in advance.
import pandas as pd
import numpy as np
class TemperatureAnalyzer:
def __init__(self):
self.temp_data = []
def add_temperature(self, temp, timestamp):
self.temp_data.append({
'timestamp': timestamp,
'temperature': temp
})
def analyze_trend(self, window_size=12): # Default to using 1-hour data (collected every 5 minutes)
df = pd.DataFrame(self.temp_data)
df['rolling_mean'] = df['temperature'].rolling(window=window_size).mean()
return df
if __name__ == "__main__":
analyzer = TemperatureAnalyzer()
# Simulate adding a day's temperature data
for hour in range(24):
temp = 20 + np.sin(hour * np.pi / 12) * 5 # Simulate temperature changes
analyzer.add_temperature(temp, pd.Timestamp(f'2024-10-24 {hour:02d}:00:00'))
trend_data = analyzer.analyze_trend()
print(trend_data)
Remote Control
Now let's implement the most exciting part—remote control. We'll use the Flask framework to build a simple web interface, allowing you to check your home temperature anytime using your phone and adjust the air conditioner remotely.
from flask import Flask, render_template, jsonify
from threading import Thread
import paho.mqtt.client as mqtt
app = Flask(__name__)
class SmartThermostat:
def __init__(self):
self.current_temp = None
self.target_temp = 24
self.is_running = False
self.setup_mqtt()
def setup_mqtt(self):
self.client = mqtt.Client()
self.client.on_connect = self.on_connect
self.client.on_message = self.on_message
self.client.connect("localhost", 1883, 60)
self.client.loop_start()
def on_connect(self, client, userdata, flags, rc):
print("MQTT Connected with result code "+str(rc))
client.subscribe("home/temperature")
def on_message(self, client, userdata, msg):
self.current_temp = float(msg.payload)
self.check_temperature()
def check_temperature(self):
if self.current_temp > self.target_temp + 1:
self.turn_on_ac()
elif self.current_temp < self.target_temp - 1:
self.turn_off_ac()
def turn_on_ac(self):
if not self.is_running:
print("Turning on AC")
self.is_running = True
def turn_off_ac(self):
if self.is_running:
print("Turning off AC")
self.is_running = False
thermostat = SmartThermostat()
@app.route('/')
def index():
return render_template('index.html',
current_temp=thermostat.current_temp,
target_temp=thermostat.target_temp,
is_running=thermostat.is_running)
@app.route('/api/set_temperature/<float:temp>')
def set_temperature(temp):
thermostat.target_temp = temp
thermostat.check_temperature()
return jsonify({'status': 'success'})
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000)
Practical Application
After discussing so much code, you might ask: how effective is this system in practice? I’ve been using it in my own home for over six months, and it has indeed brought a lot of convenience. For example, now the system automatically adjusts the home temperature to the most comfortable state half an hour before I get off work each day, based on outdoor temperature and historical data.
What surprises me even more is that this system has helped me save a lot on electricity bills. By analyzing temperature trends, the system turns the air conditioner on and off at the most appropriate times, avoiding the situation where the air conditioner is always on.
Advanced Optimization
After running the system for a while, I found that some interesting features could be added. For example:
- Integrate a weather forecast API to anticipate weather changes.
- Automatically adjust the temperature based on family members' schedules.
- Record electricity expenses and generate monthly electricity reports.
These features are not difficult to implement, and you can add more features according to your needs.
Conclusion and Outlook
Through this project, we see the power of Python in the IoT field. From sensor data collection and data analysis processing to remote control and web interface development, Python can handle it all with ease.
What other functions do you think this smart temperature control system could have? Feel free to share your thoughts in the comments. Your creativity might help more people build their own smart home systems.