#!/usr/bin/perl
#$Id: UIdata.cgi,v 1.17 2020/10/05 07:01:23 sqko Exp $
use strict;
use warnings;
use RFC::Rig;
use RFC::Main;
use RFC::RFCCGI qw(:cgi :html);
use CGI qw(:standard :netscape);
use Fcntl qw(:DEFAULT :flock);

my $maxdelay = get_cv('main','maximum_time_delay_for_current_values');
$maxdelay = 60 unless $maxdelay;

print header();
my $rig = RFC::Rig->new(param('rig'));
my %setup = ();

### Aquire lock to make suer no other data logging is running ###
my $lockfile = '/tmp/rig_'.$rig->name.'_logfile.lock';
unless (-e $lockfile)
{
    sysopen(FH, $lockfile, O_WRONLY | O_CREAT) or CORE::die "Error: Could not open $lockfile $!";
    chmod 0666, $lockfile;
}
else
{
    sysopen(FH, $lockfile, O_WRONLY | O_CREAT) or CORE::die "Error: Could not open $lockfile $!";
}
flock(FH,LOCK_EX);
### Only use lock to wait for logfile.pl, do not delay unlocking as lockfile.pl may be prevented from starting!
flock(FH,LOCK_UN);
close(FH);

foreach my $name ($rig->get_cv('userinterface','temp'))
{
    my $dev;
    eval {
	$dev = $rig->init_device('templog',$name);
	# Ignore error as we tryu a tempcotnrol device if no templog device #
    };
    $dev = $rig->init_device('tempcontrol',$name) unless ($dev);
    $setup{'temp'}{$name} = $dev if ($dev);
}

foreach my $name ($rig->get_cv('userinterface','gas'))
{		
    my $dev = $rig->init_device('gas',$name);
    $setup{'gas'}{$name} = $dev if ($dev);
}	

foreach my $name ($rig->get_cv('userinterface','voltage'))
{		
    my $dev = $rig->init_device('simplechannel',$name);
    $setup{'voltage'}{$name} = $dev if ($dev);
}	

foreach my $name ($rig->get_cv('userinterface','current'))
{		
    my $dev = $rig->init_device('simplechannel',$name);
    $setup{'current'}{$name} = $dev if ($dev);
}

foreach my $name ($rig->get_cv('userinterface','alert'))
{		
    my $dev = $rig->init_device('Alert',$name);
    $setup{'alert'}{$name} = $dev if ($dev);
}


my $data = RFC::Cache->new();

foreach my $type (keys %setup)
{
    foreach my $name (keys %{$setup{$type}})
    {
	my $dev = $setup{$type}{$name};
	my $val = $dev->read_cache($maxdelay,$data);
	if (ref($dev) =~/TempControl/)
	{
	    eval {
		$val = $dev->get_atemp();
	    };
	}
	next unless defined($val);
	$val = $val/1000 if ($type eq 'voltage');
	if (ref($dev) =~ /Alert|Trigger/)
	{
	    if ($dev->has_triggered)
	    {
		$val = $val .= ' - Triggered!';
	    }
	    else
	    {
		$val = $val .= ' - Reset';
	    }
	    print $name,"\t",$val,"\n";
	}
	else
	{
	    printf("%s\t%.4g\n",$name,$val);
	}
    }
}

$rig = undef;
