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

869 lines
42 KiB
C#

///
/// Copyright (c) 2013-2023 Sensus Slovensko a.s.
///
using System;
using System.Collections.Generic;
using log4net;
using Common;
using Config.Entities;
using TBF.Resources;
using TBF.Rig.GenericDevices;
using TBF.UiBridge;
namespace TBF.Rig.TestMethods.CombinedWithDetection
{
public class CombinedWithDetectionSeq : Sequences.SequenceBase
{
private static readonly ILog log = LogManager.GetLogger(typeof(CombinedWithDetectionSeq));
const int DetectionBufferSize = 9;
const int DetectionKernelSize = 5;
/// <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.ControlBoard 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 (!(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;
}
public IList<Event> Execute(Config.Entities.Test test, int repetitionNr, bool isLastRepetition,
bool isDelayedStart, CombinedWithDetTestParams testParams,
Common.DebugMode debugLevel)
{
if (debugLevel == Common.DebugMode.Simulate)
{
return Simulate(test, repetitionNr, isLastRepetition, testParams);
}
ControlBoard.Uni.UniCB cBrd = StateMachine.ControlBoard as 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 ???
}
if (test.Part < 0 || test.Part > TBF.Data.CompoundWMsCount)
{
UiBridge.Bridge.OnError(this, string.Format("Test 'Part' should be '-' or 1 .. {0}", TBF.Data.CompoundWMsCount));
return new List<Event> { Event.ConfigurationError };
}
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, false);
/// Since CheckDeviceCaps() passed 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.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));
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));
/// Specific for combined meters
int[] lastWMPulses = new int[2 * TBF.Data.CompoundWMsCount];
cBrd.StopAll(false);
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, heatMetersPath));
string testName = Results.Utils.GetTestName(test.Name, test.Repeats, repetitionNr);
TestStartTime = DateTime.Now;
Bridge.OnTestProgress(this, new TestProgressEventArgs(test, repetitionNr, Progress.FlowSetting));
Qrise = 0;
Qfall = 0;
double estimatedEndMass = scale.Mass + test.Volume;
if (test.DoDraining || estimatedEndMass >= scale.Capacity * Constants.TankFullFactor)
{
/// Empty the water tank
switch (DrainTheTank(scale, readTempPressOps))
{
case Event.Error: { retVal = Event.Error; goto stopTest; }
case Event.UiCmdStop: { retVal = Event.UiCmdStop; goto stopTest; }
}
}
int flowDetectTime0 = StateMachine.Time;
///
/// Prepare cameras, ROI-s and measurementOperations
///
/// Find ROI-s
IList<IRegReaderLiveCamera> rois = new List<IRegReaderLiveCamera>();
foreach (var rr in sensPath.RegisterReaders)
{
var cameraRoI = rr as IRegReaderLiveCamera;
if (cameraRoI != null && cameraRoI.Detected) rois.Add(cameraRoI);
}
/// Find cameras
var 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
var 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, 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.RegValve.SetFlowAndMeasureOp(outPath.FlowMeter, test.Qfrom, test.Qto, RefFlow, FlowSettingTimeoutSec, (float)test.ShortPulses))
.EnterState();
do {
e = StateMachine.WaitRunDevsRunOps();
Bridge.OnTestProgress(this, new TestProgressEventArgs(test, repetitionNr, 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: { retVal = Event.Error; goto stopTest; }
case Event.UiCmdStop: { retVal = 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.0) ? 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, 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.RegValve.ChangeRegValvePositionOp(rvPulse))
.EnterState();
do {
e = StateMachine.WaitRunDevsRunOps();
Bridge.OnTestProgress(this, new TestProgressEventArgs(test, repetitionNr, Progress.SwitchingFlowDetection));
if (e.Contains(Event.Error)) { retVal = Event.Error; goto stopTest; }
if (TestAndLogUiCmdStop(test, e)) { retVal = Event.UiCmdStop; 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 * TBF.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: { retVal = Event.Error; goto stopTest; }
case Event.UiCmdStop: { retVal = Event.UiCmdStop; goto stopTest; }
}
flowsForDetection[0] = cBrd.RefFrequency * outPath.FlowMeter.NominalFlow / outPath.FlowMeter.NominalFreq;
double diff = RegisterReaders[Math.Max(0, test.Part - 1) * 2 + 1].WMPulses - lastWMPulses[Math.Max(0, test.Part - 1) * 2 + 1];
pulseFreqsForDetection[0] = 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.OnCompoundDetection(this, string.Format("time={0}, flow{1}, aveFlowB={2}, aveFlowA={3}, pulseFreq={4}, aveFreqB={5}, aveFreqA={6}",
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;
if (rvPulse > 0)
{
/// rise
detected = (aveFreqAfter < aveFreqBefore * (1 - testParams.DetectionThreshold));
targetReached = ((aveFlowAfter + aveFlowBefore) / 2) > testParams.TargetQ;
}
else
{
/// fall
detected = (aveFreqAfter > (aveFreqBefore + testParams.OffsetPulsesFreq) * (1 + testParams.DetectionThreshold));
targetReached = ((aveFlowAfter + aveFlowBefore) / 2) < testParams.TargetQ;
}
}
}
while (!detected && !targetReached);
if (rvPulse > 0)
{
Qrise = detectedFlow;
}
else
{
Qfall = detectedFlow;
}
UiBridge.Bridge.OnCompoundDetection(this, string.Format("detected flow={0}", detectedFlow.ToString("F2")));
double qfrom_detected = detectedFlow + testParams.RelativeQfrom;
double qto_detected = detectedFlow + testParams.RelativeQto;
/// Update test results with the test flow determined from the detected switching flow
double Qave_lps = (qfrom_detected + qto_detected) / 7.2;
double testTimeFromDetectedFlow = test.Volume / Qave_lps; /// Test volume wont be changed
double relativeQave = (testParams.RelativeQfrom + testParams.RelativeQto) / 2.0;
bool goBackToInitFlow = ((rvPulse > 0) && (relativeQave < 0)) ||
((rvPulse < 0) && (relativeQave > 0));
Bridge.OnTestProgress(this, new TestProgressEventArgs(test, repetitionNr, 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(cBrd.SetFlowOp(test.Qfrom, test.Qto, RefFlow, FlowSettingTimeoutSec))
.EnterState();
do {
e = StateMachine.WaitRunDevsRunOps();
Bridge.OnTestProgress(this, new TestProgressEventArgs(test, repetitionNr, 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.RegValve.SetFlowOp(outPath.FlowMeter, qfrom_detected, qto_detected, RefFlow, FlowSettingTimeoutSec, 0))
//.AddOp(pOut.RegulValve.SetPositionOp(35.0f, 38.0f, uint.MaxValue))
.EnterState();
do {
e = StateMachine.WaitRunDevsRunOps();
Bridge.OnTestProgress(this, new TestProgressEventArgs(test, repetitionNr, 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);
//----------------------------------------------------
LogProcessDataTestInfo(processDataLogger, test.Procedure.Name, test.Name);
if (heatMetersPath == null) LogProcessDataHeader(processDataLogger, "Start mass");
else LogProcessDataHeaderHeatMeters(processDataLogger, "Start mass");
State.Create(Strings.Measure_the_mass)
.AddOperation(checkUiOp)
.AddOperations(readTempPressOps)
.AddOperations(measureOperations)
.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;
//------------------------------------------------
Bridge.OnActivity(this, Strings.Test_in_progress);
//------------------------------------------------
/// Measurement loop preparation
int estimtdEndTime = StateMachine.Time + Convert.ToInt32(testTimeFromDetectedFlow);
int remainingTime;
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);
State.Create(Strings.Start_the_test)
.AddOperation(checkUiOp)
.AddOperations(readTempPressOps)
.AddOperations(measureOperations)
.AddOperation(cBrd.FlyingStartStopTestOp(test, qfrom_detected, qto_detected, totalPulses, true, isDelayedStart, 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}", 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));
/// 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));
/// Measurement loop end
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 (isLastRepetition && transitionAfter == null)
{
if (inPath.Pump is GenericDevices.IPumpFM) (inPath.Pump as GenericDevices.IPumpFM).TurnOff();
State.Create("SequenceBase : Transition : TestEnd - Default action")
.AddOperation(checkUiOp)
.AddOperations(readTempPressOps)
.AddOperation(cBrd.SetValvesOp(StateMachine.DefaultValvesOpen, StateMachine.DefaultValvesClose))
.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.ValvesSet));
}
//------------------------------------------------
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.TimeStop2Mass, test.MassMethod, test.MassRepeats, test.MassSpread))
.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;
if (test.DoDrainingAfter)
{
State.Create(string.Format("{0}({1}) : Open the drain valve", test.Method, test.Name))
.AddOperation(checkUiOp)
.AddOperation(StateMachine.ControlBoard.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));
}
/// Read the diverter switch time
if (StateMachine.ControlBoard is ControlBoard.Uni.UniCB)
{
ControlBoard.Uni.UniCB eldeCB = StateMachine.ControlBoard as ControlBoard.Uni.UniCB;
//switchTimeEnd = 0.001f * (float)eldeCB.DivTime(0);
//log.WarnFormat("Diverter switch time on test end = {0} ms", eldeCB.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 (e.Contains(Event.Error)) { retVal = Event.Error; goto stopTest; }
if (TestAndLogUiCmdStop(test, e)) { retVal = Event.UiCmdStop; goto stopTest; }
}
while (!e.Contains(Event.ValvesSet));
cBrd.StopAll(false);
/// 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);
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 = cBrd.TestTime; /// [s] measurement time
tstRslt.PulsesMaster = Convert.ToDouble(cBrd.RefPulses); /// 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 = tstRslt.ConstMasterRaw * 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 = 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 = 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 != null) ? outPath.Diverter.SwitchTimeStart.Val : 0;
tstRslt.DivStart10 = 0;
tstRslt.DivStart50 = 0;
tstRslt.DivStart90 = 0;
tstRslt.DiverterEnd = (outPath.Diverter != null) ? outPath.Diverter.SwitchTimeEnd.Val : 0;
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;
for (int i = 0; i < BatchRslts.WMPositionsCount; i++)
{
if (!test.IsPartCompatible(Utils.PartNr(i + 1, BatchRslts.Batch.Compound))) continue;
var mainMeterRslt = BatchRslts.GetMeterTestRslt(testName, i, CompoundMeterId.CompoundMain);
var auxMeterRslt = BatchRslts.GetMeterTestRslt(testName, i, CompoundMeterId.CompoundAux);
for (int isAux = 0; isAux <= 1; isAux++) /// 0=main, 1=aux
{
GenericDevices.IRegReader regReader = sensPath.RegisterReaders[2 * i + isAux];
var oneMTR = (isAux == 0) ? mainMeterRslt : auxMeterRslt;
if (oneMTR != null && regReader != null)
{
oneMTR.RegReaderType = (int)regReader.RegisterReaderType;
oneMTR.PulsesPerLiter = regReader.PulsesPerLtr;
/// Optionally supress pulses from the large water meter
oneMTR.PulsesMeter = (isAux == 0 && testParams.SupressTrills) ? 0 : Convert.ToDouble(regReader.WMPulses);
oneMTR.PulsesMaster = Convert.ToDouble(regReader.WMRefPulses);
oneMTR.TestTime = cBrd.TestTime;
oneMTR.VolumeStart = 0;
oneMTR.VolumeEnd = 0;
oneMTR.VolumeRef = tstRslt.VolumeCTV;
if (oneMTR.PulsesMaster != 0)
{
oneMTR.PulsesMeter *= (tstRslt.PulsesMaster / oneMTR.PulsesMaster);
oneMTR.PulsesMaster = tstRslt.PulsesMaster;
}
oneMTR.VolumeMeter = oneMTR.PulsesMeter * regReader.LtrsPerPulse; /// liter
oneMTR.Error = Formulas.ErrorFromVolumes(oneMTR.VolumeMeter, tstRslt.VolumeCTV); /// Main/Aux meter error is not usedfor evaluation
}
}
var compoundMTR = BatchRslts.GetMeterTestRslt(testName, i, CompoundMeterId.Compound);
if (compoundMTR != null && mainMeterRslt != null && auxMeterRslt != null)
{
compoundMTR.VolumeRef = tstRslt.VolumeCTV;
compoundMTR.VolumeMeter = mainMeterRslt.VolumeMeter + auxMeterRslt.VolumeMeter;
compoundMTR.PulsesMaster = tstRslt.PulsesMaster;
compoundMTR.TestTime = tstRslt.TestTime;
compoundMTR.Error = Formulas.ErrorFromVolumes(compoundMTR.VolumeMeter, compoundMTR.VolumeRef);
compoundMTR.Passed = (compoundMTR.Error >= test.GetErrLimLo(tstRslt.VolumeCTV, tstRslt.TestTime) + test.Uncertainty)
&& (compoundMTR.Error <= test.GetErrLimHi(tstRslt.VolumeCTV, tstRslt.TestTime) - test.Uncertainty)
&& (tstRslt.ErrorFlags == 0);
mainMeterRslt.Passed = auxMeterRslt.Passed = compoundMTR.Passed;
mainMeterRslt.TestDone = auxMeterRslt.TestDone = compoundMTR.TestDone = true;
tstRslt.TestDone = true;
if (Qrise != 0) BatchRslts.Batch.WaterMeters[i].QRise = Qrise;
if (Qfall != 0) BatchRslts.Batch.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.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));
///----------------------///
/// Quit this sequence ///
///----------------------///
if (isLastRepetition || stopCycle)
{
/// 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)) { retVal = Event.Error; goto stopTest; }
if (e.Contains(Event.UiCmdStop)) { retVal = Event.UiCmdStop; goto stopTest; }
}
while (!e.Contains(Event.ValvesSet) || ((inPath.Pump is GenericDevices.IPumpFM) && !e.Contains(Event.TurnPumpOnOffDone)));
}
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 };
}
IList<Event> Simulate(Config.Entities.Test test, int repetitionNr, bool isLastRepetition,
CombinedWithDetTestParams testParams)
{
///
/// Test method simulation
///
Bridge.OnTestProgress(this, new TestProgressEventArgs(test, repetitionNr, 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, 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 };
}
}
}