
clc %Clear the MATLAB command window
clear %Clear the MATLAB variables

addpath('..\LoadDumpControl');

global CalFactors MinChargeCurrent fid Outputs;
global Capacity_Low Capacity_High;
MinChargeCurrent = 0.35;

ChargeSamplePeriod = 0.25;  %seconds
MaxChargeDuration = 10*3600;  %Max Charge Cycle Duration in seconds

DischargeSamplePeriod = 1;  %seconds
MaxDischargeDuration = 15*3600;  %Max Discharge Cycle Duration in seconds

DischargeCurrent = 1.4;  %Amps
MinimumVoltage = 10.5 %10.5;  %Volts

NumCycles = 100;


CalFactors.ImonLow_Zero = 2.4947;
CalFactors.ImonLow_AmpsperVolt = 3.5/(4.6785-CalFactors.ImonLow_Zero);

CalFactors.ImonHigh_Zero = -.0041;
CalFactors.ImonHigh_AmpsperVolt = 5/(1.3833-CalFactors.ImonHigh_Zero);


ResultsPath = ['Results_' datestr(now,'mmm-dd-yyyy_HH-MM-SS') '\'];
mkdir(ResultsPath(1:end-1));

ljasm = NET.addAssembly('LJUDDotNet'); %Make the UD .NET assembly visible in MATLAB
[ljudObj, ljhandle] = SetUp_LJ();

fclose('all');  %Close all open file descriptors

alltimers = timerfind;
if(~isempty(alltimers))
  stop(alltimers);
  delete(alltimers);  %Stop and delete all timers
end

existing_sp = instrfind  % Find,close, and delete existing serial port instrument interfaces
if(~isempty(existing_sp))
  fclose(existing_sp);
  delete(existing_sp);
end




%Find existing serial ports, assumption is that only load dumps are plugged
%in as serial ports to this computer.
SerialInfo = instrhwinfo('serial');
if(length(SerialInfo.AvailableSerialPorts) < 2)
    error('There are not two serial ports available.');
end

%Open serial ports.  Assumes Load Dumps are the last two enumerated.
for i = 1:2
   LD_sp(i) = serial(SerialInfo.AvailableSerialPorts{end-i+1});
   LD_sp(i).BaudRate=38400;
   LD_sp(i).BytesAvailableFcnMode = 'byte';
   LD_sp(i).BytesAvailableFcnCount = 1;
   LD_sp(i).Terminator = 'CR/LF';
   %LowLD_sp.BytesAvailableFcn = @SerialPortCallBack;
   fopen(LD_sp(i));
   if(~strcmp(LD_sp(i).Status,'open'))
       error(['Error opening ' SerialInfo.AvailableSerialPorts{end-i+1}]);
   end
end

%Enable Remote and figure out which is which
for i = 1:2
err = BK_EnableRemote(LD_sp(i),1);
  if(err)
   error(['Error enabling Load Dump at ' SerialInfo.AvailableSerialPorts{i}]);
  end
[FirmwareVersion SN err] = BK_GetSN(LD_sp(i));
  if(err)
   error(['Error reading firmware from ' SerialInfo.AvailableSerialPorts{i}]);
  end
  
  switch char(SN')
      case '6274001126'
          LowLD_sp = LD_sp(i);
      case '6269001006'
          HighLD_sp = LD_sp(i);
      otherwise
          error('Unknown Load Dump Serial Number');
  end 
end
if(isempty(LowLD_sp) || isempty(HighLD_sp))
    error('Both Load Dumps not Found');
end


[log_fid, errmsg] = fopen([ResultsPath 'TestLog.txt'],'w+');
if(log_fid == -1)
    error(['Error opening file  ' errmsg]);
end


   err = BK_SetMaxCurrent(HighLD_sp,5);
   err = BK_SetMaxCurrent(LowLD_sp,5);
   
  ChargeTimer = timer;
  ChargeTimer.StartFcn = {@ChargeTimerStartCallBack,ljudObj,ljhandle};
  ChargeTimer.TimerFcn = {@ChargeTimerCallBack,ljudObj,ljhandle,LowLD_sp,HighLD_sp};
  ChargeTimer.StopFcn = {@ChargeTimerStopCallBack,ljudObj,ljhandle};
  ChargeTimer.Period = ChargeSamplePeriod;
  ChargeTimer.TasksToExecute = MaxChargeDuration/ChargeSamplePeriod;
  ChargeTimer.ExecutionMode = 'fixedRate';
  
  DischargeTimer = timer;
  DischargeTimer.StartFcn = {@DischargeTimerStartCallBack,ljudObj,ljhandle};
  DischargeTimer.TimerFcn = {@DischargeTimerCallBack,ljudObj,ljhandle,LowLD_sp,HighLD_sp,DischargeCurrent};
  DischargeTimer.StopFcn = {@DischargeTimerStopCallBack,ljudObj,ljhandle};
  DischargeTimer.Period = DischargeSamplePeriod;
  DischargeTimer.TasksToExecute = MaxDischargeDuration/DischargeSamplePeriod;
  DischargeTimer.ExecutionMode = 'fixedRate';
  
  
for ChargeCycle = 1:NumCycles
   for i = 1:3
     err =  BK_SetFunction(LowLD_sp,0);  if (err == 0)  continue;  end
     pause(1);
   end
   if(err ~=0) error('Unable to set BK_SetFunction to 0 for Low Rate Load Dump'); end
      
   %err = err+BK_SetCCMode(LowLD_sp);
   %err = err+BK_SetCurrent(LowLD_sp,0);
   for i = 1:3
     err = BK_LoadOn(LowLD_sp,0);
   pause(1);
   end
   if(err ~=0) error('Unable to set BK_LoadOn to 0 for Low Rate Load Dump'); end
   
   

   for i = 1:3
     err =  BK_SetFunction(HighLD_sp,0);  if (err == 0)  continue;  end
     pause(1);
   end
   if(err ~=0) error('Unable to set BK_SetFunction to 0 for High Rate Load Dump'); end
   
   %err = err+BK_SetCCMode(HighLD_sp);
   %err = err+BK_SetCurrent(HighLD_sp,0);
   for i = 1:3  
     err = BK_LoadOn(HighLD_sp,0);
   pause(1);
   end
   if(err ~=0) error('Unable to set BK_LoadOn to 0 for High Rate Load Dump'); end
    
  fprintf(log_fid,'%s  Starting Charge Cycle # %d\n',datestr(now),ChargeCycle);
   
  [fid, errmsg] = fopen([ResultsPath 'ChargeData_Cycle_' num2str(ChargeCycle) '.txt'],'w+');
  if(fid == -1)
      error(['Error opening file  ' errmsg]);
  end
  
  start(ChargeTimer);
   while(strcmp(get(ChargeTimer,'Running'),'on'))  %Wait here until charge cycle is complete 
   end
  
  fprintf(log_fid,'%s  Ending Charge Cycle # %d\n',datestr(now),ChargeCycle);

  fclose(fid);
  pause(3)
  
  [fid, errmsg] = fopen([ResultsPath 'DischargeData_Cycle_' num2str(ChargeCycle) '.txt'],'w+');
  if(fid == -1)
      error(['Error opening file  ' errmsg]);
  end

  
%%%  Set up discharge current for Low Rate Load Dump  %%%  
 for i = 1:3
    err =  BK_SetCurrent(LowLD_sp,DischargeCurrent); if (err == 0)  continue;  end
    pause(1);
 end
 if(err ~=0) error(['Unable to set BK_SetCurrent to ' num2str(DischargeCurrent) ' A for Low Rate Load Dump']); end 
  
 for i = 1:3
    err = BK_SetMinVoltageForBattTest(LowLD_sp,MinimumVoltage); if (err == 0)  continue;  end
    pause(1);
 end
 if(err ~=0) error(['Unable to set BK_SetMinVoltageForBattTest to ' num2str(MinimumVoltage) ' V for Low Rate Load Dump']); end 
 
 for i = 1:3
    err =  BK_SetFunction(LowLD_sp,4);  if (err == 0)  continue;  end
    pause(1);
 end
 if(err ~=0) error('Unable to set BK_SetFunction to 4 for Low Rate Load Dump'); end 

 
 %%%  Set up discharge current for Low Rate Load Dump  %%%  
 for i = 1:3
    err =  BK_SetCurrent(HighLD_sp,DischargeCurrent); if (err == 0)  continue;  end
    pause(1);
 end
 if(err ~=0) error(['Unable to set BK_SetCurrent to ' num2str(DischargeCurrent) ' A for High Rate Load Dump']); end   
  
 for i = 1:3
    err = BK_SetMinVoltageForBattTest(HighLD_sp,MinimumVoltage); if (err == 0)  continue;  end
    pause(1);
 end
 if(err ~=0) error(['Unable to set BK_SetMinVoltageForBattTest to ' num2str(MinimumVoltage) ' V for High Rate Load Dump']); end 
 
 for i = 1:3
   err =  BK_SetFunction(HighLD_sp,4);  if (err == 0)  continue;  end
   pause(1);
 end
 if(err ~=0) error('Unable to set BK_SetFunction to 4 for High Rate Load Dump'); end
 
 tic
   
  [fid, errmsg] = fopen([ResultsPath 'DischargeData_Cycle_' num2str(ChargeCycle) '.txt'],'w+');
  if(fid == -1)
      error(['Error opening file  ' errmsg]);
  end
  
  fprintf(log_fid,'%s  Starting Discharge Cycle # %d\n',datestr(now),ChargeCycle);

  pause(2);  %Give it a moment to start drawing current.
  Capacity_Low = 0;
  Capacity_High = 0;
  start(DischargeTimer);
  while(strcmp(get(DischargeTimer,'Running'),'on'))  %Wait here until charge cycle is complete 
  end
 
  fclose(fid);
  
  fprintf(log_fid,'%s  Ending Discharge Cycle # %d\n',datestr(now),ChargeCycle);
  fprintf(log_fid,'%s  Cycle # %d:  Low Rate Capacity = %f A-Hr to %f V at %f A\n',datestr(now),ChargeCycle,Capacity_Low,MinimumVoltage,DischargeCurrent);
  fprintf(log_fid,'%s  Cycle # %d:  High Rate Capacity = %f A-Hr to %f V at %f A\n\n',datestr(now),ChargeCycle,Capacity_High,MinimumVoltage,DischargeCurrent);

end

fclose(log_fid);


return

