Create Your Own Smart Home Control System
Do you want to have your own smart home system? Control your appliances, lights, air conditioning… with your phone. Sounds cool, right? You can easily achieve this idea using Python. Today, I will guide you through creating a simple smart device remote control system, making your home devices as smart as in a sci-fi movie.
Building the Control Center
The core of the system is a control center, responsible for receiving commands and controlling devices. We will use the Flask framework to set up a web server, allowing us to send control commands via a webpage or mobile app.
from flask import Flask, request, jsonify
import RPi.GPIO as GPIO
app = Flask(__name__)
# Set GPIO mode
GPIO.setmode(GPIO.BCM)
GPIO.setup(18, GPIO.OUT) # LED connected to GPIO 18
@app.route('/device/control', methods=['POST'])
def control_device():
data = request.get_json()
device = data.get('device')
action = data.get('action')
if device == 'light':
if action == 'on':
GPIO.output(18, GPIO.HIGH)
else:
GPIO.output(18, GPIO.LOW)
return jsonify({'status': 'success'})
🔔 Reminder: Remember to install the Flask framework first, you can do this with pip install flask.
Adding Device Control Logic
Now that the control center is set up, we need to write the specific device control logic. I used the Raspberry Pi GPIO interface to control physical devices, but you can use other development boards as well.
class Device:
def __init__(self, name, pin):
self.name = name
self.pin = pin
self.status = False
def turn_on(self):
GPIO.output(self.pin, GPIO.HIGH)
self.status = True
def turn_off(self):
GPIO.output(self.pin, GPIO.LOW)
self.status = False
# Create device instances
light = Device('Living Room Light', 18)
fan = Device('Fan', 23)
Remote Control Interface
Having just a backend is not enough; we also need a nice control interface. I wrote a simple webpage using HTML and JavaScript, so you can control the devices by accessing it from your phone.
@app.route('/')
def index():
return '''
<!DOCTYPE html>
<html>
<head>
<title>Smart Home Control</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
.btn { padding: 10px; margin: 5px; }
</style>
</head>
<body>
<h2>My Smart Devices</h2>
<button class="btn" onclick="control('light','on')">Turn On Light</button>
<button class="btn" onclick="control('light','off')">Turn Off Light</button>
<script>
function control(device, action) {
fetch('/device/control', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({device: device, action: action})
});
}
</script>
</body>
</html>
'''
Adding Some Security
Is it really that simple? No way! What if the neighbor finds out about this control page and can control your devices at will? We need to add a simple user authentication.
from functools import wraps
from flask import session, redirect
def login_required(f):
@wraps(f)
def wrapper(*args, **kwargs):
if not session.get('logged_in'):
return redirect('/login')
return f(*args, **kwargs)
return wrapper
@app.route('/login', methods=['POST'])
def login():
if request.form['password'] == '666666':
session['logged_in'] = True
return redirect('/')
return 'Incorrect password!'
🚨 Reminder: In actual projects, passwords should be stored securely; this is just for demonstration purposes.
Status Monitoring
The remote control system is basically complete, but we can add a real-time monitoring feature to check the operational status of the devices. We will use WebSocket to implement real-time data pushing.
from flask_socketio import SocketIO, emit
socketio = SocketIO(app)
def monitor_status():
while True:
status = {
'light': light.status,
'fan': fan.status,
'temperature': get_temperature()
}
socketio.emit('status_update', status)
time.sleep(5)
import threading
threading.Thread(target=monitor_status).start()
Once the code is complete, run the program, and you can access the control interface by visiting the Raspberry Pi’s IP address on your phone! Maybe in the future, we can integrate a voice assistant, and just lying in bed, you can say “turn on the light” to get it done. After writing all this, I really want to buy a Raspberry Pi to play with…