latest changes

This commit is contained in:
Stoyan Zlatev 2026-02-11 09:56:31 +01:00
parent dc78e7954e
commit 3a589020bf
15 changed files with 155 additions and 286 deletions

View File

@ -40,6 +40,7 @@
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Management" />
</ItemGroup>
<ItemGroup>
<Compile Include="Program.cs" />

View File

@ -1,12 +1,28 @@
namespace CommonConsole
{
using Common.Hardware.SIRT;
using System;
public static partial class Program
{
static void Main()
{
SIRTLogger.Message += Console.WriteLine;
var sirtHub = new SIRTHub();
_ = sirtHub.TryOpen("COM6", out var _1, out var _2);
_ = sirtHub.TryOpen("COM7", out var _3, out var _4);
var addresses = new uint[]
{
319017452,
319017453,
319017454,
309031154,
};
Console.ReadKey();
sirtHub.CloseAll();
SIRTLogger.Message -= Console.WriteLine;
}
@ -24,10 +40,6 @@
static void Main_ProgrammingParameters_Cordonel()

View File

@ -4,14 +4,12 @@
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
public class SIRTHub
{
private static readonly ConcurrentDictionary<string, SIRTBroadcaster> broadcasters = new ConcurrentDictionary<string, SIRTBroadcaster>();
private static List<Action<SIRTMessage>> messageReceiveDelegates = new List<Action<SIRTMessage>>();
private readonly bool log_RX_TX;
@ -20,6 +18,7 @@
public event Action<SIRTBroadcaster> Connected;
public event Action<SIRTBroadcaster> Disconnected;
public event Action<SIRTMessage> MessageReceived;
public void CloseAll()
{
@ -53,11 +52,6 @@
void SIRTBroadcaster_Disconnected(SIRTBroadcaster _broadcaster)
{
foreach (var @delegate in messageReceiveDelegates)
{
broadcaster.MessageReceived -= @delegate;
}
this.Disconnected?.Invoke(_broadcaster);
disconnectedEvent.Set();
@ -99,27 +93,17 @@
void SIRTBroadcasterConnected(SIRTBroadcaster _broadcaster)
{
broadcasters.GetOrAdd(portName, _broadcaster);
foreach (var @delegate in messageReceiveDelegates)
{
_broadcaster.MessageReceived += @delegate;
}
_broadcaster.MessageReceived += this.OnSIRTMessageReceived;
broadcasters.AddOrUpdate(portName, _broadcaster, (_, _1) => _broadcaster);
this.Connected?.Invoke(_broadcaster);
connectedEvent.Set();
}
void SIRTBroadcasterDisconnected(SIRTBroadcaster _broadcaster)
{
foreach (var @delegate in messageReceiveDelegates)
{
_broadcaster.MessageReceived -= @delegate;
}
_broadcaster.MessageReceived -= this.OnSIRTMessageReceived;
broadcasters.TryRemove(portName, out var _);
this.Disconnected?.Invoke(_broadcaster);
connectedEvent.Set();
}
@ -127,7 +111,7 @@
broadcaster.Disconnected += SIRTBroadcasterDisconnected;
broadcaster.Open();
connectedEvent.Wait(3000);
connectedEvent.Wait();
hexId = broadcaster.Id;
frequency = broadcaster.Frequency;
@ -140,5 +124,8 @@
private void LogMessage(object message)
=> SIRTLogger.LogMessage($"{nameof(SIRTHub)}|{message}");
private void OnSIRTMessageReceived(SIRTMessage message)
=> this.MessageReceived?.Invoke(message);
}
}

View File

@ -26,9 +26,11 @@
this.LogMessage($"Closing: {this}");
var waitEvent = new ManualResetEventSlim();
var disposed = false;
void SerialPortDisposed(object sender, EventArgs args)
{
disposed = true;
this.LogMessage($"Disposed: {this}");
waitEvent.Set();
}
@ -47,7 +49,7 @@
this.serialPort.Disposed -= SerialPortDisposed;
if (!this.IsOpen)
if (disposed)
{
this.LogMessage($"Closed: {this}");
}
@ -76,6 +78,40 @@
}
}
public IEnumerable<byte[]> GetEnumerable()
{
var manualResetEventSlim = new ManualResetEventSlim();
void DataReceived(object sender, SerialDataReceivedEventArgs args)
{
if (args.EventType == SerialData.Chars)
{
manualResetEventSlim.Set();
}
}
this.serialPort.DataReceived += DataReceived;
var bufferSize = this.serialPort.ReadBufferSize;
var buffer = new byte[bufferSize];
var length = default(int);
while (this.serialPort.IsOpen)
{
buffer = new byte[bufferSize];
length = this.serialPort.Read(buffer, 0, bufferSize);
Array.Resize(ref buffer, length);
yield return buffer;
manualResetEventSlim.Reset();
manualResetEventSlim.Wait();
}
this.serialPort.DataReceived -= DataReceived;
}
public IEnumerable<byte[]> ReadBytes()
{
var bufferSize = this.serialPort.ReadBufferSize;
@ -90,7 +126,7 @@
{
length = this.serialPort.Read(buffer, 0, bufferSize);
}
catch (IOException _)
catch (IOException e)
{
break;
}

View File

@ -2,15 +2,19 @@
{
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
public sealed class SIRTStream
{
private readonly SIRTPort sirtPort;
private readonly bool log_RX_TX;
private readonly List<byte> stream;
public SIRTStream(string portName, bool log_RX_TX = true)
{
this.sirtPort = new SIRTPort(portName, false);
this.stream = new List<byte>();
this.log_RX_TX = log_RX_TX;
}
@ -24,7 +28,17 @@
public IEnumerable<byte[]> ReadMessages()
{
var buffer = new List<byte>();
void StartReading()
{
foreach (var bytes in this.sirtPort.ReadBytes())
{
this.stream.AddRange(bytes);
}
}
var cancellationTokenSource = new CancellationTokenSource();
var cancellationToken = cancellationTokenSource.Token;
var task = Task.Factory.StartNew(StartReading, cancellationToken);
var bytesCount = default(int);
var startIndex = default(int);
var lengthIndex = default(int);
@ -33,20 +47,19 @@
var messageLength = default(int);
var message = default(byte[]);
foreach (var bytes in this.sirtPort.ReadBytes())
while (this.sirtPort.IsOpen)
{
buffer.AddRange(bytes);
bytesCount = buffer.Count;
bytesCount = this.stream.Count;
// until can parse messages from the buffer
while (bytesCount > 0)
{
startIndex = buffer.IndexOf(SIRTConstants.SIRT_PC, 0);
startIndex = this.stream.IndexOf(SIRTConstants.SIRT_PC, 0);
// when no start byte found clear and break
if (startIndex < 0)
{
buffer.Clear();
this.stream.Clear();
break;
}
@ -59,7 +72,7 @@
break;
}
length = buffer[lengthIndex];
length = this.stream[lengthIndex];
endIndex = lengthIndex + length + 3;
// when not enough bytes to the end of the message just break
@ -71,8 +84,8 @@
messageLength = endIndex - startIndex + 1;
message = new byte[messageLength];
buffer.CopyTo(startIndex, message, 0, messageLength);
buffer.RemoveRange(0, endIndex + 1);
this.stream.CopyTo(startIndex, message, 0, messageLength);
this.stream.RemoveRange(0, endIndex + 1);
// when message dose not ends with 0x16 clear bytes and break
if (message[messageLength - 1] != SIRTConstants.MSG_END)
@ -88,11 +101,20 @@
}
// in case there are more messages in the buffer
bytesCount = buffer.Count;
bytesCount = this.stream.Count;
yield return message;
}
}
try
{
cancellationTokenSource.Cancel();
}
catch (Exception e)
{
this.LogMessage($"{e.Message}");
}
}
public void Write(params byte[] bytes)

View File

@ -44,12 +44,6 @@
internal IEnumerable<EregisterTask> LoadInspectionInitializationTasks()
{
this.executionType = nameof(LoadInspectionInitializationTasks);
//if (this.parameters.Completed)
//{
// return new EregisterTask[] { };
//}
var features = this.parameters.LoadInspectionInitializationFeatures();
if (features.RequestAddress > 0 && features.ResponseAddress > 0)
@ -82,12 +76,26 @@
if (features.RequestAddress > 0 && features.ResponseAddress > 0)
{
this.LoadProgrammingParameters(features);
// this.LoadProgrammingParameters(features);
if (this.parameters.StatusFertigung == 30)
{
this.runningTasks.Add(new EregisterCheckFinalizationTask(this.parameters, features.Frequency)
//this.runningTasks.Add(new EregisterCheckFinalizationTask(this.parameters, features.Frequency)
//{
// WakeUpModul = true,
// SlotNr = features.SlotNr,
// PoNr = features.PoNr,
// SerialNr = features.SerialNr,
// RequestAddress = features.RequestAddress,
// ResponseAddress = features.ResponseAddress,
// EncryptionKeyI = features.EncryptionKey,
// EncryptionKeyII = SENSUS_STANDARD.GetEncryptionKey(),
//});
this.runningTasks.Add(new EregisterTask(this.parameters.Frequency)
{
Name = "WUP",
WakeUpCmd = true,
WakeUpModul = true,
SlotNr = features.SlotNr,
PoNr = features.PoNr,
@ -96,10 +104,18 @@
ResponseAddress = features.ResponseAddress,
EncryptionKeyI = features.EncryptionKey,
EncryptionKeyII = SENSUS_STANDARD.GetEncryptionKey(),
Data = new ChangeWakeUp(WakeUpMode.StayAwake)
.Append(new ChangeNumberOfLatWindows(this.parameters.LatWindowsInitialization))
.Append(new ChangeTransmissionInterval(this.parameters.TransmissionIntervalInitialization))
// .Append(new ChangeSensusRFEncryptionKey(features.EncryptionKey))
.Append(new ProvidePin(AuthLevel.II)),
Timeout = 10_000
});
this.runningTasks.Add(new EregisterTask(this.parameters.Frequency)
{
WakeUpModul = true,
Name = "0, 2, 16",
SlotNr = features.SlotNr,
PoNr = features.PoNr,

View File

@ -265,11 +265,6 @@
EncryptionKey = this.EncryptionKey.GetEncryptionKey(),
};
//if (this.Completed)
//{
// return features;
//}
features.Debug = new EregisterDebugFeatures();
features.ChangeMeterReading = this.DisplayVolume;
@ -301,10 +296,7 @@
features.Debug.ChangeState = FactoryState.Shipment;
}
// features.ChangeWakeUp = (WakeUpMode)this.Wake_Up_Interval;
// features.ChangeNumberOfLatWindows = this.LAT_Interval;
// features.ChangeTransmissionInterval = this.Transmission_Intervall;
features.OpenMeteringTransmitionIntervalWMBus = this.OMS_Interval;
features.ChangeRadioId = (uint)this.Adresse;
features.ChangeMeterId = this.MeterId;

View File

@ -12,7 +12,7 @@
internal class AppHost
{
public static readonly ILogger NLogger = CreateSIRTLogger();
public static readonly SIRTHub SIRTHub = CreateSIRTFactory();
public static readonly SIRTHub SIRTHub = CreateSIRTHub();
public static string GetSetting(string key)
=> Appsettings.GetSetting(key);
@ -44,7 +44,7 @@
return LogManager.GetLogger(name);
}
private static SIRTHub CreateSIRTFactory()
private static SIRTHub CreateSIRTHub()
{
var sirtHub = new SIRTHub();

View File

@ -51,11 +51,5 @@
return settingValue;
}
public static string[] GetSIRTComPorts()
=> GetSetting("SIRTComPorts")
?.Split(new[] { ';', ',', ' ' }, StringSplitOptions.RemoveEmptyEntries)
?.Select(x => x?.Trim())
?.ToArray() ?? new string[0];
}
}

View File

@ -6,14 +6,14 @@
{
public SIRTBroadcastersVM SIRTBroadcasterVM => new SIRTBroadcastersVM();
public EregisterHistoryVM EregisterHistoryVM { get; } = new EregisterHistoryVM();
public EregisterHistoryVM EregisterHistoryVM => new EregisterHistoryVM();
public EregisterInitializeVM EregisterInitializeVM { get; } = new EregisterInitializeVM();
public EregisterInitializeVM EregisterInitializeVM => new EregisterInitializeVM();
public EregisterFinalizeVM EregisterFinalizeVM { get; } = new EregisterFinalizeVM();
public EregisterFinalizeVM EregisterFinalizeVM => new EregisterFinalizeVM();
public ManualProgrammingVM ManualProgrammingVM { get; } = new ManualProgrammingVM();
public ManualProgrammingVM ManualProgrammingVM => new ManualProgrammingVM();
public SetMetrologyParametersVM SetMetrologyParametersVM { get; } = new SetMetrologyParametersVM();
public SetMetrologyParametersVM SetMetrologyParametersVM => new SetMetrologyParametersVM();
}
}

View File

@ -3,5 +3,5 @@
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
ShowsNavigationUI="False"
Source="Pages/EregisterInitialize.xaml"
Title="PAM 146: Set metrology parameters">
Title="Eregister Programierung">
</NavigationWindow>

View File

@ -98,7 +98,7 @@
.CreateCommand($@"
SELECT CAST((SELECT DISTINCT *
FROM VieweRegisterProgrammingParameters
WHERE SharedId = @{nameof(sharedId)}
WHERE SharedId = @{nameof(sharedId)} AND Completed = 0
FOR XML PATH('{nameof(EregisterProgrammingParameters)}')
, ROOT('{nameof(EregisterProgrammingParametersList)}')) AS XML)")
.SetParameter(nameof(sharedId), sharedId)

View File

@ -1,41 +1,20 @@
<Page x:Class="Common.UI.Pages.ManualProgramming"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:Controls="clr-namespace:Common.UI.Controls"
DataContext="{Binding ManualProgrammingVM, Source={StaticResource VMLocator}}"
FontFamily="Consolas"
FontSize="12">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<!-- SIRT COM ports - connect / disconnect / reconnect-->
<Controls:SIRTBroadcasters Background="#FFF0F0F0" Grid.Row="0" />
<Grid Grid.Row="1">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<Label Grid.Row="0" Grid.Column="0" Content="MHz" Padding="2 5 5 0" />
<TextBox Grid.Row="1" Grid.Column="0" Width="50" Margin="1" Padding="5" Text="{Binding Frequency}"/>
<Label Grid.Row="0" Grid.Column="1" Content="Seriennr" Padding="2 5 5 0" />
<TextBox Grid.Row="1" Grid.Column="1" Width="150" Margin="1" Padding="5" Text="{Binding SerienNr}"/>
<Label Grid.Row="0" Grid.Column="2" Content="Radio Adresse" Padding="2 5 5 0" />
<TextBox Grid.Row="1" Grid.Column="2" Width="150" Margin="1" Padding="5" Text="{Binding Address}"/>
<Button Grid.Row="1" Grid.Column="3" Content="In Versandmodus setzen" Margin="1" Padding="5" Cursor="Hand" Command="{Binding SetFactoryState}" IsEnabled="{Binding IsEnabled}" />
</Grid>
<!-- Pams & Programming -->
<ScrollViewer Grid.Row="2" HorizontalScrollBarVisibility="Auto" VerticalScrollBarVisibility="Auto">
<ItemsControl ItemsSource="{Binding ItemsSource}" Margin="10"/>
</ScrollViewer>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<ItemsControl ItemsSource="{Binding Messages}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Label Content="{Binding Key}" />
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</Grid>
</Page>

View File

@ -15,7 +15,6 @@
using System.Timers;
using System.Windows;
using System.Windows.Input;
using System.Windows.Media;
using SystemTimer = System.Timers.Timer;
public class EregisterInitializeVM : VM<EregisterInitializeVM>

View File

@ -1,212 +1,43 @@
namespace Common.UI.ViewModels
{
using Common.Hardware.SIRT;
using Common.Hardware.SIRT.Tasks;
using Common.Hardware.WaterMeter.eRegister;
using Common.Hardware.WaterMeter.eRegister.Features;
using Common.Hardware.WaterMeter.eRegister.Models;
using Common.UI.Infrastructure;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Net.Http;
using System.Reflection;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Input;
public class ManualProgrammingVM : VM<ManualProgrammingVM>
{
public int? Frequency { get; set; } = 433;
public uint? SerienNr { get; set; } = 22724224;
public uint? Address { get; set; } = 319017454;
private bool enabled = true;
public bool IsEnabled
public ManualProgrammingVM()
{
get => this.enabled;
set => this.SetValue(x => x.enabled = value);
this.Messages = new SortedDictionary<uint, SIRTMessage>();
}
public ICommand SetFactoryState => new Command(this.SetFactoryStateCommand);
public SortedDictionary<uint, SIRTMessage> Messages { get; }
public ObservableCollection<string> ItemsSource { get; set; } = new ObservableCollection<string>();
private void SetFactoryStateCommand()
internal override void ViewModel_Loaded(object _)
{
this.InvokeAsync(() => this.IsEnabled = false);
AppHost.SIRTHub.MessageReceived += SirtHub_MessageReceived;
Task.Factory.StartNew(async () =>
foreach (Match match in Regex.Matches(Appsettings.GetSetting("SIRTComPorts"), "[cC][oO][mM][0-9]+"))
{
void WriteToLog(string message) => this.InvokeAsync(() => this.ItemsSource.Add(message));
WriteToLog($"MHz| | {this.Frequency}");
WriteToLog($"Adr| |esse: {this.Address}");
WriteToLog($"Ser| |ienNr: {this.SerienNr}");
var uriFormat = Appsettings.GetSetting("EncryptionKeisUrl");
var httpClient = new HttpClient();
var encryptionKey = default(byte[]);
try
if (match.Success)
{
using (var httpResponeMessage = await httpClient.GetAsync(string.Format(uriFormat, this.SerienNr)))
{
var content = await httpResponeMessage.Content.ReadAsStringAsync();
if (httpResponeMessage?.IsSuccessStatusCode == true)
{
var _encryptionKey = content?.Trim('"');
encryptionKey = _encryptionKey?.GetEncryptionKey();
}
else
{
WriteToLog("Feh| |ler beim Laden des Schlüssels!");
}
}
}
catch (Exception e)
{
WriteToLog(e.Message);
return;
}
WriteToLog($"Enc| |ryption key: {BitConverter.ToString(encryptionKey)}");
var task = new EregisterTask(this.Frequency.Value)
{
Timeout = 10_000,
WakeUpCmd = true,
DelPamSemi = true,
WakeUpModul = true,
RequestAddress = this.Address.Value,
EncryptionKeyI = encryptionKey,
Data = new ChangeFactoryState
{
FactoryState = FactoryState.Production
}
.Append(new ProvidePin
{
AuthLevel = AuthLevel.III
})
};
void MessageReceived(byte[] bytes) => WriteToLog($"RX:| |{BitConverter.ToString(bytes)}");
task.MessageReceived += MessageReceived;
for (var i = 1; i <= 5 && task.State != SIRTTaskState.Completed && task.State != SIRTTaskState.Cancelled; i++)
{
if (AppHost.SIRTHub.Start(task))
{
WriteToLog($"---| |{i} -------------------------");
WriteToLog($"TX:| |{task}");
task.Wait();
}
}
task.MessageReceived -= MessageReceived;
WriteToLog($"---| |-----------------------------");
WriteToLog($"ST:| |{task.State}");
this.InvokeAsync(() => this.IsEnabled = true);
});
}
}
public class DynamicPropertyVM : VM<DynamicPropertyVM>
{
protected readonly Dictionary<string, DynamicPropertyVM> properties;
protected readonly PropertyInfo propertyInfo;
protected readonly object instance;
protected readonly object value;
public DynamicPropertyVM(object instance, PropertyInfo propertyInfo)
{
this.properties = new Dictionary<string, DynamicPropertyVM>();
this.propertyInfo = propertyInfo;
this.instance = instance;
if (this.propertyInfo != null)
{
this.Name = this.propertyInfo.Name;
this.value = Activator.CreateInstance(this.propertyInfo.PropertyType);
if (this.value is Pam pam)
{
this.Name = $"{pam.CmdHex} - {this.Name}";
Task.Run(() => AppHost.SIRTHub.TryOpen(match.Value.ToUpper(), out var _1, out var _2));
}
}
}
public event Action PropertyValueChanged;
public string Name { get; }
private bool selected;
public bool Selected
protected override void ViewModel_Dispose()
{
get => this.selected;
set => this.SetValue(x =>
{
x.selected = value;
var propertyValue = default(object);
if (x.selected)
{
propertyValue = this.value;
}
this.propertyInfo.SetValue(this.instance, propertyValue);
this.PropertyValueChanged?.Invoke();
});
AppHost.SIRTHub.MessageReceived -= SirtHub_MessageReceived;
}
public virtual IEnumerable<DynamicPropertyVM> GetAllProperties()
=> this.properties
.Values
.SelectMany(x => x.GetAllProperties())
.Union(this.properties.Values)
.OrderBy(x => x.Name);
}
public class DynamicTypeVM : DynamicPropertyVM
{
private readonly Type type;
public DynamicTypeVM(object instance) : base(instance, null)
private void SirtHub_MessageReceived(SIRTMessage message)
{
this.type = this.instance.GetType();
foreach (var propertyInfo in this.type.GetProperties(BindingFlags.Instance | BindingFlags.Public))
{
var pamAttribute = propertyInfo.GetCustomAttribute<PamAttribute>();
if (pamAttribute is null)
{
continue;
}
var dynamicProperty = new DynamicPropertyVM(this.instance, propertyInfo);
if (propertyInfo.PropertyType == typeof(EregisterDebugFeatures))
{
var propertyInstance = new EregisterDebugFeatures();
propertyInfo.SetValue(this.instance, propertyInstance);
dynamicProperty = new DynamicTypeVM(propertyInstance);
}
this.properties[propertyInfo.Name] = dynamicProperty;
}
this.Messages[message.Address] = message;
this.NotifyPropertyChanged(nameof(this.Messages));
}
}
}