#!/usr/bin/perl

use lib 'd:/Programs/Perl/lib';
use lib 'd:/Programs/Perl/lib2.0';
use lib '.';

use strict;

use MyApplication2;
use Device::Device;
use Device::Cornerstone130;
use Device::Keithley6517A;
use Device::Keithley2000;


$SIG{INT} = \&ctrl_c_handler;
BEGIN {
#	$| = 1;
	open (STDERR, ">&STDOUT");
}

#===============================================
# 測定関係変数
#===============================================
#データファイルの名前
my $DataFileName = "CPM12.csv";

#測定前のWait
my $WaitBefore = 1.0;
my $WaitForMeasurement = 3.0;

# 測定電圧範囲
my $VStart =  0.0;
my $VEnd   =  20.0;
my $VStep  =  0.5;


#Keuthley6517Aゼロチェック
my $ZeroCheck = 'on';

# 平均を取る回数
my $nAverage = 10;


my $Who = 'Tsukamoto';
my $Today = Utils::BuildDateString(time());


#===============================================
# Applicationオブジェクト作成
#===============================================
my $App = new MyApplication2;
$App->SetOutputMode("auto");
my $ProgramPath = $App->SpeculateProgramPath($0, "");
my $IniFile = $App->OpenIniFile($ProgramPath, 1);
$App->AddIniFileVariable("\\Preferences\\DeviceName", "DeviceName", "Keithley2000");
$App->AddIniFileVariable("\\Preferences\\Port",       "Port",       "GPIB17");
$App->ReadSetting();


#===============================================
# Deviceオブジェクト作成
#===============================================
my $K6517A         = OpenDevice("Keithley6517A",  "GPIB27");
#my $K2000          = OpenDevice("Keithley2000" ,  "GPIB17");
my $Cornerstone130 = OpenDevice("Cornerstone130", "COM1");

#Keithley6517Aの初期化
$K6517A->Initialize();
$K6517A->SetDCCurrentMode($ZeroCheck);
$K6517A->SetDCCurrentMode("on");
$K6517A->SetAutoRangeForCurrent("on");

#Keithley2000の初期化
#$K2000->Initialize();
#$K2000->SetDCVoltsMode();
#$K2000->SetAutoRangeForVoltage("on");

#Cornerstone130の設定
$Cornerstone130->GOWAVE(500);



#===============================================
# 測定開始
#===============================================
my $nVStep = int( ($VEnd - $VStart) / $VStep + 1.000000001 );

Utils::sleep($WaitBefore);

$K6517A->SetSourceVoltage($VStart);
$K6517A->SetVSourceOutput("on");
$Cornerstone130->Shutter("0");      #シャッター開


#回折格子の波長が設定されたら、人間がENTERキーを押して次の作業に進む
print "\nPress ENTER if ready>";
<>;


#ファイル書込み
if(-w $DataFileName) { print "Can write to [$DataFileName]\n"; }
my $out = new JFile;
if(!$out->Open($DataFileName, "w")) {
	print "Error: Can not write to [$DataFileName]\n";
	exit;
}


#Excel用にデータを書き出す
$out->print("V,I,**********Measured by $Who, $Today,\n");
for(my $i = 0 ; $i < $nVStep ; $i++) {
	my $V = $VStart + $VStep * $i;

	$K6517A->SetSourceVoltage($V);
	Utils::sleep($WaitForMeasurement);
	print("Waiting $WaitForMeasurement s...\n");

	my $I = $K6517A->MeasureAveraged($nAverage);
	print("V=$V    I=$I\n");
	$out->print("$V,$I\n");
}

$out->Close();

#Cornerstone130シャッター閉じる
$Cornerstone130->Shutter("1");


exit;



#============================================================
#　一般関数
#============================================================
sub ctrl_c_handler{
	$App->print("CTRL+C pressed\n");
	$App->print("Input 'yes' if terminate this program.\n>>");
	my $line = <>;
	if($line =~ /^\s*yes\s*$/i) {
	   exit;
	}
	return;
}

sub OpenDevice
{
	my ($DeviceName, $Port) = @_;
	Utils::DelSpace($DeviceName);
	Utils::DelSpace($Port);

#RS232Cの設定
my $ConfFile        = '';
my $COMPort         = 'COM1';
my $UseModule       = 0;
my $BaudRate        = 9600;
my $Parity          = 'none';
my $DataBits        = 8;
my $StopBits        = 1;
my $HandShake       = 'none';
my $WriteBufferSize = 1024 * 20;
my $ReadBufferSize  = 1024 * 4;
my $ReadInterval    = 800;
my $ReadCharTime    = 400;
my $ErrorMessage    = 1;
my $UserMessage     = 1;

#GPIBの設定
my $GPIBInterface   = "ni";
my $GPIBTimeOut     = GPIB->T1s;
my $GPIBEOT         = 1;
my $GPIBEOS         = 0;

	my $dev = new Device(
			-Port               => $Port,
			-ModuleName         => $DeviceName,
			-DeviceName         => $DeviceName,
			-GPIBInterface      => $GPIBInterface,
			-GPIBTimeOut        => $GPIBTimeOut,
			-GPIBEOT            => $GPIBEOT,
			-GPIBEOS            => $GPIBEOS,
			-COMConfName        => $ConfFile,
			-COMBaudRate        => $BaudRate,
			-COMParity          => $Parity,
			-COMDataBits        => $DataBits,
			-COMStopBits        => $StopBits,
			-COMHandShake       => $HandShake,
			-COMWriteBufferSize => $WriteBufferSize,
			-COMReadBufferSize  => $ReadBufferSize,
			-COMReadInterval    => $ReadInterval,
			-COMReadCharTime    => $ReadCharTime,
			-COMErrorMessage    => $ErrorMessage,
			-COMUserMessage     => $UserMessage,
			-PrintError         => 1,
			);
	if(!defined $dev) {
		$App->print("Device can not be opened. [$DeviceName: $Port]\n");
		exit;
	}

	my $Id = $dev->GetId();
	$App->print("$DeviceName: [$dev->{ModuleName}:$dev->{Port}] (Object: $dev)\n");
	$App->print("Id: $Id\n");

	return $dev;
}
