Compare commits

..
Author SHA1 Message Date
Milan Hanajik 128734de01 Reconfigured for ROMA_200 2020-11-23 13:01:28 +01:00
1999 changed files with 40701 additions and 110626 deletions
-28
View File
@@ -20,16 +20,12 @@ EventViewer/bin/
EventViewer/obj/
Events/bin/
Events/obj/
FeatureVectorCalculator/bin/
FeatureVectorCalculator/obj/
GemCard/bin
GemCard/obj
GenCode128/bin
GenCode128/obj
GraphLib/bin
GraphLib/obj
MergeResultsDBs/bin
MergeResultsDBs/obj
TracingDB/bin
TracingDB/obj
ResetBatchNr/bin
@@ -40,8 +36,6 @@ Results/bin/
Results/obj/
ResultsBrowser/bin/
ResultsBrowser/obj/
ResultsParser/bin/
ResultsParser/obj/
Statistics/bin/
Statistics/obj/
TBF/bin/
@@ -54,28 +48,6 @@ Users/bin/
Users/obj/
UserManagement/bin/
UserManagement/obj/
DataMatrix4Net/bin/
DataMatrix4Net/obj/
GenericTest/bin/
GenericTest/obj/
LabelPrinting/bin/
LabelPrinting/obj/
OrderManagement/bin/
OrderManagement/obj/
ProductionTracing/bin/
ProductionTracing/obj/
RecordProcessing/bin/
RecordProcessing/obj/
S640TestApp/bin/
S640TestApp/obj/
SchematicDrawing/bin/
SchematicDrawing/obj/
SharedDatabase/bin/
SharedDatabase/obj/
WorkflowConfigurator/bin/
WorkflowConfigurator/obj/
Workplace/bin/
Workplace/obj/
.vs/
*.suo
*.bak
-37
View File
@@ -1,37 +0,0 @@
///
/// Copyright (c) 2021 Sensus Slovensko a.s.
///
using System;
using System.Threading;
namespace Common
{
public class BackgroundBeep
{
static Thread beepThread;
static AutoResetEvent signalBeep;
static BackgroundBeep()
{
signalBeep = new AutoResetEvent(false);
beepThread = new Thread(() =>
{
while (true)
{
signalBeep.WaitOne(); /// waits for an event
Console.Beep(500, 400); /// frequency (Hz), duration (ms)
}
}, 1);
beepThread.IsBackground = true;
beepThread.Start();
}
/// <summary>
/// Invokes one beep in a separate thread (non-blocking function)
/// </summary>
public static void Beep()
{
signalBeep.Set();
}
}
}
+7 -41
View File
@@ -41,57 +41,23 @@
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="BackgroundBeep.cs" />
<Compile Include="Const.cs" />
<Compile Include="DatabaseSettings.cs" />
<Compile Include="DBSettings.cs" />
<Compile Include="Enums.cs" />
<Compile Include="Forms\ListViewEx.cs">
<SubType>Component</SubType>
</Compile>
<Compile Include="Forms\ListViewExtensions.cs" />
<Compile Include="Forms\LviDateTimeColumnComparer.cs" />
<Compile Include="Forms\LviIntColumnComparer.cs" />
<Compile Include="Forms\LviNameSurnameColumnComparer.cs" />
<Compile Include="Forms\LviTextColumnComparer.cs" />
<Compile Include="Forms\MessageEventArgs.cs" />
<Compile Include="Forms\ModelessForm.cs">
<SubType>Form</SubType>
</Compile>
<Compile Include="Forms\ModelessForm.designer.cs">
<DependentUpon>ModelessForm.cs</DependentUpon>
</Compile>
<Compile Include="IMeasurementCorrection.cs" />
<Compile Include="IOrderInfo.cs" />
<Compile Include="IParamsProvider.cs" />
<Compile Include="IUncertainty.cs" />
<Compile Include="IUser.cs" />
<Compile Include="Printers\PrintersCommon.cs">
<SubType>Component</SubType>
</Compile>
<Compile Include="QuitAppException.cs" />
<Compile Include="StatisticalMetrics.cs" />
<Compile Include="Iperl\OptoTelegramRaw.cs" />
<Compile Include="SerializableDictionary.cs" />
<Compile Include="Telegram.cs" />
<Compile Include="UIControls\CoolButtonCtrl.cs">
<SubType>UserControl</SubType>
</Compile>
<Compile Include="UIControls\CoolButtonCtrl.Designer.cs">
<DependentUpon>CoolButtonCtrl.cs</DependentUpon>
</Compile>
<Compile Include="UIControls\LviDateTimeColumnComparer.cs" />
<Compile Include="UIControls\RoundedRectangle.cs" />
<Compile Include="Units.cs" />
<Compile Include="Utils.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="Forms\ListViewEx.resx">
<DependentUpon>ListViewEx.cs</DependentUpon>
</EmbeddedResource>
<EmbeddedResource Include="Forms\ModelessForm.resx">
<DependentUpon>ModelessForm.cs</DependentUpon>
</EmbeddedResource>
<Compile Include="UIControls\ListViewEx.cs">
<SubType>Component</SubType>
</Compile>
<Compile Include="UIControls\ListViewExtensions.cs" />
<Compile Include="UIControls\LviIntColumnComparer.cs" />
<Compile Include="UIControls\LviTextColumnComparer.cs" />
</ItemGroup>
<ItemGroup />
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
-12
View File
@@ -1,12 +0,0 @@
///
/// Copyright (c) 2023 Sensus Slovensko a.s.
///
using System;
namespace Common
{
public static class Const
{
public const string MySqlConnectTimeoutSec = "120";
}
}
-121
View File
@@ -1,121 +0,0 @@
///
/// Copyright (c) 2013-2020 Sensus Slovensko a.s.
///
using System;
using System.Text;
using System.Xml.Serialization;
namespace Common
{
/// <summary>
/// Test bench database settings, contains bench name and settings od several databases
/// </summary>
public class DatabaseSettings : ICloneable, IComparable
{
// Public fields
public string BenchName;
public bool IsRealBench;
public DBSettings ProceduresDBSettings; /// Configuration database settings
public DBSettings WaterMetersDBSettings; /// Results database settings
public DBSettings EventsDBSettings; /// Events database settings
public DBSettings UsersDBSettings; /// Shared configuration database settings
// Constructor
public DatabaseSettings()
{
BenchName = String.Empty; /// Empty string (avoid null)
IsRealBench = false;
ProceduresDBSettings = new DBSettings(DBType.MySql, string.Empty);
WaterMetersDBSettings = new DBSettings(DBType.MySql, string.Empty);
EventsDBSettings = new DBSettings(DBType.MySql, string.Empty);
UsersDBSettings = new DBSettings(DBType.MySql, string.Empty);
}
public object Clone()
{
DatabaseSettings result = new DatabaseSettings();
result.BenchName = BenchName;
result.IsRealBench = IsRealBench;
result.ProceduresDBSettings = (DBSettings)ProceduresDBSettings.Clone();
result.WaterMetersDBSettings = (DBSettings)WaterMetersDBSettings.Clone();
result.EventsDBSettings = (DBSettings)EventsDBSettings.Clone();
result.UsersDBSettings = (DBSettings)UsersDBSettings.Clone();
return result;
}
public int CompareTo(object dbs2)
{
if (!(dbs2 is DatabaseSettings)) return 0;
return String.Compare(BenchName, (dbs2 as DatabaseSettings).BenchName);
}
/// <summary>
/// Extract and return a DB server from a MySQL connection string.
/// </summary>
public static string GetDBServer(string connectionString)
{
return GetFromConnectionString(connectionString, new string[] { "SERVER=" });
}
/// <summary>
/// Extract and return a DB name from a MySQL connection string.
/// </summary>
public static string GetDBName(string connectionString)
{
return GetFromConnectionString(connectionString, new string[] { "DATABASE=" });
}
/// <summary>
/// Extract and return a username from a MySQL connection string
/// </summary>
public static string GetDBUser(string connectionString)
{
return GetFromConnectionString(connectionString, new string[] { "USER=", "UID=" });
}
/// <summary>
/// Extract and return a password from a MySQL connection string
/// </summary>
public static string GetDBPassword(string connectionString)
{
return GetFromConnectionString(connectionString, new string[] { "PASSWORD=", "PWD=" });
}
/// <summary>
/// Extract and return an element of a MySQL connection string
/// (a host, a database, a user name or a password).
/// Return an empty string on any error.
/// </summary>
public static string GetFromConnectionString(string connectionString, string[] patterns)
{
foreach (var pattern in patterns)
{
int startIx = connectionString.IndexOf(pattern);
if (startIx >= 0)
{
/// pattern found, extract the subsequent element
startIx += pattern.Length;
int endIx = connectionString.IndexOf(';', startIx);
return (endIx > 0) ? connectionString.Substring(startIx, endIx - startIx) : string.Empty;
}
}
/// pattern NOT found
return string.Empty;
}
public override string ToString()
{
return string.Format("{0} config={1} results={2} events={3} users={4}",
BenchName,
ProceduresDBSettings.ConnectionString,
WaterMetersDBSettings.ConnectionString,
EventsDBSettings.ConnectionString,
UsersDBSettings.ConnectionString);
}
}
}
-10
View File
@@ -1,10 +0,0 @@
using System;
namespace Common.Forms
{
public class MessageEventArgs : EventArgs
{
public string Message;
public MessageEventArgs(string message) { Message = message; }
}
}
-63
View File
@@ -1,63 +0,0 @@
namespace Common.Forms
{
partial class ModelessForm
{
/// <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 Windows Form 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.label1 = new System.Windows.Forms.Label();
this.SuspendLayout();
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(47, 29);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(35, 13);
this.label1.TabIndex = 0;
this.label1.Text = "label1";
//
// ModelessForm
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(191, 56);
this.Controls.Add(this.label1);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.Name = "ModelessForm";
this.SizeGripStyle = System.Windows.Forms.SizeGripStyle.Hide;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "ModelessForm";
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Label label1;
}
}
-79
View File
@@ -1,79 +0,0 @@
///
/// Copyright (c) 2021-2023 Sensus Slovensko a.s.
///
using System;
using System.Drawing;
using System.Windows.Forms;
namespace Common.Forms
{
public partial class ModelessForm : Form
{
/// <summary>
/// Constructor to be used by the application
/// </summary>
/// <param name="title">Window title</param>
/// <param name="message">Displayed message</param>
public ModelessForm(string message, int backArgb = 0, int textArgb = 0, Font textFont = null, string title = null)
{
InitializeComponent();
ControlBox = false;
label1.Text = (message != null) ? message : "Please wait";
BackColor = (backArgb != 0) ? Color.FromArgb(backArgb) : Color.LightGreen;
ForeColor = (textArgb != 0) ? Color.FromArgb(textArgb) : Color.Black;
label1.Font = (textFont != null) ? textFont : new Font("Arial", 14, FontStyle.Regular);
Text = (title != null) ? title : string.Empty;
float textWidth = Graphics.FromImage(new Bitmap(1, 1)).MeasureString(label1.Text, label1.Font).Width;
float textHeight = Graphics.FromImage(new Bitmap(1, 1)).MeasureString(label1.Text, label1.Font).Height;
Width = (int)textWidth + 120; /// Form width calculated from the text width
Height += (int)textHeight; /// Form height calculated from the text height
UpdateMessageHandler += delegate(object sender, MessageEventArgs args)
{
if (InvokeRequired) { Invoke(new EventHandler<MessageEventArgs>(OnUpdateMessage), sender, args); }
else OnUpdateMessage(sender, args);
};
CloseFormHandler += delegate(object sender, EventArgs args)
{
if (InvokeRequired) { Invoke(new EventHandler<EventArgs>(OnCloseForm), sender, args); }
else OnCloseForm(sender, args);
};
}
/// <summary>
/// Called from the state machine when an operation forces a modeless dialog close.
/// </summary>
public void UpdateMessage(MessageEventArgs args)
{
if (UpdateMessageHandler == null) return;
try { UpdateMessageHandler(null, args); }
catch (Exception) { }
}
public event EventHandler<MessageEventArgs> UpdateMessageHandler;
void OnUpdateMessage(object sender, MessageEventArgs args)
{
if (args != null && args.Message != null) label1.Text = args.Message;
}
/// <summary>
/// Called from the state machine when an operation forces a modeless dialog close.
/// </summary>
public void CloseForm()
{
if (CloseFormHandler == null) return;
try { CloseFormHandler(null, null); }
catch (Exception) { }
}
public event EventHandler<EventArgs> CloseFormHandler;
void OnCloseForm(object sender, EventArgs args)
{
DialogResult = DialogResult.Cancel;
Close();
}
}
}
-352
View File
@@ -1,352 +0,0 @@
///
/// Copyright (c) 2013-2021 Sensus Slovensko a.s.
///
using System;
using System.Collections.Generic;
using log4net;
namespace Common
{
public static class Formulas
{
private static readonly ILog log = LogManager.GetLogger(typeof(Formulas));
///
/// Wrappers
///
public static double RealDensity() { return GlobalData.SampleDensity; }
public static double AtTemperature() { return GlobalData.SampleTemp; }
public static double Buoyancy() { return GlobalData.Buoyancy; }
/// Private tables with coeficients to calculate specific enthalpy
static readonly int[] Ii;
static readonly int[] Ji;
static readonly double[] ni;
/// Private table with coeficients to calculate temperature of a platinum thermometer
static readonly double[] Di;
/// <summary>
/// Constructor
/// </summary>
static Formulas()
{
///
/// Initialize tables to calculate specific enthalpies
///
Ii = new int[34] { 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 8, 8, 21, 23, 29, 30, 31, 32 };
Ji = new int[34] { -2, -1, 0, 1, 2, 3, 4, 5, -9, -7, -1, 0, 1, 3, -3, 0, 1, 3, 17, -4, 0, 6, -5, -2, 10, -8, -11, -6, -29, -31, -38, -39, -40, -41 };
ni = new double[34] {
0.14632971213167, /// 1
-0.84548187169114, /// 2
-0.37563603672040E1, /// 3
0.33855169168385E1, /// 4
-0.95791963387872, /// 5
0.15772038513228, /// 6
-0.16616417199501E-1, /// 7
0.81214629983568E-3, /// 8
0.28319080123804E-3, /// 9
-0.60706301565874E-3, /// 10
-0.18990068218419E-1, /// 11
-0.32529748770505E-1, /// 12
-0.21841717175414E-1, /// 13
-0.52838357969930E-4, /// 14
-0.47184321073267E-3, /// 15
-0.30001780793026E-3, /// 16
0.47661393906987E-4, /// 17
-0.44141845330846E-5, /// 18
-0.72694996297594E-15, /// 19
-0.31679644845054E-4, /// 20
-0.28270797985312E-5, /// 21
-0.85205128120103E-9, /// 22
-0.22425281908000E-5, /// 23
-0.65171222895601E-6, /// 24
-0.14341729937924E-12, /// 25
-0.40516996860117E-6, /// 26
-0.12734301741641E-8, /// 27
-0.17424871230634E-9, /// 28
-0.68762131295531E-18, /// 29
0.14478307828521E-19, /// 30
0.26335781662795E-22, /// 31
-0.11947622640071E-22, /// 32
0.18228094581404E-23, /// 33
-0.93537087292458E-25, /// 34
};
///
/// Initialize a table to calculate temperature of a platinum thermometer from resistance
///
Di = new double[]
{
439.932854,
472.418020,
37.684494,
7.472018,
2.920828,
0.005184,
-0.963864,
-0.188732,
0.191203,
0.049025,
};
}
/// <summary>
/// Calculate density of distilled water from temperature
/// </summary>
/// <param name="t">ITS-90 temperature in [°C]</param>
/// <returns>Density in [kg/m3]</returns>
public static double DistilledWaterDensityFromTemp(double t)
{
if (t <= 40)
{
const double c0 = 999.839564;
const double c1 = 0.067998613;
const double c2 = -0.0091101468;
const double c3 = 0.00010058299;
const double c4 = -0.0000011275659;
const double c5 = 6.5985371e-09;
return ((((c5 * t + c4) * t + c3) * t + c2) * t + c1) * t + c0;
}
else
{
const double a0 = 9.9983952E2;
const double a1 = 1.6952577E1;
const double a2 = -7.9905127E-3;
const double a3 = -4.6241757E-5;
const double a4 = 1.0584601E-7;
const double a5 = -2.8103006E-10;
const double b = 1.6887236E-2;
return (((((a5 * t + a4) * t + a3) * t + a2) * t + a1) * t + a0) / (1.0 + b * t);
}
}
/// <summary>
/// Calculate density of distilled water from temperature (obsolete)
/// </summary>
/// <param name="t">IPTS-68 temperature in [°C]</param>
/// <returns>Density in [kg/m3]</returns>
public static double DistilledWaterDensityFromTempIPTS68(double t)
{
const double a0 = 999.842594;
const double a1 = 0.06793952;
const double a2 = -0.009095290;
const double a3 = 0.0001001685;
const double a4 = -0.000001120083;
const double a5 = 6.536332e-09;
return ((((a5 * t + a4) * t + a3) * t + a2) * t + a1) * t + a0;
}
/// <summary>
/// Calculate density by comparing calculated data and data from a certificate
/// </summary>
/// <param name="realDensity">Density from a certificate in [kg/m3]</param>
/// <param name="atTemperature">Temperature from a certificate in [°C]</param>
/// <returns>Density correction in [kg/m3]</returns>
public static double DensityCorrection(double realDensity, double atTemperature)
{
/// Calculated data
double calculatedDensity = DistilledWaterDensityFromTemp(atTemperature);
return realDensity - calculatedDensity;
}
/// <summary>
/// Calculate corrected (real) water density from temperature
/// </summary>
/// <param name="t">Temperature in [°C]</param>
/// <returns>Density in [kg/m3]</returns>
public static double WaterDensityFromTemp(double t)
{
return DistilledWaterDensityFromTemp(t) + DensityCorrection(RealDensity(), AtTemperature());
}
/// <summary>
/// Calculate corrected (real) water density from temperature
/// </summary>
/// <param name="t">Temperature in [°C]</param>
/// <returns>Density in [kg/m3]</returns>
public static double WaterDensityFromTempPress(double temp, double pressure)
{
double x0 = 5.08821E-10;
double x1 = 1.2639418;
double x2 = 0.2660269;
double x3 = 0.3734838;
double x4 = 2.0205242;
double theta = temp / 100.0;
double B = x0 * (((x3 * theta + x2) * theta + x1) * theta + 1) / (1 + x4 * theta);
return WaterDensityFromTemp(temp) * (1 + B * Common.Units.ConvertTo(Common.Unit.Pa, pressure));
}
public static float AirDensityFromAmbientVales(float tempC, float pressureBar, float humiPct)
{
double pressurePa = 100000.0 * (double)pressureBar; /// [Pa]
double tempKelvin = 273.15 + (double)tempC;
double coef1 = 1.2811805 / 10000.0 * tempKelvin * tempKelvin
- 1.950987 / 100.0 * tempKelvin
+ 34.04926034
- 6.353631 * 1000.0 / tempKelvin;
double coef3 = humiPct / 100.0 * System.Math.Exp(coef1) / pressurePa;
double airDensityKgm3 = 0.00348353 * pressurePa * (1.0 - 0.378 * coef3) / tempKelvin; /// kg/m3
return (float)airDensityKgm3;
}
/// <summary>
/// Convert 'pulses' to 'volume', prevent division by zero
/// </summary>
public static double VolumeFromPulses(int pulses, double pulsesPerLiter)
{
if (pulsesPerLiter <= double.Epsilon) return 0;
return Convert.ToDouble(pulses) / pulsesPerLiter;
}
/// <summary>
/// Calculate the error in % from 'measured' and 'true' volume, prevent division by zero
/// </summary>
public static double ErrorFromVolumes(double measuredVolume, double trueVolume)
{
if (trueVolume <= float.Epsilon)
{
if (measuredVolume <= float.Epsilon)
{
log.WarnFormat("ErrorFromVolumes({0},{1}) returns {2}", measuredVolume, trueVolume, -100.0);
return -100.0;
}
log.WarnFormat("ErrorFromVolumes({0},{1}) returns {2}", measuredVolume, trueVolume, 99.0);
return 99.0;
}
double error = 100.0 * (measuredVolume - trueVolume) / trueVolume;
log.InfoFormat("ErrorFromVolumes({0},{1}) returns {2}", measuredVolume, trueVolume, error);
return error;
}
/// <summary>
/// Converts a measurement error to a correction (used when preparing correction tables).
/// </summary>
/// <param name="measuredValue">Measured value (in arbitrary units)</param>
/// <param name="error">Measurement error in %</param>
/// <returns>Correction in the same units as the measured value</returns>
public static double CorrectionFromError(double measuredValue, double error)
{
double trueValue = measuredValue / (1 + error/100);
double correction = trueValue - measuredValue;
return correction;
}
/// <summary>
/// Calculates the heat coefficient for water
/// </summary>
/// <param name="pressure">Pressure [bar]</param>
/// <param name="T_in">Inlet temperature [°C]</param>
/// <param name="T_out">Outlet temperature [°C]</param>
/// <param name="flowMeasuredAtInlet">true = flow measured @inlet, false = flow measured @outlet</param>
/// <returns> Heat coefficient for water [J/(m3 K)]</returns>
public static double HeatCoefficientWater(double pressure, double T_in, double T_out, bool flowMeasuredAtInlet)
{
if (T_in == T_out) return 0;
const double R = 461.526; /// [J kg^-1 K^-1]
const double p_star_Pa = 16.53E6; /// [Pa] (=16.53 MPa)
const double T_star = 1386.0; /// [K]
double T_in_K = Common.Units.ConvertTo(Common.Unit.K, T_in);
double T_out_K = Common.Units.ConvertTo(Common.Unit.K, T_out);
double tau_in = T_star / T_in_K;
double tau_out = T_star / T_out_K;
double pi = Common.Units.ConvertTo(Common.Unit.Pa, pressure) / p_star_Pa;
double h_in = tau_in * GammaTau(pi, tau_in) * R * T_in_K;
double h_out = tau_out * GammaTau(pi, tau_out) * R * T_out_K;
double ni = flowMeasuredAtInlet ? GammaPi(pi, tau_in) * R * T_in_K / p_star_Pa
: GammaPi(pi, tau_out) * R * T_out_K / p_star_Pa;
return (h_in - h_out) / (ni * (T_in - T_out));
}
/// <summary>
/// gamma(pi) see also STN EN 1434-1 Annex A (A.4)
/// </summary>
/// <param name="pi">pi = p / p* where p* = 16.53 MPa</param>
/// <param name="tau">tau = T* / T where T* = 1386 K</param>
/// <returns>gamma(pi)</returns>
static double GammaPi(double pi, double tau)
{
double result = 0;
for (int i = 0; i < 34; i++)
{
result -= ni[i] * Ii[i] * Math.Pow(7.1 - pi, Ii[i] - 1) * Math.Pow(tau - 1.222, Ji[i]);
}
return result;
}
/// <summary>
/// gamma(tau) see also STN EN 1434-1 Annex A (A.7)
/// </summary>
/// <param name="pi">pi = p / p* where p* = 16.53 MPa</param>
/// <param name="tau">tau = T* / T where T* = 1386 K</param>
/// <returns>gamma(tau)</returns>
static double GammaTau(double pi, double tau)
{
double result = 0;
for (int i = 0; i < 34; i++)
{
result += ni[i] * Math.Pow(7.1 - pi, Ii[i]) * Ji[i] * Math.Pow(tau - 1.222, Ji[i] - 1);
}
return result;
}
/// <summary>
/// Conversion of measured resistance of a platinum thermometer to temperature according to ITS-90
/// </summary>
/// <param name="R">Measured resistance in [°C]</param>
/// <param name="R001C">Calibrated resistance in Ohm at 0.01°C</param>
/// <param name="a7">Calibrated ITS-90 coefficient a7</param>
/// <param name="b7">Calibrated ITS-90 coefficient b7</param>
/// <param name="c7">Calibrated ITS-90 coefficient c7</param>
/// <returns>Temperature in [°C]</returns>
public static double PlatinumResistanceTM_ITS90_R2T(double R, double R001C, double a7, double b7, double c7)
{
double w = R / R001C; /// ratio
double r1 = w - 1.0;
double dw = r1 * (a7 + r1 * (b7 + r1 * c7)); /// = a7*r1 + b7*r1^2 + c7*r1^3
double wr = w - dw;
double x = (wr - 2.64) / 1.64;
double sum = 0;
for (int i = Di.Length - 1; i >= 0; i--)
{
sum = sum * x + Di[i];
}
return sum;
}
/// <summary>
/// Conversion of measured resistance of a platinum thermometer to temperature using Callendar-Van Dusen equations
/// </summary>
/// <param name="R">Measured resistance in [°C]</param>
/// <param name="R0">Calibrated resistance in Ohm at 0°C</param>
/// <param name="A">Calibration coefficient a</param>
/// <param name="B">Calibration coefficient b</param>
/// <returns>Temperature in [°C]</returns>
public static double PlatinumResistanceTM_ITS27_R2T(double R, double R0, double A, double B)
{
if (R0 * R0 * A * A - 4 * R0 * B * (R0 - R) <= 0) return 0; /// Out of range
return (-(R0 * A) + Math.Sqrt(R0 * R0 * A * A - 4 * R0 * B * (R0 - R))) / (2 * R0 * B);
}
}
}
-11
View File
@@ -1,11 +0,0 @@
using System;
namespace Common
{
public interface IMeasurementCorrection
{
int RangeIx { get; set; }
double Measurement { get; set; }
double Correction { get; set; }
}
}
-26
View File
@@ -1,26 +0,0 @@
///
/// Copyright (c) 2021 Sensus Slovensko a.s.
///
using System;
namespace Common
{
public interface IOrderInfo
{
string POName { get; }
string VariantCode { get; }
string ModuleParam { get; }
int PiecesCount { get; }
string SNPrefix { get; }
int SNFirst { get; }
int SNDigitsCount { get; }
string SNSuffix { get; }
string RAPrefix { get; }
int RAFirst { get; }
string RASuffix { get; }
string Remark { get; }
int CurrentPcsCount { get; set; }
int CurrentSN { get; set; }
int CurrentRA { get; set; }
}
}
-14
View File
@@ -1,14 +0,0 @@
using System;
namespace Common
{
public interface IUncertainty
{
float Measurement { get; }
float MainUncertainty { get; }
float Resolution { get; }
float DriftPerYr { get; }
float Conditions { get; }
float UncertaintyOfCorrection { get; }
}
}
-22
View File
@@ -1,22 +0,0 @@
using System;
namespace Common
{
public interface IUser
{
string UserName { get; } /// = name, alias, abbreviation
string FullName { get; } /// = description
string Tag { get; }
int Number { get; }
/// Access rights
bool IsMemberOf(GID group);
bool IsMemberOf(GID[] groups);
bool IsCorrectPassword(string password);
/// Password complexity, history, etc.
bool IsPasswordExpired();
bool IsPasswordUsedInPast(string passwordCandidate);
void SetPassword(string password);
}
}
+1 -1
View File
@@ -10,7 +10,7 @@ using System.Runtime.InteropServices;
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Common")]
[assembly: AssemblyCopyright("Copyright © 2020-2022")]
[assembly: AssemblyCopyright("Copyright © 2020")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
+1 -4
View File
@@ -1,7 +1,4 @@
///
/// Copyright (c) 2021 Sensus Slovensko a.s.
///
using System;
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
-338
View File
@@ -1,338 +0,0 @@
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Common.Iperl;
namespace Common
{
public static class Extensions
{
public static float[] SubArray(this float[] array, int offset, int length)
{
float[] result = new float[length];
Array.Copy(array, offset, result, 0, length);
return result;
}
}
public class StatisticalMetrics
{
const int VectorSize = 7;
const int MinLength = 100;
const float AdcBit = (float)57e-9;
const int NeighbourhoodSize = 30; /// To determine extended outliers
/// <summary>
/// Calculates a 7-dimensional vector with these components:
/// x[0] = X1 = Number of outliers
/// x[1] = X2 = Relative cal-factor shift due to outliers
/// x[2] = X3 = Standard deviation of high-pass filteres ++++ demodulation of EMF (cut-off at Nyquist frequency)
/// x[3] = X4 = Robust standard deviation of high-pass filtered ++++ demodulation
/// x[4] = X5 = Peak-to-peak of low-pass filtered ++++ demodulation of EMF (cut-off TBD)
/// x[5] = X6 = Peak-to-peak of reference flow rate
/// x[6] = X7 = Mean impedance (++-- demodulation)
/// </summary>
/// <param name="optoData"></param>
/// <param name="optoDataCount"></param>
/// <param name="startIx"></param>
/// <param name="endIx"></param>
/// <returns></returns>
public static float[] Calculate(OptoTelegramRaw[] optoData, int optoDataCount, int startIx, int endIx, bool downsample,
out float[] offsetV, out float[] kOhmsR, out float[] kOhmsC, out float[] dutFlow,
out float[] refFlow, out float[] flowRatio, out float[] magField, out float[] emfV,
out PointF[] outliers, out PointF[] extendedOutliers)
{
offsetV = kOhmsR = kOhmsC = dutFlow = refFlow = flowRatio = magField = emfV = null;
outliers = extendedOutliers = null;
if (optoData == null || optoData.Length < optoDataCount ||
startIx < 0 || endIx >= optoDataCount || endIx <= startIx + MinLength + 3) return null;
float[] modulatedData = GetModulatedEmf(optoData, optoDataCount, AdcBit);
FindShiftAndDemodulate(modulatedData, downsample,
new float[] { +1, +1, +1, +1 }, out offsetV,
new float[] { +1, +1, -1, -1 }, out kOhmsR,
new float[] { +1, -1, -1, +1 }, out kOhmsC,
new float[] { +1, -1, +1, -1 }, out dutFlow);
//offsetV = FirFilter(modulatedData, new float[] { 1, 3, 4, 4, 3, 1}, 0.0625F);
magField = GetMagField(optoData, optoDataCount, downsample, new float[] { 1, 1, 1, 1 });
refFlow = GetRefFlow(optoData, optoDataCount, downsample, new float[] { 1, 1, 1, 1 });
flowRatio = new float[Math.Min(dutFlow.Length, refFlow.Length)];
for (int i = 0; i < flowRatio.Length; i++)
{
flowRatio[i] = (refFlow[i] != 0) ? dutFlow[i] / refFlow[i] : 1;
}
float[] x = new float[VectorSize];
/// X1 = Number of outliers
int outliersCount = GetOutliers(flowRatio, out outliers, out extendedOutliers);
/// X2 = Relative cal-factor shift due to outliers
/// X3 = Standard deviation of high-pass filteres ++++ demodulation of EMF (cut-off at Nyquist frequency)
/// X4 = Robust standard deviation of high-pass filtered ++++ demodulation
/// X5 = Peak-to-peak of low-pass filtered ++++ demodulation of EMF (cut-off TBD)
/// X6 = Peak-to-peak of reference flow rate
/// X7 = Mean impedance (++-- demodulation)
double sum = 0;
foreach (var z in kOhmsR) sum += z;
x[6] = Convert.ToSingle(sum / kOhmsR.Length);
return x;
}
static float[] GetModulatedEmf(OptoTelegramRaw[] optoData, int optoDataCount, float factor)
{
if (optoData == null || optoDataCount < 0) return null;
float[] result = new float[optoDataCount];
for (int i = 0; i < optoDataCount; i++)
{
result[i] = optoData[i].EmfRaw * factor;
}
return result;
}
static float[] GetMagField(OptoTelegramRaw[] optoData, int optoDataCount, bool downsample, float[] kernel)
{
if (optoData == null || optoDataCount < 0 || (downsample && (kernel == null || kernel.Length < 4))) return null;
int resultLen = downsample ? (optoDataCount / 4) : optoDataCount;
float[] result = new float[resultLen];
if (downsample)
{
float ksum = 0;
for (int j = 0; j < kernel.Length; j++) ksum += kernel[j];
for (int j = 0; j < kernel.Length; j++) kernel[j] /= ksum;
for (int i = 0; (4 * i) + kernel.Length - 1 < optoDataCount; i++)
{
float sum = 0;
for (int j = 0; j < kernel.Length; j++) sum += Convert.ToSingle(optoData[4 * i + j].MagneticFieldRaw) * kernel[j];
result[i] = sum;
}
}
else
{
for (int i = 0; i < optoDataCount; i++) result[i] = optoData[i].MagneticFieldRaw;
}
return result;
}
static float[] GetRefFlow(OptoTelegramRaw[] optoData, int optoDataCount, bool downsample, float[] kernel)
{
if (optoData == null || optoDataCount < 0 || (downsample && (kernel == null || kernel.Length < 4))) return null;
int resultLen = downsample ? (optoDataCount / 4) : optoDataCount;
float[] result = new float[resultLen];
if (downsample)
{
float ksum = 0;
for (int j = 0; j < kernel.Length; j++) ksum += kernel[j];
for (int j = 0; j < kernel.Length; j++) kernel[j] /= ksum;
for (int i = 0; (4 * i) + kernel.Length - 1 < optoDataCount; i++)
{
float sum = 0;
for (int j = 0; j < kernel.Length; j++) sum += Convert.ToSingle(optoData[4 * i + j].RefFlow) * kernel[j];
result[i] = sum;
}
}
else
{
for (int i = 0; i < optoDataCount; i++) result[i] = optoData[i].RefFlow;
}
return result;
}
public static void FindShiftAndDemodulate(float[] modulatedData, bool downsample,
float[] kernel1, out float[] data1,
float[] kernel2, out float[] data2,
float[] kernel3, out float[] data3,
float[] kernel4, out float[] data4)
{
int shift = GetShift(modulatedData.SubArray(0, MinLength));
data1 = (kernel1 != null) ? Demodulate(modulatedData, kernel1, shift, downsample) : null;
data2 = (kernel2 != null) ? Demodulate(modulatedData, kernel2, shift, downsample) : null;
data3 = (kernel3 != null) ? Demodulate(modulatedData, kernel3, shift, downsample) : null;
data4 = (kernel4 != null) ? Demodulate(modulatedData, kernel4, shift, downsample) : null;
}
/// <summary>
/// Unlike FIR filtering, demodulation shifts the kernel in 4 phases
/// </summary>
/// <param name="data">Input data</param>
/// <param name="kernel">Demodulation kernel</param>
/// <param name="shift">shift 0..3</param>
/// <returns>Output data</returns>
static float[] Demodulate(float[] data, float[] kernel, int shift, bool downsample)
{
if (data == null || data.Length < MinLength || kernel == null || kernel.Length != 4)
{
return null;
}
float ksum = 0;
for (int i = 0; i < 4; i++) ksum += Math.Abs(kernel[i]);
for (int i = 0; i < 4; i++) kernel[i] /= ksum;
int rsltLen = downsample ? (data.Length - 3) / 4 : data.Length - 3;
float[] result = new float[rsltLen];
if (downsample)
{
for (int i = shift; i < 4 * rsltLen; i += 4)
{
float sum = 0;
for (int j = 0; j < 4; j++) sum += data[i + j] * kernel[(i + j + 4 - shift) % 4];
result[i / 4] = sum;
}
}
else
{
for (int i = 0; i < rsltLen; i++)
{
float sum = 0;
for (int j = 0; j < 4; j++) sum += data[i + j] * kernel[(i + j + 4 - shift) % 4];
result[i] = sum;
}
}
return result;
}
/// <summary>
/// Determine modulation phase by maximizing ++-- demodulation result.
/// </summary>
/// <param name="modulatedEmf">Input data</param>
/// <returns>0..3 = modulation phase or, -1 = error</returns>
static int GetShift(float[] modulatedData)
{
float[] kernel = new float[4] { 1, 1, -1, -1 };
int maximizingShift = -1;
float maximum = float.MinValue;
for (int shift = 0; shift <= 3; shift++)
{
var demodulatedCandidate = Demodulate(modulatedData, kernel, shift, false);
float sum = 0;
foreach (var d in demodulatedCandidate) sum += d;
if (sum > maximum)
{
maximum = sum;
maximizingShift = shift;
}
}
return maximizingShift;
}
/// <summary>
/// FIR filtering = convolution with a kernel
/// </summary>
/// <param name="data">Input data</param>
/// <param name="kernel">Convolution kernel</param>
/// <returns>Output data</returns>
static float[] FirFilter(float[] data, float[] kernel, float factor)
{
if (data == null || kernel == null) return null;
int kernelLen = kernel.Length;
int rsltLen = data.Length - kernelLen + 1;
if (rsltLen < 0) return null;
float[] result = new float[rsltLen];
for (int i = 0; i < rsltLen; i++)
{
float sum = 0;
for (int j = 0; j < kernelLen; j++) sum += data[i + j] * kernel[j];
result[i] = sum * factor;
}
return result;
}
static int GetOutliers(float[] flowRatio, out PointF[] outliers, out PointF[] extendedOutliers)
{
float mean = Enumerable.Average(flowRatio);
var fr = new float[flowRatio.Length];
for (int i = 0; i < fr.Length; i++) fr[i] = flowRatio[i] - mean;
Array.Sort(fr);
float qLo = fr[fr.Length / 4];
float qHi = fr[3 * fr.Length / 4];
int N = fr.Length / 2;
float sumY = 0;
float sumYY = 0;
for (int i = fr.Length / 4; i < 3 * fr.Length / 4; i++)
{
sumY += fr[i];
sumYY += fr[i] * fr[i];
}
float std = (float)Math.Sqrt(sumYY / N - (sumY / N) * (sumY / N));
float robustStd = std * 5.1812824F;
float threshold = 7 * robustStd;
/// Restore fr as it was before sorting
for (int i = 0; i < fr.Length; i++) fr[i] = flowRatio[i] - mean;
IList<PointF> listOfOutliers = new List<PointF>();
bool[] boolExtendedOutliers = new bool[fr.Length];
int outliersCount = 0;
for (int i = 0; i < fr.Length; i++)
{
if (fr[i] < -threshold || fr[i] > threshold)
{
/// This is an outlier
listOfOutliers.Add(new PointF(Convert.ToSingle(i), fr[i] + mean));
outliersCount++;
for (int j = Math.Max(0, i - NeighbourhoodSize); j <= Math.Min(i + NeighbourhoodSize, fr.Length - 1); j++)
{
boolExtendedOutliers[j] = true;
}
}
}
IList<PointF> listOfExtendedOutliers = new List<PointF>();
for (int i = 0; i < fr.Length; i++)
{
if (boolExtendedOutliers[i])
{
listOfExtendedOutliers.Add(new PointF(Convert.ToSingle(i), fr[i] + mean));
}
}
outliers = listOfOutliers.ToArray<PointF>();
extendedOutliers = listOfExtendedOutliers.ToArray<PointF>();
return outliersCount;
}
}
}
@@ -1,5 +1,5 @@
///
/// Copyright (c) 2013-2022 Sensus Slovensko a.s.
/// Copyright (c) 2013-2020 Sensus Slovensko a.s.
///
using System;
using System.Collections;
@@ -9,7 +9,7 @@ using System.Data;
using System.Windows.Forms;
using System.Runtime.InteropServices;
namespace Common.Forms
namespace Common.UIControls
{
/// <summary>
/// Event Handler for SubItem events
@@ -61,9 +61,6 @@ namespace Common.Forms
private const int HDN_ITEMCHANGINGW = (HDN_FIRST-20);
#endregion
public MySortOrder SortOrder = MySortOrder.None;
public int SortColumn = -1;
/// <summary>
/// Required designer variable.
/// </summary>
@@ -427,18 +424,12 @@ namespace Common.Forms
OnSubItemEndEditing(e);
if (_editSubItem >= 0 && _editSubItem < _editItem.SubItems.Count)
{
_editItem.SubItems[_editSubItem].Text = e.DisplayText;
}
_editItem.SubItems[_editSubItem].Text = e.DisplayText;
if (_editingControl != null)
{
_editingControl.Leave -= new EventHandler(_editControl_Leave);
_editingControl.KeyPress -= new KeyPressEventHandler(_editControl_KeyPress);
_editingControl.Leave -= new EventHandler(_editControl_Leave);
_editingControl.KeyPress -= new KeyPressEventHandler(_editControl_KeyPress);
_editingControl.Visible = false;
}
_editingControl.Visible = false;
_editingControl = null;
_editItem = null;
+107
View File
@@ -0,0 +1,107 @@
///
/// Copyright (c) 2019-2020 Sensus Slovensko a.s.
///
using System;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Windows.Forms;
namespace Common.UIControls
{
[EditorBrowsable(EditorBrowsableState.Never)]
public static class ListViewExtensions
{
[StructLayout(LayoutKind.Sequential)]
public struct HDITEM
{
public Mask mask;
public int cxy;
[MarshalAs(UnmanagedType.LPTStr)]
public string pszText;
public IntPtr hbm;
public int cchTextMax;
public Format fmt;
public IntPtr lParam;
// _WIN32_IE >= 0x0300
public int iImage;
public int iOrder;
// _WIN32_IE >= 0x0500
public uint type;
public IntPtr pvFilter;
// _WIN32_WINNT >= 0x0600
public uint state;
[Flags]
public enum Mask
{
Format = 0x4, // HDI_FORMAT
};
[Flags]
public enum Format
{
SortDown = 0x200, // HDF_SORTDOWN
SortUp = 0x400, // HDF_SORTUP
};
};
public const int LVM_FIRST = 0x1000;
public const int LVM_GETHEADER = LVM_FIRST + 31;
public const int HDM_FIRST = 0x1200;
public const int HDM_GETITEM = HDM_FIRST + 11;
public const int HDM_SETITEM = HDM_FIRST + 12;
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern IntPtr SendMessage(IntPtr hWnd, UInt32 msg, IntPtr wParam, IntPtr lParam);
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern IntPtr SendMessage(IntPtr hWnd, UInt32 msg, IntPtr wParam, ref HDITEM lParam);
public static void SetSortIcon(this ListViewEx listViewControl, int columnIndex, SortOrder order)
{
IntPtr columnHeader = SendMessage(listViewControl.Handle, LVM_GETHEADER, IntPtr.Zero, IntPtr.Zero);
for (int columnNumber = 0; columnNumber <= listViewControl.Columns.Count - 1; columnNumber++)
{
var columnPtr = new IntPtr(columnNumber);
var item = new HDITEM
{
mask = HDITEM.Mask.Format
};
if (SendMessage(columnHeader, HDM_GETITEM, columnPtr, ref item) == IntPtr.Zero)
{
throw new Win32Exception();
}
if (order != SortOrder.None && columnNumber == columnIndex)
{
switch (order)
{
case SortOrder.Ascending:
item.fmt &= ~HDITEM.Format.SortDown;
item.fmt |= HDITEM.Format.SortUp;
break;
case SortOrder.Descending:
item.fmt &= ~HDITEM.Format.SortUp;
item.fmt |= HDITEM.Format.SortDown;
break;
default:
break;
}
}
else
{
item.fmt &= ~HDITEM.Format.SortDown & ~HDITEM.Format.SortUp;
}
if (SendMessage(columnHeader, HDM_SETITEM, columnPtr, ref item) == IntPtr.Zero)
{
throw new Win32Exception();
}
}
}
}
}
@@ -1,24 +1,24 @@
///
/// Copyright (c) 2019-2021 Sensus Slovensko a.s.
/// Copyright (c) 2019-2020 Sensus Slovensko a.s.
///
using System;
using System.Collections;
using System.Windows.Forms;
namespace Common.Forms
namespace Common.UIControls
{
public class LviDateTimeColumnComparer : IComparer
{
int column;
MySortOrder order;
SortOrder order;
public LviDateTimeColumnComparer()
{
column = 0;
order = MySortOrder.Ascending;
order = SortOrder.Ascending;
}
public LviDateTimeColumnComparer(int column, MySortOrder order)
public LviDateTimeColumnComparer(int column, SortOrder order)
{
this.column = column;
this.order = order;
@@ -33,13 +33,13 @@ namespace Common.Forms
{
return 0;
}
else if ((order == MySortOrder.Descending || order == MySortOrder.Descending2))
else if (order == SortOrder.Ascending)
{
return (valY > valX) ? 1 : -1;
return (valX > valY) ? 1 : -1;
}
else
{
return (valX > valY) ? 1 : -1;
return (valY > valX) ? 1 : -1;
}
}
}
+34
View File
@@ -0,0 +1,34 @@
///
/// Copyright (c) 2019-2020 Sensus Slovensko a.s.
///
using System;
using System.Collections;
using System.Windows.Forms;
namespace Common.UIControls
{
public class LviIntColumnComparer : IComparer
{
int column;
SortOrder order;
public LviIntColumnComparer()
{
column = 0;
order = SortOrder.Ascending;
}
public LviIntColumnComparer(int column, SortOrder order)
{
this.column = column;
this.order = order;
}
public int Compare(object x, object y)
{
int valX = int.Parse(((ListViewItem)x).SubItems[column].Text);
int valY = int.Parse(((ListViewItem)y).SubItems[column].Text);
return (order == SortOrder.Descending) ? (valY - valX) : (valX - valY);
}
}
}
@@ -0,0 +1,34 @@
///
/// Copyright (c) 2019-2020 Sensus Slovensko a.s.
///
using System;
using System.Collections;
using System.Windows.Forms;
namespace Common.UIControls
{
public class LviTextColumnComparer : IComparer
{
private int column;
SortOrder order;
public LviTextColumnComparer()
{
column = 0;
order = SortOrder.Ascending;
}
public LviTextColumnComparer(int column, SortOrder order)
{
this.column = column;
this.order = order;
}
public int Compare(object x, object y)
{
string txtX = ((ListViewItem)x).SubItems[column].Text;
string txtY = ((ListViewItem)y).SubItems[column].Text;
return (order == SortOrder.Descending) ? String.Compare(txtY, txtX) : String.Compare(txtX, txtY);
}
}
}
+5 -130
View File
@@ -1,137 +1,12 @@
///
/// Copyright (c) 2021-2022 Sensus Slovensko a.s.
///
using System;
using System.IO.Ports;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Common
{
public class Utils
{
public static string GetTestName(string name, int repeats, int repetitionNr)
{
if (name == null) return null;
if (repeats == 1) return name;
return string.Format("{0} ({1}/{2})", name, repetitionNr, repeats);
}
public static string ToNiceString(double value, int sigDigits)
{
string format = SignificantDigitsToFmt(value, sigDigits);
return (format == "F0") ? value.ToString("F0") : value.ToString(format).TrimEnd(new char[] { '0' });
}
public static FlowNames ProfileType2FlowNames(ProfileType pt)
{
switch (pt)
{
case ProfileType.Q3R: return FlowNames.Q3Q2Q1;
case ProfileType.QnClassColdWater: return FlowNames.QnQtQmin;
case ProfileType.QnClassHotWater: return FlowNames.QnQtQmin;
case ProfileType.QpQi: return FlowNames.QpQi;
default: return FlowNames.Q3Q2Q1;
}
}
public static string SignificantDigitsToFmt(double value, int sigDigits)
{
if (sigDigits == 6)
{
if (value >= 99999.5 || value < -99999.5) return "F0";
else if (value >= 9999.95 || value < -9999.95) return "F1";
else if (value >= 999.995 || value < -999.995) return "F2";
else if (value >= 99.9995 || value < -99.9995) return "F3";
else if (value >= 9.99995 || value < -9.99995) return "F4";
else if (value >= 0.999995 || value < -0.999995) return "F5";
else if (value >= 0.0999995 || value < -0.0999995) return "F6";
else if (value >= 0.00999995 || value < -0.00999995) return "F7";
else if (value >= 0.000999995 || value < -0.000999995) return "F8";
else if (value >= 0.0000999995 || value < -0.0000999995) return "F9";
else return "F10";
}
else if (sigDigits == 5)
{
if (value >= 9999.5 || value < -9999.5) return "F0";
else if (value >= 999.95 || value < -999.95) return "F1";
else if (value >= 99.995 || value < -99.995) return "F2";
else if (value >= 9.9995 || value < -9.9995) return "F3";
else if (value >= 0.99995 || value < -0.99995) return "F4";
else if (value >= 0.099995 || value < -0.099995) return "F5";
else if (value >= 0.0099995 || value < -0.0099995) return "F6";
else if (value >= 0.00099995 || value < -0.00099995) return "F7";
else if (value >= 0.000099995 || value < -0.000099995) return "F8";
else return "F9";
}
else if (sigDigits == 4)
{
if (value >= 999.5 || value < -999.5) return "F0";
else if (value >= 99.95 || value < -99.95) return "F1";
else if (value >= 9.995 || value < -9.995) return "F2";
else if (value >= 0.9995 || value < -0.9995) return "F3";
else if (value >= 0.09995 || value < -0.09995) return "F4";
else if (value >= 0.009995 || value < -0.009995) return "F5";
else if (value >= 0.0009995 || value < -0.0009995) return "F6";
else if (value >= 0.00009995 || value < -0.00009995) return "F7";
else return "F8";
}
else if (sigDigits == 3)
{
if (value >= 99.5 || value < -99.5) return "F0";
else if (value >= 9.95 || value < -9.95) return "F1";
else if (value >= 0.995 || value < -0.995) return "F2";
else if (value >= 0.0995 || value < -0.0995) return "F3";
else if (value >= 0.00995 || value < -0.00995) return "F4";
else if (value >= 0.000995 || value < -0.000995) return "F5";
else if (value >= 0.0000995 || value < -0.0000995) return "F6";
else return "F7";
}
else if (sigDigits == 2)
{
if (value >= 9.5 || value < -9.5) return "F0";
else if (value >= 0.95 || value < -0.95) return "F1";
else if (value >= 0.095 || value < -0.095) return "F2";
else if (value >= 0.0095 || value < -0.0095) return "F3";
else if (value >= 0.00095 || value < -0.00095) return "F4";
else if (value >= 0.000095 || value < -0.000095) return "F5";
else return "F6";
}
else /// if (sigDigits == 1)
{
if (value >= 0.95 || value < -0.95) return "F0";
else if (value >= 0.095 || value < -0.095) return "F1";
else if (value >= 0.0095 || value < -0.0095) return "F2";
else if (value >= 0.00095 || value < -0.00095) return "F3";
else if (value >= 0.000095 || value < -0.000095) return "F4";
else return "F5";
}
}
public static Parity GetParity(string str, Parity defaultParity = Parity.None)
{
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;
if (str.Equals(Parity.Mark.ToString())) return Parity.Mark;
if (str.Equals(Parity.Space.ToString())) return Parity.Space;
return defaultParity;
}
public static StopBits GetStopBits(string str, StopBits defaultStopBits = StopBits.One)
{
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 defaultStopBits;
}
public static Handshake GetHandshake(string str, Handshake defaultHandshake = Handshake.None)
{
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;
if (str.Equals(Handshake.RequestToSendXOnXOff.ToString())) return Handshake.RequestToSendXOnXOff;
return defaultHandshake;
}
}
}
+4 -4
View File
@@ -122,7 +122,7 @@ namespace Config.CalendarEvent
}
public static bool IsCalendarEventTrigerred(ICalendarEvent evnt, DateTime dateTimeNow)
public static bool IsCalendarEventTrigerred(ICalendarEvent evnt, DateTime currentDate)
{
DateTime evntDT = evnt.AllDay
? new DateTime(evnt.Date.Year, evnt.Date.Month, evnt.Date.Day, 0, 0, 0)
@@ -133,17 +133,17 @@ namespace Config.CalendarEvent
DateTime dt1 = evntDT;
DateTime dt2 = evntDT + new TimeSpan(8, 0, 0);
DateTime dt3 = evntDT + new TimeSpan(16, 0, 0);
return (dateTimeNow >= dt1) || (dateTimeNow >= dt1) || (dateTimeNow >= dt3);
return (currentDate >= dt1) || (currentDate >= dt1) || (currentDate >= dt3);
}
else if (!evnt.TriggerOnExactDayOnly)
{
/// Trigger after event expires
return (dateTimeNow >= evntDT);
return (currentDate >= evntDT);
}
else
{
/// Trigger event on exact date only
return (dateTimeNow >= evntDT) && DayMatchesExactly(evnt, dateTimeNow);
return (currentDate >= evntDT) && DayMatchesExactly(evnt, currentDate);
}
}
+8 -8
View File
@@ -19,18 +19,18 @@
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>TRACE;DEBUG;MUNICH</DefineConstants>
<DefineConstants>TRACE;DEBUG;ROMA_200;LANG_IT;TEST_PROFILES</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<AllowUnsafeBlocks>false</AllowUnsafeBlocks>
<PlatformTarget>AnyCPU</PlatformTarget>
<PlatformTarget>x86</PlatformTarget>
<Prefer32Bit>false</Prefer32Bit>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE;MUNICH</DefineConstants>
<DefineConstants>TRACE;ROMA_200;LANG_IT;TEST_PROFILES</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<Prefer32Bit>false</Prefer32Bit>
@@ -69,17 +69,21 @@
<ItemGroup>
<Compile Include="CalendarEvent\ICalendarEvent.cs" />
<Compile Include="Data.cs" />
<Compile Include="DatabaseSettings.cs" />
<Compile Include="Entities\BenchPath.cs" />
<Compile Include="Entities\CustomEvent.cs" />
<Compile Include="Entities\Component.cs" />
<Compile Include="Entities\ComponentProcedure.cs" />
<Compile Include="Entities\ComponentTest.cs" />
<Compile Include="Entities\Enums.cs" />
<Compile Include="Entities\FeedingPath.cs" />
<Compile Include="Entities\Group.cs" />
<Compile Include="Entities\HeatMetersPath.cs" />
<Compile Include="Entities\IHasItemNr.cs" />
<Compile Include="Entities\IHasName.cs" />
<Compile Include="Entities\IHasValves.cs" />
<Compile Include="Entities\IParamsProvider.cs" />
<Compile Include="Entities\IperlEnums.cs" />
<Compile Include="Entities\MeasurementCorrection.cs" />
<Compile Include="Entities\MetersPath.cs" />
<Compile Include="Entities\OutputPath.cs" />
@@ -87,7 +91,6 @@
<Compile Include="Entities\Profile.cs" />
<Compile Include="Entities\PTest.cs" />
<Compile Include="Entities\Test.cs" />
<Compile Include="Entities\TestInstance.cs" />
<Compile Include="Entities\TransitionSequence.cs" />
<Compile Include="Entities\TransitionStep.cs" />
<Compile Include="Entities\Uncertainty.cs" />
@@ -122,6 +125,7 @@
<DesignTime>True</DesignTime>
<DependentUpon>Strings.resx</DependentUpon>
</Compile>
<Compile Include="Units.cs" />
<Compile Include="Utils.cs" />
</ItemGroup>
<ItemGroup>
@@ -137,10 +141,6 @@
<EmbeddedResource Include="Resources\Strings.zh-CN.resx" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Common\Common.csproj">
<Project>{c8939821-ba5c-4988-a3d0-bf53b74865c7}</Project>
<Name>Common</Name>
</ProjectReference>
<ProjectReference Include="..\Users\Users.csproj">
<Project>{6E5CB0E9-E1B6-4E5D-AC6E-B1049E180F2B}</Project>
<Name>Users</Name>
+12 -13
View File
@@ -2,7 +2,7 @@
namespace Config
{
public class Data : Users.CurrentUser
public class Data : Users.GlobalData
{
public const string AdminUsername = "admin";
public const string AdminPassword = "staratura";
@@ -15,10 +15,10 @@ namespace Config
public const int HeatMetersCount = 0;
public const int MaxPartNr = 1;
#elif MUNICH
public const int WMsCount = 3;
public const int LineSize = 3;
public const int CompoundWMsCount = 3;
public const int HeatMetersCount = 0;
public const int WMsCount = 3;
public const int LineSize = 3;
public const int CompoundWMsCount = 3;
public const int HeatMetersCount = 0;
public const int MaxPartNr = 3;
#elif MALTA_WSD25
public const int WMsCount = 6;
@@ -26,7 +26,7 @@ namespace Config
public const int CompoundWMsCount = 0;
public const int HeatMetersCount = 0;
public const int MaxPartNr = 1;
#elif BADGER_MALA_TRAT || BERLIN || FUZHOU_150 || FUZHOU_300 || GELSENWASSER || GENESIS || IZRAEL_200 || PETERSBURG_200 || SENTEC || SLM_150 || TORINO_50
#elif BADGER_MALA_TRAT || BERLIN || FUZHOU_150 || FUZHOU_300 || GELSENWASSER || GENESIS || IZRAEL_200 || PETERSBURG_200 || SENTEC || SLM_150 || TORINO_50 || TURA_SPECIAL
public const int WMsCount = 6;
public const int LineSize = 6;
public const int CompoundWMsCount = 1;
@@ -44,12 +44,6 @@ namespace Config
public const int CompoundWMsCount = 1;
public const int HeatMetersCount = 0;
public const int MaxPartNr = WMsCount / LineSize;
#elif TURA_SPECIAL
public const int WMsCount = 6;
public const int LineSize = 6;
public const int CompoundWMsCount = 1;
public const int HeatMetersCount = 0;
public const int MaxPartNr = WMsCount / LineSize;
#elif DEWA_300 || FUZHOU_100 || ROMA_200 || LUXEMBURG_40
public const int WMsCount = 10;
public const int LineSize = 10;
@@ -74,7 +68,7 @@ namespace Config
public const int CompoundWMsCount = 1;
public const int HeatMetersCount = 6;
public const int MaxPartNr = WMsCount / LineSize;
#elif ALZIR_25 || BAHRAIN_50 || CEVAK_40 || FEWA_50 || FILIPINY_50 || FUZHOU_50 || HONGKONG_50 || IZRAEL_25 || JUZNA_AFRIKA_50 || KEMPNO_50 || KRAKOW_50 || MILWAUKEE || MURES_40 || PETERSBURG_50 || TORUN_50 || WARSAW_50 || ZAMBIA || ZODINO
#elif ALZIR_25 || BAHRAIN_50 || CEVAK_40 || FEWA_50 || FILIPINY_50 || FUZHOU_50 || HONGKONG_50 || IZRAEL_25 || JUZNA_AFRIKA_50 || KEMPNO_50 || KRAKOW_50 || MURES_40 || PETERSBURG_50 || TORUN_50 || ZAMBIA || ZODINO
public const int WMsCount = 20;
public const int LineSize = 10;
public const int CompoundWMsCount = 1;
@@ -94,6 +88,11 @@ namespace Config
public const int MaxPartNr = WMsCount / LineSize;
#endif
///
/// Database related: This object reference is set after a successful user login
///
public static DatabaseSettings CurrentBench;
public static double RealDensity = 0; /// true water density [kg/m3]
public static double AtTemperature = 0; /// measured at temperature [°C]
public static double Buoyancy = 0;
+64
View File
@@ -0,0 +1,64 @@
///
/// Copyright (c) 2013-2020 Sensus Slovensko a.s.
///
using System;
using System.Text;
using System.Xml.Serialization;
namespace Config
{
/// <summary>
/// Test bench database settings, contains bench name and settings od several databases
/// </summary>
public class DatabaseSettings : ICloneable, IComparable
{
// Public fields
public string BenchName;
public bool IsRealBench;
public Users.DBSettings ProceduresDBSettings; /// Configuration database settings
public Users.DBSettings WaterMetersDBSettings; /// Results database settings
public Users.DBSettings EventsDBSettings; /// Events database settings
public Users.DBSettings UsersDBSettings; /// Shared configuration database settings
// Constructor
public DatabaseSettings()
{
BenchName = String.Empty; /// Empty string (avoid null)
IsRealBench = false;
ProceduresDBSettings = new Users.DBSettings(Users.Entities.DBType.MySql, string.Empty);
WaterMetersDBSettings = new Users.DBSettings(Users.Entities.DBType.MySql, string.Empty);
EventsDBSettings = new Users.DBSettings(Users.Entities.DBType.MySql, string.Empty);
UsersDBSettings = new Users.DBSettings(Users.Entities.DBType.MySql, string.Empty);
}
public object Clone()
{
DatabaseSettings result = new DatabaseSettings();
result.BenchName = BenchName;
result.IsRealBench = IsRealBench;
result.ProceduresDBSettings = (Users.DBSettings)ProceduresDBSettings.Clone();
result.WaterMetersDBSettings = (Users.DBSettings)WaterMetersDBSettings.Clone();
result.EventsDBSettings = (Users.DBSettings)EventsDBSettings.Clone();
result.UsersDBSettings = (Users.DBSettings)UsersDBSettings.Clone();
return result;
}
public int CompareTo(object dbs2)
{
if (!(dbs2 is DatabaseSettings)) return 0;
return String.Compare(BenchName, (dbs2 as DatabaseSettings).BenchName);
}
public override string ToString()
{
return string.Format("{0} config={1} results={2} events={3} users={4}",
BenchName,
ProceduresDBSettings.ConnectionString,
WaterMetersDBSettings.ConnectionString,
EventsDBSettings.ConnectionString,
UsersDBSettings.ConnectionString);
}
}
}
+3 -11
View File
@@ -1,9 +1,8 @@
///
/// Copyright (c) 2013-2022 Sensus Slovensko a.s.
/// Copyright (c) 2013-2017 Sensus Metering Systems
///
using System;
using System.Collections.Generic;
using Common;
namespace Config.Entities
{
@@ -15,8 +14,6 @@ namespace Config.Entities
public virtual string OriName { get; set; } /// Not mapped to database
public virtual float Qfrom { get; set; } /// Water flow in [m3/h]
public virtual float Qto { get; set; } /// Water flow in [m3/h]
public virtual Unit FlowUnit { get; set; } /// Not mapped to database, used in UI
public virtual string Selector { get; set; }
public virtual string TempMtrUp { get; set; }
public virtual string TempMtrDown { get; set; }
public virtual string PressMtrUp { get; set; }
@@ -28,16 +25,13 @@ namespace Config.Entities
public virtual string ValvesOpen { get; set; }
public virtual string ValvesClose { get; set; }
public virtual bool QfromTextChngd { get; set; } /// Not mapped to database, used in ProcedureDlg / Metrology1Tab
public virtual bool QtoTextChngd { get; set; } /// Not mapped to database, used in ProcedureDlg / Metrology1Tab
/// ------------- Additional stuff not mapped into the database -------------
public BenchPath()
{
ValvesOpen = string.Empty;
ValvesClose = string.Empty;
}
}
public BenchPath(string name, int itemNr)
: this()
@@ -52,9 +46,7 @@ namespace Config.Entities
result.Qfrom = Qfrom;
result.Qto = Qto;
result.FlowUnit = FlowUnit;
result.Selector = Selector;
result.TempMtrUp = TempMtrUp;
result.TempMtrUp = TempMtrUp;
result.TempMtrDown = TempMtrDown;
result.PressMtrUp = PressMtrUp;
result.PressMtrDown = PressMtrDown;
+1 -2
View File
@@ -4,7 +4,6 @@
using System;
using System.Collections.Generic;
using System.IO;
using Common;
namespace Config.Entities
{
@@ -87,7 +86,7 @@ namespace Config.Entities
else if (line.Equals(DebugMode.FailureDuringOperation.ToString())) result.Mode = DebugMode.FailureDuringOperation;
else if (line.Equals(DebugMode.Off.ToString())) result.Mode = DebugMode.Off;
else if (line.Equals(DebugMode.Record.ToString())) result.Mode = DebugMode.Record;
else if (line.Equals(DebugMode.Replay.ToString())) result.Mode = DebugMode.Replay;
else if (line.Equals(DebugMode.Reply.ToString())) result.Mode = DebugMode.Reply;
else if (line.Equals(DebugMode.Simulate.ToString())) result.Mode = DebugMode.Simulate;
else if (line.Equals(DebugMode.Inherit.ToString())) result.Mode = DebugMode.Inherit;
-1
View File
@@ -3,7 +3,6 @@
///
using System;
using System.IO;
using Common;
namespace Config.Entities
{
-1
View File
@@ -3,7 +3,6 @@
///
using System;
using System.IO;
using Common;
namespace Config.Entities
{
+2 -2
View File
@@ -46,8 +46,8 @@ namespace Config.Entities
Rank = 2;
Hidden = false;
ReadOnly = false;
BackColor = unchecked((int)0xFFFF5050); /// (MSB)AARRGGBB(LSB) ... pink
TextColor = unchecked((int)0xFFFFFFFF); /// (MSB)AARRGGBB(LSB) ... white
BackColor = unchecked((int)0xFFFF5050);
TextColor = unchecked((int)0xFFFFFFFF);
TooltipEnabled = true;
CustomRecurringFunction = null;
}
+36 -235
View File
@@ -1,11 +1,11 @@
///
/// Copyright (c) 2013-2023 Sensus Slovensko a.s.
/// Copyright (c) 2013-2018 Sensus Slovensko a.s.
///
using System;
using System.Collections.Generic;
using System.Reflection;
namespace Common
namespace Config.Entities
{
/// <summary>
/// Helper class to assign descriptions to enum values
@@ -38,117 +38,6 @@ namespace Common
}
}
/// <summary>
/// Identifies the type of a database
/// </summary>
public enum DBType
{
None, /// Database disabled
MySql, /// MySQL database
SQLite, /// SQLite
Count
}
public enum ProcedureSelection
{
#if LANG_CS
[Description("Žádné")] None,
[Description("Lokální postupy")] FromLocalDB,
[Description("Postupy ze sdílené databázy")] FromSharedDB,
[Description("Zakázky z Oracle databázy")] OrderNrFromOracleDB,
[Description("Zakázky ze sledovací databázy")] OrderNrFromTracingDB,
#else
[Description("None")] None,
[Description("Local procedures")] FromLocalDB,
[Description("Shared procedures")] FromSharedDB,
[Description("Orders from Oracle DB")] OrderFromOracleDB,
[Description("Orders from Tracing DB")] OrderFromTracingDB,
#endif
Count
}
/// <summary>
/// Obsolete - replaced by enum ProcedureSelection (above) in 3.1 and newer
/// </summary>
public enum RemoteDBUse
{
[Description("Local DB only")] LocalDBOnly,
[Description("Remote DB only")] RemoteDBOnly,
[Description("Both DB-s, local 1st")] BothDBsLocalFirst,
[Description("Both DB-s, remote 1st")] BothDBsRemoteFirst,
Count
}
/// <summary>
/// Obsolete - Contains a procedure name and a database specification (local/remote).
/// </summary>
public class ProcedureInfo
{
public readonly string Name;
public readonly bool IsRemote;
public ProcedureInfo(string name, bool isRemote)
{
Name = name;
IsRemote = isRemote;
}
}
/// <summary>
/// Test designation mode for IperlLogger and IperlHead opto data files
/// </summary>
public enum DesigMode
{
Auto,
Based_on_procedure,
As_specified,
Count
}
public enum LoginMethod
{
UserName, /// = alias, abbreviation
FullName, /// = description
Number,
Count
}
public enum AuthorizedAs
{
PowerUser,
LocalUser,
RemoteUser,
Count
}
/// <summary>
/// GID-s of user groups, each user is member of one or more groups.
/// </summary>
public enum GID
{
Testers,
TestingSpecialists,
HeadOfLab,
MaintenanceSpecialists,
Metrologists,
CalibrationSpecialists,
Administrators, /// application / network / database administrator
TraceabilityManagement,
MetrologicalAuthority,
WaterMeterAuthority,
NrOfGroups, /// Number of groups (this is not a GroupID)
None,
}
public enum MySortOrder
{
None,
Ascending, /// The same like SortOrder.Ascending
Descending, /// The same like SortOrder.Descending
Ascending2, /// Sorts by a surname in ascending order in case or 'Name Surname' column
Descending2, /// Sorts by a surname in descending order in case or 'Name Surname' column
}
/// <summary>
/// Flags returned by each device configuration control Verify(...) function.
/// </summary>
@@ -163,48 +52,28 @@ namespace Common
InvokeCfgChange = 0x20, /// Invoke CfgChange handler of the component
}
public enum RemoteDBUse
{
[Description("Local DB only")] LocalDBOnly,
[Description("Remote DB only")] RemoteDBOnly,
[Description("Both DB-s, local 1st")] BothDBsLocalFirst,
[Description("Both DB-s, remote 1st")] BothDBsRemoteFirst,
Count
}
/// <summary>
/// Event severity
/// Contains a procedure name and a database specification (local/remote).
/// </summary>
public enum Severity
public class ProcedureInfo
{
Undefined,
Notification,
Warning,
Error,
FatalError,
Count
}
public readonly string Name;
public readonly bool IsRemote;
public enum EventClass
{
Undefined,
EquipmentHW,
Metrology,
TestingProcess,
BadResults,
ComputerResources,
Network,
Other,
Count
}
public enum SubscriberGroup : long
{
None = 0,
Metrology = 1,
Maintenance = 2,
Production = 4,
Management = 8,
Finish = 16,
}
public enum EViewerOption
{
Undefined,
AllEvents,
RecentEvents,
UnreadEvents,
public ProcedureInfo(string name, bool isRemote)
{
Name = name;
IsRemote = isRemote;
}
}
public enum ProcedureState
@@ -214,14 +83,6 @@ namespace Common
Count,
}
public enum FlowNames
{
QnQtQmin = 0,
Q3Q2Q1 = 1,
QpQi = 2,
Count,
}
public enum ProfileType
{
Q3R,
@@ -303,13 +164,11 @@ namespace Common
[Description("V")] V, /// vertical
[Description("STR")] S, /// standrohre
[Description("F")] F, /// fall
[Description("H/V")] HV, /// horizontal / vertical
#else
[Description("H")] H, /// horizontal
[Description("V")] V, /// vertical
[Description("S")] S, /// steig
[Description("F")] F, /// fall
[Description("H/V")] HV, /// horizontal / vertical
[Description("H")] H, /// horizontal
[Description("V")] V, /// vertical
[Description("S")] S, /// steig
[Description("F")] F, /// fall
#endif
Count
}
@@ -341,7 +200,6 @@ namespace Common
[Description("")] NotSpecified,
[Description("U0")] U0, /// ?
[Description("D0")] D0, /// ?
///
Count
}
@@ -390,17 +248,6 @@ namespace Common
Count
}
/// <summary>
/// State of water filled in the test bench.
/// </summary>
public enum FillState
{
Unknown, /// Test bench fill state is unknown
Empty, /// Test bench is empty, no water
Full, /// Test bench is full of water
Count
}
public enum MeretProtocol
{
[Description("<undefined>")] Undefined,
@@ -577,7 +424,7 @@ namespace Common
[Description("Fehler")] FailureDuringOperation, /// Failure during operation -> disabled
[Description("Aus")] Off, /// The component is off
[Description("Aufzeichnen")] Record,
[Description("Abspielen")] Replay,
[Description("Reply")] Reply,
[Description("Simuliert")] Simulate, /// Test bench simulation, this mode does not require any hardware
[Description("Geerbt")] Inherit,
#elif LANG_FR
@@ -588,7 +435,7 @@ namespace Common
[Description("Erreur d'exécution")] FailureDuringOperation,
[Description("Éteindre")] Off,
[Description("Record")] Record,
[Description("Répondre")] Replay,
[Description("Répondre")] Reply,
[Description("Simuler")] Simulate,
[Description("Hériter")] Inherit,
#else
@@ -599,7 +446,7 @@ namespace Common
[Description("Run-time error")] FailureDuringOperation, /// Failure during operation -> disabled
[Description("Off")] Off, /// The component is off
[Description("Record")] Record,
[Description("Replay")] Replay,
[Description("Reply")] Reply,
[Description("Simulate")] Simulate, /// Test bench simulation, this mode does not require any hardware
[Description("Inherit")] Inherit,
#endif
@@ -704,32 +551,26 @@ namespace Common
[Description("aus")] Off,
[Description("info")] Info,
[Description("ein")] On,
[Description("stopp")] Stop,
#elif LANG_FR
[Description("éteindre")] Off,
[Description("info")] Info,
[Description("allumé")] On,
[Description("arrêter")] Stop,
#elif LANG_CS
[Description("vypnuto")] Off,
[Description("info")] Info,
[Description("zapnuto")] On,
[Description("stop")] Stop,
#elif LANG_RU
[Description("выкл")] Off,
[Description("инфо")] Info,
[Description("вкл")] On,
[Description("останов")] Stop,
#elif LANG_PL
[Description("nie")] Off,
[Description("info")] Info,
[Description("tak")] On,
[Description("przestać")] Stop,
#else // LANG_EN
[Description("off")] Off,
[Description("info")] Info,
[Description("on")] On,
[Description("stop")] Stop,
#endif
Count
}
@@ -737,15 +578,15 @@ namespace Common
public enum ErrorFlagMask : long
{
E1 = (1L << 0), /// shift = 0, E1 = 1L
E2 = (1L << 1),
E3 = (1L << 2),
E4 = (1L << 3),
E5 = (1L << 4),
E6 = (1L << 5),
E7 = (1L << 6),
E8 = (1L << 7),
E9 = (1L << 8),
E1 = (1L << 0), /// shift = 0, E1 = 1L
E2 = (1L << 1),
E3 = (1L << 2),
E4 = (1L << 3),
E5 = (1L << 4),
E6 = (1L << 5),
E7 = (1L << 6),
E8 = (1L << 7),
E9 = (1L << 8),
E10 = (1L << 9),
E11 = (1L << 10),
E12 = (1L << 11),
@@ -801,44 +642,4 @@ namespace Common
E62 = (1L << 61),
E63 = (1L << 62),
}
#region iPERL enums
public enum Side
{
#if LANG_CS
[Description("Levá")] Left,
[Description("Pravá")] Right,
#else
[Description("Left")] Left,
[Description("Right")] Right,
#endif
Count
}
public enum FlowDir
{
R_L,
L_R,
Count
}
public enum Counting
{
Arbitrary,
Positive,
Negative,
Count
}
public enum OptoHeadState
{
Disabled,
OptoAndDirOK,
OptoNok,
DirNok,
Count
}
#endregion iPERL enums
}
+10 -18
View File
@@ -1,22 +1,19 @@
///
/// Copyright (c) 2013-2022 Sensus Slovensko a.s.
/// Copyright (c) 2013-2017 Sensus Metering Systems
///
using System;
using System.Collections.Generic;
using Common;
namespace Config.Entities
{
public class FeedingPath : IHasName, IHasItemNr, IHasValves
{
public virtual int Id { get; protected set; }
public virtual int ItemNr { get; set; }
public virtual int Id { get; protected set; }
public virtual int ItemNr { get; set; }
public virtual string Name { get; set; }
public virtual string OriName { get; set; } /// Not mapped to database
public virtual float Qfrom { get; set; } /// Water flow in [m3/h]
public virtual float Qto { get; set; } /// Water flow in [m3/h]
public virtual Unit FlowUnit { get; set; } /// Not mapped to database, used in UI
public virtual string Selector { get; set; }
public virtual float Qfrom { get; set; } /// Water flow in [m3/h]
public virtual float Qto { get; set; } /// Water flow in [m3/h]
public virtual string Pump { get; set; }
public virtual string RegulValvesPct { get; set; } /// Positions of regulation valves in % separated by ';'
@@ -24,9 +21,6 @@ namespace Config.Entities
public virtual string ValvesOpen { get; set; }
public virtual string ValvesClose { get; set; }
public virtual bool QfromTextChngd { get; set; } /// Not mapped to database, used in ProcedureDlg / Metrology1Tab
public virtual bool QtoTextChngd { get; set; } /// Not mapped to database, used in ProcedureDlg / Metrology1Tab
/// ------------- Additional stuff not mapped into the database -------------
public FeedingPath()
@@ -46,14 +40,12 @@ namespace Config.Entities
{
FeedingPath result = new FeedingPath(name, itemNr);
result.Qfrom = Qfrom;
result.Qto = Qto;
result.FlowUnit = FlowUnit;
result.Selector = Selector;
result.Pump = Pump;
result.Qfrom = Qfrom;
result.Qto = Qto;
result.Pump = Pump;
result.RegulValvesPct = RegulValvesPct;
result.ValvesOpen = ValvesOpen;
result.ValvesClose = ValvesClose;
result.ValvesOpen = ValvesOpen;
result.ValvesClose = ValvesClose;
return result;
}
+2 -2
View File
@@ -9,7 +9,7 @@ namespace Config.Entities
public class Group
{
public virtual int Id { get; protected set; }
public virtual Common.GID GID { get; set; }
public virtual Users.Entities.GID GID { get; set; }
public virtual long AccessFlags { get; set; } /// Bitfield of access flags: bit0 .. bit62
public virtual IList<User> Users { get; set; } /// Group can be a member of a list of users
@@ -18,7 +18,7 @@ namespace Config.Entities
Users = new List<User>();
}
public Group(Common.GID gid)
public Group(Users.Entities.GID gid)
: this()
{
GID = gid;
@@ -1,11 +1,11 @@
///
/// Copyright (c) 2013-2021 Sensus Slovensko a.s.
/// Copyright (c) 2013-2018 Sensus Slovensko a.s.
///
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
namespace Common
namespace Config.Entities
{
public interface IParamsProvider
{
@@ -31,7 +31,7 @@ namespace Common
/// Returns a list of possible values of one parameter (ComboBox when editing) or null (Textbox when editing).
/// </summary>
/// <param name="ix">Zero based index of the parameter</param>
ICollection<string> ParamValues(int ix);
IList<string> ParamValues(int ix);
/// <summary>
/// Returns a parameter value in the string form
+44
View File
@@ -0,0 +1,44 @@
///
/// Copyright (c) 2018 Sensus Slovensko a.s.
///
using System;
namespace Config.Entities
{
public enum Side
{
#if LANG_CS
[Description("Levá")] Left,
[Description("Pravá")] Right,
#else
[Description("Left")] Left,
[Description("Right")] Right,
#endif
Count
}
public enum FlowDir
{
R_L,
L_R,
Count
}
public enum Counting
{
Arbitrary,
Positive,
Negative,
Count
}
public enum OptoHeadState
{
Disabled,
OptoAndDirOK,
OptoNok,
DirNok,
Count
}
}
+5 -69
View File
@@ -1,17 +1,16 @@
///
/// Copyright (c) 2013-2022 Sensus Slovensko a.s.
/// Copyright (c) 2013-2018 Sensus Slovensko a.s.
///
using System;
using System.Collections.Generic;
namespace Config.Entities
{
public class MeasurementCorrection : Common.IMeasurementCorrection, IComparable<MeasurementCorrection>
public class MeasurementCorrection
{
public virtual int Id { get; protected set; }
public virtual int RangeIx { get; set; } /// 0..5
public virtual double Measurement { get; set; }
public virtual double Correction { get; set; }
public virtual float Measurement { get; set; }
public virtual float Correction { get; set; }
public MeasurementCorrection()
{
@@ -22,68 +21,5 @@ namespace Config.Entities
{
RangeIx = rangeIx;
}
public virtual int CompareTo(MeasurementCorrection other)
{
return (Measurement > other.Measurement) ? 1 : ((Measurement == other.Measurement) ? 0 : -1);
}
/// <summary>
/// Calculates corrected value from a list of corrections by interpolation.
/// It is assumed that values in the list 'corrections' are sorted.
/// </summary>
/// <param name="rawMeasurement">Raw uncorrected value</param>
/// <param name="corrections">Sorted (value, correction) pairs</param>
/// <returns>Corrected value</returns>
public static double CorrectedValue(double rawValue, IList<MeasurementCorrection> corrections)
{
return rawValue + GetCorrection(rawValue, corrections);
}
/// <summary>
/// Get a correction from a list of corrections by interpolation.
/// It is assumed that values in the list 'corrections' are sorted.
/// </summary>
/// <param name="rawMeasurement">Raw uncorrected value</param>
/// <param name="corrections">Sorted (value, correction) pairs</param>
/// <returns>Corrected value</returns>
public static double GetCorrection(double rawValue, IList<MeasurementCorrection> corrections)
{
if ((corrections == null) || (corrections.Count == 0)) return 0; /// No correction
if (rawValue < corrections[0].Measurement)
{
/// rawValue is below the lowest value in the correction table
return corrections[0].Correction;
}
for (int i = 1; i < corrections.Count; i++)
{
if (rawValue < corrections[i].Measurement)
{
double d1 = rawValue - corrections[i - 1].Measurement;
double d2 = corrections[i].Measurement - rawValue;
if (d1 + d2 <= float.Epsilon)
{
/// Neigboring values in the corection table are close to each other -> calculate the average
return (corrections[i - 1].Correction + corrections[i].Correction) / 2.0;
}
else
{
/// Interpolate the correction from neigboring values in the corection table
return (corrections[i - 1].Correction * d2 + corrections[i].Correction * d1) / (d1 + d2);
}
}
}
/// rawValue is above the highest value in the correction table
return corrections[corrections.Count - 1].Correction;
}
public override string ToString()
{
return string.Format("{0} {1} ({2})", Measurement, Correction, RangeIx);
}
}
}
}
+21 -29
View File
@@ -1,45 +1,39 @@
///
/// Copyright (c) 2013-2022 Sensus Slovensko a.s.
/// Copyright (c) 2013-2017 Sensus Metering Systems
///
using System;
using System.Collections.Generic;
using Common;
namespace Config.Entities
{
public class OutputPath : IHasName, IHasItemNr, IHasValves
{
public virtual int Id { get; protected set; }
public virtual int ItemNr { get; set; }
public virtual int Id { get; protected set; }
public virtual int ItemNr { get; set; }
public virtual string Name { get; set; }
public virtual string OriName { get; set; } /// Not mapped to database
public virtual float Qfrom { get; set; } /// Water flow in [m3/h]
public virtual float Qto { get; set; } /// Water flow in [m3/h]
public virtual Unit FlowUnit { get; set; } /// Not mapped to database, used in UI
public virtual string Selector { get; set; }
public virtual float Qfrom { get; set; } /// Water flow in [m3/h]
public virtual float Qto { get; set; } /// Water flow in [m3/h]
public virtual string RegulValve { get; set; }
public virtual string FlowMeter { get; set; }
public virtual float PidCoef { get; set; } /// PID coefficient for the regulation path
public virtual float PidCoef { get; set; } /// PID coefficient for the regulation path
public virtual string StartValve { get; set; }
public virtual string Diverter { get; set; }
public virtual string TempDiv { get; set; }
public virtual string Scale { get; set; }
public virtual string RegulValvesPct { get; set; } /// Positions of regulation valves in % separated by ';'
public virtual string EmptyTankValve { get; set; } /// Not used anywhere
/// Valves
public virtual string ValvesOpen { get; set; }
public virtual string ValvesClose { get; set; }
public virtual bool QfromTextChngd { get; set; } /// Not mapped to database, used in ProcedureDlg / Metrology1Tab
public virtual bool QtoTextChngd { get; set; } /// Not mapped to database, used in ProcedureDlg / Metrology1Tab
/// ------------- Additional stuff not mapped into the database -------------
public OutputPath()
{
ValvesOpen = string.Empty;
ValvesClose = string.Empty;
}
}
public OutputPath(string name, int itemNr)
: this()
@@ -52,21 +46,19 @@ namespace Config.Entities
{
OutputPath result = new OutputPath(name, itemNr);
result.Name = Name;
result.Qfrom = Qfrom;
result.Qto = Qto;
result.FlowUnit = FlowUnit;
result.Selector = Selector;
result.RegulValve = RegulValve;
result.FlowMeter = FlowMeter;
result.PidCoef = PidCoef;
result.StartValve = StartValve;
result.Diverter = Diverter;
result.TempDiv = TempDiv;
result.Scale = Scale;
result.RegulValvesPct = RegulValvesPct;
result.ValvesOpen = ValvesOpen;
result.ValvesClose = ValvesClose;
result.Name = Name;
result.Qfrom = Qfrom;
result.Qto = Qto;
result.RegulValve = RegulValve;
result.FlowMeter = FlowMeter;
result.PidCoef = PidCoef;
result.StartValve = StartValve;
result.Diverter = Diverter;
result.TempDiv = TempDiv;
result.Scale = Scale;
result.EmptyTankValve = EmptyTankValve;
result.ValvesOpen = ValvesOpen;
result.ValvesClose = ValvesClose;
return result;
}
+4 -29
View File
@@ -1,10 +1,9 @@
///
/// Copyright (c) 2019-2022 Sensus Slovensko a.s.
/// Copyright (c) 2019 Sensus Slovensko a.s.
///
using System;
using System.Globalization;
using System.IO;
using Common;
namespace Config.Entities
{
@@ -27,7 +26,6 @@ namespace Config.Entities
public virtual double PressLimHi { get; set; } /// [bar] max. water pressure
public virtual sbyte Publish { get; set; } /// 0=no, 1=in all protocols, 2=on screen, 3=internal
public virtual bool Evaluate { get; set; }
public virtual string Method { get; set; } /// Test method (component name)
public virtual sbyte E1 { get; set; } ///
public virtual sbyte E2 { get; set; } ///
@@ -80,9 +78,8 @@ namespace Config.Entities
TempLimHi = 25.0; /// [°C]
PressLimLo = 0; /// [bar]
PressLimHi = 16.0; /// [bar]
Publish = (sbyte)Common.Publish.Always;
Publish = (sbyte)Config.Entities.Publish.Always;
Evaluate = true;
Method = string.Empty;
E1 = (sbyte)ErrorFlagsMode.On;
E2 = (sbyte)ErrorFlagsMode.On;
@@ -142,7 +139,6 @@ namespace Config.Entities
result.PressLimHi = PressLimHi;
result.Publish = Publish;
result.Evaluate = Evaluate;
result.Method = Method;
result.E1 = E1;
result.E2 = E2;
@@ -196,7 +192,6 @@ namespace Config.Entities
output.WriteLine(PressLimHi.ToString(ci));
output.WriteLine(Publish.ToString());
output.WriteLine(Evaluate.ToString());
output.WriteLine(Method);
output.WriteLine(E1.ToString());
output.WriteLine(E2.ToString());
@@ -251,29 +246,10 @@ namespace Config.Entities
tst.ErrLimHi = double.Parse(input.ReadLine(), ci);
tst.TempLimLo = double.Parse(input.ReadLine(), ci);
tst.TempLimHi = double.Parse(input.ReadLine(), ci);
tst.PressLimLo = double.Parse(input.ReadLine(), ci);
tst.PressLimHi = double.Parse(input.ReadLine(), ci);
tst.Publish = sbyte.Parse(input.ReadLine(), ci);
tst.Publish = sbyte.Parse(input.ReadLine());
tst.Evaluate = bool.Parse(input.ReadLine());
tst.Method = input.ReadLine();
tst.E1 = sbyte.Parse(input.ReadLine(), ci);
tst.E2 = sbyte.Parse(input.ReadLine(), ci);
tst.E3 = sbyte.Parse(input.ReadLine(), ci);
tst.E4 = sbyte.Parse(input.ReadLine(), ci);
tst.E5 = sbyte.Parse(input.ReadLine(), ci);
tst.E6 = sbyte.Parse(input.ReadLine(), ci);
tst.E7 = sbyte.Parse(input.ReadLine(), ci);
tst.E8 = sbyte.Parse(input.ReadLine(), ci);
tst.E9 = sbyte.Parse(input.ReadLine(), ci);
tst.E10 = sbyte.Parse(input.ReadLine(), ci);
tst.E11 = sbyte.Parse(input.ReadLine(), ci);
tst.E12 = sbyte.Parse(input.ReadLine(), ci);
tst.E13 = sbyte.Parse(input.ReadLine(), ci);
tst.E14 = sbyte.Parse(input.ReadLine(), ci);
tst.E15 = sbyte.Parse(input.ReadLine(), ci);
tst.E16 = sbyte.Parse(input.ReadLine(), ci);
tst.E21 = sbyte.Parse(input.ReadLine(), ci);
/// TODO (E1 .. E21)
tst.Delta_Q_pct = double.Parse(input.ReadLine(), ci);
tst.Delta_T = double.Parse(input.ReadLine(), ci);
@@ -316,7 +292,6 @@ namespace Config.Entities
ln = inp.ReadLine(); if (ln != PressLimHi.ToString(ci)) { diff.AppendFormat(fmt, "Pressure_max", PressLimHi.ToString(ci), ln); };
ln = inp.ReadLine(); if (ln != Publish.ToString()) { diff.AppendFormat(fmt, "Publish", Publish.ToString(), ln); };
ln = inp.ReadLine(); if (ln != Evaluate.ToString()) { diff.AppendFormat(fmt, "Evaluate", Evaluate.ToString(), ln); };
ln = inp.ReadLine(); if (ln != Method) { diff.AppendFormat(fmt, "Method", Method, ln); };
ln = inp.ReadLine(); if (ln != E1.ToString()) { diff.AppendFormat(fmt, "E1", E1.ToString(), ln); };
ln = inp.ReadLine(); if (ln != E2.ToString()) { diff.AppendFormat(fmt, "E2", E2.ToString(), ln); };
+9 -74
View File
@@ -1,18 +1,17 @@
///
/// Copyright (c) 2013-2021 Sensus Slovensko a.s.
/// Copyright (c) 2013-2020 Sensus Slovensko a.s.
///
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using Common;
namespace Config.Entities
{
/// <summary>
/// Stores one test procedure, supports revisions and history log
/// </summary>
public class Procedure : IHasName, IHasItemNr
public class Procedure : IHasName, IHasItemNr
{
public virtual int Id { get; protected set; }
public virtual int ItemNr { get; set; }
@@ -47,20 +46,21 @@ namespace Config.Entities
public virtual int AltProcPeriod { get; set; } /// Period of alternative procedures (0 = no alt. procedure)
public virtual float DN { get; set; } /// Not mapped to DB, valid in ProceduresCtrl for procedure filtering only
public virtual double Qn { get; set; } /// - ' ' -
public virtual float Qn { get; set; } /// - ' ' -
public virtual string MClass { get; set; } /// - ' ' -
public virtual string Producer { get; set; } /// - ' ' -
public virtual IList<ComponentProcedure> MoreParams { get; set; }
public virtual IList<Test> Tests { get; set; }
TestInstance[] testInstances;
/// Wrapper
public virtual IList<Test> RegularTests()
{
IList<Test> rslt = new List<Test>();
foreach (var t in Tests) if (t.IsRegular()) rslt.Add(t);
foreach (var t in Tests)
{
if ((t.Name.Length > 0 && t.Name[0] != '[') || !t.Name.Contains("]")) rslt.Add(t);
}
return rslt;
}
@@ -70,16 +70,15 @@ namespace Config.Entities
{
MoreParams = new List<ComponentProcedure>();
Tests = new List<Test>();
testInstances = null;
///
/// Default values
///
CreationUser = Users.CurrentUser.UserName();
CreationUser = (Users.GlobalData.CurrentUser != null) ? Users.GlobalData.CurrentUser.UserName : null;
CreationTime = DateTime.Now;
LastChgUser = CreationUser;
LastChgTime = CreationTime;
MetersKind = MetersKind.Single;
MetersKind = Entities.MetersKind.Single;
Watermeters = string.Empty;
Description = string.Empty;
LongDescription = string.Empty;
@@ -97,70 +96,6 @@ namespace Config.Entities
ItemNr = itemNr;
}
public virtual TestInstance[] UpdateTestInstances(IList<string> loopStartNames, IList<string> loopEndNames, IList<string> autoTests = null)
{
List<TestInstance> instances = new List<TestInstance>();
if (Tests != null)
{
int i = 0;
while (i < Tests.Count)
{
if (!loopStartNames.Contains(Tests[i].Method) && !loopEndNames.Contains(Tests[i].Method)) /// Loop.End is ignored outside a loop
{
///
/// Outside a loop
///
for (int j = 1; j <= Tests[i].Repeats; j++)
if (Tests[i].BelongsTo(autoTests))
instances.Add(new TestInstance(Tests[i], j));
}
else if (loopStartNames.Contains(Tests[i].Method))
{
///
/// Entering a loop
///
int loopsCount = Tests[i].Repeats;
List<Test> testsInsideLoop = new List<Test>();
i++;
while (i < Tests.Count && !loopEndNames.Contains(Tests[i].Method))
{
///
/// Inside a loop
///
if (Tests[i].Repeats == loopsCount && !loopStartNames.Contains(Tests[i].Method)) /// Loop.Start is ignored inside a loop
{
if (Tests[i].BelongsTo(autoTests))
testsInsideLoop.Add(Tests[i]);
}
i++;
}
///
/// Append instances of tests inside the last loop to the list
///
for (int j = 1; j <= loopsCount; j++)
{
foreach (var t in testsInsideLoop)
instances.Add(new TestInstance(t, j));
}
}
i++;
}
}
testInstances = instances.ToArray();
return testInstances;
}
public virtual TestInstance[] GetTestInstances()
{
return testInstances;
}
public virtual Procedure Clone()
{
Procedure result = new Procedure();
+2 -6
View File
@@ -5,7 +5,6 @@ using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using Common;
namespace Config.Entities
{
@@ -36,7 +35,7 @@ namespace Config.Entities
///
/// Default values
///
CreationUser = Users.CurrentUser.UserName();
CreationUser = (Users.GlobalData.CurrentUser != null) ? Users.GlobalData.CurrentUser.UserName : null;
CreationTime = DateTime.Now;
LastChgUser = CreationUser;
LastChgTime = CreationTime;
@@ -78,8 +77,6 @@ namespace Config.Entities
output.WriteLine(CreationTime.ToString(CultureInfo.InvariantCulture));
output.WriteLine(LastChgUser);
output.WriteLine(LastChgTime.ToString(CultureInfo.InvariantCulture));
output.WriteLine(((sbyte)ProfileType).ToString());
output.WriteLine(((sbyte)ErrorLimitType).ToString());
foreach (var test in Tests) { test.Export(output); }
output.WriteLine();
@@ -98,8 +95,7 @@ namespace Config.Entities
result.CreationTime = DateTime.Parse(input.ReadLine(), CultureInfo.InvariantCulture);
result.LastChgUser = input.ReadLine();
result.LastChgTime = DateTime.Parse(input.ReadLine(), CultureInfo.InvariantCulture);
result.ProfileType = (ProfileType)sbyte.Parse(input.ReadLine());
result.ErrorLimitType = (ErrorLimitType)sbyte.Parse(input.ReadLine());
string line = input.ReadLine();
while (true)
{
+81 -149
View File
@@ -1,11 +1,10 @@
///
/// Copyright (c) 2013-2023 Sensus Slovensko a.s.
/// Copyright (c) 2013-2019 Sensus Slovensko a.s.
///
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using Common;
namespace Config.Entities
{
@@ -22,11 +21,11 @@ namespace Config.Entities
public virtual TestProfile Profile { get; set; } /// UserDefined, Protected, UserDefinedHeatMeter, ProtectedHeatMeter
public virtual sbyte Publish { get; set; } /// 0=no, 1=in all protocols, 2=on screen, 3=internal
public virtual bool DoEvaluate { get; set; }
public virtual double Qtg { get; set; } /// Target water flow [m3/h]
public virtual double Qfrom { get; set; } /// Water flow low limit in [m3/h]
public virtual double Qto { get; set; } /// Water flow high limit in [m3/h]
public virtual double Volume { get; set; } /// Test volume (target) in [l]
public virtual double TestTime { get; set; } /// Test time (estimate) in [s]
public virtual float Qtg { get; set; } /// Target water flow [m3/h]
public virtual float Qfrom { get; set; } /// Water flow low limit in [m3/h]
public virtual float Qto { get; set; } /// Water flow high limit in [m3/h]
public virtual float Volume { get; set; } /// Test volume (target) in [l]
public virtual float TstTime { get; set; } /// Test time (estimate) in [s]
public virtual string Method { get; set; }
public virtual float ErrLimLo { get; set; } /// in [%] usually < 0, in case of heat meters: 1=class1, 2=class2, 3=class3
public virtual float ErrLimHi { get; set; } /// in [%] usually > 0, in case of heat meters: -Qn in m3/h
@@ -34,10 +33,10 @@ namespace Config.Entities
public virtual int Repeats { get; set; }
public virtual bool DoDraining { get; set; }
public virtual bool DoDrainingAfter { get; set; }
public virtual bool DoControlWaterTemp { get; set; }
public virtual float TempLimLo { get; set; } /// Lower limit for the controlled temperature
public virtual float TempLimHi { get; set; } /// Upper limit for the controlled temperature
public virtual string TempControl { get; set; } /// Water temperature controller, null or empty = Do not control water temp
public virtual float PumpPower { get; set; } /// Power of the pump in [%] in the range 0 .. 100.0f, use values 0% and 100% for non-FM pumps
public virtual float PumpPower { get; set; } /// Power of the pump in [%] in the range 0 .. 100.0f, use values 0% and 100% for non-FM pumps
public virtual int MassRepeats { get; set; } /// Number of mass. measurements at the beginning/end of test, 0 = default (=5)
public virtual float MassSpread { get; set; } /// Max spread of mass. measurements at the beginning/end of test, 0 = default
public virtual MassMethod MassMethod { get; set; } /// method of mass. measurement at the beginning/end of test: false=slow (precise), true=using immediate mass measurement and evaluation
@@ -45,7 +44,7 @@ namespace Config.Entities
public virtual int TimeFlow2Mass { get; set; } /// Delay time from the flow stable to the 1st mass measurement in [s]
public virtual int TimePump2StartV { get; set; } /// Delay time from the start of the pump to opening the start valve in [s]
public virtual int TimeStop2Mass { get; set; } /// Delay time from the test end (diverted) to the 2nd mass measuremen in [s]
public virtual double ShortPulses { get; set; } /// = Filter
public virtual double TolerRed { get; set; } /// = Filter
public virtual string RedType { get; set; }
public virtual string FeedingPath { get; set; }
public virtual string BenchPath { get; set; }
@@ -54,32 +53,12 @@ namespace Config.Entities
#if HEAT_METERS
public virtual string HeatMetersPath { get; set; }
#endif
public virtual string TransBefore { get; set; }
public virtual string TransBetween { get; set; }
public virtual string TransAfter { get; set; }
#if ORACLE_DB
public virtual int OraId { get; set; }
public virtual int OraIdRepetMulti { get; set; }
public virtual string OraDesignation { get; set; }
public virtual int RawDataId { get; set; }
public virtual int RawDataIdRepetMulti { get; set; }
public virtual string RawDataDesignation { get; set; }
#endif
public virtual bool IsOuterLoopStart { get; set; } /// Not mapped to database
public virtual bool IsOuterLoopEnd { get; set; } /// Not mapped to database
public virtual string RelTransBefore { get; set; }
public virtual string RelTransBetween { get; set; }
public virtual string TransitionAfter { get; set; }
public virtual bool QtgTextChngd { get; set; } /// Not mapped to database, used in ProcedureDlg / Metrology1Tab
public virtual bool QfromTextChngd { get; set; } /// Not mapped to database, used in ProcedureDlg / Metrology1Tab
public virtual bool QtoTextChngd { get; set; } /// Not mapped to database, used in ProcedureDlg / Metrology1Tab
public virtual bool VolumeTextChngd { get; set; } /// Not mapped to database, used in ProcedureDlg / Metrology1Tab
public virtual bool TempLimLoTextChngd { get; set; } /// Not mapped to database, used in ProcedureDlg / Metrology1Tab
public virtual bool TempLimHiTextChngd { get; set; } /// Not mapped to database, used in ProcedureDlg / Metrology1Tab
public virtual Unit VolumeUnit { get; set; } /// Not mapped to database, used in ProcedureDlg / Metrology1Tab
public virtual Unit FlowUnit { get; set; } /// Not mapped to database, used in ProcedureDlg / Metrology1Tab
public virtual Unit MassUnit { get; set; } /// Not mapped to database, used in ProcedureDlg / Metrology1Tab
public virtual Unit TempUnit { get; set; } /// Not mapped to database, used in ProcedureDlg / Metrology1Tab
public virtual Unit PressUnit { get; set; } /// Not mapped to database, used in ProcedureDlg / Metrology1Tab
public virtual Unit LengthUnit { get; set; } /// Not mapped to database, used in ProcedureDlg / Metrology1Tab
public virtual bool IsOuterLoopStart { get; set; } /// Not mapped to database
public virtual bool IsOuterLoopEnd { get; set; } /// Not mapped to database
public virtual IList<ComponentTest> MoreParams { get; set; }
@@ -96,38 +75,30 @@ namespace Config.Entities
///
Part = 0;
Profile = TestProfile.UserDefined;
Publish = (sbyte)Common.Publish.Always;
Publish = (sbyte)Config.Entities.Publish.Always;
DoEvaluate = true;
ErrLimLo = -2.0f; /// [%] lower error limit
ErrLimHi = 2.0f; /// [%] upper error limit
Uncertainty = 0;
Repeats = 1;
Repeats = 1;
DoDraining = false;
DoDrainingAfter = false;
DoControlWaterTemp = false;
TempLimLo = 15.0f;
TempLimHi = 25.0f;
TempControl = string.Empty;
ErrLimLo = -2.0f; /// [%] lower error limit
ErrLimHi = 2.0f; /// [%] upper error limit
Uncertainty = 0;
PumpPower = 60.0f; /// [%]
MassRepeats = 0; /// default
MassSpread = 0; /// default
MassMethod = MassMethod.Scale; /// default
MassMethod = MassMethod.Scale; /// default
TimeBeforeFlow = 10; /// [s] time before the start of flow control in [s]
TimeFlow2Mass = 5; /// [s] time from the flow stable to the 1st mass measurement in [s]
TimePump2StartV = 1; /// [s] time from the 1st mass measurement to the test start in [s]
TimeStop2Mass = 5; /// [s] between the test end and the final mass measurement
ShortPulses = 0; /// Short pulses parameter (0 or 1)
TransBefore = string.Empty;
TransBetween = string.Empty;
TransAfter = string.Empty;
#if ORACLE_DB
OraId = 0;
OraIdRepetMulti = 0;
OraDesignation = string.Empty;
RawDataId = 0;
RawDataIdRepetMulti = 0;
RawDataDesignation = string.Empty;
#endif
}
TolerRed = 0; /// = Filter parameter
RelTransBefore = string.Empty;
RelTransBetween = string.Empty;
TransitionAfter = string.Empty;
}
public Test(string name, int itemNr, Procedure procedure)
: this()
@@ -137,32 +108,6 @@ namespace Config.Entities
Procedure = procedure;
}
public virtual bool IsRegular()
{
/// Irregular / event triggered test names have form "[event] TestName"
return (Name.Length > 0 && Name[0] != '[') || !Name.Contains("]");
}
public virtual bool BelongsTo(IList<string> autoTests)
{
if (IsRegular()) return true;
if (autoTests == null) return false;
string action = Name.Substring(1, Name.IndexOf(']') - 1);
return autoTests.Contains(action);
}
public virtual void ResetChngdFlags()
{
QtgTextChngd = false;
QfromTextChngd = false;
QtoTextChngd = false;
VolumeTextChngd = false;
TempLimLoTextChngd = false;
TempLimHiTextChngd = false;
}
// Makes a new copy of this object (not just a reference)
public virtual Test Clone()
{
@@ -176,7 +121,7 @@ namespace Config.Entities
result.Qfrom = Qfrom;
result.Qto = Qto;
result.Volume = Volume;
result.TestTime = TestTime;
result.TstTime = TstTime;
result.Method = Method;
result.ErrLimLo = ErrLimLo;
result.ErrLimHi = ErrLimHi;
@@ -184,10 +129,10 @@ namespace Config.Entities
result.Repeats = Repeats;
result.DoDraining = DoDraining;
result.DoDrainingAfter = DoDrainingAfter;
result.DoControlWaterTemp = DoControlWaterTemp;
result.TempLimLo = TempLimLo;
result.TempLimHi = TempLimHi;
result.TempControl = TempControl;
result.PumpPower = PumpPower;
result.PumpPower = PumpPower;
result.MassRepeats = MassRepeats;
result.MassSpread = MassSpread;
result.MassMethod = MassMethod;
@@ -195,7 +140,7 @@ namespace Config.Entities
result.TimeFlow2Mass = TimeFlow2Mass;
result.TimePump2StartV = TimePump2StartV;
result.TimeStop2Mass = TimeStop2Mass;
result.ShortPulses = ShortPulses;
result.TolerRed = TolerRed;
result.RedType = RedType;
result.FeedingPath = FeedingPath;
result.BenchPath = BenchPath;
@@ -204,24 +149,10 @@ namespace Config.Entities
#if HEAT_METERS
result.HeatMetersPath = HeatMetersPath;
#endif
result.TransBefore = TransBefore;
result.TransBetween = TransBetween;
result.TransAfter = TransAfter;
#if ORACLE_DB
result.OraId = OraId;
result.OraIdRepetMulti = OraIdRepetMulti;
result.OraDesignation = OraDesignation;
result.RawDataId = RawDataId;
result.RawDataIdRepetMulti = RawDataIdRepetMulti;
result.RawDataDesignation = RawDataDesignation;
#endif
result.VolumeUnit = VolumeUnit;
result.FlowUnit = FlowUnit;
result.MassUnit = MassUnit;
result.TempUnit = TempUnit;
result.PressUnit = PressUnit;
result.LengthUnit = LengthUnit;
foreach (var prms in MoreParams) { result.MoreParams.Add(prms.Clone()); }
result.RelTransBefore = RelTransBefore;
result.RelTransBetween = RelTransBetween;
result.TransitionAfter = TransitionAfter;
foreach (var prms in MoreParams) { result.MoreParams.Add(prms.Clone()); }
return result;
}
@@ -238,7 +169,7 @@ namespace Config.Entities
output.WriteLine(Qfrom.ToString(ci));
output.WriteLine(Qto.ToString(ci));
output.WriteLine(Volume.ToString(ci));
output.WriteLine(TestTime.ToString(ci));
output.WriteLine(TstTime.ToString(ci));
output.WriteLine(Method);
output.WriteLine(ErrLimLo.ToString(ci));
output.WriteLine(ErrLimHi.ToString(ci));
@@ -246,10 +177,10 @@ namespace Config.Entities
output.WriteLine(Repeats.ToString(ci));
output.WriteLine(DoDraining.ToString());
output.WriteLine(DoDrainingAfter.ToString());
output.WriteLine(DoControlWaterTemp.ToString());
output.WriteLine(TempLimLo.ToString(ci));
output.WriteLine(TempLimHi.ToString(ci));
output.WriteLine((TempControl != null) ? TempControl : string.Empty);
output.WriteLine(PumpPower.ToString(ci));
output.WriteLine(PumpPower.ToString(ci));
output.WriteLine(MassRepeats.ToString(ci));
output.WriteLine(MassSpread.ToString(ci));
output.WriteLine(((byte)MassMethod).ToString(ci));
@@ -261,18 +192,11 @@ namespace Config.Entities
output.WriteLine(BenchPath);
output.WriteLine(OutputPath);
output.WriteLine(MetersPath);
output.WriteLine(TransBefore);
output.WriteLine(TransBetween);
output.WriteLine(RelTransBefore);
output.WriteLine(RelTransBetween);
output.WriteLine(Profile);
output.WriteLine(TransAfter);
#if ORACLE_DB
output.WriteLine(OraId);
output.WriteLine(OraIdRepetMulti);
output.WriteLine(OraDesignation);
output.WriteLine(RawDataId);
output.WriteLine(RawDataIdRepetMulti);
output.WriteLine(RawDataDesignation);
#endif
output.WriteLine(TransitionAfter);
foreach (var prms in MoreParams) { prms.Export(output); }
output.WriteLine();
}
@@ -292,11 +216,11 @@ namespace Config.Entities
tst.Part = int.Parse(input.ReadLine(), ci);
tst.Publish = sbyte.Parse(input.ReadLine(), ci);
tst.DoEvaluate = bool.Parse(input.ReadLine());
tst.Qtg = double.Parse(input.ReadLine(), ci);
tst.Qfrom = double.Parse(input.ReadLine(), ci);
tst.Qto = double.Parse(input.ReadLine(), ci);
tst.Volume = double.Parse(input.ReadLine(), ci);
tst.TestTime = double.Parse(input.ReadLine(), ci);
tst.Qtg = float.Parse(input.ReadLine(), ci);
tst.Qfrom = float.Parse(input.ReadLine(), ci);
tst.Qto = float.Parse(input.ReadLine(), ci);
tst.Volume = float.Parse(input.ReadLine(), ci);
tst.TstTime = float.Parse(input.ReadLine(), ci);
tst.Method = input.ReadLine();
tst.ErrLimLo = float.Parse(input.ReadLine(), ci);
tst.ErrLimHi = float.Parse(input.ReadLine(), ci);
@@ -304,10 +228,10 @@ namespace Config.Entities
tst.Repeats = int.Parse(input.ReadLine(), ci);
tst.DoDraining = bool.Parse(input.ReadLine());
tst.DoDrainingAfter = bool.Parse(input.ReadLine());
tst.DoControlWaterTemp = bool.Parse(input.ReadLine());
tst.TempLimLo = float.Parse(input.ReadLine(), ci);
tst.TempLimHi = float.Parse(input.ReadLine(), ci);
tst.TempControl = input.ReadLine();
tst.PumpPower = float.Parse(input.ReadLine(), ci);
tst.PumpPower = float.Parse(input.ReadLine(), ci);
tst.MassRepeats = int.Parse(input.ReadLine(), ci);
tst.MassSpread = float.Parse(input.ReadLine(), ci);
tst.MassMethod = (MassMethod)byte.Parse(input.ReadLine(), ci);
@@ -319,21 +243,13 @@ namespace Config.Entities
tst.BenchPath = input.ReadLine();
tst.OutputPath = input.ReadLine();
tst.MetersPath = input.ReadLine();
tst.TransBefore = input.ReadLine();
tst.TransBetween = input.ReadLine();
tst.RelTransBefore = input.ReadLine();
tst.RelTransBetween = input.ReadLine();
string line = input.ReadLine();
tst.Profile = line.Equals(TestProfile.ProtectedHeatMeter.ToString()) ? TestProfile.ProtectedHeatMeter
: line.Equals(TestProfile.UserDefinedHeatMeter.ToString()) ? TestProfile.UserDefinedHeatMeter
: line.Equals(TestProfile.Protected.ToString()) ? TestProfile.Protected : TestProfile.UserDefined; /// UserDefined is the default
tst.TransAfter = input.ReadLine();
#if ORACLE_DB
tst.OraId = int.Parse(input.ReadLine(), ci);
tst.OraIdRepetMulti = int.Parse(input.ReadLine(), ci);
tst.OraDesignation = input.ReadLine();
tst.RawDataId = int.Parse(input.ReadLine(), ci);
tst.RawDataIdRepetMulti = int.Parse(input.ReadLine(), ci);
tst.RawDataDesignation = input.ReadLine();
#endif
tst.TransitionAfter = input.ReadLine();
while (true)
{
@@ -366,7 +282,7 @@ namespace Config.Entities
ln = inp.ReadLine(); if (ln != Qfrom.ToString(ci)) { diff.AppendFormat(fmt, "Qfrom", Qfrom.ToString(ci), ln); };
ln = inp.ReadLine(); if (ln != Qto.ToString(ci)) { diff.AppendFormat(fmt, "Qto", Qto.ToString(ci), ln); };
ln = inp.ReadLine(); if (ln != Volume.ToString(ci)) { diff.AppendFormat(fmt, "Volume", Volume.ToString(ci), ln); };
ln = inp.ReadLine(); if (ln != TestTime.ToString(ci)) { diff.AppendFormat(fmt, "TstTime", TestTime.ToString(ci), ln); };
ln = inp.ReadLine(); if (ln != TstTime.ToString(ci)) { diff.AppendFormat(fmt, "TstTime", TstTime.ToString(ci), ln); };
ln = inp.ReadLine(); if (ln != Method) { diff.AppendFormat(fmt, "Method", Method, ln); };
ln = inp.ReadLine(); if (ln != ErrLimLo.ToString(ci)) { diff.AppendFormat(fmt, "ErrLimLo", ErrLimLo.ToString(ci), ln); };
ln = inp.ReadLine(); if (ln != ErrLimHi.ToString(ci)) { diff.AppendFormat(fmt, "ErrLimHi", ErrLimHi.ToString(ci), ln); };
@@ -374,9 +290,9 @@ namespace Config.Entities
ln = inp.ReadLine(); if (ln != Repeats.ToString(ci)) { diff.AppendFormat(fmt, "Repeats", Repeats.ToString(ci), ln); };
ln = inp.ReadLine(); if (ln != DoDraining.ToString(ci)) { diff.AppendFormat(fmt, "Draining", DoDraining.ToString(ci), ln); };
ln = inp.ReadLine(); if (ln != DoDrainingAfter.ToString(ci)) { diff.AppendFormat(fmt, "Zeroing", DoDrainingAfter.ToString(ci), ln); };
ln = inp.ReadLine(); if (ln != DoControlWaterTemp.ToString()) { diff.AppendFormat(fmt, "DoControlWaterTemp", DoControlWaterTemp.ToString(ci), ln); };
ln = inp.ReadLine(); if (ln != TempLimLo.ToString(ci)) { diff.AppendFormat(fmt, "TempLimLo", TempLimLo.ToString(ci), ln); };
ln = inp.ReadLine(); if (ln != TempLimHi.ToString(ci)) { diff.AppendFormat(fmt, "TempLimHi", TempLimHi.ToString(ci), ln); };
ln = inp.ReadLine(); if (ln != TempControl) { diff.AppendFormat(fmt, "TempController", TempControl, ln); };
ln = inp.ReadLine(); if (ln != PumpPower.ToString(ci)) { diff.AppendFormat(fmt, "PumpPower", PumpPower.ToString(ci), ln); };
ln = inp.ReadLine(); if (ln != MassRepeats.ToString(ci)) { diff.AppendFormat(fmt, "MassRepeats", MassRepeats.ToString(ci), ln); };
ln = inp.ReadLine(); if (ln != MassSpread.ToString(ci)) { diff.AppendFormat(fmt, "MassSpread", MassSpread.ToString(ci), ln); };
@@ -389,18 +305,11 @@ namespace Config.Entities
ln = inp.ReadLine(); if (ln != BenchPath) { diff.AppendFormat(fmt, "BenchPath", BenchPath, ln); };
ln = inp.ReadLine(); if (ln != OutputPath) { diff.AppendFormat(fmt, "OutputPath", OutputPath, ln); };
ln = inp.ReadLine(); if (ln != MetersPath) { diff.AppendFormat(fmt, "MetersPath", MetersPath, ln); };
ln = inp.ReadLine(); if (ln != TransBefore) { diff.AppendFormat(fmt, "RelTransBefore", TransBefore, ln); };
ln = inp.ReadLine(); if (ln != TransBetween) { diff.AppendFormat(fmt, "RelTransBetween", TransBetween, ln); };
ln = inp.ReadLine(); if (ln != Profile.ToString()) { diff.AppendFormat(fmt, "RelTransAfter", Profile, ln); };
ln = inp.ReadLine(); if (ln != TransAfter) { diff.AppendFormat(fmt, "TransitionAfter", TransAfter, ln); };
#if ORACLE_DB
ln = inp.ReadLine(); if (ln != OraId.ToString(ci)) { diff.AppendFormat(fmt, "OraId", OraId.ToString(ci), ln); };
ln = inp.ReadLine(); if (ln != OraIdRepetMulti.ToString(ci)) { diff.AppendFormat(fmt, "OraIdRepetMulti", OraIdRepetMulti.ToString(ci), ln); };
ln = inp.ReadLine(); if (ln != OraDesignation) { diff.AppendFormat(fmt, "OraDesignation", OraDesignation, ln); };
ln = inp.ReadLine(); if (ln != RawDataId.ToString(ci)) { diff.AppendFormat(fmt, "RawDataId", RawDataId.ToString(ci), ln); };
ln = inp.ReadLine(); if (ln != RawDataIdRepetMulti.ToString(ci)){ diff.AppendFormat(fmt, "RawDataIdRepetMulti", RawDataIdRepetMulti.ToString(ci), ln); };
ln = inp.ReadLine(); if (ln != RawDataDesignation) { diff.AppendFormat(fmt, "RawDataDesignation", RawDataDesignation, ln); };
#endif
ln = inp.ReadLine(); if (ln != RelTransBefore) { diff.AppendFormat(fmt, "RelTransBefore", RelTransBefore, ln); };
ln = inp.ReadLine(); if (ln != RelTransBetween) { diff.AppendFormat(fmt, "RelTransBetween", RelTransBetween, ln); };
ln = inp.ReadLine(); if (ln != Profile.ToString()) { diff.AppendFormat(fmt, "RelTransAfter", Profile, ln); };
ln = inp.ReadLine(); if (ln != TransitionAfter) { diff.AppendFormat(fmt, "TransitionAfter", TransitionAfter, ln); };
return diff.ToString();
}
@@ -500,6 +409,29 @@ namespace Config.Entities
return false;
}
/// <summary>
/// Determines whether tests part number is OK.
/// Examples of correct part number are:
/// 1, 2, 12, 21 in case of max. part nr.== 2
/// 1, 2, 3, 4, 12, 13, 14, 23, 24, 34, 123, 124, 134, 234, 1234 in case of max. part nr.== 4
/// </summary>
/// <param name="partNr">Tests par tnumber</param>
/// <returns>true when Part number is OK</returns>
public static bool IsGoodPartNr(int partNr)
{
bool firstDigitIsOK = ((partNr % 10) > 0) && ((partNr % 10) <= Config.Data.MaxPartNr);
bool secondDigitIsOK = (((partNr/10) % 10) > 0) && (((partNr/10) % 10) <= Config.Data.MaxPartNr);
bool thirdDigitIsOK = (((partNr/100) % 10) > 0) && (((partNr/100) % 10) <= Config.Data.MaxPartNr);
bool fourthDigitIsOK = (((partNr/1000) % 10) > 0) && (((partNr/1000) % 10) <= Config.Data.MaxPartNr);
if (firstDigitIsOK && (partNr / 10 == 0)) return true;
if (firstDigitIsOK && secondDigitIsOK && (partNr / 100 == 0)) return true;
if (firstDigitIsOK && secondDigitIsOK && thirdDigitIsOK && (partNr / 1000 == 0)) return true;
if (firstDigitIsOK && secondDigitIsOK && thirdDigitIsOK && fourthDigitIsOK && (partNr / 10000 == 0)) return true;
return false;
}
public override string ToString()
{
string partStr = (Part > 0) ? string.Format(", part {0}", Part) : string.Empty;
-32
View File
@@ -1,32 +0,0 @@
///
/// Copyright (c) 2021 Sensus Slovensko a.s.
///
using System;
namespace Config.Entities
{
public class TestInstance
{
public Test Test;
public int Repetition;
public string Name
{
get
{
return (Test != null) ? Common.Utils.GetTestName(Test.Name, Test.Repeats, Repetition) : string.Empty;
}
}
public TestInstance(Test test, int repetition)
{
Test = test;
Repetition = repetition;
}
public override string ToString()
{
return Name;
}
}
}
+2 -2
View File
@@ -1,11 +1,11 @@
///
/// Copyright (c) 2019-2021 Sensus Slovensko a.s.
/// Copyright (c) 2019 Sensus Slovensko a.s.
///
using System;
namespace Config.Entities
{
public class Uncertainty : Common.IUncertainty
public class Uncertainty
{
public virtual int Id { get; protected set; }
public virtual float Measurement { get; set; }
+183
View File
@@ -1,10 +1,193 @@
///
/// Copyright (c) 2013-2018 Sensus Slovensko a.s.
///
using System;
using System.Windows.Forms;
using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;
using NHibernate;
using NHibernate.Cfg;
using NHibernate.Tool.hbm2ddl;
using Config.Resources;
namespace Config
{
public static class FluentCommon
{
/// <summary>
/// Session factories for regular sessions.
/// </summary>
public static ISessionFactory[] SessionFactories = new ISessionFactory[(int)Users.Entities.DBKind.Count];
/// <summary>
/// NHibernate session factory (to create the database session 'SessionFactory')
/// </summary>
/// <returns>A database session</returns>
static ISessionFactory CreateSessionFactory(Users.Entities.DBKind database)
{
Users.Entities.DBType dbType;
string connectionString;
switch (database)
{
default:
case Users.Entities.DBKind.Config:
dbType = Data.CurrentBench.ProceduresDBSettings.DbType;
connectionString = Data.CurrentBench.ProceduresDBSettings.ConnectionString;
break;
case Users.Entities.DBKind.Results:
dbType = Data.CurrentBench.WaterMetersDBSettings.DbType;
connectionString = Data.CurrentBench.WaterMetersDBSettings.ConnectionString;
break;
case Users.Entities.DBKind.RemoteConfig:
dbType = Data.CurrentBench.UsersDBSettings.DbType;
connectionString = Data.CurrentBench.UsersDBSettings.ConnectionString;
break;
}
return CreateSessionFactory(database, dbType, connectionString, false);
}
/// <summary>
/// NHibernate session factory (to create the database session 'SessionFactory')
/// </summary>
/// <returns>A database session</returns>
public static ISessionFactory CreateSessionFactory(Users.Entities.DBKind database, Users.Entities.DBType dbType, string connectionString, bool createDB)
{
try
{
FluentConfiguration cfg = Fluently.Configure();
switch (dbType)
{
default:
case Users.Entities.DBType.SQLite:
cfg = cfg.Database(SQLiteConfiguration.Standard.UsingFile(connectionString));
break;
case Users.Entities.DBType.MySql:
cfg = cfg.Database(MySQLConfiguration.Standard.ConnectionString(connectionString));
break;
}
switch (database)
{
default:
case Users.Entities.DBKind.Config:
case Users.Entities.DBKind.RemoteConfig:
cfg = cfg.Mappings(m => m.FluentMappings.AddFromAssemblyOf<Data>());
break;
case Users.Entities.DBKind.Results:
cfg = cfg.Mappings(m => m.FluentMappings.AddFromAssemblyOf<Data>());
break;
}
if (createDB)
{
return cfg.ExposeConfiguration(BuildSchemaCreate).BuildSessionFactory();
}
else
{
return cfg.ExposeConfiguration(BuildSchema).BuildSessionFactory();
}
}
catch (Exception exc)
{
MessageBox.Show(string.Format(Strings.Cannot_open_DB_Cause_0, exc.Message),
Strings.Error,
MessageBoxButtons.OK,
MessageBoxIcon.Error);
return null;
}
}
public delegate void BuildSchemaDlgt(Configuration config);
static void BuildSchema(Configuration config)
{
/// This NHibernate tool takes a configuration (with mapping info in)
/// and exports a database schema from it
new SchemaExport(config).SetOutputFile("db_schema");
}
static void BuildSchemaCreate(Configuration config)
{
/// This NHibernate tool takes a configuration (with mapping info in)
/// and exports a database schema from it
new SchemaExport(config).Create(true, true);
}
/// Create a NHibernate session for the given database
public static ISession CreateSession(Users.Entities.DBKind database)
{
if (database < 0 || database >= Users.Entities.DBKind.Count) return null;
int ix = (int)database;
if (SessionFactories[ix] == null) SessionFactories[ix] = CreateSessionFactory(database);
return SessionFactories[ix].OpenSession();
}
/// <summary>
/// Create an empty users database.
/// Database contains only the user 'admin' and the control board component 'CB'.
/// </summary>
/// <param name="dbType">DBType.SQLite or DBType.MySql</param>
/// <param name="connectionString">Connection string</param>
/// <returns>true=success, false=error</returns>
public static bool CreateEmptyConfigDB(Users.Entities.DBType dbType, string connectionString)
{
ISessionFactory sessionFactory = CreateSessionFactory(Users.Entities.DBKind.Config, dbType, connectionString, true);
if (sessionFactory == null) return false;
/// Populate the database
using (var session = sessionFactory.OpenSession())
{
using (var transaction = session.BeginTransaction())
{
///
/// Create user 'admin'
///
var admin = new Config.Entities.User
{
UserName = Data.AdminUsername,
FullName = Strings.Administrator,
LastPwChange = DateTime.Now
};
admin.SetPassword(Data.AdminPassword);
///
/// Prepare all groups, add some of them to admin
///
for (Users.Entities.GID gid = 0; gid < Users.Entities.GID.NrOfGroups; gid++)
{
Config.Entities.Group group = new Config.Entities.Group(gid);
switch (gid)
{
case Users.Entities.GID.Testers:
case Users.Entities.GID.TestingSpecialists:
case Users.Entities.GID.HeadOfLab:
case Users.Entities.GID.MaintenanceSpecialists:
case Users.Entities.GID.Metrologists:
case Users.Entities.GID.CalibrationSpecialists:
case Users.Entities.GID.Administrators:
#if TURA_IPERL || TURA_IPERL_NEW || TURA_SPECIAL
case Users.Entities.GID.TraceabilityManagement:
#elif KEMPNO_50 || KRAKOW_50 || TORUN_50 || WARSAW_END
case Users.Entities.GID.MetrologicalAuthority:
case Users.Entities.GID.WaterMeterAuthority:
#endif
admin.AddGroup(group);
session.SaveOrUpdate(group); /// Save this group
break;
}
}
session.SaveOrUpdate(admin); /// Save user 'admin'
transaction.Commit();
}
}
return true;
}
}
}
+8 -9
View File
@@ -4,7 +4,6 @@
using System;
using System.Collections.Generic;
using log4net;
using Common;
namespace Config
{
@@ -183,7 +182,7 @@ namespace Config
double theta = temp / 100.0;
double B = x0 * (((x3 * theta + x2) * theta + x1) * theta + 1) / (1 + x4 * theta);
return WaterDensityFromTemp(temp) * (1 + B * Units.ConvertTo(Unit.Pa, pressure));
return WaterDensityFromTemp(temp) * (1 + B * Config.Units.ConvertTo(Config.Unit.Pa, pressure));
}
@@ -214,9 +213,9 @@ namespace Config
/// </summary>
public static double ErrorFromVolumes(double measuredVolume, double trueVolume)
{
if (-float.Epsilon <= trueVolume && trueVolume <= float.Epsilon)
if (trueVolume <= float.Epsilon)
{
if (-float.Epsilon <= measuredVolume && measuredVolume <= float.Epsilon)
if (measuredVolume <= float.Epsilon)
{
log.WarnFormat("ErrorFromVolumes({0},{1}) returns {2}", measuredVolume, trueVolume, -100.0);
return -100.0;
@@ -239,7 +238,7 @@ namespace Config
/// <param name="rawMeasurement">Raw uncorrected value</param>
/// <param name="corrections">Sorted (value, correction) pairs</param>
/// <returns>Corrected value</returns>
public static double CorrectedValue(double rawValue, IList<IMeasurementCorrection> corrections)
public static double CorrectedValue(double rawValue, IList<Config.Entities.MeasurementCorrection> corrections)
{
return rawValue + GetCorrection(rawValue, corrections);
}
@@ -251,7 +250,7 @@ namespace Config
/// <param name="rawMeasurement">Raw uncorrected value</param>
/// <param name="corrections">Sorted (value, correction) pairs</param>
/// <returns>Corrected value</returns>
public static double GetCorrection(double rawValue, IList<IMeasurementCorrection> corrections)
public static double GetCorrection(double rawValue, IList<Config.Entities.MeasurementCorrection> corrections)
{
if ((corrections == null) || (corrections.Count == 0)) return 0; /// No correction
@@ -317,11 +316,11 @@ namespace Config
const double p_star_Pa = 16.53E6; /// [Pa] (=16.53 MPa)
const double T_star = 1386.0; /// [K]
double T_in_K = Units.ConvertTo(Unit.K, T_in);
double T_out_K = Units.ConvertTo(Unit.K, T_out);
double T_in_K = Config.Units.ConvertTo(Config.Unit.K, T_in);
double T_out_K = Config.Units.ConvertTo(Config.Unit.K, T_out);
double tau_in = T_star / T_in_K;
double tau_out = T_star / T_out_K;
double pi = Units.ConvertTo(Unit.Pa, pressure) / p_star_Pa;
double pi = Config.Units.ConvertTo(Config.Unit.Pa, pressure) / p_star_Pa;
double h_in = tau_in * GammaTau(pi, tau_in) * R * T_in_K;
double h_out = tau_out * GammaTau(pi, tau_out) * R * T_out_K;
+2 -3
View File
@@ -1,5 +1,5 @@
///
/// Copyright (c) 2013-2022 Sensus Slovensko a.s.
/// Copyright (c) 2013-2015 Sensus Metering Systems
///
using FluentNHibernate.Mapping;
using Config.Entities;
@@ -15,8 +15,7 @@ namespace Config.Mappings
Map(x => x.Name);
Map(x => x.Qfrom);
Map(x => x.Qto);
Map(x => x.Selector);
Map(x => x.TempMtrUp).Column("TempIn");
Map(x => x.TempMtrUp).Column("TempIn");
Map(x => x.TempMtrDown).Column("TempOut");
Map(x => x.PressMtrUp).Column("PressIn");
Map(x => x.PressMtrDown).Column("PressOut");
+2 -3
View File
@@ -1,5 +1,5 @@
///
/// Copyright (c) 2013-2022 Sensus Slovensko a.s.
/// Copyright (c) 2013-2015 Sensus Metering Systems
///
using FluentNHibernate.Mapping;
using Config.Entities;
@@ -15,8 +15,7 @@ namespace Config.Mappings
Map(x => x.Name);
Map(x => x.Qfrom);
Map(x => x.Qto);
Map(x => x.Selector);
Map(x => x.Pump);
Map(x => x.Pump);
Map(x => x.RegulValvesPct);
Map(x => x.ValvesOpen)
.CustomType("StringClob")
+3 -5
View File
@@ -1,5 +1,5 @@
///
/// Copyright (c) 2013-2022 Sensus Slovensko a.s.
/// Copyright (c) 2013-2015 Sensus Metering Systems
///
using FluentNHibernate.Mapping;
using Config.Entities;
@@ -15,8 +15,7 @@ namespace Config.Mappings
Map(x => x.Name);
Map(x => x.Qfrom);
Map(x => x.Qto);
Map(x => x.Selector);
Map(x => x.RegulValve);
Map(x => x.RegulValve);
Map(x => x.FlowMeter);
Map(x => x.PidCoef);
Map(x => x.StartValve);
@@ -24,8 +23,7 @@ namespace Config.Mappings
Map(x => x.TempDiv);
Map(x => x.Scale)
.Column("Balance");
Map(x => x.RegulValvesPct)
.Column("EmptyTankValve");
Map(x => x.EmptyTankValve);
Map(x => x.ValvesOpen)
.CustomType("StringClob")
.CustomSqlType("varchar(8000)");
-1
View File
@@ -24,7 +24,6 @@ namespace Config.Mappings
Map(x => x.PressLimHi);
Map(x => x.Publish);
Map(x => x.Evaluate);
Map(x => x.Method);
Map(x => x.E1);
Map(x => x.E2);
Map(x => x.E3);
+8 -17
View File
@@ -1,5 +1,5 @@
///
/// Copyright (c) 2013-2022 Sensus Slovensko a.s.
/// Copyright (c) 2013-2017 Sensus Metering Systems
///
using FluentNHibernate.Mapping;
using Config.Entities;
@@ -22,17 +22,16 @@ namespace Config.Mappings
Map(x => x.Qfrom);
Map(x => x.Qto);
Map(x => x.Volume);
Map(x => x.TestTime)
.Column("TstTime");
Map(x => x.TstTime);
Map(x => x.Repeats);
Map(x => x.DoDraining)
.Column("Emptying");
Map(x => x.DoDrainingAfter)
.Column("Zeroing");
Map(x => x.DoControlWaterTemp);
Map(x => x.TempLimLo);
Map(x => x.TempLimHi);
Map(x => x.TempControl);
Map(x => x.PumpPower);
Map(x => x.PumpPower);
Map(x => x.MassRepeats);
Map(x => x.MassSpread);
Map(x => x.MassMethod)
@@ -46,7 +45,7 @@ namespace Config.Mappings
Map(x => x.ErrLimLo);
Map(x => x.ErrLimHi);
Map(x => x.Uncertainty);
Map(x => x.ShortPulses)
Map(x => x.TolerRed)
.Column("TolerRed"); /// ???
Map(x => x.RedType);
Map(x => x.FeedingPath);
@@ -56,20 +55,12 @@ namespace Config.Mappings
#if HEAT_METERS
Map(x => x.HeatMetersPath);
#endif
Map(x => x.TransBefore)
Map(x => x.RelTransBefore)
.Column("RelTransBefore");
Map(x => x.TransBetween)
Map(x => x.RelTransBetween)
.Column("RelTransBetween");
Map(x => x.TransAfter)
Map(x => x.TransitionAfter)
.Column("TransitionAfter");
#if ORACLE_DB
Map(x => x.OraId);
Map(x => x.OraIdRepetMulti);
Map(x => x.OraDesignation);
Map(x => x.RawDataId);
Map(x => x.RawDataIdRepetMulti);
Map(x => x.RawDataDesignation);
#endif
HasMany(x => x.MoreParams)
.Cascade.All();
+3 -3
View File
@@ -10,7 +10,7 @@ using System.Runtime.InteropServices;
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Sensus")]
[assembly: AssemblyProduct("Config")]
[assembly: AssemblyCopyright("Copyright © 2013 - 2022 Sensus Slovensko a.s.")]
[assembly: AssemblyCopyright("Copyright © 2013 - 2018 Sensus Slovensko a.s.")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
@@ -32,5 +32,5 @@ using System.Runtime.InteropServices;
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("2.31.1990.0")]
[assembly: AssemblyFileVersion("2.31.1990.0")]
[assembly: AssemblyVersion("2.26.1519.0")]
[assembly: AssemblyFileVersion("2.26.1519.0")]
+27 -64
View File
@@ -1,9 +1,11 @@
///
/// Copyright (c) 2016-2021 Sensus Slovensko a.s.
/// Copyright (c) 2016-2020 Sensus Slovensko a.s.
///
using System;
using System.Reflection;
using Config.Entities;
namespace Common
namespace Config
{
public enum Unit
{
@@ -24,9 +26,7 @@ namespace Common
[Description("m3")] m3, /// 1 m3 = 1000 l
[Description("l/h")] lph, /// 1 l/h = 0.001 m3/h
[Description("cf/h")] cfph, /// 1 cf/h = 0.028316846592 m3/h
[Description("l/m")] lpm, /// 1 l/m = 60 l/h = 0.06 m3/h
[Description("US gal/m")] USgalpm, /// 1 US gallon per minute = 0.2271247068 m3/h
[Description("m3/h")] m3ph, /// * 1 m3/h
[Description("l/s")] lps, /// 1 liter/s = 3.6 m3/h
[Description("US gal/s")] USgalps, /// 1 US gallon per second = 13.627482408 m3/h
@@ -34,7 +34,6 @@ namespace Common
[Description("cf/s")] cfs, /// 1 cubic foot per second = 101.9406477312 m3/h
[Description("g")] g, /// 0.001 kg
[Description("oz")] oz, /// 0.0283495231 kg
[Description("lb")] lb, /// 0.45359237 kg
[Description("kg")] kg, /// * 1 kilogram
[Description("t")] t, /// 1000 kg
@@ -245,14 +244,14 @@ namespace Common
unit == Unit.J || unit == Unit.uSpcm || unit == Unit.ppl || unit == Unit.ppkWh;
}
public static bool IsQuantity(Unit unit, Quantity quantity)
public static bool IsQuantity(Unit units, Quantity quantity)
{
return (quantity == GetQuantity(unit));
return (quantity == GetQuantity(units));
}
public static Quantity GetQuantity(Unit unit)
public static Quantity GetQuantity(Unit units)
{
switch (unit)
switch (units)
{
case Unit.pulse:
case Unit.degree:
@@ -268,9 +267,7 @@ namespace Common
return Quantity.Volume;
case Unit.lph:
case Unit.cfph:
case Unit.lpm:
case Unit.USgalpm:
case Unit.m3ph:
case Unit.lps:
case Unit.USgalps:
@@ -279,7 +276,6 @@ namespace Common
return Quantity.Flow;
case Unit.g:
case Unit.oz:
case Unit.lb:
case Unit.kg:
case Unit.t:
@@ -357,32 +353,26 @@ namespace Common
}
}
public static bool IsVolume(Unit unit) { return IsQuantity(unit, Quantity.Volume); }
public static bool IsFlow(Unit unit) { return IsQuantity(unit, Quantity.Flow); }
public static bool IsMass(Unit unit) { return IsQuantity(unit, Quantity.Mass); }
public static bool IsTime(Unit unit) { return IsQuantity(unit, Quantity.Time); }
public static bool IsTemperature(Unit unit) { return IsQuantity(unit, Quantity.Temperature); }
public static bool IsPressure(Unit unit) { return IsQuantity(unit, Quantity.Pressure); }
public static bool IsHumidity(Unit unit) { return IsQuantity(unit, Quantity.Humidity); }
public static bool IsError(Unit unit) { return IsQuantity(unit, Quantity.Error); }
public static bool IsLength(Unit unit) { return IsQuantity(unit, Quantity.Length); }
public static bool IsDensity(Unit unit) { return IsQuantity(unit, Quantity.Density); }
public static bool IsEnergy(Unit unit) { return IsQuantity(unit, Quantity.Energy); }
public static bool IsPulses(Unit unit) { return IsQuantity(unit, Quantity.Pulses); }
public static bool IsPulsePerLtr(Unit unit) { return IsQuantity(unit, Quantity.PulsePerLtr); }
public static bool IsPulsePerKWh(Unit unit) { return IsQuantity(unit, Quantity.PulsePerKWh); }
public static bool IsConductivity(Unit unit) { return IsQuantity(unit, Quantity.Conductivity); }
public static bool IsVolume(Unit units) { return IsQuantity(units, Config.Quantity.Volume); }
public static bool IsFlow(Unit units) { return IsQuantity(units, Config.Quantity.Flow); }
public static bool IsMass(Unit units) { return IsQuantity(units, Config.Quantity.Mass); }
public static bool IsTime(Unit units) { return IsQuantity(units, Config.Quantity.Time); }
public static bool IsTemperature(Unit units) { return IsQuantity(units, Config.Quantity.Temperature); }
public static bool IsPressure(Unit units) { return IsQuantity(units, Config.Quantity.Pressure); }
public static bool IsHumidity(Unit units) { return IsQuantity(units, Config.Quantity.Humidity); }
public static bool IsError(Unit units) { return IsQuantity(units, Config.Quantity.Error); }
public static bool IsLength(Unit units) { return IsQuantity(units, Config.Quantity.Length); }
public static bool IsDensity(Unit units) { return IsQuantity(units, Config.Quantity.Density); }
public static bool IsEnergy(Unit units) { return IsQuantity(units, Config.Quantity.Energy); }
public static bool IsPulses(Unit units) { return IsQuantity(units, Config.Quantity.Pulses); }
public static bool IsPulsePerLtr(Unit units) { return IsQuantity(units, Config.Quantity.PulsePerLtr); }
public static bool IsPulsePerKWh(Unit units) { return IsQuantity(units, Config.Quantity.PulsePerKWh); }
public static bool IsConductivity(Unit units) { return IsQuantity(units, Config.Quantity.Conductivity); }
public static float ConvertTo(Unit unit, float v)
public static double ConvertTo(Unit units, double v)
{
return (float)ConvertTo(unit, (double)v);
}
public static double ConvertTo(Unit unit, double v)
{
switch (unit)
switch (units)
{
/// Volume: internal representation in l
case Unit.ml: return 1000 * v; /// 1 ml = 0.001 l
@@ -393,9 +383,7 @@ namespace Common
/// Flow: internal representation in m3/h
case Unit.lph: return 1000 * v; /// 1 l/h
case Unit.cfph: return 35.3146667214886 * v;/// 1 cf/h
case Unit.lpm: return v / 0.06; /// 1 l/m
case Unit.USgalpm: return 4.40286754395493 * v;/// 1 US gallon per minute
case Unit.lps: return v / 3.6; /// 1 l/s
case Unit.USgalps: return 0.0733811257326 * v; /// 1 US gallon per second
case Unit.m3pm: return v / 60; /// 1 m3/m
@@ -403,7 +391,6 @@ namespace Common
/// Mass: internal representation in kg
case Unit.g: return 1000 * v; /// 1 g = 0.001 kg
case Unit.oz: return 35.273962 * v; /// 1 oz = 0.0283495231 kg
case Unit.lb: return 2.2046226 * v; /// 1 lb = 0.45359237 kg
case Unit.t: return 0.001 * v; /// 1 t = 1000 kg
@@ -460,15 +447,9 @@ namespace Common
}
}
public static float ConvertFrom(Unit unit, float v)
public static double ConvertFrom(Unit units, double v)
{
return (float)ConvertFrom(unit, (double)v);
}
public static double ConvertFrom(Unit unit, double v)
{
switch (unit)
switch (units)
{
/// Volume: internal representation in l
case Unit.ml: return 0.001 * v; /// 0.001 l
@@ -479,9 +460,7 @@ namespace Common
/// Flow: internal representation in m3/h
case Unit.lph: return 0.001 * v; /// 1 l/h
case Unit.cfph: return 0.028316846592 * v; /// 1 cf/h
case Unit.lpm: return 0.06 * v; /// 1 l/m
case Unit.USgalpm: return 0.2271247068 * v; /// 1 US gallon per minute
case Unit.lps: return 3.6 * v; /// 1 l/s
case Unit.USgalps: return 13.627482408 * v; /// 1 US gallon per second
case Unit.m3pm: return 60 * v; /// 1 m3/m
@@ -489,7 +468,6 @@ namespace Common
/// Mass: internal representation in kg
case Unit.g: return 0.001 * v; /// 1 g = 0.001 kg
case Unit.oz: return 0.0283495231 * v; /// 1 oz = 0.0283495231 kg
case Unit.lb: return 0.45359237 * v; /// 1 lb = 0.45359237 kg
case Unit.t: return 1000 * v; /// 1 t = 1000 kg
@@ -545,20 +523,5 @@ namespace Common
default: return v; /// Do not convert
}
}
/// <summary>
/// Converts a string to a unit
/// </summary>
/// <param name="description">Unit description string</param>
/// <returns>Converted unit or Unit.None if not recognized</returns>
public static Unit FromDescription(string description)
{
for (Unit unit = 0; unit < Unit.Count; unit++)
{
if (unit.ToDescription() == description) return unit;
}
return Unit.None;
}
}
}
+189 -1
View File
@@ -1,5 +1,5 @@
///
/// Copyright (c) 2017-2022 Sensus Slovensko a.s.
/// Copyright (c) 2017-2018 Sensus Slovensko a.s.
///
using System;
using System.Collections.Generic;
@@ -10,6 +10,80 @@ namespace Config
{
public static class Utils
{
public static string SignificantDigitsToFmt(double value, int sigDigits)
{
if (sigDigits == 6)
{
if (value >= 99999.5 || value < -99999.5) return "F0";
else if (value >= 9999.95 || value < -9999.95) return "F1";
else if (value >= 999.995 || value < -999.995) return "F2";
else if (value >= 99.9995 || value < -99.9995) return "F3";
else if (value >= 9.99995 || value < -9.99995) return "F4";
else if (value >= 0.999995 || value < -0.999995) return "F5";
else if (value >= 0.0999995 || value < -0.0999995) return "F6";
else if (value >= 0.00999995 || value < -0.00999995) return "F7";
else if (value >= 0.000999995 || value < -0.000999995) return "F8";
else if (value >= 0.0000999995 || value < -0.0000999995) return "F9";
else return "F10";
}
else if (sigDigits == 5)
{
if (value >= 9999.5 || value < -9999.5) return "F0";
else if (value >= 999.95 || value < -999.95) return "F1";
else if (value >= 99.995 || value < -99.995) return "F2";
else if (value >= 9.9995 || value < -9.9995) return "F3";
else if (value >= 0.99995 || value < -0.99995) return "F4";
else if (value >= 0.099995 || value < -0.099995) return "F5";
else if (value >= 0.0099995 || value < -0.0099995) return "F6";
else if (value >= 0.00099995 || value < -0.00099995) return "F7";
else if (value >= 0.000099995 || value < -0.000099995) return "F8";
else return "F9";
}
else if (sigDigits == 4)
{
if (value >= 999.5 || value < -999.5) return "F0";
else if (value >= 99.95 || value < -99.95) return "F1";
else if (value >= 9.995 || value < -9.995) return "F2";
else if (value >= 0.9995 || value < -0.9995) return "F3";
else if (value >= 0.09995 || value < -0.09995) return "F4";
else if (value >= 0.009995 || value < -0.009995) return "F5";
else if (value >= 0.0009995 || value < -0.0009995) return "F6";
else if (value >= 0.00009995 || value < -0.00009995) return "F7";
else return "F8";
}
else if (sigDigits == 3)
{
if (value >= 99.5 || value < -99.5) return "F0";
else if (value >= 9.95 || value < -9.95) return "F1";
else if (value >= 0.995 || value < -0.995) return "F2";
else if (value >= 0.0995 || value < -0.0995) return "F3";
else if (value >= 0.00995 || value < -0.00995) return "F4";
else if (value >= 0.000995 || value < -0.000995) return "F5";
else if (value >= 0.0000995 || value < -0.0000995) return "F6";
else return "F7";
}
else if (sigDigits == 2)
{
if (value >= 9.5 || value < -9.5) return "F0";
else if (value >= 0.95 || value < -0.95) return "F1";
else if (value >= 0.095 || value < -0.095) return "F2";
else if (value >= 0.0095 || value < -0.0095) return "F3";
else if (value >= 0.00095 || value < -0.00095) return "F4";
else if (value >= 0.000095 || value < -0.000095) return "F5";
else return "F6";
}
else /// if (sigDigits == 1)
{
if (value >= 0.95 || value < -0.95) return "F0";
else if (value >= 0.095 || value < -0.095) return "F1";
else if (value >= 0.0095 || value < -0.0095) return "F2";
else if (value >= 0.00095 || value < -0.00095) return "F3";
else if (value >= 0.000095 || value < -0.000095) return "F4";
else return "F5";
}
}
/// <summary>
/// Extract and return a DB server from a MySQL connection string.
/// </summary>
@@ -64,5 +138,119 @@ namespace Config
/// pattern NOT found
return string.Empty;
}
/// <summary>
/// Get either Q1 or Qmin flow for a given Qn and metrological class
/// </summary>
/// <param name="Qn">Nominal flow in m3/h</param>
/// <param name="metroClass">Metrological class ("A" ,"B", "C" or "R#")</param>
/// <param name="medium">NotSpecified, ColdWater or HotWater</param>
/// <param name="Qdflt">Default flow when metrologic does not match pattern</param>
/// <returns>Q1 or Qmin flow in m3/h</returns>
public static double GetQ1Qmin(double Qn, string metroClass, Entities.Medium medium = Entities.Medium.ColdWater, double Qdflt = 0)
{
if (string.IsNullOrEmpty(metroClass)) return Qdflt;
int metroClassRatio;
if ((metroClass[0] == 'R') && int.TryParse(metroClass.Substring(1), out metroClassRatio) && (metroClassRatio > 0))
{
return Qn / (double)metroClassRatio;
}
else
{
if (medium == Entities.Medium.HotWater)
{
switch (metroClass)
{
case "A": return (Qn < 15) ? (0.04 * Qn) : (0.08 * Qn);
case "B": return (Qn < 15) ? (0.02 * Qn) : (0.04 * Qn);
case "C": return (Qn < 15) ? (0.01 * Qn) : (0.02 * Qn);
case "D": return (Qn < 15) ? (0.01 * Qn) : Qdflt;
default: break;
}
}
else
{
switch (metroClass)
{
case "A": return (Qn < 15) ? (0.04 * Qn) : (0.08 * Qn);
case "B": return (Qn < 15) ? (0.02 * Qn) : (0.03 * Qn);
case "C": return (Qn < 15) ? (0.01 * Qn) : (0.006 * Qn);
default: break;
}
}
}
return Qdflt;
}
/// <summary>
/// Get either Q2 or Qt flow for a given Qn and metrological class
/// </summary>
/// <param name="Qn">Nominal flow in m3/h</param>
/// <param name="metroClass">Metrological class ("A" ,"B", "C" or "R#")</param>
/// <param name="medium">NotSpecified, ColdWater or HotWater</param>
/// <param name="Qdflt">Default flow when metrologic does not match pattern</param>
/// <returns>Q2 or Qt flow in m3/h</returns>
public static double GetQ2Qt(double Qn, string metroClass, Entities.Medium medium = Entities.Medium.ColdWater, double Qdflt = 0)
{
if (string.IsNullOrEmpty(metroClass)) return Qdflt;
int metroClassRatio;
if ((metroClass[0] == 'R') && int.TryParse(metroClass.Substring(1), out metroClassRatio) && (metroClassRatio > 0))
{
return 1.6 * Qn / (double)metroClassRatio;
}
if (medium == Entities.Medium.HotWater)
{
switch (metroClass)
{
case "A": return (Qn < 15) ? (0.1 * Qn) : (0.2 * Qn);
case "B": return (Qn < 15) ? (0.08 * Qn) : (0.15 * Qn);
case "C": return (Qn < 15) ? (0.06 * Qn) : (0.1 * Qn);
case "D": return (Qn < 15) ? (0.015 * Qn) : Qdflt;
default: break;
}
}
else
{
switch (metroClass)
{
case "A": return (Qn < 15) ? (0.1 * Qn) : (0.3 * Qn);
case "B": return (Qn < 15) ? (0.08 * Qn) : (0.2 * Qn);
case "C": return (Qn < 15) ? (0.015 * Qn) : (0.015 * Qn);
default: break;
}
}
return Qdflt;
}
/// <summary>
/// Get either Q4 or Qmax flow for a given Qn and metrological class
/// </summary>
/// <param name="Qn">Nominal flow in m3/h</param>
/// <param name="metroClass">Metrological class ("A" ,"B", "C" or "R#")</param>
/// <param name="medium">NotSpecified, ColdWater or HotWater</param>
/// <param name="Qdflt">Default flow when metrologic does not match pattern</param>
/// <returns>Q4 or Qmax flow in m3/h</returns>
public static double GetQ4Qmax(double Qn, string metroClass, Entities.Medium medium = Entities.Medium.ColdWater, double Qdflt = 0)
{
if (string.IsNullOrEmpty(metroClass)) return Qdflt;
switch (metroClass[0])
{
case 'A':
case 'B':
case 'C':
case 'D':
return 2 * Qn;
case 'R':
return 1.25 * Qn;
default:
return Qdflt;
}
}
}
}
+1 -1
View File
@@ -86,7 +86,7 @@ namespace DataStreamMeter
public int GetMetersCount()
{
return 20;
return 1;
}
public bool OpenConnection(int meterIx, string connectionParameters, out string meterID)
+2 -2
View File
@@ -16,7 +16,7 @@
<FileAlignment>512</FileAlignment>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|x86' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<PlatformTarget>x86</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
@@ -27,7 +27,7 @@
<Prefer32Bit>false</Prefer32Bit>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|x86' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<PlatformTarget>x86</PlatformTarget>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
+2 -6
View File
@@ -16,7 +16,7 @@
<FileAlignment>512</FileAlignment>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|x86' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<PlatformTarget>x86</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
@@ -27,7 +27,7 @@
<Prefer32Bit>false</Prefer32Bit>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|x86' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<PlatformTarget>x86</PlatformTarget>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
@@ -90,10 +90,6 @@
</Compile>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Common\Common.csproj">
<Project>{c8939821-ba5c-4988-a3d0-bf53b74865c7}</Project>
<Name>Common</Name>
</ProjectReference>
<ProjectReference Include="..\Config\Config.csproj">
<Project>{743DF7DB-C7B6-42EB-986D-0F485E5588E4}</Project>
<Name>Config</Name>
+115 -116
View File
@@ -2,13 +2,12 @@
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Threading;
using System.Xml.Serialization;
using System.Windows.Forms;
using Common;
using TBF.Rig;
using TBF.Rig.Generic;
using TBF.UI.Bench.Components;
using TBF.BenchControl;
using TBF.BenchControl.Generic;
using System.Xml.Serialization;
namespace DeviceTest
@@ -80,7 +79,7 @@ namespace DeviceTest
compClasses.Add(componentFactory.ClassName);
}
tbfComponents = new List<TBF.Rig.Generic.IComponent>();
tbfComponents = new List<TBF.BenchControl.Generic.IComponent>();
tbfDevices = new List<IDevice>();
}
@@ -109,8 +108,8 @@ namespace DeviceTest
config.Name = Program.LocalSettings.ParentName;
config.ParentName = string.Empty;
config.ItemNr = 0;
config.DebugLevel = DebugMode.Normal;
config.LogLevel = LogLevel.Debug;
config.DebugLevel = Config.Entities.DebugMode.Normal;
config.LogLevel = Config.Entities.LogLevel.Debug;
config.Corrections = null;
config.Factory = parentFactory;
parentCfg = config;
@@ -142,8 +141,8 @@ namespace DeviceTest
config.Name = Program.LocalSettings.ComponentName;
config.ParentName = string.IsNullOrEmpty(Program.LocalSettings.ComponentParentName) ? string.Empty : Program.LocalSettings.ComponentParentName;
config.ItemNr = 1;
config.DebugLevel = DebugMode.Normal;
config.LogLevel = LogLevel.Debug;
config.DebugLevel = Config.Entities.DebugMode.Normal;
config.LogLevel = Config.Entities.LogLevel.Debug;
config.Corrections = null;
config.Factory = component1Factory;
component1Cfg = config;
@@ -177,8 +176,8 @@ namespace DeviceTest
config.Name = Program.LocalSettings.Component2Name;
config.ParentName = string.IsNullOrEmpty(Program.LocalSettings.Component2ParentName) ? string.Empty : Program.LocalSettings.Component2ParentName;
config.ItemNr = 2;
config.DebugLevel = DebugMode.Normal;
config.LogLevel = LogLevel.Debug;
config.DebugLevel = Config.Entities.DebugMode.Normal;
config.LogLevel = Config.Entities.LogLevel.Debug;
config.Corrections = null;
config.Factory = component2Factory;
component2Cfg = config;
@@ -212,8 +211,8 @@ namespace DeviceTest
config.Name = Program.LocalSettings.Component3Name;
config.ParentName = string.IsNullOrEmpty(Program.LocalSettings.Component3ParentName) ? string.Empty : Program.LocalSettings.Component3ParentName;
config.ItemNr = 3;
config.DebugLevel = DebugMode.Normal;
config.LogLevel = LogLevel.Debug;
config.DebugLevel = Config.Entities.DebugMode.Normal;
config.LogLevel = Config.Entities.LogLevel.Debug;
config.Corrections = null;
config.Factory = component3Factory;
component3Cfg = config;
@@ -384,7 +383,7 @@ namespace DeviceTest
/// <returns>true when factory changed</returns>
bool FactoryFromClassName(string className, ref IComponentFactory factory)
{
foreach (var fac in TbfComponents.Factories)
foreach (var fac in TbfComponents.Factories)
{
if (className == fac.ClassName)
{
@@ -422,13 +421,13 @@ namespace DeviceTest
{
parentCfg = parentFactory.DefaultConfig();
}
ComponentParametersDlg cfgForm = new ComponentParametersDlg(this);
cfgForm.CmpntEntities = new List<Config.Entities.Component>();
IComponentCfgCtrl cfgControl = parentCfg.GetControl(cfgForm.CmpntEntities);
IComponentCfgCtrl cfgControl = parentCfg.GetControl();
cfgControl.Config = parentCfg;
cfgControl.Config.ItemNr = 0;
ComponentParametersDlg cfgForm = new ComponentParametersDlg();
cfgForm.TbfComponents = new List<Config.Entities.Component>();
cfgForm.ComponentCfgCtrl = cfgControl;
cfgForm.UnlockAfterStart = true;
DialogResult dr = cfgForm.ShowDialog();
@@ -451,17 +450,17 @@ namespace DeviceTest
{
component1Cfg = component1Factory.DefaultConfig();
}
ComponentParametersDlg cfgForm = new ComponentParametersDlg(this);
IComponentCfgCtrl cfgControl = component1Cfg.GetControl();
cfgControl.Config = component1Cfg;
cfgControl.Config.ItemNr = 1;
ComponentParametersDlg cfgForm = new ComponentParametersDlg();
///
var compEntities = new List<Config.Entities.Component>();
IList<Config.Entities.Component> compEntities = new List<Config.Entities.Component>();
if (parentFactory != null && parentCfg != null) compEntities.Add(parentCfg.CreateDbEntity());
cfgForm.CmpntEntities = compEntities;
cfgForm.TbfComponents = compEntities;
IComponentCfgCtrl cfgControl = component1Cfg.GetControl(compEntities);
cfgControl.Config = component1Cfg;
cfgControl.Config.ItemNr = 1;
cfgForm.ComponentCfgCtrl = cfgControl;
cfgForm.ComponentCfgCtrl = cfgControl;
cfgForm.UnlockAfterStart = true;
DialogResult dr = cfgForm.ShowDialog();
if (dr != DialogResult.OK) return;
@@ -485,18 +484,18 @@ namespace DeviceTest
{
component2Cfg = component2Factory.DefaultConfig();
}
ComponentParametersDlg cfgForm = new ComponentParametersDlg(this);
IComponentCfgCtrl cfgControl = component2Cfg.GetControl();
cfgControl.Config = component2Cfg;
cfgControl.Config.ItemNr = 1;
ComponentParametersDlg cfgForm = new ComponentParametersDlg();
///
var compEntities = new List<Config.Entities.Component>();
IList<Config.Entities.Component> compEntities = new List<Config.Entities.Component>();
if (parentFactory != null && parentCfg != null) compEntities.Add(parentCfg.CreateDbEntity());
if (component1Factory != null && component1Cfg != null) compEntities.Add(component1Cfg.CreateDbEntity());
cfgForm.CmpntEntities = compEntities;
cfgForm.TbfComponents = compEntities;
IComponentCfgCtrl cfgControl = component2Cfg.GetControl(compEntities);
cfgControl.Config = component2Cfg;
cfgControl.Config.ItemNr = 1;
cfgForm.ComponentCfgCtrl = cfgControl;
cfgForm.ComponentCfgCtrl = cfgControl;
cfgForm.UnlockAfterStart = true;
DialogResult dr = cfgForm.ShowDialog();
if (dr != DialogResult.OK) return;
@@ -520,19 +519,19 @@ namespace DeviceTest
{
component3Cfg = component3Factory.DefaultConfig();
}
ComponentParametersDlg cfgForm = new ComponentParametersDlg(this);
IComponentCfgCtrl cfgControl = component3Cfg.GetControl();
cfgControl.Config = component3Cfg;
cfgControl.Config.ItemNr = 1;
ComponentParametersDlg cfgForm = new ComponentParametersDlg();
///
var compEntities = new List<Config.Entities.Component>();
IList<Config.Entities.Component> compEntities = new List<Config.Entities.Component>();
if (parentFactory != null && parentCfg != null) compEntities.Add(parentCfg.CreateDbEntity());
if (component1Factory != null && component1Cfg != null) compEntities.Add(component1Cfg.CreateDbEntity());
if (component2Factory != null && component2Cfg != null) compEntities.Add(component2Cfg.CreateDbEntity());
cfgForm.CmpntEntities = compEntities;
cfgForm.TbfComponents = compEntities;
IComponentCfgCtrl cfgControl = component3Cfg.GetControl(compEntities);
cfgControl.Config = component3Cfg;
cfgControl.Config.ItemNr = 1;
cfgForm.ComponentCfgCtrl = cfgControl;
cfgForm.ComponentCfgCtrl = cfgControl;
cfgForm.UnlockAfterStart = true;
DialogResult dr = cfgForm.ShowDialog();
if (dr != DialogResult.OK) return;
@@ -569,7 +568,7 @@ namespace DeviceTest
{
if (parentFactory != null && parentCfg != null)
{
TBF.Rig.Generic.IComponent component = parentFactory.GetComponent(parentCfg, tbfComponents);
TBF.BenchControl.Generic.IComponent component = parentFactory.GetComponent(parentCfg, tbfComponents);
tbfComponents.Add(component);
IDevice dev = component as IDevice;
if (dev != null)
@@ -581,7 +580,7 @@ namespace DeviceTest
}
if (component1Factory != null && component1Cfg != null)
{
TBF.Rig.Generic.IComponent component = component1Factory.GetComponent(component1Cfg, tbfComponents);
TBF.BenchControl.Generic.IComponent component = component1Factory.GetComponent(component1Cfg, tbfComponents);
tbfComponents.Add(component);
tbfComponent1forOp = component;
IDevice dev = component as IDevice;
@@ -594,7 +593,7 @@ namespace DeviceTest
}
if (component2Factory != null && component2Cfg != null)
{
TBF.Rig.Generic.IComponent component2 = component2Factory.GetComponent(component2Cfg, tbfComponents);
TBF.BenchControl.Generic.IComponent component2 = component2Factory.GetComponent(component2Cfg, tbfComponents);
tbfComponents.Add(component2);
tbfComponent2forOp = component2;
IDevice dev = component2 as IDevice;
@@ -607,7 +606,7 @@ namespace DeviceTest
}
if (component3Factory != null && component3Cfg != null)
{
TBF.Rig.Generic.IComponent component3 = component3Factory.GetComponent(component3Cfg, tbfComponents);
TBF.BenchControl.Generic.IComponent component3 = component3Factory.GetComponent(component3Cfg, tbfComponents);
tbfComponents.Add(component3);
tbfComponent3forOp = component3;
IDevice dev = component3 as IDevice;
@@ -664,120 +663,120 @@ namespace DeviceTest
int previousOperation = 0;
if (tbfComponent1forOp is TBF.Rig.Modbus.PressureMeter.Meret.PressureMeter)
if (tbfComponent1forOp is TBF.BenchControl.Modbus.PressureMeter.Meret.PressureMeter)
{
operation1 = (tbfComponent1forOp as TBF.Rig.Modbus.PressureMeter.Meret.PressureMeter).ReadPressureOp(ref floatBox);
operation1 = (tbfComponent1forOp as TBF.BenchControl.Modbus.PressureMeter.Meret.PressureMeter).ReadPressureOp(ref floatBox);
}
else if (tbfComponent1forOp is TBF.Rig.Network.Camera.CLP1611.Camera)
else if (tbfComponent1forOp is TBF.BenchControl.Network.Camera.CLP1611.Camera)
{
operation1 = (tbfComponent1forOp as TBF.Rig.Network.Camera.CLP1611.Camera).LiveStreamOp(false);
operation2 = (tbfComponent1forOp as TBF.Rig.Network.Camera.CLP1611.Camera).LiveStreamOp(true);
operation1 = (tbfComponent1forOp as TBF.BenchControl.Network.Camera.CLP1611.Camera).LiveStreamOp(false);
operation2 = (tbfComponent1forOp as TBF.BenchControl.Network.Camera.CLP1611.Camera).LiveStreamOp(true);
}
else if (tbfComponent1forOp is TBF.Rig.Network.Camera.Roi.Roi)
else if (tbfComponent1forOp is TBF.BenchControl.Network.Camera.Roi.Roi)
{
operation1 = (tbfComponent1forOp as TBF.Rig.Network.Camera.Roi.Roi).RoiDetectionOp();
operation1 = (tbfComponent1forOp as TBF.BenchControl.Network.Camera.Roi.Roi).RoiDetectionOp();
}
else if (tbfComponent1forOp is TBF.Rig.Modbus.TempControl.Easytherm.Easytherm)
else if (tbfComponent1forOp is TBF.BenchControl.Modbus.Easytherm.Easytherm)
{
operation1 = (tbfComponent1forOp as TBF.Rig.Modbus.TempControl.Easytherm.Easytherm).SetTemperatureOp(10);
operation2 = (tbfComponent1forOp as TBF.Rig.Modbus.TempControl.Easytherm.Easytherm).SetTemperatureOp(20);
operation1 = (tbfComponent1forOp as TBF.BenchControl.Modbus.Easytherm.Easytherm).SetTemperatureOp(10);
operation2 = (tbfComponent1forOp as TBF.BenchControl.Modbus.Easytherm.Easytherm).SetTemperatureOp(20);
}
else if (tbfComponent1forOp is TBF.Rig.Modbus.UltrasoundLevelMeter.LevelMeter)
else if (tbfComponent1forOp is TBF.BenchControl.Modbus.UltrasoundLevelMeter.LevelMeter)
{
operation1 = (tbfComponent1forOp as TBF.Rig.Modbus.UltrasoundLevelMeter.LevelMeter).ReadLevelOp(ref dblBox1);
operation2 = (tbfComponent1forOp as TBF.Rig.Modbus.UltrasoundLevelMeter.LevelMeter).ReadTempOp(ref dblBox3);
operation1 = (tbfComponent1forOp as TBF.BenchControl.Modbus.UltrasoundLevelMeter.LevelMeter).ReadLevelOp(ref dblBox1);
operation2 = (tbfComponent1forOp as TBF.BenchControl.Modbus.UltrasoundLevelMeter.LevelMeter).ReadTempOp(ref dblBox3);
}
else if (tbfComponent1forOp is TBF.Rig.Modbus.TankSelector.TankSelector)
else if (tbfComponent1forOp is TBF.BenchControl.Modbus.TankSelector.TankSelector)
{
//operation1 = (tbfComponent1forOp as TBF.Rig.Modbus.TankSelector.TankSelector).SelectTankOp(1);
//operation2 = (tbfComponent1forOp as TBF.Rig.Modbus.TankSelector.TankSelector).SelectTankOp(2);
//operation3 = (tbfComponent1forOp as TBF.Rig.Modbus.TankSelector.TankSelector).SelectTankOp(3);
//operation4 = (tbfComponent1forOp as TBF.Rig.Modbus.TankSelector.TankSelector).SelectTankOp(0);
//operation1 = (tbfComponent1forOp as TBF.BenchControl.Modbus.TankSelector.TankSelector).SelectTankOp(1);
//operation2 = (tbfComponent1forOp as TBF.BenchControl.Modbus.TankSelector.TankSelector).SelectTankOp(2);
//operation3 = (tbfComponent1forOp as TBF.BenchControl.Modbus.TankSelector.TankSelector).SelectTankOp(3);
//operation4 = (tbfComponent1forOp as TBF.BenchControl.Modbus.TankSelector.TankSelector).SelectTankOp(0);
}
else if (tbfComponent3forOp is TBF.Rig.Modbus.TankSelector.TankSelector)
else if (tbfComponent3forOp is TBF.BenchControl.Modbus.TankSelector.TankSelector)
{
operation1 = (tbfComponent3forOp as TBF.Rig.Modbus.QuidoRS.QuidoRS).SetOutputsOp(1);
operation2 = (tbfComponent3forOp as TBF.Rig.Modbus.QuidoRS.QuidoRS).SetOutputsOp(2);
operation3 = (tbfComponent3forOp as TBF.Rig.Modbus.QuidoRS.QuidoRS).SetOutputsOp(4);
operation4 = (tbfComponent3forOp as TBF.Rig.Modbus.QuidoRS.QuidoRS).SetOutputsOp(0);
operation1 = (tbfComponent3forOp as TBF.BenchControl.Modbus.QuidoRS.QuidoRS).SetOutputsOp(1);
operation2 = (tbfComponent3forOp as TBF.BenchControl.Modbus.QuidoRS.QuidoRS).SetOutputsOp(2);
operation3 = (tbfComponent3forOp as TBF.BenchControl.Modbus.QuidoRS.QuidoRS).SetOutputsOp(4);
operation4 = (tbfComponent3forOp as TBF.BenchControl.Modbus.QuidoRS.QuidoRS).SetOutputsOp(0);
}
if (tbfComponent2forOp is TBF.Rig.Modbus.PressureMeter.Meret.PressureMeter)
if (tbfComponent2forOp is TBF.BenchControl.Modbus.PressureMeter.Meret.PressureMeter)
{
operation21 = (tbfComponent2forOp as TBF.Rig.Modbus.PressureMeter.Meret.PressureMeter).ReadPressureOp(ref floatBox);
operation21 = (tbfComponent2forOp as TBF.BenchControl.Modbus.PressureMeter.Meret.PressureMeter).ReadPressureOp(ref floatBox);
}
else if (tbfComponent2forOp is TBF.Rig.Network.Camera.CLP1611.Camera)
else if (tbfComponent2forOp is TBF.BenchControl.Network.Camera.CLP1611.Camera)
{
operation21 = (tbfComponent2forOp as TBF.Rig.Network.Camera.CLP1611.Camera).LiveStreamOp(false);
operation22 = (tbfComponent2forOp as TBF.Rig.Network.Camera.CLP1611.Camera).LiveStreamOp(true);
operation21 = (tbfComponent2forOp as TBF.BenchControl.Network.Camera.CLP1611.Camera).LiveStreamOp(false);
operation22 = (tbfComponent2forOp as TBF.BenchControl.Network.Camera.CLP1611.Camera).LiveStreamOp(true);
}
else if (tbfComponent2forOp is TBF.Rig.Network.Camera.Roi.Roi)
else if (tbfComponent2forOp is TBF.BenchControl.Network.Camera.Roi.Roi)
{
operation21 = (tbfComponent2forOp as TBF.Rig.Network.Camera.Roi.Roi).RoiDetectionOp();
operation21 = (tbfComponent2forOp as TBF.BenchControl.Network.Camera.Roi.Roi).RoiDetectionOp();
}
else if (tbfComponent2forOp is TBF.Rig.Modbus.TempControl.Easytherm.Easytherm)
else if (tbfComponent2forOp is TBF.BenchControl.Modbus.Easytherm.Easytherm)
{
operation21 = (tbfComponent2forOp as TBF.Rig.Modbus.TempControl.Easytherm.Easytherm).SetTemperatureOp(10);
operation22 = (tbfComponent2forOp as TBF.Rig.Modbus.TempControl.Easytherm.Easytherm).SetTemperatureOp(20);
operation21 = (tbfComponent2forOp as TBF.BenchControl.Modbus.Easytherm.Easytherm).SetTemperatureOp(10);
operation22 = (tbfComponent2forOp as TBF.BenchControl.Modbus.Easytherm.Easytherm).SetTemperatureOp(20);
}
else if (tbfComponent2forOp is TBF.Rig.Modbus.UltrasoundLevelMeter.LevelMeter)
else if (tbfComponent2forOp is TBF.BenchControl.Modbus.UltrasoundLevelMeter.LevelMeter)
{
operation21 = (tbfComponent2forOp as TBF.Rig.Modbus.UltrasoundLevelMeter.LevelMeter).ReadLevelOp(ref dblBox1);
operation22 = (tbfComponent2forOp as TBF.Rig.Modbus.UltrasoundLevelMeter.LevelMeter).ReadTempOp(ref dblBox3);
operation21 = (tbfComponent2forOp as TBF.BenchControl.Modbus.UltrasoundLevelMeter.LevelMeter).ReadLevelOp(ref dblBox1);
operation22 = (tbfComponent2forOp as TBF.BenchControl.Modbus.UltrasoundLevelMeter.LevelMeter).ReadTempOp(ref dblBox3);
}
else if (tbfComponent2forOp is TBF.Rig.Modbus.TankSelector.TankSelector)
else if (tbfComponent2forOp is TBF.BenchControl.Modbus.TankSelector.TankSelector)
{
//operation21 = (tbfComponent2forOp as TBF.Rig.Modbus.TankSelector.TankSelector).SelectTankOp(1);
//operation22 = (tbfComponent2forOp as TBF.Rig.Modbus.TankSelector.TankSelector).SelectTankOp(2);
//operation23 = (tbfComponent2forOp as TBF.Rig.Modbus.TankSelector.TankSelector).SelectTankOp(3);
//operation24 = (tbfComponent2forOp as TBF.Rig.Modbus.TankSelector.TankSelector).SelectTankOp(0);
//operation21 = (tbfComponent2forOp as TBF.BenchControl.Modbus.TankSelector.TankSelector).SelectTankOp(1);
//operation22 = (tbfComponent2forOp as TBF.BenchControl.Modbus.TankSelector.TankSelector).SelectTankOp(2);
//operation23 = (tbfComponent2forOp as TBF.BenchControl.Modbus.TankSelector.TankSelector).SelectTankOp(3);
//operation24 = (tbfComponent2forOp as TBF.BenchControl.Modbus.TankSelector.TankSelector).SelectTankOp(0);
}
else if (tbfComponent3forOp is TBF.Rig.Modbus.TankSelector.TankSelector)
else if (tbfComponent3forOp is TBF.BenchControl.Modbus.TankSelector.TankSelector)
{
operation21 = (tbfComponent3forOp as TBF.Rig.Modbus.QuidoRS.QuidoRS).SetOutputsOp(1);
operation22 = (tbfComponent3forOp as TBF.Rig.Modbus.QuidoRS.QuidoRS).SetOutputsOp(2);
operation23 = (tbfComponent3forOp as TBF.Rig.Modbus.QuidoRS.QuidoRS).SetOutputsOp(4);
operation24 = (tbfComponent3forOp as TBF.Rig.Modbus.QuidoRS.QuidoRS).SetOutputsOp(0);
operation21 = (tbfComponent3forOp as TBF.BenchControl.Modbus.QuidoRS.QuidoRS).SetOutputsOp(1);
operation22 = (tbfComponent3forOp as TBF.BenchControl.Modbus.QuidoRS.QuidoRS).SetOutputsOp(2);
operation23 = (tbfComponent3forOp as TBF.BenchControl.Modbus.QuidoRS.QuidoRS).SetOutputsOp(4);
operation24 = (tbfComponent3forOp as TBF.BenchControl.Modbus.QuidoRS.QuidoRS).SetOutputsOp(0);
}
if (tbfComponent3forOp is TBF.Rig.Modbus.PressureMeter.Meret.PressureMeter)
if (tbfComponent3forOp is TBF.BenchControl.Modbus.PressureMeter.Meret.PressureMeter)
{
operation31 = (tbfComponent3forOp as TBF.Rig.Modbus.PressureMeter.Meret.PressureMeter).ReadPressureOp(ref floatBox);
operation31 = (tbfComponent3forOp as TBF.BenchControl.Modbus.PressureMeter.Meret.PressureMeter).ReadPressureOp(ref floatBox);
}
else if (tbfComponent3forOp is TBF.Rig.Network.Camera.CLP1611.Camera)
else if (tbfComponent3forOp is TBF.BenchControl.Network.Camera.CLP1611.Camera)
{
operation31 = (tbfComponent3forOp as TBF.Rig.Network.Camera.CLP1611.Camera).LiveStreamOp(false);
operation33 = (tbfComponent3forOp as TBF.Rig.Network.Camera.CLP1611.Camera).LiveStreamOp(true);
operation31 = (tbfComponent3forOp as TBF.BenchControl.Network.Camera.CLP1611.Camera).LiveStreamOp(false);
operation33 = (tbfComponent3forOp as TBF.BenchControl.Network.Camera.CLP1611.Camera).LiveStreamOp(true);
}
else if (tbfComponent3forOp is TBF.Rig.Network.Camera.Roi.Roi)
else if (tbfComponent3forOp is TBF.BenchControl.Network.Camera.Roi.Roi)
{
operation31 = (tbfComponent3forOp as TBF.Rig.Network.Camera.Roi.Roi).RoiDetectionOp();
operation31 = (tbfComponent3forOp as TBF.BenchControl.Network.Camera.Roi.Roi).RoiDetectionOp();
}
else if (tbfComponent3forOp is TBF.Rig.Modbus.TempControl.Easytherm.Easytherm)
else if (tbfComponent3forOp is TBF.BenchControl.Modbus.Easytherm.Easytherm)
{
operation31 = (tbfComponent3forOp as TBF.Rig.Modbus.TempControl.Easytherm.Easytherm).SetTemperatureOp(10);
operation32 = (tbfComponent3forOp as TBF.Rig.Modbus.TempControl.Easytherm.Easytherm).SetTemperatureOp(20);
operation31 = (tbfComponent3forOp as TBF.BenchControl.Modbus.Easytherm.Easytherm).SetTemperatureOp(10);
operation32 = (tbfComponent3forOp as TBF.BenchControl.Modbus.Easytherm.Easytherm).SetTemperatureOp(20);
}
else if (tbfComponent3forOp is TBF.Rig.Modbus.UltrasoundLevelMeter.LevelMeter)
else if (tbfComponent3forOp is TBF.BenchControl.Modbus.UltrasoundLevelMeter.LevelMeter)
{
operation31 = (tbfComponent3forOp as TBF.Rig.Modbus.UltrasoundLevelMeter.LevelMeter).ReadLevelOp(ref dblBox1);
operation32 = (tbfComponent3forOp as TBF.Rig.Modbus.UltrasoundLevelMeter.LevelMeter).ReadTempOp(ref dblBox3);
operation31 = (tbfComponent3forOp as TBF.BenchControl.Modbus.UltrasoundLevelMeter.LevelMeter).ReadLevelOp(ref dblBox1);
operation32 = (tbfComponent3forOp as TBF.BenchControl.Modbus.UltrasoundLevelMeter.LevelMeter).ReadTempOp(ref dblBox3);
}
else if (tbfComponent3forOp is TBF.Rig.Modbus.TankSelector.TankSelector)
else if (tbfComponent3forOp is TBF.BenchControl.Modbus.TankSelector.TankSelector)
{
//operation31 = (tbfComponent3forOp as TBF.Rig.Modbus.TankSelector.TankSelector).SelectTankOp(1);
//operation32 = (tbfComponent3forOp as TBF.Rig.Modbus.TankSelector.TankSelector).SelectTankOp(2);
//operation33 = (tbfComponent3forOp as TBF.Rig.Modbus.TankSelector.TankSelector).SelectTankOp(3);
//operation34 = (tbfComponent3forOp as TBF.Rig.Modbus.TankSelector.TankSelector).SelectTankOp(0);
//operation31 = (tbfComponent3forOp as TBF.BenchControl.Modbus.TankSelector.TankSelector).SelectTankOp(1);
//operation32 = (tbfComponent3forOp as TBF.BenchControl.Modbus.TankSelector.TankSelector).SelectTankOp(2);
//operation33 = (tbfComponent3forOp as TBF.BenchControl.Modbus.TankSelector.TankSelector).SelectTankOp(3);
//operation34 = (tbfComponent3forOp as TBF.BenchControl.Modbus.TankSelector.TankSelector).SelectTankOp(0);
}
else if (tbfComponent3forOp is TBF.Rig.Modbus.TankSelector.TankSelector)
else if (tbfComponent3forOp is TBF.BenchControl.Modbus.TankSelector.TankSelector)
{
operation31 = (tbfComponent3forOp as TBF.Rig.Modbus.QuidoRS.QuidoRS).SetOutputsOp(1);
operation32 = (tbfComponent3forOp as TBF.Rig.Modbus.QuidoRS.QuidoRS).SetOutputsOp(2);
operation33 = (tbfComponent3forOp as TBF.Rig.Modbus.QuidoRS.QuidoRS).SetOutputsOp(4);
operation34 = (tbfComponent3forOp as TBF.Rig.Modbus.QuidoRS.QuidoRS).SetOutputsOp(0);
operation31 = (tbfComponent3forOp as TBF.BenchControl.Modbus.QuidoRS.QuidoRS).SetOutputsOp(1);
operation32 = (tbfComponent3forOp as TBF.BenchControl.Modbus.QuidoRS.QuidoRS).SetOutputsOp(2);
operation33 = (tbfComponent3forOp as TBF.BenchControl.Modbus.QuidoRS.QuidoRS).SetOutputsOp(4);
operation34 = (tbfComponent3forOp as TBF.BenchControl.Modbus.QuidoRS.QuidoRS).SetOutputsOp(0);
}
+2 -2
View File
@@ -16,7 +16,7 @@
<FileAlignment>512</FileAlignment>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|x86' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<PlatformTarget>x86</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
@@ -27,7 +27,7 @@
<Prefer32Bit>false</Prefer32Bit>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|x86' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<PlatformTarget>x86</PlatformTarget>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
-143
View File
@@ -1,143 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;
using NHibernate;
using NHibernate.Cfg;
using NHibernate.Tool.hbm2ddl;
using Common;
using Events;
namespace EventViewer
{
public static class EViewerDB
{
/// <summary> Session factory for all regular sessions, not for CreateEmptyResultsDB(). </summary>
public static ISessionFactory SessionFactory;
/// <summary> Connection string for all sessions </summary>
static string connectionString;
///
public static string ConnectionString
{
get { return connectionString; }
set
{
if (value != connectionString)
{
connectionString = value;
SessionFactory = null; /// Clear SessionFactory on connection string change
}
}
}
/// <summary> Database type (MySQL or SQLite) for all sessions </summary>
private static DBType dbType;
///
public static DBType DbType
{
get { return dbType; }
set { dbType = value; SessionFactory = null; }
}
/// <summary>
/// NHibernate session factory (to create the database session 'SessionFactory')
/// </summary>
/// <returns>A database session</returns>
static ISessionFactory CreateSessionFactory()
{
return CreateSessionFactory(false);
}
/// <summary>
/// NHibernate session factory (to create the database session 'SessionFactory')
/// </summary>
/// <param name="createDB">true = Create a new DB, false = Regular DB</param>
/// <returns>A database session</returns>
public static ISessionFactory CreateSessionFactory(bool createDB)
{
FluentConfiguration cfg = Fluently.Configure();
switch (dbType)
{
default:
case DBType.MySql:
cfg = cfg.Database(MySQLConfiguration.Standard.ConnectionString(connectionString));
break;
case DBType.SQLite:
cfg = cfg.Database(SQLiteConfiguration.Standard.UsingFile(connectionString));
break;
}
cfg = cfg.Mappings(m => m.FluentMappings.AddFromAssemblyOf<global::Events.Entities.Event>());
if (createDB)
{
return cfg.ExposeConfiguration(BuildSchemaCreate)
.BuildConfiguration()
.SetProperty("hibernate.connection.connect_timeout", Const.MySqlConnectTimeoutSec)
.BuildSessionFactory();
}
else
{
return cfg.ExposeConfiguration(BuildSchema)
.BuildConfiguration()
.SetProperty("hibernate.connection.connect_timeout", Const.MySqlConnectTimeoutSec)
.BuildSessionFactory();
}
}
static void BuildSchema(Configuration config)
{
/// This NHibernate tool takes a configuration with mapping info and exports a database schema
new SchemaExport(config).SetOutputFile("db_schema");
}
static void BuildSchemaCreate(Configuration config)
{
/// This NHibernate tool takes a configuration with mapping info and exports a database schema
new SchemaExport(config).Create(true, true);
}
/// Create a NHibernate session for the given database
public static ISession CreateSession()
{
if (string.IsNullOrEmpty(connectionString))
{
throw new Exception("Connection string was not specified");
}
if (SessionFactory == null) SessionFactory = CreateSessionFactory();
return SessionFactory.OpenSession();
}
/// <summary>
/// Create an empty users database.
/// Database contains only the user 'admin' and the control board component 'CB'.
/// </summary>
/// <param name="dbType">DBType.SQLite or DBType.MySql</param>
/// <param name="connectionString">Connection string</param>
/// <returns>true=success, false=error</returns>
public static bool CreateEmptyDB()
{
ISessionFactory sessionFactory = CreateSessionFactory(true);
if (sessionFactory == null) return false;
/// Populate the database
using (var session = sessionFactory.OpenSession())
{
using (var transaction = session.BeginTransaction())
{
transaction.Commit();
}
}
return true;
}
}
}
-1
View File
@@ -66,7 +66,6 @@
<Compile Include="EventViewerWnd.Designer.cs">
<DependentUpon>EventViewerWnd.cs</DependentUpon>
</Compile>
<Compile Include="EViewerDB.cs" />
<Compile Include="Forms\EventDetailsDlg.cs">
<SubType>Form</SubType>
</Compile>
+2 -3
View File
@@ -35,7 +35,7 @@
this.unreadEventsRadioButton = new System.Windows.Forms.RadioButton();
this.allEventsRadioButton = new System.Windows.Forms.RadioButton();
this.settingsButton = new System.Windows.Forms.Button();
this.eventsListView = new Common.Forms.ListViewEx();
this.eventsListView = new Common.UIControls.ListViewEx();
((System.ComponentModel.ISupportInitialize)(this.splitContainer1)).BeginInit();
this.splitContainer1.Panel1.SuspendLayout();
this.splitContainer1.Panel2.SuspendLayout();
@@ -138,7 +138,6 @@
// eventsListView
//
this.eventsListView.AllowColumnReorder = true;
this.eventsListView.CheckBoxes = true;
this.eventsListView.Dock = System.Windows.Forms.DockStyle.Fill;
this.eventsListView.DoubleClickActivation = false;
this.eventsListView.FullRowSelect = true;
@@ -176,7 +175,7 @@
private System.Windows.Forms.SplitContainer splitContainer1;
private System.Windows.Forms.Button settingsButton;
private Common.Forms.ListViewEx eventsListView;
private Common.UIControls.ListViewEx eventsListView;
private System.Windows.Forms.GroupBox eventsSelectionGroupBox;
private System.Windows.Forms.RadioButton unreadEventsRadioButton;
private System.Windows.Forms.RadioButton allEventsRadioButton;
+12 -13
View File
@@ -5,8 +5,7 @@ using System;
using System.Collections.Generic;
using System.Windows.Forms;
using NHibernate;
using Common;
using Common.Forms;
using Common.UIControls;
using Events;
using Events.Entities;
using EventViewer.Resources;
@@ -33,7 +32,7 @@ namespace EventViewer
ISession session;
IList<Subscriber> subscribers;
IList<Event> events;
MySortOrder sortOrder = MySortOrder.Ascending;
SortOrder sortOrder = SortOrder.Ascending;
int sortColumn = -1; /// 0-based index of column to be used for sorting
EViewerOption eViewerOption;
@@ -102,9 +101,9 @@ namespace EventViewer
{
try
{
EViewerDB.DbType = DBType.MySql;
EViewerDB.ConnectionString = Program.LocalSettings.ConnectionString;
session = EViewerDB.CreateSession();
DB.DbType = DBType.MySql;
DB.ConnectionString = Program.LocalSettings.ConnectionString;
session = DB.CreateSession();
subscribers = session.QueryOver<Subscriber>().List();
unreadEventsRadioButton.Checked = true;
}
@@ -211,8 +210,8 @@ namespace EventViewer
{
lvi.UseItemStyleForSubItems = false;
lvi.SubItems.Add(evnt.Severity.ToString());
lvi.SubItems[lvi.SubItems.Count - 1].BackColor = global::Events.Utils.GetSeverityColor(evnt.Severity);
lvi.SubItems[lvi.SubItems.Count - 1].ForeColor = global::Events.Utils.GetSeverityColor(evnt.Severity, true);
lvi.SubItems[lvi.SubItems.Count - 1].BackColor = Utils.GetSeverityColor(evnt.Severity);
lvi.SubItems[lvi.SubItems.Count - 1].ForeColor = Utils.GetSeverityColor(evnt.Severity, true);
}
lvi.SubItems.Add(evnt.Message);
eventsListView.Items.Add(lvi);
@@ -222,13 +221,13 @@ namespace EventViewer
{
if (e.Column == sortColumn)
{
sortOrder = (sortOrder == MySortOrder.Ascending) ? MySortOrder.Descending : MySortOrder.Ascending;
sortOrder = (sortOrder == SortOrder.Ascending) ? SortOrder.Descending : SortOrder.Ascending;
}
else
{
/// Clicked on another column header => set sortOrder to SortOrder.Ascending
sortColumn = e.Column;
sortOrder = MySortOrder.Ascending;
sortOrder = SortOrder.Ascending;
}
switch ((Column)sortColumn)
@@ -276,8 +275,8 @@ namespace EventViewer
private void settingsButton_Click(object sender, EventArgs e)
{
//Common.GID[] groupsWithAccess = new Common.GID[] { Common.GID.Administrators };
Users.Forms.LoginDlg dlg = new Users.Forms.LoginDlg();
//Users.Entities.GID[] groupsWithAccess = new Users.Entities.GID[] { Users.Entities.GID.Administrators };
Users.Forms.LoginDlg dlg = new Users.Forms.LoginDlg(true);
if (dlg.ShowDialog() == DialogResult.OK)
{
if ((new Forms.SettingsDlg()).ShowDialog() == DialogResult.OK)
@@ -291,7 +290,7 @@ namespace EventViewer
{
try
{
Users.CurrentUser.RemoteUsersDB = new Common.DBSettings(Common.DBType.MySql, Program.LocalSettings.UsersDBConnString);
Users.GlobalData.RemoteUsersDB = new Users.DBSettings(Users.Entities.DBType.MySql, Program.LocalSettings.UsersDBConnString);
Users.Forms.LoginDlg dlg = new Users.Forms.LoginDlg();
if (dlg.ShowDialog() == DialogResult.OK)
{
+4 -4
View File
@@ -59,8 +59,8 @@ namespace EventViewer
ConnectionString = "SERVER=localhost; DATABASE=test-e; UID=root; PASSWORD=kraken; CHARSET=utf8";
UsersDBConnString = "SERVER=localhost; DATABASE=test; UID=root; PASSWORD=kraken; CHARSET=utf8;";
#else
ConnectionString = "SERVER=10.42.128.24; DATABASE=st_wr_shared_events; UID=v9305784; PASSWORD=p89344390; CHARSET=utf8";
UsersDBConnString = "SERVER=10.42.128.24; DATABASE=st_wr_shared_config; UID=u9305784; PASSWORD=p89344390; CHARSET=utf8;";
ConnectionString = "SERVER=10.42.128.16; DATABASE=st_wr_shared_events; UID=v9305784; PASSWORD=p89344390; CHARSET=utf8";
UsersDBConnString = "SERVER=10.42.128.16; DATABASE=st_wr_shared_config; UID=u9305784; PASSWORD=p89344390; CHARSET=utf8;";
#endif
RecentTimeDays = 7;
Language = "sk";
@@ -147,7 +147,7 @@ namespace EventViewer
}
}
}
catch (Exception)
catch (Exception e)
{
//log.ErrorFormat("Failed to load from '{0}': {1}", fileName, e.Message);
return null;
@@ -203,7 +203,7 @@ namespace EventViewer
}
#endif
}
catch (Exception)
catch (Exception e)
{
//log.ErrorFormat("Failed to save to '{0}': {1}", Program.LocalSettingsFileName, e.Message);
}
+1 -1
View File
@@ -122,7 +122,7 @@ namespace EventViewer
/// Open the main application window
Application.Run(new EventViewerWnd());
}
catch (Exception)
catch (Exception e)
{
//LogException(log, "Exception in Application.Run(new ResultsBrowserWnd(args))", e);
}
+155 -8
View File
@@ -1,5 +1,5 @@
///
/// Copyright (c) 2020-2023 Sensus Slovensko a.s.
/// Copyright (c) 2020 Sensus Slovensko a.s.
///
using System;
using System.Collections.Generic;
@@ -8,13 +8,162 @@ using FluentNHibernate.Cfg.Db;
using NHibernate;
using NHibernate.Cfg;
using NHibernate.Tool.hbm2ddl;
using Common;
using Events.Entities;
namespace Events
{
public static class DB
{
/// <summary> Session factory for all regular sessions, not for CreateEmptyResultsDB(). </summary>
public static ISessionFactory SessionFactory;
/// <summary> Connection string for all sessions </summary>
static string connectionString;
///
public static string ConnectionString
{
get { return connectionString; }
set
{
if (value != connectionString)
{
connectionString = value;
SessionFactory = null; /// Clear SessionFactory on connection string change
}
}
}
/// <summary> Database type (MySQL or SQLite) for all sessions </summary>
private static Entities.DBType dbType;
///
public static Entities.DBType DbType
{
get { return dbType; }
set { dbType = value; SessionFactory = null; }
}
/// <summary>
/// NHibernate session factory (to create the database session 'SessionFactory')
/// </summary>
/// <returns>A database session</returns>
static ISessionFactory CreateSessionFactory()
{
return CreateSessionFactory(false);
}
/// <summary>
/// NHibernate session factory (to create the database session 'SessionFactory')
/// </summary>
/// <param name="createDB">true = Create a new DB, false = Regular DB</param>
/// <returns>A database session</returns>
public static ISessionFactory CreateSessionFactory(bool createDB)
{
FluentConfiguration cfg = Fluently.Configure();
switch (dbType)
{
default:
case Entities.DBType.SQLite:
cfg = cfg.Database(SQLiteConfiguration.Standard.UsingFile(connectionString));
break;
case Entities.DBType.MySql:
cfg = cfg.Database(MySQLConfiguration.Standard.ConnectionString(connectionString));
break;
}
cfg = cfg.Mappings(m => m.FluentMappings.AddFromAssemblyOf<Entities.Event>());
if (createDB)
{
return cfg.ExposeConfiguration(BuildSchemaCreate).BuildSessionFactory();
}
else
{
return cfg.ExposeConfiguration(BuildSchema).BuildSessionFactory();
}
}
static void BuildSchema(Configuration config)
{
/// This NHibernate tool takes a configuration with mapping info and exports a database schema
new SchemaExport(config).SetOutputFile("db_schema");
}
static void BuildSchemaCreate(Configuration config)
{
/// This NHibernate tool takes a configuration with mapping info and exports a database schema
new SchemaExport(config).Create(true, true);
}
/// Create a NHibernate session for the given database
public static ISession CreateSession()
{
if (string.IsNullOrEmpty(connectionString))
{
throw new Exception("Connection string was not specified");
}
if (SessionFactory == null) SessionFactory = CreateSessionFactory();
return SessionFactory.OpenSession();
}
public static void SaveObject(object obj)
{
SaveObject(CreateSession(), obj);
}
///
public static void SaveObject(ISession session, object obj)
{
using (var transaction = session.BeginTransaction())
{
session.SaveOrUpdate(obj);
try { transaction.Commit(); }
catch { }
}
}
public static void DeleteObject(object obj)
{
DeleteObject(CreateSession(), obj);
}
///
public static void DeleteObject(ISession session, object obj)
{
using (var transaction = session.BeginTransaction())
{
session.Delete(obj);
transaction.Commit();
}
}
/// <summary>
/// Create an empty users database.
/// Database contains only the user 'admin' and the control board component 'CB'.
/// </summary>
/// <param name="dbType">DBType.SQLite or DBType.MySql</param>
/// <param name="connectionString">Connection string</param>
/// <returns>true=success, false=error</returns>
public static bool CreateEmptyDB()
{
ISessionFactory sessionFactory = CreateSessionFactory(true);
if (sessionFactory == null) return false;
/// Populate the database
using (var session = sessionFactory.OpenSession())
{
using (var transaction = session.BeginTransaction())
{
transaction.Commit();
}
}
return true;
}
/// <summary>
/// Shared data (initially empty)
/// </summary>
@@ -30,7 +179,7 @@ namespace Events
DB.BenchName = benchName;
}
/// <summary>
/// <summary>
/// Loads shared data from the database
/// </summary>
public static void LoadSubscribers(ISession session)
@@ -43,7 +192,6 @@ namespace Events
/// </summary>
public static void LoadRecentEvents(ISession session, string benchName, int days)
{
BenchName = benchName;
RecentEvents = session.QueryOver<Event>()
.Where(e => (e.Bench == benchName))
.And(e => (e.TimeStamp >= DateTime.Now - new TimeSpan(days, 0, 0, 0)))
@@ -52,8 +200,7 @@ namespace Events
public static void SaveEvent(ISession session, Event evnt, SubscriberGroup groups)
{
if (allSubscribers == null) LoadSubscribers(session);
if (allSubscribers == null) return;
IList<Subscriber> thisEventSubscribers = new List<Subscriber>();
foreach (var s in allSubscribers)
{
@@ -63,10 +210,10 @@ namespace Events
thisEventSubscribers.Add(s);
}
}
evnt.Subscribers = thisEventSubscribers;
evnt.Bench = BenchName;
evnt.Subscribers = thisEventSubscribers;
session.SaveOrUpdate(evnt);
session.Flush();
}
}
}
+58
View File
@@ -0,0 +1,58 @@
///
/// Copyright (c) 2020 Sensus Slovensko a.s.
///
namespace Events.Entities
{
/// <summary>
/// Identifies the type of a database
/// </summary>
public enum DBType
{
None, /// Database disabled
MySql, /// MySQL database
SQLite, /// SQLite
Count
}
public enum Severity
{
Undefined,
Notification,
Warning,
Error,
FatalError,
Count
}
public enum EventClass
{
Undefined,
EquipmentHW,
Metrology,
TestingProcess,
BadResults,
ComputerResources,
Network,
Other,
Count
}
public enum SubscriberGroup : long
{
None = 0,
Metrology = 1,
Maintenance = 2,
Production = 4,
Management = 8,
Finish = 16,
}
public enum EViewerOption
{
Undefined,
AllEvents,
RecentEvents,
UnreadEvents,
}
}
-1
View File
@@ -3,7 +3,6 @@
///
using System;
using System.Collections.Generic;
using Common;
namespace Events.Entities
{
+1 -6
View File
@@ -56,6 +56,7 @@
</ItemGroup>
<ItemGroup>
<Compile Include="DB.cs" />
<Compile Include="Entities\Enums.cs" />
<Compile Include="Entities\Event.cs" />
<Compile Include="Entities\Subscriber.cs" />
<Compile Include="Utils.cs" />
@@ -66,12 +67,6 @@
<ItemGroup>
<Folder Include="DeliveryServices\" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Common\Common.csproj">
<Project>{c8939821-ba5c-4988-a3d0-bf53b74865c7}</Project>
<Name>Common</Name>
</ProjectReference>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
-1
View File
@@ -3,7 +3,6 @@
///
using System;
using System.Drawing;
using Common;
using Events.Entities;
namespace Events
-6
View File
@@ -1,6 +0,0 @@
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2" />
</startup>
</configuration>
-280
View File
@@ -1,280 +0,0 @@
namespace FeatureVectorCalculator
{
partial class CalculatorWnd
{
/// <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 Windows Form 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.rawFileComboBox = new System.Windows.Forms.ComboBox();
this.browseButton = new System.Windows.Forms.Button();
this.resultsTextBox = new System.Windows.Forms.TextBox();
this.splitContainer1 = new System.Windows.Forms.SplitContainer();
this.splitContainer2 = new System.Windows.Forms.SplitContainer();
this.splitContainer3 = new System.Windows.Forms.SplitContainer();
this.tabControl1 = new System.Windows.Forms.TabControl();
this.tabPage1 = new System.Windows.Forms.TabPage();
this.tabPage2 = new System.Windows.Forms.TabPage();
this.tabPage3 = new System.Windows.Forms.TabPage();
this.tabPage4 = new System.Windows.Forms.TabPage();
this.tabPage5 = new System.Windows.Forms.TabPage();
this.tabPage6 = new System.Windows.Forms.TabPage();
this.tabPage7 = new System.Windows.Forms.TabPage();
this.tabPage8 = new System.Windows.Forms.TabPage();
((System.ComponentModel.ISupportInitialize)(this.splitContainer1)).BeginInit();
this.splitContainer1.Panel1.SuspendLayout();
this.splitContainer1.Panel2.SuspendLayout();
this.splitContainer1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.splitContainer2)).BeginInit();
this.splitContainer2.Panel1.SuspendLayout();
this.splitContainer2.Panel2.SuspendLayout();
this.splitContainer2.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.splitContainer3)).BeginInit();
this.splitContainer3.Panel1.SuspendLayout();
this.splitContainer3.Panel2.SuspendLayout();
this.splitContainer3.SuspendLayout();
this.tabControl1.SuspendLayout();
this.SuspendLayout();
//
// rawFileComboBox
//
this.rawFileComboBox.Dock = System.Windows.Forms.DockStyle.Fill;
this.rawFileComboBox.FormattingEnabled = true;
this.rawFileComboBox.Location = new System.Drawing.Point(0, 0);
this.rawFileComboBox.Name = "rawFileComboBox";
this.rawFileComboBox.Size = new System.Drawing.Size(1040, 21);
this.rawFileComboBox.TabIndex = 0;
//
// browseButton
//
this.browseButton.Location = new System.Drawing.Point(7, 0);
this.browseButton.Name = "browseButton";
this.browseButton.Size = new System.Drawing.Size(66, 37);
this.browseButton.TabIndex = 1;
this.browseButton.Text = "Browse";
this.browseButton.UseVisualStyleBackColor = true;
this.browseButton.Click += new System.EventHandler(this.browseButton_Click);
//
// resultsTextBox
//
this.resultsTextBox.Dock = System.Windows.Forms.DockStyle.Fill;
this.resultsTextBox.Location = new System.Drawing.Point(0, 0);
this.resultsTextBox.Multiline = true;
this.resultsTextBox.Name = "resultsTextBox";
this.resultsTextBox.Size = new System.Drawing.Size(1127, 156);
this.resultsTextBox.TabIndex = 3;
//
// splitContainer1
//
this.splitContainer1.Dock = System.Windows.Forms.DockStyle.Fill;
this.splitContainer1.Location = new System.Drawing.Point(0, 0);
this.splitContainer1.Name = "splitContainer1";
this.splitContainer1.Orientation = System.Windows.Forms.Orientation.Horizontal;
//
// splitContainer1.Panel1
//
this.splitContainer1.Panel1.Controls.Add(this.splitContainer2);
//
// splitContainer1.Panel2
//
this.splitContainer1.Panel2.Controls.Add(this.tabControl1);
this.splitContainer1.Size = new System.Drawing.Size(1127, 733);
this.splitContainer1.SplitterDistance = 200;
this.splitContainer1.TabIndex = 4;
//
// splitContainer2
//
this.splitContainer2.Dock = System.Windows.Forms.DockStyle.Fill;
this.splitContainer2.FixedPanel = System.Windows.Forms.FixedPanel.Panel1;
this.splitContainer2.Location = new System.Drawing.Point(0, 0);
this.splitContainer2.Name = "splitContainer2";
this.splitContainer2.Orientation = System.Windows.Forms.Orientation.Horizontal;
//
// splitContainer2.Panel1
//
this.splitContainer2.Panel1.Controls.Add(this.splitContainer3);
//
// splitContainer2.Panel2
//
this.splitContainer2.Panel2.Controls.Add(this.resultsTextBox);
this.splitContainer2.Size = new System.Drawing.Size(1127, 200);
this.splitContainer2.SplitterDistance = 40;
this.splitContainer2.TabIndex = 3;
//
// splitContainer3
//
this.splitContainer3.Dock = System.Windows.Forms.DockStyle.Fill;
this.splitContainer3.FixedPanel = System.Windows.Forms.FixedPanel.Panel2;
this.splitContainer3.Location = new System.Drawing.Point(0, 0);
this.splitContainer3.Name = "splitContainer3";
//
// splitContainer3.Panel1
//
this.splitContainer3.Panel1.Controls.Add(this.rawFileComboBox);
//
// splitContainer3.Panel2
//
this.splitContainer3.Panel2.Controls.Add(this.browseButton);
this.splitContainer3.Size = new System.Drawing.Size(1127, 40);
this.splitContainer3.SplitterDistance = 1040;
this.splitContainer3.TabIndex = 0;
//
// tabControl1
//
this.tabControl1.Controls.Add(this.tabPage1);
this.tabControl1.Controls.Add(this.tabPage2);
this.tabControl1.Controls.Add(this.tabPage3);
this.tabControl1.Controls.Add(this.tabPage4);
this.tabControl1.Controls.Add(this.tabPage5);
this.tabControl1.Controls.Add(this.tabPage6);
this.tabControl1.Controls.Add(this.tabPage7);
this.tabControl1.Controls.Add(this.tabPage8);
this.tabControl1.Dock = System.Windows.Forms.DockStyle.Fill;
this.tabControl1.Location = new System.Drawing.Point(0, 0);
this.tabControl1.Name = "tabControl1";
this.tabControl1.SelectedIndex = 0;
this.tabControl1.Size = new System.Drawing.Size(1127, 529);
this.tabControl1.TabIndex = 0;
//
// tabPage1
//
this.tabPage1.Location = new System.Drawing.Point(4, 22);
this.tabPage1.Name = "tabPage1";
this.tabPage1.Padding = new System.Windows.Forms.Padding(3);
this.tabPage1.Size = new System.Drawing.Size(1119, 503);
this.tabPage1.TabIndex = 0;
this.tabPage1.Text = "OffsetV";
this.tabPage1.UseVisualStyleBackColor = true;
//
// tabPage2
//
this.tabPage2.Location = new System.Drawing.Point(4, 22);
this.tabPage2.Name = "tabPage2";
this.tabPage2.Padding = new System.Windows.Forms.Padding(3);
this.tabPage2.Size = new System.Drawing.Size(1119, 503);
this.tabPage2.TabIndex = 1;
this.tabPage2.Text = "KOhmsR";
this.tabPage2.UseVisualStyleBackColor = true;
//
// tabPage3
//
this.tabPage3.Location = new System.Drawing.Point(4, 22);
this.tabPage3.Name = "tabPage3";
this.tabPage3.Size = new System.Drawing.Size(1119, 503);
this.tabPage3.TabIndex = 2;
this.tabPage3.Text = "KOhmsC";
this.tabPage3.UseVisualStyleBackColor = true;
//
// tabPage4
//
this.tabPage4.Location = new System.Drawing.Point(4, 22);
this.tabPage4.Name = "tabPage4";
this.tabPage4.Size = new System.Drawing.Size(1119, 503);
this.tabPage4.TabIndex = 3;
this.tabPage4.Text = "DutFlowLph";
this.tabPage4.UseVisualStyleBackColor = true;
//
// tabPage5
//
this.tabPage5.Location = new System.Drawing.Point(4, 22);
this.tabPage5.Name = "tabPage5";
this.tabPage5.Size = new System.Drawing.Size(1119, 503);
this.tabPage5.TabIndex = 4;
this.tabPage5.Text = "RefFlowLph";
this.tabPage5.UseVisualStyleBackColor = true;
//
// tabPage6
//
this.tabPage6.Location = new System.Drawing.Point(4, 22);
this.tabPage6.Name = "tabPage6";
this.tabPage6.Size = new System.Drawing.Size(1119, 503);
this.tabPage6.TabIndex = 5;
this.tabPage6.Text = "FlowRatio";
this.tabPage6.UseVisualStyleBackColor = true;
//
// tabPage7
//
this.tabPage7.Location = new System.Drawing.Point(4, 22);
this.tabPage7.Name = "tabPage7";
this.tabPage7.Size = new System.Drawing.Size(1119, 503);
this.tabPage7.TabIndex = 6;
this.tabPage7.Text = "MagField";
this.tabPage7.UseVisualStyleBackColor = true;
//
// tabPage8
//
this.tabPage8.Location = new System.Drawing.Point(4, 22);
this.tabPage8.Name = "tabPage8";
this.tabPage8.Size = new System.Drawing.Size(1119, 503);
this.tabPage8.TabIndex = 7;
this.tabPage8.Text = "EmfV";
this.tabPage8.UseVisualStyleBackColor = true;
//
// CalculatorWnd
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(1127, 733);
this.Controls.Add(this.splitContainer1);
this.Name = "CalculatorWnd";
this.Text = "Feature vector calculator";
this.splitContainer1.Panel1.ResumeLayout(false);
this.splitContainer1.Panel2.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.splitContainer1)).EndInit();
this.splitContainer1.ResumeLayout(false);
this.splitContainer2.Panel1.ResumeLayout(false);
this.splitContainer2.Panel2.ResumeLayout(false);
this.splitContainer2.Panel2.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.splitContainer2)).EndInit();
this.splitContainer2.ResumeLayout(false);
this.splitContainer3.Panel1.ResumeLayout(false);
this.splitContainer3.Panel2.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.splitContainer3)).EndInit();
this.splitContainer3.ResumeLayout(false);
this.tabControl1.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.ComboBox rawFileComboBox;
private System.Windows.Forms.Button browseButton;
private System.Windows.Forms.TextBox resultsTextBox;
private System.Windows.Forms.SplitContainer splitContainer1;
private System.Windows.Forms.SplitContainer splitContainer2;
private System.Windows.Forms.SplitContainer splitContainer3;
private System.Windows.Forms.TabControl tabControl1;
private System.Windows.Forms.TabPage tabPage1;
private System.Windows.Forms.TabPage tabPage2;
private System.Windows.Forms.TabPage tabPage3;
private System.Windows.Forms.TabPage tabPage4;
private System.Windows.Forms.TabPage tabPage5;
private System.Windows.Forms.TabPage tabPage6;
private System.Windows.Forms.TabPage tabPage7;
private System.Windows.Forms.TabPage tabPage8;
}
}
-148
View File
@@ -1,148 +0,0 @@
///
/// Copyright (c) 2021 Sensus Slovensko a.s.
///
using System;
using System.IO;
using System.Windows.Forms;
using System.Windows.Forms.DataVisualization.Charting;
using Common.Iperl;
using System.Globalization;
using System.Drawing;
namespace FeatureVectorCalculator
{
public partial class CalculatorWnd : Form
{
public const int MaxOptoDataCount = 40000;
public const bool Downsample = true;
public const bool Extend = true;
OptoTelegramRaw[] optoData;
Int64 volumeRawExtLast;
Int64 timestampExtLast;
public CalculatorWnd()
{
InitializeComponent();
optoData = new OptoTelegramRaw[MaxOptoDataCount];
for (int i = 0; i < MaxOptoDataCount; i++)
{
optoData[i] = new OptoTelegramRaw();
}
}
void ClearOutput()
{
resultsTextBox.Clear();
tabControl1.TabPages[0].Controls.Clear();
tabControl1.TabPages[1].Controls.Clear();
tabControl1.TabPages[2].Controls.Clear();
tabControl1.TabPages[3].Controls.Clear();
tabControl1.TabPages[4].Controls.Clear();
tabControl1.TabPages[5].Controls.Clear();
tabControl1.TabPages[6].Controls.Clear();
tabControl1.TabPages[7].Controls.Clear();
}
private void browseButton_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
if (ofd.ShowDialog() == DialogResult.OK)
{
rawFileComboBox.Text = ofd.FileName;
ProcessRawDataFile(ofd.FileName);
}
}
void ProcessRawDataFile(string fileName)
{
int counter = 0;
int startIx = -1;
int endIx = -1;
ClearOutput();
resultsTextBox.Text = string.Format("File name: {0}{1}", fileName, Environment.NewLine);
try
{
using (StreamReader reader = new StreamReader(fileName))
{
string line;
while ((line = reader.ReadLine()) != null && counter < MaxOptoDataCount)
{
int ix = line.IndexOf(" :\t");
string[] items = line.Split('\t');
if (items.Length > 18)
{
string telegram = string.Format("{0}\t{1}\t{2}\t{3}\t{4}\t{5}\t{6}\r\n",
items[2], items[3], items[4], items[5], items[6], items[7], items[8]);
if (optoData[counter].UpdateFromString(telegram, counter, 0, ref volumeRawExtLast, ref timestampExtLast))
{
if (line.EndsWith("#### start test ####"))
{
startIx = counter;
optoData[counter].Flags = OptoTelegramFlags.OK_TestStart;
}
else if (line.EndsWith("#### end of test ####"))
{
endIx = counter;
optoData[counter].Flags = OptoTelegramFlags.OK_TestEnd;
}
else
{
optoData[counter].Flags = OptoTelegramFlags.OK;
}
}
optoData[counter].RefFlow = float.Parse(items[15].Replace(',', '.'), CultureInfo.InvariantCulture);
}
else
{
optoData[counter].Flags = OptoTelegramFlags.InvalidTelegram;
}
counter++;
}
reader.Close();
}
}
catch (Exception exc)
{
MessageBox.Show(string.Format("Exception: {0}", exc.Message));
return;
}
int start = Extend ? 0 : startIx;
int end = Extend ? (counter - 1) : endIx;
float[] offsetV, kOhmsR, kOhmsC, dutFlow, refFlow, flowRatio, magField, emfV;
PointF[] outliers, extendedOutliers;
float[] featureVector = Common.StatisticalMetrics.Calculate(optoData, counter, start, end, Downsample,
out offsetV, out kOhmsR, out kOhmsC, out dutFlow,
out refFlow, out flowRatio, out magField, out emfV,
out outliers, out extendedOutliers);
for (int i = 0; i < Math.Min(9, featureVector.Length); i++)
{
resultsTextBox.Text += string.Format("X{0} = {1}{2}", i + 1, featureVector[i], Environment.NewLine);
}
float period = Downsample ? 0.5F : 0.125F;
if (offsetV != null) tabControl1.TabPages[0].Controls.Add(SignalChart.GetChart(offsetV, period, "OffsetV", "OffsetV [μV]"));
if (kOhmsR != null) tabControl1.TabPages[1].Controls.Add(SignalChart.GetChart(kOhmsR, period, "kOhmsR", "kΩ"));
if (kOhmsC != null) tabControl1.TabPages[2].Controls.Add(SignalChart.GetChart(kOhmsC, period, "kOhmsC", "kΩ"));
if (dutFlow != null) tabControl1.TabPages[3].Controls.Add(SignalChart.GetChart(dutFlow, period, "dutFlow", "L/h"));
if (refFlow != null) tabControl1.TabPages[4].Controls.Add(SignalChart.GetChart(refFlow, period, "refFlow", "L/h"));
if (flowRatio != null) tabControl1.TabPages[5].Controls.Add(SignalChart.GetChart(flowRatio, period, "flowRatio", "", true, extendedOutliers, outliers));
if (magField != null) tabControl1.TabPages[6].Controls.Add(SignalChart.GetChart(magField, period, "magField", "μV", false));
if (emfV != null) tabControl1.TabPages[7].Controls.Add(SignalChart.GetChart(emfV, period, "emfV", "μV"));
}
}
}
@@ -1,100 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{6280F3F9-139A-48E3-8C88-25EB4124E982}</ProjectGuid>
<OutputType>WinExe</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>FeatureVectorCalculator</RootNamespace>
<AssemblyName>FeatureVectorCalculator</AssemblyName>
<TargetFrameworkVersion>v4.7.2</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup>
<StartupObject>FeatureVectorCalculator.Program</StartupObject>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Windows.Forms.DataVisualization" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Deployment" />
<Reference Include="System.Drawing" />
<Reference Include="System.Windows.Forms" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="CalculatorWnd.cs">
<SubType>Form</SubType>
</Compile>
<Compile Include="CalculatorWnd.Designer.cs">
<DependentUpon>CalculatorWnd.cs</DependentUpon>
</Compile>
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="SignalChart.cs" />
<EmbeddedResource Include="CalculatorWnd.resx">
<DependentUpon>CalculatorWnd.cs</DependentUpon>
</EmbeddedResource>
<EmbeddedResource Include="Properties\Resources.resx">
<Generator>ResXFileCodeGenerator</Generator>
<LastGenOutput>Resources.Designer.cs</LastGenOutput>
<SubType>Designer</SubType>
</EmbeddedResource>
<Compile Include="Properties\Resources.Designer.cs">
<AutoGen>True</AutoGen>
<DependentUpon>Resources.resx</DependentUpon>
<DesignTime>True</DesignTime>
</Compile>
<None Include="Properties\Settings.settings">
<Generator>SettingsSingleFileGenerator</Generator>
<LastGenOutput>Settings.Designer.cs</LastGenOutput>
</None>
<Compile Include="Properties\Settings.Designer.cs">
<AutoGen>True</AutoGen>
<DependentUpon>Settings.settings</DependentUpon>
<DesignTimeSharedInput>True</DesignTimeSharedInput>
</Compile>
</ItemGroup>
<ItemGroup>
<None Include="App.config" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Common\Common.csproj">
<Project>{c8939821-ba5c-4988-a3d0-bf53b74865c7}</Project>
<Name>Common</Name>
</ProjectReference>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>
-25
View File
@@ -1,25 +0,0 @@
///
/// Copyright (c) 2021 Sensus Slovensko a.s.
///
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace FeatureVectorCalculator
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new CalculatorWnd());
}
}
}
@@ -1,36 +0,0 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("FeatureVectorCalculator")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("FeatureVectorCalculator")]
[assembly: AssemblyCopyright("Copyright © 2021")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("4d3a6fe2-3153-4581-8ec7-e5a386b50177")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
-63
View File
@@ -1,63 +0,0 @@
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace FeatureVectorCalculator.Properties {
using System;
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources() {
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("FeatureVectorCalculator.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
}
}
@@ -1,117 +0,0 @@
<?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.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: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" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
</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" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
</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=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>
-26
View File
@@ -1,26 +0,0 @@
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace FeatureVectorCalculator.Properties {
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase {
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default {
get {
return defaultInstance;
}
}
}
}
@@ -1,7 +0,0 @@
<?xml version='1.0' encoding='utf-8'?>
<SettingsFile xmlns="http://schemas.microsoft.com/VisualStudio/2004/01/settings" CurrentProfile="(Default)">
<Profiles>
<Profile Name="(Default)" />
</Profiles>
<Settings />
</SettingsFile>
-108
View File
@@ -1,108 +0,0 @@
using System;
using System.Drawing;
using System.Windows.Forms;
using System.Windows.Forms.DataVisualization.Charting;
namespace FeatureVectorCalculator
{
public class SignalChart
{
public static Chart GetChart(float[] data, float period, string caption, string captionY, bool fromZero = true,
PointF[] extendedOutliers = null, PointF[] outliers = null)
{
Series series1 = null, series2 = null, series3 = null;
series1 = new Series { Name = caption, ChartArea = "area1", ChartType = SeriesChartType.Line, Color = Color.DeepSkyBlue };
float minY = float.MaxValue;
float maxY = float.MinValue;
for (int x = 0; x < data.Length; x++)
{
float y = data[x];
if (minY > y) minY = y;
if (maxY < y) maxY = y;
series1.Points.AddXY(x * period, y);
}
if (extendedOutliers != null)
{
series2 = new Series { Name = "extended outliers", ChartArea = "area1", ChartType = SeriesChartType.Point, Color = Color.Yellow };
for (int i = 0; i < extendedOutliers.Length; i++)
{
series2.Points.AddXY(extendedOutliers[i].X * period, extendedOutliers[i].Y);
}
}
if (outliers != null)
{
series3 = new Series { Name = "outliers", ChartArea = "area1", ChartType = SeriesChartType.Point, Color = Color.DarkRed };
for (int i = 0; i < outliers.Length; i++)
{
series3.Points.AddXY(outliers[i].X * period, outliers[i].Y);
}
}
ChartArea chArea = new ChartArea { Name = "area1" };
chArea.AxisX.Title = "Time [s]";
chArea.AxisX.IsLogarithmic = false;
chArea.AxisX.IsLabelAutoFit = true;
chArea.AxisX.Minimum = 0;
chArea.AxisX.Maximum = (data.Length - 1) * period;
// for (int j = i; j < i + 3; j++)
// {
// CustomLabel cl = new CustomLabel();
// cl.Text = string.Format("{0} {1}", xs[j], flowUnit.ToDescription());
// cl.FromPosition = Math.Log10(xs[j] * spacer);
// cl.ToPosition = Math.Log10(xs[j] / spacer);
// chArea.AxisX.CustomLabels.Add(cl);
// }
chArea.AxisY.Title = captionY;
chArea.AxisY.IsLogarithmic = false;
chArea.AxisY.IsLabelAutoFit = true;
if (!fromZero)
{
/// fromZero = false
chArea.AxisY.IsStartedFromZero = false;
float diff = maxY - minY;
chArea.AxisY.Minimum = minY - 0.05 * diff;
chArea.AxisY.Maximum = maxY + 0.05 * diff;
}
else if (minY >= 0)
{
/// fromZero = true, All points are above zero
chArea.AxisY.IsStartedFromZero = true;
chArea.AxisY.Minimum = 0;
chArea.AxisY.Maximum = 1.05 * maxY;
}
else if (maxY <= 0)
{
/// fromZero = true, All points are below zero
chArea.AxisY.IsStartedFromZero = true;
chArea.AxisY.Minimum = 1.05 * minY;
chArea.AxisY.Maximum = 0;
}
else
{
/// Points are both below and above zero
chArea.AxisY.IsStartedFromZero = false;
float diff = maxY - minY;
chArea.AxisY.Minimum = minY - 0.05 * diff;
chArea.AxisY.Maximum = maxY + 0.05 * diff;
}
if (chArea.AxisY.Maximum == chArea.AxisY.Minimum)
{
chArea.AxisY.Maximum = chArea.AxisY.Maximum + 1;
}
Chart chart = new Chart { Text = caption, Dock = DockStyle.Fill };
chart.ChartAreas.Add(chArea);
chart.Series.Add(series1);
if (series2 != null) chart.Series.Add(series2);
if (series3 != null) chart.Series.Add(series3);
return chart;
}
}
}
+50 -58
View File
@@ -199,8 +199,7 @@ namespace GemCard
{
Disconnect(DISCONNECT.Unpower);
try { ReleaseContext(); }
catch { }
ReleaseContext();
}
#region ICard Members
@@ -216,73 +215,66 @@ namespace GemCard
/// <returns>A string array of the readers</returns>
public override string[] ListReaders()
{
try
{
EstablishContext(SCOPE.User);
EstablishContext(SCOPE.User);
string[] sListReaders = null;
UInt32 pchReaders = 0;
IntPtr szListReaders = IntPtr.Zero;
string[] sListReaders = null;
UInt32 pchReaders = 0;
IntPtr szListReaders = IntPtr.Zero;
m_nLastError = SCardListReaders(m_hContext, null, szListReaders, out pchReaders);
if (m_nLastError == 0)
{
szListReaders = Marshal.AllocHGlobal((int)pchReaders);
m_nLastError = SCardListReaders(m_hContext, null, szListReaders, out pchReaders);
if (m_nLastError == 0)
{
char[] caReadersData = new char[pchReaders];
int nbReaders = 0;
for (int nI = 0; nI < pchReaders; nI++)
{
caReadersData[nI] = (char)Marshal.ReadByte(szListReaders, nI);
m_nLastError = SCardListReaders(m_hContext, null, szListReaders, out pchReaders);
if (m_nLastError == 0)
{
szListReaders = Marshal.AllocHGlobal((int) pchReaders);
m_nLastError = SCardListReaders(m_hContext, null, szListReaders, out pchReaders);
if (m_nLastError == 0)
{
char[] caReadersData = new char[pchReaders];
int nbReaders = 0;
for (int nI = 0; nI < pchReaders; nI++)
{
caReadersData[nI] = (char) Marshal.ReadByte(szListReaders, nI);
if (caReadersData[nI] == 0)
nbReaders++;
}
if (caReadersData[nI] == 0)
nbReaders++;
}
// Remove last 0
--nbReaders;
// Remove last 0
--nbReaders;
if (nbReaders != 0)
{
sListReaders = new string[nbReaders];
char[] caReader = new char[pchReaders];
int nIdx = 0;
int nIdy = 0;
int nIdz = 0;
// Get the nJ string from the multi-string
if (nbReaders != 0)
{
sListReaders = new string[nbReaders];
char[] caReader = new char[pchReaders];
int nIdx = 0;
int nIdy = 0;
int nIdz = 0;
// Get the nJ string from the multi-string
while (nIdx < pchReaders - 1)
{
caReader[nIdy] = caReadersData[nIdx];
if (caReader[nIdy] == 0)
{
sListReaders[nIdz] = new string(caReader, 0, nIdy);
++nIdz;
nIdy = 0;
caReader = new char[pchReaders];
}
else
++nIdy;
while(nIdx < pchReaders - 1)
{
caReader[nIdy] = caReadersData[nIdx];
if (caReader[nIdy] == 0)
{
sListReaders[nIdz] = new string(caReader, 0, nIdy);
++nIdz;
nIdy = 0;
caReader = new char[pchReaders];
}
else
++nIdy;
++nIdx;
}
}
++nIdx;
}
}
}
}
Marshal.FreeHGlobal(szListReaders);
}
Marshal.FreeHGlobal(szListReaders);
}
ReleaseContext();
ReleaseContext();
return sListReaders;
}
catch
{
return new string[0];
}
return sListReaders;
}
/// <summary>
+2 -2
View File
@@ -97,7 +97,7 @@
<BaseAddress>285212672</BaseAddress>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<FileAlignment>4096</FileAlignment>
<PlatformTarget>AnyCPU</PlatformTarget>
<PlatformTarget>x86</PlatformTarget>
<CodeAnalysisIgnoreBuiltInRuleSets>true</CodeAnalysisIgnoreBuiltInRuleSets>
<CodeAnalysisIgnoreBuiltInRules>true</CodeAnalysisIgnoreBuiltInRules>
<CodeAnalysisFailOnMissingRules>false</CodeAnalysisFailOnMissingRules>
@@ -110,7 +110,7 @@
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<Optimize>true</Optimize>
<FileAlignment>4096</FileAlignment>
<PlatformTarget>AnyCPU</PlatformTarget>
<PlatformTarget>x86</PlatformTarget>
<CodeAnalysisIgnoreBuiltInRuleSets>false</CodeAnalysisIgnoreBuiltInRuleSets>
<CodeAnalysisIgnoreBuiltInRules>false</CodeAnalysisIgnoreBuiltInRules>
<Prefer32Bit>false</Prefer32Bit>
+1 -3
View File
@@ -35,7 +35,7 @@
</FileUpgradeFlags>
<UpgradeBackupLocation>
</UpgradeBackupLocation>
<TargetFrameworkVersion>v4.7.2</TargetFrameworkVersion>
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
<OldToolsVersion>2.0</OldToolsVersion>
<PublishUrl>publish\</PublishUrl>
<Install>true</Install>
@@ -76,7 +76,6 @@
<WarningLevel>4</WarningLevel>
<DebugType>full</DebugType>
<ErrorReport>prompt</ErrorReport>
<Prefer32Bit>false</Prefer32Bit>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<OutputPath>bin\Release\</OutputPath>
@@ -100,7 +99,6 @@
<WarningLevel>4</WarningLevel>
<DebugType>none</DebugType>
<ErrorReport>prompt</ErrorReport>
<Prefer32Bit>false</Prefer32Bit>
</PropertyGroup>
<ItemGroup>
<Reference Include="System">
-6
View File
@@ -1,6 +0,0 @@
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2" />
</startup>
</configuration>
-84
View File
@@ -1,84 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{9786D0A8-BA9A-41F6-9E61-C7B2B76D4C08}</ProjectGuid>
<OutputType>Exe</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>MergeResultsDBs</RootNamespace>
<AssemblyName>MergeResultsDBs</AssemblyName>
<TargetFrameworkVersion>v4.7.2</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="FluentNHibernate">
<HintPath>..\packages\FluentNHibernate.2.0.3.0\lib\net40\FluentNHibernate.dll</HintPath>
</Reference>
<Reference Include="Iesi.Collections">
<HintPath>..\packages\Iesi.Collections.4.0.0.4000\lib\net40\Iesi.Collections.dll</HintPath>
</Reference>
<Reference Include="log4net">
<HintPath>..\packages\log4net.2.0.2\lib\net40-full\log4net.dll</HintPath>
</Reference>
<Reference Include="MySql.Data">
<HintPath>..\packages\MySql.Data.6.6.5\lib\net40\MySql.Data.dll</HintPath>
</Reference>
<Reference Include="NHibernate">
<HintPath>..\packages\NHibernate.4.0.4.4000\lib\net40\NHibernate.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Windows.Forms" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<ItemGroup>
<None Include="App.config" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Config\Config.csproj">
<Project>{743df7db-c7b6-42eb-986d-0f485e5588e4}</Project>
<Name>Config</Name>
</ProjectReference>
<ProjectReference Include="..\Results\Results.csproj">
<Project>{9d0dcc88-dc81-47eb-9fdd-4c3907871bfb}</Project>
<Name>Results</Name>
</ProjectReference>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>
-190
View File
@@ -1,190 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using log4net;
using NHibernate;
using FluentNHibernate;
using Results;
using Results.Entities;
namespace MergeResultsDBs
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("A range of records from the 2nd database will be appended to the 1st database.");
Console.WriteLine("Enter the 1st (target) database name:");
string firstDB = Console.ReadLine();
Console.WriteLine("Enter the 2nd database name:");
string secondDB = Console.ReadLine();
Console.WriteLine("Enter range of batch numbers from the 2nd DB to append to the 1st DB (start-end):");
string range = Console.ReadLine();
ISession session1;
IList<Components> componentsList;
int componentsListInitialCount;
IList<TestData> testDataList;
int testDataListInitialCount;
IList<WaterMeterData> waterMeterDataList;
int waterMeterDataListInitialCount;
try
{
DB.ConnectionString = string.Format("SERVER=localhost; DATABASE={0}; UID=root; PASSWORD=kraken; CHARSET=utf8;", firstDB);
session1 = DB.CreateSession();
componentsList = session1.QueryOver<Components>().List();
componentsListInitialCount = componentsList.Count;
testDataList = session1.QueryOver<TestData>().List();
testDataListInitialCount = testDataList.Count();
waterMeterDataList = session1.QueryOver<WaterMeterData>().List();
waterMeterDataListInitialCount = waterMeterDataList.Count();
}
catch (Exception exc)
{
MessageBox.Show(string.Format("Cannot open the 1st database:\r\n{0}", exc.Message));
return;
}
ISession session2;
IList<Components> oriComponentsList;
IList<TestData> oriTestDataList;
IList<WaterMeterData> oriWMDataList;
try
{
DB.ConnectionString = string.Format("SERVER=localhost; DATABASE={0}; UID=root; PASSWORD=kraken; CHARSET=utf8;", secondDB);
session2 = DB.CreateSession();
oriComponentsList = session2.QueryOver<Components>().List();
oriTestDataList = session2.QueryOver<TestData>().List();
oriWMDataList = session2.QueryOver<WaterMeterData>().List();
}
catch (Exception exc)
{
MessageBox.Show(string.Format("Cannot open the 2nd database:\r\n{0}", exc.Message));
return;
}
int batchNrStart;
int batchNrEnd;
string[] fields = range.Split(new char[] { '-' });
if (fields.Length != 2 ||
!int.TryParse(fields[0], out batchNrStart) ||
!int.TryParse(fields[1], out batchNrEnd) ||
batchNrEnd < batchNrStart)
{
MessageBox.Show("Invalid range of batch numbers");
return;
}
Console.WriteLine(string.Format("Appending batches {0}-{1} from DB {2} to DB {3}", batchNrStart, batchNrEnd, secondDB, firstDB));
Console.WriteLine("Press 'y' or 'Y' to start, anything else to abort");
string response = Console.ReadLine();
if (response != "y" && response != "Y")
{
return;
}
Console.WriteLine("PROCESSING DATABASES ...");
for (int batchNr = batchNrStart; batchNr <= batchNrEnd; batchNr++)
{
Console.Write(string.Format("{0} ", batchNr));
/// Copy one batch from the 2nd to the 1st database
var oriBatches = session2.QueryOver<Batch>()
.Where(x => (x.BatchNr == batchNr))
.List();
if (oriBatches.Count != 1) continue;
///---------------------------------------------------------------
Batch oriBatch = oriBatches[0];
var transaction = session1.BeginTransaction();
try
{
Batch batch = new Batch(oriBatch);
oriBatch.TestRslts = session2.QueryOver<TestRslt>()
.Where(x => (x.Batch.Id == oriBatch.Id))
.List();
foreach (var oriTR in oriBatch.TestRslts)
{
/// Find appropriate Components
Components components = oriTR.Components == null
? null
: Components.UpdateList(componentsList, new Components(oriTR.Components));
if (components != null) session1.SaveOrUpdate(components);
/// Find appropriate TestData
TestData testData = TestData.UpdateList(testDataList, new TestData(oriTR.TestData));
session1.SaveOrUpdate(testData);
TestRslt tr = new TestRslt();
tr.CopyContentFrom(oriTR);
tr.Batch = batch;
tr.Components = components;
tr.TestData = testData;
batch.TestRslts.Add(tr);
session1.SaveOrUpdate(tr);
}
oriBatch.WaterMeters = session2.QueryOver<WaterMeter>()
.Where(x => (x.Batch.Id == oriBatch.Id))
.List();
foreach (var oriWM in oriBatch.WaterMeters)
{
/// Find appropriate WaterMeterData
WaterMeterData wmData = WaterMeterData.UpdateList(waterMeterDataList, new WaterMeterData(oriWM.WaterMeterData));
session1.SaveOrUpdate(wmData);
WaterMeter wm = new WaterMeter();
wm.CopyContentFrom(oriWM);
wm.Batch = batch;
wm.WaterMeterData = wmData;
foreach (var oriMTR in oriWM.MeterTestRslts)
{
MeterTestRslt mtr = new MeterTestRslt(oriMTR);
mtr.WaterMeter = wm;
mtr.TestRslt = batch.TestRslts.FirstOrDefault<TestRslt>(x => (x.Name() == oriMTR.TestRslt.Name() &&
x.Part == oriMTR.TestRslt.Part &&
x.RepetitionNr == oriMTR.TestRslt.RepetitionNr));
if (mtr.TestRslt == null)
{
throw new Exception("Something strange happened");
}
wm.MeterTestRslts.Add(mtr);
session1.SaveOrUpdate(mtr);
}
batch.WaterMeters.Add(wm);
session1.SaveOrUpdate(wm);
}
session1.SaveOrUpdate(batch);
transaction.Commit();
}
catch
{
transaction.Rollback();
throw new Exception("Commit failed - transaction reverted");
}
}
Console.WriteLine();
session1.Flush();
session1.Close();
session2.Close();
Console.WriteLine("Successfully completed");
Console.ReadLine();
}
}
}
@@ -1,36 +0,0 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("MergeResultsDBs")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("MergeResultsDBs")]
[assembly: AssemblyCopyright("Copyright © 2021")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("f7543f83-5414-4010-ac3f-3af4b6864812")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
+3 -3
View File
@@ -48,9 +48,9 @@
<None Include="App.config" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Common\Common.csproj">
<Project>{c8939821-ba5c-4988-a3d0-bf53b74865c7}</Project>
<Name>Common</Name>
<ProjectReference Include="..\Config\Config.csproj">
<Project>{743df7db-c7b6-42eb-986d-0f485e5588e4}</Project>
<Name>Config</Name>
</ProjectReference>
<ProjectReference Include="..\TBF\TBF.csproj">
<Project>{8648fd92-cda1-4c3a-b5f9-fe547ce1fa48}</Project>
+2 -2
View File
@@ -20,7 +20,7 @@
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<PlatformTarget>AnyCPU</PlatformTarget>
<PlatformTarget>x86</PlatformTarget>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
@@ -29,7 +29,7 @@
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<PlatformTarget>AnyCPU</PlatformTarget>
<PlatformTarget>x86</PlatformTarget>
</PropertyGroup>
<ItemGroup>
<Reference Include="Newtonsoft.Json, Version=12.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL">
+44 -47
View File
@@ -1,12 +1,8 @@
///
/// Copyright (c) 2021 Sensus Slovensko a.s.
///
using System;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using Common;
using Results.Entities;
namespace Results
@@ -44,7 +40,7 @@ namespace Results
public static BatchResults NewFromProcedure(int batchNr, int benchId, string benchName, string a1, string a2, string a3, string a4, string a5,
string user, int userNr, string programVer, Config.Entities.Procedure procedure,
WaterMeterData[] waterMeterDatas, int[] waterMeterParts, double realDensity, double atTemperature, double buoyancy)
WaterMeterData[] waterMeterDatas, int[] waterMeterParts, double densityCorr)
{
BatchResults d = new BatchResults(waterMeterDatas.Length);
int year = DateTime.Now.Year;
@@ -69,12 +65,10 @@ namespace Results
ProcedureRevision = procedure.Revision,
ProtocolTitle = string.Empty,
StartTime = DateTime.Now,
RealDensity = realDensity,
AtTemperature = atTemperature,
Buoyancy = buoyancy,
Compound = (procedure.MetersKind == MetersKind.Combined),
DensityCorr = (float)densityCorr,
Compound = (procedure.MetersKind == Config.Entities.MetersKind.Combined),
#if HEAT_METERS
HeatMeter = (procedure.MetersKind == MetersKind.HeatMeter),
HeatMeter = (procedure.MetersKind == Config.Entities.MetersKind.HeatMeter),
#endif
};
@@ -102,42 +96,45 @@ namespace Results
}
}
foreach (var ti in procedure.GetTestInstances())
foreach (var t in procedure.Tests)
{
TestData td = TestData.UpdateList(d.TestDataList, new TestData(ti.Test));
if (!d.Batch.Tests.Contains(td)) d.Batch.Tests.Add(td);
TestData td = TestData.UpdateList(d.TestDataList, new TestData(t));
/// Create an empty test result and add it to the list
TestRslt tr = new TestRslt(d.Batch, td, ti.Test.Part, ti.Repetition);
d.Batch.TestRslts.Add(tr);
for (int i = 0; i < d.WMPositionsCount; i++)
for (int rnr = 1; rnr <= t.Repeats; rnr++)
{
if (!d.Batch.WaterMeters[i].Disabled && ti.Test.IsPartCompatible(waterMeterParts[i]))
{
///
/// Create empty watermeter test results and add them to the list and to dictionaries
///
IList<MeterTestRslt> wmtrs = d.Batch.WaterMeters[i].MeterTestRslts;
if (d.Batch.Compound)
/// Create an empty test result and add it to the list
TestRslt tr = new TestRslt(d.Batch, td, t.Part, rnr);
d.Batch.TestRslts.Add(tr);
for (int i = 0; i < d.WMPositionsCount; i++)
{
if (!d.Batch.WaterMeters[i].Disabled && t.IsPartCompatible(waterMeterParts[i]))
{
/// Compound water meter
wmtrs.Add(new MeterTestRslt(d.Batch.WaterMeters[i], tr, CompoundMeterId.CompoundMain));
wmtrs.Add(new MeterTestRslt(d.Batch.WaterMeters[i], tr, CompoundMeterId.CompoundAux));
wmtrs.Add(new MeterTestRslt(d.Batch.WaterMeters[i], tr, CompoundMeterId.Compound));
///
/// Create empty watermeter test results and add them to the list and to dictionaries
///
IList<MeterTestRslt> wmtrs = d.Batch.WaterMeters[i].MeterTestRslts;
if (d.Batch.Compound)
{
/// Compound water meter
wmtrs.Add(new MeterTestRslt(d.Batch.WaterMeters[i], tr, Config.Entities.CompoundMeterId.CompoundMain));
wmtrs.Add(new MeterTestRslt(d.Batch.WaterMeters[i], tr, Config.Entities.CompoundMeterId.CompoundAux));
wmtrs.Add(new MeterTestRslt(d.Batch.WaterMeters[i], tr, Config.Entities.CompoundMeterId.Compound));
}
else if (d.Batch.HeatMeter)
{
/// Heat meter
wmtrs.Add(new MeterTestRslt(d.Batch.WaterMeters[i], tr, Config.Entities.CompoundMeterId.HeatMeterVolume));
wmtrs.Add(new MeterTestRslt(d.Batch.WaterMeters[i], tr, Config.Entities.CompoundMeterId.HeatMeterEnergy));
}
else
{
/// Water meter
wmtrs.Add(new MeterTestRslt(d.Batch.WaterMeters[i], tr, Config.Entities.CompoundMeterId.Single));
}
}
else if (d.Batch.HeatMeter)
{
/// Heat meter
wmtrs.Add(new MeterTestRslt(d.Batch.WaterMeters[i], tr, CompoundMeterId.HeatMeterVolume));
wmtrs.Add(new MeterTestRslt(d.Batch.WaterMeters[i], tr, CompoundMeterId.HeatMeterEnergy));
}
else
{
/// Water meter
wmtrs.Add(new MeterTestRslt(d.Batch.WaterMeters[i], tr, CompoundMeterId.Single));
}
}
}
}
}
@@ -159,10 +156,10 @@ namespace Results
if (batch.WaterMeters[wmNr0].WMPosition > wmNr0 + 1)
{
batch.WaterMeters.Insert(wmNr0, new WaterMeter() { Batch = batch,
WaterMeterData = null,
WMPosition = wmNr0 + 1,
YearOfProduction = 0,
Disabled = true, });
WaterMeterData = null,
WMPosition = wmNr0 + 1,
YearOfProduction = 0,
Disabled = true, });
}
}
@@ -174,7 +171,7 @@ namespace Results
return Batch.GetTestRslt(name, part);
}
public MeterTestRslt GetMeterTestRslt(string name, int wmNr0, CompoundMeterId meterId = CompoundMeterId.Single)
public MeterTestRslt GetMeterTestRslt(string name, int wmNr0, Config.Entities.CompoundMeterId meterId)
{
if (Batch.WaterMeters != null && Batch.WaterMeters.Count > wmNr0 && !Batch.WaterMeters[wmNr0].Disabled)
{
+20 -52
View File
@@ -37,9 +37,9 @@ namespace Results
}
/// <summary> Database type (MySQL or SQLite) for all sessions </summary>
private static Common.DBType dbType;
private static Users.Entities.DBType dbType;
///
public static Common.DBType DbType
public static Users.Entities.DBType DbType
{
get { return dbType; }
set { dbType = value; SessionFactory = null; }
@@ -66,10 +66,10 @@ namespace Results
switch (dbType)
{
default:
case Common.DBType.MySql:
case Users.Entities.DBType.MySql:
cfg = cfg.Database(MySQLConfiguration.Standard.ConnectionString(connectionString));
break;
case Common.DBType.SQLite:
case Users.Entities.DBType.SQLite:
cfg = cfg.Database(SQLiteConfiguration.Standard.UsingFile(connectionString));
break;
}
@@ -78,17 +78,11 @@ namespace Results
if (createDB)
{
return cfg.ExposeConfiguration(BuildSchemaCreate)
.BuildConfiguration()
.SetProperty("hibernate.connection.connect_timeout", Common.Const.MySqlConnectTimeoutSec)
.BuildSessionFactory();
return cfg.ExposeConfiguration(BuildSchemaCreate).BuildSessionFactory();
}
else
{
return cfg.ExposeConfiguration(BuildSchema)
.BuildConfiguration()
.SetProperty("hibernate.connection.connect_timeout", Common.Const.MySqlConnectTimeoutSec)
.BuildSessionFactory();
return cfg.ExposeConfiguration(BuildSchema).BuildSessionFactory();
}
}
@@ -186,55 +180,29 @@ namespace Results
/// Loads shared data from the database
/// </summary>
/// <exception>Throws NHibernate exceptions</exception>
public static void LoadSharedData(ISession session = null)
public static void LoadSharedData()
{
bool openAndCloseSession = (session == null);
ISession session = DB.CreateSession();
try
{
if (openAndCloseSession) session = Results.DB.CreateSession();
TestDataList = session.QueryOver<TestData>().List();
ComponentsList = session.QueryOver<Components>().List();
WaterMeterDataList = session.QueryOver<WaterMeterData>().List();
}
catch (Exception e)
{
log.ErrorFormat("Cannot open results DB: {0}", e.Message);
}
finally
{
if (openAndCloseSession && session != null && session.IsOpen) session.Close();
}
}
TestDataList = session.QueryOver<TestData>().List();
ComponentsList = session.QueryOver<Components>().List();
WaterMeterDataList = session.QueryOver<WaterMeterData>().List();
}
/// <summary>
/// Loads shared data from the database
/// </summary>
/// <exception>Throws NHibernate exceptions</exception>
public static int GetMaxSavedBatchNr(ISession session = null)
public static int GetMaxSavedBatchNr()
{
bool openAndCloseSession = (session == null);
int maxBatchNr = 0;
try
{
if (openAndCloseSession) session = Results.DB.CreateSession();
IList<Entities.Batch> batches = session.QueryOver<Batch>().List();
foreach (var b in batches)
{
if (b.BatchNr > maxBatchNr) maxBatchNr = b.BatchNr;
}
}
catch (Exception e)
{
log.ErrorFormat("Cannot open results DB: {0}", e.Message);
}
finally
{
if (openAndCloseSession && session != null && session.IsOpen) session.Close();
}
ISession session = DB.CreateSession();
IList<Entities.Batch> batches = session.QueryOver<Batch>().List();
int maxBatchNr = 0;
foreach (var b in batches)
{
if (b.BatchNr > maxBatchNr) maxBatchNr = b.BatchNr;
}
return maxBatchNr;
}
-2
View File
@@ -40,8 +40,6 @@ namespace Results
.Database(MySQLConfiguration.Standard.ConnectionString(connectionString))
.Mappings(m => m.FluentMappings.AddFromAssemblyOf<Entities.WaterMeterData>())
.ExposeConfiguration(BuildSchema)
.BuildConfiguration()
.SetProperty("hibernate.connection.connect_timeout", Common.Const.MySqlConnectTimeoutSec)
.BuildSessionFactory();
}
+66 -104
View File
@@ -1,55 +1,51 @@
///
/// Copyright (c) 2015-2023 Sensus Slovensko a.s.
/// Copyright (c) 2015-2020 Sensus Slovensko a.s.
///
using System;
using System.Collections.Generic;
using System.IO;
using Common;
namespace Results.Entities
{
public class Batch
{
public virtual int Id { get; protected set; }
public virtual int BatchNr { get; set; }
public virtual int BatchNr { get; set; }
public virtual string ProgramVersion { get; set; }
public virtual int TestBenchId { get; set; }
public virtual string TestBenchName { get; set; } /// CEVAK, not mapped to DB
public virtual string Address1 { get; set; } /// CEVAK, not mapped to DB
public virtual string Address2 { get; set; } /// CEVAK, not mapped to DB
public virtual string Address3 { get; set; } /// CEVAK, not mapped to DB
public virtual string Address4 { get; set; } /// CEVAK, not mapped to DB
public virtual string Address5 { get; set; } /// CEVAK, not mapped to DB
public virtual string UserName { get; set; }
public virtual int UserNumber { get; set; }
public virtual string ProcedureName { get; set; }
public virtual string TestBenchName { get; set; } /// CEVAK, not mapped to DB
public virtual string Address1 { get; set; } /// CEVAK, not mapped to DB
public virtual string Address2 { get; set; } /// CEVAK, not mapped to DB
public virtual string Address3 { get; set; } /// CEVAK, not mapped to DB
public virtual string Address4 { get; set; } /// CEVAK, not mapped to DB
public virtual string Address5 { get; set; } /// CEVAK, not mapped to DB
public virtual string UserName { get; set; }
public virtual int UserNumber { get; set; }
public virtual string ProcedureName { get; set; }
public virtual bool IsRemoteProcedure { get; set; } /// Stara Tura, not mapped to DB
public virtual string PurchaseOrder { get; set; } /// Stara Tura, Nanjing, not mapped to DB
public virtual string Workflow { get; set; } /// Stara Tura, Nanjing, not mapped to DB
public virtual string ProcedureDescription { get; set; } /// CEVAK, not mapped to DB
public virtual int ProcedureRevision { get; set; }
public virtual string WatermetersStr { get; set; } /// CEVAK, not mapped to DB
public virtual string ProtocolTitle { get; set; }
public virtual string ProcedureDescription { get; set; } /// CEVAK, not mapped to DB
public virtual int ProcedureRevision { get; set; }
public virtual string WatermetersStr { get; set; } /// CEVAK, not mapped to DB
public virtual string ProtocolTitle { get; set; }
public virtual string Remark { get; set; }
public virtual double RealDensity { get; set; } /// Density correction in [kg/m3]
public virtual double AtTemperature { get; set; }
public virtual double Buoyancy { get; set; }
public virtual float DensityCorr { get; set; } /// Density correction in [kg/m3]
public virtual float Custom2 { get; set; }
public virtual float Custom3 { get; set; }
public virtual int Counter6 { get; set; }
public virtual int Counter7 { get; set; }
public virtual int Counter8 { get; set; }
public virtual int Counter9 { get; set; }
public virtual int Counter10 { get; set; }
public virtual DateTime StartTime { get; set; }
public virtual DateTime EndTime { get; set; }
public virtual DateTime SaveTime { get; set; }
public virtual DateTime EndTime { get; set; }
public virtual bool Dirty { get; set; }
public virtual bool RsltsSent { get; set; }
public virtual bool RsltsPrinted { get; set; }
public virtual IList<TestData> Tests { get; set; }
public virtual IList<WaterMeter> WaterMeters { get; set; }
public virtual IList<TestRslt> TestRslts { get; set; }
public virtual bool Compound { get; set; } /// Not mapped to DB now
public virtual bool HeatMeter { get; set; } /// Not mapped to DB now
public virtual bool RsltsPrinted { get; set; }
public virtual IList<TestData> Tests { get; set; }
public virtual IList<WaterMeter> WaterMeters { get; set; }
public virtual IList<TestRslt> TestRslts { get; set; }
public virtual bool Compound { get; set; } /// Not mapped to DB now
public virtual bool HeatMeter { get; set; } /// Not mapped to DB now
public virtual IList<TestData> RegularTests()
{
@@ -121,55 +117,8 @@ namespace Results.Entities
ProtocolTitle = string.Empty;
ProtocolTitle = string.Empty;
Remark = string.Empty;
RealDensity = Config.Data.RealDensity;
AtTemperature = Config.Data.AtTemperature;
Buoyancy = Config.Data.Buoyancy;
}
/// <summary>
/// Copy constructor, copies all except of Id.
/// Lists Tests, WaterMeters and TestRslts are empty. Have to be copied elwhere.
/// </summary>
public Batch(Batch oriBatch)
{
BatchNr = oriBatch.BatchNr;
ProgramVersion = oriBatch.ProgramVersion;
TestBenchId = oriBatch.TestBenchId;
TestBenchName = oriBatch.TestBenchName;
Address1 = oriBatch.Address1;
Address2 = oriBatch.Address2;
Address3 = oriBatch.Address3;
Address4 = oriBatch.Address4;
Address5 = oriBatch.Address5;
UserName = oriBatch.UserName;
UserNumber = oriBatch.UserNumber;
ProcedureName = oriBatch.ProcedureName;
IsRemoteProcedure = oriBatch.IsRemoteProcedure;
ProcedureDescription = oriBatch.ProcedureDescription;
ProcedureRevision = oriBatch.ProcedureRevision;
WatermetersStr = oriBatch.WatermetersStr;
ProtocolTitle = oriBatch.ProtocolTitle;
Remark = oriBatch.Remark;
RealDensity = oriBatch.RealDensity;
AtTemperature = oriBatch.AtTemperature;
Buoyancy = oriBatch.Buoyancy;
Counter6 = oriBatch.Counter6;
Counter7 = oriBatch.Counter7;
Counter8 = oriBatch.Counter8;
Counter9 = oriBatch.Counter9;
Counter10 = oriBatch.Counter10;
StartTime = oriBatch.StartTime;
EndTime = oriBatch.EndTime;
SaveTime = oriBatch.SaveTime;
Dirty = oriBatch.Dirty;
RsltsSent = oriBatch.RsltsSent;
RsltsPrinted = oriBatch.RsltsPrinted;
Tests = new List<TestData>();
WaterMeters = new List<WaterMeter>();
TestRslts = new List<TestRslt>();
}
public virtual int PassedMetersCount()
{
int count = 0;
@@ -211,7 +160,7 @@ namespace Results.Entities
foreach (var tr in TestRslts)
{
if (tr.TestDone && tr.AmbTempMean != 0)
if (tr.TestDone)
{
double duration = (tr.EndTime - tr.StartTime).TotalSeconds;
timeSum += duration;
@@ -229,7 +178,7 @@ namespace Results.Entities
foreach (var tr in TestRslts)
{
if (tr.TestDone && tr.AmbPressMean != 0)
if (tr.TestDone)
{
double duration = (tr.EndTime - tr.StartTime).TotalSeconds;
timeSum += duration;
@@ -247,7 +196,7 @@ namespace Results.Entities
foreach (var tr in TestRslts)
{
if (tr.TestDone && tr.AmbHumiMean != 0)
if (tr.TestDone)
{
double duration = (tr.EndTime - tr.StartTime).TotalSeconds;
timeSum += duration;
@@ -262,7 +211,7 @@ namespace Results.Entities
{
for (int i = 0; i < TestRslts.Count; i++)
{
if (TestRslts[i].Publish() == Common.Publish.Always && TestRslts[i].AmbTempStart != 0)
if (TestRslts[i].Publish() == Config.Entities.Publish.Always)
return TestRslts[i].AmbTempStart;
}
return 0;
@@ -271,7 +220,7 @@ namespace Results.Entities
{
for (int i = 0; i < TestRslts.Count; i++)
{
if (TestRslts[i].Publish() == Common.Publish.Always && TestRslts[i].AmbPressStart != 0)
if (TestRslts[i].Publish() == Config.Entities.Publish.Always)
return TestRslts[i].AmbPressStart;
}
return 0;
@@ -280,7 +229,7 @@ namespace Results.Entities
{
for (int i = 0; i < TestRslts.Count; i++)
{
if (TestRslts[i].Publish() == Common.Publish.Always && TestRslts[i].AmbHumiStart != 0)
if (TestRslts[i].Publish() == Config.Entities.Publish.Always)
return TestRslts[i].AmbHumiStart;
}
return 0;
@@ -288,32 +237,50 @@ namespace Results.Entities
public virtual double AmbTempEnd()
{
for (int i = TestRslts.Count - 1; i >= 0; i--)
for (int i = TestRslts.Count - 1; i >= 0; i++)
{
if (TestRslts[i].Publish() == Common.Publish.Always && TestRslts[i].AmbTempEnd != 0)
if (TestRslts[i].Publish() == Config.Entities.Publish.Always)
return TestRslts[i].AmbTempEnd;
}
return 0;
}
public virtual double AmbPressEnd()
{
for (int i = TestRslts.Count - 1; i >= 0; i--)
for (int i = TestRslts.Count - 1; i >= 0; i++)
{
if (TestRslts[i].Publish() == Common.Publish.Always && TestRslts[i].AmbPressEnd != 0)
if (TestRslts[i].Publish() == Config.Entities.Publish.Always)
return TestRslts[i].AmbPressEnd;
}
return 0;
}
public virtual double AmbHumiEnd()
{
for (int i = TestRslts.Count - 1; i >= 0; i--)
for (int i = TestRslts.Count - 1; i >= 0; i++)
{
if (TestRslts[i].Publish() == Common.Publish.Always && TestRslts[i].AmbHumiEnd != 0)
if (TestRslts[i].Publish() == Config.Entities.Publish.Always)
return TestRslts[i].AmbHumiEnd;
}
return 0;
}
public virtual double Buoyancy()
{
double timeSum = 0;
double sum = 0;
foreach (var tr in TestRslts)
{
if (tr.TestData.Evaluate && tr.TestDone)
{
double duration = (tr.EndTime - tr.StartTime).TotalSeconds;
timeSum += duration;
sum += (tr.Buoyancy * duration);
}
}
return (timeSum == 0) ? 0 : (sum / timeSum);
}
public virtual TestRslt GetTestRslt(string name, int part)
{
foreach (var tr in TestRslts)
@@ -325,19 +292,16 @@ namespace Results.Entities
public override string ToString()
{
return string.Format("Batch {0} ({1}s) Start {2}, End {3}, Proc={4}",
BatchNr, (EndTime - StartTime).TotalSeconds, StartTime, EndTime, ProcedureName);
return string.Format("Batch #{0}, Start:{1}, End:{2}, Procedure:{3}", BatchNr, StartTime, EndTime, ProcedureName);
}
public virtual string ToString(int i)
{
return string.Format("Batch {0} ({1}s) ver={2} TestBenchId={3} User={4}/{5} Proc={6}{7} Rev={8} Remark={9} RealDensity={10} AtTemperature={11} Buoyancy={12} StartTime={13} EndTime={14} SaveTime={15} RsltsSent={16} RsltsPrinted={17}",
BatchNr,
(EndTime - StartTime).TotalSeconds,
ProgramVersion, TestBenchId, UserName, UserNumber,
return string.Format("Batch: BatchNr={0} ProgramVersion={1} TestBenchId={2} UserName={3} UserNumber={4} ProcedureName={5}{6} ProcRev={7} ProtocolTitle={8} Remark={9} DensityCorr={10} Custom2={11} Custom3={12} StartTime={13} EndTime={14} Dirty={15} RsltsSent={16} RsltsPrinted={17}",
BatchNr, ProgramVersion, TestBenchId, UserName, UserNumber,
ProcedureName, (IsRemoteProcedure ? "(R)" : ""), ProcedureRevision,
Remark, RealDensity, AtTemperature, Buoyancy,
StartTime, EndTime, SaveTime, RsltsSent, RsltsPrinted);
ProtocolTitle, Remark, DensityCorr, Custom2, Custom3,
StartTime, EndTime, Dirty, RsltsSent, RsltsPrinted);
}
public virtual void WriteBinary(BinaryWriter writer)
@@ -361,9 +325,9 @@ namespace Results.Entities
writer.Write((WatermetersStr != null) ? WatermetersStr : string.Empty);
writer.Write((ProtocolTitle != null) ? ProtocolTitle : string.Empty);
writer.Write((Remark != null) ? Remark : string.Empty);
writer.Write(RealDensity);
writer.Write(AtTemperature);
writer.Write(Buoyancy);
writer.Write(DensityCorr);
writer.Write(Custom2);
writer.Write(Custom3);
writer.Write(Counter6);
writer.Write(Counter7);
writer.Write(Counter8);
@@ -371,7 +335,6 @@ namespace Results.Entities
writer.Write(Counter10);
writer.Write(StartTime.ToString());
writer.Write(EndTime.ToString());
writer.Write(SaveTime.ToString());
writer.Write(Dirty);
writer.Write(RsltsSent);
writer.Write(RsltsPrinted);
@@ -429,9 +392,9 @@ namespace Results.Entities
WatermetersStr = reader.ReadString();
ProtocolTitle = reader.ReadString();
Remark = reader.ReadString();
RealDensity = reader.ReadDouble();
AtTemperature = reader.ReadDouble();
Buoyancy = reader.ReadDouble();
DensityCorr = reader.ReadInt32();
Custom2 = reader.ReadInt32();
Custom3 = reader.ReadInt32();
Counter6 = reader.ReadInt32();
Counter7 = reader.ReadInt32();
Counter8 = reader.ReadInt32();
@@ -439,7 +402,6 @@ namespace Results.Entities
Counter10 = reader.ReadInt32();
StartTime = DateTime.Parse(reader.ReadString());
EndTime = DateTime.Parse(reader.ReadString());
SaveTime = DateTime.Parse(reader.ReadString());
Dirty = reader.ReadBoolean();
RsltsSent = reader.ReadBoolean();
RsltsPrinted = reader.ReadBoolean();
+9 -29
View File
@@ -22,25 +22,22 @@ namespace Results.Entities
public virtual string Custom2 { get; set; }
public virtual string Custom3 { get; set; }
/// <summary>
/// Default constructor, safe values
/// </summary>
public Components()
{
TestBenchId = 0;
TestBenchName = string.Empty;
Pump = string.Empty;
RegValve = string.Empty;
Flowmeter = string.Empty;
Diverter = string.Empty;
Scale = string.Empty;
Custom1 = string.Empty;
Custom2 = string.Empty;
Custom3 = string.Empty;
Pump = string.Empty;
RegValve = string.Empty;
Flowmeter = string.Empty;
Diverter = string.Empty;
Scale = string.Empty;
Custom1 = string.Empty;
Custom2 = string.Empty;
Custom3 = string.Empty;
}
public Components(int benchId, string benchName, string pump, string flowmeter,
string scale, string regValve, string diverter)
string scale, string regValve, string diverter)
{
TestBenchId = benchId;
TestBenchName = benchName;
@@ -54,23 +51,6 @@ namespace Results.Entities
Custom3 = string.Empty;
}
/// <summary>
/// Copy constructor, copies all except of Id
/// </summary>
public Components(Components oriComponents)
{
TestBenchId = oriComponents.TestBenchId;
TestBenchName = oriComponents.TestBenchName;
Pump = oriComponents.Pump;
RegValve = oriComponents.RegValve;
Flowmeter = oriComponents.Flowmeter;
Diverter = oriComponents.Diverter;
Scale = oriComponents.Scale;
Custom1 = oriComponents.Custom1;
Custom2 = oriComponents.Custom2;
Custom3 = oriComponents.Custom3;
}
/// <summary>
/// Method to compare the content of two entities
+43 -168
View File
@@ -1,64 +1,45 @@
///
/// Copyright (c) 2013-2021 Sensus Slovensko a.s.
/// Copyright (c) 2013-2020 Sensus Slovensko a.s.
///
using System;
using System.Collections.Generic;
using System.IO;
using Common;
namespace Results.Entities
{
public class MeterTestRslt
{
public virtual int Id { get; protected set; }
public virtual byte CompoundMeterId { get; set; } /// 0=single, 1=compound/main, 2=compound/aux., 3=compound/overal, 4=heat meter volume, 5=heat meter energy
public virtual int RegReaderType { get; set; } /// Not mapped to the DB, does not depend on localization and customer
public virtual double PulsesMeter { get; set; } /// # of water meter or heat meter pulses
public virtual double PulsesMaster { get; set; } /// # of reference flowmeter pulses (gated by this water meter pulses)
public virtual byte CompoundMeterId { get; set; } /// 0=single, 1=compound/main, 2=compound/aux., 3=compound/overal, 4=heat meter volume, 5=heat meter energy
public virtual int RegReaderType { get; set; } /// Not mapped to the DB, does not depend on localization and customer
public virtual double PulsesMeter { get; set; } /// # of water meter or heat meter pulses
public virtual double PulsesMaster { get; set; } /// # of reference flowmeter pulses (gated by this water meter pulses)
public virtual double PulsesPerLiter { get; set; } /// [l ^ -1], in case of heat meters (CompoundMeterId==5) pulses per kWh in [kWh ^ -1]
public virtual double VolumeStart { get; set; } /// Volume or energy (CompoundMeterId==5) on test start in [l] or [J]
public virtual double VolumeEnd { get; set; } /// Volume or energy (CompoundMeterId==5) on test end in [l] or [J]
public virtual double VolumeMeter { get; set; } /// Measured volume or energy (CompoundMeterId==5) in [l] or [J]
public virtual double VolumeRef { get; set; } /// Reference volume or energy (CompoundMeterId==5) in [l] or [J]
public virtual double TimestampStart { get; set; } /// [s]
public virtual double TimestampEnd { get; set; } /// [s]
public virtual double TestTime { get; set; } /// [s]
public virtual double TimestampStart { get; set; } /// [s]
public virtual double TimestampEnd { get; set; } /// [s]
public virtual double TestTime { get; set; } /// [s]
/// Main result
public virtual double Error { get; set; } /// [%]
/// Main result
public virtual double Error { get; set; } /// [%]
public virtual long ErrorIndicators { get; set; } /// Not mapped to DB !!!, bit24=E25, bit25=E26, bit26=E27, bit27=E28 (error flags)
public virtual long InfoIndicators { get; set; } /// Not mapped to DB !!!, bit24=E25, bit25=E26, bit26=E27, bit27=E28 (info flags)
public virtual bool TestDone { get; set; } /// true = test was completed
public virtual bool Passed { get; set; } /// true = test passed, water meter is OK
#if IPERL
public virtual int CalibFactor { get; set; }
public virtual int CalibFactorLNA { get; set; }
public virtual int Q2CorrRL { get; set; }
public virtual int Q2CorrLR { get; set; }
public virtual int FlowDirection { get; set; } /// 0=unknown, 1=RL, 2=LR
public virtual string ExtraDataPath { get; set; } /// Relative path to a file with opto-data/raw-data
public virtual float X1 { get; set; }
public virtual float X2 { get; set; }
public virtual float X3 { get; set; }
public virtual float X4 { get; set; }
public virtual float X5 { get; set; }
public virtual float X6 { get; set; }
public virtual float X7 { get; set; }
public virtual float X8 { get; set; }
public virtual float X9 { get; set; }
#endif
public virtual double KorrErrQ { get; set; } /// [%] not mapped to results DB, saved to Oracle DB
public virtual bool TestDone { get; set; } /// true = test was completed
public virtual bool Passed { get; set; } /// true = test passed, water meter is OK
#if ORACLE_DB
public virtual double ErrorBC { get; set; } /// [%] error before correction, saved to Oracle to table VT_PRUEFREIHE_IST_PD as KorrErrQ
public virtual double LastError { get; set; } /// [%] Previous test error at this Q in case Pruefindex > 1
#endif
public virtual WaterMeter WaterMeter { get; set; } /// reference to the WaterMeter entity
public virtual TestRslt TestRslt { get; set; } /// reference to the TestRslt entity
///
/// Wrappers
///
public virtual string Name() { return TestRslt.Name(); }
public virtual string Name() { return TestRslt.Name(); }
public virtual DateTime StartTime() { return TestRslt.StartTime; }
public virtual DateTime EndTime() { return TestRslt.EndTime; }
public virtual double FlowSetTime() { return TestRslt.FlowSetTime; } /// [s]
@@ -88,30 +69,23 @@ namespace Results.Entities
public virtual double QRise() { return WaterMeter.QRise; } /// [m3/h]
public virtual double QFall() { return WaterMeter.QFall; } /// [m3/h]
public virtual bool Evaluate() { return TestData().Evaluate; }
public virtual Common.Publish Publish() { return (Publish)TestData().Publish; }
public virtual bool Evaluate() { return TestData().Evaluate; }
public virtual Config.Entities.Publish Publish() { return (Config.Entities.Publish)TestData().Publish; }
public virtual WaterMeterData WaterMeterData() { return WaterMeter.WaterMeterData; }
public virtual Batch Batch() { return WaterMeter.Batch; }
public virtual bool IsPilotRslt()
{
return (CompoundMeterId == (byte)Common.CompoundMeterId.Single) ||
(CompoundMeterId == (byte)Common.CompoundMeterId.Compound) ||
(CompoundMeterId == (byte)Common.CompoundMeterId.HeatMeterEnergy);
return (CompoundMeterId == (byte)Config.Entities.CompoundMeterId.Single) ||
(CompoundMeterId == (byte)Config.Entities.CompoundMeterId.Compound) ||
(CompoundMeterId == (byte)Config.Entities.CompoundMeterId.HeatMeterEnergy);
}
public virtual bool IsPulses() { return (RegReaderType == (int)RegisterReaderType.Pulses || RegReaderType == (int)RegisterReaderType.Unknown); }
public virtual bool IsCamera() { return (RegReaderType == (int)RegisterReaderType.Camera); }
public virtual bool IsDataStream() { return (RegReaderType == (int)RegisterReaderType.DataStream); }
public virtual bool IsManual() { return (RegReaderType == (int)RegisterReaderType.Manual); }
public virtual string PassedOrErrorFlagsStr()
{
string eFlags = Utils.ErrorFlagsStr(ErrorIndicators);
var str = string.IsNullOrEmpty(eFlags) ? PassedColorStr(null) : eFlags;
return str;
}
public virtual bool IsPulses() { return (RegReaderType == (int)Config.Entities.RegisterReaderType.Pulses || RegReaderType == (int)Config.Entities.RegisterReaderType.Unknown); }
public virtual bool IsCamera() { return (RegReaderType == (int)Config.Entities.RegisterReaderType.Camera); }
public virtual bool IsDataStream() { return (RegReaderType == (int)Config.Entities.RegisterReaderType.DataStream); }
public virtual bool IsManual() { return (RegReaderType == (int)Config.Entities.RegisterReaderType.Manual); }
public virtual string PassedColorStr(string yesNoFormatOrEmpty)
{
@@ -132,7 +106,7 @@ namespace Results.Entities
Passed = false;
}
public MeterTestRslt(WaterMeter waterMeterRslt, TestRslt testRslt, CompoundMeterId compoundMeterId)
public MeterTestRslt(WaterMeter waterMeterRslt, TestRslt testRslt, Config.Entities.CompoundMeterId compoundMeterId)
: this()
{
WaterMeter = waterMeterRslt;
@@ -140,93 +114,28 @@ namespace Results.Entities
CompoundMeterId = (byte)compoundMeterId;
}
/// <summary>
/// Copy constructor, copies all except of Id
/// TestRslt and WaterMeter references arenot set.
/// They have to be copied/ser manually.
/// </summary>
public MeterTestRslt(MeterTestRslt oriMTR)
{
CompoundMeterId = oriMTR.CompoundMeterId;
RegReaderType = oriMTR.RegReaderType;
PulsesMeter = oriMTR.PulsesMeter;
PulsesMaster = oriMTR.PulsesMaster;
PulsesPerLiter = oriMTR.PulsesPerLiter;
VolumeStart = oriMTR.VolumeStart;
VolumeEnd = oriMTR.VolumeEnd;
VolumeMeter = oriMTR.VolumeMeter;
VolumeRef = oriMTR.VolumeRef;
TimestampStart = oriMTR.TimestampStart;
TimestampEnd = oriMTR.TimestampEnd;
TestTime = oriMTR.TestTime;
Error = oriMTR.Error;
ErrorIndicators = oriMTR.ErrorIndicators;
InfoIndicators = oriMTR.InfoIndicators;
TestDone = oriMTR.TestDone;
Passed = oriMTR.Passed;
#if IPERL
CalibFactor = oriMTR.CalibFactor;
CalibFactorLNA = oriMTR.CalibFactorLNA;
Q2CorrRL = oriMTR.Q2CorrRL;
Q2CorrLR = oriMTR.Q2CorrLR;
FlowDirection = oriMTR.FlowDirection;
ExtraDataPath = oriMTR.ExtraDataPath;
X1 = oriMTR.X1;
X2 = oriMTR.X2;
X3 = oriMTR.X3;
X4 = oriMTR.X4;
X5 = oriMTR.X5;
X6 = oriMTR.X6;
X7 = oriMTR.X7;
X8 = oriMTR.X8;
X9 = oriMTR.X9;
#endif
#if ORACLE_DB
ErrorBC = oriMTR.ErrorBC;
LastError = oriMTR.LastError;
#endif
}
public virtual void CopyContentFrom(MeterTestRslt src)
{
if (src == null) return;
CompoundMeterId = src.CompoundMeterId;
RegReaderType = src.RegReaderType;
PulsesMeter = src.PulsesMeter;
PulsesMaster = src.PulsesMaster;
PulsesPerLiter = src.PulsesPerLiter;
VolumeStart = src.VolumeStart;
VolumeEnd = src.VolumeEnd;
VolumeMeter = src.VolumeMeter;
VolumeRef = src.VolumeRef;
TimestampStart = src.TimestampStart;
TimestampEnd = src.TimestampEnd;
TestTime = src.TestTime;
Error = src.Error;
RegReaderType = src.RegReaderType;
PulsesMeter = src.PulsesMeter;
PulsesMaster = src.PulsesMaster;
PulsesPerLiter = src.PulsesPerLiter;
VolumeStart = src.VolumeStart;
VolumeEnd = src.VolumeEnd;
VolumeMeter = src.VolumeMeter;
VolumeRef = src.VolumeRef;
TimestampStart = src.TimestampStart;
TimestampEnd = src.TimestampEnd;
TestTime = src.TestTime;
Error = src.Error;
ErrorIndicators = src.ErrorIndicators;
InfoIndicators = src.InfoIndicators;
TestDone = src.TestDone;
Passed = src.Passed;
#if IPERL
CalibFactor = src.CalibFactor;
CalibFactorLNA = src.CalibFactorLNA;
Q2CorrRL = src.Q2CorrRL;
Q2CorrLR = src.Q2CorrLR;
FlowDirection = src.FlowDirection;
ExtraDataPath = src.ExtraDataPath;
X1 = src.X1;
X2 = src.X2;
X3 = src.X3;
X4 = src.X4;
X5 = src.X5;
X6 = src.X6;
X7 = src.X7;
X8 = src.X8;
X9 = src.X9;
#endif
KorrErrQ = src.KorrErrQ;
TestDone = src.TestDone;
Passed = src.Passed;
#if ORACLE_DB
ErrorBC = src.ErrorBC;
LastError = src.LastError;
#endif
}
@@ -254,31 +163,14 @@ namespace Results.Entities
writer.Write(Error);
writer.Write(ErrorIndicators);
writer.Write(InfoIndicators);
writer.Write(KorrErrQ);
writer.Write(TestDone);
writer.Write(Passed);
#if IPERL
writer.Write(CalibFactor);
writer.Write(CalibFactorLNA);
writer.Write(Q2CorrRL);
writer.Write(Q2CorrLR);
writer.Write(FlowDirection);
writer.Write((ExtraDataPath != null) ? ExtraDataPath : string.Empty);
writer.Write(X1);
writer.Write(X2);
writer.Write(X3);
writer.Write(X4);
writer.Write(X5);
writer.Write(X6);
writer.Write(X7);
writer.Write(X8);
writer.Write(X9);
#endif
#if ORACLE_DB
writer.Write(ErrorBC);
writer.Write(LastError);
#endif
writer.Write((TestRslt != null && TestRslt.Name() != null) ? TestRslt.Name() : string.Empty);
writer.Write(TestRslt != null ? TestRslt.Part : 0);
writer.Write(TestRslt.Part);
}
public virtual void ReadBinary(BinaryReader reader, IList<TestRslt> testResults)
@@ -299,27 +191,10 @@ namespace Results.Entities
Error = reader.ReadDouble();
ErrorIndicators = reader.ReadInt64();
InfoIndicators = reader.ReadInt64();
KorrErrQ = reader.ReadDouble();
TestDone = reader.ReadBoolean();
Passed = reader.ReadBoolean();
#if IPERL
CalibFactor = reader.ReadInt32();
CalibFactorLNA = reader.ReadInt32();
Q2CorrRL = reader.ReadInt32();
Q2CorrLR = reader.ReadInt32();
FlowDirection = reader.ReadInt32();
ExtraDataPath = reader.ReadString();
X1 = reader.ReadSingle();
X2 = reader.ReadSingle();
X3 = reader.ReadSingle();
X4 = reader.ReadSingle();
X5 = reader.ReadSingle();
X6 = reader.ReadSingle();
X7 = reader.ReadSingle();
X8 = reader.ReadSingle();
X9 = reader.ReadSingle();
#endif
#if ORACLE_DB
ErrorBC = reader.ReadDouble();
LastError = reader.ReadDouble();
#endif
TestRslt = null;
+33 -109
View File
@@ -1,12 +1,10 @@
///
/// Copyright (c) 2016-2022 Sensus Slovensko a.s.
/// Copyright (c) 2016-2020 Sensus Slovensko a.s.
///
using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using Common;
using Config.Entities;
namespace Results.Entities
{
@@ -27,88 +25,39 @@ namespace Results.Entities
public virtual double ErrLimLo { get; set; } /// [%] usually < 0, in case of heat meters: 1=class1, 2=class2, 3=class3
public virtual double ErrLimHi { get; set; } /// [%] usually > 0, in case of heat meters: -Qn in m3/h
public virtual double ErrLimMargin { get; set; } /// [%] makes error limits tighter: 0 <= ErrLimMargin <= abs(ErrLimXx)
public virtual bool DoControlWaterTemp { get; set; }
public virtual float TempLimLo { get; set; }
public virtual float TempLimHi { get; set; }
public virtual string TempControl { get; set; }
public virtual sbyte Publish { get; set; } /// 0=no, 1=in all protocols, 2=on screen, 3=internal
public virtual sbyte Publish { get; set; } /// 0=no, 1=in all protocols, 2=on screen, 3=internal
public virtual bool Evaluate { get; set; }
#if ORACLE_DB
public virtual int OraId { get; set; }
public virtual int OraIdRepetMulti { get; set; }
public virtual string OraDesignation { get; set; }
public virtual int RawDataId { get; set; }
public virtual int RawDataIdRepetMulti { get; set; }
public virtual string RawDataDesignation { get; set; }
#endif
/// <summary>
/// Default constructor, safe values
/// </summary>
public TestData()
public TestData()
{
Name = string.Empty;
Method = string.Empty;
}
public TestData(Test test)
public TestData(Config.Entities.Test test)
: this()
{
Name = test.Name;
Repeats = test.Repeats;
Qtg = test.Qtg;
Qfrom = test.Qfrom;
Qto = test.Qto;
TargetVolume = test.Volume;
TargetTime = test.TestTime;
Method = test.Method;
ErrLimLo = test.ErrLimLo;
ErrLimHi = test.ErrLimHi;
ErrLimMargin = test.Uncertainty;
TempLimLo = test.TempLimLo;
TempLimHi = test.TempLimHi;
TempControl = test.TempControl;
Publish = test.Publish;
Evaluate = test.DoEvaluate;
#if ORACLE_DB
OraId = test.OraId;
OraIdRepetMulti = test.OraIdRepetMulti;
OraDesignation = test.OraDesignation;
RawDataId = test.RawDataId;
RawDataIdRepetMulti = test.RawDataIdRepetMulti;
RawDataDesignation = test.RawDataDesignation;
#endif
}
/// <summary>
/// Copy constructor, copies all except of Id
/// </summary>
public TestData(TestData oriTestData)
{
Name = oriTestData.Name;
Repeats = oriTestData.Repeats;
Qtg = oriTestData.Qtg;
Qfrom = oriTestData.Qfrom;
Qto = oriTestData.Qto;
TargetVolume = oriTestData.TargetVolume;
TargetTime = oriTestData.TargetTime;
Method = oriTestData.Method;
ErrLimLo = oriTestData.ErrLimLo;
ErrLimHi = oriTestData.ErrLimHi;
ErrLimMargin = oriTestData.ErrLimMargin;
TempLimLo = oriTestData.TempLimLo;
TempLimHi = oriTestData.TempLimHi;
TempControl = oriTestData.TempControl;
Publish = oriTestData.Publish;
Evaluate = oriTestData.Evaluate;
#if ORACLE_DB
OraId = oriTestData.OraId;
OraIdRepetMulti = oriTestData.OraIdRepetMulti;
OraDesignation = oriTestData.OraDesignation;
RawDataId = oriTestData.RawDataId;
RawDataIdRepetMulti = oriTestData.RawDataIdRepetMulti;
RawDataDesignation = oriTestData.RawDataDesignation;
#endif
}
Name = test.Name;
Repeats = test.Repeats;
Qtg = (double)test.Qtg;
Qfrom = (double)test.Qfrom;
Qto = (double)test.Qto;
TargetVolume = (double)test.Volume;
TargetTime = (double)test.TstTime;
Method = test.Method;
ErrLimLo = (double)test.ErrLimLo;
ErrLimHi = (double)test.ErrLimHi;
ErrLimMargin = (double)test.Uncertainty;
DoControlWaterTemp = test.DoControlWaterTemp;
TempLimLo = test.TempLimLo;
TempLimHi = test.TempLimHi;
Publish = test.Publish;
Evaluate = test.DoEvaluate;
}
/// <summary>
@@ -129,19 +78,15 @@ namespace Results.Entities
if (ErrLimLo != td.ErrLimLo) return false;
if (ErrLimHi != td.ErrLimHi) return false;
if (ErrLimMargin != td.ErrLimMargin) return false;
if (TempLimLo != td.TempLimLo) return false;
if (TempLimHi != td.TempLimHi) return false;
if (TempControl != td.TempControl) return false;
if (Publish != td.Publish) return false;
if (DoControlWaterTemp != td.DoControlWaterTemp) return false;
if (DoControlWaterTemp)
{
if (TempLimLo != td.TempLimLo) return false;
if (TempLimHi != td.TempLimHi) return false;
}
if (Publish != td.Publish) return false;
if (Evaluate != td.Evaluate) return false;
#if ORACLE_DB
if (OraId != td.OraId) return false;
if (OraIdRepetMulti != td.OraIdRepetMulti) return false;
if (OraDesignation != td.OraDesignation) return false;
if (RawDataId != td.RawDataId) return false;
if (RawDataIdRepetMulti != td.RawDataIdRepetMulti) return false;
if (RawDataDesignation != td.RawDataDesignation) return false;
#endif
return true;
}
@@ -178,19 +123,11 @@ namespace Results.Entities
writer.Write(ErrLimLo);
writer.Write(ErrLimHi);
writer.Write(ErrLimMargin);
writer.Write(DoControlWaterTemp);
writer.Write(TempLimLo);
writer.Write(TempLimHi);
writer.Write((TempControl != null) ? TempControl : string.Empty);
writer.Write(Publish);
writer.Write(Evaluate);
#if ORACLE_DB
writer.Write(OraId);
writer.Write(OraIdRepetMulti);
writer.Write((OraDesignation != null) ? OraDesignation : string.Empty);
writer.Write(RawDataId);
writer.Write(RawDataIdRepetMulti);
writer.Write((RawDataDesignation != null) ? RawDataDesignation : string.Empty);
#endif
}
public virtual void ReadBinary(BinaryReader reader)
@@ -207,24 +144,11 @@ namespace Results.Entities
ErrLimLo = reader.ReadDouble();
ErrLimHi = reader.ReadDouble();
ErrLimMargin = reader.ReadDouble();
DoControlWaterTemp = reader.ReadBoolean();
TempLimLo = reader.ReadSingle();
TempLimHi = reader.ReadSingle();
TempControl = reader.ReadString();
Publish = reader.ReadSByte();
Evaluate = reader.ReadBoolean();
#if ORACLE_DB
OraId = reader.ReadInt32();
OraIdRepetMulti = reader.ReadInt32();
OraDesignation = reader.ReadString();
RawDataId = reader.ReadInt32();
RawDataIdRepetMulti = reader.ReadInt32();
RawDataDesignation = reader.ReadString();
#endif
}
public override string ToString()
{
return string.Format("{0} (P.{1},{2})", Name, ((Publish)Publish).ToString(), Evaluate ? "E" : "-");
}
}
}
+172 -204
View File
@@ -1,179 +1,164 @@
///
/// Copyright (c) 2015-2023 Sensus Slovensko a.s.
/// Copyright (c) 2015-2020 Sensus Slovensko a.s.
///
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using Common;
namespace Results.Entities
{
public class TestRslt
{
/// Identity
public virtual int Id { get; protected set; }
public virtual Batch Batch { get; set; }
public virtual TestData TestData { get; set; }
public virtual Components Components { get; set; }
public virtual int Part { get; set; }
public virtual int RepetitionNr { get; set; } /// Repetition number from the set of repeated tests (1...)
public virtual string MethodClass { get; set; } /// Not mapped to DB, does not depend on localization and customer
public virtual int Id { get; protected set; }
public virtual Batch Batch { get; set; }
public virtual TestData TestData { get; set; }
public virtual Components Components { get; set; }
public virtual int Part { get; set; }
public virtual int RepetitionNr { get; set; } /// Repetition number from the set of repeated tests (1...)
public virtual string MethodClass { get; set; } /// Not mapped to DB, does not depend on localization and customer
/// Main results
public virtual bool TestDone { get; set; }
public virtual string Remark { get; set; }
public virtual DateTime StartTime { get; set; } /// Date and time of the test start
public virtual DateTime EndTime { get; set; } /// Date and time of the test end
public virtual int FlowSetTime { get; set; } /// [s] Flow set time in seconds
public virtual int TimeBtwnMassMsrmnts { get; set; } /// [s] Time between two mass measurements in seconds (if applicable)
public virtual double TestTime { get; set; } /// [s] Test time in seconds
public virtual double TestTimeCorrection { get; set; } /// [s] Correction of the test time due to diverter (0 for methods w/o diverter or when there is no correction table)
public virtual double PulsesMaster { get; set; } /// [pls] FlyingStartMassCollectionProlonged: MID pulses of the water to the tank
public virtual double TotalPulsesMstr { get; set; } /// [pls] FlyingStartMassCollectionProlonged: MID pulses of the complete test (not mapped to DB)
public virtual double ConstMasterRaw { get; set; } /// [l/pls] Liters per pulse of the master flow meter uncorrected.
public virtual double ConstMasterCorr { get; set; } /// [l/pls] Liters per pulse of the master flow meter corrected by a correction table.
public virtual double ConstMaster { get; set; } /// [l/pls] Liters per pulse of the master flow meter calculated from a mass measurement.
/// When mass measurement is not available, corrected by a correction table.
public virtual double MassStartRaw { get; set; } /// [kg]
public virtual double MassStart { get; set; } /// [kg]
public virtual double MassEndRaw { get; set; } /// [kg]
public virtual double MassEnd { get; set; } /// [kg]
public virtual double DensityIn { get; set; } /// [kg/m3]
public virtual double DensityLine { get; set; } /// [kg/m3]
public virtual double DensityDiv { get; set; } /// [kg/m3]
public virtual double MassOfEvapWater { get; set; } /// [kg]
public virtual double FlowMass { get; set; } /// [kg/h] calculated from conventional true value
public virtual double FlowVolume { get; set; } /// [m3/h]
public virtual double VolumeCTV { get; set; } /// [l] Volume conventional true value
public virtual double VolumeMaster { get; set; } /// [l] Volume from the master flow meter
public virtual double ErrorMaster { get; set; } /// [%] Error of the master flow meter
public virtual bool TestDone { get; set; }
public virtual string Remark { get; set; }
public virtual DateTime StartTime { get; set; } /// Date and time of the test start
public virtual DateTime EndTime { get; set; } /// Date and time of the test end
public virtual int FlowSetTime { get; set; } /// [s] Flow set time in seconds
public virtual int TimeBtwnMassMsrmnts { get; set; } /// [s] Time between two mass measurements in seconds (if applicable)
public virtual double TestTime { get; set; } /// [s] Test time in seconds
public virtual double TestTimeCorrection { get; set; } /// [s] Correction of the test time due to diverter (0 for methods w/o diverter or when there is no correction table)
public virtual double PulsesMaster { get; set; } /// [pls] FlyingStartMassCollectionProlonged: MID pulses of the water to the tank
public virtual double TotalPulsesMstr { get; set; } /// [pls] FlyingStartMassCollectionProlonged: MID pulses of the complete test (not mapped to DB)
public virtual double ConstMasterRaw { get; set; } /// [l/pls] Liters per pulse of the master flow meter uncorrected.
public virtual double ConstMasterCorr { get; set; } /// [l/pls] Liters per pulse of the master flow meter corrected by a correction table.
public virtual double ConstMaster { get; set; } /// [l/pls] Liters per pulse of the master flow meter calculated from a mass measurement.
/// When mass measurement is not available, corrected by a correction table.
public virtual double MassStartRaw { get; set; } /// [kg]
public virtual double MassStart { get; set; } /// [kg]
public virtual double MassEndRaw { get; set; } /// [kg]
public virtual double MassEnd { get; set; } /// [kg]
public virtual double DensityIn { get; set; } /// [kg/m3]
public virtual double DensityLine { get; set; } /// [kg/m3]
public virtual double DensityDiv { get; set; } /// [kg/m3]
public virtual double Buoyancy { get; set; }
public virtual double FlowMass { get; set; } /// [kg/h] calculated from conventional true value
public virtual double FlowVolume { get; set; } /// [m3/h]
public virtual double VolumeCTV { get; set; } /// [l] Volume conventional true value
public virtual double VolumeMaster { get; set; } /// [l] Volume from the master flow meter
public virtual double ErrorMaster { get; set; } /// [%] Error of the master flow meter
public virtual float DiverterStart { get; set; } /// [s] Diverter switch time when test starts
public virtual float DivStart10 { get; set; } /// [s] Diverter switch time when test starts at level 10 (e.g. 10%) (not mapped to DB)
public virtual float DivStart50 { get; set; } /// [s] Diverter switch time when test starts at level 50 (e.g. 50%) (not mapped to DB)
public virtual float DivStart90 { get; set; } /// [s] Diverter switch time when test starts at level 90 (e.g. 90%) (not mapped to DB)
public virtual float DiverterStart { get; set; } /// [s] Diverter switch time when test starts
public virtual float DivStart10 { get; set; } /// [s] Diverter switch time when test starts at level 10 (e.g. 10%) (not mapped to DB)
public virtual float DivStart50 { get; set; } /// [s] Diverter switch time when test starts at level 50 (e.g. 50%) (not mapped to DB)
public virtual float DivStart90 { get; set; } /// [s] Diverter switch time when test starts at level 90 (e.g. 90%) (not mapped to DB)
public virtual float DiverterEnd { get; set; } /// [s] Diverter switch time when test ends
public virtual float DivEnd90 { get; set; } /// [s] Diverter switch time when test starts at level 90 (e.g. 90%) (not mapped to DB)
public virtual float DivEnd50 { get; set; } /// [s] Diverter switch time when test starts at level 50 (e.g. 50%) (not mapped to DB)
public virtual float DivEnd10 { get; set; } /// [s] Diverter switch time when test starts at level 10 (e.g. 10%) (not mapped to DB)
public virtual float DiverterEnd { get; set; } /// [s] Diverter switch time when test ends
public virtual float DivEnd90 { get; set; } /// [s] Diverter switch time when test starts at level 90 (e.g. 90%) (not mapped to DB)
public virtual float DivEnd50 { get; set; } /// [s] Diverter switch time when test starts at level 50 (e.g. 50%) (not mapped to DB)
public virtual float DivEnd10 { get; set; } /// [s] Diverter switch time when test starts at level 10 (e.g. 10%) (not mapped to DB)
public virtual long ErrorFlags { get; set; } /// bitfield : bit0=E1, bit1=E2, bit2=E3, etc.
public virtual long InfoFlags { get; set; } /// bitfield : bit0=E1, bit1=E2, bit2=E3, etc.
public virtual long ErrorFlags { get; set; } /// bitfield : bit0=E1, bit1=E2, bit2=E3, etc.
public virtual long InfoFlags { get; set; } /// bitfield : bit0=E1, bit1=E2, bit2=E3, etc.
/// Main results of heat meters
public virtual double RefEnergy { get; set; } /// [J] Joul
public virtual double RefEnergy { get; set; } /// [J] Joul
/// Auxiliary results
public virtual float AmbTempMean { get; set; } /// [°C] Average ambient air temperature
public virtual float AmbTempStart { get; set; } /// [°C] Ambient air temperature on test start
public virtual float AmbTempEnd { get; set; } /// [°C] Ambient air temperature on test end
public virtual float AmbTempMin { get; set; } /// [°C] Minimum ambient air temperature
public virtual float AmbTempMax { get; set; } /// [°C] Maximum ambient air temperature
public virtual float AmbPressMean { get; set; } /// [bar] Average ambient air pressure
public virtual float AmbPressStart { get; set; } /// [bar] Ambient air pressure on test start
public virtual float AmbPressEnd { get; set; } /// [bar] Ambient air pressure on test end
public virtual float AmbPressMin { get; set; } /// [bar] Minimum ambient air pressure
public virtual float AmbPressMax { get; set; } /// [bar] Maximum ambient air pressure
public virtual float AmbHumiMean { get; set; } /// [%] Average ambient air relative humidity
public virtual float AmbHumiStart { get; set; } /// [%] Ambient air relative humidity on test start
public virtual float AmbHumiEnd { get; set; } /// [%] Ambient air relative humidity on test end
public virtual float AmbHumiMin { get; set; } /// [%] Minimum ambient air relative humidity
public virtual float AmbHumiMax { get; set; } /// [%] Maximum ambient air relative humidity
public virtual float PressUpMean { get; set; } /// [bar] Input water pressure (average)
public virtual float PressUpStart { get; set; } /// [bar]
public virtual float PressUpEnd { get; set; } /// [bar]
public virtual float PressUpMin { get; set; } /// [bar]
public virtual float PressUpMax { get; set; } /// [bar]
public virtual float PressDownMean { get; set; } /// [bar]
public virtual float PressDownStart { get; set; } /// [bar]
public virtual float PressDownEnd { get; set; } /// [bar]
public virtual float PressDownMin { get; set; } /// [bar]
public virtual float PressDownMax { get; set; } /// [bar]
public virtual float PressDeltaMean { get; set; } /// [bar]
public virtual float PressDeltaStart { get; set; } /// [bar]
public virtual float PressDeltaEnd { get; set; } /// [bar]
public virtual float PressDeltaMin { get; set; } /// [bar]
public virtual float PressDeltaMax { get; set; } /// [bar]
public virtual float TempUpMean { get; set; } /// [°C]
public virtual float TempUpStart { get; set; } /// [°C]
public virtual float TempUpEnd { get; set; } /// [°C]
public virtual float TempUpMin { get; set; } /// [°C]
public virtual float TempUpMax { get; set; } /// [°C]
public virtual float TempDownMean { get; set; } /// [°C]
public virtual float TempDownStart { get; set; } /// [°C]
public virtual float TempDownEnd { get; set; } /// [°C]
public virtual float TempDownMin { get; set; } /// [°C]
public virtual float TempDownMax { get; set; } /// [°C]
public virtual float TempDivMean { get; set; } /// [°C]
public virtual float TempDivStart { get; set; } /// [°C]
public virtual float TempDivEnd { get; set; } /// [°C]
public virtual float TempDivMin { get; set; } /// [°C]
public virtual float TempDivMax { get; set; } /// [°C]
public virtual float FlowMean { get; set; } /// [m3/h] mean flow from the reference flowmeter
public virtual float FlowStart { get; set; } /// [m3/h] flow at the start of test from the reference flowmeter
public virtual float FlowEnd { get; set; } /// [m3/h] flow at the end of test from the reference flowmeter
public virtual float FlowMin { get; set; } /// [m3/h]
public virtual float FlowMax { get; set; } /// [m3/h]
public virtual float ConductMean { get; set; } /// [uS/cm]
public virtual float ConductStart { get; set; } /// [uS/cm]
public virtual float ConductEnd { get; set; } /// [uS/cm]
public virtual float ConductMin { get; set; } /// [uS/cm]
public virtual float ConductMax { get; set; } /// [uS/cm]
public virtual float AmbTempMean { get; set; } /// [°C] Average ambient air temperature
public virtual float AmbTempStart { get; set; } /// [°C] Ambient air temperature on test start
public virtual float AmbTempEnd { get; set; } /// [°C] Ambient air temperature on test end
public virtual float AmbTempMin { get; set; } /// [°C] Minimum ambient air temperature
public virtual float AmbTempMax { get; set; } /// [°C] Maximum ambient air temperature
public virtual float AmbPressMean { get; set; } /// [bar] Average ambient air pressure
public virtual float AmbPressStart { get; set; } /// [bar] Ambient air pressure on test start
public virtual float AmbPressEnd { get; set; } /// [bar] Ambient air pressure on test end
public virtual float AmbPressMin { get; set; } /// [bar] Minimum ambient air pressure
public virtual float AmbPressMax { get; set; } /// [bar] Maximum ambient air pressure
public virtual float AmbHumiMean { get; set; } /// [%] Average ambient air relative humidity
public virtual float AmbHumiStart { get; set; } /// [%] Ambient air relative humidity on test start
public virtual float AmbHumiEnd { get; set; } /// [%] Ambient air relative humidity on test end
public virtual float AmbHumiMin { get; set; } /// [%] Minimum ambient air relative humidity
public virtual float AmbHumiMax { get; set; } /// [%] Maximum ambient air relative humidity
public virtual float PressUpMean { get; set; } /// [bar] Input water pressure (average)
public virtual float PressUpStart { get; set; } /// [bar]
public virtual float PressUpEnd { get; set; } /// [bar]
public virtual float PressUpMin { get; set; } /// [bar]
public virtual float PressUpMax { get; set; } /// [bar]
public virtual float PressDownMean { get; set; } /// [bar]
public virtual float PressDownStart { get; set; } /// [bar]
public virtual float PressDownEnd { get; set; } /// [bar]
public virtual float PressDownMin { get; set; } /// [bar]
public virtual float PressDownMax { get; set; } /// [bar]
public virtual float PressDeltaMean { get; set; } /// [bar]
public virtual float PressDeltaStart { get; set; } /// [bar]
public virtual float PressDeltaEnd { get; set; } /// [bar]
public virtual float PressDeltaMin { get; set; } /// [bar]
public virtual float PressDeltaMax { get; set; } /// [bar]
public virtual float TempUpMean { get; set; } /// [°C]
public virtual float TempUpStart { get; set; } /// [°C]
public virtual float TempUpEnd { get; set; } /// [°C]
public virtual float TempUpMin { get; set; } /// [°C]
public virtual float TempUpMax { get; set; } /// [°C]
public virtual float TempDownMean { get; set; } /// [°C]
public virtual float TempDownStart { get; set; } /// [°C]
public virtual float TempDownEnd { get; set; } /// [°C]
public virtual float TempDownMin { get; set; } /// [°C]
public virtual float TempDownMax { get; set; } /// [°C]
public virtual float TempDivMean { get; set; } /// [°C]
public virtual float TempDivStart { get; set; } /// [°C]
public virtual float TempDivEnd { get; set; } /// [°C]
public virtual float TempDivMin { get; set; } /// [°C]
public virtual float TempDivMax { get; set; } /// [°C]
public virtual float FlowMean { get; set; } /// [m3/h] mean flow from the reference flowmeter
public virtual float FlowStart { get; set; } /// [m3/h] flow at the start of test from the reference flowmeter
public virtual float FlowEnd { get; set; } /// [m3/h] flow at the end of test from the reference flowmeter
public virtual float FlowMin { get; set; } /// [m3/h]
public virtual float FlowMax { get; set; } /// [m3/h]
public virtual float ConductMean { get; set; } /// [uS/cm]
public virtual float ConductStart { get; set; } /// [uS/cm]
public virtual float ConductEnd { get; set; } /// [uS/cm]
public virtual float ConductMin { get; set; } /// [uS/cm]
public virtual float ConductMax { get; set; } /// [uS/cm]
public virtual float Uncertnt { get; set; } /// [%] Relative error uncertainty
public virtual float UncertntScale { get; set; } /// [%] Contribution to uncertainty from scale
public virtual float UncertntDensity { get; set; } /// [%] Contribution to uncertainty from density
public virtual float UncertntTemp { get; set; } /// [%] Contribution to uncertainty from temperature
public virtual float UncertntPressure { get; set; } /// [%] Contribution to uncertainty from pressure
public virtual float Uncertnt { get; set; } /// [%] Relative error uncertainty
public virtual float UncertntScale { get; set; } /// [%] Contribution to uncertainty from scale
public virtual float UncertntDensity { get; set; } /// [%] Contribution to uncertainty from density
public virtual float UncertntTemp { get; set; } /// [%] Contribution to uncertainty from temperature
public virtual float UncertntPressure { get; set; } /// [%] Contribution to uncertainty from pressure
public virtual float Custom1 { get; set; } /// [°C] T ref hi mean
public virtual float Custom2 { get; set; } /// [°C] T ref hi start
public virtual float Custom3 { get; set; } /// [°C] T ref hi end
public virtual float Custom4 { get; set; } /// [°C] T ref hi min
public virtual float Custom5 { get; set; } /// [°C] T ref hi max
public virtual float Custom6 { get; set; } /// [°C] T ref lo mean
public virtual float Custom7 { get; set; } /// [°C] T ref lo start
public virtual float Custom8 { get; set; } /// [°C] T ref lo end
public virtual float Custom9 { get; set; } /// [°C] T ref lo min
public virtual float Custom10 { get; set; } /// [°C] T ref lo max
public virtual float Custom1 { get; set; } /// [°C] T ref hi mean
public virtual float Custom2 { get; set; } /// [°C] T ref hi start
public virtual float Custom3 { get; set; } /// [°C] T ref hi end
public virtual float Custom4 { get; set; } /// [°C] T ref hi min
public virtual float Custom5 { get; set; } /// [°C] T ref hi max
public virtual float Custom6 { get; set; } /// [°C] T ref lo mean
public virtual float Custom7 { get; set; } /// [°C] T ref lo start
public virtual float Custom8 { get; set; } /// [°C] T ref lo end
public virtual float Custom9 { get; set; } /// [°C] T ref lo min
public virtual float Custom10 { get; set; } /// [°C] T ref lo max
public virtual int Counter1 { get; set; }
public virtual int Counter2 { get; set; }
public virtual int Counter3 { get; set; }
public virtual int Counter4 { get; set; }
public virtual int Counter5 { get; set; }
public virtual int Counter1 { get; set; }
public virtual int Counter2 { get; set; }
public virtual int Counter3 { get; set; }
public virtual int Counter4 { get; set; }
public virtual int Counter5 { get; set; }
/// Wrappers
public virtual string Name() { return Common.Utils.GetTestName(TestData.Name, TestData.Repeats, RepetitionNr); }
public virtual string Key() { return string.Format("{0}~{1}~{2}~{3}", TestData.Name, Part, TestData.Repeats, RepetitionNr); } /// Unique key
public virtual string Name() { return Utils.GetTestName(TestData.Name, TestData.Repeats, RepetitionNr); }
public virtual int Repeats() { return TestData.Repeats; }
public virtual double Qfrom() { return TestData.Qfrom; }
public virtual double Qto() { return TestData.Qto; }
public virtual double TargetVolume() { return TestData.TargetVolume; }
public virtual double TargetTime() { return TestData.TargetTime; }
public virtual string Method() { return TestData.Method; }
public virtual string RefFlowmeter() { return (Components != null && Components.Flowmeter != null) ? Components.Flowmeter : string.Empty; }
public virtual string Scale() { return (Components != null && Components.Scale != null) ? Components.Scale : string.Empty; }
public virtual string Diverter() { return (Components != null && Components.Diverter != null) ? Components.Diverter : string.Empty; }
public virtual string RegValve() { return (Components != null && Components.RegValve != null) ? Components.RegValve : string.Empty; }
public virtual string RefFlowmeter() { return (Components != null) ? Components.Flowmeter : string.Empty; }
public virtual bool IsRelErrTest() { return (MethodClass != null) ? (MethodClass.Contains("FixedStart") || MethodClass.Contains("FlyingStart") || MethodClass.Contains("CombinedWithDetection") || MethodClass.Contains("DiverterTest") || MethodClass.Contains("ManualEntry")) : true; }
public virtual bool IsPMaxTest() { return (MethodClass != null) ? (MethodClass.Contains("PMaxTest") || MethodClass.Contains("LeakTest") || TestData.Method.ToLower().Contains("pmax")) : true; }
public virtual bool IsStartStop() { return (MethodClass != null) ? MethodClass.Contains("FixedStart") : true; }
public virtual bool IsDiverter() { return (MethodClass != null) ? ((MethodClass.Contains("FlyingStart") && MethodClass.Contains("MassColl")) || MethodClass.Contains("DiverterTest")) : true; }
public virtual bool IsVolumeMethod() { return (MethodClass != null) ? (MethodClass.Contains("TestMethods.FixedStart.") || MethodClass.Contains("TestMethods.FlyingStart.")) : false; }
#if ORACLE_DB
public virtual int OraId() { return TestData.OraId; }
public virtual int OraIdRepetMulti() { return TestData.OraIdRepetMulti; }
public virtual string OraDesignation() { return TestData.OraDesignation; }
public virtual int RawDataId() { return TestData.RawDataId; }
public virtual int RawDataIdRepetMulti() { return TestData.RawDataIdRepetMulti; }
public virtual string RawDataDesignation() { return TestData.RawDataDesignation; }
#endif
public virtual string MethodElde()
{
if (MethodClass == null) return string.Empty;
@@ -239,7 +224,7 @@ namespace Results.Entities
public virtual float TempLimLo() { return TestData.TempLimLo; }
public virtual float TempLimHi() { return TestData.TempLimHi; }
public virtual bool Evaluate() { return TestData.Evaluate; }
public virtual Publish Publish() { return (Publish)TestData.Publish; }
public virtual Config.Entities.Publish Publish() { return (Config.Entities.Publish)TestData.Publish; }
public TestRslt()
@@ -261,51 +246,46 @@ namespace Results.Entities
{
if (src == null) return;
Components = src.Components; /// ???
Part = src.Part;
RepetitionNr = src.RepetitionNr;
MethodClass = src.MethodClass;
TestDone = src.TestDone;
Remark = src.Remark;
StartTime = src.StartTime;
EndTime = src.EndTime;
FlowSetTime = src.FlowSetTime;
Components = src.Components; /// ???
Part = src.Part;
RepetitionNr = src.RepetitionNr;
MethodClass = src.MethodClass;
TestDone = src.TestDone;
Remark = src.Remark;
StartTime = src.StartTime;
EndTime = src.EndTime;
FlowSetTime = src.FlowSetTime;
TimeBtwnMassMsrmnts = src.TimeBtwnMassMsrmnts;
TestTime = src.TestTime;
TestTimeCorrection = src.TestTimeCorrection;
PulsesMaster = src.PulsesMaster;
TotalPulsesMstr = src.TotalPulsesMstr;
ConstMasterRaw = src.ConstMasterRaw;
ConstMasterCorr = src.ConstMasterCorr;
ConstMaster = src.ConstMaster;
MassStartRaw = src.MassStartRaw;
MassStart = src.MassStart;
MassEndRaw = src.MassEndRaw;
MassEnd = src.MassEnd;
DensityIn = src.DensityIn;
DensityLine = src.DensityLine;
DensityDiv = src.DensityDiv;
MassOfEvapWater = src.MassOfEvapWater;
FlowMass = src.FlowMass;
FlowVolume = src.FlowVolume;
VolumeCTV = src.VolumeCTV;
VolumeMaster = src.VolumeMaster;
ErrorMaster = src.ErrorMaster;
TestTime = src.TestTime;
PulsesMaster = src.PulsesMaster;
TotalPulsesMstr = src.TotalPulsesMstr;
ConstMasterRaw = src.ConstMasterRaw;
ConstMasterCorr = src.ConstMasterCorr;
ConstMaster = src.ConstMaster;
MassStartRaw = src.MassStartRaw;
MassStart = src.MassStart;
MassEndRaw = src.MassEndRaw;
MassEnd = src.MassEnd;
DensityIn = src.DensityIn;
DensityLine = src.DensityLine;
DensityDiv = src.DensityDiv;
Buoyancy = src.Buoyancy;
FlowMass = src.FlowMass;
FlowVolume = src.FlowVolume;
VolumeCTV = src.VolumeCTV;
VolumeMaster = src.VolumeMaster;
ErrorMaster = src.ErrorMaster;
DiverterStart = src.DiverterStart;
DivStart10 = src.DivStart10;
DivStart50 = src.DivStart50;
DivStart90 = src.DivStart90;
DiverterEnd = src.DiverterEnd;
DivEnd10 = src.DivEnd10;
DivEnd50 = src.DivEnd50;
DivEnd90 = src.DivEnd90;
DivStart10 = src.DivStart10;
DivStart50 = src.DivStart50;
DivStart90 = src.DivStart90;
DiverterEnd = src.DiverterEnd;
DivEnd10 = src.DivEnd10;
DivEnd50 = src.DivEnd50;
DivEnd90 = src.DivEnd90;
ErrorFlags = src.ErrorFlags;
InfoFlags = src.InfoFlags;
RefEnergy = src.RefEnergy;
AmbTempMean = src.AmbTempMean;
AmbTempStart = src.AmbTempStart;
AmbTempEnd = src.AmbTempEnd;
@@ -362,21 +342,15 @@ namespace Results.Entities
ConductMin = src.ConductMin;
ConductMax = src.ConductMax;
Uncertnt = src.Uncertnt;
UncertntScale = src.UncertntScale;
UncertntDensity = src.UncertntDensity;
UncertntTemp = src.UncertntTemp;
UncertntPressure = src.UncertntPressure;
Custom1 = src.Custom1;
Custom2 = src.Custom2;
Custom3 = src.Custom3;
Custom4 = src.Custom4;
Custom5 = src.Custom5;
Custom6 = src.Custom6;
Custom7 = src.Custom7;
Custom8 = src.Custom8;
Custom9 = src.Custom9;
Custom1 = src.Custom1;
Custom2 = src.Custom2;
Custom3 = src.Custom3;
Custom4 = src.Custom4;
Custom5 = src.Custom5;
Custom6 = src.Custom6;
Custom7 = src.Custom7;
Custom8 = src.Custom8;
Custom9 = src.Custom9;
Custom10 = src.Custom10;
Counter1 = src.Counter1;
@@ -397,12 +371,6 @@ namespace Results.Entities
#endif
}
/// <summary> Wrapper </summary>
public virtual string InfoFlagsStr()
{
return Utils.ErrorFlagsStr(InfoFlags);
}
public virtual bool IsPartCompatible(int waterMeterPartNr)
{
if ((this.Part == 0) || (waterMeterPartNr == 0)) return true;
@@ -422,10 +390,10 @@ namespace Results.Entities
public virtual string ToString(int i)
{
return string.Format("TestRslt: Part={0} RepetitionNr={1} TestDone={2} Remark={3} StartTime={4} EndTime={5} FlowSetTime={6} TestTime={7} PulsesMaster={8} ConstMaster={9} MassStartRaw={10} MassStart={11} MassEndRaw={12} MassEnd={13} DensityIn={14} DensityOut={15} DensityDiv={16} MassOfEvapWaater={17} FlowMass={18} FlowVolume={19} VolumeCTV={20} VolumeMaster={21} ErrorMaster={22} DiverterStart={85} DiverterEnd={86} ErrorFlags={23} InfoFlags={24} AmbTempMean={25} AmbTempStart={26} AmbTempEnd={27} AmbTempMin={28} AmbTempMax={29} AmbPressMean={30} AmbPressStart={31} AmbPressEnd={32} AmbPressMin={33} AmbPressMax={34} AmbHumiMean={35} AmbHumiStart={36} AmbHumiEnd={37} AmbHumiMin={38} AmbHumiMax={39} PressUpMean={40} PressUpStart={41} PressUpEnd={42} PressUpMin={43} PressUpMax={44} PressDownMean={45} PressDownStart={46} PressDownEnd={47} PressDownMin={48} PressDownMax={49} PressDeltaMean={50} PressDeltaStart={51} PressDeltaEnd={52} PressDeltaMin={53} PressDeltaMax={54} TempUpMean={55} TempUpStart={56} TempUpEnd={57} TempUpMin={58} TempUpMax={59} TempDownMean={60} TempDownStart={61} TempDownEnd={62} TempDownMin={63} TempDownMax={64} TempDivMean={65} TempDivStart={66} TempDivEnd={67} TempDivMin={68} TempDivMax={69} FlowMean={70} FlowStart={71} FlowEnd={72} FlowMin={73} FlowMax={74} Custom1={75} Custom2={76} Custom3={77} Custom4={78} Custom5={79} Custom6={80} Custom7={81} Custom8={82} Custom9={83} Custom10={84}",
return string.Format("TestRslt: Part={0} RepetitionNr={1} TestDone={2} Remark={3} StartTime={4} EndTime={5} FlowSetTime={6} TestTime={7} PulsesMaster={8} ConstMaster={9} MassStartRaw={10} MassStart={11} MassEndRaw={12} MassEnd={13} DensityIn={14} DensityOut={15} DensityDiv={16} Buoyancy={17} FlowMass={18} FlowVolume={19} VolumeCTV={20} VolumeMaster={21} ErrorMaster={22} DiverterStart={85} DiverterEnd={86} ErrorFlags={23} InfoFlags={24} AmbTempMean={25} AmbTempStart={26} AmbTempEnd={27} AmbTempMin={28} AmbTempMax={29} AmbPressMean={30} AmbPressStart={31} AmbPressEnd={32} AmbPressMin={33} AmbPressMax={34} AmbHumiMean={35} AmbHumiStart={36} AmbHumiEnd={37} AmbHumiMin={38} AmbHumiMax={39} PressUpMean={40} PressUpStart={41} PressUpEnd={42} PressUpMin={43} PressUpMax={44} PressDownMean={45} PressDownStart={46} PressDownEnd={47} PressDownMin={48} PressDownMax={49} PressDeltaMean={50} PressDeltaStart={51} PressDeltaEnd={52} PressDeltaMin={53} PressDeltaMax={54} TempUpMean={55} TempUpStart={56} TempUpEnd={57} TempUpMin={58} TempUpMax={59} TempDownMean={60} TempDownStart={61} TempDownEnd={62} TempDownMin={63} TempDownMax={64} TempDivMean={65} TempDivStart={66} TempDivEnd={67} TempDivMin={68} TempDivMax={69} FlowMean={70} FlowStart={71} FlowEnd={72} FlowMin={73} FlowMax={74} Custom1={75} Custom2={76} Custom3={77} Custom4={78} Custom5={79} Custom6={80} Custom7={81} Custom8={82} Custom9={83} Custom10={84}",
Part, RepetitionNr, TestDone, Remark, StartTime, EndTime, FlowSetTime, TestTime,
PulsesMaster, ConstMaster, MassStartRaw, MassStart, MassEndRaw, MassEnd,
DensityIn, DensityLine, DensityDiv, MassOfEvapWater, FlowMass, FlowVolume,
DensityIn, DensityLine, DensityDiv, Buoyancy, FlowMass, FlowVolume,
VolumeCTV, VolumeMaster, ErrorMaster, ErrorFlags, InfoFlags,
AmbTempMean, AmbTempStart, AmbTempEnd, AmbTempMin, AmbTempMax,
AmbPressMean, AmbPressStart, AmbPressEnd, AmbPressMin, AmbPressMax,
@@ -493,7 +461,7 @@ namespace Results.Entities
writer.Write(DensityIn);
writer.Write(DensityLine);
writer.Write(DensityDiv);
writer.Write(MassOfEvapWater);
writer.Write(Buoyancy);
writer.Write(FlowMass);
writer.Write(FlowVolume);
writer.Write(VolumeCTV);
@@ -634,7 +602,7 @@ namespace Results.Entities
DensityIn = reader.ReadDouble();
DensityLine = reader.ReadDouble();
DensityDiv = reader.ReadDouble();
MassOfEvapWater = reader.ReadDouble();
Buoyancy = reader.ReadDouble();
FlowMass = reader.ReadDouble();
FlowVolume = reader.ReadDouble();
VolumeCTV = reader.ReadDouble();
+139 -146
View File
@@ -1,11 +1,11 @@
///
/// Copyright (c) 2015-2023 Sensus Slovensko a.s.
/// Copyright (c) 2015-2020 Sensus Slovensko a.s.
///
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using Common;
using Config.Entities;
using Results.Resources;
namespace Results.Entities
@@ -43,9 +43,8 @@ namespace Results.Entities
{
public virtual int Id { get; protected set; }
public virtual string SerialNr { get; set; } /// S/N _or_ S/N of the main meter of a compound meter _or_ PCB Number of an iPerl water meter
public virtual string SerialNrAux { get; set; } /// S/N of the aux. meter of a compound meter _or_ eRegister PCB Number of a 640 water meter
public virtual string RadioAddress { get; set; }
public virtual string PurchaseOrder { get; set; }
public virtual string SerialNrAux { get; set; } /// S/N of the aux. meter of a compound meter _or_ a complete assigned S/N of an iPerl water meter
public virtual string PurchaseOrder { get; set; }
public virtual int YearOfProduction { get; set; }
public virtual int WMPosition { get; set; } /// 1-based water meter position
public virtual string EndState { get; set; } /// End state (of the main water meter)
@@ -60,7 +59,7 @@ namespace Results.Entities
public virtual string Remark { get; set; }
#if IPERL
public virtual double OrigCalibFactor { get; set; } /// Original iPerl calibration factor used during the test
public virtual double OrigCalibFactor { get; set; } /// Original iPerl calibration factor used during the test
public virtual double CalibFactor { get; set; } /// iPerl calibration factor used during the test
public virtual double OrigCalibFactorLNA{ get; set; } /// Original iPerl LNA calibration factor used during the test
public virtual double CalibFactorLNA { get; set; } /// iPerl LNA calibration factor used during the test
@@ -77,6 +76,9 @@ namespace Results.Entities
/// <summary>
/// Data from a production test bench (in case of tests on iPerl special)
/// </summary>
public virtual int AssignedSerialNr { get; set; }
public virtual string CompleteSerialNr { get; set; }
public virtual string RadioAddress { get; set; }
public virtual int PaletteNr { get; set; }
public virtual int UmkartonNr { get; set; }
public virtual string ProdTestBench { get; set; }
@@ -89,18 +91,15 @@ namespace Results.Entities
public virtual int ProdQ2CorrLR { get; set; } /// iPerl Q2 correction for the L-flow written to iPerl
#endif
#if ORACLE_DB
public virtual int AssignedSerialNr { get; set; }
public virtual string Prefix { get; set; }
public virtual string Suffix { get; set; }
public virtual string CompleteSerialNr { get; set; }
public virtual string OriRadioAddress { get; set; } /// Original radio address of a 640 water meter (AlbatrosID)
public virtual int WMTypeRevision { get; set; }
public virtual int Pruefindex { get; set; } /// >=1 ... pruefindex, 0 ... unknown (no reading from DB yet)
public virtual int Pruefindex { get; set; } /// >= 1 ... pruefindex
public virtual int HydrPruefung { get; set; }
public virtual int WMTypeRevision { get; set; } /// Not mapped to DB !!!
public virtual object RawTestInfos { get; set; } /// IList<SensusTestInfo> fetched from Oracle at the beginning of the cycle, not mapped to DB !!!
public virtual object CompleteTestInfos { get; set; } /// SensusTestInfo[] obtained as a best match at the beginning of the cycle, not mapped to DB !!!
#endif
public virtual int ProcessId { get; set; } /// Not mapped to DB !!! Tracing DB Process ID
public virtual bool LastRecordIsNok { get; set; } /// Not mapped to DB !!! Previous record verification result
public virtual bool PrintLabel { get; set; } /// Not mapped to DB !!!
public virtual int ProcessId { get; set; } /// Not mapped to DB !!! Tracing DB Process ID
public virtual int SessionId { get; set; } /// Not mapped to DB !!! 1 (regular tracing DB session) or 2 (alternative tracing DB session)
public virtual bool LastRecordIsNok { get; set; } /// Not mapped to DB !!! Previous record verification result
public virtual WaterMeterData WaterMeterData { get; set; }
public virtual Batch Batch { get; set; }
@@ -109,23 +108,15 @@ namespace Results.Entities
///
/// Wrappers
///
public virtual string GetEndStateAux() { return Compound() ? EndStateAux : string.Empty; }
public virtual void SetEndStateAux(string s) { if (Compound()) EndStateAux = s; }
public virtual string GetStartState() { return Compound() ? string.Empty : EndStateAux; }
public virtual void SetStartState(string s) { if (!Compound()) EndStateAux = s; }
public virtual string ProductName() { return WaterMeterData.ProductName; }
public virtual string ProductName() { return WaterMeterData.ProductName; }
public virtual string Producer() { return WaterMeterData.Producer; }
public virtual string MetrologicalClass() { return WaterMeterData.MetrologicalClass; }
public virtual string ApprovalInfo() { return WaterMeterData.ApprovalInfo; }
public virtual FlowNames Qnames() { return (FlowNames)WaterMeterData.Qnames; }
public virtual bool NewQnames() { return WaterMeterData.NewQnames; }
public virtual double Q4_Qmax() { return WaterMeterData.Q4_Qmax; }
public virtual double Q3_Qn() { return WaterMeterData.Q3_Qn; }
public virtual double Q2_Qt() { return WaterMeterData.Q2_Qt; }
public virtual double Q1_Qmin() { return WaterMeterData.Q1_Qmin; }
public virtual double ErrLimHiQ() { return WaterMeterData.ErrLimHiQ; }
public virtual double ErrLimLoQ() { return WaterMeterData.ErrLimLoQ; }
public virtual bool Compound() { return WaterMeterData.Compound; }
public virtual bool HeatMeter() { return WaterMeterData.HeatMeter; }
@@ -134,10 +125,8 @@ namespace Results.Entities
public virtual double Q3_Qn_Aux() { return WaterMeterData.Q3_Qn_Aux; }
public virtual string MetrologicalClassAux() { return WaterMeterData.MetrologicalClassAux; }
public virtual string ApprovalInfoAux() { return WaterMeterData.ApprovalInfoAux; }
#if ORACLE_DB
public virtual int WMTypeId() { return WaterMeterData.WMTypeId; }
#endif
public virtual int BatchNr() { return Batch.BatchNr; }
public virtual int BatchNr() { return Batch.BatchNr; }
public virtual int BenchId() { return Batch.TestBenchId; }
public virtual string ProcedureName() { return Batch.ProcedureName; }
public virtual int ProcedureRevision() { return Batch.ProcedureRevision; }
@@ -197,30 +186,6 @@ namespace Results.Entities
#endif
}
public virtual long InfoFlagsFromTests()
{
long infoFlags = 0;
foreach (var mtr in MeterTestRslts)
{
if (mtr.Evaluate() && mtr.TestDone) infoFlags |= mtr.TestRslt.InfoFlags;
}
return infoFlags;
}
public virtual long InfoFlagsFromTestsAndWM()
{
return InfoFlagsFromTests() | InfoFlags;
}
/// <summary>
/// Convert combined errorFlags of all tests to string
/// </summary>
/// <returns>ErrorFlags string</returns>
public virtual string InfoFlagsStr()
{
return Utils.ErrorFlagsStr(InfoFlagsFromTestsAndWM());
}
public virtual string PassedOrErrorFlagsStr()
{
string eFlags = Utils.ErrorFlagsStr(ErrorFlagsFromTestsAndWM());
@@ -260,9 +225,7 @@ namespace Results.Entities
break;
}
}
#if ORACLE_DB
if (Utils.MaxTestIndex != 0 && (Pruefindex % 100) > Utils.MaxTestIndex) passed = false;
#endif
return passed;
}
@@ -340,7 +303,7 @@ namespace Results.Entities
return GetMeterTestRslt(testName, CompoundMeterId.SingleOrCompound);
}
public virtual MeterTestRslt GetMeterTestRslt(string testName, CompoundMeterId meterId = CompoundMeterId.Single)
public virtual MeterTestRslt GetMeterTestRslt(string testName, Config.Entities.CompoundMeterId meterId)
{
if (string.IsNullOrEmpty(testName)) return null;
if (Disabled) return null;
@@ -354,15 +317,18 @@ namespace Results.Entities
{
return mtr;
}
else if (meterId == CompoundMeterId.SingleOrCompound && mtr.CompoundMeterId == (byte)CompoundMeterId.Single)
else if (meterId == Config.Entities.CompoundMeterId.SingleOrCompound &&
mtr.CompoundMeterId == (byte)Config.Entities.CompoundMeterId.Single)
{
return mtr;
}
else if (meterId == CompoundMeterId.SingleOrCompound && mtr.CompoundMeterId == (byte)CompoundMeterId.Compound)
else if (meterId == Config.Entities.CompoundMeterId.SingleOrCompound &&
mtr.CompoundMeterId == (byte)Config.Entities.CompoundMeterId.Compound)
{
return mtr;
}
else if (meterId == CompoundMeterId.SingleOrCompound && mtr.CompoundMeterId == (byte)CompoundMeterId.HeatMeterEnergy)
else if (meterId == Config.Entities.CompoundMeterId.SingleOrCompound &&
mtr.CompoundMeterId == (byte)Config.Entities.CompoundMeterId.HeatMeterEnergy)
{
return mtr;
}
@@ -428,38 +394,35 @@ namespace Results.Entities
public WaterMeter()
{
MeterTestRslts = new List<MeterTestRslt>();
#if ORACLE_DB
Pruefindex = 1;
HydrPruefung = 0;
WMTypeRevision = 0;
RawTestInfos = null;
CompleteTestInfos = null;
#endif
ProcessId = 0;
SessionId = 0;
ErrorFlags = 0;
LastRecordIsNok = false;
/// Initialize strings
SerialNr = string.Empty;
SerialNrAux = string.Empty;
RadioAddress = string.Empty;
PurchaseOrder = string.Empty;
EndState = string.Empty;
EndStateAux = string.Empty;
ErrorFlags = 0;
InfoFlags = 0;
ArchivePath = string.Empty;
Remark = string.Empty;
#if IPERL
FWVersion = string.Empty;
#endif
#if TURA_SPECIAL
CompleteSerialNr = string.Empty;
RadioAddress = string.Empty;
ProdUserName = string.Empty;
ProdPurchaseOrder = string.Empty;
#endif
#if ORACLE_DB
AssignedSerialNr = 0;
Prefix = string.Empty;
Suffix = string.Empty;
CompleteSerialNr = string.Empty;
OriRadioAddress = string.Empty;
WMTypeRevision = 0;
Pruefindex = 0;
HydrPruefung = 0;
#if IPERL
FWVersion = string.Empty;
#endif
ProcessId = 0;
LastRecordIsNok = false;
PrintLabel = true;
}
@@ -467,65 +430,63 @@ namespace Results.Entities
{
if (src == null) return;
SerialNr = src.SerialNr;
SerialNrAux = src.SerialNrAux;
RadioAddress = src.RadioAddress;
PurchaseOrder = src.PurchaseOrder;
YearOfProduction = src.YearOfProduction;
WMPosition = src.WMPosition;
EndState = src.EndState;
EndStateAux = src.EndStateAux;
QRise = src.QRise;
QFall = src.QFall;
ErrorFlags = src.ErrorFlags;
InfoFlags = src.InfoFlags;
Passed = src.Passed;
ResultCode = src.ResultCode;
ArchivePath = src.ArchivePath;
Remark = src.Remark;
SerialNr = src.SerialNr;
SerialNrAux = src.SerialNrAux;
PurchaseOrder = src.PurchaseOrder;
YearOfProduction = src.YearOfProduction;
// WMPosition skipped
EndState = src.EndState;
EndStateAux = src.EndStateAux;
QRise = src.QRise;
QFall = src.QFall;
ErrorFlags = src.ErrorFlags;
Passed = src.Passed;
ResultCode = src.ResultCode;
ArchivePath = src.ArchivePath;
Remark = src.Remark;
#if IPERL
OrigCalibFactor = src.OrigCalibFactor;
CalibFactor = src.CalibFactor;
OrigCalibFactor = src.OrigCalibFactor;
CalibFactor = src.CalibFactor;
OrigCalibFactorLNA = src.OrigCalibFactorLNA;
CalibFactorLNA = src.CalibFactorLNA;
Q2ErrWOCorrection = src.Q2ErrWOCorrection;
Q2CorrRL = src.Q2CorrRL;
Q2CorrLR = src.Q2CorrLR;
Q2CorrFlowRight = src.Q2CorrFlowRight;
Diff2Hz8Hz = src.Diff2Hz8Hz;
Hz2CorrectionDone = src.Hz2CorrectionDone;
Hz2Correction = src.Hz2Correction;
FWVersion = src.FWVersion;
CalibFactorLNA = src.CalibFactorLNA;
Q2ErrWOCorrection = src.Q2ErrWOCorrection;
Q2CorrRL = src.Q2CorrRL;
Q2CorrLR = src.Q2CorrLR;
Q2CorrFlowRight = src.Q2CorrFlowRight;
Diff2Hz8Hz = src.Diff2Hz8Hz;
Hz2CorrectionDone = src.Hz2CorrectionDone;
Hz2Correction = src.Hz2Correction;
FWVersion = src.FWVersion;
#endif
#if TURA_SPECIAL
PaletteNr = src.PaletteNr;
UmkartonNr = src.UmkartonNr;
ProdTestBench = src.ProdTestBench;
ProdWMPosition = src.ProdWMPosition;
ProdUserName = src.ProdUserName;
ProdPurchaseOrder = src.ProdPurchaseOrder;
ProdPassed = src.ProdPassed;
ProdResultCode = src.ProdResultCode;
ProdQ2CorrRL = src.ProdQ2CorrRL;
ProdQ2CorrLR = src.ProdQ2CorrLR;
AssignedSerialNr = src.AssignedSerialNr;
CompleteSerialNr = src.CompleteSerialNr;
RadioAddress = src.RadioAddress;
PaletteNr = src.PaletteNr;
UmkartonNr = src.UmkartonNr;
ProdTestBench = src.ProdTestBench;
ProdWMPosition = src.ProdWMPosition;
ProdUserName = src.ProdUserName;
ProdPurchaseOrder = src.ProdPurchaseOrder;
ProdPassed = src.ProdPassed;
ProdResultCode = src.ProdResultCode;
ProdQ2CorrRL = src.ProdQ2CorrRL;
ProdQ2CorrLR = src.ProdQ2CorrLR;
#endif
#if ORACLE_DB
AssignedSerialNr = src.AssignedSerialNr;
Prefix = src.Prefix;
Suffix = src.Suffix;
CompleteSerialNr = src.CompleteSerialNr;
OriRadioAddress = src.OriRadioAddress;
WMTypeRevision = src.WMTypeRevision;
Pruefindex = src.Pruefindex;
HydrPruefung = src.HydrPruefung;
Pruefindex = src.Pruefindex;
HydrPruefung = src.HydrPruefung;
WMTypeRevision = src.WMTypeRevision;
RawTestInfos = src.RawTestInfos;
CompleteTestInfos = src.CompleteTestInfos;
#endif
ProcessId = src.ProcessId; /// Not mapped to DB
LastRecordIsNok = src.LastRecordIsNok; /// Not mapped to DB
PrintLabel = src.PrintLabel; /// Not mapped to DB
ProcessId = src.ProcessId;
SessionId = src.SessionId;
LastRecordIsNok = src.LastRecordIsNok;
foreach (var mtr in MeterTestRslts)
{
MeterTestRslt srcMtr = src.GetMeterTestRslt(mtr.Name(), (CompoundMeterId)mtr.CompoundMeterId);
MeterTestRslt srcMtr = src.GetMeterTestRslt(mtr.Name(), (Config.Entities.CompoundMeterId)mtr.CompoundMeterId);
if (srcMtr != null)
{
mtr.CopyContentFrom(srcMtr);
@@ -564,8 +525,8 @@ namespace Results.Entities
{
if ((mtr.CompoundMeterId == (byte)CompoundMeterId.Single || mtr.CompoundMeterId == (byte)CompoundMeterId.Compound || mtr.CompoundMeterId == (byte)CompoundMeterId.HeatMeterEnergy)
&& mtr.TestDone
&& (mtr.Publish() != Publish.Never)
&& (mtr.Publish() != Publish.Internal))
&& (mtr.Publish() != Config.Entities.Publish.Never)
&& (mtr.Publish() != Config.Entities.Publish.Internal))
{
testNames.Add(mtr.Name());
}
@@ -649,7 +610,6 @@ namespace Results.Entities
writer.Write(Id);
writer.Write((SerialNr != null) ? SerialNr : string.Empty);
writer.Write((SerialNrAux != null) ? SerialNrAux : string.Empty);
writer.Write((RadioAddress != null) ? RadioAddress : string.Empty);
writer.Write((PurchaseOrder != null) ? PurchaseOrder : string.Empty);
writer.Write(YearOfProduction);
writer.Write(WMPosition);
@@ -678,6 +638,9 @@ namespace Results.Entities
writer.Write((FWVersion != null) ? FWVersion : string.Empty);
#endif
#if TURA_SPECIAL
writer.Write(AssignedSerialNr);
writer.Write((CompleteSerialNr != null) ? CompleteSerialNr : string.Empty);
writer.Write((RadioAddress != null) ? RadioAddress : string.Empty);
writer.Write(PaletteNr);
writer.Write(UmkartonNr);
writer.Write((ProdTestBench != null) ? ProdTestBench : string.Empty);
@@ -690,18 +653,29 @@ namespace Results.Entities
writer.Write(ProdQ2CorrLR);
#endif
#if ORACLE_DB
writer.Write(AssignedSerialNr);
writer.Write((Prefix != null) ? Prefix : string.Empty);
writer.Write((Suffix != null) ? Suffix : string.Empty);
writer.Write((CompleteSerialNr != null) ? CompleteSerialNr : string.Empty);
writer.Write((OriRadioAddress != null) ? OriRadioAddress : string.Empty);
writer.Write(WMTypeRevision);
writer.Write(Pruefindex);
writer.Write(HydrPruefung);
writer.Write(WMTypeRevision);
/// Write RawTestInfos
IList<Results.Output.SensusTestInfo> rawTestInfos = RawTestInfos as IList<Results.Output.SensusTestInfo>;
writer.Write((rawTestInfos != null) ? rawTestInfos.Count : 0);
if (rawTestInfos != null)
{
for (int i = 0; i < rawTestInfos.Count; i++) rawTestInfos[i].WriteBinary(writer);
}
/// Write CompleteTestInfos
Results.Output.SensusTestInfo[] completeTestInfos = CompleteTestInfos as Results.Output.SensusTestInfo[];
writer.Write((completeTestInfos != null) ? completeTestInfos.Length : 0);
if (completeTestInfos != null)
{
for (int i = 0; i < completeTestInfos.Length; i++) completeTestInfos[i].WriteBinary(writer);
}
#endif
writer.Write(ProcessId);
writer.Write(SessionId);
writer.Write(LastRecordIsNok);
writer.Write(PrintLabel);
/// Save WaterMeterData or WaterMeterData.Id
if (WaterMeterData != null && savedWMDatas != null && !savedWMDatas.Contains(WaterMeterData))
@@ -729,7 +703,6 @@ namespace Results.Entities
Id = reader.ReadInt32();
SerialNr = reader.ReadString();
SerialNrAux = reader.ReadString();
RadioAddress = reader.ReadString();
PurchaseOrder = reader.ReadString();
YearOfProduction = reader.ReadInt32();
WMPosition = reader.ReadInt32();
@@ -758,6 +731,9 @@ namespace Results.Entities
FWVersion = reader.ReadString();
#endif
#if TURA_SPECIAL
AssignedSerialNr = reader.ReadInt32();
CompleteSerialNr = reader.ReadString();
RadioAddress = reader.ReadString();
PaletteNr = reader.ReadInt32();
UmkartonNr = reader.ReadInt32();
ProdTestBench = reader.ReadString();
@@ -770,18 +746,35 @@ namespace Results.Entities
ProdQ2CorrLR = reader.ReadInt32();
#endif
#if ORACLE_DB
AssignedSerialNr = reader.ReadInt32();
Prefix = reader.ReadString();
Suffix = reader.ReadString();
CompleteSerialNr = reader.ReadString();
OriRadioAddress = reader.ReadString();
WMTypeRevision = reader.ReadInt32();
Pruefindex = reader.ReadInt32();
HydrPruefung = reader.ReadInt32();
WMTypeRevision = reader.ReadInt32();
/// Read RawTestInfos
int rawTestInfosCount = reader.ReadInt32();
IList<Results.Output.SensusTestInfo> rawTestInfos = new List<Results.Output.SensusTestInfo>();
for (int i = 0; i < rawTestInfosCount; i++)
{
Results.Output.SensusTestInfo ti = new Results.Output.SensusTestInfo();
ti.ReadBinary(reader);
rawTestInfos.Add(ti);
}
RawTestInfos = rawTestInfos;
/// Read CompleteTestInfos
int completeTestInfosLen = reader.ReadInt32();
Results.Output.SensusTestInfo[] completeTestInfos = new Results.Output.SensusTestInfo[completeTestInfosLen];
for (int i = 0; i < completeTestInfosLen; i++)
{
Results.Output.SensusTestInfo ti = new Results.Output.SensusTestInfo();
ti.ReadBinary(reader);
completeTestInfos[i] = ti;
}
CompleteTestInfos = completeTestInfos;
#endif
ProcessId = reader.ReadInt32();
SessionId = reader.ReadInt32();
LastRecordIsNok = reader.ReadBoolean();
PrintLabel = reader.ReadBoolean();
/// Retrieve TestData
if (reader.ReadBoolean())

Some files were not shown because too many files have changed in this diff Show More