tbf/TestBenchFramework/BenchControl/TestMethods/Adjustment/AdjustmentSeq.cs

415 lines
18 KiB
C#

///
/// Copyright (c) 2013-2015 Sensus Metering Systems
///
using System;
using System.Collections.Generic;
using System.Text;
using log4net;
using Config.Entities;
using TBF.BenchControl;
using TBF.Boxes;
using TBF.Resources;
using TBF.UiBridge;
namespace TBF.BenchControl.TestMethods.Adjustment
{
public class AdjustmentSeq : Sequences.SequenceBase
{
private static readonly ILog log = LogManager.GetLogger(typeof(AdjustmentSeq));
System.Windows.Forms.Form modelessDlg;
///
delegate void ErrorsFormDlgt(AdjustmentSeq myRef, IList<GenericDevices.IWaterMeter> waterMeters);
///
void OpenWMErrorsForm(AdjustmentSeq myRef, IList<GenericDevices.IWaterMeter> waterMeters)
{
#pragma warning disable 162 /// Disables 'Unreachable code detected' warning
if (Config.Data.WMsCount > 12)
{
myRef.modelessDlg = new WMErrorsForm24(waterMeters);
}
else if (Config.Data.WMsCount > 6)
{
myRef.modelessDlg = new WMErrorsForm12(waterMeters);
}
else
{
myRef.modelessDlg = new WMErrorsForm(waterMeters);
}
#pragma warning restore 162 /// Disables 'Unreachable code detected' warning
modelessDlg.Show();
}
/// <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(Test test, DebugMode mode)
{
float simulatedError = 4.5f; /// %
Elde.ControlBoardDev cBrd = StateMachine.ControlBoard;
IList<Event> e = new List<Event>(); /// Events from currently running operations
Event retVal = Event.Done;
checkUiOp = new Operations.CheckUIOp(true); /// Runs in more then one state
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);
int repetitionNr = 1; /// First test: repetitionNr=1
//====================================
// Transition or SetRoute - Start
//====================================
switch (Transition(transitionBefore, TransitionContext.BeforeTest))
{
case Event.Error: { retVal = Event.Error; goto stopTest; }
case Event.UiCmdStop: { retVal = Event.UiCmdStop; goto stopTest; }
}
/// Start the test, initialize test results
Bridge.OnTestSelected(this, new TestSelectedEventArgs(test, repetitionNr, inPath, benchPath, outPath, sensPath, totalPulses));
string testName = Results.Utils.GetTestName(test.Name, test.Repeats, repetitionNr);
TestStartTime = DateTime.Now;
TestProgressEventArgs.SetEstimatedTimes(new int[] { 1, 1, 1, 30, Convert.ToInt32(test.TstTime) + 15, 0, 0 });
Bridge.OnTestProgress(this, new TestProgressEventArgs(test, repetitionNr, Config.Entities.Progress.JustStarted));
Bridge.OnTestProgress(this, new TestProgressEventArgs(test, repetitionNr, Config.Entities.Progress.FlowSetting));
int flowSetTime0 = StateMachine.Time;
//------------------------------------------------
Bridge.OnActivity(this, Strings.Starting_the_pump);
//------------------------------------------------
if (inPath.Pump is GenericDevices.IPumpFM) (inPath.Pump as GenericDevices.IPumpFM).TurnOn(test.PumpPower);
///
State.Create("Adjustment : Starting the pump")
.AddOperation(checkUiOp)
.AddOperation(StateMachine.ControlBoard.UpdateTankWeightOp())
.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.TimeBeforeFlow > 0)
{
State.Create("Adjustment : Waiting before flow setting process starts")
.AddOperation(checkUiOp)
.AddOperation(new Operations.TimerOp(test.TimeBeforeFlow))
.AddOperation(StateMachine.ControlBoard.UpdateTankWeightOp())
.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);
//------------------------------------------------
State.Create("Adjustment : Setting the flow")
.AddOperation(checkUiOp)
.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 (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.Timeout);
retVal = Event.Done;
goto stopTest;
}
if (e.Contains(Event.Next)) goto flow_set;
}
while (!e.Contains(Event.FlowReached));
flow_set:
int flowSetTime = StateMachine.Time - flowSetTime0;
/// Show the modeless dialog with error indication
Program.MainWnd.Invoke(new ErrorsFormDlgt(OpenWMErrorsForm), new object[] { this, WaterMeters });
loop:
int time = StateMachine.Time;
double currentFlow = RefFlow.Val;
/// Extract cameras from the current sensors path, add operations to the detection state
IList<IOperation> measureOperations = new List<IOperation>();
for (int i = 0; i < sensPath.RegisterReaders.Length; i++)
{
GenericDevices.ICameraRoi cameraRoi = sensPath.RegisterReaders[i] as GenericDevices.ICameraRoi;
if (cameraRoi != null) measureOperations.Add(cameraRoi.MeasureOp());
}
//------------------------------------------------
Bridge.OnActivity(this, Strings.Test_in_progress);
//------------------------------------------------
if (mode == Config.Entities.DebugMode.Simulate)
{
/// TODO: Reimplement
//tstRslt = MakeSimulated(test, 1, simulatedError);
simulatedError *= 0.6f;
State.Create("Adjustment : Simulating the test")
.AddOperation(checkUiOp)
.AddOperation(new Operations.TimerOp(5))
.EnterState();
do
{
e = StateMachine.WaitRunDevsRunOps();
if (e.Contains(Event.Error)) { retVal = Event.Error; goto stopTest; }
if (TestAndLogUiCmdStop(test,e)) { retVal = Event.UiCmdStop; goto stopTest; }
}
while (!e.Contains(Event.TimerExpired));
}
else
{
State.Create("Adjustment : Starting the test")
.AddOperation(checkUiOp)
.AddOperations(measureOperations)
.AddOperation(cBrd.StartMeasurementOp(outPath, Elde.TestMethods.Synchro,
test.Qfrom, test.Qto, totalPulses, (float)test.TolerRed))
.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.MeasurementStarted));
/// Measurement loop - preparation
readRegistersOp = new Operations.ReadMoreRegistersOp(sensPath.RegisterReaders);
queryEnd1 = cBrd.QueryMeasurementEndOp();
queryEnd2 = cBrd.QueryMeasurementEndOp();
ClearAllStatistics();
/// Measurement loop - begin
while (true)
{
//--------------------------------
switch (ReadRegistersTempPressAmbient(measureOperations, true))
{
case Event.Error: { retVal = Event.Error; goto stopTest; }
case Event.UiCmdStop: { retVal = Event.UiCmdStop; goto stopTest; }
case Event.MeasurementCompleted: goto one_test_completed;
}
RefFreq.Val = cBrd.ReferenceFreq;
RefFlow.Val = cBrd.ReferenceFlow;
UpdateAllStatistics();
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
one_test_completed:
//------------------------------------------------
Bridge.OnActivity(this, Strings.Adjustment_in_progress);
//------------------------------------------------
TestEndTime = DateTime.Now;
/// 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)
{
/// Auxiliary results
tstRslt.AmbientTempAve = (float)AmbientTempStat.Average;
tstRslt.AmbTempStart = (float)AmbientTempStat.First;
tstRslt.AmbTempEnd = (float)AmbientTempStat.Last;
tstRslt.AmbTempMin = (float)AmbientTempStat.Min;
tstRslt.AmbTempMax = (float)AmbientTempStat.Max;
tstRslt.AmbientPressAve = (float)AmbientPressureStat.Average;
tstRslt.AmbPressStart = (float)AmbientPressureStat.First;
tstRslt.AmbPressEnd = (float)AmbientPressureStat.Last;
tstRslt.AmbPressMin = (float)AmbientPressureStat.Min;
tstRslt.AmbPressMax = (float)AmbientPressureStat.Max;
tstRslt.AmbientHumiAve = (float)AmbientHumidityStat.Average;
tstRslt.AmbHumiStart = (float)AmbientHumidityStat.First;
tstRslt.AmbHumiEnd = (float)AmbientHumidityStat.Last;
tstRslt.AmbHumiMin = (float)AmbientHumidityStat.Min;
tstRslt.AmbHumiMax = (float)AmbientHumidityStat.Max;
tstRslt.PressUpAvrg = (float)PressureUpStat.Average;
tstRslt.PressUpStart = (float)PressureUpStat.First;
tstRslt.PressUpEnd = (float)PressureUpStat.Last;
tstRslt.PressUpMin = (float)PressureUpStat.Min;
tstRslt.PressUpMax = (float)PressureUpStat.Max;
tstRslt.PressDownAvrg = (float)PressureDownStat.Average;
tstRslt.PressDownStart = (float)PressureDownStat.First;
tstRslt.PressDownEnd = (float)PressureDownStat.Last;
tstRslt.PressDownMin = (float)PressureDownStat.Min;
tstRslt.PressDownMax = (float)PressureDownStat.Max;
tstRslt.TempInAvrg = (float)TempInStat.Average;
tstRslt.TempInStart = (float)TempInStat.First;
tstRslt.TempInEnd = (float)TempInStat.Last;
tstRslt.TempInMin = (float)TempInStat.Min;
tstRslt.TempInMax = (float)TempInStat.Max;
tstRslt.TempOutAvrg = (float)TempOutStat.Average;
tstRslt.TempOutStart = (float)TempOutStat.First;
tstRslt.TempOutEnd = (float)TempOutStat.Last;
tstRslt.TempOutMin = (float)TempOutStat.Min;
tstRslt.TempOutMax = (float)TempOutStat.Max;
tstRslt.TempDivAvrg = (float)TempDivStat.Average;
tstRslt.TempDivStart = (float)TempDivStat.First;
tstRslt.TempDivEnd = (float)TempDivStat.Last;
tstRslt.TempDivMin = (float)TempDivStat.Min;
tstRslt.TempDivMax = (float)TempDivStat.Max;
tstRslt.DensityIn = Formulas.WaterDensityFromTemp(tstRslt.TempInAvrg); /// [kg/m3]
tstRslt.DensityOut = Formulas.WaterDensityFromTemp(tstRslt.TempOutAvrg); /// [kg/m3]
tstRslt.DensityDiv = Formulas.WaterDensityFromTemp(tstRslt.TempDivAvrg); /// [kg/m3]
/// 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.MassStart = 0;
tstRslt.MassEnd = 0;
tstRslt.FlowMass = 0; /// [kg/h]
tstRslt.FlowVolume = 3.6 * LtrPerRefPulse * cBrd.EtPulses(0) / tstRslt.TestTime; /// [m3/h]
tstRslt.VolumeMaster = LtrPerRefPulse * tstRslt.PulsesMaster; /// [l] volume from the master flow meter
tstRslt.ConstMaster = outPath.FlowMeter.LtrPerPulseCorrected(tstRslt.FlowVolume); /// Calculate master flowmeter coefficient
tstRslt.VolumeCTV = tstRslt.ConstMaster * tstRslt.PulsesMaster; /// [l] 1000.0f is because density is in [kg/m3]
tstRslt.ErrorMaster = 0.0f; /// Cannot be determined without the collected water mass measurement
tstRslt.FlowMin = (float)((tstRslt.VolumeMaster != 0) ? (RefFlowStat.Min * tstRslt.VolumeCTV / tstRslt.VolumeMaster) : RefFlowStat.Min);
tstRslt.FlowMax = (float)((tstRslt.VolumeMaster != 0) ? (RefFlowStat.Max * tstRslt.VolumeCTV / tstRslt.VolumeMaster) : RefFlowStat.Max);
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 meterRslt = BatchRslts.GetMeterTestRslt(testName, i, CompoundMeterId.Single);
GenericDevices.IRegisterReader regReader = sensPath.RegisterReaders[i];
if (meterRslt != null && regReader != null)
{
meterRslt.PulsesPerLiter = regReader.PulsesPerLtr;
meterRslt.PulsesMeter = Convert.ToDouble(regReader.WMPulses);
meterRslt.PulsesMaster = Convert.ToDouble(regReader.WMRefPulses);
meterRslt.VolumeStart = 0; /// liter
meterRslt.VolumeEnd = 0; /// liter
meterRslt.VolumeMeter = meterRslt.PulsesMeter * regReader.LtrsPerPulse; /// liter
meterRslt.VolumeRef = meterRslt.PulsesMaster * tstRslt.ConstMaster; /// liter
meterRslt.TestTime = tstRslt.TestTime;
meterRslt.Error = Formulas.ErrorFromVolumes(meterRslt.VolumeMeter, meterRslt.VolumeRef);
meterRslt.Passed = (meterRslt.Error >= test.ErrLimLo + test.Uncertainty)
&& (meterRslt.Error <= test.ErrLimHi - test.Uncertainty);
meterRslt.TestDone = meterRslt.Passed;
}
}
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.Balance != null ? outPath.Balance.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));
}
/// Add data - end
}
/// Update modeless dialog error information
Bridge.OnAdjustmentInProgress(this, new AdjustmentInProgressEventArgs(testName));
/// Test 'Quit'
if ((modelessDlg is GenericDevices.IHasCompleted) && !(modelessDlg as GenericDevices.IHasCompleted).Completed)
{
goto loop; /// Modeless dilaog not closed, keep looping
}
modelessDlg = null; /// Modeless dialog is closed now
/// Append the results to the CSV-file
allResults.Info(TestResult2CsvLine(testName, test.Part));
stopTest:
///----------------------///
/// Quit this sequence ///
///----------------------///
State.Create("Adjustment : Stopping diverter, gate, etc.")
.AddOperation(checkUiOp)
.AddOperation(cBrd.StopPreviousOp())
.EnterState();
do
{
e = StateMachine.WaitRunDevsRunOps();
if (TestAndLogUiCmdStop(test,e)) { retVal = Event.UiCmdStop; goto stopTest; }
}
while (!e.Contains(Event.PreviousStopped));
/// Transition sequence at the end of test
/// Prevent overwriting 'retVal' in case it was set to non-default value earlier
switch (Transition(transitionAfter, (retVal == Event.Done) ? TransitionContext.AfterTest : TransitionContext.Stop))
{
case Event.Error: { if (retVal == Event.Done) retVal = Event.Error; break; }
case Event.UiCmdStop: { if (retVal == Event.Done) retVal = Event.UiCmdStop; break; }
}
Bridge.OnTestProgress(this, new TestProgressEventArgs(test, repetitionNr, Config.Entities.Progress.Completed));
/// Create a list with one item 'retVal' (default is Event.Done) and return it
IList<Event> retList = new List<Event>(1);
retList.Add(retVal);
return retList;
}
}
}