diff --git a/Common/Ui/GenesisToolBox/FrmTempMeter.Designer.cs b/Common/Ui/GenesisToolBox/FrmTempMeter.Designer.cs index a7667815..e6603a78 100644 --- a/Common/Ui/GenesisToolBox/FrmTempMeter.Designer.cs +++ b/Common/Ui/GenesisToolBox/FrmTempMeter.Designer.cs @@ -76,8 +76,6 @@ namespace Xylem.Common.Ui.GenesisToolBox this.label1 = new System.Windows.Forms.Label(); this.timer3 = new System.Windows.Forms.Timer(this.components); this.mainMenuStrip = new System.Windows.Forms.MenuStrip(); - this.messurementExitAfterInMin = new System.Windows.Forms.TextBox(); - this.label12 = new System.Windows.Forms.Label(); this.automaticCalibrationTabControl.SuspendLayout(); this.tabPage1.SuspendLayout(); this.tabPage2.SuspendLayout(); @@ -368,8 +366,6 @@ namespace Xylem.Common.Ui.GenesisToolBox // automaticControlsPanel // this.automaticControlsPanel.BackColor = System.Drawing.SystemColors.Menu; - this.automaticControlsPanel.Controls.Add(this.messurementExitAfterInMin); - this.automaticControlsPanel.Controls.Add(this.label12); this.automaticControlsPanel.Controls.Add(this.messurementTOFTolerance); this.automaticControlsPanel.Controls.Add(this.label42); this.automaticControlsPanel.Controls.Add(this.stopAutomaticBtn); @@ -423,7 +419,7 @@ namespace Xylem.Common.Ui.GenesisToolBox this.stopAutomaticBtn.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.stopAutomaticBtn.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink; - this.stopAutomaticBtn.Location = new System.Drawing.Point(5, 426); + this.stopAutomaticBtn.Location = new System.Drawing.Point(5, 382); this.stopAutomaticBtn.Margin = new System.Windows.Forms.Padding(5); this.stopAutomaticBtn.Name = "stopAutomaticBtn"; this.stopAutomaticBtn.Padding = new System.Windows.Forms.Padding(0, 5, 0, 5); @@ -438,7 +434,7 @@ namespace Xylem.Common.Ui.GenesisToolBox this.startAutomaticBtn.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.startAutomaticBtn.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink; - this.startAutomaticBtn.Location = new System.Drawing.Point(5, 380); + this.startAutomaticBtn.Location = new System.Drawing.Point(5, 336); this.startAutomaticBtn.Margin = new System.Windows.Forms.Padding(5); this.startAutomaticBtn.Name = "startAutomaticBtn"; this.startAutomaticBtn.Padding = new System.Windows.Forms.Padding(0, 5, 0, 5); @@ -613,31 +609,6 @@ namespace Xylem.Common.Ui.GenesisToolBox this.mainMenuStrip.TabIndex = 57; this.mainMenuStrip.Text = "menuStrip1"; // - // messurementExitAfterInMin - // - this.messurementExitAfterInMin.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) - | System.Windows.Forms.AnchorStyles.Right))); - this.messurementExitAfterInMin.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; - this.messurementExitAfterInMin.Font = new System.Drawing.Font("Microsoft Sans Serif", 11.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); - this.messurementExitAfterInMin.Location = new System.Drawing.Point(5, 344); - this.messurementExitAfterInMin.Margin = new System.Windows.Forms.Padding(0); - this.messurementExitAfterInMin.Name = "messurementExitAfterInMin"; - this.messurementExitAfterInMin.Size = new System.Drawing.Size(318, 24); - this.messurementExitAfterInMin.TabIndex = 18; - // - // label12 - // - this.label12.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) - | System.Windows.Forms.AnchorStyles.Right))); - this.label12.FlatStyle = System.Windows.Forms.FlatStyle.System; - this.label12.Location = new System.Drawing.Point(5, 327); - this.label12.Margin = new System.Windows.Forms.Padding(5); - this.label12.Name = "label12"; - this.label12.Size = new System.Drawing.Size(318, 18); - this.label12.TabIndex = 17; - this.label12.Text = "Exit when °C is not changing (in minutes) "; - this.label12.TextAlign = System.Drawing.ContentAlignment.BottomLeft; - // // FrmTempMeter // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); @@ -710,7 +681,5 @@ namespace Xylem.Common.Ui.GenesisToolBox private System.Windows.Forms.Button startAutomaticBtn; private System.Windows.Forms.TextBox messurementTOFTolerance; private System.Windows.Forms.Label label42; - private System.Windows.Forms.TextBox messurementExitAfterInMin; - private System.Windows.Forms.Label label12; } } \ No newline at end of file diff --git a/Common/Ui/GenesisToolBox/FrmTempMeter.cs b/Common/Ui/GenesisToolBox/FrmTempMeter.cs index 01fb78ac..e5fb33f3 100644 --- a/Common/Ui/GenesisToolBox/FrmTempMeter.cs +++ b/Common/Ui/GenesisToolBox/FrmTempMeter.cs @@ -603,7 +603,8 @@ Font = fontBold, TextAlign = ContentAlignment.MiddleCenter, Margin = new Padding(10, 0, 0, 0), - Padding = new Padding(10, 0, 10, 0) + Padding = new Padding(10, 0, 10, 0), + BackColor = Color.LightGray }; this.connectBtn.Click += this.BtnConnect_Click; @@ -614,7 +615,8 @@ Font = fontBold, TextAlign = ContentAlignment.MiddleCenter, Margin = new Padding(5, 0, 0, 0), - Padding = new Padding(10, 0, 10, 0) + Padding = new Padding(10, 0, 10, 0), + BackColor = Color.LightGray }; this.connectBtn.Click += this.TestBtn_Click; @@ -691,7 +693,6 @@ this.messurementStep.DataBindings.Add(property, source, nameof(source.MessurementStep), false, mode); this.messurementToleranceInC.DataBindings.Add(property, source, nameof(source.MessurementToleranceInC), false, mode); this.messurementTOFTolerance.DataBindings.Add(property, source, nameof(source.MessurementTOFTolerance), false, mode); - this.messurementExitAfterInMin.DataBindings.Add(property, source, nameof(source.ExitWhenNotChangedInMin), false, mode); } private void RemoveTextBoxBindings(Object sender, EventArgs e) @@ -703,7 +704,6 @@ this.messurementStep.DataBindings.Clear(); this.messurementToleranceInC.DataBindings.Clear(); this.messurementTOFTolerance.DataBindings.Clear(); - this.messurementExitAfterInMin.DataBindings.Clear(); } private bool automatic = false; @@ -713,22 +713,26 @@ private void StartAutomaticBtn_Clicked(object sender, EventArgs args) { - this.previousCulture = Thread.CurrentThread.CurrentCulture; - var cultureInfo = new CultureInfo("en-US"); - cultureInfo.DateTimeFormat.DateSeparator = "-"; - Thread.CurrentThread.CurrentCulture = cultureInfo; - Thread.CurrentThread.CurrentUICulture = cultureInfo; + if (this.currentGenesis is null) + { + return; + } + + //this.previousCulture = Thread.CurrentThread.CurrentCulture; + //var cultureInfo = new CultureInfo("en-US"); + //cultureInfo.DateTimeFormat.DateSeparator = "-"; + //Thread.CurrentThread.CurrentCulture = cultureInfo; + //Thread.CurrentThread.CurrentUICulture = cultureInfo; this.automatic = true; this.start = DateTimeOffset.Now; this.messurementsFile = $"{this.start:yyyy-MM-dd}.messurements"; - this.currentGenesis?.StartRecordData(); - this.currentGenesis?.WriteRegister(Register.Genesisflow.SampleRate, 16, checkRegister: true); - this.currentGenesis?.WriteRegister("GENESISFLOW_MaxValidDeltaToF", 4294967295, checkRegister: true); - this.currentGenesis?.WriteRegister("GENESISFLOW_MaxValidToF", 4294967295, checkRegister: true); - this.currentGenesis?.WriteRegister("GENESISFLOW_MinValidToF", 0, checkRegister: true); - + this.currentGenesis.StartRecordData(); + this.currentGenesis.WriteRegister(Register.Genesisflow.SampleRate, (byte)16, checkRegister: true); + this.currentGenesis.WriteRegister("GENESISFLOW_MaxValidDeltaToF", 4294967295, checkRegister: true); + this.currentGenesis.WriteRegister("GENESISFLOW_MaxValidToF", 4294967295, checkRegister: true); + this.currentGenesis.WriteRegister("GENESISFLOW_MinValidToF", (uint)0, checkRegister: true); this.automaticCalibration = new AutomaticTemperatureCalibration(() => this.OutputAvgTof()); this.automaticCalibration.TemperatureMesured += this.SaveMessurement; @@ -752,9 +756,9 @@ private void StopAutomaticBtn_Clicked(object sender, EventArgs args) { - Thread.CurrentThread.CurrentCulture = this.previousCulture; - Thread.CurrentThread.CurrentUICulture = this.previousCulture; - this.previousCulture = default(CultureInfo); + //Thread.CurrentThread.CurrentCulture = this.previousCulture; + //Thread.CurrentThread.CurrentUICulture = this.previousCulture; + //this.previousCulture = default(CultureInfo); this.automatic = false; this.automaticCalibration.TemperatureMesured -= this.SaveMessurement; @@ -798,16 +802,17 @@ File.AppendAllLines(this.messurementsFile, new[] { message }); } - private void SaveMessurement(double meterTOF, double referenceT, DateTime timestamp) + private void SaveMessurement(double meterTOF, double temperature, DateTime timestamp) { - var pcbid = this.currentGenesis.PcbId; - var tmp = referenceT.ToString("us-US"); - var tof = meterTOF.ToString("us-US"); + var pcbid = this.currentGenesis?.PcbId ?? "200000000"; + var tmp = temperature.ToString("en-US"); + var tof = meterTOF.ToString("en-US"); File.AppendAllLines(this.messurementsFile, new[] { $"{pcbid}\t{tmp}\t{tof}\t{timestamp}" }); // Note: the MeterProcessState should be also updated. // To the endpoint was added new property: dt <=> Timestamp -> this is the timestamp provided from the automatic temperature calibration. - LocalWebRequest.PostRequestAsync($"http://10.49.40.25/MeterProcessState/api/TempFlange/AddLut?PcbId={pcbid}&RefTempC={tmp}&AvgTof={tof}&dt={timestamp}"); + File.AppendAllLines("temp_luts.txt", new[] { $"{pcbid}\t{tmp}\t{tof}\t{timestamp}" }); + // LocalWebRequest.PostRequestAsync($"http://10.49.40.25/MeterProcessState/api/TempFlange/AddLut?PcbId={pcbid}&RefTempC={tmp}&AvgTof={tof}&dt={timestamp}"); } } } diff --git a/Common/Ui/GenesisToolBox/GenesisToolBox.csproj b/Common/Ui/GenesisToolBox/GenesisToolBox.csproj index 12d30676..961867ac 100644 --- a/Common/Ui/GenesisToolBox/GenesisToolBox.csproj +++ b/Common/Ui/GenesisToolBox/GenesisToolBox.csproj @@ -14,7 +14,7 @@ true false - publish\ + L:\Stoyan\temperature_calibration\ false Disk false @@ -24,8 +24,8 @@ false false true - 2 - 2.6.0 + 3 + 1.0.0.%2a false true true @@ -85,7 +85,7 @@ GenesisToolBox_TemporaryKey.pfx - false + true false @@ -153,6 +153,9 @@ false + + ..\..\packages\ConfigurationJson.1.0.2\lib\net48\ConfigurationJson.dll + ..\..\packages\Newtonsoft.Json.13.0.3\lib\net45\Newtonsoft.Json.dll diff --git a/Common/Ui/GenesisToolBox/GenesisToolBox.csproj.user b/Common/Ui/GenesisToolBox/GenesisToolBox.csproj.user index ea750310..888ca413 100644 --- a/Common/Ui/GenesisToolBox/GenesisToolBox.csproj.user +++ b/Common/Ui/GenesisToolBox/GenesisToolBox.csproj.user @@ -10,6 +10,6 @@ de-DE false - ShowAllFiles + ProjectFiles \ No newline at end of file diff --git a/Common/Ui/GenesisToolBox/Infrastructure/Appsettings.cs b/Common/Ui/GenesisToolBox/Infrastructure/Appsettings.cs index ca62e3a7..6d4f9dc6 100644 --- a/Common/Ui/GenesisToolBox/Infrastructure/Appsettings.cs +++ b/Common/Ui/GenesisToolBox/Infrastructure/Appsettings.cs @@ -14,23 +14,33 @@ private class DefaultValues { - public const int TemperatureCheckInMs = 6_000; + public const int TemperatureCheckInMs = 5_00; public const double TemperatureCheckInC = 1.00; - public const int TemperatureChecksCount = 10; - public const int MessurementDauerInMs = 600_000; - public const int MessurementStep = 10_000; + public const int TemperatureChecksCount = 5; + public const int MessurementDauerInMs = 6_000; + public const int MessurementStep = 5_00; public const double MessurementToleranceInC = 0.05; public const double MessurementTOFTolerance = 30.00; - public const int ExitWhenNotChangedInMin = 60; } public class AppsettingsModel : INotifyPropertyChanged { + public AppsettingsModel() + { + this.TemperatureCheckInMs = DefaultValues.TemperatureCheckInMs.ToString(); + this.TemperatureCheckInC = DefaultValues.TemperatureCheckInC.ToString(); + this.TemperatureChecksCount = DefaultValues.TemperatureChecksCount.ToString(); + this.MessurementDauerInMs = DefaultValues.MessurementDauerInMs.ToString(); + this.MessurementStep = DefaultValues.MessurementStep.ToString(); + this.MessurementToleranceInC = DefaultValues.MessurementToleranceInC.ToString(); + this.MessurementTOFTolerance = DefaultValues.MessurementTOFTolerance.ToString(); + } + /// /// The time in whitch should be checked for temperature changes greater than °C. By default: 1min * 60sec * 1000ms = 60_000ms. /// After temperature change is detected, messurement should start for in tolerance from +/- °C. /// - public string TemperatureCheckInMs + public string TemperatureCheckInMs // { get; set; } { get => GetStringValue(DefaultValues.TemperatureCheckInMs); set => this.NotifyPropertyChanged(value, DefaultValues.TemperatureCheckInMs); @@ -40,7 +50,7 @@ /// The mark on whitch should be notified for temperature change. /// By default +/-1°C. /// - public string TemperatureCheckInC + public string TemperatureCheckInC // { get; set; } { get => GetStringValue(DefaultValues.TemperatureCheckInC); set => this.NotifyPropertyChanged(value, DefaultValues.TemperatureCheckInC); @@ -50,7 +60,7 @@ /// Describes after how many checks the temperature is counted as same. /// By default 10. /// - public string TemperatureChecksCount + public string TemperatureChecksCount // { get; set; } { get => GetStringValue(DefaultValues.TemperatureChecksCount); set => this.NotifyPropertyChanged(value, DefaultValues.TemperatureChecksCount); @@ -60,7 +70,7 @@ /// Describes how long should be messured current temperature. /// By default: 10min * 60sec * 1000ms = 600_000ms. /// - public string MessurementDauerInMs + public string MessurementDauerInMs // { get; set; } { get => GetStringValue(DefaultValues.MessurementDauerInMs); set => this.NotifyPropertyChanged(value, DefaultValues.MessurementDauerInMs); @@ -70,7 +80,7 @@ /// Describes in how many seconds schuld be messured. /// By default: 10sec * 1000ms = 10_000ms. /// - public string MessurementStep + public string MessurementStep // { get; set; } { get => GetStringValue(DefaultValues.MessurementStep); set => this.NotifyPropertyChanged(value, DefaultValues.MessurementStep); @@ -81,7 +91,7 @@ /// If the tolerance is oversteped, the messurement is canceled. /// By default: +/-0.05°C. /// - public string MessurementToleranceInC + public string MessurementToleranceInC // { get; set; } { get => GetStringValue(DefaultValues.MessurementToleranceInC); set => this.NotifyPropertyChanged(value, DefaultValues.MessurementToleranceInC); @@ -91,21 +101,12 @@ /// Describes the tolerance in whitch should all TOF's laying (in %). /// By default: +/-30.00%. /// - public string MessurementTOFTolerance + public string MessurementTOFTolerance // { get; set; } { get => GetStringValue(DefaultValues.MessurementTOFTolerance); set => this.NotifyPropertyChanged(value, DefaultValues.MessurementTOFTolerance); } - /// - /// Describes in how mutch time schuld the messurement be canceled when temperature not changing. - /// - public string ExitWhenNotChangedInMin - { - get => GetStringValue(DefaultValues.ExitWhenNotChangedInMin); - set => this.NotifyPropertyChanged(value, DefaultValues.ExitWhenNotChangedInMin); - } - public event PropertyChangedEventHandler PropertyChanged; protected void NotifyPropertyChanged(object currentValue, T defaultValue, [CallerMemberName] string property = EMPTY) @@ -143,7 +144,7 @@ public static int TemperatureChecksCount => GetValue(DefaultValues.TemperatureChecksCount); /// - /// + /// /// public static int MessurementDauerInMs => GetValue(DefaultValues.MessurementDauerInMs); @@ -162,10 +163,11 @@ /// public static double MessurementTOFTolerance => GetValue(DefaultValues.MessurementTOFTolerance); - /// - /// - /// - public static int ExitWhenNotChangedInMin => GetValue(DefaultValues.ExitWhenNotChangedInMin); + public static void Refresh() + { + configuration.Save(ConfigurationSaveMode.Full); + ConfigurationManager.RefreshSection("appSettings"); + } private static int GetValue(int defaultValue, [CallerMemberName] string property = EMPTY) { diff --git a/Common/Ui/GenesisToolBox/Infrastructure/TempMeterModels.cs b/Common/Ui/GenesisToolBox/Infrastructure/TempMeterModels.cs index 9996aea4..24d707b1 100644 --- a/Common/Ui/GenesisToolBox/Infrastructure/TempMeterModels.cs +++ b/Common/Ui/GenesisToolBox/Infrastructure/TempMeterModels.cs @@ -8,6 +8,8 @@ using System.Linq; using System.Timers; + using static System.Globalization.NumberStyles; + public class CordonelTempLut { public int Id { get; set; } @@ -62,37 +64,110 @@ public DateTime DTS { get; set; } } - internal class AutomaticTemperatureCalibration + class TemperatureSource : IDisposable + { + private readonly NamedPipeClientStream pipeStream; + private readonly StreamReader pipeReader; + private readonly CultureInfo de; + private readonly CultureInfo us; +#if false + private readonly TestValues values; + + public TemperatureSource() + => this.values = new TestValues(); + + public bool TryGetTemperature(out double temperature) + { + temperature = this.values.Temperature.Dequeue(); + + this.values.Temperature.Enqueue(temperature); + + return true; + } + + public double GetTOF(double temperature) + => this.values.GetTOF(temperature); +#else + public TemperatureSource() + { + try + { + this.pipeStream = new NamedPipeClientStream(".", "TempPipe", PipeDirection.In); + this.pipeStream.Connect(3000); + } + catch (Exception e) + { + } + + if (this.pipeStream.IsConnected) + { + this.pipeReader = new StreamReader(this.pipeStream); + } + + this.de = new CultureInfo("de-DE"); + this.us = new CultureInfo("en-US"); + } + + public bool TryGetTemperature(out double temperature) + { + temperature = double.MinValue; + + try + { + lock (this.pipeReader) + { + var value = $"{this.pipeReader.ReadLine()}"; + + if (double.TryParse(value, Any, this.de, out temperature) || double.TryParse(value, Any, this.us, out temperature)) + { + return true; + } + } + } + catch (Exception e) + { + Console.Error.WriteLine(e.Message); + } + + return false; + } +#endif + public void Dispose() + { + this.pipeReader?.Dispose(); + this.pipeStream?.Dispose(); + } + } + + partial class AutomaticTemperatureCalibration { private readonly int messurementsCount; - private readonly Func tofSource; + private readonly Func sourceTOF; private readonly Timer temperatureWatcher; private readonly Timer messurementWatcher; - private readonly ICollection messurements; - - private int messurmentN; - private double referenceT; - private bool waitingChanges; - private int temperatureChecks; - private int temperatureErrors; - private StreamReader streamReader; - private NamedPipeClientStream pipeStream; - private DateTime? timestamp; + private readonly TemperatureSource temperature; - public AutomaticTemperatureCalibration(Func tofSource) + private ICollection messurements; + private int temperatureChecks; + private int messurementsN; + private double previousT; + + public AutomaticTemperatureCalibration(Func sourceTOF) { - this.tofSource = tofSource; - // Instead of time tracking, +#if false + this.sourceTOF = () => this.temperature.GetTOF(this.previousT); +#else + this.sourceTOF = sourceTOF; +#endif + this.temperature = new TemperatureSource(); + this.messurements = new List(); this.messurementsCount = Appsettings.MessurementDauerInMs / Appsettings.MessurementStep; - this.temperatureWatcher = new Timer(Appsettings.TemperatureCheckInMs); + this.temperatureWatcher = new Timer(Math.Max(Appsettings.TemperatureCheckInMs, 1000)); this.temperatureWatcher.Elapsed += this.CheckTemperature; - this.messurementWatcher = new Timer(Appsettings.MessurementStep); + this.messurementWatcher = new Timer(Math.Max(Appsettings.MessurementStep, 1000)); this.messurementWatcher.Elapsed += this.Messure; - - this.waitingChanges = true; - this.messurements = new List(); } public event Action Start; @@ -104,327 +179,255 @@ public void StartMessuring() { - this.Info(string.Empty); - this.Info($"================================"); - this.Info($"[INFO] Starting messurements ..."); + Appsettings.Refresh(); - if (this.tofSource != null) + if (this.sourceTOF is null) { - try - { - this.pipeStream = new NamedPipeClientStream(".", "TempPipe", PipeDirection.In); - this.pipeStream.Connect(3000); - } - catch (Exception e) - { - this.Error(e.Message); - this.Stop?.Invoke(); - } - - if (this.pipeStream.IsConnected) - { - this.streamReader = new StreamReader(this.pipeStream); - this.StopMessurementWatcher(); - this.StartTemperatureWatcher(); - - this.Start?.Invoke(); - } + this.StopTemperatureWatcher(); + this.StopMessurementWatcher(); + this.Stop?.Invoke(); } else { - this.Stop?.Invoke(); - this.Info($"\tTOF source is missing."); + this.StopMessurementWatcher(); + this.StartTemperatureWatcher(); + this.Start?.Invoke(); } } public void StopMessuring() { - this.Info(string.Empty); - - if (this.tofSource != null) + if (this.sourceTOF != null) { - this.StopMessurementWatcher(); - this.StopTemperatureWatcher(); - this.streamReader.Dispose(); - this.pipeStream.Close(); + this.temperature.Dispose(); } + this.StopMessurementWatcher(); + this.StopTemperatureWatcher(); this.Stop?.Invoke(); - this.Info($"[INFO] Messurements canceled."); - this.Info($"============================="); - this.Info(string.Empty); - } - - private void Info(string message) - => this.InfoMessage?.Invoke(message); - - private void Warning(string message) - => this.WarningMessage?.Invoke(message); - - private void Error(string message) - => this.ErrorMessage?.Invoke(message); - - private void StartTemperatureWatcher() - { - this.temperatureWatcher.AutoReset = true; - this.temperatureWatcher.Enabled = true; - this.temperatureWatcher.Start(); - } - - private void StopTemperatureWatcher() - { - this.temperatureWatcher.Stop(); - this.temperatureWatcher.Enabled = false; - this.temperatureWatcher.AutoReset = false; - } - - private void StartMessurementWatcher() - { - this.messurmentN = 1; - this.messurementWatcher.AutoReset = true; - this.messurementWatcher.Enabled = true; - this.messurementWatcher.Start(); - } - - private void StopMessurementWatcher() - { - this.messurmentN = 1; - this.messurementWatcher.Stop(); - this.messurementWatcher.Enabled = false; - this.messurementWatcher.AutoReset = false; } private void CheckTemperature(object sender, ElapsedEventArgs args) { - // Default start number. - const int start = 1; + this.temperatureChecks++; - // If reading of the reference temperature succeeds. - if (this.TryGetReferenceT(out var referenceT)) + if (this.temperature.TryGetTemperature(out var currentT)) { - // Calculating the absolute difference to the previouse temperature. - var differenceT = Math.Abs(this.referenceT - referenceT); - - if (this.waitingChanges && differenceT < Appsettings.TemperatureCheckInC) + var differenceT = Math.Abs(this.previousT - currentT); + + if (differenceT <= Appsettings.MessurementToleranceInC) { - // Reset counter to default. - this.temperatureChecks = 0; - - this.Warning($"[CHECK] Temperature is not changed {this.referenceT,5:0.00} <=> {referenceT,5:0.00}°C difference {differenceT,5:0.00}°C {args.SignalTime:hh:mm:ss.fff}ms"); - - if (this.timestamp.HasValue && Math.Abs((args.SignalTime - this.timestamp.Value).TotalMinutes) > Appsettings.ExitWhenNotChangedInMin) + if (this.temperatureChecks > Appsettings.TemperatureChecksCount) { - this.StopMessuring(); + this.previousT = currentT; + this.temperatureChecks = 0; + + this.StopTemperatureWatcher(); + this.StartMessurementWatcher(); + + return; } - - return; } - - this.timestamp = args.SignalTime; - - // If difference is greater or equal than configured, reset counter and start tracking the new temperature. - if (differenceT >= Appsettings.TemperatureCheckInC) + else { - if (this.temperatureChecks == 0) + this.temperatureChecks = 1; + + if (this.previousT != 0) { - this.Info(string.Empty); - this.Info($"[CHECK] Start counting: {Appsettings.TemperatureChecksCount} times for {referenceT:0.00}°C +/-{Appsettings.MessurementToleranceInC:0.00}°C"); + this.WarningMessage?.Invoke("\t... temperature difference is not in the tolerance span, restarting counter!"); } - - this.waitingChanges = false; - // Start counting from 1. - this.temperatureChecks = start; - // Saving current temperature for fuhrter comparisons. - this.referenceT = referenceT; - - var t = differenceT == referenceT ? 0 : differenceT; - this.Info($"[CHECK] {this.temperatureChecks, 2}. {referenceT, 5:0.00}°C difference {t, 5:0.00}°C {args.SignalTime:hh:mm:ss.fff}ms"); - } - // If tolerance is smaller or equal than configured, - else if (differenceT <= Appsettings.MessurementToleranceInC) - { - // the temperature is same also continue counting. - this.temperatureChecks++; - - this.Info($"[CHECK] {this.temperatureChecks, 2}. {referenceT, 5:0.00}°C difference {differenceT, 5:0.00}°C {args.SignalTime:hh:mm:ss.fff}ms"); } - // If counter reaches configured counts then start messurement for configured time. - if (this.temperatureChecks == Appsettings.TemperatureChecksCount) - { - this.waitingChanges = true; - // Reset counter to default. - this.temperatureChecks = 0; - // Next call breaks current method execution. - this.StopTemperatureWatcher(); - // Next call starts new messurement as configured. - this.StartMessurementWatcher(); - - this.Info(string.Empty); - this.Info($"[INFO] Starting messurement - {args.SignalTime: yyyy-MM-dd hh:mm:ss.ffff}, {Appsettings.MessurementStep}ms for {Appsettings.MessurementDauerInMs}ms"); - } + this.InfoMessage?.Invoke($"\t{this.temperatureChecks,3}\t{this.previousT,8:F2}\t{currentT,7:F2}\t{differenceT,10:F2}"); } else { - this.waitingChanges = true; - // Reset counter to default. this.temperatureChecks = 0; - // Reset temperature to default. - this.referenceT = default(double); - this.Info(string.Empty); - this.Warning($"[WARNING] Reading reference temperature failed, resseting state."); + this.InfoMessage?.Invoke($"\t{this.temperatureChecks,3}\t{this.previousT,8:F2}\t.......\t.........."); } + + this.previousT = currentT; } private void Messure(object sender, ElapsedEventArgs args) { - // If reading of the reference temperature succeeds ... - if (this.TryGetReferenceT(out var referenceT)) + this.messurementsN++; + + if (!this.temperature.TryGetTemperature(out var currentT)) { - var differenceT = Math.Abs(this.referenceT - referenceT); + return; + } - // If the absolute difference is in expected tolerance. - if (differenceT <= Appsettings.MessurementToleranceInC) + var differenceT = Math.Abs(this.previousT - currentT); + + if (differenceT > Appsettings.MessurementToleranceInC) + { + if (this.messurements.Count >= this.messurementsCount / 2) { - this.referenceT = referenceT; + this.StopMessurementWatcher(); + this.StartTemperatureWatcher(); - var currentTOF = this.tofSource(); - var hasValidTOF = true; - - this.Info($"[INFO] {this.messurmentN, 2}. {currentTOF, 19:F18}, {referenceT, 5:0.00}°C, +/-{differenceT, 5:0.00}°C, {args.SignalTime:hh:mm:ss.fff}ms"); - - // For some LINQ expressions the collection should have at least 1 item in it. if (this.messurements.Any()) { - // For instance if the tolerance is 30% => 30 / 100 = 0.3 - var tolerance = Appsettings.MessurementTOFTolerance / 100; - // Calculating min tolerance: (if TOF = 1) * (1.00 - 0.3 = 0.7) = 0.7 is the min tolerance. - var min = this.messurements.Min(x => x.TOF) * (1.00 - tolerance); - // Calculating max tolerance: (if TOF = 1) * (1.00 + 0.3 = 1.3) = 1.3 is the max tolerance. - var max = this.messurements.Max(x => x.TOF) * (1.00 + tolerance); - - // Determinates wheter current TOF is between min and max tolerance - hasValidTOF = currentTOF >= min && currentTOF <= max; - - if (!hasValidTOF) - { - this.Error($"[ERROR] Invalid TOF: {currentTOF}"); - } + var avgT = this.messurements.Average(x => x.T); + var avgTOF = this.messurements.Average(x => x.TOF); + this.TemperatureMesured?.Invoke(avgT, avgTOF, args.SignalTime); } - // When current TOF is between min and max tolerance - if (hasValidTOF) + this.messurements = new List(); + + this.ErrorMessage?.Invoke("\t ... temperature difference is not in the tolerance span!"); + this.WarningMessage?.Invoke("\t ... messurement saved, start looking new temperature change!"); + } + + return; + } + + var currentTOF = this.sourceTOF(); + var minTOF = currentTOF; + var maxTOF = currentTOF; + + if (this.messurements.Any()) + { + var tolerance = Appsettings.MessurementTOFTolerance / 100; + minTOF = this.messurements.Min(x => x.TOF) * (1.00 - tolerance); + maxTOF = this.messurements.Max(x => x.TOF) * (1.00 + tolerance); + } + + if (currentTOF < minTOF || currentTOF > maxTOF) + { + if (this.messurements.Count >= this.messurementsCount / 2) + { + this.StopMessurementWatcher(); + this.StartTemperatureWatcher(); + + if (this.messurements.Any()) { - // New messurement record is created and added to the messurements. - this.messurements.Add(new Messurement - { - T = referenceT, - TOF = currentTOF, - DTS = args.SignalTime - }); + var avgT = this.messurements.Average(x => x.T); + var avgTOF = this.messurements.Average(x => x.TOF); + this.TemperatureMesured?.Invoke(avgT, avgTOF, args.SignalTime); } - } - // Else the absolute difference was greater than expected. - else if (differenceT >= Appsettings.TemperatureCheckInC) - { - // Sets the messurements to the calculated count. - // This should breack current method execution in the next step. - this.messurmentN = this.messurementsCount; - this.Warning($"[WARNING] {referenceT:0.00}°C overstepped the tolerance of +/-{Appsettings.TemperatureCheckInC:0.00}."); - } - else - { - this.temperatureErrors++; + this.messurements = new List(); - this.Warning($"[WARNING] {referenceT:0.00}°C overstepped the tolerance of +/-{Appsettings.MessurementToleranceInC:0.00}."); - this.Warning($"[WARNING] Next time current messurment will be canceled."); + this.ErrorMessage?.Invoke("\t ... TOF is not in a tolerance span!"); + this.WarningMessage?.Invoke("\t ... messurement saved, start looking new temperature change!"); } - // In each case counts 1 more. - this.messurmentN++; + return; } else { - this.Warning($"[WARNING] Reading reference temperature failed."); + this.messurements.Add(new Messurement + { + T = currentT, + TOF = currentTOF, + DTS = args.SignalTime + }); + + this.InfoMessage?.Invoke($"\t{this.messurementsN,4}\t{args.SignalTime,8:hh:mm:ss}\t{currentTOF,17:F15}\t {currentT,5:F2}"); } - // If the messurements count is reached. - if (this.messurmentN > this.messurementsCount || this.temperatureErrors > 2) + if (this.messurementsN >= this.messurementsCount) { - // Calculates the time difference between first and last messurement times. - var timespan = this.messurements.LastOrDefault().DTS - this.messurements.FirstOrDefault().DTS; - - // If there are enough messurements, more than the half of the Appsettings.MessurementDauerInMs. - if (timespan.TotalMilliseconds > Appsettings.MessurementDauerInMs / 2) - { - // Average temperature is calculated. - var tmp = this.messurements.Average(x => x.T); - // Average times od flights is calculated. - var tof = this.messurements.Average(x => x.TOF); - - this.Info($"[INFO] Data collected over {timespan}, sending average values ..."); - - // Notifies whit the average values and a timestamp that the messurement is completed. - this.TemperatureMesured?.Invoke(tmp, tof, args.SignalTime); - // All existing messurements are cleared. - this.messurements.Clear(); - - this.Info($"[SENT] {tmp, 5} {tof, 19} {args.SignalTime}"); - } - else - { - this.Error($"[ERROR] {timespan.Milliseconds}ms <= {Appsettings.MessurementDauerInMs / 2}"); - } - - this.messurmentN = 1; - - // In each case, when the messuremens count is reached current method execution should be stopped. this.StopMessurementWatcher(); - // Next call starts seeking for new temperature change. this.StartTemperatureWatcher(); - this.Info($"[INFO] Messurement is done."); - this.Info(string.Empty); + if (this.messurements.Any()) + { + var avgT = this.messurements.Average(x => x.T); + var avgTOF = this.messurements.Average(x => x.TOF); + this.TemperatureMesured?.Invoke(avgT, avgTOF, args.SignalTime); + } + + this.messurements = new List(); + + return; } } - private bool TryGetReferenceT(out double referenceT) + private void StartTemperatureWatcher() { - referenceT = 0; + this.temperatureChecks = 0; + this.temperatureWatcher.AutoReset = true; + this.temperatureWatcher.Enabled = true; + this.temperatureWatcher.Start(); - var succeeded = false; - var readAttempts = 1; - var value = string.Empty; + this.InfoMessage?.Invoke("\t\t\t\t "); + this.InfoMessage?.Invoke("\t Nr\tPrevious\tCurrent\tDifference - temperature changes in °C."); + } - try - { - do - { - lock (this.streamReader) - { - value = this.streamReader.ReadLine(); - } + private void StopTemperatureWatcher() + { + this.temperatureChecks = 0; + this.temperatureWatcher.Stop(); + this.temperatureWatcher.Enabled = false; + this.temperatureWatcher.AutoReset = false; - if (double.TryParse(value, NumberStyles.Any, new CultureInfo("de"), out referenceT) - || double.TryParse(value, NumberStyles.Any, new CultureInfo("us"), out referenceT)) - { - succeeded = true; + this.InfoMessage?.Invoke("\t\t\t\t "); + } - break; - } + private void StartMessurementWatcher() + { + this.messurementsN = 0; + this.messurementWatcher.AutoReset = true; + this.messurementWatcher.Enabled = true; + this.messurementWatcher.Start(); - System.Threading.Thread.Sleep(10); + this.InfoMessage?.Invoke("\t\t\t\t "); + this.InfoMessage?.Invoke("\t Nr\tTimestamp\t TOF\tTemperature\t"); + } - } while (readAttempts++ <= 1000); - } - catch (Exception e) - { - this.Error(e.Message); - } - - return succeeded; + private void StopMessurementWatcher() + { + this.messurementsN = 0; + this.messurementWatcher.Stop(); + this.messurementWatcher.Enabled = false; + this.messurementWatcher.AutoReset = false; } } -} + + class TestValues + { + private readonly Random random; + + public TestValues() + { + this.random = new Random(); + this.Temperature = new Queue(); + + for (int c = 15; c < 25; c++) + { + var countInvalidT = 2; + + for (int i = 0; i < countInvalidT; i++) + { + var t = random.Next(c - 2, c) / 0.99; + + this.Temperature.Enqueue(t); + } + + var countSameT = Appsettings.TemperatureChecksCount + Appsettings.MessurementDauerInMs / Appsettings.MessurementStep + 3; + + for (int i = 0; i < countSameT; i++) + { + var p = 1 - random.Next(96, 99) / 100; + var t = c * p; + + this.Temperature.Enqueue(t); + } + } + } + + public Queue Temperature { get; } + + public double GetTOF(double temperature) + { + var tmp = this.random.Next(1, 5); + var retrn = temperature / 9000 - Math.Pow(temperature, 1.6) / 100_000; + + return retrn - (retrn * tmp / 100 + Math.Pow(tmp, 1.6) / 100_000); + } + } +} \ No newline at end of file diff --git a/Common/Ui/GenesisToolBox/packages.config b/Common/Ui/GenesisToolBox/packages.config index 2521e3a4..a1e8efea 100644 --- a/Common/Ui/GenesisToolBox/packages.config +++ b/Common/Ui/GenesisToolBox/packages.config @@ -1,5 +1,6 @@  + diff --git a/nuget.config b/nuget.config index 02f7f25c..a9759313 100644 --- a/nuget.config +++ b/nuget.config @@ -4,6 +4,7 @@ +