TBF.Rig.Modbus.TempControl folder with Easytherm and Novus components.

This commit is contained in:
Milan Hanajik
2022-04-26 16:52:49 +02:00
parent fc81344857
commit deabff9a18
31 changed files with 865 additions and 1233 deletions
@@ -0,0 +1,25 @@
///
/// Copyright (c) 2022 Sensus Slovensko a.s.
///
using System.Collections.Generic;
using TBF.Rig.Generic;
namespace TBF.Rig.Modbus.TempControl.Novus
{
public class Factory : IComponentFactory
{
public string ClassName { get { return GetType().Namespace.Substring(8); } }
public override string ToString() { return ClassName; }
public IComponent DummyComponent() { return new TControl(); }
public IComponent GetComponent(IComponentCfg cfg, IList<IComponent> components) { return new TControl(cfg, components); }
public IComponentCfg DefaultConfig() { return new TControlCfg(this); }
public IComponentCfg CmpntCfgFromCmpntEntity(Config.Entities.Component component)
{
return ComponentCfgBase.CreateFromDbEntity(TControlCfg.Serializer, component, this);
}
}
}
@@ -0,0 +1,140 @@
///
/// Copyright (c) 2022 Sensus Slovensko a.s.
///
using System.IO;
using System.Xml.Serialization;
using Common;
using Config.Entities;
using TBF.Rig.Generic;
using TBF.Resources;
namespace TBF.Rig.Modbus.TempControl.Novus
{
public class ProcParams : ProcedureParamsBase, IParamsProvider, IProcedureParams
{
public static XmlSerializer Serializer = XmlSerializer.FromTypes(new[] { typeof(ProcParams) })[0];
public override XmlSerializer GetSerializer() { return Serializer; }
public float RequiredTemp; /// [°C] target temperature for a temperature controller or 0=not communicated to the controller
public override void InitializeAll()
{
RequiredTemp = 0.0f;
}
string[] paramNames = new string[]
{
Strings.Required_temperature_C,
};
public override string ParamName(int i) { return paramNames[i]; }
public override int ParamsCount() { return paramNames.Length; }
public override string ToString(int i)
{
switch (i)
{
case 0: return (RequiredTemp == 0) ? "---" : RequiredTemp.ToString();
default: return string.Empty;
}
}
public CfgUpdateFlags UpdateParam(int i, string strValue)
{
switch (i)
{
case 0:
if (strValue == "-" || strValue == "--" || strValue == "---")
{
RequiredTemp = 0;
}
else
{
RequiredTemp = Utils.ParseUFloat(strValue);
}
return CfgUpdateFlags.None;
default:
return CfgUpdateFlags.None;
}
}
/// <summary>
/// Verifiy the string representation of the parameter
/// </summary>
/// <param name="i">Parameter ID</param>
/// <param name="strValue">String representation of the parameter</param>
/// <param name="message">In case false is returned this is the error messsage to be displayed</param>
/// <returns>true = parameter OK, false = parameter NOK</returns>
public bool ValidateParam(int i, string strValue, out string message)
{
message = string.Empty;
float temp;
switch (i)
{
case 0: /// T_hot_heating
if (strValue == "-" || strValue == "--" || strValue == "---" ||
(Utils.TryParseUFloat(strValue, out temp) && (temp == 0 || (temp >= 5 && temp <= 95.0f))))
{
return true;
}
break;
default:
message = "Invalid index";
return false;
}
message = ParamName(i) + " is invalid";
return false;
}
void CopyContentTo(ProcParams prms)
{
prms.RequiredTemp = this.RequiredTemp;
}
public IParamsProvider Clone()
{
ProcParams pars = new ProcParams();
CopyContentTo(pars);
return pars;
}
public override void UpdateFromDbEntity(ComponentProcedure dbEntity)
{
if (dbEntity == null) return;
try
{
ProcParams tmp = Serializer.Deserialize(new StringReader(dbEntity.Parameters)) as ProcParams;
procedureParamsEntity = dbEntity;
componentName = dbEntity.CmpntName;
procedure = dbEntity.Procedure;
if (tmp != null) tmp.CopyContentTo(this);
}
catch
{
}
}
/// <summary>
/// Parameterless constructor initializes the parameters
/// </summary>
public ProcParams()
{
}
public ProcParams(bool initialize)
{
if (initialize) InitializeAll();
}
public ProcParams(ComponentProcedure procParamsEntity, string componentName, Procedure procedure)
{
this.procedureParamsEntity = procParamsEntity;
this.componentName = componentName;
this.procedure = procedure;
}
}
}
@@ -0,0 +1,61 @@
///
/// Copyright (c) 2022 Sensus Slovensko a.s.
///
using System;
using log4net;
using TBF.Boxes;
namespace TBF.Rig.Modbus.TempControl.Novus
{
public class ReadTempOp : IOperation
{
private static readonly ILog log = LogManager.GetLogger(typeof(ReadTempOp));
public override string ToString() { return string.Format("ReadTempOp({0},.,{1})", novus.Name, eventDone); }
/// Set by the constructor
TControl novus;
Event eventDone;
DoubleBox temp;
/// <summary>
/// Events: TempInDone, TempOutDone, TempDivDone or Error
/// </summary>
/// <param name="easytherm">TempMeter reference</param>
/// <param name="temp">Reference to the variable, value is in degree Celsius</param>
/// <param name="eventDone">Event to be returned by Run() when completed OK</param>
public ReadTempOp(TControl easytherm, ref DoubleBox temp, Event eventDone)
{
if (easytherm == null) throw new ArgumentNullException("easytherm");
this.novus = easytherm;
this.temp = temp;
this.eventDone = eventDone;
log.Debug(this.ToString());
}
public ReadTempOp(TControl tempMeter, ref DoubleBox temp)
: this(tempMeter, ref temp, Event.TempDone)
{
}
/// <summary>Start this operation</summary>
public void Start()
{
temp.Val = novus.ReadTemperature();
}
/// <summary>Run this operation</summary>
/// <returns>
/// Event.TempInDone, Event.TempOutDone or Event.TempDivDone
/// </returns>
public Event Run()
{
temp.Val = novus.ReadTemperature();
return eventDone;
}
/// <summary>Stop this operation</summary>
public void Stop()
{
}
}
}
@@ -0,0 +1,55 @@
///
/// Copyright (c) 2022 Sensus Slovensko a.s.
///
using System;
using log4net;
using TBF.Boxes;
namespace TBF.Rig.Modbus.TempControl.Novus
{
public class SetRequiredTemperatureOp : IOperation
{
private static readonly ILog log = LogManager.GetLogger(typeof(SetRequiredTemperatureOp));
public override string ToString() { return string.Format("SetRequiredTemperatureOp({0})", eventDone); }
/// Set by the constructor
readonly TControl easytherm;
readonly Event eventDone;
/// <summary>
/// Events: PressureInDone, PressureOutDone or Error
/// </summary>
/// <param name="easytherm">Pressure meter reference</param>
/// <param name="pressure">Reference to the measured pressure variable, value is in bar</param>
/// <param name="eventDone">Event to be returned by Run() when completed OK</param>
public SetRequiredTemperatureOp(TControl easytherm, Event eventDone)
{
if (easytherm == null) throw new ArgumentNullException("easytherm");
this.easytherm = easytherm;
this.eventDone = eventDone;
log.Debug(this.ToString());
}
public SetRequiredTemperatureOp(TControl easytherm)
: this(easytherm, Event.ConditionMet)
{
}
/// <summary>Start this operation</summary>
public void Start()
{
easytherm.SetTemperatureSetpoint();
}
/// <summary>Run this operation</summary>
public Event Run()
{
return eventDone;
}
/// <summary>Stop this operation</summary>
public void Stop()
{
}
}
}
@@ -0,0 +1,57 @@
///
/// Copyright (c) 2022 Sensus Slovensko a.s.
///
using System;
using log4net;
using TBF.Boxes;
namespace TBF.Rig.Modbus.TempControl.Novus
{
public class SetTemperatureOp : IOperation
{
private static readonly ILog log = LogManager.GetLogger(typeof(SetTemperatureOp));
public override string ToString() { return string.Format("SetTemperatureOp({0},{1})", temperatureSetpoint, eventDone); }
/// Set by the constructor
readonly TControl easytherm;
readonly Event eventDone;
float temperatureSetpoint;
/// <summary>
/// Events: PressureInDone, PressureOutDone or Error
/// </summary>
/// <param name="easytherm">Pressure meter reference</param>
/// <param name="pressure">Reference to the measured pressure variable, value is in bar</param>
/// <param name="eventDone">Event to be returned by Run() when completed OK</param>
public SetTemperatureOp(TControl easytherm, float temperatureSetpoint, Event eventDone)
{
if (easytherm == null) throw new ArgumentNullException("easytherm");
this.easytherm = easytherm;
this.temperatureSetpoint = temperatureSetpoint;
this.eventDone = eventDone;
log.Debug(this.ToString());
}
public SetTemperatureOp(TControl easytherm, float temperatureSetpoint)
: this(easytherm, temperatureSetpoint, Event.SetOutputsDone)
{
}
/// <summary>Start this operation</summary>
public void Start()
{
easytherm.SetTemperatureSetpoint(temperatureSetpoint);
}
/// <summary>Run this operation</summary>
public Event Run()
{
return eventDone;
}
/// <summary>Stop this operation</summary>
public void Stop()
{
}
}
}
@@ -0,0 +1,289 @@
///
/// Copyright (c) 2022 Sensus Slovensko a.s.
///
using System;
using System.Collections.Generic;
using log4net;
using Common;
using Config.Entities;
using SchematicDrawing;
using TBF.Rig.Generic;
using TBF.Boxes;
namespace TBF.Rig.Modbus.TempControl.Novus
{
public class TControl : ComponentBase, IDevice, ITempControl, IDrawingItCmpntWithSetpoint, IDrawingItCmpntWithMeasuredVal
{
private static readonly ILog log = LogManager.GetLogger(typeof(TControl));
public override string ToString() { return string.Format("{0}({1})", ClassName, Cfg.ToString(-1)); }
const UInt16 SetpointAddress = 0; /// Temperature setpoint
const UInt16 ProcessValueAddress = 1; /// Actual temperature
const UInt16 StatusWord1 = 6; /// Status word 1
const UInt16 StatusWord2 = 9; /// Status word 2
const UInt16 StatusWord3 = 10; /// Status word 3
readonly TControlCfg novusCfg;
public IDrawingItem DrawingItem { get { return novusCfg as IDrawingItem; } }
Common.Modbus modbus;
int ticketNumber; /// 0 .. number of devices registered for regular polling - 1
public bool MsrmntAvailable { get { return true; } }
public double MeasuredVal { get { return ReadTemperature(); } }
public string AltString { get { return string.Empty; } }
public double SetpointVal
{
get { return temperatureSetPoint; }
set { temperatureSetPoint = value; }
}
///
public void IncreaseSetpoint()
{
temperatureSetPoint += 0.5;
if (temperatureSetPoint > 95.0) temperatureSetPoint = 95.0;
}
///
public void DecreaseSetpoint()
{
temperatureSetPoint -= 0.5;
if (temperatureSetPoint <= 5) temperatureSetPoint = 5;
}
bool novusDataValid;
double temperatureSetPoint;
double actualTemperature;
Int16 status1;
Int16 status2;
Int16 status3;
Int16 fwVersion;
Int16 controllerId;
bool temperatureSetPointValid;
bool temperatureSetPointRequested;
public float requiredTemp
{
get
{
return novusCfg.ProcParams != null ? novusCfg.ProcParams.RequiredTemp : 0;
}
}
bool heating;
bool cooling;
public TControl() { }
public TControl(Generic.IComponentCfg cfg, IList<Generic.IComponent> components)
: base(cfg)
{
novusCfg = cfg as TControlCfg;
}
/// <summary>Initialize this device</summary>
public override void Initialize()
{
temperatureSetPointValid = false;
temperatureSetPointRequested = false;
novusDataValid = false;
if (novusCfg.DebugLevel == DebugMode.Simulate)
{
log.FatalFormat("{0} simulated: {1}", Name, this);
}
else
{
modbus = TbfComponents.FindComponent(novusCfg.ParentName) as Common.Modbus;
if (modbus == null) throw new Exception("Cannot find " + Name + " parent");
modbus.ComponentNames[novusCfg.ModbusAddress] = Name;
ticketNumber = modbus.RegisterForPolling();
log.FatalFormat("{0} initialized: {1}", Name, this);
}
}
/// <summary>Run this device</summary>
public void RunDeviceBefore()
{
if (novusCfg.DebugLevel != DebugMode.Simulate &&
novusCfg.DebugLevel != DebugMode.FailureDuringOperation &&
modbus.ReceivedTelegrams[novusCfg.ModbusAddress].Count > 0)
{
byte[] telegram = modbus.ReceivedTelegrams[novusCfg.ModbusAddress].Dequeue();
if (telegram.Length == 5)
{
log.InfoFormat("[{0}] received 5 bytes", Name);
}
else if (telegram.Length == 27 && telegram[1] == (byte)Function.ReadHoldingRegisters && telegram[2] == 22)
{
Int16[] values = new Int16[11];
for (int i = 0; i < values.Length; i++)
{
values[i] = (Int16)(256 * telegram[2 * i + 3] + telegram[2 * i + 4]
- ((telegram[2 * i + 3] & 0x80) != 0 ? 65536 : 0));
}
temperatureSetPoint = (double)values[0] * 0.1; /// setpoint in 0.1 °C
actualTemperature = (double)values[1] * 0.1; /// temperature in 0.1 °C
status1 = values[6];
fwVersion = values[7];
controllerId = values[8];
status2 = values[9];
status3 = values[10];
novusDataValid = true;
log.InfoFormat("[{0}] setpoint = {1} temperature = {2}", Name, temperatureSetPoint, actualTemperature);
log.InfoFormat("[{0}] s1={1} s2={2} s3={3} fw={4} id={5}",
Name, status1.ToString("X02"), status2.ToString("X02"), status3.ToString("X02"),
fwVersion, controllerId == 18 ? "N1200HC" : controllerId == 48 ? "N1200" : "unknonw");
}
else
{
log.InfoFormat("[{0}] received soemthing else", Name);
}
}
}
const int Modulo = 2;
/// <summary>Run this device</summary>
public void RunDeviceAfter()
{
if (novusCfg.DebugLevel != DebugMode.Simulate &&
novusCfg.DebugLevel != DebugMode.FailureDuringOperation &&
modbus.IsMyTurn(ticketNumber))
{
if (novusDataValid && (requiredTemp != 0) && (requiredTemp != temperatureSetPoint))
{
SetTemperatureSetpoint(requiredTemp);
log.InfoFormat("{0} - Set new temperature setpoint = {1}", Name, requiredTemp);
}
else
{
SendValueToNovus(Function.ReadHoldingRegisters, 0, 11); /// Read setpoint, PV (actual temperature), status1, status2, status3, FW version etc.
//SendValueToNovus(Function.ReadHoldingRegisters, 0, 2); /// Read setpoint and PV (actual temperature)
//SendValueToNovus(Function.ReadHoldingRegisters, 6, 5); /// Read status1, status2, status3, FW version etc.
}
}
}
public void StopDevice() { }
public void StopDevice2() { }
/// <summary>
/// Set Easytherm controller to required temperature procedure parameter
/// </summary>
/// <returns>true = OK, false = any error</returns>
public bool SetTemperatureSetpoint()
{
return SetTemperatureSetpoint(requiredTemp);
}
/// <summary>
/// Set Easytherm controller to specified temperature
/// </summary>
/// <param name="reqTemp">Temperature in °C</param>
/// <returns>true = OK, false = any error</returns>
public bool SetTemperatureSetpoint(float reqTemp)
{
if (reqTemp != 0 && (reqTemp < 5 || reqTemp > 95.0f))
{
return false; /// required temperature out of range
}
if (novusDataValid && (reqTemp == temperatureSetPoint))
{
return true; /// already set to the required temperature
}
if (reqTemp != 0) /// temperature==0 disables sending the setpoint
{
Int16 usTempSetpoint = Convert.ToInt16(Math.Round(10 * reqTemp)); /// setpoint in 0.1 °C
ushort destAddress = SetpointAddress;
///
SendValueToNovus(Function.PresetSingleRegister, destAddress, usTempSetpoint);
}
temperatureSetPoint = reqTemp;
temperatureSetPointValid = true;
return true;
}
public void RequestTemperatureSetpoint()
{
SendValueToNovus(Function.ReadHoldingRegisters, SetpointAddress, 1); /// rel.address=2, 1 word
}
public void RequestActualTemperature()
{
SendValueToNovus(Function.ReadInputRegister, ProcessValueAddress, 1); /// rel.address=x, 1 word
}
public void RequestAll()
{
SendValueToNovus(Function.ReadInputRegister, 0, 2); /// Registers: Setpoint=0, ProcessValue=1, Status1=6, Status2=9, Status3=10
}
void SendValueToNovus(Function function, UInt16 address, Int16 value)
{
byte[] msg = new byte[8];
msg[0] = (byte)novusCfg.ModbusAddress;
msg[1] = (byte)function;
msg[2] = (byte)(address >> 8); /// Relative address Hi
msg[3] = (byte)(address & 0xFF); /// Relative address Lo
msg[4] = (byte)(value >> 8); /// Data Hi
msg[5] = (byte)(value & 0xFF); /// Data Lo
modbus.SendMessage(msg, Name);
}
///
/// Operations, etc.
///
public double ReadTemperature()
{
return actualTemperature;
}
/// <summary>
/// Events: SetOpututsDone, Error
/// </summary>
/// <returns>SetOutputsOp instance reference casted to IOperaton</returns>
public IOperation SetRequiredTemperatureOp()
{
return new SetRequiredTemperatureOp(this);
}
/// <summary>
/// Events: SetOpututsDone, Error
/// </summary>
/// <param name="temperature">Reference to a variable for the pressure in Bar</param>
/// <returns>SetOutputsOp instance reference casted to IOperaton</returns>
public IOperation SetTemperatureOp(float temperature)
{
return new SetTemperatureOp(this, temperature);
}
public IOperation ReadTempOp(ref DoubleBox temp)
{
return new ReadTempOp(this, ref temp);
}
public IOperation ReadTempOp(ref DoubleBox temp, Event eventDone)
{
return new ReadTempOp(this, ref temp, eventDone);
}
}
}
@@ -0,0 +1,218 @@
///
/// Copyright (c) 2022 Sensus Slovensko a.s.
///
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Serialization;
using Common;
using Config.Entities;
using SchematicDrawing;
using TBF.Rig.Generic;
namespace TBF.Rig.Modbus.TempControl.Novus
{
public class TControlCfg : ComponentCfgBase, IChildComponentCfg, IParamsProvider,
IDrawingItemWithSetpoint, IDrawingItemWithMeasuredVal
{
public static XmlSerializer Serializer = XmlSerializer.FromTypes(new[] { typeof(TControlCfg) })[0];
public override XmlSerializer GetSerializer() { return Serializer; }
public IComponentCfgCtrl GetControl(IList<Component> cmpntEntities)
{
var parents = cmpntEntities.Where(x => x.ClassName == "Modbus.Common");
return new Configs.ParamsProvider.ComponentCfgCtrl(this, parents);
}
///
/// Serialized parameters
///
public int ModbusAddress; /// 0: 1..254
/// Schematic drawing info
public Shape Shape { get; set; }
public int X { get; set; }
public int Y { get; set; }
public Sz Sz { get; set; }
public Orient Orient { get; set; }
public bool Flip { get; set; }
public int LblX { get; set; }
public int LblY { get; set; }
public Orient LblOrient { get; set; }
public int MsrdX { get; set; }
public int MsrdY { get; set; }
public Orient MsrdOrient { get; set; }
public string MsrdFormat { get; set; } /// 1
public Unit MsrdUnit { get; set; } /// 2
public double MsrdValLimLo { get; set; }
public double MsrdValLimHi { get; set; }
public int SetpX { get; set; }
public int SetpY { get; set; }
public Orient SetpOrient { get; set; }
public string SetpFormat { get; set; } /// 3
public Unit SetpUnit { get; set; } /// 4
[XmlIgnore]
public IList<GNode> GNodes { get; set; }
/// <summary> Procedure parameters </summary>
[XmlIgnore]
public ProcParams ProcParams;
public override IParamsProvider GetRuntimeProcParamsProvider() { return ProcParams; }
public override IParamsProvider CreateProcParamsProvider() { return new ProcParams(true); }
/// Private parameterless constructor invoked by all other (public) constructors
TControlCfg()
{
GNodes = new List<GNode>();
}
public TControlCfg(IComponentFactory factory)
: this()
{
this.Factory = factory;
ProcParams = CreateProcParamsProvider() as ProcParams;
Name = "Novus";
ParentName = "Modbus";
Shape = Shape.TempControl;
Sz = Sz.M;
MsrdValLimLo = 5;
MsrdValLimHi = 95;
MsrdY = 22;
InitializeAll();
}
public string ComponentName { get { return Name; } }
public void InitializeAll()
{
ModbusAddress = 49;
MsrdFormat = "{0:F1} °C";
MsrdUnit = Unit.C;
SetpFormat = "{0:F1} °C";
SetpUnit = Unit.C;
}
string[] paramNames = new string[]
{
"Modbus address", /// 0
"Measured temperature format", /// 1
"Unit of measured temperature", /// 2
"Setpoint format", /// 3
"Unit of temperature setpoint", /// 4
};
public string ParamName(int i) { return paramNames[i]; }
public int ParamsCount() { return paramNames.Length; }
public ICollection<string> ParamValues(int i)
{
switch (i)
{
case 2:
case 4:
return new string[] { "°C", "°F", "K" };
default:
return null;
}
}
public string ToString(int i)
{
switch (i)
{
case 0: return ModbusAddress.ToString();
case 1: return MsrdFormat;
case 2: return (MsrdUnit == Unit.K) ? "K" : (MsrdUnit == Unit.F) ? "°F" : "°C";
case 3: return SetpFormat;
case 4: return (SetpUnit == Unit.K) ? "K" : (SetpUnit == Unit.F) ? "°F" : "°C";
default:
return string.Format("{0}({1}) address={2}", Name, string.IsNullOrEmpty(ParentName) ? "-" : ParentName, ModbusAddress);
}
}
public CfgUpdateFlags UpdateParam(int i, string str)
{
switch (i)
{
case 0: ModbusAddress = int.Parse(str); return CfgUpdateFlags.RestartRqrd;
case 1: MsrdFormat = str; return CfgUpdateFlags.RestartRqrd;
case 2: MsrdUnit = (str == "°K" || str == "K") ? Unit.K
: (str == "°F" || str == "F") ? Unit.F
: Unit.C; return CfgUpdateFlags.RestartRqrd;
case 3: SetpFormat = str; return CfgUpdateFlags.RestartRqrd;
case 4: SetpUnit = (str == "°K" || str == "K") ? Unit.K
: (str == "°F" || str == "F") ? Unit.F
: Unit.C; return CfgUpdateFlags.RestartRqrd;
default: return CfgUpdateFlags.None;
}
}
public bool ValidateParam(int i, string str, out string message)
{
message = string.Empty;
int idummy;
switch (i)
{
case 0:
if (int.TryParse(str, out idummy) && idummy >= 1 && idummy <= 254) return true;
break;
case 1:
case 3:
return true;
case 2:
case 4:
if (str == "°K" || str == "K" || str == "°F" || str == "F" || str == "°C" || str == "C") return true;
break;
default:
message = "Invalid index";
return false;
}
message = ParamName(i) + " is invalid";
return false;
}
void CopyContentTo(TControlCfg prms)
{
prms.ParentName = ParentName;
prms.ModbusAddress = ModbusAddress;
prms.Shape = Shape;
prms.Sz = Sz;
prms.Orient = Orient;
prms.Flip = Flip;
prms.LblX = LblX;
prms.LblY = LblY;
prms.LblOrient = LblOrient;
prms.SetpX = SetpX;
prms.SetpY = SetpY;
prms.SetpOrient = SetpOrient;
prms.SetpFormat = SetpFormat;
prms.SetpUnit = SetpUnit;
prms.MsrdX = MsrdX;
prms.MsrdY = MsrdY;
prms.MsrdOrient = MsrdOrient;
prms.MsrdFormat = MsrdFormat;
prms.MsrdUnit = MsrdUnit;
prms.MsrdValLimLo = MsrdValLimLo;
prms.MsrdValLimHi = MsrdValLimHi;
}
public IParamsProvider Clone()
{
TControlCfg pars = new TControlCfg();
CopyContentTo(pars);
return pars;
}
public bool UpdateEmbeddedDbEntity()
{
return true; /// =OK, do nothing
}
}
}