tbf/TBF/BenchControl/TestMethods/CombinedWithDetection/CombinedWithDetectionSeq.cs

866 lines
40 KiB
C#

///
/// Copyright (c) 2013-2019 Sensus Slovensko a.s.
///
using System;
using System.Collections.Generic;
using System.Text;
using log4net;
using TBF.BenchControl;
using TBF.Resources;
using TBF.UiBridge;
using TBF.BenchControl.GenericDevices;
namespace TBF.BenchControl.TestMethods.CombinedWithDetection
{
public class CombinedWithDetectionSeq : Sequences.SequenceBase
{
private static readonly ILog log = LogManager.GetLogger(typeof(CombinedWithDetectionSeq));
const int DetectionBufferSize = 9;
const int DetectionKernelSize = 5;
public IList<Event> Execute(Config.Entities.Test test, int repetitionNr, bool isLastRepetition,
CombinedWithDetTestParams testParams,
Config.Entities.DebugMode debugLevel)
{
if (debugLevel == Config.Entities.DebugMode.Simulate)
{
return Simulate(test, repetitionNr, isLastRepetition, testParams);
}
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);
return new List<Event> { Event.ConfigurationError };
}
}
IScale scale = outPath.Scale as IScale;
if (scale == null)
{
Bridge.OnError(this, Strings.Missing_a_scale);
return new List<Event> { Event.ConfigurationError };
}
if (test.Part < 1 || test.Part > Config.Data.CompoundWMsCount)
{
UiBridge.Bridge.OnError(this, string.Format("Test 'Part' should be 1 .. {0}", Config.Data.CompoundWMsCount));
return new List<Event> { Event.ConfigurationError };
}
IList<Event> e; /// Events from currently running operations
Elde.ControlBoardDev cBrd = StateMachine.ControlBoard;
int tMass1 = 0;
int tMass2 = 0;
checkUiOp = new Operations.CheckUIOp(true); /// Runs in more then one state
processDataLoggingOp = new TBF.BenchControl.Operations.ProcessDataLoggingOp(processDataLogger, this, false);
int[] filters = new int[] { 0, 0, 0, 0, 0, 0, 0, 0 };
if (sensPath != null && sensPath.RegisterReaders != null)
{
foreach (var rr in sensPath.RegisterReaders)
{
TBF.BenchControl.Elde.RegisterReader.RegisterReader eldeRR = rr as TBF.BenchControl.Elde.RegisterReader.RegisterReader;
if ((eldeRR != null) && (eldeRR.Position >= 1) && (eldeRR.Position <= 8))
{
filters[eldeRR.Position - 1] = eldeRR.Filter;
}
}
}
cBrd.SetFiltersPidShortPulses(filters, outPath.PidCoef, (test.TolerRed == 0) ? 0 : 1);
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.TempDiv != null) readTempPressOps.Add(outPath.TempDiv.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));
if (heatMetersPath != null) readTempPressOps.Add(heatMetersPath.TMeterRefWarm1.ReadTempOp(ref TempRefHi1));
if (heatMetersPath != null) readTempPressOps.Add(heatMetersPath.TMeterRefWarm2.ReadTempOp(ref TempRefHi2));
if (heatMetersPath != null) readTempPressOps.Add(heatMetersPath.TMeterRefCold1.ReadTempOp(ref TempRefLo1));
if (heatMetersPath != null) readTempPressOps.Add(heatMetersPath.TMeterRefCold2.ReadTempOp(ref TempRefLo2));
float switchTimeStart = 0.001f; /// in seconds, original vale is 1 ms
float switchTimeEnd = 0.001f; /// in seconds, original vale is 1 ms
/// Specific for combined meters
int[] lastWMPulses = new int[2 * Config.Data.CompoundWMsCount];
//--------------------------------
State.Create(string.Format("{0}({1}) : Stop diverter gate etc", test.Method, test.Name))
.AddOperation(checkUiOp)
.AddOperation(cBrd.StopPreviousOp())
.EnterState();
do {
e = StateMachine.WaitRunDevsRunOps();
if (TestAndLogUiCmdStop(test,e)) goto stopTest;
}
while (!e.Contains(Event.PreviousStopped));
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);
/// Meters path is required for the following:
readRegistersOp = new Operations.ReadMoreRegistersOp(sensPath.RegisterReaders);
//====================================
loop:
/// 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)) { goto stopTest; }
if (TestAndLogUiCmdStop(test, e)) { goto stopTest; }
}
while (e.Contains(Event.Busy));
/// Start the test, initialize test results
Bridge.OnTestSelected(this, new TestSelectedEventArgs(test, repetitionNr, inPath, benchPath, outPath, sensPath, heatMetersPath, totalPulses));
string testName = Results.Utils.GetTestName(test.Name, test.Repeats, repetitionNr);
TestStartTime = DateTime.Now;
Bridge.OnTestProgress(this, new TestProgressEventArgs(test, repetitionNr, Config.Entities.Progress.FlowSetting));
Qrise = 0;
Qfall = 0;
if (!test.DoDraining) /// Do not skip emptying if test.Emptying==true
{
//--------------------------------
State.Create(string.Format("{0}({1}) : Mesuring mass of water in the tank", test.Method, test.Name))
.AddOperation(checkUiOp)
.AddOperations(readTempPressOps)
.AddOperation(scale.ReadMassOp(ref Mass))
.EnterState();
do {
e = StateMachine.WaitRunDevsRunOps();
if (e.Contains(Event.Error)) goto error;
if (TestAndLogUiCmdStop(test,e)) goto stopTest;
}
while (!e.Contains(Event.BalanceDone));
double estimatedEndMass = Mass.Val + test.Volume;
if (estimatedEndMass < scale.Capacity * Constants.TankFullFactor)
{
goto switching_flow_detection; /// Enough room in the tank -> skip emptying
}
}
/// Empty the water tank
switch (DrainTheTank(scale, readTempPressOps))
{
case Event.Error: goto error;
case Event.UiCmdStop: goto stopTest;
}
switching_flow_detection:
int flowDetectTime0 = StateMachine.Time;
int flowDetectTime = 0;
float estFlowSetTime = 100.0f;
///
/// Prepare cameras, ROI-s and measurementOperations
///
/// Find ROI-s
IList<GenericDevices.IRoi> rois = new List<GenericDevices.IRoi>();
foreach (var rr in sensPath.RegisterReaders)
{
GenericDevices.IRoi cameraRoI = rr as GenericDevices.IRoi;
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))
{
roi.Camera.ClearRoiParams();
cameras.Add(roi.Camera);
}
}
/// Register ROI-parameters to cameras
foreach (var roi in rois) roi.RegisterRoiToCamera();
/// Prepare measurementOperations
IList<IOperation> measureOperations = new List<IOperation>();
foreach (var camera in cameras) measureOperations.Add(camera.MeasurementOp());
//------------------------------------------------
Bridge.OnActivity(this, Strings.Switching_flow_detection);
//------------------------------------------------
State.Create(string.Format("{0}({1}) : Start the pump", test.Method, test.Name))
.AddOperation(checkUiOp)
.AddOperations(readTempPressOps)
.AddOperations(measureOperations)
.AddOperation((inPath.Pump is GenericDevices.IPumpFM) ? (inPath.Pump as GenericDevices.IPumpFM).TurnOnOp(test.PumpPower) : null)
.AddOperation(cBrd.SetValvesOp(inPath.Pump, null))
.EnterState();
do {
e = StateMachine.WaitRunDevsRunOps();
Bridge.OnTestProgress(this, new TestProgressEventArgs(test, repetitionNr, Config.Entities.Progress.SwitchingFlowDetection));
if (TestAndLogUiCmdStop(test,e)) goto stopTest;
}
while (!e.Contains(Event.ValvesSet));
State.Create(string.Format("{0}({1}) : Set the initial flow", test.Method, test.Name))
.AddOperation(checkUiOp)
.AddOperations(readTempPressOps)
.AddOperations(measureOperations)
.AddOperation(outPath.RegulValve.SetFlowAndMeasureOp(outPath.FlowMeter, test.Qfrom, test.Qto, RefFlow, FlowSettingTimeoutSec, (float)test.TolerRed))
.EnterState();
do {
e = StateMachine.WaitRunDevsRunOps();
Bridge.OnTestProgress(this, new TestProgressEventArgs(test, repetitionNr, Config.Entities.Progress.SwitchingFlowDetection));
if (TestAndLogUiCmdStop(test,e)) goto stopTest;
if (e.Contains(Event.RegulValveTimeOut))
{
Bridge.OnError(this, Strings.Flow_adjustment_failed);
goto stopTest;
}
if (e.Contains(Event.Next)) goto init_flow_set;
}
while (!e.Contains(Event.FlowReached));
switch (ReadRegistersTempPressAmbient(measureOperations, false))
{
case Event.Error: goto error;
case Event.UiCmdStop: goto stopTest;
}
init_flow_set:
//====================================
// Find the switching flow
//====================================
/// Allocate detection buffers
double[] flowsForDetection = new double[DetectionBufferSize]; /// in [m3/h]
double[] pulseFreqsForDetection = new double[DetectionBufferSize];
/// Current values
flowsForDetection[0] = RefFlow.Val;
pulseFreqsForDetection[0] = 0.0f;
int startTime = StateMachine.Time;
int lastTime = StateMachine.Time;
/// Detection parameters
float rvPulse = (testParams.TargetQ > (test.Qfrom + test.Qto) / 2.0f) ? 0.05f : -0.05f; /// rise(+) or fall(-)
rvPulse *= (100.0f * testParams.RateOfChange);
bool detected = false;
bool targetReached = false;
double detectedFlow = 0;
int detectionStartTime = StateMachine.Time;
Bridge.OnTestProgress(this, new TestProgressEventArgs(test, repetitionNr, Config.Entities.Progress.SwitchingFlowDetection));
do
{
State.Create(string.Format("{0}({1}) : Change the RV position", test.Method, test.Name))
.AddOperation(checkUiOp)
.AddOperations(readTempPressOps)
.AddOperations(measureOperations)
.AddOperation(outPath.RegulValve.ChangeRegulValvePositionOp(rvPulse))
.EnterState();
do {
e = StateMachine.WaitRunDevsRunOps();
Bridge.OnTestProgress(this, new TestProgressEventArgs(test, repetitionNr, Config.Entities.Progress.SwitchingFlowDetection));
if (TestAndLogUiCmdStop(test, e)) goto stopTest;
}
while (!e.Contains(Event.PositionReached));
{
///
/// Update FIFO buffers for the reference flow and the frequency of pulses
///
/// Last pulses are kept to calculate differences
for (int i = 0; i < 2 * Config.Data.CompoundWMsCount; i++) lastWMPulses[i] = RegisterReaders[i].WMPulses;
/// Shift data in the detection buffers
for (int i = DetectionBufferSize - 2; i >= 0; i--)
{
flowsForDetection[i + 1] = flowsForDetection[i];
pulseFreqsForDetection[i + 1] = pulseFreqsForDetection[i];
}
switch (ReadRegistersTempPressAmbient(measureOperations, false))
{
case Event.Error: goto error;
case Event.UiCmdStop: goto stopTest;
}
int diff = RegisterReaders[(test.Part - 1) * 2 + 1].WMPulses - lastWMPulses[(test.Part - 1) * 2 + 1];
flowsForDetection[0] = cBrd.ReferenceFreq * outPath.FlowMeter.NominalFlow / 2000.0;
pulseFreqsForDetection[0] = (double)diff / (double)(StateMachine.Time - lastTime);
lastTime = StateMachine.Time;
}
if ((StateMachine.Time - detectionStartTime > 15) && (flowsForDetection[0] > 0) && (flowsForDetection[DetectionBufferSize - 1] > 0))
{
///
/// Evaluate ref. flow and WM pulses frequency data in FIFO buffers.
/// Updpate 'detected' and 'targetReached' flags.
///
double[] flowBefore = new double[DetectionKernelSize];
double[] flowAfter = new double[DetectionKernelSize];
double[] freqBefore = new double[DetectionKernelSize];
double[] freqAfter = new double[DetectionKernelSize];
for (int i = 0; i < DetectionKernelSize; i++)
{
flowBefore[i] = flowsForDetection[DetectionBufferSize - DetectionKernelSize + i]; /// The oldest DetectionKernelSize samples
freqBefore[i] = pulseFreqsForDetection[DetectionBufferSize - DetectionKernelSize + i];
flowAfter[i] = flowsForDetection[i]; /// The newest DetectionKernelSize samples
freqAfter[i] = pulseFreqsForDetection[i];
}
/// Skip the smallest and the largest flow
Array.Sort(flowBefore);
Array.Sort(flowAfter);
flowBefore[0] = 0;
flowAfter[0] = 0;
flowBefore[DetectionKernelSize - 1] = 0;
flowAfter[DetectionKernelSize - 1] = 0;
///
double aveFlowBefore = 0;
double aveFlowAfter = 0;
foreach (var f in flowBefore) aveFlowBefore += f;
foreach (var f in flowAfter) aveFlowAfter += f;
aveFlowBefore /= (double)(DetectionKernelSize - 2);
aveFlowAfter /= (double)(DetectionKernelSize - 2);
/// Do NOT skip the smallest and the largest flow
//Array.Sort(freqBefore);
//Array.Sort(freqAfter);
//freqBefore[0] = 0;
//freqAfter[0] = 0;
//freqBefore[DetectionKernelSize - 1] = 0;
//freqAfter[DetectionKernelSize - 1] = 0;
///
double aveFreqBefore = 0;
double aveFreqAfter = 0;
foreach (var f in freqBefore) aveFreqBefore += f;
foreach (var f in freqAfter) aveFreqAfter += f;
aveFreqBefore /= (double)DetectionKernelSize;
aveFreqAfter /= (double)DetectionKernelSize;
UiBridge.Bridge.OnLog(this, string.Format("time={0}, flow{1}, aveFlowB={2}, aveFlowA={3}, pulseFreq={4}, aveFreqB={5}, aveFreqA={6}\r\n",
StateMachine.Time - startTime,
flowsForDetection[0].ToString("F2"),
aveFlowBefore.ToString("F2"),
aveFlowAfter.ToString("F2"),
pulseFreqsForDetection[0].ToString("F2"),
aveFreqBefore.ToString("F2"),
aveFreqAfter.ToString("F2")));
//detectedFlow = (aveFlowBefore + aveFlowAfter) / 2.0f;
detectedFlow = aveFlowBefore;
if (rvPulse > 0)
{
/// rise
detected = (aveFreqAfter < aveFreqBefore * (1.0f - testParams.DetectionThreshold));
targetReached = ((aveFlowAfter + aveFlowBefore) / 2.0f) > testParams.TargetQ;
}
else
{
/// fall
detected = (aveFreqAfter > (aveFreqBefore + testParams.OffsetPulsesFreq) * (1.0f + testParams.DetectionThreshold));
targetReached = ((aveFlowAfter + aveFlowBefore) / 2.0f) < testParams.TargetQ;
}
}
}
while (!detected && !targetReached);
if (rvPulse > 0)
{
Qrise = detectedFlow;
}
else
{
Qfall = detectedFlow;
}
UiBridge.Bridge.OnLog(this, string.Format("detected flow={0}\r\n", detectedFlow.ToString("F2")));
float qfrom_detected = (float)(detectedFlow + testParams.RelativeQfrom);
float qto_detected = (float)(detectedFlow + testParams.RelativeQto);
/// Update test results with the test flow determined from the detected switching flow
float Qave_lps = (qfrom_detected + qto_detected) / 7.2f;
float testTimeFromDetectedFlow = test.Volume / Qave_lps; /// Test volume wont be changed
float relativeQave = (testParams.RelativeQfrom + testParams.RelativeQto) / 2.0f;
bool goBackToInitFlow = ((rvPulse > 0) && (relativeQave < 0)) ||
((rvPulse < 0) && (relativeQave > 0));
Bridge.OnProcessData(this, new ProcessDataEventArgs(test, repetitionNr, Config.Entities.Progress.FlowSetting));
Bridge.OnTestProgress(this, new TestProgressEventArgs(test, repetitionNr, Config.Entities.Progress.FlowSetting));
int flowSetTime0 = StateMachine.Time;
if (goBackToInitFlow)
{
//--------------------------------
State.Create(string.Format("{0}({1}) : Switching flow detected, going back", test.Method, test.Name))
.AddOperation(checkUiOp)
.AddOperations(readTempPressOps)
.AddOperations(measureOperations)
.AddOperation(outPath.RegulValve.SetFlowOp(outPath.FlowMeter, test.Qfrom, test.Qto, RefFlow, FlowSettingTimeoutSec))
.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)) goto stopTest;
if (e.Contains(Event.RegulValveTimeOut))
{
Bridge.OnError(this, Strings.Flow_adjustment_failed);
goto stopTest;
}
}
while (!e.Contains(Event.FlowReached));
}
//--------------------------------
State.Create(string.Format("{0}({1}) : Going to the test flow", test.Method, test.Name))
.AddOperation(checkUiOp)
.AddOperations(readTempPressOps)
.AddOperations(measureOperations)
.AddOperation(outPath.RegulValve.SetFlowOp(outPath.FlowMeter, qfrom_detected, qto_detected, RefFlow, FlowSettingTimeoutSec))
//.AddOp(pOut.RegulValve.SetPositionOp(35.0f, 38.0f, uint.MaxValue))
.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)) goto stopTest;
//if (e.Contains(Event.FlowTimeOut)) goto do_detection;
}
while (!e.Contains(Event.FlowReached));
int flowSetTime = StateMachine.Time - flowDetectTime0;
//start_measurement:
//------------------------------------------------
Bridge.OnActivity(this, Strings.Measuring_the_weight);
//------------------------------------------------
State.Create(Strings.Measure_the_mass)
.AddOperation(checkUiOp)
.AddOperations(readTempPressOps)
.AddOperations(measureOperations)
.AddOperation(scale.ReadStableMassOp(ref StartMass, test.MassRepeats, test.MassSpread, test.MassMethod))
.AddOperation(new Operations.TimerOp(StableMassMsrmntTimeoutSec))
.EnterState();
do {
e = StateMachine.WaitRunDevsRunOps();
if (e.Contains(Event.Error)) goto error;
if (TestAndLogUiCmdStop(test,e)) goto stopTest;
if (e.Contains(Event.TimerExpired))
{
Bridge.OnError(this, Strings.Mass_measurement_timeout);
goto stopTest;
}
}
while (!e.Contains(Event.BalanceDone));
///
Mass.Val = StartMass.Val;
tMass1 = StateMachine.Time;
//------------------------------------------------
Bridge.OnActivity(this, Strings.Test_in_progress);
//------------------------------------------------
State.Create(Strings.Start_the_test)
.AddOperation(checkUiOp)
.AddOperations(readTempPressOps)
.AddOperations(measureOperations)
.AddOperation(cBrd.StartMeasurementOp(outPath, (Elde.TestMethods.Diverter | Elde.TestMethods.Synchro), qfrom_detected, qto_detected, totalPulses))
.EnterState();
do {
e = StateMachine.WaitRunDevsRunOps();
if (e.Contains(Event.Error)) goto error;
if (TestAndLogUiCmdStop(test,e)) goto stopTest;
}
while (!e.Contains(Event.MeasurementStarted));
///
/// Measurement loop - preparation
///
queryEnd1 = cBrd.QueryMeasurementEndOp();
queryEnd2 = cBrd.QueryMeasurementEndOp();
StartNewStatistics(StateMachine.Time, BatchRslts.Batch.BatchNr, test.Name, repetitionNr, 0);
int estimtdEndTime = StateMachine.Time + (int)test.TstTime;
/// Read the diverter switch time
switchTimeStart = 0.001f * (float)cBrd.DivTime(0);
log.WarnFormat("Diverter switch time on test start = {0} ms", cBrd.DivTime(0));
/// Measurement loop - begin
while (true)
{
//--------------------------------
switch (ReadRegistersTempPressAmbient(measureOperations, true))
{
case Event.Error: goto error;
case Event.UiCmdStop: goto stopTest;
case Event.MeasurementCompleted: goto measurement_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));
}
UpdateAllStatistics(StateMachine.Time);
/// TODO: Reimplement
//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));
}
/// Measurement loop - end
measurement_completed:
//------------------------------------------------
Bridge.OnActivity(this, Strings.Measuring_the_weight);
//------------------------------------------------
State.Create(string.Format("{0}({1}) : Measuring the mass", test.Method, test.Name))
.AddOperation(checkUiOp)
.AddOperations(readTempPressOps)
.AddOperation(scale.ReadStableMassOp(ref EndMass, test.MassRepeats, test.MassSpread, test.MassMethod))
.AddOperation(new Operations.TimerOp(StableMassMsrmntTimeoutSec))
.EnterState();
do {
e = StateMachine.WaitRunDevsRunOps();
if (e.Contains(Event.Error)) goto error;
if (TestAndLogUiCmdStop(test,e)) goto stopTest;
if (e.Contains(Event.TimerExpired))
{
Bridge.OnError(this, Strings.Mass_measurement_timeout);
goto stopTest;
}
}
while (!e.Contains(Event.BalanceDone));
///
tMass2 = StateMachine.Time;
TestEndTime = DateTime.Now;
/// Read the diverter switch time
switchTimeEnd = 0.001f * (float)cBrd.DivTime(0);
log.WarnFormat("Diverter switch time on test end = {0} ms", cBrd.DivTime(0));
//------------------------------------------------
Bridge.OnActivity(this, Strings.Test_completed);
//------------------------------------------------
State.Create(Strings.Stop_the_pump)
.AddOperation(checkUiOp)
.AddOperations(readTempPressOps)
.AddOperation((inPath != null && inPath.Pump is GenericDevices.IPumpFM) ? (inPath.Pump as GenericDevices.IPumpFM).TurnOffOp() : null)
.AddOperation(cBrd.SetValvesOp(null, inPath.Pump))
.EnterState();
do {
e = StateMachine.WaitRunDevsRunOps();
if (TestAndLogUiCmdStop(test,e)) goto stopTest;
}
while (!e.Contains(Event.ValvesSet));
//--------------------------------
State.Create(string.Format("{0}({1}) : Stop_diverter_gate_etc", test.Method, test.Name))
.AddOperation(checkUiOp)
.AddOperations(readTempPressOps)
.AddOperation(cBrd.StopPreviousOp())
.EnterState();
do {
e = StateMachine.WaitRunDevsRunOps();
if (TestAndLogUiCmdStop(test,e)) goto stopTest;
}
while (!e.Contains(Event.PreviousStopped));
/// 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.TimeBtwnMassMsrmnts = tMass2 - tMass1;
tstRslt.TestTime = cBrd.TTime; /// [s] measurement time
tstRslt.PulsesMaster = Convert.ToDouble(cBrd.EtPulses(0)); /// Pulses of the master flow meter (test total)
tstRslt.MassStartRaw = StartMass.Val;
tstRslt.MassStart = Config.Formulas.CorrectedValue(tstRslt.MassStartRaw, scale.Corrections);
tstRslt.MassEndRaw = EndMass.Val;
tstRslt.MassEnd = Config.Formulas.CorrectedValue(tstRslt.MassEndRaw, scale.Corrections);
tstRslt.FlowMass = 3600.0 * (tstRslt.MassEnd - tstRslt.MassStart) / tstRslt.TestTime; /// [kg/h]
tstRslt.FlowVolume = 3.6 * LtrPerRefPulse * cBrd.EtPulses(0) / tstRslt.TestTime; /// [m3/h]
tstRslt.Buoyancy = Config.Formulas.Buoyancy();
tstRslt.VolumeCTV = 1000 * tstRslt.Buoyancy * (tstRslt.MassEnd - tstRslt.MassStart) / tstRslt.DensityLine; /// [l] commercially true volume
tstRslt.VolumeMaster = LtrPerRefPulse * tstRslt.PulsesMaster; /// [l] volume from the master flow meter
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, true, false, switchTimeStart, switchTimeEnd) : 0;
for (int i = 0; i < BatchRslts.WMPositionsCount; i++)
{
if (!test.IsPartCompatible(Utils.PartNr(i + 1, BatchRslts.Batch.Compound))) continue;
Results.Entities.MeterTestRslt mainMeterRslt = BatchRslts.GetMeterTestRslt(testName, i, Config.Entities.CompoundMeterId.CompoundMain);
Results.Entities.MeterTestRslt auxMeterRslt = BatchRslts.GetMeterTestRslt(testName, i, Config.Entities.CompoundMeterId.CompoundAux);
for (int isAux = 0; isAux <= 1; isAux++) /// 0=main, 1=aux
{
GenericDevices.IRegisterReader regReader = sensPath.RegisterReaders[2 * i + isAux];
Results.Entities.MeterTestRslt meterRslt = (isAux == 0) ? mainMeterRslt : auxMeterRslt;
if (meterRslt != null && regReader != null)
{
meterRslt.RegReaderType = (int)regReader.RegisterReaderType;
meterRslt.PulsesPerLiter = regReader.PulsesPerLtr;
/// Optionally supress pulses from the large water meter
meterRslt.PulsesMeter = (isAux == 0 && testParams.SupressTrills) ? 0 : Convert.ToDouble(regReader.WMPulses);
meterRslt.PulsesMaster = Convert.ToDouble(regReader.WMRefPulses);
meterRslt.TestTime = cBrd.TTime;
meterRslt.VolumeStart = 0;
meterRslt.VolumeEnd = 0;
meterRslt.VolumeRef = tstRslt.VolumeCTV;
meterRslt.VolumeMeter = meterRslt.PulsesMeter * regReader.LtrsPerPulse; /// liter
///
if (meterRslt.PulsesMaster != 0)
{
meterRslt.VolumeMeter *= (tstRslt.PulsesMaster / meterRslt.PulsesMaster);
}
meterRslt.Error = Config.Formulas.ErrorFromVolumes(meterRslt.VolumeMeter, tstRslt.VolumeCTV); /// Main/Aux meter error is not usedfor evaluation
}
}
Results.Entities.MeterTestRslt compoundMeterRslt = BatchRslts.GetMeterTestRslt(testName, i, Config.Entities.CompoundMeterId.Compound);
if (compoundMeterRslt != null && mainMeterRslt != null && auxMeterRslt != null)
{
compoundMeterRslt.VolumeRef = tstRslt.VolumeCTV;
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.VolumeCTV, tstRslt.TestTime) + test.Uncertainty)
&& (compoundMeterRslt.Error <= test.GetErrLimHi(tstRslt.VolumeCTV, tstRslt.TestTime) - 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;
if (Qrise != 0) BatchRslts.WaterMeters[i].QRise = Qrise;
if (Qfall != 0) BatchRslts.WaterMeters[i].QFall = Qfall;
}
}
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.RegulValve != null ? outPath.RegulValve.Name : string.Empty,
outPath.Diverter != null ? outPath.Diverter.Name : string.Empty));
/// 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(testName, tstRslt));
}
Bridge.OnTestProgress(this, new TestProgressEventArgs(test, repetitionNr, Config.Entities.Progress.TransitionAfter));
/// Append the results to the CSV-file
allResults.Info(TestResult2CsvLine(testName, test.Part));
///----------------------///
/// Quit this sequence ///
///----------------------///
if (isLastRepetition)
{
/// Stop the pump
State.Create(string.Format("{0}({1}) : Test(s) completed -> Stopping the pump", test.Method, test.Name))
.AddOperation(checkUiOp)
.AddOperation(cBrd.SetValvesOp(null, inPath.Pump))
.AddOperation((inPath != null && inPath.Pump is GenericDevices.IPumpFM) ? (inPath.Pump as GenericDevices.IPumpFM).TurnOffOp() : null)
.EnterState();
do {
e = StateMachine.WaitRunDevsRunOps();
if (e.Contains(Event.Error)) goto error;
}
while (!e.Contains(Event.ValvesSet) || ((inPath.Pump is GenericDevices.IPumpFM) && !e.Contains(Event.TurnPumpOnOffDone)));
}
return new List<Event> { Event.Done };
//====================================
stopTest:
State.Create(string.Format("{0}({1}) : User selected STOP -> Closing the valves", test.Method, test.Name))
.AddOperation(checkUiOp)
.AddOperation((inPath != null && inPath.Pump is GenericDevices.IPumpFM) ? (inPath.Pump as GenericDevices.IPumpFM).TurnOffOp() : null)
.AddOperation(cBrd.SetValvesOp(StateMachine.DefaultValvesOpen, StateMachine.DefaultValvesClose))
.EnterState();
do
{
e = StateMachine.WaitRunDevsRunOps();
if (e.Contains(Event.Error)) goto error;
}
while (!e.Contains(Event.ValvesSet));
return new List<Event> { Event.UiCmdStop };
//====================================
error:
State.Create("close_before_error")
.AddOperation(checkUiOp)
.AddOperation((inPath != null && inPath.Pump is GenericDevices.IPumpFM) ? (inPath.Pump as GenericDevices.IPumpFM).TurnOffOp() : null)
.AddOperation(cBrd.SetValvesOp(StateMachine.DefaultValvesOpen, StateMachine.DefaultValvesClose))
.EnterState();
do
{
e = StateMachine.WaitRunDevsRunOps();
if (e.Contains(Event.Error)) break;
}
while (!e.Contains(Event.ValvesSet));
return new List<Event> { Event.Error };
}
IList<Event> Simulate(Config.Entities.Test test, int repetitionNr, bool isLastRepetition,
CombinedWithDetTestParams testParams)
{
///
/// Test method simulation
///
Bridge.OnTestProgress(this, new TestProgressEventArgs(test, repetitionNr, Config.Entities.Progress.FlowSetting));
if (test.Name.ToLower().Contains("rise") || test.Name.ToLower().Contains("steig"))
{
MakeSimulatedCompound(test, 1, 0, 0.7f, 0.0f);
}
else
{
MakeSimulatedCompound(test, 1, 0, 0.7f, 0.9f);
}
Bridge.OnTestProgress(this, new TestProgressEventArgs(test, repetitionNr, Config.Entities.Progress.Completed));
Bridge.OnTestCompleted(this, new TestCompletedEventArgs(test.Name, BatchRslts.GetTestRslt(Results.Utils.GetTestName(test.Name, 1, 1), 0)));
allResults.Info(TestResult2CsvLine(test.Name, 0)); /// Append the results to the CSV-file
//------------------------------------------------
Bridge.OnActivity(this, string.Format("Simulating {0}", test.Name));
//------------------------------------------------
State.Create(string.Format("{0}({1}) : Simulating {1}", test.Method, test.Name))
.AddOperation(checkUiOp)
.EnterState();
IList<Event> e = StateMachine.WaitRunDevsRunOps();
return new List<Event> { TestAndLogUiCmdStop(test, e) ? Event.UiCmdStop : Event.Done };
}
}
}