// 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:  17.11.2003 - first version - H. Sandaker
//                   27.11.2003 - modify it according to changes in runstate 
//					    DDC commands P.Ferrari
//                   07.01.2004 - Adapt to change of DDC command
//                   08.01.2004 - Added loading of Cnf database HS & PM
//                   28.01.2004 - Both loading of Cnf databas and hardcoded values
//                                for on/off/stb/fatals - HS
//                   16.02,2004 - Manual loading of DB - PF
//===================================-======================================*/

main()
{ 
DebugN("Started loadConfiguration script");
dpConnect("loadConfiguration", FALSE, "loadConfiguration.trigger:_original.._value");
}


void loadConfiguration(string Text, bool Flag) 
{
int iRST,skip,timeout;
int crate,channel;
string allChannels,state;
string sParameter;
dyn_string para_split;


//==========================================================
// GET SAVING PARAMETERS FROM DAQ 
//========================================================== 

//Get Values from DAQ
  dpGet("loadConfiguration.parameters:_original.._value", sParameter);
  para_split=strsplit(sParameter,"|");
  //DebugN("sParameter", sParameter);

//Split string and get status. The format of the parameters send by DDC is Crate|State|timeout
  sscanf(para_split[1],"%d", crate);
  sscanf(para_split[2],"%s", state);
  sscanf(para_split[3],"%d", timeout);

//Check if all parameters should be loaded or only one
  if(state == "all") {
     iRST = 333; 
    }
  else {
     sscanf(state,"%d", iRST);
    }
  //DebugN("Load all states or one: ",iRST);


//==========================================================
// CHOICE OF LOADING METHOD (all or one state)
//========================================================== 

// Load parameters OFF=> iRST=0, ON=> iRST=1
if (Flag==1)
   {
   //Info
   dpSet("Info.Name:_original.._value", "CS: Loading new configuration to CC");
   DebugN("CS: Loading new configuration to CC");
   
     //Load all states
     if (iRST==333) {
        iRST=0;  // off
        LoadConfig(iRST, crate);
        DebugN("Loading state 0...");
        dpSet("Info.Name:_original.._value", "CS: Loading state OFF to CC");
        iRST=1;  //on
        LoadConfig(iRST, crate);
        DebugN("Loading state 1..");
        dpSet("Info.Name:_original.._value", "CS: Loading state ON to CC");
        iRST=2;  // stb
        LoadConfig(iRST, crate);
        DebugN("Loading state 2..");
        dpSet("Info.Name:_original.._value", "CS: Loading state STB to CC");
        iRST=128;  //fatal off
        LoadConfig(iRST, crate);
        DebugN("Loading state 128..");
        dpSet("Info.Name:_original.._value", "CS: Loading fatal alarms OFF to CC");
        iRST=129;  //fatal on
        LoadConfig(iRST, crate);
        DebugN("Loading state 129..");
        dpSet("Info.Name:_original.._value", "CS: Loading fatal alarms ON to CC");
        iRST=130;  //fatal stb
        LoadConfig(iRST, crate);
        DebugN("Loading state 130..");
        dpSet("Info.Name:_original.._value", "CS: Loading fatal alarms STB to CC");
        }
     //Load one state    
     else {
        LoadConfig(iRST, crate);
        DebugN("Loading state..", iRST);
        }
        // change the values in the PVSS datapoints to be sure that we are reading back the 
        // configuration in the ELMB
        // change(iRST);       
        // TestConfig(iRST); // Test configuration in ELMB
  
//==========================================================
// Reset Trigger and Response
//========================================================== 
   
   //Reset trigger and set response of database loading     
   dpSet("loadConfiguration.trigger:_original.._value",0);
   //DebugN("trigger");
   dpSetWait("loadConfiguration.response:_original.._value",0);
   }
}


LoadConfig(int iRST, int crate)
{
dyn_errClass err;
int  k, iDBtype;
int iStoreEnd;
string addressCC, addressCCr, addressCC2, addressCC3, dpDB, dpDB2;
int checkRST, checkDB, i;

//==========================================================
// Prepare Crate Controller for loading of database 
//==========================================================

//Tell crate controller to start database loading:
  sprintf(dpDB, "Crate%02d.Controller.CCcfsetDB.Send:_original.._value", crate); 
  dpSetWait(dpDB, 1);
  delay(0,50);
  DebugN("Setting database loading: 1");
  
//Info
  dpSet("Info.Name:_original.._value", "CS: Waiting for acknowledgement DB loading ...");

// Enable sdo reading
  dpSet(getSystemName()+"_sdo.RefreshTimer:_original.._value",20);
  dpSet(getSystemName()+"_sdo.Active:_original.._value",TRUE);
  dpSet(getSystemName()+"_sdo.EnableCallback:_original.._value",TRUE);
   
// Check that the Databaseloading procedure has been taken 
  sprintf(dpDB2, "Crate%02d.Controller.CCcfsetDB.Recv:_original.._value", crate);
  
  i=0; 
  while ((i<10) && (checkDB!=1)) { 
        dpGet(dpDB2, checkDB);
        delay(1);
        DebugN("Check CC DB", checkDB);
        i++;
        }  

if (checkDB==1) {

//Tell crate controller what datapoints to store 0 = off:
  sprintf(addressCC, "Crate%02d.Controller.CCcf_RST.Send:_original.._value", crate); 
  dpSetWait(addressCC, iRST);
  delay(0,50);
  DebugN("Setting RST: ", iRST);

//Info
  dpSet("Info.Name:_original.._value", "CS: Waiting for acknowledgement of state ...");
   
// Check that the RST has been taken 
  sprintf(addressCCr, "Crate%02d.Controller.CCcf_RST.Recv:_original.._value", crate); 
  
  i=0;
  while ((i<10) && (checkRST!=iRST)) { 
        dpGet(addressCCr, checkRST);
        delay(2);
        DebugN("Check CC RST", checkRST);
        i++;
        }  
        
// Disable sdo reading
  dpSet(getSystemName()+"_sdo.RefreshTimer:_original.._value",0);
  dpSet(getSystemName()+"_sdo.Active:_original.._value",FALSE);
  dpSet(getSystemName()+"_sdo.EnableCallback:_original.._value",FALSE); 
 
 
//==========================================================
// SEND SDO VALUES TO THE CRATE CONTROLLER VIA
// DIFFERENT METHODS (CNF file, harcoded values, select)
//========================================================== 
   
// Do loop only if run state is correctly set by ELMB
if (iRST==checkRST) { 
   
//Info:
   dpSet("Info.Name:_original.._value", "CS: Setting CC in "+iRST+"mode");
   DebugN("CS: Setting CC in", iRST," mode");

//Trigger loading of state=iRST parameters from file to PVSS 
// SDO's are sendt. Choose between hardcoded values and database values for loading:
   dpGet("ChoiceDB.Data:_online.._value", iDBtype);
  
     if (iDBtype==1){         // loading hardcoded values for modules
        dpSet("Info.Name:_original.._value", "CS: Loading hardcoded values: Modules..");
        DebugN("CS: Loading hardcoded values: Modules"); 
        Test(iRST, crate);
        }
     else if (iDBtype==3){    // loading hardcoded values for dummy's
        dpSet("Info.Name:_original.._value", "CS: Loading hardcoded values: Dummy..");
        DebugN("CS: Loading hardcoded values: Dummy"); 
        TestD(iRST, crate);
        }
     else if (iDBtype==0){     // loading hardcoded values from cnf file
        LoadCNDB(iRST, crate);
        dpSet("Info.Name:_original.._value", "CS: Loading values from config file..");
        DebugN("CS: Loading values from config file.."); 
        }
     else if (iDBtype==2){     // loading hardcoded values from manual control
        dpSet("Info.Name:_original.._value", "CS: Loading values from manual control..");
        DebugN("CS: Loading values from manual control.."); 
        // we don't need anymore to load the values, they are already in the 
        // datapoints
        }
        
 }       
 // missing: check of values!!
 
//==========================================================
// TELL CRATE CONTROLLER TO SAVE RECEIVED VALUES
//==========================================================    
     
//When finished tell crate controller to save these values:
   sprintf(addressCC3, "Crate%02d.Controller.CCcf_Set.Send:_original.._value", crate); 
   dpSetWait(addressCC3, 1702257011);
   
//Info:
   dpSet("Info.Name:_original.._value", "CS: Saving parameters to CC memory");
   DebugN("CS: Saving parameters to CC memory");
 
//==========================================================
// Check Reception of Acknowledgement
//==========================================================  
       
// Read the save-acknowledgement to check if storing values has finished
   if(iRST<3) delay(60,0);
   if(iRST>3) delay(30,0);
       
//Enable sdo Reading
  dpSet(getSystemName()+"_sdo1.RefreshTimer:_original.._value",20);
  dpSet(getSystemName()+"_sdo1.Active:_original.._value",TRUE);
  dpSet(getSystemName()+"_sdo1.EnableCallback:_original.._value",TRUE);
  dpSet(getSystemName()+"_sdo.RefreshTimer:_original.._value",10);
  dpSet(getSystemName()+"_sdo.Active:_original.._value",TRUE);
  dpSet(getSystemName()+"_sdo.EnableCallback:_original.._value",TRUE);   
// Read acknowledgement sdo
   i=0;
   sprintf(addressCC2, "Crate%02d.Controller.CCcf_RST.Recv:_original.._value", crate);
   while ((i<20) && (iStoreEnd!=255)) { 
         dpGet(addressCC2, iStoreEnd);
         DebugN("Check CC Ack", iStoreEnd,i);
         delay(5);
         i++;
   		 } 
  
// Check if database loading has been acknowledged
   if (iStoreEnd == 255){
       dpSet("Info.Name:_original.._value", "CS: Finished saving parameters to CC memory");
       DebugN("CS: Finished saving parameters to CC memory");   
       }
   else {
       dpSet("Info.Name:_original.._value", "CS: Stopped - Timeout "+iStoreEnd);
       DebugN("CS: Stopped - Timeout "); 
       //DebugN("RST",iStoreEnd);     
       }
       
// Disable sdo reading
   dpSet(getSystemName()+"_sdo.RefreshTimer:_original.._value",0);
   dpSet(getSystemName()+"_sdo.Active:_original.._value",FALSE);
   dpSet(getSystemName()+"_sdo.EnableCallback:_original.._value",FALSE);  
   
// end storing of values  
   }

// in case of error     
else {
   dpSet("Info.Name:_original.._value", "ERROR: Loading stopped: wrong state "+checkRST);
   DebugN("ERROR: Loading stopped: wrong state "+checkRST); 
   }
      
}



//------------------------------------------------------------------
//
//    LOADING VALUES FROM CONFIGURATION DATABASE - .TXT FILE
//
//------------------------------------------------------------------

LoadCNDB(int iRST, int crate) {

// Load database into Send values
int i, j, valuemax, tell;
file paraDB;
int id, channelNB;
string address, addressF;
// Parameters for all values in one line of the file opened:
string s02w, s03w,  s04w, s05w, s06w, s07w, s08w, s09w,
       s10w, s11w, s12w, s13w, s14w, s15w, s16w, s17w, s18w, s19w, s20w, s21w;
string fstr, name;
dyn_float sendTest, sendTestF;
float errorOpen;
// Values relevant for the changing of states
float offFatalL, offWarningL, offValue, offWarningH, offFatalH,
      stbFatalL, stbWarningL, stbValue, stbWarningH, stbFatalH, 
      onFatalL, onWarningL, onValue, onWarningH, onFatalH;
// Names of the corresponding parameters to be used in addressing
string LVch_Vcc, LVch_Vdd, LVchVCSV, LVchPINV,LVchDTrp, LVchCTrp, LVchTLim, LVchTTrp, 
       LVchCLKS, LVchCLKR, LVchVOut, HVchVolt, HVchITrp, HVchRamp; 


//==========================================================
// OPEN DATABASE
//========================================================== 

//Open Database
  paraDB = fopen("C:/SCT_DCS/Configs/Mops/Cnf_Para.txt","r");   

//DebugN("iRST", iRST);
  DebugN("Start Config");
  DebugN("Load .TXT file");


//==========================================================
// LOAD PARAMETERS
//==========================================================  

//Check for errors
  errorOpen = ferror(paraDB);
  if (errorOpen!=0) {
     DebugN("File Cnf_Para.txt did not open / correctly");
     }
//If no errors loop all parameters on one channel, valuemax=1296 - one full crate;    
  else {   
     valuemax=1296;
     j=0;
     
     for (i=0; i<=valuemax; i++) {

         //GET VALUES:
         //fscanf (f,"%f",value[i]); // read as float again  
         //DebugN(value[i]); // output for checking
         fgets(fstr, 300, paraDB);        

         //Take away "'s!
         strreplace(fstr, "\"", "");
         //DebugN(fstr);

         //Scan each line of the database file and store the values in temporary items
         sscanf (fstr,"%d%d%s%s%f%f%f%f%f%s%f%f%f%f%f%s%f%f%f%f%f", 
                id, channelNB, name, s03w, offFatalL, offWarningL, offValue, offWarningH, offFatalH, 
                s10w, stbFatalL, stbWarningL, stbValue, stbWarningH, stbFatalH, 
                s16w, onFatalL, onWarningL, onValue, onWarningH, onFatalH);
                //DebugN ("fstr", onValue);

         // Correction for error in conf_para file:channel nb starts with 1 not 0 
         channelNB = channelNB -1;      

         
         // Load datapoint for right STATE, for send values lines 2,6,10,12,16,17,18,19,20,21,22,24,26,27 (now changed!)
         // the array sendTest starts with line nb 1 in cnf_para, for list of values - names see below
         sendTest = makeDynFloat(0,1,0,0,0,1,0,0,0,1, 0, 1, 0, 0, 0, 1, 1, 1, 1, 1, 0, 1, 1, 0, 1, 1);
         sendTestF = makeDynFloat(0,0,0,0,0,0,0,0,0,0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1);
                                //0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25

// FROM CURRENT DATABASE TXT FILE:
//!1	1	"LVch_Vcc"	"!"	"-0.20002"	"-0.10002"	"0"			"0.10002"	"0.20002"	"!"	"1.00002"	"1.50002"	"2.00002"	"2.50002"	"3.00002"	"!"	"2.00002"	"2.50002"	"3.50002"	"4.00002"	"4.50002"	"MoniComm"
//2		1	"LVps_Vcc"	"!"	"-0.20003"	"-0.10003"	"0.00003"	"0.10003"	"0.20003"	"!"	"1.10003"	"1.60003"	"2.10003"	"5.00003"	"9.00003"	"!"	"3.10003"	"3.60003"	"3.65003"	"5.00003"	"9.00003"	"Moni"
//3		1	"LVretVcc"	"!"	"-0.20004"	"-0.10004"	"0.00004"	"0.10004"	"0.20004"	"!"	"0.00104"	"0.00204"	"0.00804"	"0.20004"	"0.50004"	"!"	"0.01004"	"0.02004"	"0.08004"	"0.20004"	"0.50004"	"Moni"
//4		1	"LVch_Icc"	"!"	"-0.20005"	"-0.10005"	"0.00005"	"0.10005"	"0.20005"	"!"	"0.00005"	"0.00005"	"353.00005"	"1050.00005""1100.00005""!"	"750.00005"	"850.00005"	"950.00005"	"1050.00005""1100.00005""Moni"
//!5	1	"LVch_Vdd"	"!"	"-0.20006"	"-0.10006"	"0"			"0.10006"	"0.20006"	"!"	"3.50006"	"3.70006"	"4.00006"	"4.70006"	"4.90006"	"!"	"3.50006"	"3.70006"	"4.00006"	"4.70006"	"4.90006"	"MoniComm"
//6		1	"LVps_Vdd"	"!"	"-0.20007"	"-0.10007"	"0.00007"	"0.10007"	"0.20007"	"!"	"3.70007"	"4.00007"	"4.40007"	"6.00007"	"9.00007"	"!"	"3.70007"	"4.00007"	"4.40007"	"6.00007"	"9.00007"	"Moni"
//7		1	"LVretVdd"	"!"	"-0.20008"	"-0.10008"	"0.00008"	"0.10008"	"0.20008"	"!"	"0.00508"	"0.01008"	"0.02008"	"0.70008"	"1.00008"	"!"	"0.00508"	"0.01008"	"0.02008"	"0.07008"	"1.00008"	"Moni"
//8		1	"LVch_Idd"	"!"	"-0.20009"	"-0.10009"	"0.00009"	"0.10009"	"0.20009"	"!"	"450.00009"	"500.00009"	"550.00009"	"600.00009"	"650.00009"	"!"	"450.00009"	"500.00009"	"550.00009"	"600.00009"	"650.00009"	"Moni"
//!9	1	"LVchVCSV"	"!"	"-0.20010"	"-0.10010"	"0"			"0.10010"	"0.20010"	"!"	"3.50010"	"3.70010"	"4.00010"	"4.20010"	"4.50010"	"!"	"3.50010"	"3.70010"	"4.00010"	"4.20010"	"4.50010"	"MoniComm"
//10	1	"LVchVCSI"	"!"	"-0.20011"	"-0.10011"	"0.00011"	"0.10011"	"0.20011"	"!"	"0.01011"	"0.02011"	"2.20011"	"2.23011"	"2.30011"	"!"	"0.01011"	"0.02011"	"2.20011"	"2.30011"	"2.50011"	"Moni"
//!11	1	"LVchPINV"	"!"	"-0.20012"	"-0.10012"	"0"			"0.10012"	"0.20012"	"!"	"5.50012"	"5.80012"	"6.00012"	"6.20012"	"6.50012"	"!"	"5.50012"	"5.80012"	"6.00012"	"6.20012"	"6.50012"	"MoniComm"
//12	1	"LVchPINI"	"!"	"-0.20013"	"-0.10013"	"0.00013"	"0.10013"	"0.20013"	"!"	"0.01013"	"0.02013"	"0.03013"	"0.03313"	"0.03913"	"!"	"0.01013"	"0.02013"	"0.03013"	"0.04013"	"0.050013"	"Moni"
//13	1	"MOch_Tm0"	"!"	"-5.00014"	"-8.00014"	"20.00014"	"10.00014"	"8.00014"	"!"	"-99.0014"	"15.00014"	"25.00014"	"30.00014"	"33.00014"	"!"	"-99.00014"	"-15.00014"	"0.00014"	"10.00014"	"33.00014"	"Moni"
//14	1	"MOch_Tm1"	"!"	"-5.00015"	"-8.00015"	"20.00015"	"10.00015"	"8.00015"	"!"	"-99.0015"	"15.00015"	"25.00015"	"30.00015"	"33.00015"	"!"	"-99.00015"	"-15.00015"	"0.00015"	"10.00015"	"33.00015"	"Moni"
//!15	1	"LVchDTrp"	"!"	"47.00016"	"49.00016"	"50.00016"	"51.00016"	"53.00016"	"!"	"49.10016"	"49.5016"	"50.00016"	"50.50016"	"50.90016"	"!"	"47.00016"	"49.00016"	"50.00016"	"51.00016"	"53.00016"	"Comm"
//!16	1	"LVchCTrp"	"!"	"47.00017"	"49.00017"	"50.00017"	"51.00017"	"53.00017"	"!"	"49.10017"	"49.5017"	"50.00017"	"50.50017"	"50.90017"	"!"	"47.00017"	"49.00017"	"50.00017"	"51.00017"	"53.00017"	"Comm"
//!17	1	"LVchTLim"	"!"	"27.00018"	"29.00018"	"30.00018"	"31.00018"	"33.00018"	"!"	"29.10018"	"29.50018"	"30.00018"	"30.50018"	"30.90018"	"!"	"27.00018"	"29.00018"	"30.00018"	"31.00018"	"33.00018"	"Comm"
//!18	1	"LVchTTrp"	"!"	"47.00019"	"49.00019"	"50.00019"	"51.00019"	"53.00019"	"!"	"34.10019"	"34.50019"	"35.00019"	"35.50019"	"35.90019"	"!"	"34.00019"	"34.00019"	"35.00019"	"36.00019"	"38.00019"	"Comm"
//!19	1	"LVchCLKS"	"!"	"-0.01020"	"-0.00120"	"0"			"0.00120"	"0.01020"	"!"	"-0.0320"	"-0.0120"	"0"			"0.01020"	"0.03020"	"!"	"-0.01020"	"-0.00120"	"0"			"0.00120"	"0.01020"	"Comm"
//20	1	"LVchCLKR"	"!"	"-0.01021"	"-0.00121"	"0"			"0.00121"	"0.01021"	"!"	"-0.0321"	"-0.0121"	"0"			"0.01021"	"0.03021"	"!"	"-0.01021"	"-0.00221"	"0"			"0.00221"	"0.01021"	"Comm"
//!21	1	"LVchVOut"	"!"	"-0.20022"	"-0.10022"	"0"			"0.10022"	"0.20022"	"!"	"0.80022"	"0.95022"	"1.00022"	"1.05022"	"1.20022"	"!"	"0.90022"	"0.95022"	"1.00022"	"1.05022"	"1.10022"	"Comm"
//!22	1	"HVchVolt"	"!"	"-0.20024"	"-0.10024"	"0"			"5.00024"	"10.00024"	"!"	"10.00024"	"19.00024"	"20.00024"	"22.00024"	"24.00024"	"!"	"130.00024"	"140.00024"	"150.00024"	"160.00024"	"170.00024"	"MoniComm"
//23	1	"HVchCurr"	"!"	"-0.20025"	"-0.10025"	"0.00025"	"400.00025"	"600.00025"	"!"	"20.00025"	"40.00025"	"100.00025"	"150000.025""200000.025""!"	"3.00025"	"3.60025"	"4.00025"	"1100.00025""1200.00025""Moni"
//!24	1	"HVchITrp"	"!"	"1000"		"1050"		"1100"		"1150"	"	1200"		"!"	"1000"		"1050"		"1100"		"1150"		"1200"		"!"	"1000"		"1050"		"1100"		"1150"		"1200"		"Comm"
//!25	1	"HVchRamp"	"!"	"3.70027"	
	


         // Set to read the right line number:
         j= i+1 - 25*channelNB; 
         //DebugN("channelNB", channelNB, "i", i, "j", j);
   
   
//==========================================================
// SET SEND VALUES TO DATAPOINTS FOR STATES ON/OFF/STB
//==========================================================  
                  
         if (channelNB>=0){
            
           // if ((sendTest[j]==1)&& (j>=0)) {
              if (sendTest[j]==1) {
               // Check if send value according to array;
               sprintf(address, "Crate%02d.Channel%02d.%s.Send:_original.._value", crate, channelNB, name ); 
               //choise of RST parameters:
               if (iRST == 0) { 
                  dpSet(address, offValue);
                  DebugN("off", offValue, address);
                  }
               if (iRST == 1) { 
                  dpSet(address, onValue);
                  DebugN("on", onValue, address);
                  }
               if (iRST == 2) { 
                  dpSet(address, stbValue);
                  DebugN("stb", stbValue, address);
                  } 
               }
 
 
//==========================================================
// SET SEND VALUES TO DATAPOINTS FOR FATAL STATES ON/OFF/STB
//========================================================== 
               
          //if ((sendTestF[j]==1) && (j>=0)) {
            if (sendTestF[j]==1) {
                       
               // Change address for temperature fatals to be put to send values
               if (name=="MOch_Tm0"){
                  sprintf(addressF, "Crate%02d.Channel%02d.LVchTLim.Send:_original.._value", crate, channelNB);  
                  }
               else if (name=="MOch_Tm1"){
                  sprintf(addressF, "Crate%02d.Channel%02d.LVchTTrp.Send:_original.._value", crate, channelNB);  
                  }
               else{ 
                  sprintf(addressF, "Crate%02d.Channel%02d.%s.Send:_original.._value", crate, channelNB, name );  
                  }
               
               //choise of RST parameters: 
               if (iRST == 128) { 
                  dpSet(addressF, offFatalH);
                  DebugN("offFatal", offFatalH, addressF);
                  }
               if (iRST == 129) { 
                  dpSet(addressF, onFatalH);
                  DebugN("onFatal", onFatalH, addressF);
                  }
               if (iRST == 130) { 
                  dpSet(addressF, stbFatalH);
                  DebugN("stbFatal", stbFatalH, addressF);
                  }         
               }
          }
         // Missing set lower alarms!! (not needed at the moment) 
     } 
}

//==========================================================
// CLOSE CNF FILE
//========================================================== 

//dpSetWait(datapoint1, initValue[j]);
//rewind(ParaDB);
fclose(paraDB);              
//fclose(Cnf_ParaM.txt);  
}

                 
//------------------------------------------------------------------
//
//    ROUTINE USED FOR DB TESTING - HARDCODED VALUES - DUMMY
//
//------------------------------------------------------------------

TestD(int iRST, int crate) {

// Function to simulate the Loading of values from file to PVSS

int icard, channel, statusLV, statusHV,statusLVCard;
string datapoint1, datapoint2,datapoint3; 
dyn_errClass err;
int i, j, l;
dyn_string valsetLV, valsetHV, valsetLVfatal, valsetHVfatal; 
dyn_float initValueLV, initValueHV, initValueLVfatal, initValueHVfatal;


DebugN("Start Hardcoded");
valsetLV = makeDynString("LVcaTrip","LVcaMask","LVch_Vcc","LVch_Vdd",
                         "LVchVCSV","LVchPINV","LVchDTrp","LVchCTrp",
                         "LVchTLim","LVchTTrp","LVchCLKS","LVchCLKR",
                         "LVchVOut");
valsetHV = makeDynString("HVchVolt","HVchITrp","HVchRamp");


valsetLVfatal = makeDynString("LVchTTrp","LVchTLim", "LVchVOut");
                             //fatalTemp1, fatalTemp2,fatalVout                          
                        
valsetHVfatal = makeDynString("HVchVolt","HVchITrp");
                            // FatalVolt , FatalCurrent 


//==========================================================
// Define Hardcoded values for different states
//========================================================== 

if (iRST == 0) { 
   initValueLV = makeDynFloat(46.0,15,0,0,0,0,50,50,35,38,0,0,0);
   initValueHV = makeDynFloat(0,5000,3);
   }
if (iRST == 1) { 
   initValueLV = makeDynFloat(46.0,15,3.5,4,4,6,50,50,35,38,0,0,1);
   initValueHV = makeDynFloat(150,5000,3);
   }
if (iRST == 2) { 
   initValueLV = makeDynFloat(46.0,15,2.5,4,4,6,50,50,35,38,0,0,1);
   initValueHV = makeDynFloat(20,5000,3);
   }   
if (iRST == 128) { 
   initValueLVfatal = makeDynFloat(41,41,1);
   initValueHVfatal = makeDynFloat(10,5000  ); //units nA!!
   }
if (iRST == 129) {
   initValueLVfatal = makeDynFloat(41,41,1);
   //initValueLVfatal = makeDynFloat(33,33,1);
   initValueHVfatal = makeDynFloat(10,5000); // units nA!!
   }
if (iRST == 130) { 
   initValueLVfatal = makeDynFloat(41,41,1);
   //initValueLVfatal = makeDynFloat(33,33,1);
   initValueHVfatal = makeDynFloat(10,5000); // units  nA!!   
   } 


//==========================================================
// Load Values into the datapoints
//========================================================== 

//Loading of fatals:
if (iRST==128 || iRST==129 || iRST ==130){
     for (l=0; l<=47; l++){
         for (i=1; i<=2; i++) {
             sprintf(datapoint1, "Crate%02d.Channel%02d.%s.Send:_original.._value",crate,l,valsetHVfatal[i] );
             dpSetWait(datapoint1, initValueHVfatal[i]);     
             //DebugN(" HV channel", l, valsetHVfatal[i], " = ",initValueHVfatal[i]);
             }         
         for (j=1;j<=2;j++){
             sprintf(datapoint1, "Crate%02d.Channel%02d.%s.Send:_original.._value",crate,l,valsetLVfatal[j] );
             dpSetWait(datapoint1, initValueLVfatal[j]);
             //DebugN(" LV channel", l, valsetLV[j], " = ",initValueLV[j]);
             }
        }
    }

else if (iRST==0 || iRST==1 || iRST==2) {
// Loading off values for the parameters: 
     for (l=0; l<=47; l++){
         for (i=1; i<=3; i++) {
             sprintf(datapoint1, "Crate%02d.Channel%02d.%s.Send:_original.._value",crate,l,valsetHV[i] );
             dpSetWait(datapoint1, initValueHV[i]);     
             //DebugN(" HV channel", l, valsetHV[i], " = ",initValueHV[i]);
             }
         for (j=3;j<=13;j++){
             sprintf(datapoint1, "Crate%02d.Channel%02d.%s.Send:_original.._value",crate,l,valsetLV[j] );
             dpSetWait(datapoint1, initValueLV[j]);
             //DebugN(" LV channel", l, valsetLV[j], " = ",initValueLV[j]);
             }
          }
     }
  err = getLastError();
  if (dynlen(err) > 0)
    errorDialog(err);       
 
}



//------------------------------------------------------------------
//
//    ROUTINE USED FOR DB TESTING - HARDCODED VALUES - MODULES
//
//------------------------------------------------------------------

Test(int iRST, int crate) {

// Function to simulate the Loading of values from file to PVSS

int icard, channel, statusLV, statusHV,statusLVCard;
string datapoint1, datapoint2,datapoint3; 
dyn_errClass err;
int i, j, l;
dyn_string valsetLV, valsetHV, valsetLVfatal, valsetHVfatal; 
dyn_float initValueLV, initValueHV, initValueLVfatal, initValueHVfatal;


DebugN("Start Hardcoded");
DebugN("Load Module values");
valsetLV = makeDynString("LVcaTrip","LVcaMask","LVch_Vcc","LVch_Vdd",
                         "LVchVCSV","LVchPINV","LVchDTrp","LVchCTrp",
                         "LVchTLim","LVchTTrp","LVchCLKS","LVchCLKR",
                         "LVchVOut");
valsetHV = makeDynString("HVchVolt","HVchITrp","HVchRamp");


valsetLVfatal = makeDynString("LVchTTrp","LVchTLim", "LVchVOut");
                             //fatalTemp1, fatalTemp2,fatalVout                          
                        
valsetHVfatal = makeDynString("HVchVolt","HVchITrp");
                            // FatalVolt , FatalCurrent 

//==========================================================
// Define Hardcoded values for different states
//========================================================== 

if (iRST == 0) { 
   initValueLV = makeDynFloat(46.0,15,0,0,0,0,50,50,33,35,0,0,0);
   initValueHV = makeDynFloat(0,5000,3);
   }
if (iRST == 1) { 
   initValueLV = makeDynFloat(46.0,15,3.5,4,4,6,50,50,33,35,0,0,1);
   initValueHV = makeDynFloat(150,5000,3);
   }
if (iRST == 2) { 
   initValueLV = makeDynFloat(46.0,15,2.5,4,4,6,50,50,33,35,0,0,1);
   initValueHV = makeDynFloat(20,5000,3);
   }   
if (iRST == 128) { 
   initValueLVfatal = makeDynFloat(35,35,1);
   initValueHVfatal = makeDynFloat(10,5000); //units nA!!
   }
if (iRST == 129) {
   initValueLVfatal = makeDynFloat(35,35,1);
   //initValueLVfatal = makeDynFloat(33,33,1);
   initValueHVfatal = makeDynFloat(0,1000); // units nA!!
   }
if (iRST == 130) { 
   initValueLVfatal = makeDynFloat(37,37,1);
   //initValueLVfatal = makeDynFloat(33,33,1);
   initValueHVfatal = makeDynFloat(0,5000); // units  nA!!   
   } 

//==========================================================
// Load Hardcoded values to the datapoints
//========================================================== 

//Loading of fatals:
if (iRST==128 || iRST==129 || iRST ==130){
     for (l=0; l<=47; l++){
         for (i=1; i<=2; i++) {
             sprintf(datapoint1, "Crate%02d.Channel%02d.%s.Send:_original.._value",crate, l,valsetHVfatal[i] );
             dpSetWait(datapoint1, initValueHVfatal[i]);     
             //DebugN(" HV channel", l, valsetHVfatal[i], " = ",initValueHVfatal[i]);
             delay(0,10);
             }         
         for (j=1;j<=2;j++){
             sprintf(datapoint1, "Crate%02d.Channel%02d.%s.Send:_original.._value",crate, l,valsetLVfatal[j] );
             dpSetWait(datapoint1, initValueLVfatal[j]);
             delay(0,10);
             //DebugN(" LV channel", l, valsetLV[j], " = ",initValueLV[j]);
             }
        }
    }

else if (iRST==0 || iRST==1 || iRST==2) {
// Loading off values for the parameters: 
     for (l=0; l<=47; l++){
         for (i=1; i<=3; i++) {
             sprintf(datapoint1, "Crate%02d.Channel%02d.%s.Send:_original.._value",crate, l,valsetHV[i] );
             dpSetWait(datapoint1, initValueHV[i]); 
             delay(0,10);    
             //DebugN(" HV channel", l, valsetHV[i], " = ",initValueHV[i]);
             }
         for (j=3;j<=13;j++){
             sprintf(datapoint1, "Crate%02d.Channel%02d.%s.Send:_original.._value",crate, l,valsetLV[j] );
             dpSetWait(datapoint1, initValueLV[j]);
             delay(0,10);
             //DebugN(" LV channel", l, valsetLV[j], " = ",initValueLV[j]);
             }
          }
     }
  err = getLastError();
  if (dynlen(err) > 0)
    errorDialog(err);       
 
}



//------------------------------------------------------------------
//
//    ROUTINE USED FOR DB TESTING - MANUAL VALUES
//
//------------------------------------------------------------------

LoadManual(int iRST, int crate) {

// Function to simulate the Loading of values from file to PVSS

int icard, channel, statusLV, statusHV,statusLVCard;
string datapoint1, datapoint2,datapoint3; 
dyn_errClass err;
int i, j, l;
dyn_string valsetLV, valsetHV, valsetLVfatal, valsetHVfatal; 
dyn_float initValueLV, initValueHV, initValueLVfatal, initValueHVfatal;
int manual;

DebugN("Start Manual");
valsetLV = makeDynString("LVcaTrip","LVcaMask","LVch_Vcc","LVch_Vdd",
                         "LVchVCSV","LVchPINV","LVchDTrp","LVchCTrp",
                         "LVchTLim","LVchTTrp","LVchCLKS","LVchCLKR",
                         "LVchVOut");
valsetHV = makeDynString("HVchVolt","HVchITrp","HVchRamp");

valsetLVfatal = makeDynString("LVchTTrp","LVchTLim", "LVchVOut");
                             //fatalTemp1, fatalTemp2,fatalVout                          
                        
valsetHVfatal = makeDynString("HVchVolt","HVchITrp");
                            // FatalVolt , FatalCurrent 

//initialise the dynstring array
initValueLV = makeDynFloat(0,0,0,0,0,0,0,0,0,0,0,0,0);
initValueHV = makeDynFloat(0,0,0);
initValueLVfatal = makeDynFloat(0,0,0);
initValueHVfatal = makeDynFloat(0,0);


//Load manual values
   
  //Getting the values which are set by hand in channel 0
  if (iRST==0 || iRST==1 || iRST==2) {
    for (i=3;i<=13;i++)
    {  
    sprintf(datapoint1,getSystemName()+"Crate%02d.Channel00.%s.Send:_original.._value",crate, valsetLV[i]);
    dpGet(datapoint1,initValueLV[i]);
    }
    for (i=1; i<=3; i++) {
    sprintf(datapoint1,getSystemName()+"Crate%02d.Channel00.%s.Send:_original.._value",crate, valsetHV[i]);
    dpGet(datapoint1,initValueHV[i]);
    }
    for (l=0; l<=47; l++)
         {
         for (i=1; i<=3; i++) {
             sprintf(datapoint1, "Crate%02d.Channel%02d.%s.Send:_original.._value",crate, l,valsetHV[i]);
             dpSetWait(datapoint1, initValueHV[i]);     
             //DebugN(" HV channel", l, valsetHV[i], " = ",initValueHV[i]);
             }       
         for (j=3;j<=13;j++){
             sprintf(datapoint1, "Crate%02d.Channel%02d.%s.Send:_original.._value",crate, l,valsetLV[j]);
             dpSetWait(datapoint1, initValueLV[j]);
             //DebugN(" LV channel", l, valsetLV[j], " = ",initValueLV[j]);
             }
         }
    }
    if (iRST==128 || iRST==129 || iRST ==130){
      for(i=1;i<=2;i++)
           {
           sprintf(datapoint1,getSystemName()+"Crate%02d.Channel00.%s.Send:_original.._value",crate, valsetHVfatal[i]);
           dpGet(datapoint1,initValueHVfatal[i]);
	     } 
      for(i=1;i<=3;i++)
           {
           sprintf(datapoint1,getSystemName()+"Crate%02d.Channel00.%s.Send:_original.._value",crate, valsetLVfatal[i]);
           dpGet(datapoint1,initValueLVfatal[i]);
	     }
      for (l=0; l<=47; l++){
         for (i=1; i<=2; i++) {
             sprintf(datapoint1, "Crate00.Channel%02d.%s.Send:_original.._value",crate, l,valsetHVfatal[i] );
             dpSetWait(datapoint1, initValueHVfatal[i]);     
             //DebugN(" HV channel", l, valsetHVfatal[i], " = ",initValueHVfatal[i]);
             }         
         for (j=1;j<=3;j++){
             sprintf(datapoint1, "Crate00.Channel%02d.%s.Send:_original.._value",crate, l,valsetLVfatal[j] );
             dpSetWait(datapoint1, initValueLVfatal[j]);
             //DebugN(" LV channel", l, valsetLV[j], " = ",initValueLV[j]);
             }
        }
    }



  err = getLastError();
  if (dynlen(err) > 0)
    errorDialog(err);       
 

}
change(int iRST, int crate) {

// Function to change the values in PVSS datapoints to make sure we are reloading
//  the values from ELMB

int icard, channel, statusLV, statusHV,statusLVCard;
string datapoint1, datapoint2,datapoint3; 
dyn_errClass err;
int i, j, l;
dyn_string valsetLV, valsetHV; 
dyn_float initValueLV, initValueHV;

if (iRST == 0) { 
   initValueLV = makeDynFloat(0,0,0,0,0,0,0,0,0,0,0,0,0);
   initValueHV = makeDynFloat(0,0,0);
   }
if (iRST == 1) { 
   initValueLV = makeDynFloat(0,0,0,0,0,0,0,0,0,0,0,0,0);
   initValueHV = makeDynFloat(0,0,0);
   }
if (iRST == 2) { 
   initValueLV = makeDynFloat(0,0,0,0,0,0,0,0,0,0,0,0,0);
   initValueHV = makeDynFloat(0,0,0);
   }

valsetLV = makeDynString("LVcaTrip","LVcaMask","LVch_Vcc","LVch_Vdd",
                         "LVchVCSV","LVchPINV","LVchDTrp","LVchCTrp",
                         "LVchTLim","LVchTTrp","LVchCLKS","LVchCLKR",
                         "LVchVOut");
valsetHV = makeDynString("HVchVolt","HVchITrp","HVchRamp");


// Loading off values for the parameters: 
 for (l=0; l<=47; l++){
DebugN("Changing PVSS datapoints values for cross check");
     for (i=1; i<=3; i++) {
         sprintf(datapoint1, "Crate%02d.Channel%02d.%s.Send:_original.._value",crate, l,valsetHV[i] );
         dpSetWait(datapoint1, initValueHV[i]);     
         }
         
     for (j=3;j<=13;j++){
         sprintf(datapoint1, "Crate%02d.Channel%02d.%s.Send:_original.._value",crate, l,valsetLV[j] );
         dpSetWait(datapoint1, initValueLV[j]);
         }

     }
 
  err = getLastError();
  if (dynlen(err) > 0)
    errorDialog(err);       
 
}


TestConfig(int iRST) {

dyn_errClass err;
int  k;
int iStoreEnd;

//Tell crate controller what datapoints to read 0 = off:

dpSetWait("Crate00.Controller.CCcf_RST.Send:_original.._value", iRST);
   dpSet("Info.Name:_original.._value", "CS: chosing to read parameters from CC");
   DebugN("CS: chosing to read parameters from CC");

//Tell crate controller to send off parameters back to PVSS:
  
dpSetWait("Crate00.Controller.CCcf_Set.Send:_original.._value", 1684107116);
   dpSet("Info.Name:_original.._value", "CS: Reading parameters from CC memory...");
   DebugN("CS: Reading parameters from CC memory...");  

delay(10);
//Trigger reading of OFF parameters (0) from file to PVSS 
// SDO's are sendt

Read();
   dpSet("Info.Name:_original.._value", "CS: Reading parameters from CC memory");
   DebugN("CS: Reading parameters from CC memory");  
   
// check if readed values has finished
delay(10,0);

     dpGet("Crate00.Controller.CCcf_RST.Recv:_original.._value", iStoreEnd); 
     if (iStoreEnd = 255||iStoreEnd==128||iStoreEnd==129||iStoreEnd==130){
        dpSet("Info.Name:_original.._value", "CS: Finished reading parameters to CC memory");
        DebugN("CS: Finished reading parameters to CC memory");   
        }
     else {
        dpSet("Info.Name:_original.._value", "CS: Stopped - Timeout "+iStoreEnd);
        DebugN("CS: Stopped - Timeout",iStoreEnd);     
     } 
// check if values are ok:
   Check(iRST);

}

Read() {

int i,icard, channel;
delay(0,10);

DebugN("CS: Reading Values"); 
dpSet("Info.Name:_original.._value", "CS: Reading values...");
 
for (i=0; i<=47; i++){
    dpSetWait("Crate00.Controller.CCchRead.Send:_original.._value",i);
    channel=i+64;
    delay(0,10);
    dpSetWait("Crate00.Controller.CCchRead.Send:_original.._value", channel);
    delay(0,10);
    }
}


Check (int iRST) {
string datapoint1; 
dyn_errClass err;
int i, j, l;
float abs,x;
dyn_string valsetLV, valsetHV; 
dyn_float initValueLV, initValueHV, readValueLV, readValueHV;
int HV, LV;

valsetLV = makeDynString("LVcaTrip","LVcaMask","LVch_Vcc","LVch_Vdd",
                         "LVchVCSV","LVchPINV","LVchDTrp","LVchCTrp",
                         "LVchTTrp","LVchTLim","LVchCLKS","LVchCLKR",
                         "LVchVOut");
valsetHV = makeDynString("HVchVolt","HVchITrp","HVchRamp");

     if (iRST == 0) { 
        initValueLV = makeDynFloat(46,15,0,0,0,0,50,50,50,60,0,0,0);
        initValueHV = makeDynFloat(0,1100,3);
        }
     if (iRST == 1) { 
        initValueLV = makeDynFloat(46.5,15,3.5,4,4,6,50,50,50,60,0,0,1);
        initValueHV = makeDynFloat(300,1100,3);
        }
     if (iRST == 2) { 
        initValueLV = makeDynFloat(46.5,15,2.0,4,4,6,50,50,50,60,0,0,1);
        initValueHV = makeDynFloat(20,1100,3);
        }


// Reading values for the parameters: 
 for (l=0; l<=47; l++){
     HV=0;
     LV=0;
     for (i=1; i<=3; i++) {
         sprintf(datapoint1, "Crate00.Channel%02d.%s.Send:_original.._value",l,valsetHV[i] );
         dpGet(datapoint1, readValueHV[i]);
         DebugN(" read value Hv channel= ",l," is ",readValueHV[i], "set value is =", initValueHV[i]);
         x=readValueHV[i] - initValueHV[i];
	   abs=(x<0) ? -x : x; // abs= abs(x)
	   //DebugN( "absolute value", abs);
         if (abs <0.01) {
            HV = HV +1; 
            }     
         }        
     for (j=3;j<=13;j++){
         sprintf(datapoint1, "Crate00.Channel%02d.%s.Send:_original.._value",l,valsetLV[j] );
         dpGet(datapoint1, readValueLV[j]);
         DebugN(" read value LV channel= ",l," is ",readValueLV[j], "set value is =", initValueLV[j]);
         x=readValueLV[j] - initValueLV[j];
	   abs=(x<0) ? -x : x; // abs= abs(x)
         if (abs <0.01) {
            LV = LV +1; 
            } 
         }
     if (HV == 3 && LV == 11) {     
        DebugN("channel ok:", l);
        }
     else {
        DebugN("channel bad:", l);
        }
     }
        
}
// 1	1	"LVchStat"	
// 2	1	"LVch_Vcc"	
// 3	1	"LVps_Vcc"	
// 4	1	"LVretVcc"	
// 5	1	"LVch_Icc"	
// 6	1	"LVch_Vdd"	
// 7	1	"LVps_Vdd"	
// 8	1	"LVretVdd"	
// 9	1	"LVch_Idd"	
// 10	1	"LVchVCSV"	
// 11	1	"LVchVCSI"	
// 12	1	"LVchPINV"	
// 13	1	"LVchPINI"	
// 14	1	"MOch_Tm0"	
// 15	1	"MOch_Tm1"	
// 16	1	"LVchDTrp"	
// 17	1	"LVchCTrp"	
// 18	1	"LVchTLim"		
// 19	1	"LVchTTrp"	
// 20	1	"LVchCLKS"	
// 21	1	"LVchCLKR"	
// 22	1	"LVchVOut"	
// 23	1	"HVchStat"	
// 24	1	"HVchVolt"	
// 25	1	"HVchCurr"	
// 26	1	"HVchITrp"	
// 27	1	"HVchRamp"

// Configuration DB


