tbf/TBF/BenchControl/TestMethods/FixedStartDeferredEvaluation/FixedStartDeferredEvaluationSeq.cs

1204 lines
60 KiB
C#

///
/// Copyright (c) 2017 Sensus Slovensko a.s.
///
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using log4net;
using TBF.BenchControl;
using TBF.Boxes;
using TBF.Resources;
using TBF.UiBridge;
namespace TBF.BenchControl.TestMethods.FixedStartDeferredEvaluation
{
public class FixedStartDeferredEvaluationSeq : Sequences.SequenceBase
{
private static readonly ILog log = LogManager.GetLogger(typeof(FixedStartDeferredEvaluationSeq));
/// <summary>
/// Fixed start mass collection method with deferred evaluation of images
/// </summary>
/// <param name="test">Test entity</param>
/// <returns>
/// Event.Done . . . . . . . OK
/// Event.MakeSecondPass . . OK, 2nd pass (=evaluation) required
/// Event.UiCmdStop . . . . Stopped by the user using the on-screen button STOP
/// Event.OpArgumentError . Target flow is out of range
/// Event.Error . . . . . . Unspecified error
/// </returns>
public IList<Event> Execute(Config.Entities.Test test, int repetitionNr, bool isLastRepetition,
bool compound,
HeatMeters.TestParams heatMetersTestParams,
Config.Entities.DebugMode debugLevel,
out IntermediateData intermediateData)
{
Elde.ControlBoardDev cBrd = StateMachine.ControlBoard;
IList<Event> e = new List<Event>(); /// Events from currently running operations
Event retVal = Event.Done;
checkUiOp = new Operations.CheckUIOp(true); /// Runs in more then one state
intermediateData = new IntermediateData
{
Compound = compound,
TestName = Results.Utils.GetTestName(test.Name, test.Repeats, repetitionNr),
TestPart = test.Part,
};
GenericDevices.IHasWMStatesForm dataEntryCmpnt = TbfComponents.FindComponent(StateMachine.Procedure.DataEntry) as GenericDevices.IHasWMStatesForm;
if (!(dataEntryCmpnt is GenericDevices.IDataEntryForCamera))
{
Bridge.OnError(this, "Wrong DataEntry component");
e.Add(Event.ConfigurationError);
return e;
}
float switchTimeStart = 0.001f; /// in seconds, original vale is 1 ms
float switchTimeEnd = 0.001f; /// in seconds, original vale is 1 ms
LtrPerRefPulse = outPath.FlowMeter.LtrPerPulse; /// [ltr/pulse], nominal flow in [m3/h]
/// Notes:
/// float timeHr = volumeLtr / (1000.0f * targetFlow);
/// float timeSec = 3600.0f * timeHr;
/// int refPulses = (int)(timeSec * (2000.0f * targetFlow / pOut.FlowMeter.NominalFlow));
int totalPulses = (int)(test.Volume / LtrPerRefPulse + 0.5f);
int rangeIx = 0; /// Default range, used for non-Elde flowmeters
if (outPath.FlowMeter is Elde.FlowMeter.FlowMeter)
{
Elde.FlowMeter.FlowMeter eldeFM = outPath.FlowMeter as Elde.FlowMeter.FlowMeter;
rangeIx = -1; /// Indicates invalid range
for (int r = 0; r <= 5; r++)
{
if (eldeFM.RangeEnabled(r) && eldeFM.GetTempLo(r) <= test.TempLimLo
&& eldeFM.GetTempHi(r) >= test.TempLimHi)
{
rangeIx = r;
}
}
if (rangeIx == -1)
{
Bridge.OnError(this, Strings.Flow_meter_temperature_range_does_not_fit_this_test_conditions);
retVal = Event.UiCmdStop;
goto stopTestWOTransitionAfter;
}
}
processDataLoggingOp = new TBF.BenchControl.Operations.ProcessDataLoggingOp(processDataLogger, this, heatMetersTestParams != null);
if (test.Volume >= outPath.Scale.Capacity * Constants.TankFullFactor)
{
Bridge.OnError(this, Strings.Test_volume_exceeds_the_scale_capacity);
e.Add(Event.ConfigurationError);
return e;
}
//====================================
loop:
/// Start the test, initialize test results
Bridge.OnTestSelected(this, new TestSelectedEventArgs(test, repetitionNr, inPath, benchPath, outPath, sensPath, totalPulses));
string testName = Results.Utils.GetTestName(test.Name, test.Repeats, repetitionNr);
///
/// Optionally display prompt to emerge temperature meters to appropriate baths for heat meters test
///
IOperation heatMetersPromptOp = null;
if (heatMetersTestParams != null && !string.IsNullOrEmpty(heatMetersTestParams.Prompt))
{
/// Make sure the CycleBeginForm is closed
if (UIFlowControl.Stop == WaitBeginFormClosed()) goto stopTest;
heatMetersPromptOp = new Operations.MessageBoxOp(heatMetersTestParams.Prompt);
}
if (!test.DoDraining)
{
///
/// Measure the weight in case there is no unconditional draining
///
State.Create(string.Format("{0}({1}) : Measuring mass of water in the tank", test.Method, test.Name))
.AddOperation(checkUiOp)
.AddOperation(outPath.Scale.ReadMassOp(ref Mass))
.AddOperation(heatMetersPromptOp)
.EnterState();
do
{
e = StateMachine.WaitRunDevsRunOps();
Bridge.OnTestProgress(this, new TestProgressEventArgs(test, repetitionNr, Config.Entities.Progress.JustStarted));
if (e.Contains(Event.Error)) { retVal = Event.Error; goto stopTest; }
if (TestAndLogUiCmdStop(test, e)) { retVal = Event.UiCmdStop; goto stopTest; }
}
while (!e.Contains(Event.BalanceDone));
}
///
/// Skip draining in case there is enough room in the tank
///
if (test.DoDraining || (Mass.Val + test.Volume >= outPath.Scale.Capacity * Constants.TankFullFactor))
{
///
/// Drain the water tank
///
switch (DrainTheTank(outPath.Scale.DrainValve, outPath.Scale, heatMetersPromptOp))
{
case Event.Error: { retVal = Event.Error; goto stopTest; }
case Event.UiCmdStop: { retVal = Event.UiCmdStop; goto stopTest; }
}
}
///
/// Make sure the drain valve is closed
///
State.Create(string.Format("{0}({1}) : Make sure the drain valve is closed", test.Method, test.Name))
.AddOperation(checkUiOp)
.AddOperation(outPath.Scale.ReadMassOp(ref Mass))
.AddOperation(heatMetersPromptOp)
.AddOperation(StateMachine.ControlBoard.UpdateTankWeightOp())
.AddOperation(StateMachine.ControlBoard.SetValvesOp(null, outPath.Scale.DrainValve))
.EnterState();
do
{
e = StateMachine.WaitRunDevsRunOps();
Bridge.OnTestProgress(this, new TestProgressEventArgs(test, repetitionNr, Config.Entities.Progress.JustStarted));
if (e.Contains(Event.Error)) { retVal = Event.Error; goto stopTest; }
if (TestAndLogUiCmdStop(test, e)) { retVal = Event.UiCmdStop; goto stopTest; }
}
while (!e.Contains(Event.ValvesSet) || !e.Contains(Event.BalanceDone));
//------------------------------------------------
Bridge.OnActivity(this, Strings.Starting_the_pump);
//------------------------------------------------
Bridge.OnTestProgress(this, new TestProgressEventArgs(test, repetitionNr, Config.Entities.Progress.FlowSetting));
int flowSetTime0 = StateMachine.Time;
if (inPath.Pump is GenericDevices.IPumpFM) (inPath.Pump as GenericDevices.IPumpFM).TurnOn(test.PumpPower);
///
State.Create(string.Format("{0}({1}) : Starting the pump", test.Method, test.Name))
.AddOperation(checkUiOp)
.AddOperation(StateMachine.ControlBoard.UpdateTankWeightOp())
// .AddOperation(new Operations.SetAllRegulValvesOp(inPath.RegulValves, inPath.RegulValvesPct, 60))
.AddOperation(heatMetersPromptOp)
.AddOperation(inPath.Pump != null ? cBrd.SetValvesOp(inPath.Pump, null) : null)
.EnterState();
do
{
e = StateMachine.WaitRunDevsRunOps();
Bridge.OnProcessData(this, new ProcessDataEventArgs(test, repetitionNr, Config.Entities.Progress.FlowSetting));
Bridge.OnTestProgress(this, new TestProgressEventArgs(test, repetitionNr, Config.Entities.Progress.FlowSetting));
if (TestAndLogUiCmdStop(test, e)) { retVal = Event.UiCmdStop; goto stopTest; }
if (e.Contains(Event.Error)) { retVal = Event.Error; goto stopTest; }
}
while (e.Contains(Event.ValvesBusy) /* || !e.Contains(Event.AllPositionsReached)*/);
if (test.TimePump2StartV > 0)
{
State.Create(string.Format("{0}({1}) : Waiting after the pump started", test.Method, test.Name))
.AddOperation(checkUiOp)
.AddOperation(new Operations.TimerOp(test.TimePump2StartV))
.AddOperation(StateMachine.ControlBoard.UpdateTankWeightOp())
.AddOperation(heatMetersPromptOp)
.EnterState();
do
{
e = StateMachine.WaitRunDevsRunOps();
Bridge.OnProcessData(this, new ProcessDataEventArgs(test, repetitionNr, Config.Entities.Progress.FlowSetting));
Bridge.OnTestProgress(this, new TestProgressEventArgs(test, repetitionNr, Config.Entities.Progress.FlowSetting));
if (TestAndLogUiCmdStop(test, e)) { retVal = Event.UiCmdStop; goto stopTest; }
}
while (!e.Contains(Event.TimerExpired));
}
if (benchPath.StopBFValve != null)
{
State.Create(string.Format("{0}({1}) : Opening the stop backflow valve", test.Method, test.Name))
.AddOperation(checkUiOp)
.AddOperation(StateMachine.ControlBoard.SetValvesOp(benchPath.StopBFValve, null))
.AddOperation(StateMachine.ControlBoard.UpdateTankWeightOp())
.AddOperation(heatMetersPromptOp)
.EnterState();
do
{
e = StateMachine.WaitRunDevsRunOps();
if (TestAndLogUiCmdStop(test, e)) { retVal = Event.UiCmdStop; goto stopTest; }
if (e.Contains(Event.Error)) { retVal = Event.Error; goto stopTest; }
}
while (!e.Contains(Event.ValvesSet));
}
if (test.TimeBeforeFlow > 0)
{
State.Create(string.Format("{0}({1}) : Waiting before flow setting process starts", test.Method, test.Name))
.AddOperation(checkUiOp)
.AddOperation(new Operations.TimerOp(test.TimeBeforeFlow))
.AddOperation(StateMachine.ControlBoard.UpdateTankWeightOp())
.AddOperation(heatMetersPromptOp)
.EnterState();
do
{
e = StateMachine.WaitRunDevsRunOps();
Bridge.OnProcessData(this, new ProcessDataEventArgs(test, repetitionNr, Config.Entities.Progress.FlowSetting));
Bridge.OnTestProgress(this, new TestProgressEventArgs(test, repetitionNr, Config.Entities.Progress.FlowSetting));
if (TestAndLogUiCmdStop(test, e)) { retVal = Event.UiCmdStop; goto stopTest; }
}
while (!e.Contains(Event.TimerExpired));
}
setting_flow:
//------------------------------------------------
Bridge.OnActivity(this, Strings.Setting_the_flow);
//------------------------------------------------
if (inPath.Pump is GenericDevices.IPumpFM)
{
(inPath.Pump as GenericDevices.IPumpFM).TurnOn(test.PumpPower);
}
///
State.Create(string.Format("{0}({1}) : Pump on", test.Method, test.Name))
.AddOperation(checkUiOp)
.AddOperation(StateMachine.ControlBoard.SetValvesOp(inPath.Pump, null))
.AddOperation(heatMetersPromptOp)
.EnterState();
do
{
e = StateMachine.WaitRunDevsRunOps();
Bridge.OnProcessData(this, new ProcessDataEventArgs(test, repetitionNr, Config.Entities.Progress.FlowSetting));
Bridge.OnTestProgress(this, new TestProgressEventArgs(test, repetitionNr, Config.Entities.Progress.FlowSetting));
if (TestAndLogUiCmdStop(test, e)) { retVal = Event.UiCmdStop; goto stopTest; }
}
while (e.Contains(Event.ValvesBusy));
///
State.Create(string.Format("{0}({1}) : Start valve open", test.Method, test.Name))
.AddOperation(checkUiOp)
.AddOperation(new TBF.BenchControl.Elde.SetValvesOp(cBrd, false, outPath))
.AddOperation(heatMetersPromptOp)
.EnterState();
do
{
e = StateMachine.WaitRunDevsRunOps();
Bridge.OnProcessData(this, new ProcessDataEventArgs(test, repetitionNr, Config.Entities.Progress.FlowSetting));
Bridge.OnTestProgress(this, new TestProgressEventArgs(test, repetitionNr, Config.Entities.Progress.FlowSetting));
if (TestAndLogUiCmdStop(test, e)) { retVal = Event.UiCmdStop; goto stopTest; }
}
while (e.Contains(Event.ValvesBusy));
//--------------------------------
State.Create(string.Format("{0}({1}) : Setting the flow", test.Method, test.Name))
.AddOperation(checkUiOp)
.AddOperation(outPath.RegulValve.SetFlowOp(outPath.FlowMeter, test.Qfrom, test.Qto, outPath.PidCoef, RefFlow, 600)) /// timeout = 10 min.
.AddOperation(heatMetersPromptOp)
.EnterState();
do
{
e = StateMachine.WaitRunDevsRunOps();
Bridge.OnProcessData(this, new ProcessDataEventArgs(test, repetitionNr, Config.Entities.Progress.FlowSetting));
Bridge.OnTestProgress(this, new TestProgressEventArgs(test, repetitionNr, Config.Entities.Progress.FlowSetting));
if (e.Contains(Event.OpArgumentError)) { retVal = Event.OpArgumentError; goto stopTest; }
if (TestAndLogUiCmdStop(test, e)) { retVal = Event.UiCmdStop; goto stopTest; }
if (e.Contains(Event.RegulValveTimeOut))
{
Bridge.OnError(this, Strings.Flow_adjustment_failed);
retVal = Event.UiCmdStop;
goto stopTest;
}
if (e.Contains(Event.Next)) goto flow_set;
}
while (!e.Contains(Event.FlowReached));
flow_set:
int flowSetTime = StateMachine.Time - flowSetTime0;
if (heatMetersTestParams != null && heatMetersPath != null)
{
//---------------------------------------------------
Bridge.OnActivity(this, Strings.Setting_temperature);
//---------------------------------------------------
int lastTimeSec = StateMachine.Time;
double Tw_last = 0;
double Tc_last = 0;
State.Create(string.Format("{0}({1}) : Checking if the temperature is stable", test.Method, test.Name))
.AddOperation(checkUiOp)
.AddOperation(heatMetersPath.TMeterRefWarm1.ReadTempOp(ref TempRefHi1))
.AddOperation(heatMetersPath.TMeterRefWarm2.ReadTempOp(ref TempRefHi2))
.AddOperation(heatMetersPath.TMeterRefCold1.ReadTempOp(ref TempRefLo1))
.AddOperation(heatMetersPath.TMeterRefCold2.ReadTempOp(ref TempRefLo2))
.AddOperation(heatMetersPromptOp)
.EnterState();
do
{
e = StateMachine.WaitRunDevsRunOps();
if (TestAndLogUiCmdStop(test, e)) { retVal = Event.UiCmdStop; goto stopTest; }
if (e.Contains(Event.Next)) goto temperature_set;
if (TempRefHi1.Val != 0 && TempRefHi2.Val != 0 && TempRefLo1.Val != 0 && TempRefLo2.Val != 0)
{
if (StateMachine.Time - lastTimeSec > 10 || StateMachine.Time - lastTimeSec < 0)
{
double Tw = (TempRefHi1.Val + TempRefHi2.Val) / 2;
double Tc = (TempRefLo1.Val + TempRefLo2.Val) / 2;
if (heatMetersTestParams.TempWarmLo <= Tw && Tw <= heatMetersTestParams.TempWarmHi &&
heatMetersTestParams.TempColdLo <= Tc && Tc <= heatMetersTestParams.TempColdHi &&
Math.Abs(Tw - Tw_last) <= heatMetersTestParams.ChangeInTimeWarm &&
Math.Abs(Tc - Tc_last) <= heatMetersTestParams.ChangeInTimeCold &&
Math.Abs(TempRefHi1.Val - TempRefHi2.Val) <= heatMetersTestParams.DeltaTempWarm &&
Math.Abs(TempRefLo1.Val - TempRefLo2.Val) <= heatMetersTestParams.DeltaTempCold)
{
goto temperature_set;
}
lastTimeSec = StateMachine.Time;
Tw_last = Tw;
Tc_last = Tc;
}
}
}
while (true);
}
else if (test.DoControlWaterTemp && benchPath.TempMtrUp != null && benchPath.TempMtrDown != null)
{
//---------------------------------------------------
Bridge.OnActivity(this, Strings.Setting_temperature);
//---------------------------------------------------
State.Create(string.Format("{0}({1}) : Wait until the water temperature is within limits", test.Method, test.Name))
.AddOperation(checkUiOp)
.AddOperation(benchPath.TempMtrUp.ReadTempOp(ref TempUp))
.AddOperation(benchPath.TempMtrDown.ReadTempOp(ref TempDown))
.EnterState();
do
{
e = StateMachine.WaitRunDevsRunOps();
if (TestAndLogUiCmdStop(test, e)) { retVal = Event.UiCmdStop; goto stopTest; }
if (e.Contains(Event.Next)) goto temperature_set;
if (TempUp.Val >= test.TempLimLo && TempUp.Val <= test.TempLimHi &&
TempDown.Val >= test.TempLimLo && TempDown.Val <= test.TempLimHi)
{
goto temperature_set;
}
}
while (true);
}
temperature_set:
//-----------------------------------------------------------------
Bridge.OnActivity(this, Strings.Stopping_flow_for_the_fixed_start);
//-----------------------------------------------------------------
State.Create(string.Format("{0}({1}) : Closing the start/stop valve before the fixed start test", test.Method, test.Name))
.AddOperation(checkUiOp)
.AddOperation(new TBF.BenchControl.Elde.SetValvesOp(cBrd, true, outPath))
.AddOperation(heatMetersPath == null ? null : heatMetersPath.TMeterRefWarm1.ReadTempOp(ref TempRefHi1))
.AddOperation(heatMetersPath == null ? null : heatMetersPath.TMeterRefWarm2.ReadTempOp(ref TempRefHi2))
.AddOperation(heatMetersPath == null ? null : heatMetersPath.TMeterRefCold1.ReadTempOp(ref TempRefLo1))
.AddOperation(heatMetersPath == null ? null : heatMetersPath.TMeterRefCold2.ReadTempOp(ref TempRefLo2))
.AddOperation(StateMachine.ControlBoard.UpdateTankWeightOp())
.EnterState();
do
{
e = StateMachine.WaitRunDevsRunOps();
if (e.Contains(Event.Error)) { retVal = Event.Error; goto stopTest; }
}
while (!e.Contains(Event.ValvesSet));
int time = StateMachine.Time;
double currentFlow = RefFlow.Val;
//------------------------------------------------
Bridge.OnActivity(this, Strings.Measuring_the_weight);
//------------------------------------------------
if (test.TimeFlow2Mass > 0)
{
State.Create(string.Format("{0}({1}) : Waiting before 1st mass measurement", test.Method, test.Name))
.AddOperation(checkUiOp)
.AddOperation(heatMetersPath == null ? null : heatMetersPath.TMeterRefWarm1.ReadTempOp(ref TempRefHi1))
.AddOperation(heatMetersPath == null ? null : heatMetersPath.TMeterRefWarm2.ReadTempOp(ref TempRefHi2))
.AddOperation(heatMetersPath == null ? null : heatMetersPath.TMeterRefCold1.ReadTempOp(ref TempRefLo1))
.AddOperation(heatMetersPath == null ? null : heatMetersPath.TMeterRefCold2.ReadTempOp(ref TempRefLo2))
.AddOperation(cBrd.UpdateTankWeightOp())
.AddOperation(new Operations.TimerOp(test.TimeFlow2Mass))
.EnterState();
do
{
e = StateMachine.WaitRunDevsRunOps();
if (e.Contains(Event.Error)) { retVal = Event.Error; goto stopTest; }
if (TestAndLogUiCmdStop(test, e)) { retVal = Event.UiCmdStop; goto stopTest; }
}
while (!e.Contains(Event.TimerExpired));
}
TestStartTime = DateTime.Now;
LogProcessDataTestInfo(processDataLogger, test.Procedure.Name, test.Name);
if (heatMetersPath == null) LogProcessDataHeader(processDataLogger, "Start mass");
else LogProcessDataHeaderHeatMeters(processDataLogger, "Start mass");
State.Create(string.Format("{0}({1}) : Measuring the start mass", test.Method, test.Name))
.AddOperation(checkUiOp)
.AddOperation(benchPath.TempMtrUp == null ? null : benchPath.TempMtrUp.ReadTempOp(ref TempUp))
.AddOperation(benchPath.TempMtrDown == null ? null : benchPath.TempMtrDown.ReadTempOp(ref TempDown))
.AddOperation(outPath.TempDiv == null ? null : outPath.TempDiv.ReadTempOp(ref TempDiv))
.AddOperation(benchPath.PressMtrUp == null ? null : benchPath.PressMtrUp.ReadPressureOp(ref PressUp))
.AddOperation(benchPath.PressMtrDown == null ? null : benchPath.PressMtrDown.ReadPressureOp(ref PressDown))
.AddOperation(benchPath.PressMtrDelta == null ? null : benchPath.PressMtrDelta.ReadPressureOp(ref PressDelta))
.AddOperation(heatMetersPath == null ? null : heatMetersPath.TMeterRefWarm1.ReadTempOp(ref TempRefHi1))
.AddOperation(heatMetersPath == null ? null : heatMetersPath.TMeterRefWarm2.ReadTempOp(ref TempRefHi2))
.AddOperation(heatMetersPath == null ? null : heatMetersPath.TMeterRefCold1.ReadTempOp(ref TempRefLo1))
.AddOperation(heatMetersPath == null ? null : heatMetersPath.TMeterRefCold2.ReadTempOp(ref TempRefLo2))
.AddOperation((StateMachine.Ambient != null)
? StateMachine.Ambient.ReadAmbientOp(AmbTemp, AmbPress, AmbHumi) : null)
.AddOperation(outPath.Scale.ReadStableMassOp(ref StartMass, test.MassRepeats, test.MassSpread, test.MassMethod))
.AddOperation(cBrd.UpdateTankWeightOp())
.AddOperation(processDataLoggingOp)
.EnterState();
do
{
e = StateMachine.WaitRunDevsRunOps();
if (e.Contains(Event.Error)) { retVal = Event.Error; goto stopTest; }
if (TestAndLogUiCmdStop(test, e)) { retVal = Event.UiCmdStop; goto stopTest; }
}
while (!e.Contains(Event.BalanceDone));
Mass.Val = StartMass.Val;
///
/// Grab start images
///
string fileName = string.Format("{0}-start.bmp", test.Name);
string[] startImages = new string[sensPath.RegisterReaders.Length];
///
if (debugLevel != Config.Entities.DebugMode.Simulate)
{
State state2 = State.Create(string.Format("{0}({1}) : Grabbing images", test.Method, test.Name))
.AddOperation(checkUiOp)
.AddOperation(heatMetersPath == null ? null : heatMetersPath.TMeterRefWarm1.ReadTempOp(ref TempRefHi1))
.AddOperation(heatMetersPath == null ? null : heatMetersPath.TMeterRefWarm2.ReadTempOp(ref TempRefHi2))
.AddOperation(heatMetersPath == null ? null : heatMetersPath.TMeterRefCold1.ReadTempOp(ref TempRefLo1))
.AddOperation(heatMetersPath == null ? null : heatMetersPath.TMeterRefCold2.ReadTempOp(ref TempRefLo2));
for (int i = 0; i < sensPath.RegisterReaders.Length; i++)
{
GenericDevices.IRoiForFixedStart roi = sensPath.RegisterReaders[i] as GenericDevices.IRoiForFixedStart;
if (roi != null)
{
string directory = Path.Combine(Program.TempImagesDir, BatchRslts.Batch.BatchNr.ToString(), (i + 1).ToString());
Directory.CreateDirectory(directory);
startImages[i] = Path.Combine(directory, fileName);
state2.AddOperation(roi.GrabImageOp(startImages[i]));
}
}
state2.EnterState();
do
{
e = StateMachine.WaitRunDevsRunOps();
Bridge.OnTestProgress(this, new TestProgressEventArgs(test, repetitionNr, Config.Entities.Progress.Test));
if (e.Contains(Event.Error)) { retVal = Event.Error; break; }
if (TestAndLogUiCmdStop(test, e)) { retVal = Event.UiCmdStop; break; }
}
while (e.Contains(Event.CameraBusy));
intermediateData.StartImages = startImages;
if ((dataEntryCmpnt is GenericDevices.IDataEntryForCamera) && (dataEntryCmpnt as GenericDevices.IDataEntryForCamera).SaveImages)
{
/// SaveImages==true ... copy images to the directory that will be archived at the end of the cycle
for (int i = 0; i < sensPath.RegisterReaders.Length; i++)
{
GenericDevices.IRoiForFixedStart roi = sensPath.RegisterReaders[i] as GenericDevices.IRoiForFixedStart;
if (roi != null)
{
string srcDir = Path.Combine(Program.TempImagesDir, BatchRslts.Batch.BatchNr.ToString(), (i + 1).ToString());
string destDir = Path.Combine(Program.ImagesDir, BatchRslts.Batch.BatchNr.ToString(), (i + 1).ToString());
try
{
if (File.Exists(Path.Combine(srcDir, fileName)))
{
Directory.CreateDirectory(destDir);
File.Copy(Path.Combine(srcDir, fileName), Path.Combine(destDir, fileName), true);
}
}
catch (Exception exc)
{
log.ErrorFormat("Failed to copy image {0} to {1}: {2}", fileName, destDir, exc.Message);
}
}
}
}
}
else
{
for (int i = 0; i < sensPath.RegisterReaders.Length; i++)
{
GenericDevices.IRoiForFixedStart roi = sensPath.RegisterReaders[i] as GenericDevices.IRoiForFixedStart;
if (roi != null)
{
string directory = Path.Combine(Program.TempImagesDir, BatchRslts.Batch.BatchNr.ToString(), (i + 1).ToString());
Directory.CreateDirectory(directory);
startImages[i] = Path.Combine(directory, fileName);
File.Copy(string.Format("C:\\TBF\\SampleImages\\{0}", fileName), startImages[i], true);
}
}
}
intermediateData.StartImages = startImages;
///
if ((dataEntryCmpnt is GenericDevices.IDataEntryForCamera) && (dataEntryCmpnt as GenericDevices.IDataEntryForCamera).SaveImages)
{
/// SaveImages==true ... copy images to the directory that will be archived at the end of the cycle
for (int i = 0; i < sensPath.RegisterReaders.Length; i++)
{
GenericDevices.IRoiForFixedStart roi = sensPath.RegisterReaders[i] as GenericDevices.IRoiForFixedStart;
if (roi != null)
{
string srcDir = Path.Combine(Program.TempImagesDir, BatchRslts.Batch.BatchNr.ToString(), (i + 1).ToString());
string destDir = Path.Combine(Program.ImagesDir, BatchRslts.Batch.BatchNr.ToString(), (i + 1).ToString());
try
{
if (File.Exists(Path.Combine(srcDir, fileName)))
{
Directory.CreateDirectory(destDir);
File.Copy(Path.Combine(srcDir, fileName), Path.Combine(destDir, fileName), true);
}
}
catch (Exception exc)
{
log.ErrorFormat("Failed to copy image {0} to {1}: {2}", fileName, destDir, exc.Message);
}
}
}
}
if (heatMetersPath == null) LogProcessDataHeader(processDataLogger, "Measurement");
else LogProcessDataHeaderHeatMeters(processDataLogger, "Measurement");
//------------------------------------------------
Bridge.OnActivity(this, Strings.Test_in_progress);
//------------------------------------------------
State.Create(string.Format("{0}({1}) : Starting the test", test.Method, test.Name))
.AddOperation(checkUiOp)
.AddOperation(benchPath.TempMtrUp == null ? null : benchPath.TempMtrUp.ReadTempOp(ref TempUp))
.AddOperation(benchPath.TempMtrDown == null ? null : benchPath.TempMtrDown.ReadTempOp(ref TempDown))
.AddOperation(outPath.TempDiv == null ? null : outPath.TempDiv.ReadTempOp(ref TempDiv))
.AddOperation(benchPath.PressMtrUp == null ? null : benchPath.PressMtrUp.ReadPressureOp(ref PressUp))
.AddOperation(benchPath.PressMtrDown == null ? null : benchPath.PressMtrDown.ReadPressureOp(ref PressDown))
.AddOperation(benchPath.PressMtrDelta == null ? null : benchPath.PressMtrDelta.ReadPressureOp(ref PressDelta))
.AddOperation(heatMetersPath == null ? null : heatMetersPath.TMeterRefWarm1.ReadTempOp(ref TempRefHi1))
.AddOperation(heatMetersPath == null ? null : heatMetersPath.TMeterRefWarm2.ReadTempOp(ref TempRefHi2))
.AddOperation(heatMetersPath == null ? null : heatMetersPath.TMeterRefCold1.ReadTempOp(ref TempRefLo1))
.AddOperation(heatMetersPath == null ? null : heatMetersPath.TMeterRefCold2.ReadTempOp(ref TempRefLo2))
.AddOperation(cBrd.StartMeasurementOp(outPath, Elde.TestMethods.Diverter | Elde.TestMethods.Synchro,
test.Qfrom, test.Qto, 2 * totalPulses, new int[] { (int)test.TolerRed, }))
.EnterState();
do
{
e = StateMachine.WaitRunDevsRunOps();
if (e.Contains(Event.Error)) { retVal = Event.Error; goto stopTest; }
if (TestAndLogUiCmdStop(test, e)) { retVal = Event.UiCmdStop; goto stopTest; }
}
while (!e.Contains(Event.MeasurementStarted));
StartTime = (double)StateMachine.Time;
State.Create(string.Format("{0}({1}) : Opening the start/stop valve at the beginning of the fixed start test", test.Method, test.Name))
.AddOperation(checkUiOp)
.AddOperation(benchPath.TempMtrUp == null ? null : benchPath.TempMtrUp.ReadTempOp(ref TempUp))
.AddOperation(benchPath.TempMtrDown == null ? null : benchPath.TempMtrDown.ReadTempOp(ref TempDown))
.AddOperation(outPath.TempDiv == null ? null : outPath.TempDiv.ReadTempOp(ref TempDiv))
.AddOperation(benchPath.PressMtrUp == null ? null : benchPath.PressMtrUp.ReadPressureOp(ref PressUp))
.AddOperation(benchPath.PressMtrDown == null ? null : benchPath.PressMtrDown.ReadPressureOp(ref PressDown))
.AddOperation(benchPath.PressMtrDelta == null ? null : benchPath.PressMtrDelta.ReadPressureOp(ref PressDelta))
.AddOperation(heatMetersPath == null ? null : heatMetersPath.TMeterRefWarm1.ReadTempOp(ref TempRefHi1))
.AddOperation(heatMetersPath == null ? null : heatMetersPath.TMeterRefWarm2.ReadTempOp(ref TempRefHi2))
.AddOperation(heatMetersPath == null ? null : heatMetersPath.TMeterRefCold1.ReadTempOp(ref TempRefLo1))
.AddOperation(heatMetersPath == null ? null : heatMetersPath.TMeterRefCold2.ReadTempOp(ref TempRefLo2))
.AddOperation(new TBF.BenchControl.Elde.SetValvesOp(cBrd, false, outPath))
.AddOperation(StateMachine.ControlBoard.UpdateTankWeightOp())
.EnterState();
do
{
e = StateMachine.WaitRunDevsRunOps();
if (e.Contains(Event.Error)) { retVal = Event.Error; goto stopTest; }
}
while (!e.Contains(Event.ValvesSet));
switchTimeStart = 0.001f * cBrd.ValveOpenCloseTime;
log.WarnFormat("Start valve switch time on test start = {0} ms", cBrd.ValveOpenCloseTime);
/// Measurement loop - preparation
readRegistersOp = new Operations.ReadMoreRegistersOp(sensPath.RegisterReaders);
queryEnd1 = cBrd.QueryMeasurementEndOp();
queryEnd2 = cBrd.QueryMeasurementEndOp();
StartNewStatistics(StateMachine.Time, BatchRslts.Batch.BatchNr, test.Name, repetitionNr, Math.Max((int)(test.TstTime / 10), 5));
int estimtdEndTime = StateMachine.Time + (int)test.TstTime;
/// Measurement loop - begin
do
{
//--------------------------------
switch (ReadRegistersTempPressAmbient(null, true))
{
case Event.Error:
retVal = Event.Error;
goto stopTest;
case Event.UiCmdStop:
retVal = Event.UiCmdStop;
goto stopTest;
case Event.MeasurementCompleted:
goto test_completed;
}
int remainingTime = Math.Max(estimtdEndTime - StateMachine.Time, 0);
if (remainingTime > 60)
{
Bridge.OnActivity(this, string.Format("{0} ... {1} {2} {3} {4}", Strings.Test_in_progress, remainingTime / 60, "min", remainingTime % 60, Strings.sec));
}
else
{
Bridge.OnActivity(this, string.Format("{0} ... {1} s", Strings.Test_in_progress, remainingTime));
}
RefFreq.Val = cBrd.ReferenceFreq;
RefFlow.Val = cBrd.ReferenceFlow;
UpdateAllStatistics(StateMachine.Time);
if (heatMetersTestParams != null)
{
if (lastEnergyUpdateTime == 0)
{
lastEnergyUpdateTime = StateMachine.Time;
}
else
{
//double deltaTime = (double)(StateMachine.Time - lastEnergyUpdateTime);
double T_in = (TempRefHi1.Val + TempRefHi2.Val) / 2; /// [°C]
double T_out = (TempRefLo1.Val + TempRefLo2.Val) / 2; /// [°C]
double deltaVolume = LtrPerRefPulse * RefPulsesDelta; /// [l]
double deltaEnergy = (0.001 * deltaVolume) * (T_in - T_out) * Config.Formulas.HeatCoefficientWater(16, T_in, T_out, heatMetersTestParams.FlowMeasuredAtHiTempPipe); /// [J] = [m3] * [K] * [J/(m3 K)]
Energy.Update(deltaEnergy);
VolumeForEnergy.Update(deltaVolume);
lastEnergyUpdateTime = StateMachine.Time;
}
}
if (compound)
{
/// TODO: Reimplement for combined meters
//for (int i = 0; i < Config.Data.CompoundWMsCount; i++)
//{
// data.TestResult.CombinedMeters[i].VolumeMeter = data.TestResult.Meters[2 * i].VolumeMeter
// + data.TestResult.Meters[2 * i + 1].VolumeMeter;
// if (data.Volume.Valid)
// {
// data.TestResult.CombinedMeters[i].VolumeErrorPct =
// Formulas.ErrorFromVolumes(data.TestResult.CombinedMeters[i].VolumeMeter, data.Volume.Val);
// }
//}
}
Bridge.OnProcessData(this, new ProcessDataEventArgs(test, repetitionNr, Config.Entities.Progress.Test));
Bridge.OnTestProgress(this, new TestProgressEventArgs(test, repetitionNr, Config.Entities.Progress.Test));
}
while (cBrd.EtPulses(0) < totalPulses);
/// Measurement loop - end
test_completed:
StopRecordingStatistics();
EndTime = (double)StateMachine.Time;
State.Create(string.Format("{0}({1}) : Closing the start/stop valve at the end of the fixed start test", test.Method, test.Name))
.AddOperation(checkUiOp)
.AddOperation(benchPath.TempMtrUp == null ? null : benchPath.TempMtrUp.ReadTempOp(ref TempUp))
.AddOperation(benchPath.TempMtrDown == null ? null : benchPath.TempMtrDown.ReadTempOp(ref TempDown))
.AddOperation(outPath.TempDiv == null ? null : outPath.TempDiv.ReadTempOp(ref TempDiv))
.AddOperation(benchPath.PressMtrUp == null ? null : benchPath.PressMtrUp.ReadPressureOp(ref PressUp))
.AddOperation(benchPath.PressMtrDown == null ? null : benchPath.PressMtrDown.ReadPressureOp(ref PressDown))
.AddOperation(benchPath.PressMtrDelta == null ? null : benchPath.PressMtrDelta.ReadPressureOp(ref PressDelta))
.AddOperation(heatMetersPath == null ? null : heatMetersPath.TMeterRefWarm1.ReadTempOp(ref TempRefHi1))
.AddOperation(heatMetersPath == null ? null : heatMetersPath.TMeterRefWarm2.ReadTempOp(ref TempRefHi2))
.AddOperation(heatMetersPath == null ? null : heatMetersPath.TMeterRefCold1.ReadTempOp(ref TempRefLo1))
.AddOperation(heatMetersPath == null ? null : heatMetersPath.TMeterRefCold2.ReadTempOp(ref TempRefLo2))
.AddOperation(new TBF.BenchControl.Elde.SetValvesOp(cBrd, true, outPath))
.AddOperation(StateMachine.ControlBoard.UpdateTankWeightOp())
.EnterState();
do
{
e = StateMachine.WaitRunDevsRunOps();
if (e.Contains(Event.Error)) { retVal = Event.Error; goto stopTest; }
}
while (e.Contains(Event.ValvesBusy));
switchTimeEnd = 0.001f * cBrd.ValveOpenCloseTime;
log.WarnFormat("Start valve switch time on test end = {0} ms", cBrd.ValveOpenCloseTime);
State.Create(string.Format("{0}({1}) : Waiting before 2nd mass measurement", test.Method, test.Name))
.AddOperation(checkUiOp)
.AddOperation(benchPath.TempMtrUp == null ? null : benchPath.TempMtrUp.ReadTempOp(ref TempUp))
.AddOperation(benchPath.TempMtrDown == null ? null : benchPath.TempMtrDown.ReadTempOp(ref TempDown))
.AddOperation(outPath.TempDiv == null ? null : outPath.TempDiv.ReadTempOp(ref TempDiv))
.AddOperation(benchPath.PressMtrUp == null ? null : benchPath.PressMtrUp.ReadPressureOp(ref PressUp))
.AddOperation(benchPath.PressMtrDown == null ? null : benchPath.PressMtrDown.ReadPressureOp(ref PressDown))
.AddOperation(benchPath.PressMtrDelta == null ? null : benchPath.PressMtrDelta.ReadPressureOp(ref PressDelta))
.AddOperation(heatMetersPath == null ? null : heatMetersPath.TMeterRefWarm1.ReadTempOp(ref TempRefHi1))
.AddOperation(heatMetersPath == null ? null : heatMetersPath.TMeterRefWarm2.ReadTempOp(ref TempRefHi2))
.AddOperation(heatMetersPath == null ? null : heatMetersPath.TMeterRefCold1.ReadTempOp(ref TempRefLo1))
.AddOperation(heatMetersPath == null ? null : heatMetersPath.TMeterRefCold2.ReadTempOp(ref TempRefLo2))
.AddOperation((StateMachine.Ambient != null)
? StateMachine.Ambient.ReadAmbientOp(AmbTemp, AmbPress, AmbHumi) : null)
.AddOperation(outPath.Scale.ReadMassOp(ref Mass))
.AddOperation(cBrd.UpdateTankWeightOp())
.AddOperation(processDataLoggingOp)
.AddOperation(new Operations.TimerOp(test.TimeStop2Mass))
.EnterState();
do
{
e = StateMachine.WaitRunDevsRunOps();
if (e.Contains(Event.Error)) { retVal = Event.Error; goto stopTest; }
if (TestAndLogUiCmdStop(test, e)) { retVal = Event.UiCmdStop; goto stopTest; }
}
while (!e.Contains(Event.TimerExpired));
if (heatMetersPath == null) LogProcessDataHeader(processDataLogger, "End mass");
else LogProcessDataHeaderHeatMeters(processDataLogger, "End mass");
//------------------------------------------------
Bridge.OnActivity(this, Strings.Measuring_the_weight);
//------------------------------------------------
State.Create(string.Format("{0}({1}) : Measuring the end mass", test.Method, test.Name))
.AddOperation(checkUiOp)
.AddOperation(benchPath.TempMtrUp == null ? null : benchPath.TempMtrUp.ReadTempOp(ref TempUp))
.AddOperation(benchPath.TempMtrDown == null ? null : benchPath.TempMtrDown.ReadTempOp(ref TempDown))
.AddOperation(outPath.TempDiv == null ? null : outPath.TempDiv.ReadTempOp(ref TempDiv))
.AddOperation(benchPath.PressMtrUp == null ? null : benchPath.PressMtrUp.ReadPressureOp(ref PressUp))
.AddOperation(benchPath.PressMtrDown == null ? null : benchPath.PressMtrDown.ReadPressureOp(ref PressDown))
.AddOperation(benchPath.PressMtrDelta == null ? null : benchPath.PressMtrDelta.ReadPressureOp(ref PressDelta))
.AddOperation(heatMetersPath == null ? null : heatMetersPath.TMeterRefWarm1.ReadTempOp(ref TempRefHi1))
.AddOperation(heatMetersPath == null ? null : heatMetersPath.TMeterRefWarm2.ReadTempOp(ref TempRefHi2))
.AddOperation(heatMetersPath == null ? null : heatMetersPath.TMeterRefCold1.ReadTempOp(ref TempRefLo1))
.AddOperation(heatMetersPath == null ? null : heatMetersPath.TMeterRefCold2.ReadTempOp(ref TempRefLo2))
.AddOperation((StateMachine.Ambient != null)
? StateMachine.Ambient.ReadAmbientOp(AmbTemp, AmbPress, AmbHumi) : null)
.AddOperation(outPath.Scale.ReadStableMassOp(ref EndMass, test.MassRepeats, test.MassSpread, test.MassMethod))
.AddOperation(cBrd.UpdateTankWeightOp())
.AddOperation(processDataLoggingOp)
.EnterState();
do
{
e = StateMachine.WaitRunDevsRunOps();
if (e.Contains(Event.Error)) { retVal = Event.Error; goto stopTest; }
if (TestAndLogUiCmdStop(test, e)) { retVal = Event.UiCmdStop; goto stopTest; }
}
while (!e.Contains(Event.BalanceDone));
///
TestEndTime = DateTime.Now;
State.Create(string.Format("{0}({1}) : Stopping diverter, gate, etc.", test.Method, test.Name))
.AddOperation(checkUiOp)
.AddOperation(cBrd.StopPreviousOp())
.EnterState();
do
{
e = StateMachine.WaitRunDevsRunOps();
if (TestAndLogUiCmdStop(test, e)) { retVal = Event.UiCmdStop; goto stopTest; }
}
while (!e.Contains(Event.PreviousStopped));
double massStart = Config.Formulas.CorrectedValue(StartMass.Val, outPath.Scale.Corrections);
double massEnd = Config.Formulas.CorrectedValue(EndMass.Val, outPath.Scale.Corrections);
double densityOut = Config.Formulas.WaterDensityFromTemp(TempDownStat.Average, Program.LocalSettings.RealDensity, Program.LocalSettings.AtTemperature); /// [kg/m3]
double buoyancy = Config.Formulas.Buoyancy();
double volumeCTV = 1000.0 * buoyancy * (massEnd - massStart) / densityOut;
if (debugLevel == Config.Entities.DebugMode.Simulate) volumeCTV = test.Volume;
double refEnergy = Energy.Sum * volumeCTV / VolumeForEnergy.Sum; /// [J]=[J]*[l]/[l]
///
/// Grab END images
///
fileName = string.Format("{0}-end.bmp", test.Name);
string[] endImages = new string[sensPath.RegisterReaders.Length];
///
if (debugLevel != Config.Entities.DebugMode.Simulate)
{
State state2 = State.Create(string.Format("{0}({1}) : Grabbing images", test.Method, test.Name))
.AddOperation(checkUiOp)
.AddOperation(heatMetersPath == null ? null : heatMetersPath.TMeterRefWarm1.ReadTempOp(ref TempRefHi1))
.AddOperation(heatMetersPath == null ? null : heatMetersPath.TMeterRefWarm2.ReadTempOp(ref TempRefHi2))
.AddOperation(heatMetersPath == null ? null : heatMetersPath.TMeterRefCold1.ReadTempOp(ref TempRefLo1))
.AddOperation(heatMetersPath == null ? null : heatMetersPath.TMeterRefCold2.ReadTempOp(ref TempRefLo2));
for (int i = 0; i < sensPath.RegisterReaders.Length; i++)
{
GenericDevices.IRoiForFixedStart roi = sensPath.RegisterReaders[i] as GenericDevices.IRoiForFixedStart;
if (roi != null)
{
string directory = Path.Combine(Program.TempImagesDir, BatchRslts.Batch.BatchNr.ToString(), (i + 1).ToString());
Directory.CreateDirectory(directory);
endImages[i] = Path.Combine(directory, fileName);
state2.AddOperation(roi.GrabImageOp(endImages[i]));
}
}
state2.EnterState();
do
{
e = StateMachine.WaitRunDevsRunOps();
Bridge.OnTestProgress(this, new TestProgressEventArgs(test, repetitionNr, Config.Entities.Progress.Test));
if (e.Contains(Event.Error)) { retVal = Event.Error; break; }
if (TestAndLogUiCmdStop(test, e)) { retVal = Event.UiCmdStop; break; }
}
while (e.Contains(Event.CameraBusy));
}
else
{
for (int i = 0; i < sensPath.RegisterReaders.Length; i++)
{
GenericDevices.IRoiForFixedStart roi = sensPath.RegisterReaders[i] as GenericDevices.IRoiForFixedStart;
if (roi != null)
{
string directory = Path.Combine(Program.TempImagesDir, BatchRslts.Batch.BatchNr.ToString(), (i + 1).ToString());
Directory.CreateDirectory(directory);
endImages[i] = Path.Combine(directory, fileName);
File.Copy(string.Format("C:\\TBF\\SampleImages\\{0}", fileName), endImages[i], true);
}
}
}
intermediateData.EndImages = endImages;
///
if ((dataEntryCmpnt is GenericDevices.IDataEntryForCamera) && (dataEntryCmpnt as GenericDevices.IDataEntryForCamera).SaveImages)
{
/// SaveImages==true ... copy images to the directory that will be archived at the end of the cycle
for (int i = 0; i < sensPath.RegisterReaders.Length; i++)
{
GenericDevices.IRoiForFixedStart roi = sensPath.RegisterReaders[i] as GenericDevices.IRoiForFixedStart;
if (roi != null)
{
string srcDir = Path.Combine(Program.TempImagesDir, BatchRslts.Batch.BatchNr.ToString(), (i + 1).ToString());
string destDir = Path.Combine(Program.ImagesDir, BatchRslts.Batch.BatchNr.ToString(), (i + 1).ToString());
try
{
if (File.Exists(Path.Combine(srcDir, fileName)))
{
Directory.CreateDirectory(destDir);
File.Copy(Path.Combine(srcDir, fileName), Path.Combine(destDir, fileName), true);
}
}
catch (Exception exc)
{
log.ErrorFormat("Failed to copy image {0} to {1}: {2}", fileName, destDir, exc.Message);
}
}
}
}
//------------------------------------------------
Bridge.OnActivity(this, Strings.Test_completed);
//------------------------------------------------
/// Make sure the CycleBeginForm is closed so that water meter data (s/n) can be copied into results
if (UIFlowControl.Stop == WaitBeginFormClosed()) goto stopTest;
///
/// Populate TestResult data entity with data
///
Results.Entities.TestRslt tstRslt = BatchRslts.GetTestRslt(testName, test.Part);
if (tstRslt != null)
{
UpdateTempPressDensAmb(tstRslt);
/// Main results
tstRslt.MethodClass = TbfComponents.FindComponent(test.Method).ClassName;
tstRslt.StartTime = TestStartTime;
tstRslt.EndTime = TestEndTime;
tstRslt.FlowSetTime = flowSetTime;
tstRslt.TestTime = Math.Max(1.0, EndTime - StartTime); /// [s] measurement time, at least 1 to prevent division by zero
tstRslt.PulsesMaster = Convert.ToDouble(cBrd.EtPulses(0)); /// Pulses of the master flow meter (test total)
tstRslt.MassStartRaw = StartMass.Val;
tstRslt.MassStart = massStart;
tstRslt.MassEndRaw = EndMass.Val;
tstRslt.MassEnd = massEnd;
tstRslt.FlowMass = 3600.0 * (tstRslt.MassEnd - tstRslt.MassStart) / tstRslt.TestTime; /// [kg/h]
tstRslt.FlowVolume = 3.6 * LtrPerRefPulse * tstRslt.PulsesMaster / tstRslt.TestTime; /// [m3/h]
tstRslt.VolumeMaster = LtrPerRefPulse * tstRslt.PulsesMaster; /// [l] volume from the master flow meter
tstRslt.Buoyancy = buoyancy;
tstRslt.VolumeCTV = volumeCTV; /// [l] 1000.0f is because density is in [kg/m3]
tstRslt.ConstMasterRaw = outPath.FlowMeter.LtrPerPulse; /// Uncorrected master flowmeter coefficient
tstRslt.ConstMasterCorr = outPath.FlowMeter.LtrPerPulseCorrected(tstRslt.FlowVolume, rangeIx); /// Corrected master pulses per liter
tstRslt.ConstMaster = (tstRslt.VolumeMaster == 0) ? tstRslt.ConstMasterCorr : (LtrPerRefPulse * tstRslt.VolumeCTV / tstRslt.VolumeMaster);
/// Calculated master pulses per liter
tstRslt.ErrorMaster = Config.Formulas.ErrorFromVolumes(tstRslt.VolumeMaster, tstRslt.VolumeCTV);
tstRslt.FlowMean = (float)RefFlowStat.Average;
tstRslt.FlowStart = (float)RefFlowStat.First;
tstRslt.FlowEnd = (float)RefFlowStat.Last;
tstRslt.FlowMin = (float)RefFlowStat.Min;
tstRslt.FlowMax = (float)RefFlowStat.Max;
tstRslt.DiverterStart = switchTimeStart;
tstRslt.DiverterEnd = switchTimeEnd;
tstRslt.ErrorFlagsMd = (ErrorFlagsComp != null) ? (sbyte)ErrorFlagsComp.Mode : (sbyte)0;
tstRslt.ErrorFlags = (ErrorFlagsComp != null) ? ErrorFlagsComp.GetErrorFlags(tstRslt, false, true, switchTimeStart, switchTimeEnd) : 0;
tstRslt.Components = Results.Entities.Components
.UpdateList(BatchRslts.ComponentsList,
new Results.Entities.Components((BenchInfo != null) ? BenchInfo.TestBenchId : 1,
(BenchInfo != null) ? BenchInfo.TestBenchName : "testbench",
inPath.Pump != null ? inPath.Pump.Name : string.Empty,
outPath.FlowMeter != null ? outPath.FlowMeter.Name : string.Empty,
outPath.Scale != null ? outPath.Scale.Name : string.Empty,
outPath.RegulValve != null ? outPath.RegulValve.Name : string.Empty,
outPath.Diverter != null ? outPath.Diverter.Name : string.Empty));
tstRslt.TestDone = false;
}
retVal = Event.MakeSecondPass;
Bridge.OnTestProgress(this, new TestProgressEventArgs(test, repetitionNr, Config.Entities.Progress.TransitionAfter));
stopTest:
StopRecordingStatistics();
///
/// Quit this sequence
///
if (isLastRepetition || retVal == Event.UiCmdStop || retVal == Event.OpArgumentError
|| retVal == Event.Error || retVal == Event.ConfigurationError)
{
State.Create(string.Format("{0}({1}) : Stopping diverter, gate, etc.", test.Method, test.Name))
.AddOperation(checkUiOp)
.AddOperation(cBrd.StopPreviousOp())
.EnterState();
do
{
e = StateMachine.WaitRunDevsRunOps();
if (TestAndLogUiCmdStop(test, e)) { retVal = Event.UiCmdStop; goto stopTest; } /// TODO: this is an endless loop !!!
}
while (!e.Contains(Event.PreviousStopped));
}
stopTestWOTransitionAfter:
/// Create a list with one item 'retVal' (default is Event.Done) and return it
IList<Event> retList = new List<Event>(1);
retList.Add(retVal);
return retList;
}
/// <summary>
/// Fixed start mass collection method with deferred evaluation of images
/// </summary>
/// <param name="test">Test entity</param>
/// <returns>
/// Event.Done . . . . . . . OK
/// Event.UiCmdStop . . . . Stopped by the user using the on-screen button STOP
/// Event.Error . . . . . . Unspecified error
/// </returns>
public IList<Event> Execute2ndPass(Config.Entities.Test test, int repetNr, IntermediateData data)
{
IList<Event> e = new List<Event>(1); /// Events from currently running operations
Event retVal = Event.Done;
///
/// Populate TestResult data entity with data
///
Results.Entities.TestRslt tstRslt = BatchRslts.GetTestRslt(data.TestName, data.TestPart);
GenericDevices.IHasWMStatesForm deCmpnt = TbfComponents.FindComponent(StateMachine.Procedure.DataEntry) as GenericDevices.IHasWMStatesForm;
GenericDevices.IDataEntryForCamera de4Cam = deCmpnt as GenericDevices.IDataEntryForCamera;
if (tstRslt != null && de4Cam != null)
{
de4Cam.StartImages = data.StartImages;
de4Cam.EndImages = data.EndImages;
Bridge.OnActivity(this, Strings.Enter_water_meter_data);
State.Create(string.Format("{0}({1}) : Entering water meter states", test.Method, test.Name))
.AddOperation(de4Cam.ShowDeferredTestEvalFormOp(sensPath.RegisterReaders,
tstRslt.VolumeCTV,
test.ErrLimLo + test.Uncertainty,
test.ErrLimHi - test.Uncertainty))
.EnterState();
do
{
e = StateMachine.WaitRunDevsRunOps();
}
while (e.Contains(Event.ModelessFormIsOpen));
/// Update register reader star and end-volumes from data entry forms
for (int i = 0; i < Config.Data.WMsCount; i++)
{
GenericDevices.IRegisterReader r = sensPath.RegisterReaders[i];
BenchControl.Network.Camera.RoiForFixedStart.Roi rr = r as BenchControl.Network.Camera.RoiForFixedStart.Roi;
if (rr != null)
{
rr.BeginWMState = deCmpnt.WMStartState(i);
rr.EndWMState = deCmpnt.WMEndState(i);
}
}
if (data.Compound)
{
///
/// Compound meters
///
for (int i = 0; i < BatchRslts.WMPositionsCount; i++)
{
if (test.Part != 0 && test.Part != Utils.PartNr(i + 1, BatchRslts.Batch.Compound)) continue;
Results.Entities.MeterTestRslt mainMeterRslt = BatchRslts.GetMeterTestRslt(data.TestName, i, Config.Entities.CompoundMeterId.CompoundMain);
Results.Entities.MeterTestRslt auxMeterRslt = BatchRslts.GetMeterTestRslt(data.TestName, i, Config.Entities.CompoundMeterId.CompoundAux);
for (int isAux = 0; isAux <= 1; isAux++) /// 0=main, 1=aux
{
Results.Entities.MeterTestRslt meterRslt = (isAux == 0) ? mainMeterRslt : auxMeterRslt;
GenericDevices.IRegisterReader regReader = sensPath.RegisterReaders[2 * i + isAux];
if (meterRslt != null && regReader != null)
{
meterRslt.RegReaderType = (int)regReader.RegisterReaderType;
meterRslt.PulsesPerLiter = regReader.PulsesPerLtr;
meterRslt.VolumeStart = regReader.BeginWMState; /// [l] From forms/images
meterRslt.VolumeEnd = regReader.EndWMState; /// [l] From forms/images
meterRslt.VolumeMeter = meterRslt.VolumeEnd - meterRslt.VolumeStart; /// [l]
meterRslt.VolumeRef = tstRslt.VolumeCTV; /// [l]
meterRslt.PulsesMeter = meterRslt.VolumeMeter * regReader.PulsesPerLtr;
meterRslt.PulsesMaster = tstRslt.PulsesMaster;
meterRslt.TestTime = tstRslt.TestTime;
meterRslt.Error = Config.Formulas.ErrorFromVolumes(meterRslt.VolumeMeter, meterRslt.VolumeRef); /// Not used for evaluation
}
}
Results.Entities.MeterTestRslt compoundMeterRslt = BatchRslts.GetMeterTestRslt(data.TestName, i, Config.Entities.CompoundMeterId.Compound);
if (compoundMeterRslt != null && mainMeterRslt != null && auxMeterRslt != null)
{
compoundMeterRslt.VolumeRef = tstRslt.VolumeCTV; /// [l] must be calculated before main & aux. meter error
compoundMeterRslt.VolumeMeter = mainMeterRslt.VolumeMeter + auxMeterRslt.VolumeMeter;
compoundMeterRslt.PulsesMaster = tstRslt.PulsesMaster;
compoundMeterRslt.TestTime = tstRslt.TestTime;
compoundMeterRslt.Error = Config.Formulas.ErrorFromVolumes(compoundMeterRslt.VolumeMeter, compoundMeterRslt.VolumeRef);
compoundMeterRslt.Passed = (compoundMeterRslt.Error >= test.GetErrLimLo(tstRslt.FlowMean) + test.Uncertainty)
&& (compoundMeterRslt.Error <= test.GetErrLimHi(tstRslt.FlowMean) - test.Uncertainty)
&& (tstRslt.ErrorFlags == 0 || tstRslt.ErrorFlagsMode() != Config.Entities.ErrorFlagsMode.On);
mainMeterRslt.Passed = auxMeterRslt.Passed = compoundMeterRslt.Passed;
mainMeterRslt.TestDone = auxMeterRslt.TestDone = compoundMeterRslt.TestDone = true;
}
}
tstRslt.TestDone = true;
}
else
{
///
/// Single meters
///
for (int i = 0; i < BatchRslts.WMPositionsCount; i++)
{
if (test.Part != 0 && test.Part != Utils.PartNr(i + 1, BatchRslts.Batch.Compound)) continue;
Results.Entities.MeterTestRslt meterRslt = BatchRslts.GetMeterTestRslt(data.TestName, i, Config.Entities.CompoundMeterId.Single);
GenericDevices.IRegisterReader regReader = sensPath.RegisterReaders[i];
if (meterRslt != null && regReader != null)
{
meterRslt.RegReaderType = (int)regReader.RegisterReaderType;
meterRslt.PulsesPerLiter = regReader.PulsesPerLtr;
meterRslt.VolumeStart = regReader.BeginWMState; /// From forms/images
meterRslt.VolumeEnd = regReader.EndWMState; /// From forms/images
meterRslt.VolumeMeter = meterRslt.VolumeEnd - meterRslt.VolumeStart;
meterRslt.VolumeRef = tstRslt.VolumeCTV; /// liter
meterRslt.PulsesMeter = meterRslt.VolumeMeter * regReader.PulsesPerLtr;
meterRslt.PulsesMaster = tstRslt.PulsesMaster;
meterRslt.TestTime = tstRslt.TestTime;
meterRslt.Error = Config.Formulas.ErrorFromVolumes(meterRslt.VolumeMeter, meterRslt.VolumeRef);
meterRslt.Passed = (meterRslt.Error >= test.GetErrLimLo(tstRslt.FlowMean) + test.Uncertainty)
&& (meterRslt.Error <= test.GetErrLimHi(tstRslt.FlowMean) - test.Uncertainty)
&& (tstRslt.ErrorFlags == 0 || tstRslt.ErrorFlagsMode() != Config.Entities.ErrorFlagsMode.On);
meterRslt.TestDone = true;
}
}
tstRslt.TestDone = true;
}
/// Update water meter error flags
if (ErrorFlagsComp != null)
{
for (int i = 0; i < BatchRslts.WMPositionsCount; i++)
{
if (BatchRslts.WaterMeters[i] != null)
{
BatchRslts.WaterMeters[i].ErrorFlags = ErrorFlagsComp.GetWMtrErrorFlags(BatchRslts.WaterMeters[i].MeterTestRslts);
}
}
}
/// Update results
Bridge.OnTestCompleted(this, new TestCompletedEventArgs(data.TestName, tstRslt));
/// Append the results to the CSV-file
allResults.Info(TestResult2CsvLine(data.TestName, data.TestPart));
}
/// No operation for 1 period so that Stop() function of Data entry component is called
State.Create(string.Format("{0}({1}) : No Op.", test.Method, test.Name)).EnterState();
do { e = StateMachine.WaitRunDevsRunOps(); } while (false);
e.Add(retVal);
return e;
}
}
}