111 lines
3.0 KiB
C#
111 lines
3.0 KiB
C#
namespace InspectionUI.ViewModels
|
|
{
|
|
using InspectionUI.Models;
|
|
|
|
using OmniPlus;
|
|
|
|
using System;
|
|
using System.Collections.Generic;
|
|
using System.Collections.ObjectModel;
|
|
using System.Threading;
|
|
using System.Threading.Tasks;
|
|
|
|
internal class DisplayReaderVM : VM
|
|
{
|
|
private readonly OmniContext omniContext;
|
|
|
|
private CancellationTokenSource cancellationTokenSource;
|
|
private CancellationToken cancellationToken;
|
|
private List<Task> readers;
|
|
|
|
public DisplayReaderVM()
|
|
{
|
|
this.Meters = new ObservableCollection<MeterDisplayVM>();
|
|
this.omniContext = OmniContext.Create(Appsettings.OmniDB, Appsettings.CurrentDirectory);
|
|
}
|
|
|
|
public ObservableCollection<MeterDisplayVM> Meters { get; }
|
|
|
|
private void StartReading()
|
|
{
|
|
try
|
|
{
|
|
this.cancellationTokenSource?.Cancel(true);
|
|
this.readers?.Clear();
|
|
this.Meters?.Clear();
|
|
}
|
|
catch (Exception e)
|
|
{
|
|
|
|
}
|
|
|
|
this.cancellationTokenSource = new CancellationTokenSource();
|
|
this.cancellationToken = this.cancellationTokenSource.Token;
|
|
this.readers = new List<Task>();
|
|
|
|
this.omniContext.LoadMeters(Appsettings.COMPorts, Appsettings.PSNR);
|
|
|
|
foreach (var meter in this.omniContext.Meters)
|
|
{
|
|
var meterVM = new MeterDisplayVM(meter);
|
|
|
|
this.Meters.Add(meterVM);
|
|
this.readers.Add(meterVM.StartReadingAsync(this.cancellationToken));
|
|
}
|
|
}
|
|
}
|
|
|
|
internal class MeterDisplayVM : VM
|
|
{
|
|
private readonly OmniMeter meter;
|
|
|
|
public MeterDisplayVM(OmniMeter meter)
|
|
=> this.meter = meter;
|
|
|
|
private string meterId;
|
|
public string MeterNr
|
|
{
|
|
get => this.meterId;
|
|
set => this.Set(() => this.meterId = value);
|
|
}
|
|
|
|
private string displayValue;
|
|
public string DisplayValue
|
|
{
|
|
get => this.displayValue;
|
|
set => this.Set(() => this.displayValue = value);
|
|
}
|
|
|
|
public Task StartReadingAsync(CancellationToken cancellationToken)
|
|
{
|
|
cancellationToken.Register(this.meter.Dispose);
|
|
|
|
void StartReading(object state)
|
|
{
|
|
if (state is MeterDisplayVM vm)
|
|
{
|
|
var _meter = vm.meter;
|
|
_meter.Connect();
|
|
_meter.IdentifySelf();
|
|
|
|
if (!_meter.IsActive)
|
|
{
|
|
return;
|
|
}
|
|
|
|
vm.MeterNr = _meter.MeterNr;
|
|
|
|
while (_meter.IsActive)
|
|
{
|
|
vm.DisplayValue = _meter.ReadDisplay();
|
|
|
|
Thread.Sleep(1000);
|
|
}
|
|
}
|
|
}
|
|
|
|
return Task.Factory.StartNew(StartReading, this, cancellationToken);
|
|
}
|
|
}
|
|
}
|