Files
tbf/TBF/Rig/Uni/RegValveAnalog/SetFlowOp.cs
T

472 lines
18 KiB
C#

///
/// Copyright (c) 2021 Sensus Slovensko a.s.
///
using System;
using System.Collections.Generic;
using log4net;
using TBF.Rig.ControlBoard.Uni;
using TBF.Rig.GenericDevices;
using TBF.Boxes;
namespace TBF.Rig.Uni.RegValveAnalog
{
public class SetFlowOp : IOperation
{
private static readonly ILog log = LogManager.GetLogger(typeof(SetFlowOp));
public override string ToString()
{
return string.Format("SetFlowOp({0}, Qfrom={1}, Qto={2})", regValve.Name, finalReqFlowLo, finalReqFlowHi);
}
/// Set by the constructor
readonly UniCB uniCB;
readonly RegValve regValve;
readonly int flowMeterId;
readonly double finalReqFlowLo;
readonly double finalReqFlowHi;
readonly double reqFlowAve;
readonly int timeout;
readonly int delay;
readonly bool leaveFlowControlRunning;
readonly bool reTryCommands;
readonly double nominalFlow;
readonly double maximalFlow;
///
/// Internal states of this operation
///
enum OpState
{
Idle = 0,
ValveMoveToPosition1, /// Wait 1 takt
ValveMoveToPosition2, /// This is actual move to position
ValveMoveToPosition3, /// Wait 1 takt
CheckStatePosition, /// Verify
SettingPosition,
ValveMoveToFlow1, /// Wait 1 takt
ValveMoveToFlow2, /// This is actual move to flow
ValveMoveToFlow3, /// Wait 1 takt
CheckStateFlow, /// Verify
SettingFlow,
FlowReached,
SendCommandAgain,
}
OpState opState;
double currentReqFlowLo;
double currentReqFlowHi;
double targetPositionLo;
double targetPositionHi;
int expireTime;
DoubleBox measuredFlow;
int flowWithinBoundsTime;
/// <summary>
/// Set required water flow. Conditionally leave the measurement running.
/// Events: FlowSet, FlowTimeOut
/// </summary>
/// <param name="controlBoard">Control board device</param>
/// <param name="_regulValve">Regulation valve component</param>
/// <param name="flowMeter">Flowmeter component</param>
/// <param name="requiredFlowLo">Lower limit of the flow to be achieved in [m3/h]</param>
/// <param name="requiredFlowHi">Upper limit of the flow to be achieved in [m3/h]</param>
/// <param name="pidCoef">PID coefficient (float)</param>
/// <param name="timeout">Timeout for the flow setting in [s]</param>
/// <param name="delay">Flow setting starts after this delay in [s]</param>
/// <param name="leaveFlowControlRunning">true = Leave the measurement running after op. stop</param>
/// <remarks>Only Elde.Valve flow are used, other flow on the lists are ignored</remarks>
public SetFlowOp(TBF.Rig.ControlBoard.IControlBoard cb, IRegValve _regulValve, IFlowMeter flowMeter,
double requiredFlowLo, double requiredFlowHi, DoubleBox measuredFlow,
bool reTryCmds, int timeout, int delay, bool leaveFlowControlRunning)
{
uniCB = cb as UniCB;
if (uniCB == null) throw new ArgumentNullException("ctrlBoard");
regValve = _regulValve as TBF.Rig.Uni.RegValveAnalog.RegValve;
if (regValve == null) throw new ArgumentNullException(string.Format("{0} is not Elde.RegulValveCoax.", _regulValve.Name));
if (flowMeter is Uni.FlowMeter.FlowMeter)
{
this.flowMeterId = (flowMeter as Uni.FlowMeter.FlowMeter).Idx1;
}
else if (flowMeter is Uni.FlowMetersInParallel.FlowMeter)
{
this.flowMeterId = 0;
}
else
{
throw new ArgumentNullException("flowMeter is null or not Elde");
}
nominalFlow = flowMeter.NominalFlow;
maximalFlow = nominalFlow * 1.25;
this.reqFlowAve = (requiredFlowLo + requiredFlowHi) / 2;
this.finalReqFlowLo = (0.7 * requiredFlowLo) + (0.3 * this.reqFlowAve); /// Move the lower limit 15% of the range up
this.finalReqFlowHi = (0.7 * requiredFlowHi) + (0.3 * this.reqFlowAve); /// Move the upper limit 15% of the range down
this.measuredFlow = measuredFlow;
this.reTryCommands = reTryCmds;
this.timeout = timeout;
this.delay = delay;
this.leaveFlowControlRunning = leaveFlowControlRunning;
log.Warn(this.ToString());
}
/// <summary>
/// Set required water flow - Do not leave the measurement running.
/// Events: FlowSet
/// </summary>
public SetFlowOp(UniCB uniCB, IRegValve regValve, IFlowMeter flowMeter, double qFrom, double qTo,
DoubleBox measuredFlow, bool reTryCmds, int timeout, int delay)
: this(uniCB, regValve, flowMeter, qFrom, qTo, measuredFlow, reTryCmds, timeout, delay, false)
{
}
/// <summary>
/// Fetch target position limits from the dictionary or return false
/// </summary>
/// <param name="avgReqFlow">Average of the flow targer range (input)</param>
/// <param name="positionLo">Target valve position low limit (output)</param>
/// <param name="positionHi">Target valve position high limit (output)</param>
/// <returns>true when positions for the target flow are stored in the memory, otherwise return false</returns>
bool FetchTargetPosition(double avgReqFlow, out double positionLo, out double positionHi)
{
double targetPosition;
if (regValve.Dict.TryGetValue(avgReqFlow, out targetPosition))
{
positionLo = Math.Max(targetPosition * 0.95f, 0.0f);
positionHi = Math.Min(targetPosition * 1.05f, 100.0f);
return true;
}
else
{
positionLo = 0.0f;
positionHi = 0.0f;
return false;
}
}
void StoreTargetPosition(double avgReqFlow, double actPosition)
{
if (!regValve.Dict.ContainsKey(reqFlowAve))
{
regValve.Dict.Add(new KeyValuePair<double, double>(avgReqFlow, actPosition));
}
return;
}
/// <summary>Start this operation</summary>
public void Start()
{
double flowMtrFreq = uniCB.RefFrequency;
currentReqFlowLo = reqFlowAve;
currentReqFlowHi = reqFlowAve;
///
if (flowMtrFreq != 0)
{
double flow = flowMtrFreq * nominalFlow / 2000.0;
if (measuredFlow != null) measuredFlow.Val = flow;
if (flow >= reqFlowAve) currentReqFlowLo = finalReqFlowLo;
if (flow <= reqFlowAve) currentReqFlowHi = finalReqFlowHi;
}
else
{
currentReqFlowLo = finalReqFlowLo; /// Unexpected case when flowMtrFreq==0
currentReqFlowHi = finalReqFlowHi;
}
flowWithinBoundsTime = 0;
if (regValve.StoredPositionReuse && FetchTargetPosition(reqFlowAve, out targetPositionLo, out targetPositionHi))
{
log.WarnFormat("Start() rv#={0} flowMtr#={1} TARGET: flowLo={2} flowHi={3} FETCHED: posLo={4} posHi={5}",
regValve.Idx1, flowMeterId, currentReqFlowLo, currentReqFlowHi, targetPositionLo, targetPositionHi);
opState = OpState.ValveMoveToPosition1;
}
else
{
log.WarnFormat("Start() rv#={0} flowMtr#={1} TARGET: flowLo={2} flowHi={3}",
regValve.Idx1, flowMeterId, currentReqFlowLo, currentReqFlowHi);
opState = OpState.ValveMoveToFlow1;
}
expireTime = StateMachine.Time + timeout;
if (expireTime < 0) expireTime = int.MaxValue;
/// Start the flow measurement
uniCB.MeasureFlow(false, flowMeterId);
}
/// <summary>Run this operation</summary>
/// <returns>
/// Event.None, Event.FlowReached, Event.RegulValveTimeOut, Event.OpArgumentError
/// </returns>
public Event Run()
{
double rvPosition = regValve.Position;
double flowMtrFreq = uniCB.RefFrequency;
double flow = flowMtrFreq * nominalFlow / 2000.0;
if (flowMtrFreq != 0)
{
if (measuredFlow != null) measuredFlow.Val = flow;
if (flow >= reqFlowAve) currentReqFlowLo = finalReqFlowLo;
if (flow <= reqFlowAve) currentReqFlowHi = finalReqFlowHi;
}
log.InfoFormat("Run() rv#={0} pos={1}% freq={2} flow={3} curFlLo={4} curFlHi={5} state={6}",
regValve.Idx1, rvPosition.ToString("F1"), flowMtrFreq.ToString("F1"), flow.ToString("F3"), currentReqFlowLo.ToString("F3"), currentReqFlowHi.ToString("F3"), opState);
if (opState == OpState.SendCommandAgain)
{
flowWithinBoundsTime = 0;
if (regValve.StoredPositionReuse && FetchTargetPosition(reqFlowAve, out targetPositionLo, out targetPositionHi))
{
log.InfoFormat(" Run() rv#={0} flowMtr#={1} TARGET: flowLo={2} flowHi={3} FETCHED: posLo={4} posHi={5}",
regValve.Idx1, flowMeterId, currentReqFlowLo.ToString("F3"), currentReqFlowHi.ToString("F3"), targetPositionLo, targetPositionHi);
opState = OpState.ValveMoveToPosition1;
}
else
{
log.InfoFormat(" Run() rv#={0} flowMtr#={1} TARGET: flowLo={2} flowHi={3}",
regValve.Idx1, flowMeterId, currentReqFlowLo.ToString("F3"), currentReqFlowHi.ToString("F3"));
opState = OpState.ValveMoveToFlow1;
}
expireTime = StateMachine.Time + timeout;
if (expireTime < 0) expireTime = int.MaxValue;
/// Start the flow measurement
uniCB.MeasureFlow(false, flowMeterId);
return Event.None;
}
else if (opState == OpState.ValveMoveToPosition1)
{
opState = OpState.ValveMoveToPosition2;
log.DebugFormat(" return Event.None");
return Event.None;
}
else if (opState == OpState.ValveMoveToPosition2) /// Move to position
{
/// Issues the appropriate ValveMove(...) command
// TODO: Reimplement
//uniCB.ValveMove(regValve.Idx1, RegulValveMode.TargetPosition,
// new double[2] { (targetPositionLo + targetPositionHi) / 2, (targetPositionLo + targetPositionHi) / 2 },
// regValve.StableTime);
opState = OpState.SettingPosition;
log.DebugFormat(" return Event.None");
return Event.None;
}
else if (opState == OpState.ValveMoveToPosition3)
{
if (reTryCommands)
{
opState = OpState.CheckStatePosition;
}
else
{
opState = OpState.SettingPosition;
}
log.DebugFormat(" return Event.None");
return Event.None;
}
else if (opState == OpState.CheckStatePosition) /// Verify
{
if (((ulong)uniCB.State & (ulong)StatusP.TestWithRefFlowmtr) == 0)
{
opState = OpState.SendCommandAgain;
log.DebugFormat(" return Event.None");
return Event.None;
}
else if (((ulong)uniCB.State & (ulong)StatusP.CoaxRegValveBusy) == 0)
{
// TODO: Reimplement
///// Repeat appropriate ValveMove(...) command
//uniCB.ValveMove(regValve.Idx1, RegulValveMode.TargetPosition,
// new double[2] { (targetPositionLo + targetPositionHi) / 2, (targetPositionLo + targetPositionHi) / 2 },
// regValve.StableTime);
log.InfoFormat(" Run() ValveMove({0}, Position, {1}, {2}, {3})",
regValve.Idx1, (targetPositionLo + targetPositionHi) / 2, (targetPositionLo + targetPositionHi) / 2, regValve.StableTime);
opState = OpState.ValveMoveToPosition3;
log.DebugFormat(" return Event.None");
return Event.None;
}
else
{
opState = OpState.SettingPosition;
log.DebugFormat(" return Event.None");
return Event.None;
}
}
else if (opState == OpState.SettingPosition)
{
/// Repeated untill position is reached
if ((targetPositionLo <= rvPosition) && (rvPosition <= targetPositionHi))
{
opState = OpState.ValveMoveToFlow1;
}
log.DebugFormat(" return Event.None");
return Event.None;
}
else if (opState == OpState.ValveMoveToFlow1)
{
opState = OpState.ValveMoveToFlow2;
log.DebugFormat(" return Event.None");
return Event.None;
}
else if (opState == OpState.ValveMoveToFlow2) /// Move to flow
{
///
/// Done once, issues an appropriate ValveMove(...) command
///
if ((currentReqFlowLo >= currentReqFlowHi) || (currentReqFlowLo > maximalFlow) || (currentReqFlowHi <= 0))
{
log.DebugFormat(" return Event.OpArgumentError");
return Event.OpArgumentError;
}
double freqLo = 2000.0 * currentReqFlowLo / nominalFlow;
double freqHi = 2000.0 * currentReqFlowHi / nominalFlow;
// TODO: Reimplement
//uniCB.ValveMove(regValve.Idx1, RegulValveMode.TargetFrequency,
// new double[2] { (freqLo + freqHi) / 2, (freqLo + freqHi) / 2 },
// regValve.StableTime);
log.WarnFormat(" Run() ValveMove({0}, Freq., {1}, {2}, {3}) flowMtr#={4} TARGET: flowLo={5} flowHi={6}",
regValve.Idx1, (freqLo + freqHi) / 2, (freqLo + freqHi) / 2,
regValve.StableTime,
flowMeterId, currentReqFlowLo.ToString("F3"), currentReqFlowHi.ToString("F3"));
opState = OpState.ValveMoveToFlow3;
log.DebugFormat(" return Event.None");
return Event.None;
}
else if (opState == OpState.ValveMoveToFlow3)
{
if (reTryCommands)
{
opState = OpState.CheckStateFlow;
}
else
{
opState = OpState.SettingFlow;
}
log.DebugFormat(" return Event.None");
return Event.None;
}
else if (opState == OpState.CheckStateFlow) /// Verify the flow setting
{
if (((ulong)uniCB.State & (ulong)StatusP.CoaxRegValveBusy) == 0)
{
/// Done once, issues an appropriate ValveMove(...) command
double freqLo = 2000.0 * currentReqFlowLo / nominalFlow;
double freqHi = 2000.0 * currentReqFlowHi / nominalFlow;
// TODO: Reimplement
//uniCB.ValveMove(regValve.Idx1, RegulValveMode.TargetFrequency,
// new double[2] { (freqLo + freqHi) / 2, (freqLo + freqHi) / 2 },
// regValve.StableTime);
log.WarnFormat(" Run() ValveMove({0}, Frequency, {1}, {2}, {3}) flowMtr#={4} TARGET: flowLo={5} flowHi={6}",
regValve.Idx1, (freqLo + freqHi) / 2, (freqLo + freqHi) / 2,
regValve.StableTime,
flowMeterId, currentReqFlowLo.ToString("F3"), currentReqFlowHi.ToString("F3"));
opState = OpState.ValveMoveToFlow3;
log.DebugFormat(" return Event.None");
return Event.None;
}
else
{
opState = OpState.SettingFlow;
log.DebugFormat(" return Event.None");
return Event.None;
}
}
else if (opState == OpState.SettingFlow)
{
///
/// Repeated untill the required flow is reached
///
if ((currentReqFlowLo <= flow) && (flow <= currentReqFlowHi))
{
if (flowWithinBoundsTime++ >= regValve.FlowStableSec)
{
if (regValve.StoredPositionReuse)
{
double storedPosition;
if (regValve.Dict.TryGetValue(reqFlowAve, out storedPosition))
{
/// update the stored valve position
StoreTargetPosition(reqFlowAve, (rvPosition + storedPosition) / 2.0f);
log.InfoFormat(" Run() rv#={0} reqFlow={1} pos={2}% stored={3} <--- Updating a stored position",
regValve.Idx1, reqFlowAve, rvPosition.ToString("F1"), storedPosition);
}
else
{
/// store the valve position
StoreTargetPosition(reqFlowAve, rvPosition);
log.InfoFormat(" Run() rv#={0} reqFlow={1} pos={2}% <--- Storing a new position",
regValve.Idx1, reqFlowAve, rvPosition.ToString("F1"));
}
}
log.InfoFormat(" flow = {0} m3/h (lo={1}, hi={2}, REACHED)", flow.ToString("F3"), currentReqFlowLo.ToString("F3"), currentReqFlowHi.ToString("F3"));
opState = OpState.FlowReached;
log.DebugFormat(" return Event.FlowReached");
return Event.FlowReached;
}
else
{
log.InfoFormat(" flow = {0} m3/h (lo={1}, hi={2}, FLOW_OK_TIMER={3}s)", flow.ToString("F3"), currentReqFlowLo, currentReqFlowHi, flowWithinBoundsTime);
log.DebugFormat(" return Event.None");
return Event.None;
}
}
else if (StateMachine.Time > expireTime)
{
log.DebugFormat(" return Event.RegulValveTimeOut");
return Event.RegulValveTimeOut;
}
else
{
log.InfoFormat(" flow = {0} m3/h (lo={1}, hi={2})", flow.ToString("F3"), currentReqFlowLo, currentReqFlowHi);
flowWithinBoundsTime = 0;
log.DebugFormat(" return Event.None");
return Event.None;
}
}
else /// opState == OpState.FlowReached
{
log.InfoFormat(" flow = {0} m3/h (lo={1}, hi={2}, REACHED)", flow.ToString("F3"), currentReqFlowLo, currentReqFlowHi);
log.DebugFormat(" return Event.FlowReached");
return Event.FlowReached;
}
}
/// <summary>Start this operation</summary>
public void Stop()
{
opState = OpState.Idle;
if (leaveFlowControlRunning) return;
uniCB.StopFlowControl(false, regValve.Idx1);
log.WarnFormat("Stop() SendCommand(Stop, {0}, ...)", flowMeterId);
}
}
}