Sunday, February 15, 2009

perl script for webcam

Following is a perl script that I wrote to take and upload snapshots from webcam.
Use crontab to execute this script hourly.

streamer is from a cool package xawtv.


=========================================

#!/usr/bin/perl -w
#Capture imgs from webcam and upload it to ftp
#Author: Chenyang
#Email: higooday at gmail.com
#
#bug:somehow,the first img taken by streamer is never complete.
#So I only upload from the second one.
#If you know how to solve it, please teach me.
#
use strict;
use Net::FTP;

my $user="xxxx"; ##user name for ftp
my $pass="xxxx"; ##passwd for ftp
my $host="www"; ##ftp site
my $ftp_dir="xxx"; ##directory at ftp site for picture uploading
my $shot=6; ##number of shots taken
my $interval=1; ##number of shots in one second
my $file_prefix=hour();
my $file_name=$file_prefix."_0.jpeg";
my $working_dir="/home/yourname/xxxx";
chdir $working_dir; # change working directory, important if executed by crontab

system ("streamer -t $shot -r $interval -o $file_name");
ftp ("put",$file_prefix,$shot,$user,$pass,$host,$ftp_dir);


######################
sub ftp {
my ($method, $file_prefix,$shot,$user,$pass,$host,$ftp_dir) = @_;

my $ftp = Net::FTP->new($host, Debug => 0);
$ftp->login($user, $pass) or die "ERROR - FTP login failed: ", $ftp->message;
$ftp->binary; #switch to binary transfer mode
$ftp->cwd($ftp_dir);
if ($method eq "put") {
for (my $i=1;$i<6;$i++)
{
my $file_name=$file_prefix."_".$i.".jpeg";
$ftp->put($file_name) or die "ERROR - FTP put failed: ", $ftp->message;
}
}
elsif ($method eq "get") {
$ftp->get($file_name) or die "ERROR - FTP get failed: ", $ftp->message;
}

$ftp->quit;
}

sub hour {
my ($sec, $min, $hour, $day, $month, $year) = (localtime)[0, 1, 2, 3, 4, 5];
my $time = $hour;
return $hour;
}

No comments:

Post a Comment