MannyBot365

Home automation system.

IntermediateShowcase (no instructions)Over 16 days4,113
MannyBot365

Things used in this project

Story

Read more

Schematics

pirSecure Circuit

Code

pirSecure.py

PHP
Main Python script that captures a pic on motion. PIR Motion Sensor is connected to RPi Pin 4. Uses fswebcam to capture image through attached USB WebCam. IR Receiver is connected to pin 24 and buzzer on pin 18.
#!/usr/bin/env python

from azure.storage.blob import BlobService
from datetime import datetime, timedelta
from threading import Timer
from subprocess import call
from time import strftime
import RPi.GPIO as GPIO
import time
import uuid
import sys
import xmpp
import os.path


sensor = 4
servo = 17
beeper = 18
irLight = 24
#MOTION_DELAY = 60

GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
GPIO.setup(sensor,  GPIO.IN, GPIO.PUD_DOWN)
GPIO.setup(servo,   GPIO.OUT)
GPIO.setup(beeper,  GPIO.OUT, GPIO.PUD_DOWN)
GPIO.setup(irLight, GPIO.OUT, GPIO.PUD_DOWN)
pwm = GPIO.PWM(beeper, 1000)
food = GPIO.PWM(servo, 50)
#turned_on = False
#last_motion_time = time.time()

blob_service = BlobService(account_name='AZURE_ACCOUNT_NAME', account_key='AZURE_ACCOUNT_KEY')
blob_service.create_container('achindra')
blob_service.set_container_acl('achindra', x_ms_blob_public_access='blob')
offline = False

#Fish food feeder
def feeder_thread():
  if os.path.isfile("/home/pi/feedtime.log") == False:
    fh = open("/home/pi/feedtime.log", "w")
    fh.write(datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S'))
    fh.close()
  Timer(5, scheduleJob, ()).start()

def scheduleJob():
  print "feed job"
  Timer(5, scheduleJob, ()).start()
  fh = open("/home/pi/feedtime.log", "r")
  dt = fh.read()
  print dt
  #t = datetime.strptime(dt, '%Y-%m-%d %H:%M:%S')
  fh.close()
  time_diff = datetime.utcnow() - datetime.utcfromtimestamp(float(dt))
  print time_diff
  if time_diff > timedelta(seconds=10):
    feeder()
    fh = open("/home/pi/feedtime.log", "w")
    fh.write(datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S'))
    fh.close()

def feeder():
    for x in range(0,5):
      food.ChangeDutyCycle(5)
      time.sleep(1)
      print "-"
      food.ChangeDutyCycle(7.5)
      time.sleep(2)
      print "/"

#Interrupt Handler
def MOTION(sensor):
    global jabber
    global offline
    #last_motion_time = time.time()    
    #if time.time() > (last_motion_time + MOTION_DELAY):
    backup()
    beep()
    GPIO.output(irLight, GPIO.HIGH);
    clip()
    GPIO.output(irLight, GPIO.LOW);
    post_tv()
    post_cloud()

def clip():
    call(["fswebcam", "-S 4", "-r 1280x768", "-s Gamma=50%", "/home/pi/image.jpg"])    

def post_tv():
    call(["pkill", "fbi"])
    call(["/home/pi/ttyecho", "-n", "/dev/tty1", "fbi -a -noverbose -d /dev/fb0 /home/pi/image.jpg"]) 

def beep():    
    pwm.start(100)
    time.sleep(0.5)
    pwm.stop()

def backup():
    call(["cp", "-f",  "/home/pi/image.jpg", "/home/pi/preCam.jpg"])

def post_cloud():
    blobName = str( uuid.uuid4() )
    blob_service.put_block_blob_from_path('achindra', 'DoorCam', '/home/pi/image.jpg', x_ms_blob_content_type='image/png')
    blob_service.put_block_blob_from_path('achindra', blobName, '/home/pi/image.jpg', x_ms_blob_content_type='image/png')
    #try:
    #   if offline == True :
    #      jabber.auth('GMAIL_LOGIN','GMAIL_PASSWORD', 'DoorBot')
    #      offline = False
    #   else:
    message = xmpp.Message('achindrabhatnagar@gmail.com', 'http://pisecure.blob.core.windows.net/achindra/' + blobName + ' ' + strftime("%d/%m/%Y %H:%M") )
    message.setAttr('type', 'chat')
    jabber.send(message)
    #except:
    #   offline = True    



#Start
time.sleep(2)
#feeder_thread()
try:
    global jabber
    jabber = xmpp.Client('gmail.com')
    jabber.connect(server=('talk.google.com', 5222))
    jabber.auth('GMAIL_LOGIN', 'GMAIL_PASSWORD', 'DoorBot')
    offline = False
    GPIO.add_event_detect(sensor, GPIO.RISING, callback=MOTION, bouncetime=10000)
    while 1:
        time.sleep(100)


#Quit
except KeyboardInterrupt:
    GPIO.cleanup()
GPIO.cleanup()

irClick.py

PHP
This script is triggered from TV remote when programmed button is pressed. The script takes a picture through USB WebCam and shows it on TV.
from subprocess import call
#call(["pkill", "fbi"])
#call(["/home/pi/ttyecho", "-n", "/dev/tty1", "fbi -a -noverbose -d /dev/fb0 /home/pi/waiting.jpeg"])
call(["fswebcam", "-r 1280x768", "-s Gamma=50%", "/home/pi/image.jpg"])
call(["pkill", "fbi"])
call(["/home/pi/ttyecho", "-n", "/dev/tty1", "fbi -a -noverbose -d /dev/fb0 /home/pi/image.jpg"])

motion.py

PHP
Simple test script for motion sensor, turns on/off LED/buzzer.
#!/usr/bin/env python

import sys
import time
import RPi.GPIO as io
import subprocess

io.setmode(io.BCM)
SHUTOFF_DELAY = 60 # seconds
PIR_PIN = 25       # 22 on the board
LED_PIN = 16

def main():
    io.setup(PIR_PIN, io.IN)
    io.setup(LED_PIN, io.OUT)
    turned_off = False
    last_motion_time = time.time()

    while True:
        if io.input(PIR_PIN):
            last_motion_time = time.time()
            io.output(LED_PIN, io.LOW)
            print ".",
            sys.stdout.flush()
            if turned_off:
                turned_off = False
                turn_on()
        else:
            if not turned_off and time.time() > (last_motion_time + 
                                                 SHUTOFF_DELAY):
                turned_off = True
                turn_off()
            if not turned_off and time.time() > (last_motion_time + 1):
                io.output(LED_PIN, io.HIGH)
        time.sleep(.1)

def turn_on():
    subprocess.call("sh /home/pi/photoframe/monitor_on.sh", shell=True)

def turn_off():
    subprocess.call("sh /home/pi/photoframe/monitor_off.sh", shell=True)

if __name__ == '__main__':
    try:
        main()
    except KeyboardInterrupt:
        io.cleanup()

Credits

Achindra Bhatnagar

Achindra Bhatnagar

20 projects • 161 followers
Windows Kernel Hacker, IoT Hobbyist, Enthusiast, Developer and Dreamer
Abhishek Narain

Abhishek Narain

3 projects • 12 followers
Tech Enthusiast, Gadget lover, App Dev.
Stanley George

Stanley George

1 project • 4 followers
Hi

Comments