laatzen/Common/Ui/Common.UI/ViewModels/EregisterInitializeVM.cs
2026-03-10 11:16:20 +01:00

278 lines
9.6 KiB
C#

namespace Common.UI.ViewModels
{
using Common.Hardware.SIRT;
using Common.Hardware.WaterMeter.eRegister;
using Common.Hardware.WaterMeter.eRegister.Models;
using Common.UI.Infrastructure;
using Common.UI.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using System.Timers;
using System.Windows;
using System.Windows.Input;
using SystemTimer = System.Timers.Timer;
public class EregisterInitializeVM : VM<EregisterInitializeVM>
{
protected readonly SystemTimer timer = new SystemTimer();
protected readonly EregisterBatch eregisterFactory = new EregisterBatch(AppHost.SIRTHub);
protected CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
protected CancellationToken cancellationToken = CancellationToken.None;
protected Task programmingTask = Task.CompletedTask;
protected DateTime timestamp;
protected int sharedId;
protected bool prepeared;
public EregisterInitializeVM()
{
this.timer = new SystemTimer
{
AutoReset = true,
Enabled = false,
Interval = 500,
};
this.timer.Elapsed += this.Timer_Elapsed;
// TODO: AppHost.SIRTHub.StateLogging += x => AppHost.NLogger.Debug(x);
this.eregisterFactory = new EregisterBatch(AppHost.SIRTHub);
this.StartProgrammingCommand = new Command(this.StartProgrammingCommandHandler);
this.StopProgrammingCommand = new Command(this.StopProgrammingCommandHandler);
this.WindowTitle = "Prüfungsinitializierung";
}
private String windowTitle;
public string WindowTitle
{
get => this.windowTitle;
set => this.SetValue(vm => vm.windowTitle = value);
}
private bool startEnabled;
public bool StartEnabled
{
get => this.startEnabled;
set => this.SetValue(vm => vm.startEnabled = value);
}
private bool stopEnabled;
public bool StopEnabled
{
get => this.stopEnabled;
set => this.SetValue(vm => vm.stopEnabled = value);
}
private string timeElapsed;
public string TimeElapsed
{
get => this.timeElapsed;
set => this.SetValue(vm => vm.timeElapsed = value);
}
public ICommand StartProgrammingCommand { get; }
public ICommand StopProgrammingCommand { get; }
public IEnumerable<GridItem> ProgrammingTasks { get; set; }
internal override void ViewModel_Loaded(object data)
=> Task.Run(() =>
{
this.PrepareProgramming();
this.StartEnabled = true;
this.prepeared = true;
});
protected virtual void PrepareProgramming()
{
if (!int.TryParse($"{Appsettings.GetSetting("PSNR")}", out var psnr))
{
MessageBox.Show("Prüfstationnummer ist nicht konfiguriert.", "Fehler");
return;
}
this.sharedId = AuftragDbContext.P2000Shared.FindSharedId(psnr, "EregisterInitialize");
var parametersList = AuftragDbContext.LoadEregisterProgrammingParametersListForSharedId(this.sharedId);
this.LoadEncryptionKeysAsync(parametersList)
.Wait();
var programmingTasks = this.eregisterFactory
.LoadInspectionInitializationTasks(parametersList)
.ToList();
this.UpdateUIProgrammingTasks(programmingTasks);
}
protected async Task LoadEncryptionKeysAsync(EregisterProgrammingParametersList parametersList)
{
var keyStore = new SQLiteKeyStore();
var uriFormat = Appsettings.GetSetting("EncryptionKeisUrl");
var httpClient = new HttpClient();
var encryptionKey = default(string);
foreach (var epp in parametersList)
{
//if (keyStore.TryGetKey((uint)epp.TempAdresse, (uint)epp.Adresse, out encryptionKey))
//{
// epp.EncryptionKey = encryptionKey;
// epp.IsValid = true;
//}
//else
{
try
{
using (var httpResponeMessage = await httpClient.GetAsync(string.Format(uriFormat, epp.SerienNr)))
{
var content = await httpResponeMessage.Content.ReadAsStringAsync();
if (httpResponeMessage?.IsSuccessStatusCode == true)
{
encryptionKey = content?.Trim('"');
var key = encryptionKey?.GetEncryptionKey();
if (key?.Length == 16)
{
keyStore.AddKey((uint)epp.TempAdresse, (uint)epp.Adresse, encryptionKey);
epp.EncryptionKey = encryptionKey;
epp.IsValid = true;
}
else
{
MessageBox.Show($"Ungültiger schlüssel", $"Fehler beim Laden des Schlüssels!", MessageBoxButton.OK);
epp.IsValid = false;
}
}
else
{
MessageBox.Show(httpResponeMessage.StatusCode.ToString(), $"Fehler beim Laden des Schlüssels!", MessageBoxButton.OK);
epp.IsValid = false;
}
}
}
catch (Exception e)
{
MessageBox.Show(e.ToString(), $"Fehler beim Laden des Schlüssels!", MessageBoxButton.OK);
epp.IsValid = false;
}
}
}
}
protected void UpdateUIProgrammingTasks(IEnumerable<IEnumerable<EregisterTask>> programmingTasksEnumerable)
{
var tasks = new List<GridItem>();
var col = 0;
var row = 0;
foreach (var programmingTasks in programmingTasksEnumerable)
{
var firstOrDefault = programmingTasks.FirstOrDefault();
tasks.Add(new EregisterHeaderVM
{
Column = col++,
Frequency = $"{firstOrDefault?.Frequency ?? 0}MHz",
PoNr = firstOrDefault?.PoNr ?? 0,
Row = row,
SerialNr = firstOrDefault?.SerialNr ?? 0,
SlotNr = firstOrDefault?.SlotNr ?? 0
});
}
col = 0;
row = 1;
foreach (var programmingTasks in programmingTasksEnumerable)
{
foreach (var programmingTask in programmingTasks)
{
var etask = new EregisterTaskVM(programmingTask, col, row++);
tasks.Add(etask);
}
col += 1;
row = 1;
}
this.InvokeAsync(() =>
{
this.ProgrammingTasks = tasks;
this.NotifyPropertyChanged(nameof(this.ProgrammingTasks));
});
}
private void StartProgrammingCommandHandler()
{
if (this.StartEnabled)
{
this.StartEnabled = false;
this.StopEnabled = true;
this.TimeElapsed = null;
this.timestamp = DateTime.Now;
this.cancellationTokenSource = new CancellationTokenSource();
this.cancellationToken = this.cancellationTokenSource.Token;
this.programmingTask = Task.Factory.StartNew(() =>
{
if (!this.prepeared)
{
this.PrepareProgramming();
}
this.timer.Start();
this.eregisterFactory.StartProgramming(this.cancellationToken);
this.StopProgrammingCommandHandler();
this.prepeared = false;
})
.ContinueWith(t =>
{
if (t.Exception != null)
{
AppHost.NLogger.Error(t.Exception.ToString());
}
});
}
}
private void StopProgrammingCommandHandler()
{
this.timer.Stop();
this.prepeared = false;
this.StartEnabled = true;
this.StopEnabled = false;
AuftragDbContext.eRegister.Update(this.eregisterFactory.GetEregisterStates().ToList());
AuftragDbContext.eRegister_History.Save(this.eregisterFactory.GetEregisterHistories().ToList());
try
{
this.cancellationTokenSource?.Cancel();
}
catch { }
try
{
this.eregisterFactory.StopProgramming();
}
catch { }
}
private void Timer_Elapsed(object _, ElapsedEventArgs args)
{
var stamp = args.SignalTime - timestamp;
this.TimeElapsed = stamp.ToString("mm\\:ss");
}
}
}