// DDC control 
//123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456*/
//===================================-======================================*/
//                         DDC STATE & DATA CONTROL                         */
//-----------------------------------=--------------------------------------*/
// AUTHORs:        P.Ferrari & Heidi Sandaker
//
//   DESIGN ISSUEs:  Run state transitions
//
//   MODIF_HISTORY:  25.07.2003 - first version
//                   30.07.3003 - Preliminary - H. Sandaker
//                   01.08.2003 - startup of IV curve implemented- P.Ferrari
//===================================-======================================*/

main()
{ 
//DebugN("Started main");
DebugN("========================================1");
dpConnect("RunIV","IVcurve.trigger:_original.._value");
DebugN("========================================5");
}

void RunIV(string Text, bool Flag) 
{
int iState;
string sParameter;
int channel,start,stop,step,end,Imax,Iwarn,Twait;
string status, channelAddress;
DebugN("========================================2");


if (Flag==1){
   DebugN("IVcurve trigger", Flag);
   
	//Get Values from DAQ
	dpGet("IVcurve.parameters:_original.._value", sParameter);
	DebugN("===================== sParameter = ", sParameter);
	
   //Split string and get IV parameters:
   //String on form: channel | start | stop | step | end | Imax | Iwarn | Twait  
   sscanf(sParameter,"%d|%d|%d|%d|%d|%d|%d|%d", channel,start,stop,step,end,Imax,Iwarn,Twait );
   DebugN("sParameters", channel,start,stop,step,end,Imax,Iwarn,Twait);

DebugN("========================================3");
   sprintf(channelAddress, "Crate00.Channel%02d", channel);
   

	DebugN("======================== channelAddress = ", channelAddress);


   dpSet(channelAddress+".IVCurve.HV_Start.Send:_original.._value",start);
   dpSet(channelAddress+".IVCurve.HV_Stop.Send:_original.._value",stop);
   dpSet(channelAddress+".IVCurve.HV_Step.Send:_original.._value",step);
   dpSet(channelAddress+".IVCurve.HV_End.Send:_original.._value",end);
   dpSet(channelAddress+".IVCurve.Curr_Max.Send:_original.._value",Imax);
   dpSet(channelAddress+".IVCurve.Curr_Warn.Send:_original.._value",Iwarn);
   dpSet(channelAddress+".IVCurve.TimeWait.Send:_original.._value",Twait);
   
   //set HV channel (+100) on which IV curve should run
   DebugN("Channel",channel);
   dpSet("Crate00.Controller.CCchRead.Send:_original.._value",channel+100);  
 
   // set datapoint to trigger IV Curve

   dpSet("Crate00.Controller.StartIVCurve.Send:_original.._value",1);

   dpSet("Info.Name:_original.._value", "IV scan has started!");

   //set DAQ trigger to FALSE again
   dpSet("IVcurve.response:_original.._value",0);
   dpSet("IVcurve.trigger:_original.._value",0);

   // set back the IV trigger in the ELMB to 0
    dpSet("Crate00.Controller.StartIVCurve.Send:_original.._value",0);
   //get status
     sprintf(status,"SCTmops1:Crate00.Channel%02d.IVCurve.Status.Recv:_original.._value",channel);	
      //DebugN(" IV curve dpconnect",status);
      dpConnect("EP_textFieldInCB1",status);
   }
DebugN("========================================4");
}


EP_textFieldInCB1(string dp,int iNewValue)
{
int channel,start,stop,step,last;
file f;
string sParameter, filename, status,volt,curr;
float Ileak150, Ileak350, Ileak500,V, I;
Ileak150 = Ileak350 = Ileak500 = -1;

	dpGet("IVcurve.parameters:_original.._value", sParameter);
	sscanf(sParameter,"%d|%d|%d|%d|*", channel, start, stop, step );
	sprintf(status,"SCTmops1:Crate00.Channel%02d.IVCurve.Status.Recv:_original.._value",channel);	
	
	last = (stop - start) / step;

	DebugN("===========1 IV curve status!!", iNewValue);
	if(iNewValue==255){
	// the IV curve is started
	dpSet("SCTmops1:Info.Name:_original.._value","IV curve is started");
	//DebugN(" IV curve started!!", iNewValue);
	}
	if(iNewValue==251){
	dpSet("SCTmops1:Info.Name:_original.._value","IV curve is stopped");
	//DebugN(" IV curve stopped!!", iNewValue);
	}
	if((iNewValue>0)&&(iNewValue<=150)){
	// the IV curve is running
	dpSet("SCTmops1:Info.Name:_original.._value","IV curve is running");

	sprintf( volt , "SCTmops1:Crate00.Channel%02d.HVchVolt.Recv:_online.._value", channel);
	sprintf( curr , "SCTmops1:Crate00.Channel%02d.HVchCurr.Recv:_online.._value", channel);
	dpGet( volt, V );
	dpGet( curr, I );
	DebugN(" IV curve running!!", iNewValue,"Volt",V,"Curr",I);
	if( iNewValue == 1) openRaw(channel, filename);
	writeRaw(iNewValue, channel);
	if (iNewValue == last) 	{
	Upload(channel, filename, Ileak150, Ileak350, Ileak500);
	closeRaw();
    dpDisconnect("EP_textFieldInCB1",status);
    }
	}
	if((iNewValue==0)){
	// normal readout
	dpSet("SCTmops1:Info.Name:_original.._value","Normal readout");
	//DebugN(" Normal readout!!", iNewValue);
}

}

/* //Set Datapoints
   sprintf(dp1, "IVchannel%d.Start:_original.._value",channel);
   sprintf(dp2, "IVchannel%d.Stop:_original.._value",channel);
   sprintf(dp3, "IVchannel%d.Step:_original.._value",channel);
   sprintf(dp4, "IVchannel%d.End:_original.._value",channel);
   sprintf(dp5, "IVchannel%d.Imax:_original.._value",channel);
   sprintf(dp6, "IVchannel%d.Iwarn:_original.._value",channel);
   sprintf(dp7, "IVchannel%d.Twait:_original.._value",channel);


   dpSet(dp1,start);
   dpSet(dp2,stop);
   dpSet(dp3,step);
   dpSet(dp4,end);
   dpSet(dp5,Imax);
   dpSet(dp6,Iwarn);
   dpSet(dp7,Twait);
*/

// Open and Inizialize Raw Data File --------------------------------------------------------*
openRaw( int channel, string& filename)
{
int err; // error code
string date, path, sn, temp;
time time1;
float T;
file f;

/* set file name */
	time1 = getCurrentTime();
	date = formatTime("%Y%m%d_%H%M%S", time1);
	path = "D:/IVcurve/";
	sprintf(sn, "CHAN%02d", channel);
	filename = path + sn + "_iv_" + date + ".txt";
	dpSet("SCTmops1:IVfile.Name:_original.._value", filename);
	DebugN("==========1===filename in open", filename);

/* open file*/
	f = fopen(filename,"a"); // open for append
	err = ferror(f); // export error

/* header */
	date = formatTime("%d/%m/%Y", time1);
	fputs("TEST_DATE\t: " + date, f);
	date = formatTime("%H:%M:%S", time1);
	fputs("\nTEST_TIME\t: " + date, f);

/* temperature */
	sprintf(temp, "SCTmops1:Crate00.Channel%02d.MOch_Tm0.Recv:_online.._value", channel);
	dpGet( temp, T);
	fprintf(f, "\nTEMPERATURE\t: %f ", T);

	fputs("\n#\n#V\tI\n", f);
	
	DebugN("Open file ", filename);
	if (err!=0) DebugN("Error no. ",err," occurred");
	fclose(f); // close file
}

// Write Raw Data File ----------------------------------------------------------------------*
writeRaw(int status, int channel, string filename)
{
string volt, curr;
float temp, V, I;
int err; // error code
file f;

	if (status = 0) return;
	dpGet("SCTmops1:IVfile.Name:_online.._value", filename);	
	f = fopen(filename,"a"); // open for append
    //DebugN(" *****%%%% file name", filename);
	err = ferror(f); // export error
	
	sprintf( volt , "SCTmops1:Crate00.Channel%02d.HVchVolt.Recv:_online.._value", channel);
	sprintf( curr , "SCTmops1:Crate00.Channel%02d.HVchCurr.Recv:_online.._value", channel);
	dpGet( volt, V );
	dpGet( curr, I );
	fprintf(f, "%f\t%f\n", V, I);
	DebugN("Write file", "Volt= ",V, " Icurr",I);
	if (err!=0) DebugN("Error no. ",err," occurred");
	fclose(f); // close file
}

// Close Raw Data File -----------------------------------------------------------------------*
closeRaw(string filename)
{
int err; // error code
file f;

	dpGet("SCTmops1:IVfile.Name:_online.._value", filename);
	f = fopen(filename,"a"); // open for append
	err = ferror(f); // export error
	fputs("#V\tmicroA\n#\n", f);
	fclose(f); // close file
	DebugN("Close file");
	if (err!=0) DebugN("Error no. ",err," occurred");
	fclose(f); // close file

}

// Write the Upload file ---------------------------------------------------------------------*
Upload( int channel, string raw, float Ileak150, float Ileak350, float Ileak500 )
{
int err; // error code
string date, filename, path, sn, dr, loc, run, dut;
string passed, problem, host, version, def, raw;
file f;
time time1;
string curr, max, warn, temp0, temp1, curr_det , volt_det, curr_cc , volt_cc, curr_dd , volt_dd;
float Icurr, Imax, Iwarn, Itrip, T0, T1, Vdet, Idet, Vcc, Icc, Vdd, Idd;


DebugN("write upload file");
/* hardcode values ********************************/
	path = "D:/IVcurve/";
	sprintf(sn, "CHAN%02d", channel); // SERIAL NUMBER
	dr = "sct_dcs";			// TEST MADE BY
	loc = "Oxford";			// LOCATION NAME
	run = 111;				// Run Number
	host = "PCEF";			// DAQ_INFO
	version = "7.0";		// DAQ_INFO
	dut = "Barrel_Module";	// DAQ_INFO
	def = "No";				// DetModIV defects

// set file name ***********************************/
	time1 = getCurrentTime();
	date = formatTime("%Y%m%d", time1);
	filename = path + sn + "_" + date + ".txt";

/* open file  ***********************************/
	f = fopen(filename,"a"); // open for append
	err = ferror(f); // export error
	if (err!=0) DebugN("Error no. ",err," occurred");

// header -------------------------------------
	fputs("#\n%NewTest\n#", f);
	fputs("\nSERIAL NUMBER\t: " + sn, f);	// SERIAL NUMBER
	fputs("\nTEST MADE BY\t: " + dr, f);	// TEST MADE BY
	fputs("\nLOCATION NAME\t: " + loc, f);	// LOCATION NAME
	fputs("\nRun Number\t: " + run, f);		// Run Number
	date = formatTime("%d/%m/%Y", time1);
	fputs("\nTEST_DATE\t: " + date, f);		// TEST_DATE

/*  PASSED & PROBLEM ********************************/
	sprintf(curr, "SCTmops1:Crate00.Channel00.HVchCurr.Recv:_online.._value", channel);
	sprintf(warn, "SCTmops1:Crate00.Channel00.IVCurve.Curr_Warn.Send:_online.._value", channel);
	sprintf(max, "SCTmops1:Crate00.Channel00.IVCurve.Curr_Max.Send:_online.._value", channel);
	dpGet(curr, Icurr);
	dpGet(warn, Iwarn);
	dpGet(max, Imax);

	if (Icurr < Imax) passed ="YES";
	else passed = "NO";
	if (Icurr < Iwarn) problem = "NO";
	else problem = "YES";

	fputs("\nPASSED\t\t: " + passed, f);
	fputs("\nPROBLEM\t\t: " + problem, f);

/* DAQ_INFO ******************************************/
	fputs("\n#\n%DAQ_INFO\n#\n#HOST\n\"" + host + "\"", f);	// HOST
	fputs("\n#VERSION\n\"" + version + "\"", f);			// VERSION
	fputs("\n#DUT\n\"" + dut + "\"", f);					// DUT
	date = formatTime("%H:%M:%S", time1);
	fputs("\n#TIME\n\"" + date + "\"", f);					// TIME

/* DCS_INFO ******************************************/
	fputs("\n#\n%DCS_INFO\n#\n#T0\tT1\n", f);

// T0 & T1
	sprintf(temp0, "SCTmops1:Crate00.Channel%02d.MOch_Tm0.Recv:_online.._value", channel);
	sprintf(temp1, "SCTmops1:Crate00.Channel%02d.MOch_Tm1.Recv:_online.._value", channel);
	dpGet( temp0, T0);
	dpGet( temp1, T1);
	fprintf(f, "%f\t%f ", T0, T1);

// VDET & IDET
	fputs("\n#VDET\tIDET\n", f);
	sprintf(curr_det, "SCTmops1:Crate00.Channel00.HVchCurr.Recv:_online.._value", channel);
	sprintf(volt_det, "SCTmops1:Crate00.Channel00.HVchVolt.Recv:_online.._value", channel);
	dpGet( curr_det, Idet);
	dpGet( volt_det, Vdet);
	fprintf(f, "%f\t%f ", Vdd, Idd);

// VCC & ICC
	fputs("\n#VCC\tICC\n", f);
	sprintf(curr_cc, "SCTmops1:Crate00.Channel%02d.LVch_Icc.Recv:_online.._value", channel);
	sprintf(volt_cc, "SCTmops1:Crate00.Channel%02d.LVch_Vcc.Recv:_online.._value", channel);
	dpGet( curr_cc, Icc);
	dpGet( volt_cc, Vcc);
	fprintf(f, "%f\t%f ", Vcc, Icc);

// VDD & IDD
	fputs("\n#VDD\tIDD\n", f);
	sprintf(curr_dd, "SCTmops1:Crate00.Channel%02d.LVch_Idd.Recv:_online.._value", channel);
	sprintf(volt_dd, "SCTmops1:Crate00.Channel%02d.LVch_Vdd.Recv:_online.._value", channel);
	dpGet( curr_dd, Idd);
	dpGet( volt_dd, Vdd);
	fprintf(f, "%f\t%f ", Vdd, Idd);

// TIME POWERED
	fputs("\n#TIME_POWERED\n", f);
	fputs(".", f);///////

/* DCS_INFO ******************************************/
	fputs("\n#\n%DetModIV\n", f);				// 
	fprintf(f, "#\nTEMPERATURE\t: %f", T0);		// TEMPERATURE
	fprintf(f, "\nI LEAK 150\t: %f", Ileak150);	// I LEAK 150
	fprintf(f, "\nI LEAK 350\t: %f", Ileak350);	// I LEAK 350
	fprintf(f, "\n#I LEAK 500\t: %f", Ileak500);// I LEAK 500

// DEFECTS
	fputs("\n#" + def + " defects found!", f);

/* RAWDATA File ******************************************/
	dpGet("SCTmops1:IVfile.Name:_online.._value", raw);
	fputs("\n#\n%TEST Rawdata\n", f);
	fputs("FILENAME\t: " + raw, f);
	fputs("\n#\n", f);

	fclose(f); // close file
}
