omni before testing,

- recalculating correction factors and accuracies
- factory unseal
This commit is contained in:
Stoyan Zlatev
2024-02-05 14:48:35 +01:00
parent 89a9f1649d
commit 02943ebcbc
34 changed files with 1384 additions and 511 deletions
+1 -1
View File
@@ -13,7 +13,7 @@
{
ServiceProvider
.ServiceCollection
.AddSingleton(OmniContext.GetOrCreateInstance(Appsettings.OmniDB, Appsettings.OutputDirectory));
.AddSingleton(new OmniContext(Appsettings.OmniDB, Appsettings.OutputDirectory));
}
internal static event Action Exiting;
+14 -15
View File
@@ -23,6 +23,8 @@
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto" />
@@ -70,32 +72,29 @@
<ComboBoxItem Content="R2" Padding="10, 5" />
<ComboBoxItem Content="T2" Padding="10, 5" />
</ComboBox>
<Button Command="{Binding CheckInspection}"
Content="Überprüfen"
Cursor="Hand"
FontFamily="Consolas"
Grid.Column="5"
IsEnabled="{Binding IsCheckInspectionEnabled}"
Margin="5"
Padding="10, 5"
Visibility="Collapsed"/>
<CheckBox Content="Korakturfaktor beibehalten?"
FontFamily="Consolas"
Grid.Column="4"
IsChecked="{Binding KeepCorrection}"
Margin="5, 5, 0, 5"
Padding="5, 0"
VerticalAlignment="Center"/>
<Button Command="{Binding StartInspection}"
Content="Start"
Content="Prüfung starten"
Cursor="Hand"
FontFamily="Consolas"
Grid.Column="6"
Grid.Column="7"
IsEnabled="{Binding IsStartInspectionEnabled}"
Margin="5"
Padding="10, 5"/>
<Button Command="{Binding CancelInspection}"
Content="Abbruch"
Content="Abbrechen"
Cursor="Hand"
FontFamily="Consolas"
Grid.Column="7"
Grid.Column="8"
IsEnabled="{Binding IsCancelInspectionEnabled}"
Margin="5"
Padding="10, 5"
Visibility="Collapsed"/>
Padding="10, 5" />
</Grid>
</Border>
@@ -23,12 +23,14 @@
{
if (!dequeuing)
{
dequeuing = true;
while (statesQueue.TryDequeue(out var state))
{
File.AppendAllText(app_state, $"[{DateTime.Now}] {state}{NewLine}");
}
dequeuing = true;
dequeuing = false;
}
}
}
@@ -3,7 +3,7 @@
using System;
using System.Collections.Concurrent;
using System.Linq;
public interface IServiceCollection
{
IServiceCollection AddSingleton<T>(T instance);
@@ -9,6 +9,7 @@
this.Add(new ItemsGridHeaderVM());
this.Add(new ItemsGridHeaderVM());
this.Add(new ItemsGridHeaderVM());
this.Add(new ItemsGridHeaderVM());
var auftrag = OmniContext.Current.Auftrag;
@@ -7,8 +7,9 @@
public DefaultsRowVM()
{
this.Add(new ItemsGridHeaderVM());
this.Add(new ItemsGridHeaderVM { Value = "PP:" });
this.Add(new ItemsGridHeaderVM());
this.Add(new ItemsGridHeaderVM());
this.Add(new ItemsGridHeaderVM { Value = "0.0" });
var auftrag = OmniContext.Current.Auftrag;
@@ -19,7 +20,7 @@
this.Add(new ItemsGridHeaderVM { Value = $"{pp.MinAccuracy}-{pp.MaxAccuracy}" });
}
this.Add(new ItemsGridHeaderVM { Value = "3.3" });
this.Add(new ItemsGridHeaderVM { Value = "0.0" });
}
}
}
@@ -9,6 +9,7 @@
this.Add(new ItemsGridHeaderVM { Width = ItemsGridHeaderVM.Auto });
this.Add(new ItemsGridHeaderVM { Value = "MeterNr", Width = ItemsGridHeaderVM.Star });
this.Add(new ItemsGridHeaderVM { Value = "SerialNr", Width = ItemsGridHeaderVM.Star });
this.Add(new ItemsGridHeaderVM { Value = "Crr.F. %", Width = ItemsGridHeaderVM.Auto });
var auftrag = OmniContext.Current.Auftrag;
@@ -22,7 +23,7 @@
});
}
this.Add(new ItemsGridHeaderVM { Value = "Crr. %", Width = ItemsGridHeaderVM.Star });
this.Add(new ItemsGridHeaderVM { Value = "Crr.F. %", Width = ItemsGridHeaderVM.Star });
}
}
}
@@ -10,8 +10,6 @@
protected ItemsGridVM() : base()
{
this.rows = new List<ItemsGridRowVM>();
this.InitializeItemsGridRows();
}
public IEnumerator<ItemsGridRowVM> GetEnumerator()
@@ -48,7 +46,5 @@
{
this.rows.Insert(index, item);
}
protected abstract void InitializeItemsGridRows();
}
}
@@ -2,8 +2,6 @@
{
using InspectionUI.Models;
using OmniPlus;
using System;
using System.Windows.Input;
@@ -13,7 +11,6 @@
{
this.IsReloadEnabled = true;
this.Reload = new Command(this.ReloadCommand);
this.CheckInspection = new Command(this.CheckInspectionCommand);
this.StartInspection = new Command(this.StartInspectionCommand);
this.CancelInspection = new Command(this.CancelInspectionCommand);
}
@@ -39,6 +36,13 @@
set => this.Set(() => this.suchnr = value);
}
private bool keepCorrection;
public bool KeepCorrection
{
get => this.keepCorrection;
set => this.Set(() => this.keepCorrection = value);
}
private bool reloadEnabled;
public bool IsReloadEnabled
{
@@ -48,22 +52,12 @@
public ICommand Reload { get; }
private bool checkInspectionEnabled;
public bool IsCheckInspectionEnabled
{
get => this.checkInspectionEnabled;
private set => this.Set(() => this.checkInspectionEnabled = value);
}
public ICommand CheckInspection { get; }
private bool startInspectionEnabled;
public bool IsStartInspectionEnabled
{
get => this.startInspectionEnabled;
private set => this.Set(() => this.startInspectionEnabled = value);
}
public ICommand StartInspection { get; }
private bool cancelInspectionEnabled;
@@ -94,20 +88,15 @@
this.EnableButtons(false);
this.Errors = default(string);
var omniContext = ServiceProvider.GetService<OmniContext>();
this.MetersPool = ServiceProvider.GetService<MetersPoolVM>();
if (!string.IsNullOrWhiteSpace(this.SuchNr))
{
ServiceProvider
.GetService<OmniContext>()
.LoadAuftrag(this.SuchNr);
this.MetersPool.LoadAuftrag(this.SuchNr);
}
else if (this.size >= 0 && !string.IsNullOrWhiteSpace(this.type))
{
ServiceProvider
.GetService<OmniContext>()
.LoadAuftrag((byte)this.size, this.type);
this.MetersPool.LoadAuftrag((byte)this.size, this.type);
}
else
{
@@ -119,7 +108,6 @@
this.StartNewTask(() =>
{
this.Errors = "Connecting meters ...";
this.MetersPool = ServiceProvider.GetService<MetersPoolVM>();
this.MetersPool.LoadMeters();
})
.ContinueWith(_ =>
@@ -134,22 +122,13 @@
}
}
private void CheckInspectionCommand()
{
this.StartNewTask(() =>
{
this.EnableButtons(false);
this.MetersPool.RunCheckInspection();
this.EnableButtons(true);
});
}
private void StartInspectionCommand()
{
this.StartNewTask(() =>
{
this.EnableButtons(false);
this.MetersPool.RunInspection();
this.MetersPool.RunInspection(this.KeepCorrection);
this.IsCancelInspectionEnabled = false;
this.IsReloadEnabled = true;
});
}
@@ -160,14 +139,14 @@
{
this.EnableButtons(false);
this.MetersPool.CancelInspection();
this.EnableButtons(true);
this.IsCancelInspectionEnabled = false;
this.IsReloadEnabled = true;
});
}
private void EnableButtons(bool enabled)
{
this.IsReloadEnabled = enabled;
this.IsCheckInspectionEnabled = enabled;
this.IsStartInspectionEnabled = enabled;
this.IsCancelInspectionEnabled = !enabled;
}
@@ -1,6 +1,5 @@
namespace InspectionUI.ViewModels
{
using InspectionUI.Models;
using OmniPlus;
using System;
@@ -22,6 +21,7 @@
this.Add(new ItemsGridHeaderVM { Value = $"{this.meter.SlotNr, 2}." });
this.Add(new ItemsGridCellVM());
this.Add(new ItemsGridCellVM());
this.Add(new ItemsGridCellVM());
var auftrag = OmniContext.Current.Auftrag;
@@ -66,31 +66,31 @@
base.Dispose();
}
public Task SaveMeterStateAsync()
public Task SaveMeterStateAsync(CancellationToken cancellationToken)
{
return this.StartNewTask(this.meter.SaveMeterState);
return this.StartNewTask(this.meter.SaveMeterState, cancellationToken);
}
public Task LoadTestRunAsync()
public Task LoadTestRunAsync(CancellationToken cancellationToken)
{
return this.StartNewTask(this.meter.LoadTestRun);
return this.StartNewTask(this.meter.LoadTestRun, cancellationToken);
}
public Task InitializeInspectionAsync(bool preserveState = false)
public Task InitializeInspectionAsync(bool keepCorrection, CancellationToken cancellationToken)
{
this.uinr = 0;
void InitializeInspection()
{
this.meter.InitializeForInspection(preserveState);
this.meter.InitializeForInspection(keepCorrection);
this.Set(this.meter.TestRun.CrrfBefore, "{0:0.0}", this.LastIndex);
this.Set(this.meter.TestRun.CrrfBefore, "{0:0.0}", 3);
}
return this.StartNewTask(InitializeInspection);
return this.StartNewTask(InitializeInspection, cancellationToken);
}
public Task StartCalibrationAsync(OmniPruefpunkt pp)
public Task StartCalibrationAsync(OmniPruefpunkt pp, CancellationToken cancellationToken)
{
this.uinr++;
@@ -98,28 +98,28 @@
{
this.meter.StartCalibration((ushort)pp.Rotations, (ushort)pp.Duration);
this.ShowRestTime(pp.Duration, this.uinr * 3);
this.ShowRestTime(pp.Duration, this.uinr * 3 + 1);
}
return this.StartNewTask(StartCalibration);
return this.StartNewTask(StartCalibration, cancellationToken);
}
public Task StopCalibrationAsync(OmniPruefpunkt pp, double refm3s)
public Task StopCalibrationAsync(OmniPruefpunkt pp, double refm3s, CancellationToken cancellationToken)
{
void StopCalibration()
{
var response = this.meter.StopCalibration(pp, refm3s);
var index = this.uinr * 3;
var index = this.uinr * 3 + 1;
this.Set(response.Item2, "{0}", index);
this.Set(response.Item1, "{0:0.0000000000}", index + 1);
this.Set(response.Item3, "{0:0.00}", index + 2);
}
return this.StartNewTask(StopCalibration);
return this.StartNewTask(StopCalibration, cancellationToken);
}
public Task FinishInspectionAsync()
public Task FinishInspectionAsync(CancellationToken cancellationToken)
{
void FinishInspection()
{
@@ -138,7 +138,7 @@
foreach (var testedPP in this.meter.TestRun.TestedPoints)
{
var index = this.uinr * 3 + 2;
var index = this.uinr * 3 + 1 + 2;
this.Set(testedPP.Acc, "{0:0.00}", index);
this.Set(x =>
@@ -153,7 +153,7 @@
}
}
return this.StartNewTask(FinishInspection);
return this.StartNewTask(FinishInspection, cancellationToken);
}
private void ShowRestTime(int duration, int index)
@@ -3,15 +3,17 @@
using InspectionUI.Models;
using OmniPlus;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
public class MetersPoolVM : ItemsGridVM
{
private readonly OmniContext omniContext;
private CancellationTokenSource cancellationTokenSource;
private ReferenceMeterVM referenceMeter;
public MetersPoolVM(OmniContext omniContext) : base()
@@ -21,7 +23,8 @@
public void CancelInspection()
{
this.referenceMeter.Stop();
this.cancellationTokenSource?.Cancel();
this.referenceMeter?.Stop();
}
public override void Dispose()
@@ -49,13 +52,11 @@
});
}
public void RunCheckInspection()
public void RunInspection(bool keepCorrection = false, bool addCorrection = false)
{
this.cancellationTokenSource = new CancellationTokenSource();
}
public void RunInspection()
{
var cancellationToken = this.cancellationTokenSource.Token;
var tasks = new List<Task>();
var meters = this
.Select(x => x is MeterVM m ? m : null)
@@ -64,21 +65,21 @@
foreach (var meterVM in meters)
{
tasks.Add(meterVM.LoadTestRunAsync());
tasks.Add(meterVM.LoadTestRunAsync(cancellationToken));
}
this.ContinueWhenAll(tasks);
foreach (var meterVM in meters)
{
tasks.Add(meterVM.SaveMeterStateAsync());
tasks.Add(meterVM.SaveMeterStateAsync(cancellationToken));
}
this.ContinueWhenAll(tasks);
foreach (var meterVM in meters)
{
tasks.Add(meterVM.InitializeInspectionAsync());
tasks.Add(meterVM.InitializeInspectionAsync(keepCorrection, cancellationToken));
}
this.ContinueWhenAll(tasks);
@@ -90,36 +91,75 @@
foreach (var pp in pruefpunkte)
{
if (cancellationToken.IsCancellationRequested)
{
break;
}
this.referenceMeter.Start(pp);
if (cancellationToken.IsCancellationRequested)
{
break;
}
foreach (var meterVM in meters)
{
tasks.Add(meterVM.StartCalibrationAsync(pp));
tasks.Add(meterVM.StartCalibrationAsync(pp, cancellationToken));
}
this.ContinueWhenAll(tasks);
if (cancellationToken.IsCancellationRequested)
{
break;
}
var refm3s = this.referenceMeter.GetFlow();
if (cancellationToken.IsCancellationRequested)
{
break;
}
foreach (var meterVM in meters)
{
tasks.Add(meterVM.StopCalibrationAsync(pp, refm3s));
tasks.Add(meterVM.StopCalibrationAsync(pp, refm3s, cancellationToken));
}
this.ContinueWhenAll(tasks);
if (cancellationToken.IsCancellationRequested)
{
break;
}
}
this.referenceMeter.Stop();
foreach (var meterVM in meters)
{
tasks.Add(meterVM.FinishInspectionAsync());
tasks.Add(meterVM.FinishInspectionAsync(cancellationToken));
}
this.ContinueWhenAll(tasks);
}
protected override void InitializeItemsGridRows()
internal void LoadAuftrag(byte size, string type)
{
this.omniContext.LoadAuftrag(size, type);
this.UpdateItemsGridHeaders();
}
internal void LoadAuftrag(string suchNr)
{
this.omniContext.LoadAuftrag(suchNr);
this.UpdateItemsGridHeaders();
}
private void UpdateItemsGridHeaders()
{
this.DispatcherInvoke(() =>
{
@@ -5,46 +5,34 @@
using InspectionUI.Models;
using OmniPlus;
using OmniPlus.Inspection;
using System;
using System.IO;
using System.Threading;
using System.Timers;
public class ReferenceMeterVM : ItemsGridRowVM
{
private readonly OmniContext omniContext;
private readonly ExchangeConnection signarR;
private readonly string outputFile;
private int ppnr = 0;
private int ppnr;
private bool cancel;
public ReferenceMeterVM() : base()
public ReferenceMeterVM(OmniContext omniContext, ExchangeConnection signarR) : base()
{
this.Add(new ItemsGridHeaderVM());
this.Add(new ItemsGridHeaderVM { Value = "RZ:" });
this.Add(new ItemsGridHeaderVM());
var auftrag = OmniContext.Current.Auftrag;
foreach (var _ in auftrag.Pruefpunkte)
{
this.Add(new ItemsGridHeaderVM());
this.Add(new ItemsGridHeaderVM());
this.Add(new ItemsGridHeaderVM());
}
this.Add(new ItemsGridHeaderVM());
this.signarR = new ExchangeConnection();
this.omniContext = omniContext;
this.signarR = signarR;
this.signarR.StateChanged += this.SignarR_StateChanged;
this.outputFile = Path.Combine(Appsettings.OutputDirectory, "signalr.txt");
this.signarR.Connect(Appsettings.HubURL);
this.ppnr = 1;
this.LoadHeaders();
}
internal void Start(OmniPruefpunkt pp)
{
this.ppnr += 3;
this.cancel = false;
this.StartFlow(pp);
this.StartRZ(pp);
@@ -53,7 +41,7 @@
private void StartFlow(OmniPruefpunkt pp)
{
var interval = 1000;
var timeout = 5;// 00;
var timeout = 500;
var volume = default(double);
var waitHandle = new ManualResetEventSlim();
var timer = new System.Timers.Timer
@@ -73,7 +61,7 @@
void TimerElapsed(object _, ElapsedEventArgs _1)
{
if (timeout < 0)
if (timeout < 0 || cancel)
{
timeout = 0;
@@ -107,7 +95,7 @@
private void StartRZ(OmniPruefpunkt pp)
{
var interval = 1000;
var timeout = 6;// 0;
var timeout = 60;
var seconds = default(double);
var waitHandle = new ManualResetEventSlim();
var timer = new System.Timers.Timer
@@ -127,7 +115,7 @@
void TimerElapsed(object _, ElapsedEventArgs _1)
{
if (timeout < 0)
if (timeout < 0 || cancel)
{
timeout = 0;
@@ -161,7 +149,7 @@
internal double GetFlow()
{
var interval = 1000;
var timeout = 6;// 0;
var timeout = 60;
var referenceV = 0D;
var waitHandle = new ManualResetEventSlim();
var timer = new System.Timers.Timer
@@ -182,7 +170,7 @@
void TimerElapsed(object _, ElapsedEventArgs _1)
{
if (timeout < 0)
if (timeout < 0 || cancel)
{
timeout = 0;
@@ -205,6 +193,8 @@
waitHandle.Wait(timeout * interval);
waitHandle.Reset();
OmniPlusFormulas.OutDebugM3S(ref referenceV);
this.signarR.StopReferenceMessurement -= ReceiveFlow;
timer.Elapsed -= TimerElapsed;
@@ -218,9 +208,9 @@
internal void Stop()
{
this.signarR.SendStopFlow();
this.cancel = true;
this.ppnr = 0;
this.signarR.SendStopFlow();
}
public override void Dispose()
@@ -232,7 +222,7 @@
}
catch (Exception e)
{
File.AppendAllText(this.outputFile, $"[{DateTime.Now}][...] {e}{Environment.NewLine}");
AppLogger.Log($"[...] {e}");
}
base.Dispose();
@@ -240,7 +230,27 @@
private void SignarR_StateChanged(string value, string groupName)
{
File.AppendAllText(this.outputFile, $"[{DateTime.Now}][{groupName}] {value}{Environment.NewLine}");
AppLogger.Log($"[{groupName}] {value}");
}
private void LoadHeaders()
{
this.DispatcherInvoke(() =>
{
this.Add(new ItemsGridHeaderVM());
this.Add(new ItemsGridHeaderVM { Value = "RZ:" });
this.Add(new ItemsGridHeaderVM());
this.Add(new ItemsGridHeaderVM());
foreach (var _ in this.omniContext.Pruefpunkte)
{
this.Add(new ItemsGridHeaderVM());
this.Add(new ItemsGridHeaderVM());
this.Add(new ItemsGridHeaderVM());
}
this.Add(new ItemsGridHeaderVM());
});
}
}
}
@@ -6,6 +6,7 @@
using System.Collections.Generic;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
@@ -84,18 +85,18 @@
this.NotifyPropertyChanged(property);
}
protected Task StartNewTask(Action action)
protected Task StartNewTask(Action action, CancellationToken cancellationToken = default(CancellationToken))
{
return Task
.Factory
.StartNew(action)
.StartNew(action, cancellationToken)
.ContinueWith(task =>
{
if (task.Exception != null)
{
AppLogger.Log(task.Exception);
}
});
}, cancellationToken);
}
protected class Command : ICommand
@@ -14,10 +14,12 @@
public override byte[] Send(params byte[] message)
{
var response = new byte[0];
var received = false;
void DataReceived(byte[] data)
{
response = data;
received = true;
this.waitHandle.Set();
}
@@ -26,17 +28,12 @@
this.StartListening();
for (int i = 0; i < 3; i++)
for (int i = 0; i < 3 && !received; i++)
{
if (response != null && response.Length > 0)
{
break;
}
this.WriteEncoded(message);
this.waitHandle.Wait(3000);
this.waitHandle.Reset();
this.waitHandle.Wait(3000);
}
this.StopListening();
@@ -35,7 +35,7 @@
}
catch (Exception e)
{
this.NotifyStateChanged($"[{DateTime.Now}] --- {e}");
this.NotifyStateChanged($"--- {e}");
}
base.Close();
@@ -51,7 +51,7 @@
}
catch (Exception e)
{
this.NotifyStateChanged($"[{DateTime.Now}] --- {e}");
this.NotifyStateChanged($"--- {e}");
}
}
@@ -64,7 +64,7 @@
}
catch (Exception e)
{
this.NotifyStateChanged($"[{DateTime.Now}] --- {e}");
this.NotifyStateChanged($"--- {e}");
}
}
@@ -77,7 +77,7 @@
}
catch (Exception e)
{
this.NotifyStateChanged($"[{DateTime.Now}] --- {e}");
this.NotifyStateChanged($"--- {e}");
}
}
@@ -87,14 +87,14 @@
{
if (this.encoder.TryEncode(bytes, out byte[] message))
{
var timestamp = this.Write(message, 0, message.Length);
this.Write(message, 0, message.Length);
this.NotifyStateChanged($"[{timestamp}] >>> {BitConverter.ToString(bytes)}");
this.NotifyStateChanged($">>> {BitConverter.ToString(bytes)}");
}
}
catch (Exception e)
{
this.NotifyStateChanged($"[{DateTime.Now}] --- {e}");
this.NotifyStateChanged($"--- {e}");
}
}
@@ -102,11 +102,11 @@
{
try
{
var timestamp = this.Write(bytes, 0, bytes.Length);
this.Write(bytes, 0, bytes.Length);
}
catch (Exception e)
{
this.NotifyStateChanged($"[{DateTime.Now}] --- {e}");
this.NotifyStateChanged($"--- {e}");
}
}
@@ -124,7 +124,7 @@
{
var buffer = new byte[length];
var timestamp = serialDataStream.Read(buffer, 0, length);
serialDataStream.Read(buffer, 0, length);
serialDataStream.buffer.AddRange(buffer);
var data = serialDataStream.buffer.ToArray();
@@ -133,7 +133,7 @@
{
serialDataStream.DataReceived?.Invoke(message);
serialDataStream.NotifyStateChanged($"[{timestamp}] <<< {BitConverter.ToString(message)}");
serialDataStream.NotifyStateChanged($"<<< {BitConverter.ToString(message)}");
}
}
}
@@ -149,7 +149,7 @@
{
if (task.Exception != null)
{
this.NotifyStateChanged($"[{DateTime.Now}] --- {task.Exception}");
this.NotifyStateChanged($"--- {task.Exception}");
}
this.StartReading();
@@ -59,12 +59,12 @@
this.serialPort.Dispose();
this.serialPort = null;
this.NotifyStateChanged($"[{DateTime.Now}] --- Disconnected: {this}");
this.NotifyStateChanged($"--- Disconnected: {this}");
}
}
catch (Exception e)
{
this.NotifyStateChanged($"[{DateTime.Now}] --- {e}");
this.NotifyStateChanged($"--- {e}");
}
}
@@ -84,11 +84,11 @@
this.serialPort.Open();
this.NotifyStateChanged($"[{DateTime.Now}] --- Connected: {this}");
this.NotifyStateChanged($"--- Connected: {this}");
}
catch (Exception e)
{
this.NotifyStateChanged($"[{DateTime.Now}] --- {e}");
this.NotifyStateChanged($"--- {e}");
}
}
@@ -119,14 +119,12 @@
this.StateChanged?.Invoke(state);
}
protected DateTime Read(byte[] bytes, int start, int length)
protected void Read(byte[] bytes, int start, int length)
{
this.serialPort.Read(bytes, start, length);
return DateTime.Now;
}
protected DateTime Write(byte[] bytes, int start, int length)
protected void Write(byte[] bytes, int start, int length)
{
var lock_object = new object();
@@ -134,8 +132,6 @@
{
this.serialPort.Write(bytes, 0, length);
}
return DateTime.Now;
}
}
}
@@ -186,5 +186,13 @@
return crrf;
}
public static void OutDebugM3S(ref double value)
{
//if (true)
//{
// value = new Random().Next(95, 100) / 1005D;
//}
}
}
}
+222 -122
View File
@@ -1,12 +1,10 @@
namespace OmniPlus
{
using OmniPlus.Connections;
using OmniPlus.Features;
using System;
using System.Linq;
using System.Text;
using static OmniPlus.Features.Features;
public delegate byte[] MessageHandler(params byte[] bytes);
@@ -31,63 +29,63 @@
public FactoryID ViewFactoryID()
{
var response = this.MessageHandler.Invoke(VIEW_FACTORY_ID);
var response = this.MessageHandler(VIEW_FACTORY_ID);
return new FactoryID(response);
}
public ProgrammableID ViewProgrammableID()
{
var response = this.MessageHandler.Invoke(VIEW_PROGRAMMABLE_ID);
var response = this.MessageHandler(VIEW_PROGRAMMABLE_ID);
return new ProgrammableID(response);
}
public VersionAndType ViewVersionAndType()
{
var response = this.MessageHandler.Invoke(VIEW_VERSION_AND_TYPE);
var response = this.MessageHandler(VIEW_VERSION_AND_TYPE);
return new VersionAndType(response);
}
public CustomerText ViewCustomerText()
{
var response = this.MessageHandler.Invoke(VIEW_CUSTOMER_TEXT);
var response = this.MessageHandler(VIEW_CUSTOMER_TEXT);
return new CustomerText(response);
}
public ReadingDigits ViewReadingDigits()
{
var response = this.MessageHandler.Invoke(VIEW_READING_DIGITS);
var response = this.MessageHandler(VIEW_READING_DIGITS);
return new ReadingDigits(response);
}
public ReadingUnits ViewReadingUnits()
{
var response = this.MessageHandler.Invoke(VIEW_READING_UNITS);
var response = this.MessageHandler(VIEW_READING_UNITS);
return new ReadingUnits(response);
}
public RateUnits ViewRateUnits()
{
var response = this.MessageHandler.Invoke(VIEW_RATE_UNITS);
var response = this.MessageHandler(VIEW_RATE_UNITS);
return new RateUnits(response);
}
public ReadingResolution ViewReadingResolution()
{
var response = this.MessageHandler.Invoke(VIEW_READING_RESOLUTION);
var response = this.MessageHandler(VIEW_READING_RESOLUTION);
return new ReadingResolution(response);
}
public double? ViewFactoryCorrection()
{
var response = this.MessageHandler.Invoke(DEVICE_SPECIFIC, 0x08);
var response = this.MessageHandler(DEVICE_SPECIFIC, 0x08);
var bytes = new byte[2];
if (response is null || response.Length <= 1)
@@ -102,14 +100,14 @@
public RateResolution ViewRateResolution()
{
var response = this.MessageHandler.Invoke(VIEW_RATE_RESOLUTION);
var response = this.MessageHandler(VIEW_RATE_RESOLUTION);
return new RateResolution(response);
}
public Readings ViewReadings()
{
var response = this.MessageHandler.Invoke(VIEW_READINGS);
var response = this.MessageHandler(VIEW_READINGS);
return new Readings(response);
}
@@ -121,54 +119,54 @@
return;
}
var response = this.MessageHandler.Invoke(DEVICE_SPECIFIC, 0x09, crrf[0], crrf[1]);
var response = this.MessageHandler(DEVICE_SPECIFIC, 0x09, crrf[0], crrf[1]);
}
public ReadingMode ViewReadingMode()
{
var response = this.MessageHandler.Invoke(VIEW_READING_MODE);
var response = this.MessageHandler(VIEW_READING_MODE);
return new ReadingMode(response);
}
public BuildInfo ViewBuildInformation()
{
var response = this.MessageHandler.Invoke(VIEW_BUILD_INFORMATION);
var response = this.MessageHandler(VIEW_BUILD_INFORMATION);
return new BuildInfo(response);
}
public ChamberCalibrationResponse Set(ChamberCalibrationRequest chamberCalibrationRequest)
{
var response = this.MessageHandler.Invoke(DEVICE_SPECIFIC, CHAMBER_CALIBRATION);
var response = this.MessageHandler(DEVICE_SPECIFIC, CHAMBER_CALIBRATION);
return new ChamberCalibrationResponse(response);
}
public SystemParameters ViewSystemParameters()
{
var response = this.MessageHandler.Invoke(DEVICE_SPECIFIC, VIEW_SYSTEM_PARAMETERS);
var response = this.MessageHandler(DEVICE_SPECIFIC, VIEW_SYSTEM_PARAMETERS);
return new SystemParameters(response);
}
public ConfigurationParameters ViewConfigurationParameters()
{
var response = this.MessageHandler.Invoke(DEVICE_SPECIFIC, VIEW_CONFIGURATION_PARAMETERS, 0x01);
var response = this.MessageHandler(DEVICE_SPECIFIC, VIEW_CONFIGURATION_PARAMETERS, 0x01);
return new ConfigurationParameters(response);
}
public InputVolume ViewInputVolume()
{
var response = this.MessageHandler.Invoke(DEVICE_SPECIFIC, VIEW_INPUT_VOLUME);
var response = this.MessageHandler(DEVICE_SPECIFIC, VIEW_INPUT_VOLUME);
return new InputVolume(response);
}
public ChamberCalibrationResponse StartChamberCalibration(ushort rotations, ushort duration)
{
var response = this.MessageHandler.Invoke(new ChamberCalibrationRequest
var response = this.MessageHandler(new ChamberCalibrationRequest
{
Rotations = rotations,
Duration = duration,
@@ -180,203 +178,203 @@
public ChamberCalibrationResponse ViewChamberCalibration()
{
var response = this.MessageHandler.Invoke(DEVICE_SPECIFIC, CHAMBER_CALIBRATION, ChamberCalibrationRequest.REQUEST_RESULTS);
var response = this.MessageHandler(DEVICE_SPECIFIC, CHAMBER_CALIBRATION, ChamberCalibrationRequest.REQUEST_RESULTS);
return new ChamberCalibrationResponse(response);
}
public SystemTime ViewSystemTime()
{
var response = this.MessageHandler.Invoke(DEVICE_SPECIFIC, VIEW_SYSTEM_TIME);
var response = this.MessageHandler(DEVICE_SPECIFIC, VIEW_SYSTEM_TIME);
return new SystemTime(response);
}
public RegisterSettings ViewRegisterSettings()
{
var response = this.MessageHandler.Invoke(DEVICE_SPECIFIC, VIEW_REGISTER_SETTINGS);
var response = this.MessageHandler(DEVICE_SPECIFIC, VIEW_REGISTER_SETTINGS);
return new RegisterSettings(response);
}
public FeatureResponse ViewRegisterSettings(FeatureRequest request)
{
var response = this.MessageHandler.Invoke(request[DEVICE_SPECIFIC, SET_REGISTER_SETTINGS]);
var response = this.MessageHandler(request[DEVICE_SPECIFIC, SET_REGISTER_SETTINGS]);
return new RegisterSettings(response);
}
public AlarmsState ViewAlarmsState()
{
var response = this.MessageHandler.Invoke(VIEW_ALARMS_STATE, 0xFF, 0x00, 0x00);
var response = this.MessageHandler(VIEW_ALARMS_STATE, 0xFF, 0x00, 0x00);
return new AlarmsState(response);
}
public AlarmSettings ViewAlarmSettings(byte alarmID)
{
var response = this.MessageHandler.Invoke(VIEW_ALARM_SETTINGS, 0x00, alarmID, 0x01);
var response = this.MessageHandler(VIEW_ALARM_SETTINGS, 0x00, alarmID, 0x01);
return new AlarmSettings(response);
}
public FactorySeal ViewFactorySeal()
{
var response = this.MessageHandler.Invoke(DEVICE_SPECIFIC, VIEW_FACTORY_SEAL);
var response = this.MessageHandler(DEVICE_SPECIFIC, VIEW_FACTORY_SEAL);
return new FactorySeal(response);
}
public FeatureResponse ClearAlarms()
{
var response = this.MessageHandler.Invoke(CLEAR_ALARMS, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF);
var response = this.MessageHandler(CLEAR_ALARMS, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF);
return new FeatureResponse(response);
}
public FeatureResponse ClearDisplay()
{
var response = this.MessageHandler.Invoke(SET_READING_UNITS, 0xFF);
var response = this.MessageHandler(SET_READING_UNITS, 0xFF);
return new FeatureResponse(response);
}
public FeatureResponse EnableNFC()
{
var response = this.MessageHandler.Invoke(DEVICE_SPECIFIC, METROLOGY_TEST, 0x02);
var response = this.MessageHandler(DEVICE_SPECIFIC, METROLOGY_TEST, 0x02);
return new FeatureResponse(response);
}
public FeatureResponse Set(Alarm alarm)
{
var response = this.MessageHandler.Invoke(alarm[SET_ALARM_SETTINGS]);
var response = this.MessageHandler(alarm[SET_ALARM_SETTINGS]);
return new FeatureResponse(response);
}
public FeatureResponse Set(ASCIIString asciiString)
{
var response = this.MessageHandler.Invoke(asciiString[SET_READING_PRESET]);
var response = this.MessageHandler(asciiString[SET_READING_PRESET]);
return new FeatureResponse(response);
}
public FeatureResponse Set(BuildInfo buildInformation)
{
var response = this.MessageHandler.Invoke(buildInformation[SET_BUILD_INFORMATION]);
var response = this.MessageHandler(buildInformation[SET_BUILD_INFORMATION]);
return new FeatureResponse(response);
}
public FeatureResponse Set(ConfigurationParametersSet configurationParameters)
{
var response = this.MessageHandler.Invoke(configurationParameters[DEVICE_SPECIFIC, SET_CONFIGURATION_PARAMETERS]);
var response = this.MessageHandler(configurationParameters[DEVICE_SPECIFIC, SET_CONFIGURATION_PARAMETERS]);
return new FeatureResponse(response);
}
public FeatureResponse Set(CustomerText customerText)
{
var response = this.MessageHandler.Invoke(customerText[SET_CUSTOMER_TEXT]);
var response = this.MessageHandler(customerText[SET_CUSTOMER_TEXT]);
return new FeatureResponse(response);
}
public FeatureResponse Set(DeviceID deviceID)
{
var response = this.MessageHandler.Invoke(deviceID[DEVICE_SPECIFIC, SET_DEVICE_ID]);
var response = this.MessageHandler(deviceID[DEVICE_SPECIFIC, SET_DEVICE_ID]);
return new FeatureResponse(response);
}
public FeatureResponse Set(FactoryID factoryID)
{
var response = this.MessageHandler.Invoke(factoryID[SET_FACTORY_ID]);
var response = this.MessageHandler(factoryID[SET_FACTORY_ID]);
return new FeatureResponse(response);
}
public FeatureResponse Set(FactorySeal factorySeal)
{
var response = this.MessageHandler.Invoke(factorySeal[DEVICE_SPECIFIC, SET_FACTORY_SEAL]);
var response = this.MessageHandler(factorySeal[DEVICE_SPECIFIC, SET_FACTORY_SEAL]);
return new FeatureResponse(response);
}
public FeatureResponse Set(InputVolume inputVolume)
{
var response = this.MessageHandler.Invoke(inputVolume[DEVICE_SPECIFIC, SET_INPUT_VOLUME]);
var response = this.MessageHandler(inputVolume[DEVICE_SPECIFIC, SET_INPUT_VOLUME]);
return new FeatureResponse(response);
}
public FeatureResponse Set(ManifacturingTime manifacturingTime)
{
var response = this.MessageHandler.Invoke(manifacturingTime[DEVICE_SPECIFIC, SET_MANIFACTURING_TIME]);
var response = this.MessageHandler(manifacturingTime[DEVICE_SPECIFIC, SET_MANIFACTURING_TIME]);
return new FeatureResponse(response);
}
public FeatureResponse Set(ProgrammableID programmableID)
{
var response = this.MessageHandler.Invoke(programmableID[SET_PROGRAMMABLE_ID]);
var response = this.MessageHandler(programmableID[SET_PROGRAMMABLE_ID]);
return new FeatureResponse(response);
}
public FeatureResponse Set(RateUnits rateUnits)
{
var response = this.MessageHandler.Invoke(rateUnits[SET_RATE_UNITS]);
var response = this.MessageHandler(rateUnits[SET_RATE_UNITS]);
return new FeatureResponse(response);
}
public FeatureResponse Set(RateResolution rateResolution)
{
var response = this.MessageHandler.Invoke(rateResolution[SET_READING_RESOLUTION]);
var response = this.MessageHandler(rateResolution[SET_READING_RESOLUTION]);
return new FeatureResponse(response);
}
public FeatureResponse Set(ReadingDigits readingDigits)
{
var response = this.MessageHandler.Invoke(readingDigits[SET_READING_DIGITS]);
var response = this.MessageHandler(readingDigits[SET_READING_DIGITS]);
return new FeatureResponse(response);
}
public FeatureResponse Set(ReadingMode readingMode)
{
var response = this.MessageHandler.Invoke(readingMode[SET_READING_MODE]);
var response = this.MessageHandler(readingMode[SET_READING_MODE]);
return new FeatureResponse(response);
}
public FeatureResponse Set(ReadingPreset readingPreset)
{
var response = this.MessageHandler.Invoke(readingPreset[SET_READING_PRESET]);
var response = this.MessageHandler(readingPreset[SET_READING_PRESET]);
return new FeatureResponse(response);
}
public FeatureResponse Set(ReadingUnits readingUnits)
{
var response = this.MessageHandler.Invoke(readingUnits[SET_READING_UNITS]);
var response = this.MessageHandler(readingUnits[SET_READING_UNITS]);
return new FeatureResponse(response);
}
public FeatureResponse Set(ReadingResolution readingResolution)
{
var response = this.MessageHandler.Invoke(readingResolution[SET_READING_RESOLUTION]);
var response = this.MessageHandler(readingResolution[SET_READING_RESOLUTION]);
return new FeatureResponse(response);
}
public FeatureResponse Set(RegisterSettings request)
{
var response = this.MessageHandler.Invoke(request[DEVICE_SPECIFIC, SET_REGISTER_SETTINGS]);
var response = this.MessageHandler(request[DEVICE_SPECIFIC, SET_REGISTER_SETTINGS]);
return new FeatureResponse(response);
}
@@ -388,107 +386,209 @@
request = new SystemTime();
}
var response = this.MessageHandler.Invoke(request[DEVICE_SPECIFIC, SET_SYSTEM_TIME]);
var response = this.MessageHandler(request[DEVICE_SPECIFIC, SET_SYSTEM_TIME]);
return new FeatureResponse(response);
}
public FeatureResponse Set(params byte[] parameters)
public FeatureResponse Setnd(params byte[] parameters)
{
var response = this.MessageHandler.Invoke(parameters);
var response = this.MessageHandler(parameters);
return new FeatureResponse(response);
}
public FeatureResponse Unseal()
public FeatureResponse FactorySeal(bool? seal = null)
{
var request = new byte[18];
request[0] = DEVICE_SPECIFIC;
request[1] = SET_FACTORY_SEAL;
var request = default(byte[]);
// TODO: Implement factory unseal.
// - The ASCII values in hex for those characters are 0x33 34 35 36 which when reinterpreted as a uint32BE represents
// - the value 859059510 in decimal. That, mod 11 is 1, so VVVV is 0x0001.
// - When the input data is a string, and does not contain the number of characters required for this algorithm,
// - the value used is the input data written over the value “Factory”.
// - For example, if View Customer Text returns the string “Boo”, the value used in the CCCC step would be “Bootory.”
// - Note that due to the reliance on time and reading, the hash may become invalidated before you are able
// - to send the unseal command.Because of this, if the register responds with Unable to execute,
// - you should recalculate the hash which should last for a longer period if SSSS is large / close to rolling over.
// - Also, if the 7th digit rolls over during unsealing, the hash will not be valid.
// - Current system time is written into manufacturing date/ time if the manufacturing date / time has not been set
// - when factory seal is set.
var muster = new byte[] { (byte)'F', (byte)'a', (byte)'c', (byte)'t', (byte)'o', (byte)'r', (byte)'y' };
var key = new byte[16];
// 1. ((View Seconds Active) >> 8) &0xFFFF
var secondsActive = new Epoch20000101(this.Send(0xFD, 0x3D)).SecondsSince;
var SSSS = BitConverter.GetBytes((secondsActive >> 8) & 0xFFFF);
Buffer.BlockCopy(SSSS, 0, key, 0, 4);
// 2. CRC16_iPERL(View Factory ID),
var factoryID = this.ViewFactoryID().Value;
var factoryIDBytes = Encoding.ASCII.GetBytes(factoryID);
var IIII = factoryIDBytes.CalculateCRC16(0, (ushort)factoryIDBytes.Length);
Buffer.BlockCopy(IIII, 0, key, 4, 2);
// 3. ViewCustomerText.Substring(0, 4).Sum(x => x.Count(x => x == 1))
var customerText = this.ViewCustomerText().Value;
var ctLength = customerText?.Length ?? 0;
var CCCC = new byte[4];
for (int ct = 0; ct < 4; ct++)
if (seal is null)
{
if (ctLength > ct + 3)
request = new byte[] { 0xFD, 0x63 };
}
else if (seal == true)
{
request = new byte[] { 0xFD, 0x64, 0x01 };
}
else
{
request = new byte[] { 0xFD, 0x64, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
this.CalculateUnsealHash().CopyTo(request, 3);
}
var response = this.MessageHandler(request);
return new FactorySeal(response);
}
/// <summary>
/// If the first octet is zero, the next 8 octets are a 64-bit big endian hash code. If the 64-bit hash code matches the currently valid unseal hash for the meter, the factory seal will be broken/cleared/unset. Otherwise, the seal state is not modified.
/// The hash code is a function of the responses from several commands combined into the format 0xSSSSIIIICCCCVVVV.This is identical to code used to unseal iPERL and ally meters.
/// SSSS: ((View Seconds Active) >> 8) & 0xFFFF, little endian.
/// IIII: CRC16_iPERL(View Factory ID), little endian. (Don’t worry about the null character.CRC16_iPERL doesn’t care about additional 0’s at the end of input.)
/// CCCC: Each nibble corresponds to the number of bits set in the first four characters in (View Customer Text), little endian.
/// VVVV: Characters 3-6 of response from View Reading Preset, counting the first character as character 1 reinterpreted as a big endian uint32 modulo 11. For example, if View Reading Preset is “12345678”, characters 3-6 would be “3456”. The ASCII values in hex for those characters are 0x33 34 35 36 which when reinterpreted as a uint32BE represents the value 859059510 in decimal. That, mod 11 is 1, so VVVV is 0x0001.
/// When the input data is a string, and does not contain the number of characters required for this algorithm, the value used is the input data written over the value “Factory”. For example, if View Customer Text returns the string “Boo”, the value used in the CCCC step would be “Bootory.”
/// Note that due to the reliance on time and reading, the hash may become invalidated before you are able to send the unseal command.Because of this, if the register responds with Unable to execute, you should recalculate the hash which should last for a longer period if SSSS is large/close to rolling over.Also, if the 7th digit rolls over during unsealing, the hash will not be valid.
/// Current system time is written into manufacturing date/time if the manufacturing date/time has not been set when factory seal is set.
/// </summary>
private byte[] CalculateUnsealHash()
{
var hash = new byte[8];
this.CalculateIIII().CopyTo(hash, 2);
this.CalculateCCCC().CopyTo(hash, 4);
this.CalculateVVVV().CopyTo(hash, 6);
this.CalculateSSSS().CopyTo(hash, 0);
return hash;
}
private byte[] CalculateSSSS()
{
var response = this.MessageHandler(0xFD, 0x3D);
var result = default(ushort);
if (response[0] == 0x01)
{
var seconds = BitConverter.ToUInt32(response, 1);
result = (ushort)((seconds >> 8) & 0xFFFF);
}
return BitConverter.GetBytes(result);
}
private byte[] CalculateIIII()
{
var response = this.MessageHandler(0x01);
var length = Math.Max(response.Length - 1, 0);
var factoryID = Encoding
.ASCII
.GetString(response, 1, length)
.Trim('\0')
.Trim();
var crcU16 = default(ushort);
if (response[0] == 0x01)
{
var data = default(byte[]);
if (string.IsNullOrWhiteSpace(factoryID))
{
CCCC[ct] = (byte)customerText[ct + 3];
data = Encoding.ASCII.GetBytes("Factory");
}
else
{
CCCC[ct] = muster[ct];
data = Encoding.ASCII.GetBytes(factoryID);
}
foreach (byte byteU8 in data)
{
var tempU16 = crcU16;
crcU16 = (ushort)(tempU16 >> 8);
crcU16 += (ushort)(tempU16 << 8);
crcU16 ^= byteU8;
tempU16 = (ushort)((crcU16 >> 4) & 0x000F);
crcU16 ^= tempU16;
tempU16 = (ushort)((crcU16 & 0x000F) << 12);
crcU16 ^= tempU16;
tempU16 = (ushort)((crcU16 & 0x00FF) << 5);
crcU16 ^= tempU16;
}
}
Buffer.BlockCopy(CCCC, 0, key, 8, 4);
return BitConverter.GetBytes(crcU16);
}
// 4. ViewReadingPreset.Substring(3, 4)
var readings = this
.ViewReadings()
.Value
.Substring(3, 4)
.ToCharArray()
.Reverse()
.Select(x => (byte)x)
.ToArray();
private byte[] CalculateCCCC()
{
var response = this.MessageHandler(0x07);
var length = Math.Max(response.Length - 1, 0);
var customerText = Encoding
.ASCII
.GetString(response, 1, length)
.Trim('\0');
var cccc = new byte[2];
for (int x = readings.Length - 1; x < 4; x++)
if (response[0] == 0x01)
{
readings[x] = muster[x];
var data = new byte[4];
if (string.IsNullOrWhiteSpace(customerText))
{
data = Encoding.ASCII.GetBytes("Factory");
}
else if (customerText.Length < 4)
{
Encoding.ASCII.GetBytes(customerText).CopyTo(data, 0);
}
else
{
data = Encoding.ASCII.GetBytes(customerText);
}
var bits = new byte[16];
var hex = string.Empty;
var current = default(byte);
var count1 = default(byte);
for (int i = 0; i < 4; i++)
{
current = data[i];
count1 = 0;
for (int b = 0; b < 8; b++)
{
count1 += (byte)(current >> b & 1);
}
hex += count1;
}
cccc[0] = Convert.ToByte(hex.Substring(0, 2), 16);
cccc[1] = Convert.ToByte(hex.Substring(2, 2), 16);
}
var value = BitConverter.ToUInt32(readings, 0) % 11;
var VVVV = BitConverter.GetBytes(value);
return cccc;
}
Buffer.BlockCopy(VVVV, 0, key, 12, 4);
private byte[] CalculateVVVV()
{
var response = this.MessageHandler(0x13);
var length = Math.Max(response.Length - 1, 0);
var readingPreset = Encoding
.ASCII
.GetString(response, 1, length)
.Trim('\0');
var result = default(ushort);
Console.WriteLine(BitConverter.ToString(key));
if (key is null || key.Length != 16)
if (response[0] == 0x01)
{
return new FactorySeal();
var data = new byte[4];
if (string.IsNullOrWhiteSpace(readingPreset))
{
var bytes = Encoding.ASCII.GetBytes(readingPreset);
Array.Copy(bytes, 2, data, 0, 4);
}
else
{
Array.Copy(response, 3, data, 0, 4);
}
data = data.Reverse().ToArray();
result = (ushort)(BitConverter.ToUInt32(data, 0) % 11);
}
//var _key = key.Reverse();
Buffer.BlockCopy(key, 0, request, 2, 16);
var response = this.MessageHandler.Invoke(request);
return new FactorySeal(response);
return BitConverter.GetBytes(result);
}
protected void OnStateChanged(object state)
+16 -11
View File
@@ -4,6 +4,7 @@
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Threading;
using System.Threading.Tasks;
public class OmniContext : IDisposable
@@ -12,17 +13,31 @@
private readonly OmniDatabase database;
private readonly string outputDirectory;
private CancellationTokenSource cancellationTokenSource;
private CancellationToken cancellationToken;
private int runId;
private OmniContext(string connectionString, string outputDirectory)
public OmniContext(string connectionString, string outputDirectory)
{
this.outputDirectory = outputDirectory;
this.database = new OmniDatabase(connectionString, outputDirectory);
this.meters = new ConcurrentDictionary<int, OmniMeter>();
Current = this;
}
public OmniAuftrag Auftrag { get; set; }
public OmniParameter Defaults
{
get => this.Auftrag?.TypParameter ?? new OmniParameter();
}
public IEnumerable<OmniPruefpunkt> Pruefpunkte
{
get => this.Auftrag?.Pruefpunkte ?? new OmniPruefpunkt[] { };
}
public ReadOnlyCollection<OmniMeter> Meters
{
get => this.meters.Values as ReadOnlyCollection<OmniMeter>;
@@ -103,15 +118,5 @@
}
public static OmniContext Current { get; private set; }
public static OmniContext GetOrCreateInstance(string connectionString, string outputDirectory)
{
if (Current is null)
{
Current = new OmniContext(connectionString, outputDirectory);
}
return Current;
}
}
}
+11
View File
@@ -0,0 +1,11 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace OmniPlus
{
class OmniLogger
{
}
}
+68 -53
View File
@@ -16,10 +16,12 @@
const string NA = "n/a";
private readonly ConcurrentQueue<object> states = new ConcurrentQueue<object>();
private readonly OmniParameter defaults;
private readonly string outputDirectory;
private readonly string outputFile;
private OmniConnection connection;
private bool factorySealed;
public OmniMeter(string psnr, int nr, string portName, string outputDirectory)
{
@@ -28,6 +30,7 @@
this.PortName = portName;
this.outputDirectory = outputDirectory;
this.outputFile = GetOrCreateOutputFile(nr, portName, outputDirectory);
this.defaults = OmniContext.Current.Defaults;
}
public string PSNR { get; }
@@ -85,50 +88,46 @@
}
}
public void InitializeForInspection(bool preserveState = false)
public void InitializeForInspection(bool keepCorrection = false)
{
var systemParameters = this.connection.ViewSystemParameters();
var buildInfo = default(string);
var versionAndType = default(string);
var manifactured = default(DateTime?);
var battery = default(double?);
var isvalid = default(bool?);
this.factorySealed = systemParameters.FactorySealed;
if (systemParameters.Status == Status.Completed)
{
buildInfo = systemParameters.BuildInfo.Value;
versionAndType = systemParameters.VersionAndType.Value;
manifactured = systemParameters.ManifacturingTime.DateTime;
battery = systemParameters.BatteryVoltage.Volts / 1000D;
isvalid = systemParameters.IsValid;
this.TestRun.BuildInfo = systemParameters.BuildInfo.Value;
this.TestRun.VersionAndType = systemParameters.VersionAndType.Value;
this.TestRun.ManifacturedDate = systemParameters.ManifacturingTime.DateTime;
this.TestRun.BatteryVoltage = systemParameters.BatteryVoltage.Volts / 1000D;
this.TestRun.IsValid = systemParameters.IsValid;
}
if (this.factorySealed)
{
this.connection.FactorySeal(false);
}
else
{
if (!keepCorrection)
{
var crrfBytes = BitConverter.GetBytes(default(sbyte));
this.connection.SetFactoryCorrection(crrfBytes);
}
var inputVolumeResult = this.connection.Set(new InputVolume
{
Direction = this.defaults.Direction,
Fraction = (ushort)this.defaults.Fraction,
IntPart = this.defaults.IntPart,
Range = this.defaults.Range,
Size = this.defaults.Size
});
}
this.TestRun.SlotNr = (byte)this.SlotNr;
this.TestRun.BuildInfo = buildInfo;
this.TestRun.VersionAndType = versionAndType;
this.TestRun.ManifacturedDate = manifactured;
this.TestRun.BatteryVoltage = battery;
this.TestRun.IsValid = isvalid;
if (!preserveState)
{
var defaultCrrf = (sbyte)(3.3 * 10D);
var crrfBytes = BitConverter.GetBytes(defaultCrrf);
this.connection.SetFactoryCorrection(crrfBytes);
}
this.TestRun.CrrfBefore = this.connection.ViewFactoryCorrection();
var defaults = OmniContext.Current.Auftrag.TypParameter;
var inputVolumeResult = this.connection.Set(new InputVolume
{
Direction = defaults.Direction,
Fraction = (ushort)defaults.Fraction,
IntPart = defaults.IntPart,
Range = defaults.Range,
Size = defaults.Size
});
this.TestRun.SaveChanges();
}
@@ -226,9 +225,11 @@
var rotations = response.Rotations;
var duration = response.DurationSec;
var rs = $"{rotations}/{duration:0.0}";
var defaults = OmniContext.Current.Auftrag.TypParameter;
var mlr = OmniPlusFormulas.MilliliterPerRotation(defaults.IntPart, (ushort)defaults.Fraction, defaults.Factor);
var m3s = OmniPlusFormulas.MeterFlowM3S(rotations, mlr, response.Duration);
var mlr = OmniPlusFormulas.MilliliterPerRotation(this.defaults.IntPart, (ushort)this.defaults.Fraction, this.defaults.Factor);
var m3s = OmniPlusFormulas.MeterFlowM3S(rotations, mlr, duration);
OmniPlusFormulas.OutDebugM3S(ref m3s);
var acc = OmniPlusFormulas.AccuracyPercentage(m3s, refm3s);
this.TestRun.AddTestPoint(pp.PPNR, pp.TestPointId, pp.GalPerMin, rotations, duration, m3s, refm3s, acc);
@@ -241,7 +242,6 @@
var crrf = this.TestRun
.GetAccuracies()
.GetCorrectionFactor(out bool succeeded);
var defaults = OmniContext.Current.Auftrag.TypParameter;
var testPoints = OmniContext
.Current
.Auftrag
@@ -271,27 +271,42 @@
}
}
var response = this.connection.Set(new RegisterSettings
if (!this.factorySealed)
{
IntPart = defaults.IntPart,
Fraction = (ushort)defaults.Fraction,
Size = defaults.Size,
Range = defaults.Range,
VolumePerPulseUnit = 0x00,
MeterUnits = (byte)MessurementUnits.CubicMeters,
FlowUnits = (byte)MessurementUnits.CubicMeters,
FlowRate = (byte)TimeUnits.Hours,
FactoryCorrection = (sbyte)((succeeded ? crrf : 3.3) * 10),
FieldCorrection = 0x00,
PulseWeight = 0,
PulseWidth = 7,
PulseUpdate = 0,
});
var factor = default(sbyte);
if (succeeded)
{
factor = (sbyte)(crrf / 10D);
}
var response = this.connection.Set(new RegisterSettings
{
IntPart = this.defaults.IntPart,
Fraction = (ushort)this.defaults.Fraction,
Size = this.defaults.Size,
Range = this.defaults.Range,
VolumePerPulseUnit = 0x00,
MeterUnits = (byte)MessurementUnits.CubicMeters,
FlowUnits = (byte)MessurementUnits.CubicMeters,
FlowRate = (byte)TimeUnits.Hours,
FactoryCorrection = factor,
FieldCorrection = 0x00,
PulseWeight = 0,
PulseWidth = 7,
PulseUpdate = 0,
});
}
this.TestRun.Succeeded = succeeded;
this.TestRun.CrrfAfter = crrf;
this.TestRun.CloseTestRun();
if (this.factorySealed)
{
this.connection.FactorySeal(true);
}
while (this.states.TryDequeue(out var state))
{
File.AppendAllText(this.outputFile, $"{state}{Environment.NewLine}");
+2 -1
View File
@@ -103,6 +103,7 @@
<Compile Include="OmniConnection.cs" />
<Compile Include="OmniContext.cs" />
<Compile Include="OmniIrdaConnection.cs" />
<Compile Include="OmniLogger.cs" />
<Compile Include="OmniMeter.cs" />
<Compile Include="OmniDatabase.cs" />
<Compile Include="Inspection\OmniPlusTest.cs" />
@@ -119,7 +120,7 @@
<None Include="packages.config" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\ExchangeHub\ExchangeHub.csproj">
<ProjectReference Include="..\ExchangeHub\ExchangeHub.csproj">
<Project>{6033FF0C-CF32-4BC5-8EFE-4774CCDC663D}</Project>
<Name>ExchangeHub</Name>
</ProjectReference>