Home automation with the raspberry pi

You’re sitting in bed, drifting away to sleep, but your light is on. Who wants to get out from bed and switch the lights off? The year is 2014–why are we still carrying around keys for our homes? All of these issues can be addressed with the concept of home automation, that comes along with a variety of protocols (X10, insteon, z-wave, etc).

I wanted to get started on a project that was 1) low cost, 2) wireless, 3) relatively expandable, and 4) DIY. The raspberry pi seemed to be the obvious answer for me.  There are countless others who have used the RPi for home automation such as controlling lamps, LEDs, integrating motion sensors, scheduling events–so I naturally turned to a few of these write-ups for guidance.

I started with an Etekcity RF remote control outlet controller. If I could automate the button signal on the remote’s circuit board using the Pi, I could simulate a button press for the on or off event and control electrical devices this way.  I accomplished this using a relay. Applying 3.3V from the GPIO to a relay can activate a mechanical switch that closes the circuit for a designated button on the remote. A similar circuit could then be repeated for each respective button.

rf_system

Now that I have the hardware side figured out, how do we get the RPi to be interactive? Enter Python and Flask. Flask is a Python microframework that allows users to easily program a responsive web server using python–this will allow us to control electrical outlets from anywhere with an internet connection (including the bed!). See the python code below for an example.

from flask import Flask, render_template, request, Response
app = Flask(__name__)
app.config['DEBUG'] = True

from functools import wraps
from datetime import timedelta



import time
import datetime 
import random
import os
import subprocess
import signal
import multiprocessing
import urllib
import urllib2
 
 
# Import the Raspberry Pi GPIO library.
import RPi.GPIO as GPIO

GPIO.setwarnings(False)


#define pin variables
Dev1OnPin=23
Dev1OffPin=24
Dev2OnPin=8
Dev2OffPin=7

GPIO.setmode(GPIO.BCM)
GPIO.setup(Dev1OnPin, GPIO.OUT)
GPIO.setup(Dev1OffPin, GPIO.OUT)
GPIO.setup(Dev2OnPin, GPIO.OUT)
GPIO.setup(Dev2OffPin, GPIO.OUT)

def check_auth(username, password):
 return username == 'admin' and password == 'pass'

def authenticate():
 return Response(
 'Could not verify your access level for that URL.\n'
 'You have to login with proper credentials', 401,
 {'WWW-Authenticate': 'Basic realm="Login Required"'})

def requires_auth(f):
 @wraps(f)
 def decorated(*args, **kwargs):
 auth = request.authorization
 if not auth or not check_auth(auth.username, auth.password):
 return authenticate()
 return f(*args, **kwargs)
 return decorated

def dev1(status):
 if status == 1:
 GPIO.output(Dev1OnPin, True)
 time.sleep(.5)
 GPIO.output(Dev1OnPin, False)
 print("Device1 On")
 if status == 0:
 GPIO.output(Dev1OffPin, True)
 time.sleep(.5)
 GPIO.output(Dev1OffPin, False)
 print("Device1 Off")

 
def dev2(status):
 if status == 1:
 GPIO.output(Dev2OnPin, True)
 time.sleep(.5)
 GPIO.output(Dev2OnPin, False)
 notify()
 if status == 0:
 GPIO.output(Dev2OffPin, True)
 time.sleep(.5)
 GPIO.output(Dev2OffPin, False)

 
now = datetime.datetime.now()
templateData = {'Status': 'idle', 'Time': now.strftime("%m/%d/%Y %H:%M")}

@app.route("/")
#@requires_auth
def main():
 global templateData
 now = datetime.datetime.now()
 templateData = {'Status': 'idle', 'Time': now.strftime("%m/%d/%Y %H:%M")}
 return render_template('main.html', **templateData) ##status, action
 
 
@app.route("/control/<device>/<status>")
def control_device(device, status):
 if device == 1:
 dev1(status)
 if device == 2:
 dev2(status)
 templateData = {'Status': 'Command sent', 'Time': now.strftime("%m/%d/%Y %H:%M")}
 return render_template('main.html', **templateData)

if __name__ == "__main__":
 app.run(host='0.0.0.0', port=8080, debug=True)

If you’re interested in setting up something similar, this makezine article may be a good place to start.

Next steps: using an OpenHAB server to control the home

Leave a Reply

Your email address will not be published. Required fields are marked *

*