Shathis Kumar
Posts: 6
Joined: Sat Nov 26, 2016 7:36 pm

Help in python coding

Sat Nov 26, 2016 7:46 pm

I'm doing the same project but not using piCamera. I'm using Logitech C270 webcam.
Upon testing, I am able to capture image using webca, and able to send email without attachment.
Now all i Need is the full coding to be edited in a way that when my PIR motion sensor detects motion, it must trigger the buzzer and trigger to webcam to snap picture. And then i want it to send attachment to the gmail account.
p/s: email provided is just a sample from internet.

Code: Select all

#!/usr/bin/env python
import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEBase import MIMEBase
from email.MIMEText import MIMEText
from email.Utils import COMMASPACE, formatdate
from email import Encoders
import os
import RPi.GPIO as GPIO
import time
import picamera # new
USERNAME = "raspberrypipi795@gmail.com"
PASSWORD = "berry1993"
sensor = 24
led = 17
buzzer = 27
system_start = False
taken_image = False
hasSendMail = False
GPIO.setmode(GPIO.BCM)
GPIO.setup(sensor, GPIO.IN, GPIO.PUD_DOWN)
GPIO.setup(led, GPIO.OUT)
GPIO.setup(buzzer, GPIO.OUT)
previous_state = False
current_state = False
def sendMail(to, subject, text, files=[]):
assert type(to)==list
assert type(files)==list
msg = MIMEMultipart()
msg['From'] = USERNAME
msg['To'] = COMMASPACE.join(to)
msg['Date'] = formatdate(localtime=True)
msg['Subject'] = subject
msg.attach( MIMEText(text) )
for file in files:
part = MIMEBase('application', "octet-stream")
part.set_payload( open(file,"rb").read() )
Encoders.encode_base64(part)
part.add_header('Content-Disposition', 'attachment; filename="%s"'
% os.path.basename(file))
msg.attach(part)
server = smtplib.SMTP('smtp.gmail.com:587')
server.ehlo_or_helo_if_needed()
server.starttls()
server.ehlo_or_helo_if_needed()
server.login(USERNAME,PASSWORD)
server.sendmail(USERNAME, to, msg.as_string())
server.quit()
cam = picamera.PiCamera() # new
while True:
time.sleep(1)
openFile = open("data_cmd.txt","r")
operation = openFile.read()
if operation == "Activate":
print "Activate"
system_start = True
elif operation == "Deactivate":
print "Dectivate"
if hasSendMail == True:
GPIO.output(led, False)
GPIO.output(buzzer, False)
#cam.stop_preview()
hasSendMail = False
system_start = False
elif operation == "Capture_Image":
taken_image = True
openFile = open("data_cmd.txt","w")
appendFile = openFile.write("")
openFile.close()
if taken_image == True:
print "Capture Image"
cam.capture('/var/www/inmosis/image/image.jpg')
openFile = open("image_file.txt","w")
appendFile = openFile.write("image.jpg")
taken_image = False
if system_start == True:
previous_state = current_state
current_state = GPIO.input(sensor)
if current_state != previous_state:
new_state = "HIGH" if current_state else "LOW"
print("GPIO pin %s is %s" % (sensor, new_state))
if current_state: # new
print "Image"
GPIO.output(led, True)
GPIO.output(buzzer,1)
#cam.start_preview()
cam.capture('image.jpg')
sendMail( ["fuzza93@gmail.com"],"Motion detected!!!","Attached is the captured image",["image.jpg"] )
hasSendMail = True
print "Send Mail"
else:
GPIO.output(led, False)
GPIO.output(buzzer, False)
#cam.stop_preview()
Last edited by Shathis Kumar on Sun Nov 27, 2016 12:26 pm, edited 1 time in total.

User avatar
elParaguayo
Posts: 1943
Joined: Wed May 16, 2012 12:46 pm
Location: London, UK

Re: Help in python coding

Sun Nov 27, 2016 8:48 am

You need to post your code inside [/b] tags. Read this viewtopic.php?f=32&t=84477 and please edit your post.
RPi Information Screen: plugin based system for displaying weather, travel information, football scores etc.

Shathis Kumar
Posts: 6
Joined: Sat Nov 26, 2016 7:36 pm

Re: Help in python coding

Sun Nov 27, 2016 3:06 pm

Anyone with suggestions?

User avatar
elParaguayo
Posts: 1943
Joined: Wed May 16, 2012 12:46 pm
Location: London, UK

Re: Help in python coding

Mon Nov 28, 2016 12:14 pm

You've still lost your formatting for your code. Indentation is essential in python so, before anything else, you need to update your first post.

Next up, can you be more specific about the problem you're facing. I appreciate you want to attach the image to the email but can you confirm whether the image is sending ok, whether the email is sending ok (albeit with no attachment), whether you get any error messages (if you do, paste the full message here).
RPi Information Screen: plugin based system for displaying weather, travel information, football scores etc.

Major Tom
Posts: 65
Joined: Wed Feb 03, 2016 8:13 am
Location: Strung up in heavens high.

Re: Help in python coding

Mon Nov 28, 2016 12:26 pm

Shathis Kumar wrote:Anyone with suggestions?
Break the problem down into small parts. Get each part working. Put the parts together.

You already said you can take a picture and you can send an email. I little more Googling will tell you how to send an email with a picture as an attachment.

Next, for the PIR you'll need to know how to use GPIO. Take a look at RPi.GPIO and try a simple program looking at the state of a GPIO pin. You can connect a switch to the GPIO pin and get your program to do something based on the state of the switch. Another easy project is lighting an LED with the GPIO. Find out how to connect an LED and write a program to turn the LED on and off.

Now, write a program that checks if the switch is pressed. If it is, turn on the LED, take a picture, attach it to an email, and send it. Then, replace the switch with a PIR sensor and the LED with a buzzer. Congratulations! You finished the project!
My circuit's dead, there's something wrong.

User avatar
B.Goode
Posts: 10439
Joined: Mon Sep 01, 2014 4:03 pm
Location: UK

Re: Help in python coding

Mon Nov 28, 2016 9:34 pm

+1 to what Major Tom said.

That reply encapsulates just the advice I wanted to give, but does so with more grace and humour than I could have managed.

Shathis Kumar
Posts: 6
Joined: Sat Nov 26, 2016 7:36 pm

Re: Help in python coding

Tue Dec 06, 2016 6:01 pm

Code: Select all

import RPi.GPIO as GPIO
import time
import smtplib
import os

sensor = 4
buzzer = 18
led = 24

GPIO.setmode(GPIO.BCM)
GPIO.setup(sensor, GPIO.IN, GPIO.PUD_DOWN)
GPIO.setup(led, GPIO.OUT)
GPIO.setup(buzzer, GPIO.OUT)

#previous_state = False
current_state = False

while True:
    time.sleep(0.1)
    #previous_state = current_state
    current_state = GPIO.input(sensor)
    print("GPIO pin %s is %s" % (sensor, current_state))

    if current_state == 1:
        #new_state = "HIGH" if current_state else "LOW"
        GPIO.output(buzzer,False)
        GPIO.output(led,True)
        print("GPIO pin %s is %s" % (sensor, current_state))
        os.system("fswebcam -r 1280x720 --no-banner image31.jpg")
		

        server = smtplib.SMTP('smtp.gmail.com', 587)
        server.starttls()
        server.login("shathis14@gmail.com", "gcmvyytnxtvcdxce")

        msg = "INTRUDER!"
        server.sendmail("shathis14@gmail.com ", " raspberrypishathis@gmail.com"$
        server.quit()

    else:
        GPIO.output(led, False)
        GPIO.output(buzzer,True)

Shathis Kumar
Posts: 6
Joined: Sat Nov 26, 2016 7:36 pm

Re: Help in python coding

Tue Dec 06, 2016 6:06 pm

Guys,

Now I have successfully compiled a code where when a motion detect is detected by my PIR sensor, it will trigger an LED, a buzzer and my Logitech C270 webcam to snap picture. Thus, when the motion is detected, an email will be sent to my email as "intruder" without subject.
Now, my only problem is how to send the picture as attachment. I have google and can't get the solution. Kindly let me know how to send the picture via email based on the code I'm using now.

Major Tom
Posts: 65
Joined: Wed Feb 03, 2016 8:13 am
Location: Strung up in heavens high.

Re: Help in python coding

Wed Dec 07, 2016 11:58 am

Well done for getting it going!

Here is a discussion on adding attachments to email. In the example the person is attaching a PDF file, but it could be any file, such as a JPG:
http://stackoverflow.com/questions/1966 ... using-smtp

Good luck!
My circuit's dead, there's something wrong.

Shathis Kumar
Posts: 6
Joined: Sat Nov 26, 2016 7:36 pm

Re: Help in python coding

Thu Dec 08, 2016 2:14 am

Hey Tom/others,

I've tried to implement the code in the link but still it can't send the image. I can detect syntax errors. Now, what I want is the code to access into my SD card path which is /home/pi/image.jpg and send the image to my email. Kindly let me know how to edit my working code. I hope to hear from you guys the soonest. The due date to complete this project is tomorrow so I would appreciate someone who could help me with the code. Sorry for demanding

User avatar
B.Goode
Posts: 10439
Joined: Mon Sep 01, 2014 4:03 pm
Location: UK

Re: Help in python coding

Thu Dec 08, 2016 2:05 pm

If you cannot complete your assignment in time, at least submit what you have done so far accompanied by a report that indicates you know what features are unimplemented, what you tried to implement them, and what fault-finding process you went through to try to fix the problems you encountered.

(Saying: "I asked some guys on the Internet but they didn't help" probably isn't good enough!)

Unless there is a very harsh success or failure marking scheme that should at least get you some credit for what you have accomplished.

Shathis Kumar
Posts: 6
Joined: Sat Nov 26, 2016 7:36 pm

Re: Help in python coding

Thu Dec 08, 2016 2:25 pm

Thanks for the helpful replies guys. Now the system runs well as programmed. Good Day, people

Return to “Python”