automatic calibration changes, released!

This commit is contained in:
Stoyan Zlatev
2023-09-07 15:00:06 +02:00
parent c883146878
commit d93b3aba32
3 changed files with 130 additions and 249 deletions
+31 -37
View File
@@ -7,6 +7,7 @@
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Globalization;
using System.IO;
@@ -645,8 +646,8 @@
this.btnAddLut.Enabled = false;
this.nudRef.Visible = false;
this.btnRefreshLut.Enabled = false;
this.startAutomaticBtn.Enabled = false;
this.stopAutomaticBtn.Enabled = false;
//this.startAutomaticBtn.Enabled = false;
//this.stopAutomaticBtn.Enabled = false;
break;
case ProgrammState.Connected:
this.btnStartRecord.Enabled = true;
@@ -654,8 +655,8 @@
this.btnAddLut.Enabled = false;
this.nudRef.Visible = false;
this.btnRefreshLut.Enabled = true;
this.startAutomaticBtn.Enabled = true;
this.stopAutomaticBtn.Enabled = false;
//this.startAutomaticBtn.Enabled = true;
//this.stopAutomaticBtn.Enabled = false;
break;
case ProgrammState.RecordRuning:
this.btnStartRecord.Enabled = false;
@@ -663,8 +664,8 @@
this.btnAddLut.Enabled = false;
this.nudRef.Visible = false;
this.btnRefreshLut.Enabled = true;
this.startAutomaticBtn.Enabled = false;
this.stopAutomaticBtn.Enabled = true;
//this.startAutomaticBtn.Enabled = false;
//this.stopAutomaticBtn.Enabled = true;
break;
case ProgrammState.RecordStoped:
this.btnStartRecord.Enabled = true;
@@ -672,12 +673,15 @@
this.btnAddLut.Enabled = true;
this.nudRef.Visible = true;
this.btnRefreshLut.Enabled = true;
this.startAutomaticBtn.Enabled = true;
this.stopAutomaticBtn.Enabled = false;
//this.startAutomaticBtn.Enabled = true;
//this.stopAutomaticBtn.Enabled = false;
break;
default:
break;
}
this.startAutomaticBtn.Enabled = true;
this.stopAutomaticBtn.Enabled = false;
}
private void AddTextBoxBindings(Object sender, EventArgs e)
@@ -709,7 +713,6 @@
private bool automatic = false;
private string messurementsFile;
private AutomaticTemperatureCalibration automaticCalibration;
private CultureInfo previousCulture;
private void StartAutomaticBtn_Clicked(object sender, EventArgs args)
{
@@ -718,15 +721,9 @@
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.messurementsFile = $"messurements.txt";
this.currentGenesis.StartRecordData();
this.currentGenesis.WriteRegister(Register.Genesisflow.SampleRate, (byte)16, checkRegister: true);
@@ -739,27 +736,18 @@
this.automaticCalibration.InfoMessage += message => this.AddMessage(message, Color.Black);
this.automaticCalibration.ErrorMessage += message => this.AddMessage(message, Color.Red);
this.automaticCalibration.WarningMessage += message => this.AddMessage(message, Color.Orange);
this.automaticCalibration.Start += () =>
{
this.startAutomaticBtn.Enabled = false;
this.stopAutomaticBtn.Enabled = true;
};
this.automaticCalibration.Stop += () =>
{
this.startAutomaticBtn.Enabled = true;
this.stopAutomaticBtn.Enabled = false;
};
this.AddMessage("Automatic temperature calibration started.", Color.Black);
this.automaticCalibration.StartMessuring();
this.SetEnabled(ProgrammState.RecordRuning);
this.startAutomaticBtn.Enabled = false;
this.stopAutomaticBtn.Enabled = true;
}
private void StopAutomaticBtn_Clicked(object sender, EventArgs args)
{
//Thread.CurrentThread.CurrentCulture = this.previousCulture;
//Thread.CurrentThread.CurrentUICulture = this.previousCulture;
//this.previousCulture = default(CultureInfo);
this.automatic = false;
this.automaticCalibration.TemperatureMesured -= this.SaveMessurement;
this.automaticCalibration.InfoMessage -= message => this.AddMessage(message, Color.Black);
@@ -768,8 +756,16 @@
this.MergeToAutoFile();
this.automaticCalibration.StopMessuring();
this.currentGenesis?.WriteRegister<Byte>(Register.Genesisflow.SampleRate, 0, checkRegister: true);
this.currentGenesis.WriteRegister(Register.Genesisflow.SampleRate, (byte)0, 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.SetEnabled(ProgrammState.RecordStoped);
this.startAutomaticBtn.Enabled = true;
this.stopAutomaticBtn.Enabled = false;
this.AddMessage("Automatic temperature calibration stoped.", Color.Black);
}
private void UpdateAutomaticBtn_Clicked(object sender, EventArgs args)
@@ -804,15 +800,13 @@
private void SaveMessurement(double meterTOF, double temperature, DateTime timestamp)
{
var pcbid = this.currentGenesis?.PcbId ?? "200000000";
var tmp = temperature.ToString("en-US");
var tof = meterTOF.ToString("en-US");
var pcbid = this.currentGenesis?.PcbId ?? "000000000";
File.AppendAllLines(this.messurementsFile, new[] { $"{pcbid}\t{tmp}\t{tof}\t{timestamp}" });
File.AppendAllLines(this.messurementsFile, new[] { $"{pcbid}\t{temperature}\t{meterTOF}\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.
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}");
File.AppendAllLines("temp_luts.txt", new[] { $"{pcbid}\t{temperature}\t{meterTOF}\t{timestamp}" });
// LocalWebRequest.PostRequestAsync($"http://10.49.40.25/MeterProcessState/api/TempFlange/AddLut?PcbId={pcbid}&RefTempC={temperature}&AvgTof={meterTOF}&dt={timestamp}");
}
}
}
@@ -10,6 +10,6 @@
<ErrorReportUrlHistory />
<FallbackCulture>de-DE</FallbackCulture>
<VerifyUploadedFiles>false</VerifyUploadedFiles>
<ProjectView>ProjectFiles</ProjectView>
<ProjectView>ShowAllFiles</ProjectView>
</PropertyGroup>
</Project>
@@ -70,24 +70,7 @@
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
@@ -131,7 +114,7 @@
return false;
}
#endif
public void Dispose()
{
this.pipeReader?.Dispose();
@@ -141,37 +124,27 @@
partial class AutomaticTemperatureCalibration
{
private readonly int messurementsCount;
private readonly Timer timer;
private readonly Func<double> sourceTOF;
private readonly Timer temperatureWatcher;
private readonly Timer messurementWatcher;
private readonly TemperatureSource temperature;
private ICollection<Messurement> messurements;
private ICollection<double> timesOfFliights;
private ICollection<double> temperatures;
private int temperatureChecks;
private int messurementsCount;
private int messurementsN;
private double previousT;
private bool waiting;
public AutomaticTemperatureCalibration(Func<double> sourceTOF)
{
#if false
this.sourceTOF = () => this.temperature.GetTOF(this.previousT);
#else
this.sourceTOF = sourceTOF;
#endif
this.temperature = new TemperatureSource();
this.messurements = new List<Messurement>();
this.messurementsCount = Appsettings.MessurementDauerInMs / Appsettings.MessurementStep;
this.temperatureWatcher = new Timer(Math.Max(Appsettings.TemperatureCheckInMs, 1000));
this.temperatureWatcher.Elapsed += this.CheckTemperature;
this.messurementWatcher = new Timer(Math.Max(Appsettings.MessurementStep, 1000));
this.messurementWatcher.Elapsed += this.Messure;
this.timesOfFliights = new List<double>();
this.temperatures = new List<double>();
this.timer = new Timer();
}
public event Action Start;
public event Action Stop;
public event Action<string> InfoMessage;
public event Action<string> ErrorMessage;
public event Action<string> WarningMessage;
@@ -179,63 +152,68 @@
public void StartMessuring()
{
Appsettings.Refresh();
this.timer.Stop();
if (this.sourceTOF is null)
{
this.StopTemperatureWatcher();
this.StopMessurementWatcher();
this.Stop?.Invoke();
}
else
{
this.StopMessurementWatcher();
this.StartTemperatureWatcher();
this.Start?.Invoke();
}
Appsettings.Refresh();
this.waiting = true;
this.temperatureChecks = 0;
this.timer.Interval = Appsettings.TemperatureCheckInMs;
this.timer.Elapsed += this.CheckTemperature;
this.timer.Elapsed -= this.Messure;
this.timer.AutoReset = true;
this.timer.Enabled = true;
this.timer.Start();
this.InfoMessage?.Invoke(string.Empty);
this.InfoMessage?.Invoke($"\t Nr\tPrevious\tCurrent\tDifference");
}
public void StopMessuring()
{
if (this.sourceTOF != null)
{
this.temperature.Dispose();
}
this.StopMessurementWatcher();
this.StopTemperatureWatcher();
this.Stop?.Invoke();
this.previousT = 0;
this.timer?.Stop();
this.timer?.Dispose();
this.temperature?.Dispose();
}
private void CheckTemperature(object sender, ElapsedEventArgs args)
{
this.temperatureChecks++;
if (this.temperature.TryGetTemperature(out var currentT))
{
var differenceT = Math.Abs(this.previousT - currentT);
if (differenceT <= Appsettings.MessurementToleranceInC)
if (this.waiting && differenceT >= Appsettings.TemperatureCheckInC)
{
if (this.temperatureChecks > Appsettings.TemperatureChecksCount)
{
this.previousT = currentT;
this.temperatureChecks = 0;
this.StopTemperatureWatcher();
this.StartMessurementWatcher();
return;
}
this.waiting = false;
this.previousT = currentT;
}
else
{
this.temperatureChecks = 1;
if (this.previousT != 0)
if (!this.waiting && differenceT <= Appsettings.TemperatureCheckInC)
{
if (this.temperatureChecks >= Appsettings.TemperatureChecksCount)
{
this.WarningMessage?.Invoke("\t... temperature difference is not in the tolerance span, restarting counter!");
this.timer.Stop();
this.waiting = true;
this.messurementsN = 0;
this.messurementsCount = Appsettings.MessurementDauerInMs / Appsettings.MessurementStep;
this.timer.Interval = Appsettings.MessurementStep;
this.timer.Elapsed -= this.CheckTemperature;
this.timer.Elapsed += this.Messure;
this.timer.AutoReset = true;
this.timer.Enabled = true;
this.timer.Start();
this.InfoMessage?.Invoke(string.Empty);
this.InfoMessage?.Invoke($"\t Nr\tTimestamp\t TOF\tTemperature");
}
this.temperatureChecks++;
}
this.InfoMessage?.Invoke($"\t{this.temperatureChecks,3}\t{this.previousT,8:F2}\t{currentT,7:F2}\t{differenceT,10:F2}");
@@ -244,18 +222,17 @@
{
this.temperatureChecks = 0;
this.InfoMessage?.Invoke($"\t{this.temperatureChecks,3}\t{this.previousT,8:F2}\t.......\t..........");
this.InfoMessage?.Invoke($"\t 1\t{this.previousT,8:F2}\t.......\t..........");
}
this.previousT = currentT;
}
private void Messure(object sender, ElapsedEventArgs args)
{
this.messurementsN++;
if (!this.temperature.TryGetTemperature(out var currentT))
{
this.WarningMessage?.Invoke("\t ... temperature could not be read.");
this.StartMessuring();
return;
}
@@ -263,171 +240,81 @@
if (differenceT > Appsettings.MessurementToleranceInC)
{
if (this.messurements.Count >= this.messurementsCount / 2)
if (this.messurementsN >= this.messurementsCount / 2)
{
this.StopMessurementWatcher();
this.StartTemperatureWatcher();
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<Messurement>();
this.ErrorMessage?.Invoke("\t ... temperature difference is not in the tolerance span!");
this.WarningMessage?.Invoke("\t ... messurement saved, start looking new temperature change!");
this.NotifyTemperatureMessured(args.SignalTime);
this.InfoMessage?.Invoke("\t ... messurement saved, start looking new temperature change!");
}
else
{
this.ErrorMessage?.Invoke("\t ... not enough messurements!");
}
this.ErrorMessage?.Invoke($"\t ... temperature difference '{differenceT:F2}' is not in the tolerance span!");
this.StartMessuring();
return;
}
var currentTOF = this.sourceTOF();
var currentTOF = this.sourceTOF?.Invoke() ?? 0;
var minTOF = currentTOF;
var maxTOF = currentTOF;
if (this.messurements.Any())
if (this.timesOfFliights.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);
minTOF = this.timesOfFliights.Min() * (1.00 - tolerance);
maxTOF = this.timesOfFliights.Max() * (1.00 + tolerance);
}
if (currentTOF < minTOF || currentTOF > maxTOF)
{
if (this.messurements.Count >= this.messurementsCount / 2)
if (this.messurementsN >= this.messurementsCount / 2)
{
this.StopMessurementWatcher();
this.StartTemperatureWatcher();
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<Messurement>();
this.ErrorMessage?.Invoke("\t ... TOF is not in a tolerance span!");
this.NotifyTemperatureMessured(args.SignalTime);
this.WarningMessage?.Invoke("\t ... messurement saved, start looking new temperature change!");
}
else
{
this.ErrorMessage?.Invoke("\t ... not enough messurements!");
}
this.ErrorMessage?.Invoke($"\t ... TOF is not in a tolerance span - {minTOF} <= {currentTOF} <= {maxTOF}!");
this.StartMessuring();
return;
}
else
{
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}");
}
this.temperatures.Add(currentT);
this.timesOfFliights.Add(currentTOF);
this.InfoMessage?.Invoke($"\t{this.messurementsN,4}\t {args.SignalTime,8:hh:mm:ss}\t{currentTOF,17:F15}\t {currentT,5:F2}");
if (this.messurementsN >= this.messurementsCount)
{
this.StopMessurementWatcher();
this.StartTemperatureWatcher();
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<Messurement>();
this.NotifyTemperatureMessured(args.SignalTime);
this.InfoMessage?.Invoke("\t ... messurement done!");
this.StartMessuring();
return;
}
this.messurementsN++;
}
private void StartTemperatureWatcher()
private void NotifyTemperatureMessured(DateTime timestamp)
{
this.temperatureChecks = 0;
this.temperatureWatcher.AutoReset = true;
this.temperatureWatcher.Enabled = true;
this.temperatureWatcher.Start();
this.InfoMessage?.Invoke("\t\t\t\t ");
this.InfoMessage?.Invoke("\t Nr\tPrevious\tCurrent\tDifference - temperature changes in °C.");
}
private void StopTemperatureWatcher()
{
this.temperatureChecks = 0;
this.temperatureWatcher.Stop();
this.temperatureWatcher.Enabled = false;
this.temperatureWatcher.AutoReset = false;
this.InfoMessage?.Invoke("\t\t\t\t ");
}
private void StartMessurementWatcher()
{
this.messurementsN = 0;
this.messurementWatcher.AutoReset = true;
this.messurementWatcher.Enabled = true;
this.messurementWatcher.Start();
this.InfoMessage?.Invoke("\t\t\t\t ");
this.InfoMessage?.Invoke("\t Nr\tTimestamp\t TOF\tTemperature\t");
}
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<double>();
for (int c = 15; c < 25; c++)
if (this.timesOfFliights.Any() && this.temperatures.Any())
{
var countInvalidT = 2;
var avgT = this.temperatures.Average();
var avgTOF = this.timesOfFliights.Average();
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);
}
this.TemperatureMesured?.Invoke(avgT, avgTOF, timestamp);
}
}
public Queue<double> 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);
this.messurementsN = 0;
this.temperatures = new List<double>();
this.timesOfFliights = new List<double>();
}
}
}