Saturday, October 29, 2016

So much for error handling!

No matter how clever my error handling code was, in the program I wrote for my webcam, the Python 2.7 FTP library kept finding new ways to fall over, hang, or generally run round like a headless chicken.

I can't use Python 3.x as the picamera library only works with 2.7 at the moment. In the end, I decided not to bother with error handling at all. I wrote a bash script that calls a Python script, which takes and uploads one photograph. After a decent interval, it kills the Python script, if it is still running, waits a bit more, and loops round to take another picture.

#!/bin/bash
while true
do
# Take a picture
python oneshot.py &
# Wait 3 minutes
sleep 3m
# If oneshot.py is still running, murder it quietly
ps -ef | awk '/python oneshot.py/ && !/awk/ {print $2}' | xargs -r kill -9 > /dev/null
# Wait 6 minutes
sleep 6m
done

The webcam software now becomes very simple:-

# Imports
import io
import os
import schedule
import time
import datetime
import picamera
import ftplib

# Camera setup stuff
camera = picamera.PiCamera()
width = 2592 # As wide as the camera will go
height = 1000 # Max is 1944
camera.resolution = (width, height)

# Put the time and date in a text file
now = datetime.datetime.now().strftime("%H:%M %d-%m-%Y")
print now
with open("timedate.txt", "w") as f:
    f.write(now)

# Take the picture 
time.sleep(2) # Camera warm up time
camera.capture("view.jpg")

# Upload the picture
ftp = ftplib.FTP()
ftp.connect("ftp.YOUR-SITE", 21)
ftp.login("YOUR-LOGIN", "YOUR-PASSWORD")
ftp.storlines("STOR timedate.txt", open("timedate.txt"))
ftp.storbinary("STOR view.jpg", open("view.jpg", "rb"))
ftp.quit()

print ("Time, date and picture sent.")
print

No comments: