OhioJoe

internet_camera.py

Mar 12th, 2017
344
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 8.59 KB | None | 0 0
  1. # Raspberry Pi motion sensitive camera
  2. # this program is started when the wifi interface is up and running
  3. #https://www.instructables.com/id/Raspberry-Pi-Motion-Sensitive-Camera/?ALLSTEPS
  4. # to overlay text and data see: http://raspi.tv/2014/overlaying-text-and-graphics-on-a-photo-and-tweeting-it-pt-5-twitter-app-series
  5. # make Ram Disk
  6. # removed sudo nano /etc/crontab <-to check for internet connection q15 minutes and reconnect
  7. # from: http://alexba.in/blog/2015/01/14/automatically-reconnecting-wifi-on-a-raspberrypi/
  8.  
  9. # import required libraries
  10. import os, picamera, sys, time, smtplib, urllib2
  11. import RPi.GPIO as GPIO
  12. import subprocess
  13. import logging
  14.  
  15. # logging  
  16. LOG = "/home/pi/camera.log"                                                    
  17. logger = logging.getLogger('myapp')
  18. hdlr = logging.FileHandler('/home/pi/myapp.log')
  19. formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
  20. hdlr.setFormatter(formatter)
  21. logger.addHandler(hdlr)
  22. logger.setLevel(logging.WARNING)
  23.  
  24. hdlr1 = logging.FileHandler('/home/pi/myapp1.log')
  25. formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
  26. hdlr.setFormatter(formatter)
  27. logger.addHandler(hdlr)
  28. logger.setLevel(logging.ERROR)
  29.  
  30. from email.MIMEMultipart import MIMEMultipart
  31. from email.MIMEBase import MIMEBase
  32. from email.MIMEText import MIMEText
  33. from email import Encoders
  34. gmail_user = "[email protected]" #Sender email address
  35. gmail_pwd = "raspberryPi" #Sender email password
  36. to = "[email protected]" #Receiver email address
  37. subject = "Security Breach"
  38. text = "There is some activity in your home. See the attached picture."
  39.  
  40.  
  41. # GPIO pin for the PIR sensor
  42. PIR_GPIO_PIN = 4
  43.  
  44. # camera mode
  45. PHOTO = "Photos"
  46. VIDEO = "Videos"
  47.  
  48. # location on raspberry pi to store photos and videos
  49. #LOCAL_DIRECTORY = "/home/pi/python_programs/camera_output/"
  50. #adding Ram Disk : sudo nano /etc/fstab
  51. # add this to  fstab: tmpfs /mnt/rd tmpfs rw,mode=1777,size=4g
  52. # Testing RAM disk
  53. LOCAL_DIRECTORY = "/mnt/rd/"
  54.  
  55. # location of the program used to upload files to dropbox
  56. DROPBOX_COMMAND = "/home/pi/Dropbox-Uploader/dropbox_uploader.sh"
  57.  
  58. # video recording time in seconds
  59. RECORDING_TIME = 15
  60.  
  61. # time to wait after taking photo or video in seconds
  62. WAIT_TIME = 15 #time in seconds
  63.  
  64. # generate a file name based on the local date and time
  65. # year-month-day-hour-minutes-seconds-timezone
  66. def generate_file_name():
  67.     return time.strftime("%Y-%m-%d-%H-%M-%S-%Z", time.localtime())     # e.g., 2014-09-14-15-23-45-PST
  68.  
  69. def wait_for_internet_connection():
  70.     while True:
  71.         try:
  72.             print "Testing for active internet connection...then continue "
  73.             response = urllib2.urlopen('http://google.com',timeout=1)
  74.             return
  75.             # returns control to the next step in the program
  76.         except urllib2.URLError:
  77.             #pass
  78.             continue
  79.             # will continue to check for connection
  80.  
  81.  
  82. # when motion is detected, take a photo or record a video
  83. # based on what mode was specified by the user
  84. def motion_detected(pir_sensor):       
  85.     fname = LOCAL_DIRECTORY + generate_file_name()
  86.     print "rpi-ms-camera: Motion detected!"
  87.     if camera_mode == PHOTO:
  88.         fname = fname + ".jpg"
  89.         snap_photo(fname)
  90.         wait_for_internet_connection()
  91.         msg = MIMEMultipart()
  92.  
  93.         msg['From'] = gmail_user
  94.         msg['To'] = to
  95.         msg['Subject'] = subject
  96.         msg.attach(MIMEText(text))
  97.         mailServer = smtplib.SMTP("smtp.gmail.com", 587)
  98.         mailServer.ehlo()
  99.         mailServer.starttls()
  100.         mailServer.ehlo()
  101.         mailServer.login(gmail_user, gmail_pwd)
  102.         mailServer.sendmail(gmail_user, to, msg.as_string())
  103.         # Should be mailServer.quit(), but that crashes...
  104.         mailServer.close()
  105.         print "Email Sent"
  106.    
  107.     else:
  108.         fname = fname + ".h264"
  109.         record_video(fname, RECORDING_TIME)
  110.         wait_for_internet_connection()
  111.         msg = MIMEMultipart()
  112.  
  113.         msg['From'] = gmail_user
  114.         msg['To'] = to
  115.         msg['Subject'] = subject
  116.         msg.attach(MIMEText(text))
  117.         mailServer = smtplib.SMTP("smtp.gmail.com", 587)
  118.         mailServer.ehlo()
  119.         mailServer.starttls()
  120.         mailServer.ehlo()
  121.         mailServer.login(gmail_user, gmail_pwd)
  122.         mailServer.sendmail(gmail_user, to, msg.as_string())
  123.         # Should be mailServer.quit(), but that crashes...
  124.         mailServer.close()
  125.         print "Email Sent"
  126.        
  127.     upload_to_dropbox(fname)
  128.     os.remove(fname)
  129.     print "rpi-ms-camera: " + fname + " deleted."
  130.  
  131. # take a photo and store it a file with a unique name
  132. # based on the current date and time   
  133. def snap_photo(file_name):
  134.     #camera.rotation = 180
  135.     camera.resolution = (1024, 768)
  136.     camera.capture(file_name)
  137.     print "rpi-ms-camera: Photo taken."
  138.  
  139. # record video for the specified number of seconds and
  140. # store it in a file with a unique name based on the
  141. # current date and time
  142. def record_video(file_name, rec_time):
  143.     camera.resolution = (650,480)      
  144.     camera.start_recording(file_name)  
  145.     print "rpi-ms-camera: Video recording started."
  146.     camera.wait_recording(rec_time)
  147.     camera.stop_recording()
  148.     print "rpi-ms-camera: Video recording stopped."
  149.  
  150. # upload the file to the specified folder in dropbox
  151. # and delete the file after the upload completes
  152. def upload_to_dropbox(local_file_name):
  153.     dropbox_file_name = os.path.basename(local_file_name)
  154.     print "rpi-ms-camera: Uploading " + dropbox_file_name + " to Dropbox."
  155.     upload_command = DROPBOX_COMMAND + ' upload ' + local_file_name + ' ' + dropbox_file_name
  156.     # print "rpi-ms-camera: " + upload_command   
  157.     subprocess.call([upload_command], shell=True)
  158.  
  159. # create a file with the IP address of the raspberry pi
  160. # and upload it to dropbox so the user can easily get the
  161. # address if ssh is needed to connect to it
  162. def upload_ip_address():
  163.     print "rpi-ms-camera: Uploading IP address to Dropbox."
  164.     ip_file_name = LOCAL_DIRECTORY + "IP-" + generate_file_name() + ".txt"
  165.     ip_command = "hostname -I > " + ip_file_name
  166.     subprocess.call([ip_command], shell=True)
  167.     upload_to_dropbox(ip_file_name)
  168.     os.remove(ip_file_name)
  169.  
  170. # call the dropbox-uploader script for the first time to get it to
  171. # ask the user for the API keys needed to configure the uploader.
  172. # this is used as part of the setup process
  173. def first_time_config():
  174.     subprocess.call([DROPBOX_COMMAND], shell=True)
  175.    
  176. # call the dropbox uploader command to make sure it's working properly
  177. # by uploading a file with the IP address of the Raspberry Pi.
  178. # this is used as part of the setup process
  179. def test_dropbox():
  180.     print "rpi-ms-camera: Testing Dropbox connection."
  181.     upload_ip_address()
  182.     print "rpi-ms-camera: Check your Dropbox app folder for the uploaded file"
  183.    
  184. # Main program
  185.  
  186. # the switch specified on the command determines whether
  187. # a photo or video should be captured and uploaded
  188. # the program can be started one of three ways:
  189. #  
  190. #   'sudo python rpi-ms-camera.py -p'         snaps photos
  191. #   'sudo python rpi-ms-camera.py -v'         capture video
  192. #   'sudo python rpi-ms-camera.py -firsttime' runs first time configuration
  193. #   'sudo python rpi-ms-camera.py -test'      tests to make sure upload is working
  194.  
  195. # determine what command line parameters were specified
  196. if len(sys.argv) > 1:
  197.     if sys.argv[1] == "-p":
  198.         camera_mode = PHOTO
  199.     elif sys.argv[1] == "-v":
  200.         camera_mode = VIDEO
  201.     elif sys.argv[1] == "-firsttime":
  202.         first_time_config()
  203.         sys.exit()
  204.     elif sys.argv[1] == '-test':
  205.         test_dropbox()
  206.         sys.exit()
  207.     else:
  208.         print "Invalid option specified"
  209.         sys.exit()
  210. else:
  211.     print "Valid options are:"
  212.     print "  -p          Snap photos when motion is detected"
  213.     print "  -v          Record video when motion is detected"
  214.     print "  -firsttime  Run to configure the Dropbox application"
  215.     print "  -test       Used to test the connection to Dropbox"
  216.     sys.exit()
  217.  
  218. print "rpi-ms-camera: Raspberry Pi motion sensitive camera started."
  219. print "rpi-ms-camera: " + camera_mode + " will be captured when motion is detected."
  220.  
  221. # setup raspberry pi camera
  222. camera = picamera.PiCamera()
  223. camera.hflip = False
  224. camera.vflip = False  # True
  225.  
  226. # setup GPIO pin for the PIR (motion) sensor
  227. GPIO.setmode(GPIO.BCM)
  228. GPIO.setup(PIR_GPIO_PIN, GPIO.IN)
  229.  
  230. # test for active internet connection to server first!
  231. wait_for_internet_connection()
  232.  
  233. # upload the IP address of the Raspberry Pi to Dropbox so the
  234. # user can use "ssh" to connect to it if needed    
  235. upload_ip_address()
  236.  
  237. # main loop to detect motion and snap pictures or record videos
  238. while True:
  239.     try:
  240.         print "rpi-ms-camera: Waiting for motion."
  241.         GPIO.wait_for_edge(PIR_GPIO_PIN, GPIO.RISING)
  242.         motion_detected(PIR_GPIO_PIN)
  243.         print "rpi-ms-camera: Sleeping for " + str(WAIT_TIME) + " seconds."
  244.         time.sleep(WAIT_TIME)
  245.     except:
  246.         print "rpi-ms-camera: Stopping due to keyboard interrupt."
  247.         camera.close()
  248.         GPIO.cleanup()
  249.         break
Advertisement
Add Comment
Please, Sign In to add comment