#!/usr/bin/perl -T
#$Id: Adapter_update.pl,v 1.1 2016/06/13 07:02:45 sqko Exp $
use strict;
use warnings;
use RFC::Rig;
use RFC::Visitor;
my $v = RFC::DisableProglogVisitor->new();
use Fcntl qw(:DEFAULT :flock);
die "No rig specified!\n" unless (@ARGV);
my $r = shift;
if ($r && $r =~ /(\d+)/)
{
    $r = $1;
}
else
{
    die "'$r' is not a valid rig name!\n";
    exit;
}
my $lock = '/home/rig'.$r.'/Adapter_control.lock';
sysopen(MFH, $lock, O_WRONLY | O_CREAT) or CORE::die "Error: Could not open $lock $!";
sleep(10) unless (@ARGV);
&main();
sleep(1);
exit;

sub main
{
    my $res = flock(MFH,LOCK_EX | LOCK_NB);
    return unless ($res);
    my $rig = RFC::Rig->new($r);
    $rig->check_run;
    $rig->Accept($v);
    my $modtime = time + 600;
    my @devices = $rig->list_devices('Adapter');
    while (1)
    {	
	last unless (@devices);
	if (time > $modtime)
	{
	    $rig = undef;
	    select(undef,undef,undef,0.5);
	    $rig = RFC::Rig->new($r);
	    $rig->Accept($v);
	    $modtime = time + 600;
	    @devices = $rig->list_devices('Adapter');
	}
	foreach my $name (@devices)
	{
	    my $d = $rig->get_device('Adapter',$name);
	    next unless ($d);
	    $d->update($0); ## Do calculation and control ##
	}
	sleep(5);
    }
    $rig->DESTROY();
    return;
}

