#!/usr/bin/env perl
#
# take_picture - Takes a picture from one of a number of connected
#                cameras.  Code identifies where on the USB
#                bus the camera is before taking the photo.
#
#                This has been tested with a the following
#                binary versions of gphoto2 (raspbian):
#                - 2.4.14
#                - 2.5.4
#
#                and the following versions compiled from
#                source:
#                 - 2.5.6
#
#                Version History:
#
#                1.0 - 2014/10/24 - awr - Initial Release
#                1.1 - 2015/10/13 - awr - Camera definition required 

use strict;
use warnings;

my ($cam_name, $filename) = @ARGV;

# These are the cameras we have - add more to the list.  You can 
# determine the serial number by using a combinaton of:
#    gphoto2 --auto-detect
#    gphoto2 --get-config /main/status/serialnumber
#
my %camera_serial = ("00000000000000000000000006073055", "top",
                     "00000000000000000000000006092844", "left",
                     "00000000000000000000000006033842", "side");

# We need to find the cameras when we detect what is attached, the
# string below should be set to match your output - i.e investigate
# what is attached when this is matched.  In this case we are looking
# for all of the Nikon cameras attached, you mat find that searching 
# for "USB PTP Class Camera" might be valid for some binary
# builds of gphoto2.
my $defines_a_camera = "Nikon DSC D3300";


my %cameras;

# Now we attempt to work out which camera is on which port
my $cmd = "gphoto2 --auto-detect";    
my @output = `$cmd`;    
chomp @output;

foreach my $line (@output)
{

	if ($line =~ /$defines_a_camera/) {
		my @ports = split(/:/, $line);
		my $usb_port = "usb:" . $ports[1];
		$usb_port =~ s/\s+$//;

		my $get_serial = "gphoto2  --port $usb_port  --get-config /main/status/serialnumber";
		my @serial_output = `$get_serial`;

		# We assume it comes back on the third line ...
		my @serial_line = split(/:/, $serial_output[2]);	
		my $serial_number = $serial_line[1];
		$serial_number =~ s/^\s+|\s+$//g;

		print "Have found: $serial_number connected to $usb_port allocated to " . $camera_serial{$serial_number} . "\n";
		my $camera_name = $camera_serial{$serial_number};

		$cameras{"$camera_name"} = $usb_port;
		

	}	
}

my $capture_cmd = "gphoto2 --port " . $cameras{$cam_name} . " --capture-image-and-download  --force-overwrite  --filename=" . $filename;

my @camera_cmd_output = `$capture_cmd`;
