Initial commit almost identical to SVN-repo rev.340

This commit is contained in:
Milan Hanajik
2014-07-28 09:56:40 +02:00
commit 175a92f633
575 changed files with 186534 additions and 0 deletions
@@ -0,0 +1,66 @@
using System.IO;
using System.IO.Ports;
using System.Xml.Serialization;
using TBF.BenchControl.Generic;
namespace TBF.BenchControl.MettlerToledo
{
public class BalanceCfg : ComponentCfgBase, Generic.IComponentCfg
{
public int ComPortNr;
public int BaudRate;
public Parity Parity;
public int DataBits;
public StopBits StopBits;
public Handshake Handshake;
public float Capacity; /// Balance range in 'kg' or tank volume in 'l'
/// Parameterless constructor
public BalanceCfg()
{
}
/// Constructor
public BalanceCfg(IComponentFactory factory, string name, int comPortNr, int baudRate, Parity parity, int dataBits, StopBits stopBits, Handshake handshake, float capacity)
: base(factory, name)
{
this.ComPortNr = comPortNr;
this.BaudRate = baudRate;
this.Parity = parity;
this.DataBits = dataBits;
this.StopBits = stopBits;
this.Handshake = handshake;
this.Capacity = capacity;
}
public IComponentCfg Clone()
{
return new BalanceCfg(Factory, Name, ComPortNr, BaudRate, Parity, DataBits, StopBits, Handshake, Capacity);
}
public string ToString(int i)
{
return string.Format("COM{0}, {1}Bd, {2}bits, parity={3}, stopBits={4}, {5}, capacity={6}kg", ComPortNr, BaudRate, DataBits, Parity, StopBits, Handshake, Capacity);
}
public TBF.Entities.Component CreateDbEntity()
{
using (var writer = new StringWriter())
{
(new XmlSerializer(GetType())).Serialize(writer, this);
return Entities.Component.CreateFromCfg(Name, Factory.ClassName, ParentName, ItemNr, DebugLevel, LogLevel, writer.ToString());
}
}
public static IComponentCfg CreateFromDbEntity(Entities.Component component, IComponentFactory factory)
{
using (var reader = new StringReader(component.Parameters))
{
BalanceCfg config = (BalanceCfg)(new XmlSerializer(typeof(BalanceCfg))).Deserialize(reader);
config.InitCfgBaseFromEntity(component, factory);
return config;
}
}
}
}
@@ -0,0 +1,259 @@
namespace TBF.BenchControl.MettlerToledo
{
partial class BalanceCfgCtrl
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.handshakeComboBox = new System.Windows.Forms.ComboBox();
this.stopBitsComboBox = new System.Windows.Forms.ComboBox();
this.parityComboBox = new System.Windows.Forms.ComboBox();
this.nameTextBox = new System.Windows.Forms.TextBox();
this.nameLabel = new System.Windows.Forms.Label();
this.classNameLabel = new System.Windows.Forms.Label();
this.handshakeLabel = new System.Windows.Forms.Label();
this.stopBitsLabel = new System.Windows.Forms.Label();
this.dataBitsTextBox = new System.Windows.Forms.TextBox();
this.dataBitsLabel = new System.Windows.Forms.Label();
this.partityLabel = new System.Windows.Forms.Label();
this.baudRateTextBox = new System.Windows.Forms.TextBox();
this.baudRateLabel = new System.Windows.Forms.Label();
this.comPortNrTextBox = new System.Windows.Forms.TextBox();
this.label1 = new System.Windows.Forms.Label();
this.rangeLabel = new System.Windows.Forms.Label();
this.rangeTextBox = new System.Windows.Forms.TextBox();
this.label2 = new System.Windows.Forms.Label();
this.SuspendLayout();
//
// handshakeComboBox
//
this.handshakeComboBox.Enabled = false;
this.handshakeComboBox.FormattingEnabled = true;
this.handshakeComboBox.Location = new System.Drawing.Point(136, 173);
this.handshakeComboBox.Name = "handshakeComboBox";
this.handshakeComboBox.Size = new System.Drawing.Size(130, 21);
this.handshakeComboBox.TabIndex = 14;
//
// stopBitsComboBox
//
this.stopBitsComboBox.Enabled = false;
this.stopBitsComboBox.FormattingEnabled = true;
this.stopBitsComboBox.Location = new System.Drawing.Point(136, 149);
this.stopBitsComboBox.Name = "stopBitsComboBox";
this.stopBitsComboBox.Size = new System.Drawing.Size(130, 21);
this.stopBitsComboBox.TabIndex = 12;
//
// parityComboBox
//
this.parityComboBox.Enabled = false;
this.parityComboBox.FormattingEnabled = true;
this.parityComboBox.Location = new System.Drawing.Point(136, 101);
this.parityComboBox.Name = "parityComboBox";
this.parityComboBox.Size = new System.Drawing.Size(130, 21);
this.parityComboBox.TabIndex = 8;
//
// nameTextBox
//
this.nameTextBox.Enabled = false;
this.nameTextBox.Location = new System.Drawing.Point(136, 29);
this.nameTextBox.Name = "nameTextBox";
this.nameTextBox.Size = new System.Drawing.Size(130, 20);
this.nameTextBox.TabIndex = 2;
//
// nameLabel
//
this.nameLabel.AutoSize = true;
this.nameLabel.Location = new System.Drawing.Point(26, 32);
this.nameLabel.Name = "nameLabel";
this.nameLabel.Size = new System.Drawing.Size(35, 13);
this.nameLabel.TabIndex = 1;
this.nameLabel.Text = "Name";
//
// classNameLabel
//
this.classNameLabel.AutoSize = true;
this.classNameLabel.Location = new System.Drawing.Point(133, 8);
this.classNameLabel.Name = "classNameLabel";
this.classNameLabel.Size = new System.Drawing.Size(83, 13);
this.classNameLabel.TabIndex = 0;
this.classNameLabel.Text = "ComonentName";
//
// handshakeLabel
//
this.handshakeLabel.AutoSize = true;
this.handshakeLabel.Location = new System.Drawing.Point(25, 176);
this.handshakeLabel.Name = "handshakeLabel";
this.handshakeLabel.Size = new System.Drawing.Size(62, 13);
this.handshakeLabel.TabIndex = 13;
this.handshakeLabel.Text = "Handshake";
//
// stopBitsLabel
//
this.stopBitsLabel.AutoSize = true;
this.stopBitsLabel.Location = new System.Drawing.Point(25, 152);
this.stopBitsLabel.Name = "stopBitsLabel";
this.stopBitsLabel.Size = new System.Drawing.Size(49, 13);
this.stopBitsLabel.TabIndex = 11;
this.stopBitsLabel.Text = "Stop Bits";
//
// dataBitsTextBox
//
this.dataBitsTextBox.Enabled = false;
this.dataBitsTextBox.Location = new System.Drawing.Point(136, 125);
this.dataBitsTextBox.Name = "dataBitsTextBox";
this.dataBitsTextBox.Size = new System.Drawing.Size(43, 20);
this.dataBitsTextBox.TabIndex = 10;
//
// dataBitsLabel
//
this.dataBitsLabel.AutoSize = true;
this.dataBitsLabel.Location = new System.Drawing.Point(25, 128);
this.dataBitsLabel.Name = "dataBitsLabel";
this.dataBitsLabel.Size = new System.Drawing.Size(50, 13);
this.dataBitsLabel.TabIndex = 9;
this.dataBitsLabel.Text = "Data Bits";
//
// partityLabel
//
this.partityLabel.AutoSize = true;
this.partityLabel.Location = new System.Drawing.Point(25, 104);
this.partityLabel.Name = "partityLabel";
this.partityLabel.Size = new System.Drawing.Size(33, 13);
this.partityLabel.TabIndex = 7;
this.partityLabel.Text = "Parity";
//
// baudRateTextBox
//
this.baudRateTextBox.Enabled = false;
this.baudRateTextBox.Location = new System.Drawing.Point(136, 77);
this.baudRateTextBox.Name = "baudRateTextBox";
this.baudRateTextBox.Size = new System.Drawing.Size(130, 20);
this.baudRateTextBox.TabIndex = 6;
//
// baudRateLabel
//
this.baudRateLabel.AutoSize = true;
this.baudRateLabel.Location = new System.Drawing.Point(25, 80);
this.baudRateLabel.Name = "baudRateLabel";
this.baudRateLabel.Size = new System.Drawing.Size(58, 13);
this.baudRateLabel.TabIndex = 5;
this.baudRateLabel.Text = "Baud Rate";
//
// comPortNrTextBox
//
this.comPortNrTextBox.Enabled = false;
this.comPortNrTextBox.Location = new System.Drawing.Point(136, 53);
this.comPortNrTextBox.Name = "comPortNrTextBox";
this.comPortNrTextBox.Size = new System.Drawing.Size(43, 20);
this.comPortNrTextBox.TabIndex = 4;
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(25, 56);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(98, 13);
this.label1.TabIndex = 3;
this.label1.Text = "Serial Port Number:";
//
// rangeLabel
//
this.rangeLabel.AutoSize = true;
this.rangeLabel.Location = new System.Drawing.Point(25, 201);
this.rangeLabel.Name = "rangeLabel";
this.rangeLabel.Size = new System.Drawing.Size(76, 13);
this.rangeLabel.TabIndex = 15;
this.rangeLabel.Text = "Tank Capacity";
//
// rangeTextBox
//
this.rangeTextBox.Enabled = false;
this.rangeTextBox.Location = new System.Drawing.Point(136, 198);
this.rangeTextBox.Name = "rangeTextBox";
this.rangeTextBox.Size = new System.Drawing.Size(43, 20);
this.rangeTextBox.TabIndex = 16;
//
// label2
//
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(185, 201);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(19, 13);
this.label2.TabIndex = 17;
this.label2.Text = "kg";
//
// BalanceCfgCtrl
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.Controls.Add(this.label2);
this.Controls.Add(this.rangeTextBox);
this.Controls.Add(this.rangeLabel);
this.Controls.Add(this.handshakeComboBox);
this.Controls.Add(this.stopBitsComboBox);
this.Controls.Add(this.parityComboBox);
this.Controls.Add(this.nameTextBox);
this.Controls.Add(this.nameLabel);
this.Controls.Add(this.classNameLabel);
this.Controls.Add(this.handshakeLabel);
this.Controls.Add(this.stopBitsLabel);
this.Controls.Add(this.dataBitsTextBox);
this.Controls.Add(this.dataBitsLabel);
this.Controls.Add(this.partityLabel);
this.Controls.Add(this.baudRateTextBox);
this.Controls.Add(this.baudRateLabel);
this.Controls.Add(this.comPortNrTextBox);
this.Controls.Add(this.label1);
this.Name = "BalanceCfgCtrl";
this.Size = new System.Drawing.Size(300, 240);
this.Load += new System.EventHandler(this.BalanceCfgCtrl_Load);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.ComboBox handshakeComboBox;
private System.Windows.Forms.ComboBox stopBitsComboBox;
private System.Windows.Forms.ComboBox parityComboBox;
private System.Windows.Forms.TextBox nameTextBox;
private System.Windows.Forms.Label nameLabel;
private System.Windows.Forms.Label classNameLabel;
private System.Windows.Forms.Label handshakeLabel;
private System.Windows.Forms.Label stopBitsLabel;
private System.Windows.Forms.TextBox dataBitsTextBox;
private System.Windows.Forms.Label dataBitsLabel;
private System.Windows.Forms.Label partityLabel;
private System.Windows.Forms.TextBox baudRateTextBox;
private System.Windows.Forms.Label baudRateLabel;
private System.Windows.Forms.TextBox comPortNrTextBox;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label rangeLabel;
private System.Windows.Forms.TextBox rangeTextBox;
private System.Windows.Forms.Label label2;
}
}
@@ -0,0 +1,167 @@
using System;
using System.Globalization;
using System.Windows.Forms;
using System.IO.Ports;
using TBF.BenchControl.Generic;
namespace TBF.BenchControl.MettlerToledo
{
public partial class BalanceCfgCtrl : UserControl, IComponentCfgCtrl
{
BalanceCfg config;
public IComponentCfg Config
{
get { return config as IComponentCfg; }
set
{
config = value as BalanceCfg;
Redraw();
}
}
public BalanceCfgCtrl()
{
InitializeComponent();
parityComboBox.Items.Add(Parity.None.ToString());
parityComboBox.Items.Add(Parity.Even.ToString());
parityComboBox.Items.Add(Parity.Odd.ToString());
stopBitsComboBox.Items.Add(StopBits.None.ToString());
stopBitsComboBox.Items.Add(StopBits.One.ToString());
stopBitsComboBox.Items.Add(StopBits.OnePointFive.ToString());
stopBitsComboBox.Items.Add(StopBits.Two.ToString());
handshakeComboBox.Items.Add(Handshake.None.ToString());
handshakeComboBox.Items.Add(Handshake.RequestToSend.ToString());
handshakeComboBox.Items.Add(Handshake.XOnXOff.ToString());
}
int GetParityIx(Parity par)
{
if (par == Parity.None) return 0;
if (par == Parity.Even) return 0;
if (par == Parity.Odd) return 0;
return -1;
}
Parity GetParity(string str)
{
if (str.Equals(Parity.None.ToString())) return Parity.None;
if (str.Equals(Parity.Even.ToString())) return Parity.Even;
if (str.Equals(Parity.Odd.ToString())) return Parity.Odd;
return (Parity)(-1);
}
int GetStopBitsIx(StopBits sb)
{
if (sb == StopBits.None) return 0;
if (sb == StopBits.One) return 1;
if (sb == StopBits.OnePointFive) return 2;
if (sb == StopBits.Two) return 3;
return -1;
}
StopBits GetStopBits(string str)
{
if (str.Equals(StopBits.None.ToString())) return StopBits.None;
if (str.Equals(StopBits.One.ToString())) return StopBits.One;
if (str.Equals(StopBits.OnePointFive.ToString())) return StopBits.OnePointFive;
if (str.Equals(StopBits.Two.ToString())) return StopBits.Two;
return (StopBits)(-1);
}
int GetHandshakeIx(Handshake par)
{
if (par == Handshake.None) return 0;
if (par == Handshake.RequestToSend) return 0;
if (par == Handshake.XOnXOff) return 0;
return -1;
}
Handshake GetHandshake(string str)
{
if (str.Equals(Handshake.None.ToString())) return Handshake.None;
if (str.Equals(Handshake.RequestToSend.ToString())) return Handshake.RequestToSend;
if (str.Equals(Handshake.XOnXOff.ToString())) return Handshake.XOnXOff;
return (Handshake)(-1);
}
private void BalanceCfgCtrl_Load(object sender, EventArgs e)
{
Redraw();
}
void Redraw()
{
if (config == null) return; /// Control was not loaded, settings were not changed
classNameLabel.Text = config.Factory.ClassName;
nameTextBox.Text = config.Name;
comPortNrTextBox.Text = config.ComPortNr.ToString();
baudRateTextBox.Text = config.BaudRate.ToString();
parityComboBox.Text = config.Parity.ToString();
dataBitsTextBox.Text = config.DataBits.ToString();
stopBitsComboBox.Text = config.StopBits.ToString();
handshakeComboBox.Text = config.Handshake.ToString();
rangeTextBox.Text = config.Capacity.ToString();
}
public void Unlock()
{
nameTextBox.Enabled = true;
comPortNrTextBox.Enabled = true;
baudRateTextBox.Enabled = true;
parityComboBox.Enabled = true;
dataBitsTextBox.Enabled = true;
stopBitsComboBox.Enabled = true;
handshakeComboBox.Enabled = true;
rangeTextBox.Enabled = true;
}
public CfgVerifyFlags VerifyCfg(ref string message)
{
CfgVerifyFlags flags = CfgVerifyFlags.None;
int dummy;
if (!int.TryParse(comPortNrTextBox.Text, out dummy) || dummy < 1 || dummy > 999)
{
flags |= CfgVerifyFlags.Error;
message += Environment.NewLine + "'Serial Port Number' is not valid";
}
if (!int.TryParse(baudRateTextBox.Text, out dummy) || dummy < 150 || dummy > 115200)
{
flags |= CfgVerifyFlags.Error;
message += Environment.NewLine + "'Baud Rate' is not valid";
}
if (!int.TryParse(dataBitsTextBox.Text, out dummy) || dummy < 7 || dummy > 8)
{
flags |= CfgVerifyFlags.Error;
message += Environment.NewLine + "'Data Bits' is not valid";
}
float fdummy;
bool floatOk = (float.TryParse(rangeTextBox.Text, NumberStyles.AllowDecimalPoint, CultureInfo.CurrentCulture, out fdummy) ||
float.TryParse(rangeTextBox.Text, NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out fdummy));
if (!floatOk || fdummy <= 0)
{
flags |= CfgVerifyFlags.Error;
message += Environment.NewLine + "'Range' is not valid";
}
return flags;
}
public void UpdateCfg()
{
if (config == null) return; /// Control was not loaded, settings were not changed
config.Name = nameTextBox.Text;
config.ComPortNr = int.Parse(comPortNrTextBox.Text);
config.BaudRate = int.Parse(baudRateTextBox.Text);
config.Parity = GetParity(parityComboBox.SelectedItem.ToString());
config.DataBits = int.Parse(dataBitsTextBox.Text);
config.StopBits = GetStopBits(stopBitsComboBox.SelectedItem.ToString());
config.Handshake = GetHandshake(handshakeComboBox.SelectedItem.ToString());
bool floatOk = (float.TryParse(rangeTextBox.Text, NumberStyles.AllowDecimalPoint, CultureInfo.CurrentCulture, out config.Capacity) ||
float.TryParse(rangeTextBox.Text, NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out config.Capacity));
}
}
}
@@ -0,0 +1,120 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>
@@ -0,0 +1,423 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using System.IO.Ports;
using log4net;
using TBF.BenchControl.Generic;
namespace TBF.BenchControl.MettlerToledo
{
/// <summary>
/// Mettler Toledo ICS4_5 Weighting terminal connected via serial interface (RS232)
/// </summary>
/// <note>
/// Implemented and tested on 15.10.2013 by Milan Hanajik
/// </note>
public class BalanceDev : TestBenchSim, IComponent, IDevice, GenericDevices.IBalance
{
/// <summary>
/// Info: StartMassMeasurement() and "Balnce response = .., Mass = ..."
/// Warn: Start measurement when busy is true
/// </summary>
private static readonly ILog log = LogManager.GetLogger(typeof(BalanceDev));
public override string ToString() { return string.Format("{0}, Mettler-Toledo Balance", balanceCfg.Name); }
/// <summary>
/// Enumeration of balances via static fields and methods
/// </summary>
static int nextBalanceIdx = 0;
public static void ResetStaticProperties() { nextBalanceIdx = 0; }
public static int BalancesCount { get { return nextBalanceIdx; } }
public static BalanceDev[] Balances;
public static float[] Masses;
///
protected int balanceNr; /// 0-based balance number
protected readonly BalanceCfg balanceCfg;
public Generic.IComponentCfg Cfg { get { return balanceCfg; } }
protected SerialPort serialPort;
protected StringBuilder stringBuilder;
public string Name { get { return balanceCfg.Name; } }
public int BalanceNr { get { return balanceNr; } }
public float Capacity { get { return balanceCfg.Capacity; } }
public IList<Entities.MeasurementCorrection> Corrections { get { return balanceCfg.Corrections; } }
/// <summary>The state of the mass measurement</summary>
public MsrmntState MsrmntState
{
get { return msrmntState; }
}
protected MsrmntState msrmntState;
/// <summary>The mass after StartMassMeasurement() when MsrmntState == MsrmntState.Valid</summary>
public float Mass
{
get { return mass; }
}
protected float mass;
/// <summary>The time stamp after StartMassMeasurement() when MsrmntState == MsrmntState.Valid</summary>
public int MsrmntTimeStamp
{
get { return msrmntTimeStamp; }
}
protected int msrmntTimeStamp;
/// <summary>
/// Constructor
/// </summary>
/// <param name="balanceEntity">Balance properties</param>
public BalanceDev(BalanceCfg cfg, IList<Generic.IComponent> components)
{
if (cfg == null) throw new ArgumentNullException("cfg");
this.balanceCfg = cfg;
balanceNr = nextBalanceIdx++;
Masses = new float[nextBalanceIdx]; /// (re)initialize the static array of masses of all balances
if (Balances == null || Balances.Length < nextBalanceIdx)
{
BalanceDev[] balancesSoFar = Balances;
Balances = new BalanceDev[nextBalanceIdx];
if (balancesSoFar != null) for (int i = 0; i < balancesSoFar.Length; i++) Balances[i] = balancesSoFar[i];
Balances[nextBalanceIdx - 1] = this;
}
}
public new void Initialize()
{
msrmntState = MsrmntState.Failed; /// Data not valid yet
if (balanceCfg.DebugLevel == Entities.DebugMode.Simulate) return;
stringBuilder = new StringBuilder(40);
string comPortName = "COM" + balanceCfg.ComPortNr.ToString();
serialPort = new SerialPort(comPortName, balanceCfg.BaudRate, balanceCfg.Parity, balanceCfg.DataBits, balanceCfg.StopBits);
serialPort.Handshake = balanceCfg.Handshake;
serialPort.Open();
}
public void ZeroWhenStable()
{
if (balanceCfg.DebugLevel == Entities.DebugMode.Simulate) return;
if (msrmntState == MsrmntState.Busy)
{
log.Warn("ZeroWhenStable() returns without starting zeroing the scale because measurementState == MeasurementState.Busy");
return;
}
log.Info("ZeroWhenStable()");
msrmntState = MsrmntState.Busy;
stringBuilder.Clear();
serialPort.Write("Z\r\n");
}
public void Taring()
{
if (balanceCfg.DebugLevel == Entities.DebugMode.Simulate) return;
if (msrmntState == MsrmntState.Busy)
{
log.Warn("Taring() returns without starting taring the scale because measurementState == MeasurementState.Busy");
return;
}
log.Info("Taring()");
msrmntState = MsrmntState.Busy;
stringBuilder.Clear();
serialPort.Write("T\r\n");
}
/// <summary>
/// Get a stable mass measurement
/// </summary>
public void GetStableMassMeasurement()
{
if (balanceCfg.DebugLevel == Entities.DebugMode.Simulate) return;
if (msrmntState == MsrmntState.Busy)
{
log.Warn("GetStableMassMeasurement() returns without starting a measurement because measurementState == MeasurementState.Busy");
return;
}
log.Info("GetStableMassMeasurement()");
msrmntState = MsrmntState.Busy;
stringBuilder.Clear();
serialPort.Write("S\r\n");
}
/// <summary>
/// Get an immediate mass measurement
/// </summary>
public void GetImmediateMassMeasurement()
{
if (balanceCfg.DebugLevel == Entities.DebugMode.Simulate) return;
if (msrmntState == MsrmntState.Busy)
{
log.Warn("GetImmediateMassMeasurement() returns without starting a measurement because measurementState == MeasurementState.Busy");
return;
}
log.Info("GetImmediateMassMeasurement()");
msrmntState = MsrmntState.Busy;
stringBuilder.Clear();
serialPort.Write("SI\r\n");
}
/// <summary>Units for SetUnits() argument</summary>
public enum Units
{
g,
kg,
t,
lb,
oz
}
/// <summary>
/// Get the serial number
/// </summary>
/// <remarks>After a successful SetUnits(kg) mass is still sent in g. MH 15.10.2013</remarks>
public void SetUnits(Units unit)
{
if (balanceCfg.DebugLevel == Entities.DebugMode.Simulate) return;
if (msrmntState == MsrmntState.Busy)
{
log.Warn("SetUnits() returns without setting the units because measurementState == MeasurementState.Busy");
return;
}
log.InfoFormat("SetUnits({0})", unit);
msrmntState = MsrmntState.Busy;
stringBuilder.Clear();
switch (unit)
{
case Units.g: serialPort.Write("U g\r\n"); break;
case Units.kg: serialPort.Write("U kg\r\n"); break;
case Units.t: serialPort.Write("U t\r\n"); break;
case Units.lb: serialPort.Write("U lb\r\n"); break;
case Units.oz: serialPort.Write("U oz\r\n"); break;
}
}
/// <summary>
/// Parse characters received from the serial port
/// </summary>
public virtual void RunDeviceBefore()
{
if (balanceCfg.DebugLevel == Entities.DebugMode.Simulate)
{
mass = GetSimMass(balanceNr);
Masses[balanceNr] = mass;
msrmntState = MsrmntState.Valid;
msrmntTimeStamp = StateMachine.CurrentTime;
return;
}
log.Debug("RunDevice()");
if (msrmntState != MsrmntState.Busy) return; /// No measurement in progress
string justReceived = serialPort.ReadExisting();
if (justReceived != null && justReceived.Length > 0)
{
log.Debug("RunDevice() received " + justReceived);
stringBuilder.Append(justReceived);
}
string currentBuffer = stringBuilder.ToString();
int eolPos = currentBuffer.IndexOf("\r\n");
if (eolPos >= 0)
{
msrmntTimeStamp = StateMachine.CurrentTime;
/// Get part of theh string before EOL
string received = currentBuffer.Substring(0, eolPos);
/// Put the rest back to the string builder
stringBuilder.Clear();
if (currentBuffer.Length > eolPos + 2)
{
stringBuilder.Append(currentBuffer.Substring(eolPos + 2));
}
while (true)
{
string tmp = received.Replace(" ", " ");
if (tmp.Length == received.Length) break;
received = tmp;
}
string[] fields = received.Split(new char[] { ' ' });
if (fields.Length == 1 && fields[0].Equals("ZA")) /// Zero when stable
{
mass = 0;
Masses[balanceNr] = mass;
//msrmntState = MsrmntState.Valid;
log.InfoFormat("Balance response = \"{0}<cr><lf>\"", received);
return;
}
else if (fields.Length < 2)
{
msrmntState = MsrmntState.Failed;
log.WarnFormat("Balance response = \"{0}<cr><lf>\", Unexpected error !!!", received);
return;
}
if (fields[0].Equals("Z")) /// Zero when stable
{
if (fields.Length == 2 && fields[1].Equals("A"))
{
mass = 0;
Masses[balanceNr] = mass;
//msrmntState = MsrmntState.Valid;
log.InfoFormat("Balance response = \"{0}<cr><lf>\"", received);
return;
}
else
{
msrmntState = MsrmntState.Failed;
log.WarnFormat("Balance response = \"{0}<cr><lf>\", error !!!", received);
}
}
else if (fields[0].Equals("S")) /// Stable mass: field[1] = <mass> field[2] = "kg"
{
if (fields.Length >= 3 &&
float.TryParse(fields[1],
NumberStyles.AllowDecimalPoint | NumberStyles.AllowLeadingSign,
CultureInfo.InvariantCulture,
out mass))
{
if (fields[2].Equals("g")) mass /= 1000.0f;
if (fields[2].Equals("t")) mass *= 1000.0f;
Masses[balanceNr] = mass;
msrmntState = MsrmntState.Valid;
log.InfoFormat("Balance response = \"{0}<cr><lf>\", Mass = {1}", received, mass);
}
else if (fields.Length == 2 && fields[1].Equals("-"))
{
mass = 0;
Masses[balanceNr] = mass;
msrmntState = MsrmntState.Valid;
log.InfoFormat("Balance response = \"{0}<cr><lf>\", Mass = {1}", received, mass);
}
else
{
msrmntState = MsrmntState.Failed;
log.WarnFormat("Balance response = \"{0}<cr><lf>\", Overload or and unexpected error !!!", received);
bool b = float.TryParse(fields[1], NumberStyles.AllowDecimalPoint | NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture, out mass);
}
}
else if (fields[0].Equals("SD")) /// Dynamic mass: field[1] = <mass> field[2] = "kg"
{
if (fields.Length >= 3 &&
float.TryParse(fields[1],
NumberStyles.AllowDecimalPoint | NumberStyles.AllowLeadingSign,
CultureInfo.InvariantCulture,
out mass))
{
if (fields[2].Equals("g")) mass /= 1000.0f;
if (fields[2].Equals("t")) mass *= 1000.0f;
Masses[balanceNr] = mass;
msrmntState = MsrmntState.Valid;
log.InfoFormat("Balance response = \"{0}<cr><lf>\", Mass = {1}", received, mass);
}
else if (fields.Length == 2 && fields[1].Equals("-"))
{
mass = 0;
Masses[balanceNr] = mass;
msrmntState = MsrmntState.Valid;
log.InfoFormat("Balance response = \"{0}<cr><lf>\", Mass = {1}", received, mass);
}
else
{
msrmntState = MsrmntState.Failed;
log.WarnFormat("Balance response = \"{0}<cr><lf>\", Overload or and unexpected error !!!", received);
bool b = float.TryParse(fields[1], NumberStyles.AllowDecimalPoint | NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture, out mass);
}
}
else if (fields[0].Equals("TB")) /// Taring
{
if (fields.Length >= 3 &&
float.TryParse(fields[1],
NumberStyles.AllowDecimalPoint | NumberStyles.AllowLeadingSign,
CultureInfo.InvariantCulture,
out mass))
{
if (fields[2].Equals("g")) mass /= 1000.0f;
if (fields[2].Equals("t")) mass *= 1000.0f;
msrmntState = MsrmntState.Valid;
log.InfoFormat("Balance response = \"{0}<cr><lf>\", Tara = {1}", received, mass);
}
else
{
msrmntState = MsrmntState.Failed;
log.WarnFormat("Balance response = \"{0}<cr><lf>\", Overload or and unexpected error !!!", received);
}
}
else
{
msrmntState = MsrmntState.Failed;
log.WarnFormat("Balance response = \"{0}<cr><lf>\", Unexpected error !!!", received);
}
}
}
/// <summary>Run this device</summary>
public void RunDeviceAfter()
{
}
/// <summary>Stop this device</summary>
public void StopDevice()
{
if (serialPort != null) serialPort.Close();
}
/// <summary>
/// Events: BalanceDone, Error
/// </summary>
/// <param name="result">Reference to a variable for 'tara' in kg</param>
/// <returns>TaringOp instance reference casted to IOperaton</returns>
public IOperation TaringOp(ref FloatBox tara)
{
return new TaringOp(this, ref tara);
}
/// <summary>
/// Events: BalanceDone, Error
/// </summary>
/// <param name="result">Reference to a variable for the measured mass in kg</param>
/// <returns>ReadMassOp instance reference casted to IOperaton</returns>
public IOperation ReadMassOp(ref FloatBox mass)
{
return new ReadMassOp(this, ref mass);
}
/// <summary>
/// Events: BalanceDone, Error
/// </summary>
/// <param name="result">Reference to a variable for the measured mass in kg</param>
/// <param name="readingsCount">Required mass readings count (>= 3)</param>
/// <returns>ReadMassAverageOp instance reference casted to IOperaton</returns>
public IOperation ReadStableMassOp(ref FloatBox mass, int readingsCount)
{
return new ReadStableMassOp(this, ref mass, readingsCount);
}
}
}
@@ -0,0 +1,41 @@
using System.Collections.Generic;
using TBF.BenchControl.Generic;
namespace TBF.BenchControl.MettlerToledo
{
public class BalanceFactory : IComponentFactory
{
public string ClassName { get { return "MettlerToledo Balance"; } }
public bool HasProcedureParams { get { return false; } }
public bool HasTestParams { get { return false; } }
public IParamsProvider GetTestParams(Entities.ComponentTest testParams) { return null; }
public IParamsProvider GetProcedureParams(Entities.ComponentProcedure procedureParams) { return null; }
/// <summary>Max. number of components of this class in the system</summary>
public int MaxCount { get { return 5; } }
public IComponentCfg DefaultConfig(IList<Entities.Component> components)
{
return new BalanceCfg(this, "Balance1", 3, 2400, System.IO.Ports.Parity.Even, 7,
System.IO.Ports.StopBits.One, System.IO.Ports.Handshake.XOnXOff,
200); // kg
}
public IComponentCfgCtrl CreateCfgCtrl()
{
return new BalanceCfgCtrl();
}
public IComponent ComponentFromCmpntCfg(IComponentCfg config, IList<Generic.IComponent> components)
{
return new BalanceDev((BalanceCfg)config, components);
}
public IComponentCfg CmpntCfgFromCmpntEntity(Entities.Component component)
{
return MettlerToledo.BalanceCfg.CreateFromDbEntity(component, this);
}
public void ResetStaticProperties() { BalanceDev.ResetStaticProperties(); }
}
}
@@ -0,0 +1,264 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using System.IO.Ports;
using log4net;
using TBF.BenchControl.Generic;
namespace TBF.BenchControl.MettlerToledo
{
/// <summary>
/// Mettler Toledo ICS4_5 Weighting terminal connected via serial interface (RS232)
/// </summary>
/// <note>
/// Implemented and tested on 15.10.2013 by Milan Hanajik
/// </note>
public class BalanceNewDev : BalanceDev, IComponent, IDevice, GenericDevices.IBalance2
{
/// <summary>
/// Info: StartMassMeasurement() and "Balnce response = .., Mass = ..."
/// Warn: Start measurement when busy is true
/// </summary>
private static readonly ILog log = LogManager.GetLogger(typeof(BalanceNewDev));
public override string ToString() { return string.Format("Mettler-Toledo Balance with SN"); }
public static void ResetStaticProperties() { }
/// <summary>Serial number after GetSerialNumber() when MsrmntState == MsrmntState.Valid</summary>
public string SerialNumber
{
get { return serialNumber; }
}
string serialNumber;
public BalanceNewDev(BalanceCfg cfg, IList<Generic.IComponent> components)
: base(cfg, components)
{
}
/// <summary>
/// Get the serial number
/// </summary>
public void GetSerialNumber()
{
if (balanceCfg.DebugLevel == Entities.DebugMode.Simulate) return;
if (msrmntState == MsrmntState.Busy)
{
log.Warn("GetSerialNumber() returns without getting the s/n because measurementState == MeasurementState.Busy");
return;
}
log.Info("GetSerialNumber()");
msrmntState = MsrmntState.Busy;
stringBuilder.Clear();
serialPort.Write("I4\r\n");
}
/// <summary>
/// Parse characters received from the serial port
/// </summary>
public override void RunDeviceBefore()
{
if (balanceCfg.DebugLevel == Entities.DebugMode.Simulate)
{
mass = GetSimMass(balanceNr);
Masses[balanceNr] = mass;
serialNumber = "1234567890";
msrmntState = MsrmntState.Valid;
msrmntTimeStamp = StateMachine.CurrentTime;
return;
}
log.Debug("RunDevice()");
if (base.msrmntState != MsrmntState.Busy) return; /// No measurement in progress
string justReceived = serialPort.ReadExisting();
if (justReceived != null && justReceived.Length > 0)
{
log.Debug("RunDevice() received " + justReceived);
stringBuilder.Append(justReceived);
if (stringBuilder.ToString().EndsWith("\r\n"))
{
msrmntTimeStamp = StateMachine.CurrentTime;
string received = stringBuilder.ToString();
while (true)
{
string tmp = received.Replace(" ", " ");
if (tmp.Length == received.Length) break;
received = tmp;
}
string[] fields = received.Substring(0, received.Length - 2).Split(new char[] { ' ' });
if (fields.Length < 2)
{
msrmntState = MsrmntState.Failed;
log.WarnFormat("Balance response = {0}, Unexpected error !!!",
received.Replace("\r", "<cr>").Replace("\n", "<lf>"));
return;
}
if (fields[0].Equals("I4")) /// Serial number
{
if (fields.Length == 3 && fields[1].Equals("A") && fields[2].Length >= 3)
{
serialNumber = fields[2].Substring(1, fields[2].Length - 2);
msrmntState = MsrmntState.Valid;
log.InfoFormat("Balance response = {0}, s/n = {1}",
received.Replace("\r", "<cr>").Replace("\n", "<lf>"), serialNumber);
}
else
{
msrmntState = MsrmntState.Failed;
log.WarnFormat("Balance response = {0}, error !!!",
received.Replace("\r", "<cr>").Replace("\n", "<lf>"));
}
}
else if (fields[0].Equals("Z")) /// Zero when stable
{
if (fields.Length == 2 && fields[1].Equals("A"))
{
mass = 0;
Masses[balanceNr] = mass;
msrmntState = MsrmntState.Valid;
log.InfoFormat("Balance response = {0}",
received.Replace("\r", "<cr>").Replace("\n", "<lf>"));
}
else
{
msrmntState = MsrmntState.Failed;
log.WarnFormat("Balance response = \"{0}\", error !!!",
received.Replace("\r", "<cr>").Replace("\n", "<lf>"));
}
}
else if (fields[0].Equals("S")) /// Stable (field[1] == "S") or dynamic (field[1] == "D") mass measurement
{
if (fields.Length == 4 && fields[1].Equals("S") &&
float.TryParse(fields[2], NumberStyles.AllowDecimalPoint | NumberStyles.AllowLeadingSign | NumberStyles.AllowLeadingWhite,
CultureInfo.InvariantCulture, out mass))
{
if (fields[3].Equals("g")) mass /= 1000.0f;
if (fields[3].Equals("t")) mass *= 1000.0f;
Masses[balanceNr] = mass;
msrmntState = MsrmntState.Valid;
log.InfoFormat("Balance response = {0}, Mass = {1}",
received.Replace("\r", "<cr>").Replace("\n", "<lf>"), mass);
}
else if (fields.Length == 4 && fields[1].Equals("D") &&
float.TryParse(fields[2], NumberStyles.AllowDecimalPoint | NumberStyles.AllowLeadingSign | NumberStyles.AllowLeadingWhite,
CultureInfo.InvariantCulture, out mass))
{
if (fields[3].Equals("g")) mass /= 1000.0f;
if (fields[3].Equals("t")) mass *= 1000.0f;
Masses[balanceNr] = mass;
msrmntState = MsrmntState.Valid;
log.InfoFormat("Balance response = {0}, Mass = {1}",
received.Replace("\r", "<cr>").Replace("\n", "<lf>"), mass);
}
else if (fields.Length == 2 && fields[1].Equals("-"))
{
mass = 0;
Masses[balanceNr] = mass;
msrmntState = MsrmntState.Valid;
log.InfoFormat("Balance response = {0}, Mass = {1}",
received.Replace("\r", "<cr>").Replace("\n", "<lf>"), mass);
}
else if (fields.Length >= 2 && fields[1].Equals("I"))
{
mass = balanceCfg.Capacity;
Masses[balanceNr] = mass;
msrmntState = MsrmntState.Overload;
log.InfoFormat("Balance response = {0}, Overload",
received.Replace("\r", "<cr>").Replace("\n", "<lf>"), mass);
}
else
{
msrmntState = MsrmntState.Failed;
log.WarnFormat("Balance response = \"{0}\", Overload or and unexpected error !!!",
received.Replace("\r", "<cr>").Replace("\n", "<lf>"));
}
}
else if (fields[0].Equals("T")) /// Taring
{
if (fields.Length == 4 && fields[1].Equals("S") &&
float.TryParse(fields[2], NumberStyles.AllowDecimalPoint | NumberStyles.AllowLeadingSign | NumberStyles.AllowLeadingWhite,
CultureInfo.InvariantCulture, out mass))
{
if (fields[3].Equals("g")) mass /= 1000.0f;
if (fields[3].Equals("t")) mass *= 1000.0f;
msrmntState = MsrmntState.Valid;
log.InfoFormat("Balance response = {0}, Mass = {1}",
received.Replace("\r", "<cr>").Replace("\n", "<lf>"), mass);
}
else if (fields.Length >= 2 && fields[1].Equals("I"))
{
mass = mass = balanceCfg.Capacity;
msrmntState = MsrmntState.Overload;
log.InfoFormat("Balance response = {0}, Overload",
received.Replace("\r", "<cr>").Replace("\n", "<lf>"), mass);
}
else
{
msrmntState = MsrmntState.Failed;
log.WarnFormat("Balance response = \"{0}\", Overload or and unexpected error !!!",
received.Replace("\r", "<cr>").Replace("\n", "<lf>"));
}
}
else if (fields[0].Equals("U"))
{
if (fields.Length == 2 && fields[1].Equals("A"))
{
msrmntState = MsrmntState.Valid;
log.InfoFormat("Balance response = \"{0}\"",
received.Replace("\r", "<cr>").Replace("\n", "<lf>"));
}
else
{
msrmntState = MsrmntState.Failed;
log.WarnFormat("Balance response = \"{0}\", Unexpected error !!!",
received.Replace("\r", "<cr>").Replace("\n", "<lf>"));
}
}
else if (fields[0].Equals("SI")) /// "SI I<cr><lf>" received in case of overload -> empty the tank
{
if (fields.Length >= 2 && fields[1].Equals("I"))
{
mass = balanceCfg.Capacity;
Masses[balanceNr] = mass;
msrmntState = MsrmntState.Valid;
//msrmntState = MsrmntState.Overload;
log.WarnFormat("Balance response = \"{0}\", Overload.",
received.Replace("\r", "<cr>").Replace("\n", "<lf>"));
}
}
}
}
}
/// <summary>
/// Events: BalanceDone, Error
/// </summary>
/// <param name="serialNumber">Reference to the serialNumber</param>
/// <returns>GetBalanceSNOp instance reference casted to IOperaton</returns>
public IOperation GetBalanceSNOp(ref string serialNumber)
{
return new GetBalanceSNOp(this, ref serialNumber);
}
/// <summary>
/// Events: BalanceDone, Error
/// </summary>
/// <param name="units"></param>
/// <returns>SetUnitsOp instance reference casted to IOperaton</returns>
public IOperation SetUnitsOp(Units units)
{
return new SetUnitsOp(this, units);
}
}
}
@@ -0,0 +1,41 @@
using System.Collections.Generic;
using TBF.BenchControl.Generic;
namespace TBF.BenchControl.MettlerToledo
{
public class BalanceNewFactory : IComponentFactory
{
public string ClassName { get { return "MettlerToledoBalanceSN"; } }
public bool HasProcedureParams { get { return false; } }
public bool HasTestParams { get { return false; } }
public IParamsProvider GetTestParams(Entities.ComponentTest testParams) { return null; }
public IParamsProvider GetProcedureParams(Entities.ComponentProcedure procedureParams) { return null; }
/// <summary>Max. number of components of this class in the system</summary>
public int MaxCount { get { return 5; } }
public IComponentCfg DefaultConfig(IList<Entities.Component> components)
{
return new BalanceCfg(this, "Balance1", 3, 2400, System.IO.Ports.Parity.Even, 7,
System.IO.Ports.StopBits.One, System.IO.Ports.Handshake.XOnXOff,
200); // kg
}
public IComponentCfgCtrl CreateCfgCtrl()
{
return new BalanceCfgCtrl();
}
public IComponent ComponentFromCmpntCfg(IComponentCfg config, IList<Generic.IComponent> components)
{
return new BalanceNewDev((BalanceCfg)config, components);
}
public IComponentCfg CmpntCfgFromCmpntEntity(Entities.Component component)
{
return MettlerToledo.BalanceCfg.CreateFromDbEntity(component, this);
}
public void ResetStaticProperties() { BalanceNewDev.ResetStaticProperties(); }
}
}
@@ -0,0 +1,59 @@
using System;
using log4net;
namespace TBF.BenchControl.MettlerToledo
{
public class GetBalanceSNOp : IOperation
{
private static readonly ILog log = LogManager.GetLogger(typeof(GetBalanceSNOp));
public override string ToString() { return string.Format("GetBalanceSNOp(.,.)"); }
/// Set by the constructor
BalanceNewDev balanceDev;
string serialNumber;
/// <summary>
/// Events: BalanceDone, Error
/// </summary>
/// <param name="balanceDev">Balance device instance</param>
/// <param name="serialNumber">Reference to the serialNumber</param>
public GetBalanceSNOp(BalanceNewDev balanceDev, ref string serialNumber)
{
if (balanceDev == null) throw new ArgumentNullException("balanceDev");
this.balanceDev = balanceDev;
this.serialNumber = serialNumber;
log.Debug(this.ToString());
}
/// <summary>Start this operation</summary>
public void Start()
{
log.Debug("Start()");
balanceDev.GetSerialNumber();
}
/// <summary>Run this operation</summary>
/// <returns>
/// Event.None
/// Event.BalanceDone
/// </returns>
public Event Run()
{
if (balanceDev.MsrmntState == MsrmntState.Valid)
{
serialNumber = balanceDev.SerialNumber;
return Event.BalanceDone; /// S/N read successful
}
if (balanceDev.MsrmntState == MsrmntState.Failed) return Event.Error; /// S/N read failed
return Event.None; /// No result yet
}
/// <summary>Stop this operation</summary>
public void Stop()
{
log.Debug("Stop()");
}
}
}
@@ -0,0 +1,68 @@
using System;
using log4net;
namespace TBF.BenchControl.MettlerToledo
{
public class ReadMassOp : IOperation
{
private static readonly ILog log = LogManager.GetLogger(typeof(ReadMassOp));
public override string ToString() { return string.Format("ReadMassOp(.,.)"); }
bool done;
/// Set by the constructor
BalanceDev balanceDev;
FloatBox result;
/// <summary>
/// Events: BalanceDone, Error
/// </summary>
/// <param name="balanceDev">Balance device instance</param>
/// <param name="requiredReadingsCount">Required mass readings count (>= 3)</param>
/// <param name="result">Reference to the measured mass in kg</param>
public ReadMassOp(BalanceDev balanceDev, ref FloatBox result)
{
if (balanceDev == null) throw new ArgumentNullException("balanceDev");
this.balanceDev = balanceDev;
this.result = result;
log.Debug(this.ToString());
}
/// <summary>Start this operation</summary>
public void Start()
{
done = false;
balanceDev.GetImmediateMassMeasurement();
}
/// <summary>Run this operation</summary>
/// <returns>
/// Event.None
/// Event.BalanceDone
/// Event.Error . . . . . Current.Tick == null
/// </returns>
public Event Run()
{
if (done) return Event.BalanceDone; /// Mass has already been read
if (balanceDev.MsrmntState == MsrmntState.Busy) return Event.None;
if (balanceDev.MsrmntState == MsrmntState.Valid)
{
result.F = balanceDev.Mass;
done = true;
return Event.BalanceDone; /// Mass read OK
}
balanceDev.GetImmediateMassMeasurement(); /// Failed -> repeat the measurement
return Event.None;
}
/// <summary>Stop this operation</summary>
public void Stop()
{
}
}
}
@@ -0,0 +1,60 @@
using System;
using log4net;
namespace TBF.BenchControl.MettlerToledo
{
public class ReadMassesOp : IOperation
{
private static readonly ILog log = LogManager.GetLogger(typeof(ReadMassesOp));
public override string ToString() { return string.Format("ReadMassesOp()"); }
bool done;
/// <summary>
/// Events: BalanceDone, Error
/// </summary>
/// <param name="balanceDev">Balance device instance</param>
/// <param name="requiredReadingsCount">Required mass readings count (>= 3)</param>
/// <param name="result">Reference to the measured mass in kg</param>
public ReadMassesOp()
{
log.Debug(this.ToString());
}
/// <summary>Start this operation</summary>
public void Start()
{
done = false;
for (int i = 0; i < BalanceDev.BalancesCount; i++)
{
BalanceDev.Balances[i].GetImmediateMassMeasurement();
}
}
/// <summary>Run this operation</summary>
/// <returns>
/// Event.None
/// Event.BalanceDone
/// Event.Error . . . . . Current.Tick == null
/// </returns>
public Event Run()
{
if (done) return Event.BalanceDone; /// Mass has already been read
for (int i = 0; i < BalanceDev.BalancesCount; i++)
{
if (BalanceDev.Balances[i].MsrmntState == MsrmntState.Busy)
{
return Event.None;
}
}
done = true;
return Event.BalanceDone;
}
/// <summary>Stop this operation</summary>
public void Stop()
{
}
}
}
@@ -0,0 +1,88 @@
using System;
using log4net;
namespace TBF.BenchControl.MettlerToledo
{
/// <summary>
/// Operation to read more mass values and average them to obtain a more accurate result.
/// </summary>
public class ReadStableMassOp : IOperation
{
private static readonly ILog log = LogManager.GetLogger(typeof(ReadStableMassOp));
public override string ToString() { return string.Format("ReadStableMassOp(.,{0},.)", totalReadingsCount); }
/// Operation specific
float[] massReadings;
int currentReadingsCount;
/// Set by the constructor
BalanceDev balanceDev;
int totalReadingsCount;
FloatBox result;
/// <summary>
/// Events: BalanceDone, Error
/// </summary>
/// <param name="balanceDev">Balance device instance</param>
/// <param name="result">Reference to the measured mass in kg</param>
/// <param name="readingsCount">Required mass readings count (>= 3)</param>
public ReadStableMassOp(BalanceDev balanceDev, ref FloatBox result, int readingsCount)
{
if (balanceDev == null) throw new ArgumentNullException("balanceDev");
this.balanceDev = balanceDev;
if (readingsCount < 3) throw new ArgumentOutOfRangeException("requiredReadingsCount");
this.totalReadingsCount = readingsCount;
this.result = result;
log.Debug(this.ToString());
}
/// <summary>Start this operation</summary>
public void Start()
{
currentReadingsCount = 0;
massReadings = new float[totalReadingsCount];
balanceDev.GetStableMassMeasurement();
}
/// <summary>Run this operation</summary>
/// <returns>
/// Event.None
/// Event.BalanceDone
/// Event.Error . . . . . Current.Tick == null
/// </returns>
public Event Run()
{
if (currentReadingsCount >= totalReadingsCount) return Event.BalanceDone; /// Mass has already been calculated
if (balanceDev.MsrmntState == MsrmntState.Busy) return Event.None;
if (balanceDev.MsrmntState == MsrmntState.Valid)
{
massReadings[currentReadingsCount++] = balanceDev.Mass;
if (currentReadingsCount == totalReadingsCount)
{
/// calculate the average
float calcMass = 0;
Array.Sort(massReadings);
for (int i = 1; i < totalReadingsCount - 1; i++) calcMass += massReadings[i];
calcMass = (calcMass / (totalReadingsCount - 2));
result.F = calcMass;
return Event.BalanceDone; /// Mass has just been calculated
}
}
balanceDev.GetStableMassMeasurement();
return Event.None;
}
/// <summary>Stop this operation</summary>
public void Stop()
{
}
}
}
@@ -0,0 +1,58 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using log4net;
namespace TBF.BenchControl.MettlerToledo
{
public class SetUnitsOp : IOperation
{
private static readonly ILog log = LogManager.GetLogger(typeof(SetUnitsOp));
public override string ToString() { return string.Format("SetUnitsOp({0})", units); }
/// Set by the constructor
BalanceDev balanceDev;
BalanceDev.Units units;
/// <summary>
/// Events: BalanceDone, Error
/// </summary>
/// <param name="balanceDev">Balance device instance</param>
/// <param name="result">Reference to the serialNumber</param>
public SetUnitsOp(BalanceDev balanceDev, BalanceDev.Units units)
{
if (balanceDev == null) throw new ArgumentNullException("balanceDev");
this.balanceDev = balanceDev;
this.units = units;
log.Debug(this.ToString());
}
/// <summary>Start this operation</summary>
public void Start()
{
log.Debug("Start()");
balanceDev.SetUnits(units);
}
/// <summary>Run this operation</summary>
/// <returns>
/// Event.None
/// Event.BalanceDone
/// </returns>
public Event Run()
{
if (balanceDev.MsrmntState == MsrmntState.Valid) return Event.BalanceDone; /// Units set
if (balanceDev.MsrmntState == MsrmntState.Failed) return Event.Error; /// Failed
return Event.None; /// No result yet
}
/// <summary>Stop this operation</summary>
public void Stop()
{
log.Debug("Stop()");
}
}
}
@@ -0,0 +1,74 @@
using System;
using log4net;
namespace TBF.BenchControl.MettlerToledo
{
public class TaringOp : IOperation
{
private static readonly ILog log = LogManager.GetLogger(typeof(TaringOp));
public override string ToString() { return string.Format("TaringOp(.,.)"); }
bool done;
/// Set by the constructor
BalanceDev balanceDev;
FloatBox tara;
/// <summary>
/// Events: BalanceDone, Error
/// </summary>
/// <param name="balanceDev">Balance device instance</param>
/// <param name="result">Reference to variable for 'tara' in kg</param>
public TaringOp(BalanceDev balanceDev, ref FloatBox tara)
{
if (balanceDev == null) throw new ArgumentNullException("balanceDev");
this.balanceDev = balanceDev;
this.tara = tara;
log.Debug(this.ToString());
}
/// <summary>Start this operation</summary>
public void Start()
{
done = false;
balanceDev.Taring();
}
/// <summary>Run this operation</summary>
/// <returns>
/// Event.None
/// Event.BalanceDone
/// Event.Error . . . . . Current.Tick == null
/// </returns>
public Event Run()
{
if (done) return Event.BalanceDone; /// Taring has been done already
if (balanceDev.MsrmntState == MsrmntState.Busy) return Event.None;
if (balanceDev.MsrmntState == MsrmntState.Overload)
{
tara.F = balanceDev.Capacity;
done = true;
return Event.BalanceOverload;
}
if (balanceDev.MsrmntState == MsrmntState.Valid)
{
tara.F = balanceDev.Mass;
done = true;
return Event.BalanceDone; /// Taring completed
}
balanceDev.Taring(); /// Failed -> repeat taring
return Event.None;
}
/// <summary>Stop this operation</summary>
public void Stop()
{
}
}
}