Wednesday, November 16, 2005

Camstreams and lftp

Quick shot of me from the IBM web cam
In my last post I alluded to a web-cam project I was working on. I had hoped the software I was using for Linux, Camstream, was capable of uploading to me site, and there appeared to be facilities to do so - the only problem was that all the images it uploaded had a zero-byte size; in other words the upload didn't work properly. Luckily, Camstream did save the image perfectly to the hard drive, which meant I could use a little scripting to auto upload it to my web site.

I'm no hard core shell script hacker, this is just my solution to a problem; I'm sure there are plenty of better solutions, but this one works for me, so I thought I would share:

First I needed to find a ftp program that I could script. I chose lftp because it seemed like the easiest program to script, you just run lftp with the -f switch and the name of your script. For example, if your script is called uploadimage you'd get cron to run:

/usr/bin/lftp -f /home/username/uploadimage

Where /home/username is the path to where you put your script. The second job was to write a script that would upload the image. This was actually just a few lines of script:


open -u myusername,mypassword my.ftp.server.address
rm /img/videocamera.jpg
put -c -O /img /home/myusername/videocamera.jpg
quit


It's a very simple script. The first line connects to the ftp server at my.ftp.server.address. Line 2 removes the existing image. Line 3 puts the new image with a switch to overwrite the old image if it exists. And the last line ensures lftp quits.

I tested the script before putting it in a cron job by typing:

lftp -f /home/myusername/uploadimage

When it worked I put the script into a cron job:

0,5,10,15,20,25,30,35,40,45,50,55 * * * * /usr/bin/lftp -f /home/myusername/uploadimage

The 0,5,10,15... part ensures the cron job runs every 5 minutes. The other four stars ensures the job runs every day of the week. Now, I probably should have mentioned how to edit a cron job in the last post, and before I posted the line above, but it's been a long day and I'm still trying to wind down, so here it is: as root type:

crontab -u myusername -e

Substitute the user name you use on your local Linux system, not the username you would use on your ftp site.

The last element was creating a simple html page to display the image videocamera.jpg. I won't explain the mechanics of HTML here, but I'll mention that I borrowed some javascript code, and hacked it to refresh the web page itself about every 3 minutes.

Resources:


Please note that if the camera feed is black it's probably dark out, or I'm chilling watching a movie. I still have a way to go with this project and will probably run the images through imagemagick, but that's another post...