/// /// Copyright (c) 2013-2017 Sensus Metering Systems /// using System; using System.Collections.Generic; using System.Text; using log4net; using TBF.BenchControl; using TBF.Resources; using TBF.UiBridge; 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 Execute(Config.Entities.Test test, bool outerLoopMode, int outerLoopCounter, CombinedWithDetTestParams testParams, Config.Entities.DebugMode debugLevel) { IList e = new List(); /// Events from currently running operations checkUiOp = new Operations.CheckUIOp(true); /// Runs in more then one state if (test.Part < 1 || test.Part > Config.Data.CompoundWMsCount) { UiBridge.Bridge.OnError(this, string.Format("Test 'Part' should be 1 .. {0}", Config.Data.CompoundWMsCount)); IList retval = new List(1); retval.Add(Event.ConfigurationError); return retval; } if (debugLevel == Config.Entities.DebugMode.Simulate) { /// /// Test method simulation /// TestProgressEventArgs.SetEstimatedTimes(new int[] { 0, 0, 0, 30, 0, 30, 0, 0 }); Bridge.OnTestProgress(this, new TestProgressEventArgs(test, Config.Entities.Progress.JustStarted)); Bridge.OnTestProgress(this, new TestProgressEventArgs(test, Config.Entities.Progress.FlowSetting)); if (test.Name.ToLower().Contains("rise") || test.Name.ToLower().Contains("steig")) { MakeSimulatedCompound(test.Name, 1, 1, 0, 0.7f, 0.0f); } else { MakeSimulatedCompound(test.Name, 1, 1, 0, 0.7f, 0.9f); } Bridge.OnTestProgress(this, new TestProgressEventArgs(test, 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 for (int i = 0; i < Config.Data.WMsCount; i++) { TestMethods.iPerlCommunication.iPerlHead.IperlHead iPerl = ((sensPath.RegisterReaders != null) && (i < sensPath.RegisterReaders.Length)) ? (sensPath.RegisterReaders[i] as TestMethods.iPerlCommunication.iPerlHead.IperlHead) : null; if (iPerl != null) { /// TODO: Reimplement //iPerl.LastTestResult = meterRslt; /// Save this water meter test result to iPerl WM iPerl.NominalTestFlowLph = 500.0 * (double)(test.Qfrom + test.Qto); /// Ave. + convert to liter/hour } } //------------------------------------------------ Bridge.OnActivity(this, string.Format("Simulating {0}", test.Name)); //------------------------------------------------ State.Create(string.Format("CombinedWithDetection : Simulating {0}", test.Name)) .AddOperation(checkUiOp) .EnterState(); e = StateMachine.WaitRunDevsRunOps(); Event retVal = Event.Done; if (TestAndLogUiCmdStop(test, e)) retVal = Event.UiCmdStop; /// Create a list with one item 'retVal' (default is Event.Done) and return it IList retListSim = new List(1); retListSim.Add(retVal); return retListSim; } Elde.ControlBoardDev cBrd = StateMachine.ControlBoard; /// Specific for combined meters int[] lastWMPulses = new int[2 * Config.Data.CompoundWMsCount]; //-------------------------------- State.Create("CombinedWithDetection : stopTest diverter gate etc") .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); processDataLoggingOp = new TBF.BenchControl.Operations.ProcessDataLoggingOp(processDataLogger, this, false); /// Meters path is required for the following: readRegistersOp = new Operations.ReadMoreRegistersOp(sensPath.RegisterReaders); int repetitionNr = outerLoopMode ? outerLoopCounter : 1; /// First test: repetitionNr=1 //==================================== // Transition or SetRoute - Start //==================================== switch (Transition(transitionBefore, TransitionContext.BeforeTest)) { case Event.Error: goto error; case Event.UiCmdStop: goto stopTest; } //==================================== loop: /// Start the test, initialize test results Bridge.OnTestSelected(this, new TestSelectedEventArgs(test, repetitionNr, inPath, benchPath, outPath, sensPath, (int)totalPulses)); string testName = Results.Utils.GetTestName(test.Name, test.Repeats, repetitionNr); TestStartTime = DateTime.Now; TestProgressEventArgs.SetEstimatedTimes(new int[] { 1, 1, 120, 30, 0, Convert.ToInt32(test.TstTime) + 15, 0, 0 }); Bridge.OnTestProgress(this, new TestProgressEventArgs(test, repetitionNr, Config.Entities.Progress.JustStarted)); Qrise = 0; Qfall = 0; if (!test.DoDraining) /// Do not skip emptying if test.Emptying==true { //-------------------------------- State.Create("CombinedWithDetection : Mesuring mass of water in the tank") .AddOperation(checkUiOp) .AddOperation(outPath.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 < outPath.Scale.Capacity * Constants.TankFullFactor) { goto switching_flow_detection; /// Enough room in the tank -> skip emptying } } // Empty the water tank switch (DrainTheTank(outPath.Scale.DrainValve, outPath.Scale)) { 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 rois = new List(); foreach (var rr in sensPath.RegisterReaders) { GenericDevices.IRoi roi = rr as GenericDevices.IRoi; if (roi != null && roi.Detected) { rois.Add(roi); } } /// Find cameras IList cameras = new List(); 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 measureOperations = new List(); foreach (var camera in cameras) measureOperations.Add(camera.MeasurementOp()); //------------------------------------------------ Bridge.OnActivity(this, Strings.Switching_flow_detection); //------------------------------------------------ State.Create("CombinedWithDetection : Start the pump") .AddOperation(checkUiOp) .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("CombinedWithDetection : Set the initial flow") .AddOperation(checkUiOp) .AddOperations(measureOperations) .AddOperation(outPath.RegulValve.SetFlowAndMeasureOp(outPath.FlowMeter, test.Qfrom, test.Qto, outPath.PidCoef, RefFlow, 600, (float)test.TolerRed)) /// timeout = 10 min. .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.Timeout); goto error; } } while (!e.Contains(Event.FlowReached)); //-------------------------------- switch (ReadRegistersTempPressAmbient(measureOperations, false)) { case Event.Error: goto error; case Event.UiCmdStop: goto stopTest; } //==================================== // Find the switching flow //==================================== /// Allocate detection buffers double[] flowsForDetection = new double[DetectionBufferSize]; 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("CombinedWithDetection : Change the RV position") .AddOperation(checkUiOp) .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)); // 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 time = StateMachine.Time; int diff = RegisterReaders[(test.Part - 1) * 2 + 1].WMPulses - lastWMPulses[(test.Part - 1) * 2 + 1]; flowsForDetection[0] = cBrd.ReferenceFreq * outPath.FlowMeter.NominalFlow / 2000.0f; pulseFreqsForDetection[0] = (float)diff / (float)(time - lastTime); lastTime = StateMachine.Time; if (StateMachine.Time - detectionStartTime > 15) { if ((flowsForDetection[0] > 0) && (flowsForDetection[DetectionBufferSize - 1] > 0)) { 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]; freqBefore[i] = pulseFreqsForDetection[DetectionBufferSize - DetectionKernelSize + i]; flowAfter[i] = flowsForDetection[i]; freqAfter[i] = pulseFreqsForDetection[i]; } Array.Sort(flowBefore); Array.Sort(flowAfter); Array.Sort(freqBefore); Array.Sort(freqAfter); flowBefore[0] = 0; flowAfter[0] = 0; //freqBefore[0] = 0; //freqAfter[0] = 0; flowBefore[DetectionKernelSize - 1] = 0; flowAfter[DetectionKernelSize - 1] = 0; //freqBefore[DetectionKernelSize - 1] = 0; //freqAfter[DetectionKernelSize - 1] = 0; double aveFlowBefore = 0; double aveFlowAfter = 0; double aveFreqBefore = 0; double aveFreqAfter = 0; foreach (var f in flowBefore) aveFlowBefore += f; foreach (var f in flowAfter) aveFlowAfter += f; foreach (var f in freqBefore) aveFreqBefore += f; foreach (var f in freqAfter) aveFreqAfter += f; aveFlowBefore /= (double)(DetectionKernelSize - 2); aveFlowAfter /= (double)(DetectionKernelSize - 2); 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", 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) { detected = (aveFreqAfter < aveFreqBefore * (1.0f - testParams.DetectionThreshold)); targetReached = ((aveFlowAfter + aveFlowBefore) / 2.0f) > testParams.TargetQ; } else { detected = (aveFreqAfter > aveFreqBefore * (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("CombinedWithDetection : Switching flow detected, going back") .AddOperation(checkUiOp) .AddOperations(measureOperations) .AddOperation(outPath.RegulValve.SetFlowOp(outPath.FlowMeter, test.Qfrom, test.Qto, outPath.PidCoef, RefFlow, 600)) /// timeout = 10 min. .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.Timeout); goto error; } } while (!e.Contains(Event.FlowReached)); } //-------------------------------- State.Create("CombinedWithDetection : Going to the test flow") //State.Create("set_RV_position", .AddOperation(checkUiOp) .AddOperations(measureOperations) .AddOperation(outPath.RegulValve.SetFlowOp(outPath.FlowMeter, qfrom_detected, qto_detected, outPath.PidCoef, RefFlow, 600)) /// timeout = 10 sec. //.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(measureOperations) .AddOperation(outPath.Scale.ReadStableMassOp(ref StartMass, test.MassRepeats, test.MassSpread, test.MassMethod)) .EnterState(); do { e = StateMachine.WaitRunDevsRunOps(); if (e.Contains(Event.Error)) goto error; if (TestAndLogUiCmdStop(test,e)) goto stopTest; } while (!e.Contains(Event.BalanceDone)); Mass.Val = StartMass.Val; //------------------------------------------------ Bridge.OnActivity(this, Strings.Test_in_progress); //------------------------------------------------ State.Create(Strings.Start_the_test) .AddOperation(checkUiOp) .AddOperations(measureOperations) .AddOperation(cBrd.StartMeasurementOp(outPath, Elde.TestMethods.Diverter | Elde.TestMethods.Synchro, qfrom_detected, qto_detected, totalPulses, (float)test.TolerRed)) .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(); ClearAllStatistics(StateMachine.Time); int estimtdEndTime = StateMachine.Time + (int)test.TstTime; /// 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(Strings.Measure_the_mass) .AddOperation(checkUiOp) .AddOperation(outPath.Scale.ReadStableMassOp(ref EndMass, test.MassRepeats, test.MassSpread, test.MassMethod)) .EnterState(); do { e = StateMachine.WaitRunDevsRunOps(); if (e.Contains(Event.Error)) goto error; if (TestAndLogUiCmdStop(test,e)) goto stopTest; } while (!e.Contains(Event.BalanceDone)); /// TestEndTime = DateTime.Now; //------------------------------------------------ Bridge.OnActivity(this, Strings.Test_completed); //------------------------------------------------ State.Create(Strings.Stop_the_pump) .AddOperation(checkUiOp) .AddOperation((inPath != null && inPath.Pump is GenericDevices.IPumpFM) ? (inPath.Pump as GenericDevices.IPumpFM).TurnOffOp() : null) .AddOperation(cBrd.SetValvesOp(null, inPath.Pump)) .AddOperation(cBrd.UpdateTankWeightOp()) .EnterState(); do { e = StateMachine.WaitRunDevsRunOps(); if (TestAndLogUiCmdStop(test,e)) goto stopTest; } while (!e.Contains(Event.ValvesSet)); //-------------------------------- State.Create("stop_diverter_gate_etc") .AddOperation(checkUiOp) .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.StartTime = TestStartTime; tstRslt.EndTime = TestEndTime; tstRslt.FlowSetTime = flowSetTime; 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 = Formulas.CorrectedValue(tstRslt.MassStartRaw, outPath.Scale.Corrections); tstRslt.MassEndRaw = EndMass.Val; tstRslt.MassEnd = Formulas.CorrectedValue(tstRslt.MassEndRaw, outPath.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 = Formulas.Buoyancy(); tstRslt.VolumeCTV = 1000.0 * tstRslt.Buoyancy * (tstRslt.MassEnd - tstRslt.MassStart) / tstRslt.DensityOut; /// [l] 1000.0f is because density is in [kg/m3] tstRslt.VolumeMaster = LtrPerRefPulse * tstRslt.PulsesMaster; /// [l] volume from the master flow meter tstRslt.ConstMaster = LtrPerRefPulse * tstRslt.VolumeCTV / tstRslt.VolumeMaster; /// Corrected master pulses per liter tstRslt.ErrorMaster = 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.ErrorFlagsMd = (ErrorFlagsComp != null) ? (sbyte)ErrorFlagsComp.Mode : (sbyte)0; tstRslt.ErrorFlags = (ErrorFlagsComp != null) ? ErrorFlagsComp.GetErrorFlags(test, tstRslt.TestTime) : 0; for (int i = 0; i < BatchRslts.WMPositionsCount; i++) { if (test.Part != 0 && test.Part != Utils.PartNr(i + 1, BatchRslts.Batch.Compound)) continue; Results.Entities.MeterTestRslt mainMeterRslt = BatchRslts.GetMeterTestRslt(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.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 = 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 = Formulas.ErrorFromVolumes(compoundMeterRslt.VolumeMeter, compoundMeterRslt.VolumeRef); compoundMeterRslt.Passed = (compoundMeterRslt.Error >= test.ErrLimLo + test.Uncertainty) && (compoundMeterRslt.Error <= test.ErrLimHi - 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, outPath.Scale != null ? outPath.Scale.Name : string.Empty, outPath.RegulValve != null ? outPath.RegulValve.Name : string.Empty, outPath.Diverter != null ? outPath.Diverter.Name : string.Empty)); /// 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)); if (!outerLoopMode && (++repetitionNr <= test.Repeats)) { goto loop; } ///----------------------/// /// Quit this sequence /// ///----------------------/// /// Stop the pump State.Create("CombinedWithDetection : Test(s) completed -> Stopping the pump") .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))); /// Transition or SetRoute - End switch (Transition(transitionAfter, TransitionContext.AfterTest)) { case Event.Error: goto error; case Event.UiCmdStop: goto stopTest; } Bridge.OnTestProgress(this, new TestProgressEventArgs(test, repetitionNr, Config.Entities.Progress.Completed)); /// Create the return value - a list with one event Event.Done - and return IList retval1 = new List(1); retval1.Add(Event.Done); return retval1; //==================================== stopTest: State.Create("CombinedWithDetection : User selected STOP -> Closing the valves") .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)); Bridge.OnTestProgress(this, new TestProgressEventArgs(test, 1, Config.Entities.Progress.Aborted)); IList retval2 = new List(1); retval2.Add(Event.UiCmdStop); return retval2; //==================================== 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)) goto error; } while (!e.Contains(Event.ValvesSet)); Bridge.OnTestProgress(this, new TestProgressEventArgs(test, 1, Config.Entities.Progress.Aborted)); IList retval3 = new List(1); retval3.Add(Event.Error); return retval3; } } }