tbf/TBF/BenchControl/TestMethods/FlowAdjustment/FlowAdjustmentSeq.cs
2020-11-13 11:55:20 +01:00

455 lines
21 KiB
C#

///
/// Copyright (c) 2020 Sensus Slovensko a.s.
///
using System;
using System.Collections.Generic;
using System.Text;
using log4net;
using TBF.BenchControl;
using TBF.BenchControl.GenericDevices;
using TBF.Boxes;
using TBF.Resources;
using TBF.UiBridge;
namespace TBF.BenchControl.TestMethods.FlowAdjustment
{
public class FlowAdjustmentSeq : Sequences.SequenceBase
{
private static readonly ILog log = LogManager.GetLogger(typeof(FlowAdjustmentSeq));
/// <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.Legacy.ControlBoardDev) &&
!(StateMachine.ControlBoard is ControlBoard.Papouch.CBoard) &&
!(StateMachine.ControlBoard is ControlBoard.New.CBoard))
{
/// 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.FlowMeter is TBF.BenchControl.GenericDevices.IFlowMeter))
{
/// Flow meter is missing
message = string.Format("{0}: {1}", test.Name, Strings.Missing_a_flow_meter);
return false;
}
if (!(devices.RegulValve is GenericDevices.IRegulValve))
{
/// 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, Config.Entities.DebugMode debugLevel)
{
if (debugLevel == Config.Entities.DebugMode.Simulate)
{
return Simulate(test, repetitionNr, isLastRepetition, debugLevel);
}
ControlBoard.IControlBoard cBrd = StateMachine.ControlBoard;
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 };
}
}
IList<Event> e; /// Events from currently running operations
Event retVal = Event.Done;
checkUiOp = new Operations.CheckUIOp(true); /// Runs in more then one state
processDataLoggingOp = new TBF.BenchControl.Operations.ProcessDataLoggingOp(processDataLogger, this, false);
if (cBrd is ControlBoard.Legacy.ControlBoardDev)
{
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 eldeRR = rr as IRegReaderPulses;
if ((eldeRR != null) && (eldeRR.Position >= 1) && (eldeRR.Position <= 8))
{
filters[eldeRR.Position - 1] = eldeRR.Filter;
}
}
}
(cBrd as ControlBoard.Legacy.ControlBoardDev).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 (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));
LtrPerRefPulse = outPath.FlowMeter.LtrPerPulse; /// [ltr/pulse], nominal flow in [m3/h]
int totalPulses = (int)(test.Volume / LtrPerRefPulse + 0.5f);
//====================================
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)) { 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.OnActivity(this, Strings.Starting_the_pump);
//------------------------------------------------
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)
.AddOperations(readTempPressOps)
//.AddOperation(new Operations.SetAllRegulValvesOp(inPath.RegulValves, inPath.RegulValvesPct, 60))
.AddOperation(inPath.Pump != null ? cBrd.SetValvesOp(inPath.Pump, null) : null)
.EnterState();
do {
e = StateMachine.WaitRunDevsRunOps();
Bridge.OnProcessData(this, new ProcessDataEventArgs(test, repetitionNr, Config.Entities.Progress.FlowSetting));
Bridge.OnTestProgress(this, new TestProgressEventArgs(test, repetitionNr, Config.Entities.Progress.FlowSetting));
if (TestAndLogUiCmdStop(test, e)) { retVal = Event.UiCmdStop; goto stopTest; }
if (e.Contains(Event.Error)) { retVal = Event.Error; goto stopTest; }
}
while (e.Contains(Event.ValvesBusy) /* || !e.Contains(Event.AllPositionsReached)*/);
if (test.TimePump2StartV > 0)
{
State.Create(string.Format("{0}({1}) : Waiting after the pump started", test.Method, test.Name))
.AddOperation(checkUiOp)
.AddOperations(readTempPressOps)
.AddOperation(new Operations.TimerOp(test.TimePump2StartV))
.EnterState();
do {
e = StateMachine.WaitRunDevsRunOps();
Bridge.OnProcessData(this, new ProcessDataEventArgs(test, repetitionNr, Config.Entities.Progress.FlowSetting));
Bridge.OnTestProgress(this, new TestProgressEventArgs(test, repetitionNr, Config.Entities.Progress.FlowSetting));
if (TestAndLogUiCmdStop(test, e)) { retVal = Event.UiCmdStop; goto stopTest; }
}
while (!e.Contains(Event.TimerExpired));
}
if (benchPath.StopBFValve != null)
{
State.Create(string.Format("{0}({1}) : Opening the stop backflow valve", test.Method, test.Name))
.AddOperation(checkUiOp)
.AddOperations(readTempPressOps)
.AddOperation(cBrd.SetValvesOp(benchPath.StopBFValve, null))
.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)
.AddOperations(readTempPressOps)
.AddOperation(new Operations.TimerOp(test.TimeBeforeFlow))
.EnterState();
do {
e = StateMachine.WaitRunDevsRunOps();
Bridge.OnProcessData(this, new ProcessDataEventArgs(test, repetitionNr, Config.Entities.Progress.FlowSetting));
Bridge.OnTestProgress(this, new TestProgressEventArgs(test, repetitionNr, Config.Entities.Progress.FlowSetting));
if (TestAndLogUiCmdStop(test, e)) { retVal = Event.UiCmdStop; goto stopTest; }
}
while (!e.Contains(Event.TimerExpired));
}
//------------------------------------------------
Bridge.OnActivity(this, Strings.Setting_the_flow);
//------------------------------------------------
TestStartTime = DateTime.Now;
State.Create(string.Format("{0}({1}) : Setting the flow", test.Method, test.Name))
.AddOperation(checkUiOp)
.AddOperations(readTempPressOps)
.AddOperation(cBrd.SetFlowOp(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 (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:
TestEndTime = DateTime.Now;
double currentFlow = RefFlow.Val;
if (test.DoControlWaterTemp && benchPath.TempMtrUp != null && benchPath.TempMtrDown != null)
{
//---------------------------------------------------
Bridge.OnActivity(this, Strings.Setting_temperature);
//---------------------------------------------------
State.Create(string.Format("{0}({1}) : Wait until the water temperature is within limits", test.Method, test.Name))
.AddOperation(checkUiOp)
.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:
StopRecordingStatistics();
//------------------------------------------------
Bridge.OnActivity(this, Strings.Test_completed);
//------------------------------------------------
///
/// Populate TestResult data entity with data
///
Results.Entities.TestRslt tstRslt = BatchRslts.GetTestRslt(testName, test.Part);
if (tstRslt != null)
{
Results.Utils.GetCounterStates(tstRslt, Program.LocalSettings.Counters);
UpdateTempPressDensAmb(tstRslt);
/// Main results
tstRslt.MethodClass = TbfComponents.FindComponent(test.Method).ClassName;
tstRslt.StartTime = TestStartTime;
tstRslt.EndTime = TestEndTime;
TimeSpan duration = TestEndTime - TestStartTime;
tstRslt.TestTime = duration.TotalSeconds;
tstRslt.FlowSetTime = Convert.ToInt32(Math.Round(tstRslt.TestTime)); /// [s] test time = flow set time
tstRslt.PulsesMaster = 0;
tstRslt.MassStartRaw = 0;
tstRslt.MassStart = 0;
tstRslt.MassEndRaw = 0;
tstRslt.MassEnd = 0;
tstRslt.FlowMass = 0;
tstRslt.FlowVolume = 0;
tstRslt.Buoyancy = Config.Formulas.Buoyancy();
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.ConstMasterCorr;
tstRslt.VolumeCTV = tstRslt.ConstMaster * tstRslt.PulsesMaster; /// [l] 1000.0f is because density is in [kg/m3]
tstRslt.ErrorMaster = 0.0; /// Cannot be determined without a mass measurement
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 = 0;
tstRslt.DiverterEnd = 0;
long infoFlags = 0;
tstRslt.ErrorFlags = (ErrorFlagsComp != null) ? ErrorFlagsComp.GetErrorFlags(tstRslt, false, false, 0, 0, out infoFlags) : 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;
Results.Entities.MeterTestRslt meterRslt = BatchRslts.GetMeterTestRslt(testName, i, Config.Entities.CompoundMeterId.Single);
if (meterRslt != null)
{
meterRslt.Passed = true;
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,
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)
{
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, Config.Entities.Progress.TransitionAfter));
/// Append the results to the CSV-file
allResults.Info(TestResult2CsvLine(testName, test.Part));
stopTest:
StopRecordingStatistics();
State.Create(string.Format("{0}({1}) : Stopping flow regulation", test.Method, test.Name))
.AddOperation(checkUiOp)
.AddOperations(readTempPressOps)
.AddOperation(cBrd.StopFlowRegulationOp())
.EnterState();
do {
e = StateMachine.WaitRunDevsRunOps();
if (e.Contains(Event.Error)) { retVal = Event.Error; break; }
if (TestAndLogUiCmdStop(test, e)) { retVal = Event.UiCmdStop; break; }
}
while (!e.Contains(Event.FlowRegulationStopped));
///
/// Quit this sequence
///
if (isLastRepetition || retVal == Event.UiCmdStop || retVal == Event.OpArgumentError
|| retVal == Event.Error || retVal == Event.ConfigurationError)
{
State.Create(string.Format("{0}({1}) : Stopping diverter, gate, etc.", test.Method, test.Name))
.AddOperation(checkUiOp)
.AddOperation(cBrd.StopPreviousOp())
.EnterState();
do {
e = StateMachine.WaitRunDevsRunOps();
if (TestAndLogUiCmdStop(test, e)) { if (retVal == Event.Done) retVal = Event.UiCmdStop; break; }
}
while (!e.Contains(Event.PreviousStopped));
}
stopTestWOStoppingDivGateEtc:
return new List<Event> { retVal };
}
IList<Event> Simulate(Config.Entities.Test test, int repetitionNr, bool isLastRepetition, Config.Entities.DebugMode debugLevel)
{
///
/// Test method simulation
///
Bridge.OnTestProgress(this, new TestProgressEventArgs(test, repetitionNr, Config.Entities.Progress.FlowSetting));
if (test.Name.ToLower().Contains("q3")) MakeSimulated(test, 1, 0, -0.5f);
else if (test.Name.ToLower().Contains("q2")) MakeSimulated(test, 1, 0, 0.5f);
else if (test.Name.ToLower().Contains("q1")) MakeSimulated(test, 1, 0, -5.1f);
else MakeSimulated(test, 1, 0, 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("{0} simulation", test.Name));
//------------------------------------------------------------------
State.Create(string.Format("{0}({1}) : Simulating {0}", test.Method, test.Name))
.AddOperation(checkUiOp)
.EnterState();
IList<Event> e = StateMachine.WaitRunDevsRunOps();
return new List<Event> { TestAndLogUiCmdStop(test, e) ? Event.UiCmdStop : Event.Done };
}
}
}