Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

How could I adjust this code to open a 12v linear actuator before opening the garage door? So im wanting the code to receive the

How could I adjust this code to open a 12v linear actuator before opening the garage door? So im wanting the code to receive the command, makes the actuator slide open because it is being used as a lock and then the video and garage door begins.

image text in transcribedimage text in transcribedimage text in transcribedimage text in transcribed

import RPi.GPIO as GPIO

import MySQLdb

import datetime

import time

import os

import smtplib

from ftplib import FTP

from email.MIMEMultipart import MIMEMultipart

from email.MIMEText import MIMEText

from email.MIMEImage import MIMEImage

from contextlib import closing

from twilio.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

def SendSMS(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

def TakeVideoAndUpload():

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("sudo rm /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

def TakePictureAndUpload():

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

def OpenGarageDoor():

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

def SendGmailToHomeOwner(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()

for auth_row in auth_rows:

for auth_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()

for sid_row in sid_rows:

for sid_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

if p.status == "received":

if p.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

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

if p.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)

if p.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))

if p.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))

if p.body.lower() == "status":

if iStatusEnabled == 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))

if p.body.lower() in ("open","close"):

if iStatusEnabled == 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"))

except KeyboardInterrupt:

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()

import RPi GPIQ as GPIO import Msoldb import datetime mport time import s import autplib from ftplik import FTP Sid- GPIO PIN-23 GPIQetug(GPIO PIN, GPIO.OUT) Unfortunately, you cant delete SMS messages from Twilio's list. S we store previously processed SIDe into the database. from cmailMIMElaac import MIMEImaa from couteatlik import closing lat Authociand-listO # authorized phone numbers, that can open the garage # Connect to local MySQL database Twilio client which will be fetching messages from their server # VARIABLES # CHANGE THESE TO YOUR OWN SETTINGS! # FUNCTIONS # Insert your own account's SD and agt.taken from Twilio's account page # This function sends an SMS message, wrapped in some error handling # The phone m mber you purchased from Twilio aTwiliaNiumbs +121455512121 # Gmail information-for informing homeowner that garage activity happened recipients[myemail@gmail.com, home_ owner email@gmail.com'] format s TwilioNumber) print "Error inside function SeadSMS # 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 aee it remotely E "MyWebsite.com # Give 10 seconds to garage to raise up timealeepc10) # Now, take 60 seconds of video, to see who's coming assa maana-'aauud-w 640-h 480-o homepu movies 40)-t 60000" format avileaEus) inaide autCommand "Startup sequence initiated at (0. No open requests, msg[Subject] "GARAGE: (0)fomatMag msglTo]-"nrecipients) sadit open home pi/ movies (0format(sVideoFile),rb),blocksize-1024) # It uploaded ok, 30 delete the video file to avoid clogging up SD card space ga antem("auderm /home pi/moviea/ (0) ".format (VideoFile)) except: print Esor inside function Take VideoAadload pase except: print Error inside fonction SeadGmailTaHomeQwner try: # When doing a STATUS on the Garage SMS Butler, it will capture a screen shot ofthe garage, so I can ee if its open or closed, from anywhere in the world t Store authorized phone numbers in a List, so we don't waste SOL resources repeatedly querying tables with closing) as authRidE try: select sPhaas from Authorized") emi640-h 480-o home pi/pictures garagepic.jpg) for authxx in autha for auth al in auth Rin atce garagepic.jpg", open" home/pi pictures/garagepic.jPE".leskizs-1024) print "Error inside function TakePictareAndunlead # Store previous Twilio SMS SID ID's in querying tables pass List, again, so we dont waste SQL resources repeatedly #Send a signal to the relay id .sssute'select Sid from Door) id 0Si ac.fstchallo for sid so in gid try: SRIQ iuut(GPIO PIN, GPIO HIGH) for sidcol in aid o GRIQ SHtuutGPIO PIN, GPIO LOW) except: print Error inside function QpcagaDoos print "0 Service lcaded, found 1) authorized users, 2 previous SMS # Email the hom owner with any status updates def Send GmailtoHomeQuneraMag) SeadGmailToHomeQunet (0) Service loaded, found (1) authorized upers, (2) previous SMS try: connect-serversutplib.SMT smtp.gmailcom:587) print "(0) Error while loading service, bailaat tumattime atime("%x %X")) if con. SSRGlasO # Not critical since we're bailing, but let's be nice to MySQL ScadGmailloHomcQaeReceived KILL command from phone number (0). Exiting # MAIN GARAGE LOOP exit 3) # Continuously scan Twilo' s incoming SMS list print 10) Received STOP command from phone number 1,now disabled. Send START to while (True)- tsataat.mcoattimcattime("%x %X")SSMSScadeo STOP command from you. Send START to restart") # The TRY block is critical. If we cannot connect to the database, then we could possibly open the If we cant contact Twilio, again, we could open the garage excessively. Ideally, if any error at all # to completely bail, and ideally contact the home owner that this application stopped working. eived STOP command from phone number (0). Send START to garage dozens of times occurs, we need StatisEnabled-1 print 0Received START command from phone numberfl3. Service is now try: # Only process messages from today (Twilio uses UTC) SendsMS( Received START command from you. Service is now enabled eived START command from phone number (0 Service is for p in messages: if g.body.lgw"status": # Only processed fully received messages, otherwise we get duplicates ifstatuereceied if Raid not in latSda # ls t a unique SAIS SID ID from Twilio's 1st? print . {0) Status requested from { 1 } gspliedtermaarters at time("%x %X"), SSMSSeade # Insert this new SD into database and List, to avoid double processing else: print "(0) SERVICE DISABLED! Status requested from (1) SeadSMSC"SERVICE DISABLED! Status reply:0) fomat sLaatCommaad)) try: insert into values(o" formatp.sid)) except print "Error while inserting SID record to database" pass aLatamaaad-"Garage door last opened by {0) on {1)-formadRfga_ tuus stutuus("%x print "(0) Now opening garage for phone number {1}"formarum&mtims("%s %X"). ifnlosa_ in latautRuant # Is this phone number authorized to open garage door? SJSSeade # OPEN GARAGE DOOR HERE print "0 Received KILL command from phone number {1) bailing SendsMSC Command received, and sent to garage door) SendSMS Received KILL command from you. Bailing to terminal now! print "(0} SMS response sent to authorized user {1}"formatitane at time("%x %X"), SendSmailtotomeQmexl" Garage opened from phone (0}" format(sSMSSeade print " {0) Email sent to home swaetdomat(time attime("%x %X'')) else print "0) Open request received from (1 but SERVICE IS else: # This phone number is not authorized. Report possible intrusion to home owner print " {0) Unauthorized user tried to access system: {1}-format(timemtind%!X"), SMSSender Unauthorized phone tried opening garage (0".format sSMSSendex)) print " {0) Email sent to home One.format(time at time("% %X")) exce SeadGmailtToHmeQwaer" Application closed via keyboard interrupt (somebody closed the app)") GPIO.cleanupO # clean up GPIO on CTRL+C exit exit(4) except: print "Error occurred, bailing to terminal SeadGmailtTHemeQwasr"Error occurred, bailing to terminal) exit(1) GPIQ.cleanu0 import RPi GPIQ as GPIO import Msoldb import datetime mport time import s import autplib from ftplik import FTP Sid- GPIO PIN-23 GPIQetug(GPIO PIN, GPIO.OUT) Unfortunately, you cant delete SMS messages from Twilio's list. S we store previously processed SIDe into the database. from cmailMIMElaac import MIMEImaa from couteatlik import closing lat Authociand-listO # authorized phone numbers, that can open the garage # Connect to local MySQL database Twilio client which will be fetching messages from their server # VARIABLES # CHANGE THESE TO YOUR OWN SETTINGS! # FUNCTIONS # Insert your own account's SD and agt.taken from Twilio's account page # This function sends an SMS message, wrapped in some error handling # The phone m mber you purchased from Twilio aTwiliaNiumbs +121455512121 # Gmail information-for informing homeowner that garage activity happened recipients[myemail@gmail.com, home_ owner email@gmail.com'] format s TwilioNumber) print "Error inside function SeadSMS # 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 aee it remotely E "MyWebsite.com # Give 10 seconds to garage to raise up timealeepc10) # Now, take 60 seconds of video, to see who's coming assa maana-'aauud-w 640-h 480-o homepu movies 40)-t 60000" format avileaEus) inaide autCommand "Startup sequence initiated at (0. No open requests, msg[Subject] "GARAGE: (0)fomatMag msglTo]-"nrecipients) sadit open home pi/ movies (0format(sVideoFile),rb),blocksize-1024) # It uploaded ok, 30 delete the video file to avoid clogging up SD card space ga antem("auderm /home pi/moviea/ (0) ".format (VideoFile)) except: print Esor inside function Take VideoAadload pase except: print Error inside fonction SeadGmailTaHomeQwner try: # When doing a STATUS on the Garage SMS Butler, it will capture a screen shot ofthe garage, so I can ee if its open or closed, from anywhere in the world t Store authorized phone numbers in a List, so we don't waste SOL resources repeatedly querying tables with closing) as authRidE try: select sPhaas from Authorized") emi640-h 480-o home pi/pictures garagepic.jpg) for authxx in autha for auth al in auth Rin atce garagepic.jpg", open" home/pi pictures/garagepic.jPE".leskizs-1024) print "Error inside function TakePictareAndunlead # Store previous Twilio SMS SID ID's in querying tables pass List, again, so we dont waste SQL resources repeatedly #Send a signal to the relay id .sssute'select Sid from Door) id 0Si ac.fstchallo for sid so in gid try: SRIQ iuut(GPIO PIN, GPIO HIGH) for sidcol in aid o GRIQ SHtuutGPIO PIN, GPIO LOW) except: print Error inside function QpcagaDoos print "0 Service lcaded, found 1) authorized users, 2 previous SMS # Email the hom owner with any status updates def Send GmailtoHomeQuneraMag) SeadGmailToHomeQunet (0) Service loaded, found (1) authorized upers, (2) previous SMS try: connect-serversutplib.SMT smtp.gmailcom:587) print "(0) Error while loading service, bailaat tumattime atime("%x %X")) if con. SSRGlasO # Not critical since we're bailing, but let's be nice to MySQL ScadGmailloHomcQaeReceived KILL command from phone number (0). Exiting # MAIN GARAGE LOOP exit 3) # Continuously scan Twilo' s incoming SMS list print 10) Received STOP command from phone number 1,now disabled. Send START to while (True)- tsataat.mcoattimcattime("%x %X")SSMSScadeo STOP command from you. Send START to restart") # The TRY block is critical. If we cannot connect to the database, then we could possibly open the If we cant contact Twilio, again, we could open the garage excessively. Ideally, if any error at all # to completely bail, and ideally contact the home owner that this application stopped working. eived STOP command from phone number (0). Send START to garage dozens of times occurs, we need StatisEnabled-1 print 0Received START command from phone numberfl3. Service is now try: # Only process messages from today (Twilio uses UTC) SendsMS( Received START command from you. Service is now enabled eived START command from phone number (0 Service is for p in messages: if g.body.lgw"status": # Only processed fully received messages, otherwise we get duplicates ifstatuereceied if Raid not in latSda # ls t a unique SAIS SID ID from Twilio's 1st? print . {0) Status requested from { 1 } gspliedtermaarters at time("%x %X"), SSMSSeade # Insert this new SD into database and List, to avoid double processing else: print "(0) SERVICE DISABLED! Status requested from (1) SeadSMSC"SERVICE DISABLED! Status reply:0) fomat sLaatCommaad)) try: insert into values(o" formatp.sid)) except print "Error while inserting SID record to database" pass aLatamaaad-"Garage door last opened by {0) on {1)-formadRfga_ tuus stutuus("%x print "(0) Now opening garage for phone number {1}"formarum&mtims("%s %X"). ifnlosa_ in latautRuant # Is this phone number authorized to open garage door? SJSSeade # OPEN GARAGE DOOR HERE print "0 Received KILL command from phone number {1) bailing SendsMSC Command received, and sent to garage door) SendSMS Received KILL command from you. Bailing to terminal now! print "(0} SMS response sent to authorized user {1}"formatitane at time("%x %X"), SendSmailtotomeQmexl" Garage opened from phone (0}" format(sSMSSeade print " {0) Email sent to home swaetdomat(time attime("%x %X'')) else print "0) Open request received from (1 but SERVICE IS else: # This phone number is not authorized. Report possible intrusion to home owner print " {0) Unauthorized user tried to access system: {1}-format(timemtind%!X"), SMSSender Unauthorized phone tried opening garage (0".format sSMSSendex)) print " {0) Email sent to home One.format(time at time("% %X")) exce SeadGmailtToHmeQwaer" Application closed via keyboard interrupt (somebody closed the app)") GPIO.cleanupO # clean up GPIO on CTRL+C exit exit(4) except: print "Error occurred, bailing to terminal SeadGmailtTHemeQwasr"Error occurred, bailing to terminal) exit(1) GPIQ.cleanu0

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Microsoft Visual Basic 2005 For Windows Mobile Web Office And Database Applications Comprehensive

Authors: Gary B. Shelly, Thomas J. Cashman, Corinne Hoisington

1st Edition

0619254823, 978-0619254827

More Books

Students also viewed these Databases questions

Question

Have I incorporated my research into my outline effectively?

Answered: 1 week ago