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.

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

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 ="%H:%M %d-%m-%Y")
print now
with open("timedate.txt", "w") as f:

# Take the picture 
time.sleep(2) # Camera warm up time

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

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

No comments: