SMS Garage Door Butler: Raspberry Pi

0

Raspberry Pi – SMS Garage Door Butler:

SMS Garage Door Butler

Remote operated garage door based on Raspberry Pi have some or the other features which I didn’t like and therefore I decided to make my own remote which is much secure and has other features like it captures video of garage, log details of who opened the garage, update with garage status, etc.

Some key features of the new system are:

  1. The new system will be 100% secure with only authorized people like the family members will have access to open the garage and will be added in the control list.
  2. The garage operations can be regulated from any place with help of website and does not require open router ports.
  3. Inside video of the garage can be captured to know who all have entered the garage and can be checked later on the website.
  4. In case of any misuse or exploitation of garage, the new system has the ability to stop that process remotely.
  5. Get notification if someone enters or leaves the garage
  6. Get SMS without the use of any GSM card or SIM card.
  7. The new system is based on simple linux code which can be easiliy ported to other linux supported platforms in case new technology arrives.

Step 1:

Things Required

Required Things

The below things are required:

  1. Raspberry Pi or any similar platform to do basic configuration set up. In below lesson we are using Raspbian Wheezy.
  2. Connectivity via wireless dongle or through network cable.
  3. Webcam or Pi Cam which is compatible with other devices
  4. Solid State Relay Board preferably which has Default setting as LOW.
  5. Long wire to access the garage door.
  6. Webspace or cheap website to store data. Some possible cheap options include Good drive or drop box which comes free of cost or some cheap websites like 1and1.com which provides sufficient space for very less cost. The files created can be deleted from time to time to free the data as those will be mostly log files.
  7. Putty in case of PiCam usage.

Step 2:

Libraries to be mounted in Raspberry Pi

Firstly a new account needs to be created on Twilio.com which would require the following things:

Twilio Phone number which charges you $1 for each month

Some Balance in your account

Once, your account in Twilio is set up, you can install the important libraries in Raspberry Pi, following the below line of codes:

sudo apt-get install -y python-pip mysql-server python-devlibmysqlclient-dev

sudo pip install MySQL-python twilio

You would also require to create two folders (or directories) which are:

/home/pi/movies

/home/pi/pictures

Step 3:

Raspberry Pi – Creation of databases using SQL, creating user and giving permissions:

The next step is to create database and create users and give them privilges and permissions using SQL queries. This can be done with help of MySQL localhost server. Use the below lines of codes to do so:

mysql -pYourSQLPassword -u root -h localhost

create database GarageDoor;

useGarageDoor;

create table Door(sSid CHAR(40));

create table Authorized(sPhone CHAR(20));

create table Log(sPhone CHAR(20), sAction CHAR(10), dDatedatetime);

–In case you are working within US, prefix +1 with your phone number or prefix —-your ISD code for the country your phone number belong:

insert into Authorized (sPhone) values (‘+12145551212’);

CREATE USER ‘garage’@’localhost’ IDENTIFIED BY ‘garagepassword’;

GRANT ALL PRIVILEGES ON * . * TO ‘garage’@’localhost’;

FLUSH PRIVILEGES;

exit;

Step 4:

Raspberry Pi – Placing The Relay Board

Placing The Relay Board

The Raspberry Pi is fixed with the relay board. The 23rd pin of GPIO which is the 16th physical pin in Raspberry Pi is used to connect with relay board The Relay Board can be purchased from Amazon. SainSmart 4- Channel comes at an affordable price of $9. Connect the relay board with your garage door with the help of the wire. You might need to look up in the garage manual to carry out this activity.

As can be seen in the image, the garage remote which I has already as the button which I just soldered with two wires to connect it with the relay.

Make proper connection between the relay and Raspberry Pi. 2nd pin is connected with 5V, while 6th is grounded and the 16th one used to control the relay. Once, connected, on sending HIGH signal the door of the garage should get opened.

Step 5:

Raspberry Pi – Connecting Camera

Raspberry Pi - Connecting Camera

While making my own system, I used Raspberry Camera, however, one can purchase a webcam or Pi Cam which are compatible with your linux computer.

Place the camera so that it can capture the full view of the garage and fix it using wires and putty. The camera can be placed on Raspberry Pi or on shelf of the device or a 3D printed case can be used, however, it will be expensive.

 

Step 6:

Raspberry Pi – Installation using Butler code

Installation using Butler code

 The code which needs to be entered into the Raspberry Pi can be obtained from below:

importRPi.GPIO as GPIO

importMySQLdb

importdatetime

import time

importos

importsmtplib

fromftplib import FTP

fromemail.MIMEMultipart import MIMEMultipart

fromemail.MIMEText import MIMEText

fromemail.MIMEImage import MIMEImage

fromcontextlib import closing

fromtwilio.rest import TwilioRestClient

# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=

#                       VARIABLES

#           CHANGE THESE TO YOUR OWN SETTINGS!

# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=

# Insert your own account’s SID and auth_token from Twilio’s account page

twilio_account_sid = “xxxxxxxxxxxxxxxxxxxxxxxxxx”

twilio_auth_token = “yyyyyyyyyyyyyyyyyyyyyyyyyyyyyy”

# The phone number you purchased from Twilio

sTwilioNumber = “+12145551212”

# Gmail information – for informing homeowner that garage activity happened

recipients = [‘myemail@gmail.com’, ‘home_owner_email@gmail.com’]

sGmailAddress = “myemail@gmail.com”

sGmailLogin = “GoogleUserName”

sGmailPassword = “GoogleEmailPassword”

sFTPUserName = “WebsiteFTPUsername”

sFTPPassword = “WebsiteFTPPassword”

sFTPHost = “MyWebsite.com”

iNumOpenings = 0

iStatusEnabled = 1

iAuthorizedUser_Count = 0

iSID_Count = 0

sLastCommand = “Startup sequence initiated at {0}.  No open requests, yet”.format(time.strftime(“%x %X”))

sAuthorized = “”

sSid = “”

sSMSSender = “”

GPIO_PIN = 23

GPIO.setmode(GPIO.BCM)

GPIO.setup(GPIO_PIN, GPIO.OUT)

# Unfortunately, you can’t delete SMS messages from Twilio’s list.

# So we store previously processed SIDs into the database.

lstSids = list()

lstAuthorized = list() # authorized phone numbers, that can open the garage

# Connect to local MySQL database

con = MySQLdb.connect(‘localhost’, ‘garage’, ‘garagepassword’, ‘GarageDoor’)

# Twilio client which will be fetching messages from their server

TwilioClient = TwilioRestClient(twilio_account_sid, twilio_auth_token)

# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=

#                       FUNCTIONS

# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=

# This function sends an SMS message, wrapped in some error handling

defSendSMS(sMsg):

try:

sms = TwilioClient.sms.messages.create(body=”{0}”.format(sMsg),to=”{0}”.format(sSMSSender),from_=”{0}”.format(sTwilioNumber))

except:

print “Error inside function SendSMS”

pass

# Once the garage door has begun opening, I want a video of who’s coming in.  And then, upload the video to my website so I can see it remotely

defTakeVideoAndUpload():

try:

sVideoFile = “Vid.{0}.h264”.format(time.strftime(“%m-%d-%Y.%I.%M.%S”))

# Give 10 seconds to garage to raise up

time.sleep(10)

# Now take 60 seconds of video, to see who’s coming inside

sVideoCommand = “raspivid -w 640 -h 480 -o /home/pi/movies/{0} -t 60000”.format(sVideoFile)

os.system(sVideoCommand)

ftp = FTP(sFTPHost,sFTPUserName,sFTPPassword)

ftp.storbinary(“stor {0}”.format(sVideoFile), open(“/home/pi/movies/{0}”.format(sVideoFile),’rb’),blocksize=1024)

# It uploaded ok, so delete the video file to avoid clogging up SD card space

os.system(“sudorm /home/pi/movies/{0}”.format(sVideoFile))

except:

print “Error inside function TakeVideoAndUpload”

pass

# When doing a STATUS on the Garage SMS Butler, it will capture a screen shot of the garage, so I can see if it’s open or closed, from anywhere in the world

defTakePictureAndUpload():

try:

os.system(“raspistill -w 640 -h 480 -o /home/pi/pictures/garagepic.jpg”)

ftp = FTP(sFTPHost,sFTPUserName,sFTPPassword)

ftp.storbinary(“stor garagepic.jpg”, open(“/home/pi/pictures/garagepic.jpg”,’rb’),blocksize=1024)

except:

print “Error inside function TakePictureAndUpload”

pass

# Send a signal to the relay

defOpenGarageDoor():

try:

GPIO.output(GPIO_PIN, GPIO.HIGH)

time.sleep(0.5)

GPIO.output(GPIO_PIN, GPIO.LOW)

except:

print “Error inside function OpenGarageDoor”

pass

# Email the home owner with any status updates

defSendGmailToHomeOwner(sMsg):

try:

connect = server = smtplib.SMTP(‘smtp.gmail.com:587’)

starttls = server.starttls()

login = server.login(sGmailLogin,sGmailPassword)

msg = MIMEMultipart()

msg[‘Subject’] = “GARAGE: {0}”.format(sMsg)

msg[‘From’] = sGmailAddress

msg[‘To’] = “, “.join(recipients)

sendit = server.sendmail(sGmailAddress, recipients, msg.as_string())

server.quit()

except:

print “Error inside function SendGmailToHomeOwner”

pass

try:

# Store authorized phone numbers in a List, so we don’t waste SQL resources repeatedly querying tables

with closing(con.cursor()) as authorized_cursor:

authorized_users = authorized_cursor.execute(“select sPhone from Authorized”)

auth_rows = authorized_cursor.fetchall()

forauth_row in auth_rows:

forauth_col in auth_row:

iAuthorizedUser_Count = iAuthorizedUser_Count + 1

lstAuthorized.append(auth_col)

# Store previous Twilio SMS SID ID’s in a List, again, so we don’t waste SQL resources repeatedly querying tables

with closing(con.cursor()) as sid_cursor:

sid_rows = sid_cursor.execute(“select sSid from Door”)

sid_rows = sid_cursor.fetchall()

forsid_row in sid_rows:

forsid_col in sid_row:

iSID_Count = iSID_Count + 1

lstSids.append(sid_col)

print “{0} Service loaded, found {1} authorized users, {2} previous SMS messages”.format(time.strftime(“%x %X”),iAuthorizedUser_Count,iSID_Count)

SendGmailToHomeOwner(“{0} Service loaded, found {1} authorized users, {2} previous SMS messages”.format(time.strftime(“%x %X”),iAuthorizedUser_Count,iSID_Count))

except:

print “{0} Error while loading service, bailing!”.format(time.strftime(“%x %X”))

if con: con.close() # Not critical since we’re bailing, but let’s be nice to MySQL

exit(2)

# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=

#                       MAIN GARAGE LOOP

#

#         Continuously scan Twilio’s incoming SMS list

# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=

while (True):

# The TRY block is critical.  If we cannot connect to the database, then we could possibly open the garage dozens of times.

# If we can’t contact Twilio, again, we could open the garage excessively.  Ideally, if any error at all occurs, we need

# to completely bail, and ideally contact the home owner that this application stopped working.

try:

# Only process messages from today (Twilio uses UTC)

messages = TwilioClient.messages.list(date_sent=datetime.datetime.utcnow())

for p in messages:

sSMSSender = p.from_

# Only processed fully received messages, otherwise we get duplicates

ifp.status == “received”:

ifp.sid not in lstSids: # Is it a unique SMS SID ID from Twilio’s list?

# Insert this new SID ID into database and List, to avoid double processing

lstSids.append(p.sid)

try:

with closing(con.cursor()) as insert_sid_cursor:

insert_sid_cursor = insert_sid_cursor.execute(“insert into Door(sSid) values(‘{0}’)”.format(p.sid))

con.commit()

except:

print “Error while inserting SID record to database”

pass

ifp.from_ in lstAuthorized: # Is this phone number authorized to open garage door?

ifp.body.lower() == “kill”:

print “{0} Received KILL command from phone number {1} – bailing now!”.format(time.strftime(“%x %X”), sSMSSender)

SendSMS(“Received KILL command from you.  Bailing to terminal now!”)

SendGmailToHomeOwner(“Received KILL command from phone number {0}.  Exiting application!”.format(sSMSSender))

exit(3)

ifp.body.lower() == “disable”:

iStatusEnabled = 0

print “{0} Received STOP command from phone number {1}, now disabled.  Send START to restart”.format(time.strftime(“%x %X”), sSMSSender)

SendSMS(“Received STOP command from you.  Send START to restart”)

SendGmailToHomeOwner(“Received STOP command from phone number {0}.  Send START to restart”.format(sSMSSender))

ifp.body.lower() == “enable”:

iStatusEnabled = 1

print “{0} Received START command from phone number {1}.  Service is now enabled”.format(time.strftime(“%x %X”), sSMSSender)

SendSMS(“Received START command from you.  Service is now enabled”)

SendGmailToHomeOwner(“Received START command from phone number {0}.  Service is now enabled”.format(sSMSSender))

ifp.body.lower() == “status”:

ifiStatusEnabled == 1:

TakePictureAndUpload()

print “{0} Status requested from {1}, replied”.format(time.strftime(“%x %X”), sSMSSender)

SendSMS(“ENABLED.  Status reply: {0}”.format(sLastCommand))

else:

print “{0} SERVICE DISABLED!  Status requested from {1}, replied”.format(time.strftime(“%x %X”), sSMSSender)

SendSMS(“SERVICE DISABLED!  Status reply: {0}”.format(sLastCommand))

ifp.body.lower() in (“open”,”close”):

ifiStatusEnabled == 1:

iNumOpenings = iNumOpenings + 1

sLastCommand = “Garage door last opened by {0} on {1}”.format(p.from_, time.strftime(“%x %X”))

print “{0} Now opening garage for phone number {1}”.format(time.strftime(“%x %X”), sSMSSender)

# OPEN GARAGE DOOR HERE

SendSMS(“Command received, and sent to garage door”)

print “{0} SMS response sent to authorized user {1}”.format(time.strftime(“%x %X”), sSMSSender)

OpenGarageDoor()

TakeVideoAndUpload()

SendGmailToHomeOwner(“Garage opened from phone {0}”.format(sSMSSender))

print “{0} Email sent to home owner”.format(time.strftime(“%x %X”))

else:

print “{0} Open request received from {1} but SERVICE IS DISABLED!”.format(time.strftime(“%x %X”), sSMSSender)

else: # This phone number is not authorized.  Report possible intrusion to home owner

print “{0} Unauthorized user tried to access system: {1}”.format(time.strftime(“%x %X”), sSMSSender)

SendGmailToHomeOwner(“Unauthorized phone tried opening garage: {0}”.format(sSMSSender))

print “{0} Email sent to home owner”.format(time.strftime(“%x %X”))

exceptKeyboardInterrupt:

SendGmailToHomeOwner(“Application closed via keyboard interrupt (somebody closed the app)”)

GPIO.cleanup() # clean up GPIO on CTRL+C exit

exit(4)

except:

print “Error occurred, bailing to terminal”

SendGmailToHomeOwner(“Error occurred, bailing to terminal”)

GPIO.cleanup()

exit(1)

GPIO.cleanup()

However, the following modifications are required in the code:

Change the variable and give your Twilio account phone number.

Give your own personal cell number

Obtain authentication code from your Twilio’s account main screen and give it in the code.

Run the below lines of code:

sudochmod 755 garage_sms_butler.py

python garage_sms_butler.py

Send ansms to your Twilio phone number by writing status. Once the SMS is delivered, you would receive an SMS which provides you with information of person who opened the garage last.

Step 7:

Raspberry Pi – Checking out results on website

Index of Uploads

The following commands can be used to carry out different operations. Send SMS to Twilio phone number with below commands which will carry out the below mentioned operations.

OPEN: It will open the garage door by sending a HIGH signal to the relay. The webcam will also automatically record the video of the person and put it in your website.

STATUS: As mentioned above, it will give information about the person who opened the garage door lastly. An image will also be uploaded on the website depicting garage status.

DISABLE: This command will stops sending you notification about the opening and closing of the garage door.

ENABLE: It will start sending the notification about opening and closing of the garage door if it was disabled earlier.

KILL: The system will stop working and you comes out of the system. No commands will work after it.

 Step 8:

Raspberry Pi – FAQs

Working Camera

Why can’t we use Motion to capture videos?

The information is only required about people who are opening and closing the garage. Motion is not required, for example, any activity done in the garage need to be recorded. Moreover, the system only captures 60 second of video which gives enough time to recognize who entered the garage. Moreover, motion recording makes huge files which are then difficult to use for other purpose like live streaming, etc.

Is there a specific need to use a website to upload the video?

Website is used so that the video can be viewed from anywhere through internet. The cost of most website providers are around $11 per year which provides 100GB of data. Another option can be dropbox or google drive. In order to use them, the code has to be modified with python code which is available freely.

Why do we not host the Pi website?

Pi network or use of Web GPIO have open ports and is not secure. Hence, because of the security issues. Also, I don’t feel the necessity of live streaming the garage.

Why not use Adafruit’s FONA for sending out SMS?

Again, Twilio account and sending text is cheaper as compared to using FONA. Plus, you also have to enroll yourself into cell contract to use FONA.

Step 9:

Credits

Working Camera Credits

For selling me all these goodies, thank you ADAFRUIT. For new products, I haunt that store daily.

Share.

About Author

Leave A Reply