#!/usr/bin/perl
#$Id: potentiostat.pl,v 1.4 2012/03/27 11:33:13 sofc Exp $
use Fcntl qw/:DEFAULT :flock/;
use strict;
use warnings;
use RFC::Rig;
use RFC::Main;
use RFC::Header;

if (scalar(@ARGV) < 2)
{
    print "Usage: potentiostat \$rig \$voltage [opt \$range, opt \$istep, opt PSU_name]\n";
    print "If the range is not specified a voltage range of 20 mV is used.\n";
    print "If the currentstep is not specified 0.1 A is used.\n";
    exit;
}
my $rig = RFC::Rig->new(shift);
$rig->check_run;

##### Exit if a i-v curve is running! ###
exit if  ($rig->is_iv);

### Get config values ####
my $setpoint = shift;
$setpoint =~ /([\d\.\-]+)/;
$setpoint = $1+0;

my $vrange = 10;
if (@ARGV)
{
    $vrange = shift;
}
$vrange =~ /([\d\.]+)/;
$vrange = $1+0;
my $istep = 0.1;
if (@ARGV)
{
    $istep = shift;
}
$istep =~ /([\d\.]+)/;
$istep = $1+0;
if ($istep < 0.025)
{
    die "Too low current step attempted!\n";
}
if ($vrange < 2)
{
    die "Too low voltage range attempted!\n";
}
my $psuname = undef;
if (@ARGV)
{
    $psuname = shift;
}
###########   Get initial cell voltage and current #####
my $volt = 0;
my $cold = 0;
my $dump = &get_current();
for (my $x = 0; $x < 3; $x++)
{
    $cold += &get_current();
}
$dump = &get_voltage();
for (my $x = 0; $x < 3; $x++)
{
    $volt += &get_voltage();
}
$volt = $volt / 3;
$cold = $cold / 3;
#$istep = -$istep if ($cold < -0.1); ### Fixes electrolyser mode ###
exit if (abs($cold) < 0.1);  ## Exit if current is below 100 mA (likly ocv condition)
my $cn = 'ocv';
my $do = 0;
if ($volt > ($setpoint + $vrange))
{
    $cn = $cold + $istep;
    $do = 1;
} 
if ($volt < ($setpoint - $vrange))
{
    $cn = $cold - $istep;
    $do = 1;
} 
if ($do)
{
    my $cn = sprintf("%.3f",$cn);
    $cn = 'ocv' if (abs($cn) < 0.1);
    if ($psuname)
    {
	$rig->current($cn,$psuname,$0);
    }
    else
    {
	my @psus = $rig->list_devices_control('PSU');
	$rig->current($cn,$psus[0],$0);
    }
}
$rig=undef;

exit;

sub get_voltage()
{
    my $volt_name =  $rig->get_cv('IV_control','voltage_label');
    $volt_name = 'cell_voltage' unless ($volt_name);
    my $dev = $rig->get_device('simplechannel',$volt_name);
    return $dev->read;
}

sub get_current()
{
    my $curr_name =  $rig->get_cv('IV_control','current_label');
    $curr_name = 'current' unless ($curr_name);
    my $dev = $rig->get_device('simplechannel',$curr_name);
    return $dev->read;
}

