0

The below code is meant to call the camera and email functions when motion is detected. I tried adding the functions after printing Motion Detected but didn't work. Where to add these functions?

#!/usr/bin/python
import subprocess
import socket
import datetime
#Camera
import os
import pygame, sys
from pygame.locals import *
import pygame.camera
#Email
import os
import smtplib
from email import encoders
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
#Sensor
import RPi.GPIO as GPIO
import time

GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)

COMMASPACE = ', '
GPIO.setmode(GPIO.BCM)
PIR_PIN = 7
GPIO.setup(PIR_PIN, GPIO.IN)

def MOTION(PIR_PIN):
      print(“Motion Detected!”)

print(“PIR Module Test (CTRL+C to exit)”)
time.sleep(2)
print(“Ready”)

try:
    GPIO.add_event_detect(PIR_PIN, GPIO.RISING, callback=MOTION)
    while 1:
           time.sleep(100)
except KeyboardInterrupt:
     print(“ Quit”)
     GPIO.cleanup()

def camera():
    width = 480
    height = 360

    #initialise pygame   
    pygame.init()
    pygame.camera.init()
    cam = pygame.camera.Camera("/dev/video0",(width,height))
    cam.start()

    #setup window
    windowSurfaceObj = pygame.display.set_mode((width,height),1,16)
    pygame.display.set_caption('Camera')

    #take a picture
    image = cam.get_image()
    cam.stop()

    #display the picture
    catSurfaceObj = image
    windowSurfaceObj.blit(catSurfaceObj,(0,0))
    pygame.display.update()

    #save picture
    pygame.image.save(windowSurfaceObj,'picture.jpg')

def email():
    sender = ''
    gmail_password = ''
    recipients = ''
    composed = ''

    # Create the enclosing (outer) message
    outer = MIMEMultipart()
    outer['Subject'] = 'MOTION HAS BEEN DETECTED!'
    outer['To'] = COMMASPACE.join(recipients)
    outer['From'] = sender
    outer.preamble = 'You will not see this in a MIME-aware mail reader.\n'

    # List of attachments
    attachments = ['/home/pi/Desktop/picture.jpg']

    # Add the attachments to the message
    for file in attachments:
    try:
        with open(file, 'rb') as fp:
            msg = MIMEBase('application', "octet-stream")
            msg.set_payload(fp.read())
        encoders.encode_base64(msg)
        msg.add_header('Content-Disposition', 'attachment', filename=os.path.basename(file)) 
        outer.attach(msg)
    except:
        print("Unable to open one of the attachments. Error: ", sys.exc_info()[0])
        raise

    composed = outer.as_string()

    # Send the email
    try:
        with smtplib.SMTP('smtp.gmail.com', 587) as s:
            s.ehlo()
            s.starttls()
            s.ehlo()
            s.login(sender, gmail_password)
            s.sendmail(sender, recipients, composed)
            s.close()
        print("Email sent!")
    except:
        print("Unable to send the email. Error: ", sys.exc_info()[0])
        raise

MOTION(PIR_PIN)
  • The code as presented is syntactically incorrect. E.g. there must be an indentation after def camera: Could you post the correctly indented code? It is important as the indentation changes the meaning of the script. – joan May 15 '16 at 18:26
  • I changed the code with how it is indented. Thanks – Nick May 15 '16 at 18:33
0

The code still contains syntax errors. An unindented try after a for and the use of non-standard quotes such as “ rather than ".

You need to call functions. You need to add a call to camera() and email() in your MOTION function. I.e.

def MOTION(PIR_PIN):
      print("Motion Detected!")
      camera()
      email()
  • i tried doing like your code but it says that camera is not defined even if i do the email only. Thanks – Nick May 15 '16 at 19:45
  • You have done something wrong. I don't know what. – joan May 15 '16 at 19:59
  • Solved changed the sensor code to the last part after the email code and worked. Thanks for the help! – Nick May 15 '16 at 20:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.