Files
tbf/TBF/Rig/TestMethods/DiverterTest/DiverterTestSeq.cs
T
2024-02-04 10:06:41 +01:00

850 lines
41 KiB
C#

///
/// Copyright (c) 2019-2021 Sensus Slovensko a.s.
///
using System;
using System.Collections.Generic;
using System.Text;
using log4net;
using Common;
using Config.Entities;
using TBF.Rig;
using TBF.Boxes;
using TBF.Resources;
using TBF.UiBridge;
using TBF.Rig.GenericDevices;
using TBF.Rig.Sequences;
namespace TBF.Rig.TestMethods.DiverterTest
{
public class DiverterTestSeq : SequenceBase
{
private static readonly ILog log = LogManager.GetLogger(typeof(DiverterTestSeq));
/// <summary>
/// Check capabilities of devces in the output path required for this test method
/// </summary>
/// <param name="devices">Devices</param>
/// <returns>true when capabilities of devices are OK</returns>
public static bool CheckDeviceCaps(Config.Entities.Test test, OutputPath devices, out string message)
{
if (!(StateMachine.ControlBoardMain is ControlBoard.Uni.UniCB))
{
/// Control board does not support this method
message = string.Format("{0}: {1}", test.Name, Strings.Test_bench_does_not_suport_selected_test_method);
return false;
}
if (!(devices.Scale is IScale))
{
/// Scale is missing
message = string.Format("{0}: {1}", test.Name, Strings.Missing_a_scale);
return false;
}
if (test.Volume > devices.Scale.Capacity * Constants.TankFullFactor)
{
/// Scale capacity is not sufficient
message = string.Format("{0}: {1}", test.Name, Strings.Test_volume_exceeds_the_scale_capacity);
return false;
}
if (!(devices.Diverter is IDiverter))
{
/// Scale is missing
message = string.Format("{0}: {1}", test.Name, Strings.Missing_a_diverter);
return false;
}
if (!(devices.FlowMeter is IFlowMeter))
{
/// Flow meter is missing
message = string.Format("{0}: {1}", test.Name, Strings.Missing_a_flow_meter);
return false;
}
if (!(devices.RegValve is GenericDevices.IRegValve))
{
/// Regulation valve is missing
message = string.Format("{0}: {1}", test.Name, Strings.Missing_a_regulation_valve);
return false;
}
message = string.Empty;
return true;
}
/// <summary>
/// Flying start mass collection method sequence
/// </summary>
/// <param name="test">Test entity</param>
/// <returns>
/// Event.Done . . . . . . . OK
/// 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, TestParams testParams)
{
TBF.Rig.ControlBoard.Uni.UniCB cBrd = StateMachine.ControlBoardMain as TBF.Rig.ControlBoard.Uni.UniCB;
IScale scale = cBrd.Devices.Scale as IScale;
if ((outPath.FlowMeter is IFlowMeterSingle) &&
(outPath.FlowMeter as IFlowMeterSingle).GetRange(test.TempLimLo, test.TempLimHi) == -1)
{
Bridge.OnError(this, Strings.Flow_meter_temperature_range_does_not_fit_this_test_conditions);
return new List<Event> { Event.ConfigurationError }; /// or Event.UiCmdStop ???
}
IList<Event> e; /// Events from currently running operations
Event retVal = Event.Done;
int tMass1 = 0;
int tMass2 = 0;
checkUiOp = new Operations.CheckUIOp(true); /// Runs in more then one state
processDataLoggingOp = new TBF.Rig.Operations.ProcessDataLoggingOp(processDataLogger, this);
if (cBrd is ControlBoard.Uni.UniCB)
{
int[] filters = new int[] { 0, 0, 0, 0, 0, 0, 0, 0 };
if (sensPath != null && sensPath.RegisterReaders != null)
{
foreach (var rr in sensPath.RegisterReaders)
{
IRegReaderPulses rrPls = rr as IRegReaderPulses;
if (rrPls != null && rrPls.Position >= 1 && rrPls.Position <= 8)
{
filters[rrPls.Position - 1] = rrPls.Filter;
}
}
}
(cBrd as ControlBoard.Uni.UniCB).SetFiltersPidShortPulses(filters, outPath.PidCoef, test.ShortPulses);
}
IList<IOperation> readTempPressOps = new List<IOperation>();
if (benchPath.TempMtrUp != null) readTempPressOps.Add(benchPath.TempMtrUp.ReadTempOp(ref TempUp));
if (benchPath.TempMtrDown != null) readTempPressOps.Add(benchPath.TempMtrDown.ReadTempOp(ref TempDown));
if (outPath.TempMtrDiv != null) readTempPressOps.Add(outPath.TempMtrDiv.ReadTempOp(ref TempDiv));
if (benchPath.PressMtrUp != null) readTempPressOps.Add(benchPath.PressMtrUp.ReadPressureOp(ref PressUp));
if (benchPath.PressMtrDown != null) readTempPressOps.Add(benchPath.PressMtrDown.ReadPressureOp(ref PressDown));
if (benchPath.PressMtrDelta != null) readTempPressOps.Add(benchPath.PressMtrDelta.ReadPressureOp(ref PressDelta));
int totalPulses = Convert.ToInt32(test.Volume / outPath.FlowMeter.LtrPerPulse);
///============================================================================================
/// Read pressure and temperature once before calling Bridge.OnTestSelected(...)
State.Create(string.Format("{0}({1}) : Measuring process data", test.Method, test.Name))
.AddOperation(checkUiOp)
.AddOperations(readTempPressOps)
.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.Busy));
/// Start the test, initialize test results
Bridge.OnTestSelected(this, new TestSelectedEventArgs(test, repetitionNr, inPath, benchPath, outPath, sensPath, null));
string testName = Results.Utils.GetTestName(test.Name, test.Repeats, repetitionNr);
TestStartTime = DateTime.Now;
//------------------------------------------------
Bridge.OnActivity(this, Strings.Checking_tank_capacity);
//------------------------------------------------
bool drainTheTank = test.DoDraining;
if (!drainTheTank) /// If condition met => skip measuring and force emptying
{
double estimatedEndMass = scale.Mass + test.Volume;
if (estimatedEndMass >= scale.Capacity * Constants.TankFullFactor)
{
drainTheTank = true;
}
}
///
if (drainTheTank)
{
#if BERLIN || GELSENWASSER || SENTEC
switch (DrainTheTank(outPath.Scale, readTempPressOps))
{
case Event.Error: { retVal = Event.Error; goto stopTest; }
case Event.UiCmdStop: { retVal = Event.UiCmdStop; goto stopTest; }
}
drainTheTank = false;
#else
State.Create(string.Format("{0}({1}) : Open the drain valve", test.Method, test.Name))
.AddOperation(checkUiOp)
.AddOperation(StateMachine.ControlBoardMain.SetValvesOp(scale.DrainValve, null))
.AddOperations(readTempPressOps)
.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.ValvesBusy));
#endif
}
//------------------------------------------------
Bridge.OnActivity(this, Strings.Starting_the_pump);
//------------------------------------------------
Bridge.OnTestProgress(this, new TestProgressEventArgs(test, repetitionNr, 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(new Operations.SetAllRegulValvesOp(inPath.RegulValves, inPath.RegulValvesPct, 60))
.AddOperations(readTempPressOps)
.AddOperation(inPath.Pump != null ? cBrd.SetValvesOp(inPath.Pump, null) : null)
.EnterState();
do {
e = StateMachine.WaitRunDevsRunOps();
Bridge.OnTestProgress(this, new TestProgressEventArgs(test, repetitionNr, 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))
.AddOperations(readTempPressOps)
.EnterState();
do {
e = StateMachine.WaitRunDevsRunOps();
Bridge.OnTestProgress(this, new TestProgressEventArgs(test, repetitionNr, 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.ControlBoardMain.SetValvesOp(benchPath.StopBFValve, null))
.AddOperations(readTempPressOps)
.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))
.AddOperations(readTempPressOps)
.EnterState();
do {
e = StateMachine.WaitRunDevsRunOps();
Bridge.OnTestProgress(this, new TestProgressEventArgs(test, repetitionNr, Progress.FlowSetting));
if (TestAndLogUiCmdStop(test, e)) { retVal = Event.UiCmdStop; goto stopTest; }
}
while (!e.Contains(Event.TimerExpired));
}
//------------------------------------------------
Bridge.OnActivity(this, Strings.Setting_the_flow);
//------------------------------------------------
State.Create(string.Format("{0}({1}) : Setting the flow", test.Method, test.Name))
.AddOperation(checkUiOp)
.AddOperation(cBrd.SetFlowOp(test.QfromM3ph(), test.QtoM3ph(), RefFlow, FlowSettingTimeoutSec))
.AddOperations(readTempPressOps)
.EnterState();
do {
e = StateMachine.WaitRunDevsRunOps();
Bridge.OnTestProgress(this, new TestProgressEventArgs(test, repetitionNr, 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.RecoverableError;
goto stopTest;
}
if (e.Contains(Event.Next)) goto flow_set;
}
while (!e.Contains(Event.FlowReached));
flow_set:
int flowSetTime = StateMachine.Time - flowSetTime0;
double currentFlow = RefFlow.Val;
if (!string.IsNullOrEmpty(test.TempControl) && (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)
.AddOperations(readTempPressOps)
.EnterState();
do {
e = StateMachine.WaitRunDevsRunOps();
if (TestAndLogUiCmdStop(test, e)) { retVal = Event.UiCmdStop; goto stopTest; }
if (e.Contains(Event.Next)) goto temperature_set;
if ((test.TempLimLo <= TempUp.Val) && (TempUp.Val <= test.TempLimHi) &&
(test.TempLimLo <= TempDown.Val) && (TempDown.Val <= test.TempLimHi))
{
goto temperature_set;
}
}
while (true);
}
temperature_set:
///
/// Prepare cameras, ROI-s and measurementOperations
///
/// Find successfully detected ROI-s
IList<GenericDevices.IRegReaderLiveCamera> rois = new List<GenericDevices.IRegReaderLiveCamera>();
foreach (var rr in sensPath.RegisterReaders)
{
GenericDevices.IRegReaderLiveCamera cameraRoI = rr as GenericDevices.IRegReaderLiveCamera;
if ((cameraRoI != null) && cameraRoI.Detected)
{
rois.Add(cameraRoI);
}
}
/// Find cameras
IList<GenericDevices.ICamera> cameras = new List<GenericDevices.ICamera>();
foreach (var roi in rois)
{
if (roi.Camera != null && !cameras.Contains(roi.Camera))
{
cameras.Add(roi.Camera);
roi.Camera.ClearRoiParams();
}
}
/// Register ROI-parameters to cameras
foreach (var roi in rois) roi.RegisterRoiToCamera();
/// Prepare measurementOperations
IList<IOperation> cameraMeasurementOps = new List<IOperation>();
foreach (var camera in cameras) cameraMeasurementOps.Add(camera.MeasurementOp());
if (drainTheTank)
{
//------------------------------------------------
Bridge.OnActivity(this, Strings.Closing_the_tank);
//------------------------------------------------
///
/// Make sure tank draining completed
///
switch (DrainTheTank(scale, readTempPressOps))
{
case Event.Error: { retVal = Event.Error; goto stopTest; }
case Event.UiCmdStop: { retVal = Event.UiCmdStop; goto stopTest; }
}
drainTheTank = false;
}
else
{
/// Close the drain valve anyway
State.Create(string.Format("{0}({1}) : Close the drain valve", test.Method, test.Name))
.AddOperation(checkUiOp)
.AddOperations(readTempPressOps)
.AddOperation(StateMachine.ControlBoardMain.SetValvesOp(null, scale.DrainValve))
.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.ValvesBusy));
}
//------------------------------------------------
Bridge.OnActivity(this, Strings.Measuring_the_weight);
//------------------------------------------------
LogProcessDataTestInfo(processDataLogger, test.Procedure.Name, test.Name);
LogProcessDataHeader(processDataLogger, "Start mass");
State.Create(string.Format("{0}({1}) : Measuring the start mass", test.Method, test.Name))
.AddOperation(checkUiOp)
.AddOperations(readTempPressOps)
.AddOperations(cameraMeasurementOps)
.AddOperation(scale.ReadStableMassOp(ref StartMass, test.TimeFlow2Mass, test.MassMethod, test.MassRepeats, test.MassSpread))
.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; }
if (e.Contains(Event.ScaleTimeout))
{
Bridge.OnError(this, Strings.Mass_measurement_timeout);
retVal = Event.RecoverableError;
goto stopTest;
}
}
while (!e.Contains(Event.ScaleDone) && !e.Contains(Event.Next));
tMass1 = StateMachine.Time;
log.WarnFormat("Start mass = {0}kg", StartMass);
///
/// Initialize cumulated reference and water metert pulses
///
int[] cumulativeEtPulses = new int[ProcessData.WMsCount + 1]; /// 0 .. ProcessData.WMsCount
int[] cumulativeWMPulses = new int[ProcessData.WMsCount + 1]; /// 1 .. ProcessData.WMsCount
double[] cumulativeTestTime = new double[ProcessData.WMsCount + 1]; /// 0 .. ProcessData.WMsCount
for (int i = 0; i <= ProcessData.WMsCount; i++)
{
cumulativeEtPulses[i] = 0;
if (i > 0) cumulativeWMPulses[i] = 0;
cumulativeTestTime[i] = 0;
}
///
/// Diverter test loop
///
int remainingPulses = totalPulses;
StartNewStatistics(outPath.FlowMeter, BatchRslts.Batch.BatchNr, test, repetitionNr, 0);
DiverterStart.Start(BatchRslts.Batch.BatchNr, test.Name, repetitionNr);
DiverterEnd.Start(BatchRslts.Batch.BatchNr, test.Name, repetitionNr);
float[] divStartTimes = new float[testParams.DivRepetitions];
float[] divEndTimes = new float[testParams.DivRepetitions];
for (int divRepetNr = 1; divRepetNr <= testParams.DivRepetitions; divRepetNr++)
{
LogProcessDataHeader(processDataLogger, string.Format("Measurement {0}", divRepetNr));
foreach (var rr in sensPath.RegisterReaders)
{
if (rr is IRegReaderDatastream) (rr as IRegReaderDatastream).TestIsGoingToStartSoon(test, repetitionNr);
}
int remainingRepetitions = testParams.DivRepetitions - divRepetNr + 1;
int pulsesNow = (remainingPulses + remainingRepetitions - 1) / remainingRepetitions;
remainingPulses -= pulsesNow;
//------------------------------------------------
Bridge.OnActivity(this, Strings.Test_in_progress);
//------------------------------------------------
/// Measurement loop preparation
int estimtdEndTime = StateMachine.Time + (int)(test.TestTime / testParams.DivRepetitions);
int remainingTime;
State.Create(string.Format("{0}({1}) : Perform test", test.Method, test.Name))
.AddOperation(checkUiOp)
.AddOperations(readTempPressOps)
.AddOperations(cameraMeasurementOps)
.AddOperation(cBrd.FlyingStartStopTestOp(test, test.QfromM3ph(), test.QtoM3ph(), pulsesNow, true, false, false, 0, true, DiverterStart, DiverterEnd))
.AddOperation(processDataLoggingOp)
.EnterState();
do {
e = StateMachine.WaitRunDevsRunOps();
if (e.Contains(Event.OpArgumentError)) { retVal = Event.OpArgumentError; goto stopTest; }
if (e.Contains(Event.Error)) { retVal = Event.Error; goto stopTest; }
if (TestAndLogUiCmdStop(test, e)) { retVal = Event.UiCmdStop; goto stopTest; }
/// Show remaining time
if ((remainingTime = Math.Max(estimtdEndTime - StateMachine.Time, 0)) > 60)
Bridge.OnActivity(this, string.Format("{0}. {1} ... {2} {3} {4} {5}", divRepetNr, Strings.Test_in_progress, remainingTime / 60, "min", remainingTime % 60, Strings.sec));
else
Bridge.OnActivity(this, string.Format("{0}. {1} ... {2} s", divRepetNr, Strings.Test_in_progress, remainingTime));
/// Update statistics
RefFrequency.Val = cBrd.RefFrequency;
RefFlow.Val = outPath.FlowMeter.ReadFlow();
UpdateAllStatistics();
Bridge.OnTestProgress(this, new TestProgressEventArgs(test, repetitionNr, Progress.Test));
}
while (!e.Contains(Event.TestCompleted) && !e.Contains(Event.Next));
LogProcessDataHeader(processDataLogger, string.Format("Delay {0}", divRepetNr));
if (divRepetNr < testParams.DivRepetitions)
{
/// This is not the last diverter repetition
/// Delay 5s
State.Create(string.Format("{0}({1}) : Delay {2}", test.Method, test.Name, divRepetNr))
.AddOperation(checkUiOp)
.AddOperations(readTempPressOps)
.AddOperation(new Operations.TimerOp(5))
.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.TimerExpired));
/// Accumulate partial pulses
cumulativeEtPulses[0] += cBrd.RefPulses;
cumulativeTestTime[0] += cBrd.TestTime;
for (int i = 1; i <= ProcessData.WMsCount; i++)
{
cumulativeEtPulses[i] += cBrd.RefPulsesWM(i);
cumulativeWMPulses[i] += cBrd.PulsesWM(i);
cumulativeTestTime[i] += cBrd.TestTimeWM(i);
}
divStartTimes[divRepetNr - 1] = outPath.Diverter.SwitchTimeStart.Val;
divEndTimes[divRepetNr - 1] = outPath.Diverter.SwitchTimeEnd.Val;
}
} /// end for ... diverter test loop
/// Test completed
StopRecordingStatistics();
///
/// (Berlin:) Water is stopped immediately after the test and before the 2nd mass measurement in case:
/// - no 'transition sequence after test' is used
/// - this is the last (or the only) test repetition or test is a part of an 'outer loop'
///
#if !CEVAK_200
if (isLastRepetition && transitionAfter == null)
#endif
{
if (inPath.Pump is GenericDevices.IPumpFM) (inPath.Pump as GenericDevices.IPumpFM).TurnOff();
State.Create("SequenceBase : Transition : TestEnd - Default action")
.AddOperation(checkUiOp)
.AddOperations(readTempPressOps)
.AddOperation(StateMachine.ControlBoardMain.SetValvesOp(StateMachine.DefaultValvesOpen, StateMachine.DefaultValvesClose))
.EnterState();
do {
e = StateMachine.WaitRunDevsRunOps();
if (e.Contains(Event.Error)) { retVal = Event.Error; goto stopTest; }
if (TestAndLogUiCmdStop(e)) { retVal = Event.UiCmdStop; goto stopTest; }
}
while (!e.Contains(Event.ValvesSet));
}
//------------------------------------------------
Bridge.OnActivity(this, Strings.Measuring_the_weight);
//------------------------------------------------
LogProcessDataHeader(processDataLogger, "End mass");
State.Create(string.Format("{0}({1}) : Measuring the end mass", test.Method, test.Name))
.AddOperation(checkUiOp)
.AddOperations(readTempPressOps)
.AddOperation(scale.ReadStableMassOp(ref EndMass, test.TimeStop2Mass, test.MassMethod, test.MassRepeats, test.MassSpread))
.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; }
if (e.Contains(Event.ScaleTimeout))
{
Bridge.OnError(this, Strings.Mass_measurement_timeout);
retVal = Event.RecoverableError;
goto stopTest;
}
}
while (!e.Contains(Event.ScaleDone) && !e.Contains(Event.Next));
///
tMass2 = StateMachine.Time;
log.WarnFormat("End mass = {0}kg", EndMass);
TestEndTime = DateTime.Now;
/// Calculate average diverter start/end times
divStartTimes[testParams.DivRepetitions - 1] = outPath.Diverter.SwitchTimeStart.Val;
divEndTimes[testParams.DivRepetitions - 1] = outPath.Diverter.SwitchTimeEnd.Val;
for (int i = 0; i < testParams.DivRepetitions - 1; i++)
{
outPath.Diverter.SwitchTimeStart.Val = outPath.Diverter.SwitchTimeStart.Val + divStartTimes[i];
outPath.Diverter.SwitchTimeEnd.Val = outPath.Diverter.SwitchTimeEnd.Val + divEndTimes[i];
}
outPath.Diverter.SwitchTimeStart.Val = outPath.Diverter.SwitchTimeStart.Val / Convert.ToSingle(testParams.DivRepetitions);
outPath.Diverter.SwitchTimeEnd.Val = outPath.Diverter.SwitchTimeEnd.Val / Convert.ToSingle(testParams.DivRepetitions);
if (test.DoDrainingAfter)
{
State.Create(string.Format("{0}({1}) : Open the drain valve", test.Method, test.Name))
.AddOperation(checkUiOp)
.AddOperation(cBrd.SetValvesOp(scale.DrainValve, null))
.AddOperations(readTempPressOps)
.EnterState();
do
{
e = StateMachine.WaitRunDevsRunOps();
if (e.Contains(Event.Error)) { retVal = Event.Error; goto stopTest; }
}
while (e.Contains(Event.ValvesBusy));
}
//------------------------------------------------
Bridge.OnActivity(this, Strings.Test_completed);
//------------------------------------------------
///
/// Accumulate partial pulses from the last diverter repetition
///
cumulativeEtPulses[0] += cBrd.RefPulses;
cumulativeTestTime[0] += cBrd.TestTime;
for (int i = 1; i <= ProcessData.WMsCount; i++)
{
cumulativeEtPulses[i] += cBrd.RefPulsesWM(i);
cumulativeWMPulses[i] += cBrd.PulsesWM(i);
cumulativeTestTime[i] += cBrd.TestTimeWM(i);
}
///
/// Populate TestResult data entity with data
///
Results.Entities.TestRslt tstRslt = BatchRslts.GetTestRslt(testName, test.Part);
bool stopCycle = false;
if (tstRslt != null)
{
Results.Utils.GetCounterStates(tstRslt, Program.LocalSettings.Counters);
/// Raw data
UpdateTempPressDensAmb(tstRslt);
tstRslt.MethodClass = TbfComponents.FindComponent(test.Method).ClassName;
tstRslt.StartTime = TestStartTime;
tstRslt.EndTime = TestEndTime;
tstRslt.FlowSetTime = flowSetTime;
tstRslt.TestTime = cumulativeTestTime[0]; /// [s] measurement time
tstRslt.PulsesMaster = Convert.ToDouble(cumulativeEtPulses[0]); /// Pulses of the master flow meter (test total)
tstRslt.MassStartRaw = StartMass.Val;
tstRslt.MassEndRaw = EndMass.Val;
tstRslt.TimeBtwnMassMsrmnts = tMass2 - tMass1;
tstRslt.ConstMasterRaw = outPath.FlowMeter.LtrPerPulse; /// Uncorrected master flowmeter coefficient
tstRslt.VolumeMaster = outPath.FlowMeter.LtrPerPulse * tstRslt.PulsesMaster; /// [l] volume from the master flow meter
double flowMID = 3.6 * tstRslt.VolumeMaster / tstRslt.TestTime; /// [m3/h]
/// Corrected values
tstRslt.MassStart = MeasurementCorrection.CorrectedValue(tstRslt.MassStartRaw, scale.Corrections);
tstRslt.MassEnd = MeasurementCorrection.CorrectedValue(tstRslt.MassEndRaw, scale.Corrections);
tstRslt.MassOfEvapWater = (double)tstRslt.TimeBtwnMassMsrmnts * outPath.Scale.EvaporationRate(tstRslt.TempDivMean);
double mass = tstRslt.MassEnd - tstRslt.MassStart + tstRslt.MassOfEvapWater;
tstRslt.ConstMasterCorr = outPath.FlowMeter.LtrPerPulseCorrected(flowMID, tstRslt.TempDownMean); /// Corrected master pulses per liter
/// Main results
tstRslt.VolumeCTV = 1000 * tstRslt.Batch.Buoyancy * mass / tstRslt.DensityLine; /// [l] commercially true volume
if ((outPath.Diverter != null) && (tstRslt.TestTime > float.Epsilon))
{
tstRslt.TestTimeCorrection = testParams.DivRepetitions * outPath.Diverter.TestTimeCorrection(flowMID);
tstRslt.VolumeCTV *= tstRslt.TestTime + tstRslt.TestTimeCorrection;
tstRslt.VolumeCTV /= tstRslt.TestTime;
}
tstRslt.Flow = 3.6 * tstRslt.VolumeCTV / tstRslt.TestTime; /// [m3/h]
tstRslt.ErrorMaster = Formulas.ErrorFromVolumes(tstRslt.VolumeMaster, tstRslt.VolumeCTV);
tstRslt.ConstMaster = (tstRslt.VolumeMaster == 0) ? tstRslt.ConstMasterCorr : (tstRslt.ConstMasterRaw * tstRslt.VolumeCTV / tstRslt.VolumeMaster);
/// Calculated master pulses per liter
/// Flow statistics correction
tstRslt.FlowMean = Convert.ToSingle(tstRslt.ConstMaster * RefFlowStat.Average / tstRslt.ConstMasterRaw);
tstRslt.FlowStart = Convert.ToSingle(tstRslt.ConstMaster * RefFlowStat.First / tstRslt.ConstMasterRaw);
tstRslt.FlowEnd = Convert.ToSingle(tstRslt.ConstMaster * RefFlowStat.Last / tstRslt.ConstMasterRaw);
tstRslt.FlowMin = Convert.ToSingle(tstRslt.ConstMaster * RefFlowStat.Min / tstRslt.ConstMasterRaw);
tstRslt.FlowMax = Convert.ToSingle(tstRslt.ConstMaster * RefFlowStat.Max / tstRslt.ConstMasterRaw);
tstRslt.DiverterStart = outPath.Diverter.SwitchTimeStart.Val;
tstRslt.DivStart10 = 0;
tstRslt.DivStart50 = 0;
tstRslt.DivStart90 = 0;
tstRslt.DiverterEnd = outPath.Diverter.SwitchTimeEnd.Val;
tstRslt.DivEnd90 = 0;
tstRslt.DivEnd50 = 0;
tstRslt.DivEnd10 = 0;
log.DebugFormat("Diverter switch time [s]: Start: {0}ms ({1} {2} {3}) End: {4}ms ({5} {6} {7})",
(tstRslt.DiverterStart * 1000).ToString("F0"), tstRslt.DivStart10, tstRslt.DivStart50, tstRslt.DivStart90,
(tstRslt.DiverterEnd * 1000).ToString("F0"), tstRslt.DivEnd90, tstRslt.DivEnd50, tstRslt.DivEnd10);
long infoFlags = 0;
tstRslt.ErrorFlags = (ErrorFlagsComp != null) ? ErrorFlagsComp.GetErrorFlags(tstRslt, true, false, tstRslt.DiverterStart, tstRslt.DiverterEnd, out infoFlags, out stopCycle) : 0;
tstRslt.InfoFlags = infoFlags;
///
/// Single meters
///
for (int i = 0; i < BatchRslts.WMPositionsCount; i++)
{
if (!test.IsPartCompatible(Utils.PartNr(i + 1, BatchRslts.Batch.Compound))) continue;
/// MetersKind.Single meters
Results.Entities.MeterTestRslt meterRslt = BatchRslts.GetMeterTestRslt(testName, i, Common.CompoundMeterId.Single);
GenericDevices.IRegReader regReader = sensPath.RegisterReaders[i];
GenericDevices.IRegReaderDatastream dstrReader = regReader as GenericDevices.IRegReaderDatastream;
TestMethods.iPerlCommunication.iPerlHead.IperlHead iPerl = regReader as TestMethods.iPerlCommunication.iPerlHead.IperlHead;
GenericDevices.IRegReaderLiveCamera cameraRoi = regReader as GenericDevices.IRegReaderLiveCamera;
if (meterRslt != null && regReader != null)
{
meterRslt.RegReaderType = (int)regReader.RegisterReaderType;
meterRslt.PulsesPerLiter = regReader.PulsesPerLtr;
meterRslt.PulsesMeter = Convert.ToDouble(regReader.WMPulses);
if (dstrReader != null)
{
meterRslt.TimestampStart = dstrReader.TimestampSecStart;
meterRslt.TimestampEnd = dstrReader.NoSamples ? (dstrReader.TimestampSecStart + tstRslt.TestTime) : dstrReader.TimestampSecEnd;
meterRslt.TestTime = meterRslt.TimestampEnd - meterRslt.TimestampStart;
meterRslt.VolumeStart = dstrReader.VolumeLtrStart; /// liter
meterRslt.VolumeEnd = dstrReader.VolumeLtrEnd; /// liter
meterRslt.VolumeMeter = Math.Abs(dstrReader.VolumeLtrEnd - dstrReader.VolumeLtrStart);
meterRslt.VolumeRef = tstRslt.VolumeCTV * meterRslt.TestTime / tstRslt.TestTime;
meterRslt.PulsesMaster = tstRslt.PulsesMaster * meterRslt.TestTime / tstRslt.TestTime;
if (iPerl != null)
{
if (iPerl.ResultCode != 0 && (meterRslt.WaterMeter.ResultCode & (int)Results.Entities.ResultCode.OptoErrorCodeMask) == 0)
{
meterRslt.WaterMeter.ResultCode |= iPerl.ResultCode;
}
#if IPERL
meterRslt.WaterMeter.CalibFactor = iPerl.CalibFactor;
#endif
iPerl.LastTestResult2 = iPerl.LastTestResult; /// Save shift previous test result
iPerl.LastTestResult = meterRslt; /// Save this test result
}
}
else if (cameraRoi != null)
{
meterRslt.TimestampStart = cameraRoi.TimestampStart; /// second
meterRslt.TimestampEnd = cameraRoi.TimestampEnd; /// second
meterRslt.VolumeStart = cameraRoi.VolumeStart; /// liter
meterRslt.VolumeEnd = cameraRoi.VolumeEnd; /// liter
meterRslt.VolumeMeter = cameraRoi.VolumeEnd - cameraRoi.VolumeStart; /// liter
if (meterRslt.VolumeMeter != 0)
{
/// Normal measurement with camera
meterRslt.TestTime = cameraRoi.TimestampEnd - cameraRoi.TimestampStart; /// second
meterRslt.VolumeRef = tstRslt.VolumeCTV * meterRslt.TestTime / tstRslt.TestTime;
meterRslt.PulsesMaster = tstRslt.PulsesMaster * meterRslt.TestTime / tstRslt.TestTime;
}
else
{
/// None or one pulse from the water meter using camera
meterRslt.TestTime = tstRslt.TestTime;
meterRslt.VolumeRef = tstRslt.VolumeCTV;
meterRslt.PulsesMaster = tstRslt.PulsesMaster;
}
}
else
{
meterRslt.PulsesMaster = Convert.ToDouble(cumulativeEtPulses[i + 1]);
meterRslt.VolumeMeter = cumulativeWMPulses[i + 1] * regReader.LtrsPerPulse; /// liter
meterRslt.VolumeStart = 0; /// liter
meterRslt.VolumeEnd = meterRslt.VolumeMeter; /// liter
if (regReader.WMPulses >= 1)
{
/// Normal measurement
meterRslt.TestTime = cumulativeTestTime[i + 1];
meterRslt.VolumeRef = meterRslt.PulsesMaster * tstRslt.ConstMaster; /// liter
}
else
{
/// None or one pulse from the water meter
meterRslt.TestTime = cumulativeTestTime[0];
meterRslt.VolumeRef = tstRslt.VolumeCTV; /// liter
}
}
meterRslt.Error = Formulas.ErrorFromVolumes(meterRslt.VolumeMeter, meterRslt.VolumeRef);
meterRslt.Passed = (meterRslt.Error >= test.GetErrLimLo(tstRslt.VolumeCTV, tstRslt.TestTime) + test.Uncertainty)
&& (meterRslt.Error <= test.GetErrLimHi(tstRslt.VolumeCTV, tstRslt.TestTime) - test.Uncertainty)
&& (tstRslt.ErrorFlags == 0);
meterRslt.TestDone = true;
tstRslt.TestDone = true;
}
}
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,
scale != null ? scale.Name : string.Empty,
outPath.RegValve != null ? outPath.RegValve.Name : string.Empty,
outPath.Diverter != null ? outPath.Diverter.Name : string.Empty));
/// Update water meter error flags
if (ErrorFlagsComp != null)
{
if (BatchRslts.Batch != null && BatchRslts.Batch.WaterMeters != null)
{
for (int i = 0; i < BatchRslts.WMPositionsCount; i++)
{
if (BatchRslts.Batch.WaterMeters[i] != null && !BatchRslts.Batch.WaterMeters[i].Disabled)
{
long wmInfoFlags;
BatchRslts.Batch.WaterMeters[i].ErrorFlags = ErrorFlagsComp.GetWMtrErrorFlags(BatchRslts.Batch.WaterMeters[i].MeterTestRslts, out wmInfoFlags);
BatchRslts.Batch.WaterMeters[i].InfoFlags = wmInfoFlags;
}
}
}
}
/// Update results
Bridge.OnTestCompleted(this, new TestCompletedEventArgs(testName, tstRslt));
}
Bridge.OnTestProgress(this, new TestProgressEventArgs(test, repetitionNr, Progress.TransitionAfter));
/// Append the results to the CSV-file
allResults.Info(TestResult2CsvLine(testName, test.Part));
if (stopCycle) retVal = Event.ErrorFlagsStop;
stopTest:
StopRecordingStatistics(); /// Make sure graph files are closed
///
/// Quit this sequence
///
if (isLastRepetition || retVal == Event.UiCmdStop
|| retVal == Event.OpArgumentError
|| retVal == Event.RecoverableError
|| retVal == Event.ErrorFlagsStop
|| retVal == Event.Error
|| retVal == Event.ConfigurationError)
{
cBrd.StopAll(false);
}
return new List<Event> { retVal };
}
}
}