Dana Mah
Published © GPL3+

Trail Camera

This is a trail camera that will notify you using a cellular network that there has been activity nearby.

EasyFull instructions provided2 hours6,625

Things used in this project

Story

Read more

Schematics

Schematic of PIR to PI

Schematic gghzxmlzuv

Code

motionsensor.py

Python
This code can be found here https://feathub.com/evancohen/smart-mirror/+12
#!/usr/bin/python

# Import der Python libraries
import RPi.GPIO as GPIO
import time
import datetime

# We use the Board Mode, enter the PIN number instead of the GPIO BCM number
GPIO.setmode(GPIO.BOARD)

# define GPIO, 7 because my sensor is connected to Pin7
GPIO_PIR = 7

print "Motionsensor Test (CTRL-C for exit)"
print "========================================="

#  define GPIO as an "Input"
GPIO.setup(GPIO_PIR,GPIO.IN)

Current_State  = 0
Previous_State = 0

try:

 print "%s: initialize Sensor ..." % datetime.datetime.now()

 # waiting for signal of the Sensor
 while GPIO.input(GPIO_PIR)==1:
   Current_State  = 0

 print "%s: Ready! Waiting for motion..."  % datetime.datetime.now()

 # Loop until CTRL+C
 while True :

   #Getting status of the Sensor
   Current_State = GPIO.input(GPIO_PIR)

   if Current_State==1 and Previous_State==0:

     print " %s: Motion detected!" % datetime.datetime.now()
     Previous_State=1

   elif Current_State==0 and Previous_State==1:

     print " %s: Ready! Waiting for motion..."  % datetime.datetime.now()
     Previous_State=0

   time.sleep(0.01)

except KeyboardInterrupt:
 print " Exit"
 GPIO.cleanup()

motion.py

Python
This is similar to the motion detector code with the addition of adding support for the raspberry pi camera. There are a lot of options you can add to adjust your camera settings, but I just used the defaults.
#!/usr/bin/python

# Import der Python libraries
import RPi.GPIO as GPIO
import time
import datetime
import picamera

# We use the Board Mode, enter the PIN number instead of the GPIO BCM number
GPIO.setmode(GPIO.BOARD)

# define GPIO, 7 because my sensor is connected to Pin7
GPIO_PIR = 7

print "Motionsensor Test (CTRL-C for exit)"
print "========================================="

#  define GPIO as an "Input"
GPIO.setup(GPIO_PIR,GPIO.IN)

Current_State  = 0
Previous_State = 0

try:

 print "%s: initialize Sensor ..." % datetime.datetime.now()

 # waiting for signal of the Sensor
 while GPIO.input(GPIO_PIR)==1:
   Current_State  = 0

 print "%s: Ready! Waiting for motion..."  % datetime.datetime.now()


 camera = picamera.PiCamera()

 # Loop until CTRL+C
 while True :

   #Getting status of the Sensor
   Current_State = GPIO.input(GPIO_PIR)

   if Current_State==1 and Previous_State==0:

     print " %s: Motion detected!" % datetime.datetime.now()
     camera.capture(str(datetime.datetime.now()) + '.jpg')
     time.sleep(15)
     Previous_State=1

   elif Current_State==0 and Previous_State==1:

     print " %s: Ready! Waiting for motion..."  % datetime.datetime.now()
     Previous_State=0

   time.sleep(0.01)

except KeyboardInterrupt:
 print " Exit"
 GPIO.cleanup()

report2.sh

SH
This script should be placed in a cron job to run once a day. It will make a internet connection using the Nova Modem, run the report and then disconnect.

Once the report is sent, it will move the images from the images folder to the archive folder.
#/bin/bash

sudo hologram network connect
python emailreport.py
sudo hologram network disconnect

mv images/*.jpg archive

report.sh

SH
This is the script that is run every night at 11:55pm, it does a count of all the jpg images taken and send that number to holograms cloud where it will format a message, emailing it to me to let me know how many images were taken that day.

I wanted to send all the file names, but I keep running into issue around the size of the message. If I can figure that out, I will update the script to send the image file names.
#/bin/bash
value=$(ls -l *jpg | wc -l)
sudo hologram send -v --cloud --devicekey 'YOUR KEY' --topic 'report' $value
mv *.jpg archive

emailreport.py

Python
This will generate a list of images in the images directory and email them out to you

You will need to update the following properties to your specific values
SMTPserver = 'smtp.sendgrid.net'
sender = 'youremail@somewhere.com'
destination = ['someemail@somewhere.com']
USERNAME = "your username"
PASSWORD = "your password"
#! /usr/local/bin/python
import sys
import os
import re
import glob

from smtplib import SMTP_SSL as SMTP       # this invokes the secure SMTP protocol (port 465, uses SSL)
# from smtplib import SMTP                  # use this for standard SMTP protocol   (port 25, no encryption)
from email.mime.text import MIMEText

SMTPserver = 'smtp.sendgrid.net'
sender =     'youremail@somewhere.com'
destination = ['someemail@somewhere.com']
USERNAME = "your username"
PASSWORD = "your password"

# typical values for text_subtype are plain, html, xml
text_subtype = 'plain'

subject="Sent from Trail Cam 1"

try:
    files = glob.glob("images/*.jpg")
    files.sort(key=os.path.getmtime)
    #print("\n".join(files))

    if len(files) > 0:
        content="There were " + str(len(files)) + " images taken today:\n\n" + str("\n\r".join(files)).replace("images/", "").replace(".jpg", "") + "\n\nThank you"
    else:
        content="There were no images taken today\n\n\nThank you."

    msg = MIMEText(content, text_subtype)
    msg['Subject']=subject
    msg['From']=sender # some SMTP servers will do this automatically, not all

    conn = SMTP(SMTPserver)
    conn.set_debuglevel(False)
    conn.login(USERNAME, PASSWORD)
    try:
        conn.sendmail(sender, destination, msg.as_string())
    finally:
        conn.quit()

except Exception, exc:
    sys.exit( "mail failed; %s" % str(exc) ) # give a error message

emailimage.py

Python
This will listen for an imcomming SMS message from the Nova modem, take the message, which should be a filename from the email report, compress the image then email to you.

You will need to update the following properties for your email provider
SMTPserver = 'smtp.sendgrid.net'
sender = 'youremail@somewhere.com'
destination = ['someemail@somewhere.com']
USERNAME = "your username"
PASSWORD = "your password"

It should also be noted you will need root privileges in order to run it.
You will need Python Image Library installed to do the image compression
#! /usr/local/bin/python
import sys
import os
import re
import time
from Hologram.HologramCloud import HologramCloud

from smtplib import SMTP_SSL as SMTP       # this invokes the secure SMTP protocol (port 465, uses SSL)
from email.mime.text import MIMEText
from email.MIMEMultipart import MIMEMultipart
from email.MIMEBase import MIMEBase
from email import Encoders

#Used for image compression, requires Python Image Library Installed
import StringIO
from PIL import Image


#Setup email properties
SMTPserver = 'smtp.sendgrid.net'
sender =     'youremail@somewhere.com'
destination = ['someemail@somewhere.com']
USERNAME = "your username"
PASSWORD = "your password"

# typical values for text_subtype are plain, html, xml
text_subtype = 'plain'

subject="Image requested from Trail Cam 1"

def sendEmail(filename):
    #Compress the image requested before emailing it out
    #filename="test"
    im1 = Image.open("archive/" + filename + ".jpg")
    buffer = StringIO.StringIO()
    im1.save(buffer, "JPEG", quality=50)
    with open("tmp/" + filename + "X.jpg", "w") as handle:
        handle.write(buffer.getvalue())

    try:
        #msg = MIMEText(content, text_subtype)
        msg = MIMEMultipart()
        msg['Subject']=       subject
        msg['From']   = sender # some SMTP servers will do this automatically, not all

        part = MIMEBase('application', "octet-stream")
        #part.set_payload(open("2018-01-10_20:23:23.189189.jpg", "rb").read())
        part.set_payload(open("tmp/" + filename + "X.jpg", "rb").read())
        Encoders.encode_base64(part)

        part.add_header('Content-Disposition', 'attachment; filename="2018-01-10_20:23:23.189189.jpg"')

        msg.attach(part)

        conn = SMTP(SMTPserver)
        conn.set_debuglevel(False)
        conn.login(USERNAME, PASSWORD)
        try:
            conn.sendmail(sender, destination, msg.as_string())
        finally:
            conn.quit()

        os.remove("tmp/" + filename + "X.jpg")
    except Exception, exc:
        #sys.exit( "mail failed; %s" % str(exc) ) # give a error message
        print "Failed to send email\n " + str(exc) 



# this function now pops the received message and prints it out.

def sayHelloReceivedAndPopMessage():
  print "hello! I received something!"
  sms_obj = hologramCloud.popReceivedSMS()
  print sms_obj.message
  sendEmail(sms_obj.message)


hologramCloud = HologramCloud(dict(), network='cellular')
print hologramCloud.version # Prints 0.7.0
print hologramCloud.network_type # Prints either 'Network Agnostic Mode' or 'Cellular'

hologramCloud.event.subscribe('sms.received', sayHelloReceivedAndPopMessage)

# someone sends a "this is the payload" message
# prints "hello! I received something!"
# prints "this is the payload"

while (1):
  time.sleep(100)
  sms_obj = hologramCloud.popReceivedSMS() # prints None

Credits

Dana Mah

Dana Mah

7 projects • 12 followers
I'm a hobbyist interested in microcontroller solutions to simple problems.

Comments