This commit is contained in:
Thomas Wiedebusch
2025-04-01 09:55:43 +02:00
141 changed files with 5408 additions and 92199 deletions
@@ -21,7 +21,7 @@
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<NoWarn>IDE0003;IDE0049;</NoWarn>
<NoWarn>IDE0003;IDE0011;IDE0049;</NoWarn>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
@@ -32,7 +32,6 @@
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="Newtonsoft.Json, Version=6.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL" />
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Xml.Linq" />
@@ -56,15 +55,19 @@
<Compile Include="Parameters\SirtOperating.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="SIRTBroadcaster.cs" />
<Compile Include="SIRTChannel.cs" />
<Compile Include="SIRTConstants.cs" />
<Compile Include="SIRTExtensions.cs" />
<Compile Include="SIRTPort.cs" />
<Compile Include="SIRTFactory.cs" />
<Compile Include="SIRTHub.cs" />
<Compile Include="SIRTMessage.cs" />
<Compile Include="SIRTTask.Public.cs" />
<Compile Include="SIRTTaskState.cs" />
</ItemGroup>
<ItemGroup>
<Compile Include="SIRTTask.Internal.cs" />
<Compile Include="SIRTStream.cs" />
<Compile Include="Tasks\DeleteFromPamPoolTask.cs" />
<Compile Include="Tasks\ReadPamTask.cs" />
<Compile Include="Tasks\ReadRegisterTask.cs" />
<Compile Include="Tasks\SIRTTask.cs" />
<Compile Include="Tasks\SIRTTaskState.cs" />
<Compile Include="Tasks\WritePamTask.cs" />
<Compile Include="Tasks\WriteRegisterTask.cs" />
</ItemGroup>
<ItemGroup />
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
@@ -4,50 +4,20 @@
public class PAMStatus
{
private byte _byte;
private readonly byte[] bits;
public PAMStatus(byte _byte)
{
this._byte = _byte;
this.bits = _byte.GetBitsLE();
}
=> this.bits = _byte.GetBitsLE();
public bool IsOK
{
get => this._byte == 0;
set => this._byte = (byte)(value ? 0 : 0xFF);
}
public bool CMD_UNKNOWN => this.bits[0] == 1;
public bool CMD_UNKNOWN
{
get => this.bits[0] == 1;
set => this.bits[0] = (byte)(value ? 1 : 0);
}
public bool WRONG_AUTH => this.bits[1] == 1;
public bool WRONG_AUTH
{
get => this.bits[1] == 1;
set => this.bits[1] = (byte)(value ? 1 : 0);
}
public bool EXPIRED_AUTH => this.bits[2] == 1;
public bool EXPIRED_AUTH
{
get => this.bits[2] == 1;
set => this.bits[2] = (byte)(value ? 1 : 0);
}
public bool MIXED_TYPES => this.bits[3] == 1;
public bool MIXED_TYPES
{
get => this.bits[3] == 1;
set => this.bits[3] = (byte)(value ? 1 : 0);
}
public bool OUT_OF_RANGE
{
get => this.bits[4] == 1;
set => this.bits[4] = (byte)(value ? 1 : 0);
}
public bool OUT_OF_RANGE => this.bits[4] == 1;
public override string ToString()
{
@@ -1,383 +1,180 @@
namespace Common.Hardware.SIRT
{
using System.Collections.Concurrent;
using System.Threading.Tasks;
using System.Threading;
using System.Collections.Generic;
using System.Linq;
using Common.Hardware.SIRT.Tasks;
using System;
using System.IO.Ports;
using System.Collections.Concurrent;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
public class SIRTBroadcaster
{
private readonly ConcurrentDictionary<uint, ConcurrentQueue<SIRTTask>> tasks
= new ConcurrentDictionary<uint, ConcurrentQueue<SIRTTask>>();
private readonly ManualResetEventSlim tasksAwaiter = new ManualResetEventSlim();
private readonly SIRTPort serialPort;
private readonly ConcurrentDictionary<uint, SIRTChannel> requestChannels;
private readonly ConcurrentDictionary<uint, SIRTChannel> responseChannels;
private readonly SIRTStream sirtStream;
private CancellationTokenSource cancellationTokenSource;
private CancellationToken cancellationToken;
private Task processingTask;
private Task receiveStream;
public SIRTBroadcaster(string comPort)
public SIRTBroadcaster(string portName)
{
this.serialPort = new SIRTPort(comPort, 115200, Parity.None, 8, StopBits.One);
this.tasks = new ConcurrentDictionary<uint, ConcurrentQueue<SIRTTask>>();
this.PortName = portName;
this.sirtStream = new SIRTStream(this.PortName);
this.requestChannels = new ConcurrentDictionary<uint, SIRTChannel>();
this.responseChannels = new ConcurrentDictionary<uint, SIRTChannel>();
}
public event Action Activated;
public event Action Connected;
public event Action Disconnected;
public event Action<string> Logging;
public event Action<SIRTMessage> MessageReceived;
public event Action<SIRTBroadcaster> Connected;
public event Action<SIRTBroadcaster> Disconnected;
public event Action<object> StateLogging;
public event Action<SIRTMessage> MessageProcessed;
public string COMPort => this.serialPort.PortName;
public string PortName { get; }
public string HexId { get; protected set; }
public string Id { get; private set; }
public int Frequency { get; protected set; }
public int Frequency { get; private set; }
public bool IsConnected { get; protected set; }
public bool IsOpen => this.sirtStream.IsOpen;
public bool IsActivated { get; protected set; }
public void ClearChannels(uint requestAddress, uint responseAddress)
{
this.requestChannels.TryRemove(requestAddress, out _);
this.responseChannels.TryRemove(responseAddress, out _);
}
public void Close()
{
this.serialPort.Close();
this.sirtStream.Close();
this.HexId = null;
this.Frequency = 0;
this.serialPort.Connected -= this.SerialPort_Connected;
this.serialPort.Disconnected -= this.SerialPort_Disconnected;
this.serialPort.Logging -= this.SerialPort_Logging;
this.Activated -= this.StartProcessingTasksAsync;
this.MessageReceived -= this.SIRTConnection_MessageReceived;
this.sirtStream.Connected -= this.SirtStream_Connected;
this.sirtStream.Disconnected -= this.SirtStream_Disconnected;
this.sirtStream.StateLogging -= this.SirtStream_StateLogging;
}
public void Open()
{
this.serialPort.Connected += this.SerialPort_Connected;
this.serialPort.Disconnected += this.SerialPort_Disconnected;
this.serialPort.Logging += this.SerialPort_Logging;
this.Activated += this.StartProcessingTasksAsync;
this.MessageReceived += this.SIRTConnection_MessageReceived;
this.sirtStream.Connected += this.SirtStream_Connected;
this.sirtStream.Disconnected += this.SirtStream_Disconnected;
this.sirtStream.StateLogging += this.SirtStream_StateLogging;
this.serialPort.Open();
this.sirtStream.Open();
}
public void DequeueTasks(uint address)
public SIRTChannel CreateChannel(uint requestAddress, uint responseAddress, SIRTChannel channel = null)
{
if (this.tasks.TryRemove(address, out var tasksQueue))
if (channel is null)
{
while (tasksQueue.TryDequeue(out var task))
channel = new SIRTChannel
{
this.TaskRemoveEventHandlers(task);
RequestAddress = requestAddress,
ResponseAddress = responseAddress,
WriteHandler = this.Write
};
}
channel = this.requestChannels.GetOrAdd(requestAddress, channel);
channel = this.responseChannels.GetOrAdd(responseAddress, channel);
return channel;
}
public void Write(SIRTTask task)
{
if (task.Command != SIRTConstants.W_PAM || task.Frequency == this.Frequency)
{
task.Timestamp = DateTimeOffset.UtcNow;
task.Frequency = this.Frequency;
task.SirtId = this.Id;
var bytes = task.Run();
this.sirtStream.Write(bytes);
this.MessageProcessed?.Invoke(task);
}
}
private void ReceiveAsync()
{
foreach (SIRTMessage message in this.sirtStream.Read())
{
message.Timestamp = DateTimeOffset.UtcNow;
message.Frequency = this.Frequency;
message.SirtId = this.Id;
if (this.requestChannels.TryGetValue(message.Address, out var channel) || this.responseChannels.TryGetValue(message.Address, out channel))
{
channel.Enqueue(message);
}
this.MessageProcessed?.Invoke(message);
if (this.cancellationToken.IsCancellationRequested)
{
break;
}
}
}
public void EnqueueTask(SIRTTask task)
private void SirtStream_Connected(SIRTStream sirtStream)
{
if (this.Frequency == task.Frequency)
if (sirtStream.IsOpen)
{
this.TaskAddEventHandlers(task);
this.cancellationTokenSource = new CancellationTokenSource();
this.cancellationToken = this.cancellationTokenSource.Token;
this.receiveStream = Task
.Run((Action)this.ReceiveAsync, this.cancellationToken)
.ContinueWith(task =>
{
if (task?.Exception != null)
{
this.Invoke_StateLogging(task.Exception);
}
});
var requestTasks = this.tasks.GetOrAdd(task.RequestAddress, new ConcurrentQueue<SIRTTask>());
requestTasks.Enqueue(task);
if (task.RequestAddress != task.ResponseAddress)
if (this.TryActivate2(out var id, out var frequency))
{
this.tasks.AddOrUpdate(task.ResponseAddress, requestTasks, (_, _requestTasks) => _requestTasks);
}
}
}
this.Id = id;
this.Frequency = frequency;
private void ActivateSIRT()
{
if (this.TryRun(SIRTTask.ActivateSIRT, x => x.State == SIRTTaskState.Completed))
{
var response = this.TryRun(SIRTTask.IdentifySIRT, x => x.Last);
if (response?.Length == 8)
{
this.HexId = BitConverter.ToString(response);
this.Frequency = this.HexId[10] == '0' ? 868 : 433;
this.Activated?.Invoke();
this.Connected?.Invoke(this);
}
else
{
this.Logging?.Invoke($"SIRT on {this.COMPort} not identified.");
this.Close();
}
}
else
{
this.Logging?.Invoke($"SIRT on {this.COMPort} not activated.");
}
}
private void ExceptionLogging(Task task)
private void SirtStream_Disconnected(SIRTStream sirtStream)
{
if (task.Exception != null)
{
this.Logging?.Invoke(task.Exception.ToString());
}
}
private ICollection<uint> GetAddressesInPamPool()
{
var addresses = new List<uint>();
var task = SIRTTask.ReadPamPool;
if (this.TryRun(task))
{
var payload = task.Last;
if (payload?.Length == 20)
{
var _address = 0U;
for (var i = 0; i < 20; i += 4)
{
_address = payload.ToUInt32BE(i);
if (_address != uint.MinValue && _address != uint.MaxValue)
{
addresses.Add(_address);
}
}
}
}
return addresses;
}
private void OnStateChanged(SIRTTask task)
{
this.TaskRemoveEventHandlers(task);
if (task.State == SIRTTaskState.Completed)
{
if (this.tasks.TryGetValue(task.RequestAddress, out var tasks) && tasks.TryPeek(out var _task) && _task.State == SIRTTaskState.Completed)
{
tasks.TryDequeue(out _task);
}
if (task.RequestAddress != task.ResponseAddress)
{
if (this.tasks.TryGetValue(task.ResponseAddress, out tasks) && tasks.TryPeek(out _task) && _task.State == SIRTTaskState.Completed)
{
tasks.TryDequeue(out _task);
}
}
}
else if (task.State == SIRTTaskState.Cancelled)
{
this.OnTaskTimeout(task);
}
}
private void OnTaskTimeout(SIRTTask task)
{
var deleteRequestAddress = SIRTTask.DeleteFromPamPool(task.RequestAddress);
this.TryRun(deleteRequestAddress);
var deleteResponseAddress = SIRTTask.DeleteFromPamPool(task.ResponseAddress);
this.TryRun(deleteResponseAddress);
}
private void SerialPort_Connected()
{
this.IsConnected = true;
this.cancellationTokenSource = new CancellationTokenSource();
this.cancellationToken = this.cancellationTokenSource.Token;
Task.Factory
.StartNew(this.StartReadingMessages, this.cancellationToken)
.ContinueWith(this.ExceptionLogging);
Task.Factory
.StartNew(this.ActivateSIRT, this.cancellationToken)
.ContinueWith(this.ExceptionLogging);
this.Connected?.Invoke();
}
private void SerialPort_Disconnected()
{
this.IsActivated = false;
this.IsConnected = false;
try
{
this.cancellationTokenSource?.Cancel();
this.cancellationTokenSource.Cancel();
}
catch (Exception e)
{
this.SerialPort_Logging(e.ToString());
this.SirtStream_StateLogging(e);
}
this.Disconnected?.Invoke();
}
private void SerialPort_Logging(string e) => this.Logging?.Invoke(e);
private void SIRTConnection_MessageReceived(SIRTMessage message)
{
if (this.tasks.TryGetValue(message.Address, out var tasksQueue))
try
{
if (tasksQueue.TryPeek(out var task))
{
task.PushResponse(message);
this.Logging?.Invoke(message.ToString());
}
this.requestChannels.Clear();
this.responseChannels.Clear();
}
}
private void StartProcessingTasksAsync()
{
this.IsActivated = true;
this.processingTask = Task.Factory.StartNew(async () =>
catch (Exception e)
{
while (!this.cancellationToken.IsCancellationRequested)
{
foreach (var tasksQueue in this.tasks.Values.ToArray())
{
if (tasksQueue.TryPeek(out var task) && task.State == SIRTTaskState.Pending)
{
this.serialPort.Write(task.Start());
this.Logging?.Invoke(task.ToString());
}
await Task.Delay(10);
}
await Task.Delay(10);
}
}
, this.cancellationToken
, TaskCreationOptions.LongRunning
, TaskScheduler.Current)
.ContinueWith(this.ExceptionLogging);
}
private void StartReadingMessages()
{
var buffer = new List<byte>();
int bufferLength;
int startIX;
int lengthIX;
int dataLength;
int stopIX;
int messageLength;
byte[] message;
foreach (var bytes in this.serialPort.ReadBytes())
{
if (bytes?.Length > 0)
{
buffer.AddRange(bytes);
}
bufferLength = buffer.Count;
while (bufferLength >= 13)
{
startIX = buffer.IndexOf(SIRTMessage.SIRT2PC);
if (startIX < 0)
{
buffer.Clear();
break;
}
lengthIX = startIX + 8;
if (lengthIX >= bufferLength)
{
break;
}
dataLength = buffer[lengthIX];
stopIX = lengthIX + dataLength + 3;
if (stopIX >= bufferLength)
{
break;
}
else if (buffer[stopIX] != SIRTMessage.STOP)
{
buffer.RemoveRange(0, stopIX + 1);
}
else
{
messageLength = stopIX - startIX + 1;
message = new byte[messageLength];
buffer.CopyTo(startIX, message, 0, messageLength);
buffer.RemoveRange(0, startIX + messageLength);
this.MessageReceived?.Invoke(new SIRTMessage(message));
}
bufferLength = buffer.Count;
}
}
}
private void TaskAddEventHandlers(SIRTTask task)
{
task.Cancelled += this.OnStateChanged;
task.Completed += this.OnStateChanged;
task.Timeouted += this.OnTaskTimeout;
}
private void TaskRemoveEventHandlers(SIRTTask task)
{
task.Cancelled -= this.OnStateChanged;
task.Completed -= this.OnStateChanged;
task.Timeouted -= this.OnTaskTimeout;
this.tasksAwaiter.Set();
}
private bool TryRun<TTask>(TTask task) where TTask : SIRTTask
=> this.TryRun(task, x => x.State == SIRTTaskState.Completed);
private TResult TryRun<TTask, TResult>(TTask task, Func<TTask, TResult> result) where TTask : SIRTTask
{
var manualResetEventSlim = new ManualResetEventSlim();
void taskStateChanged(SIRTTask _)
=> manualResetEventSlim.Set();
void messageReceived(SIRTMessage message)
{
if (message.Address == task.RequestAddress)
{
task.PushResponse(message);
}
this.SirtStream_StateLogging(e);
}
this.MessageReceived += messageReceived;
task.Cancelled += taskStateChanged;
task.Completed += taskStateChanged;
this.serialPort.Write(task.Start());
manualResetEventSlim.Wait(task.Timeout);
manualResetEventSlim.Reset();
task.Cancelled += taskStateChanged;
task.Completed += taskStateChanged;
this.MessageReceived -= messageReceived;
return result(task);
this.Disconnected?.Invoke(this);
}
private void SirtStream_StateLogging(object error)
=> this.Invoke_StateLogging(error);
private void Invoke_StateLogging(object state, [CallerMemberName] string member = "")
=> this.StateLogging?.Invoke($"{nameof(SIRTBroadcaster)}|{member}|{this.PortName}|{state}");
}
}
@@ -0,0 +1,20 @@
namespace Common.Hardware.SIRT
{
using Common.Hardware.SIRT.Tasks;
using System;
public class SIRTChannel
{
public event Action<SIRTMessage> MessageReceived;
public uint RequestAddress { get; set; }
public uint ResponseAddress { get; set; }
public Action<SIRTTask> WriteHandler { get; internal set; }
internal void Enqueue(SIRTMessage message)
=> this.MessageReceived?.Invoke(message);
}
}
@@ -0,0 +1,31 @@
namespace Common.Hardware.SIRT
{
public class SIRTConstants
{
public const byte W_PAM = 0x81;
public const byte R_PAM = 0x82;
public const byte W_REG = 0x84;
public const byte R_REG = 0x87;
public const byte MIN_LEN = 12;
public const byte PC_SIRT = 0x55;
public const byte SIRT_PC = 0xFF;
public const byte MSG_END = 0x16;
public const byte DIR_IX = 0;
public const byte CMD_IX = 1;
public const byte P1_IX = 2;
public const byte P2_IX = 3;
public const byte ADDR_IX = 4;
public const byte LEN_IX = 8;
public const byte DATA_IX = 9;
public static byte ACKN_ANSW = 0x12;
public static byte FROM_AIR = 0x11;
public static byte LAT = 0x01;
public static byte BUP = 0x00;
public static byte DEBUG = 0x0B;
public static byte SEMI = 0x08;
}
}
@@ -1,8 +1,12 @@
namespace Common.Hardware.SIRT
{
using Common.Hardware.SIRT.Parameters;
using Common.Hardware.SIRT.Tasks;
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Threading;
public static class SIRTExtensions
{
@@ -578,5 +582,209 @@
return bytes;
}
public static uint GetAddress(this byte[] bytes, int index)
{
var value = default(uint);
var _index = index;
value ^= (uint)(bytes[_index++] << 24);
value ^= (uint)(bytes[_index++] << 16);
value ^= (uint)(bytes[_index++] << 8);
value ^= bytes[_index];
return value;
}
public static ushort GetCrc(this byte[] bytes, int index)
{
var value = default(ushort);
var _index = index;
value ^= (ushort)(bytes[_index++] << 8);
value ^= bytes[_index];
return value;
}
public static void SetAddress(this byte[] bytes, int index, uint address)
{
var _index = index;
bytes[_index++] = (byte)(address >> 24);
bytes[_index++] = (byte)(address >> 16);
bytes[_index++] = (byte)(address >> 8);
bytes[_index] = (byte)address;
}
public static void SetCrc(this byte[] bytes, int index, ushort crc)
{
var _index = index;
bytes[_index++] = (byte)(crc >> 8);
bytes[_index] = (byte)crc;
}
public static bool TryActivate(this SIRTBroadcaster sirtBroadcaster, out string id, out int frequency)
{
id = default(string);
frequency = default(int);
var waitHandle = new ManualResetEventSlim();
var activationTask = new WriteRegisterTask
{
RequestAddress = 0x20000000,
ResponseAddress = 0x20000000,
Payload = new byte[]
{
new SirtOperating { /* default */ },
new BluetoothOperating { BtOff = true },
new RFModuleOperating { RfOff = true },
new RFModuleOperating { OpMode = OperatingModes.ReceiveF1TransmitSensusRFF3 },
new PamTimeout { Minutes = 1 }
}
};
var activationCompleted = false;
activationTask.StateChanged += task =>
{
activationCompleted = task.State == SIRTTaskState.Completed;
waitHandle.Set();
};
var channel = sirtBroadcaster.CreateChannel(activationTask.RequestAddress, activationTask.ResponseAddress);
for (var i = 0; i < 10 && !activationCompleted; i++)
{
sirtBroadcaster.Write(activationTask);
waitHandle.Wait(3000);
waitHandle.Reset();
}
var identifyTask = new ReadRegisterTask
{
RequestAddress = 0x11001820,
ResponseAddress = 0x11001820,
Length = 0x08
};
var identifyCompleted = false;
identifyTask.StateChanged += task =>
{
identifyCompleted = task.State == SIRTTaskState.Completed;
waitHandle.Set();
};
for (var i = 0; i < 10 && !identifyCompleted; i++)
{
sirtBroadcaster.Write(identifyTask);
waitHandle.Wait(3000);
waitHandle.Reset();
}
if (identifyCompleted)
{
id = BitConverter.ToString(identifyTask.Payload);
frequency = id[10] == '0' ? 868 : 433;
}
return activationCompleted && identifyCompleted;
}
public static bool TryActivate2(this SIRTBroadcaster sirtBroadcaster, out string id, out int frequency)
{
id = default(string);
frequency = default(int);
var task = default(SIRTTask);
var channel = default(SIRTChannel);
var waitEvent = new ManualResetEventSlim();
var done = false;
void messageReceived(SIRTMessage message)
=> task.Push(message);
task = new WriteRegisterTask
{
RequestAddress = 0x20000000,
ResponseAddress = 0x20000000,
Payload = new byte[]
{
new SirtOperating { /* default */ },
new BluetoothOperating { BtOff = true },
new RFModuleOperating { RfOff = true },
new RFModuleOperating { OpMode = OperatingModes.ReceiveF1TransmitSensusRFF3 },
new PamTimeout { Minutes = 1 }
}
};
task.StateChanged += _task =>
{
done = task.State == SIRTTaskState.Completed;
if (done)
{
waitEvent.Set();
}
};
channel = sirtBroadcaster.CreateChannel(task.RequestAddress, task.ResponseAddress);
channel.MessageReceived += messageReceived;
for (var i = 0; i < 10 && !done; i++)
{
sirtBroadcaster.Write(task);
waitEvent.Wait(3000);
waitEvent.Reset();
}
channel.MessageReceived -= messageReceived;
sirtBroadcaster.ClearChannels(task.RequestAddress, task.ResponseAddress);
if (!done)
{
return false;
}
waitEvent.Wait(100);
waitEvent.Reset();
done = false;
task = new ReadRegisterTask
{
RequestAddress = 0x11001820,
ResponseAddress = 0x11001820,
Length = 0x08
};
task.StateChanged += _task =>
{
done = task.State == SIRTTaskState.Completed;
if (done)
{
waitEvent.Set();
}
};
channel = sirtBroadcaster.CreateChannel(task.RequestAddress, task.ResponseAddress);
channel.MessageReceived += messageReceived;
for (var i = 0; i < 10 && !done; i++)
{
sirtBroadcaster.Write(task);
waitEvent.Wait(3000);
waitEvent.Reset();
}
channel.MessageReceived -= messageReceived;
sirtBroadcaster.ClearChannels(task.RequestAddress, task.ResponseAddress);
if (done && task is ReadRegisterTask rtask)
{
id = BitConverter.ToString(rtask.Payload);
frequency = id[10] == '0' ? 868 : 433;
}
return done;
}
}
}
@@ -1,104 +0,0 @@
namespace Common.Hardware.SIRT
{
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
public class SIRTFactory
{
private static readonly List<Action<SIRTMessage>> messageReceivedHandlers
= new List<Action<SIRTMessage>>();
private readonly ConcurrentDictionary<string, SIRTBroadcaster> broadcasters
= new ConcurrentDictionary<string, SIRTBroadcaster>();
public event Action<string> Logging;
public void CloseConnection(string portName)
{
if (this.broadcasters.TryGetValue(portName, out var broadcaster))
{
broadcaster.Logging -= this.NotifyMessage;
foreach (var handler in messageReceivedHandlers)
{
broadcaster.MessageReceived -= handler;
}
broadcaster.Close();
}
}
public void DequeueTasks(uint address)
{
foreach (var broadcaster in this.GetConnections())
{
broadcaster.DequeueTasks(address);
}
}
public SIRTBroadcaster ConnectSIRT(string portName)
{
if (!this.broadcasters.TryGetValue(portName, out var broadcaster))
{
broadcaster = new SIRTBroadcaster(portName);
broadcaster.Logging += this.NotifyMessage;
foreach (var handler in messageReceivedHandlers)
{
broadcaster.MessageReceived += handler;
}
if (!this.broadcasters.TryAdd(portName, broadcaster))
{
this.NotifyMessage($"Cannot add SIRT on {portName}");
broadcaster = null;
}
}
if (broadcaster != null)
{
broadcaster?.Close();
broadcaster?.Open();
}
return broadcaster;
}
public void EnqueueTask(SIRTTask task)
{
foreach (var broadcaster in this.GetConnections())
{
broadcaster.EnqueueTask(task);
}
}
public void RemoveConnections()
{
foreach (var key in this.broadcasters.Keys.ToArray())
{
if (this.broadcasters.TryRemove(key, out var broadcaster))
{
broadcaster.Close();
broadcaster.Logging -= this.NotifyMessage;
}
}
}
private IEnumerable<SIRTBroadcaster> GetConnections()
=> this.broadcasters.Values.ToArray();
private void NotifyMessage(string message)
=> this.Logging?.Invoke(message);
public static void AddMessageReceivedHandler(Action<SIRTMessage> handler)
{
if (handler != null)
{
messageReceivedHandlers.Add(handler);
}
}
}
}
@@ -0,0 +1,143 @@
namespace Common.Hardware.SIRT
{
using Common.Hardware.SIRT.Tasks;
using System;
using System.Collections.Concurrent;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Threading;
public class SIRTHub
{
private static readonly ConcurrentDictionary<string, SIRTBroadcaster> broadcasters
= new ConcurrentDictionary<string, SIRTBroadcaster>();
public event Action<SIRTBroadcaster> Connected;
public event Action<SIRTBroadcaster> Disconnected;
public event Action<object> StateLogging;
public event Action<SIRTMessage> MessageProcessed;
public void ClearChannels(uint requestAddress, uint responseAddress)
{
foreach (var broadcaster in broadcasters.Values)
{
broadcaster.ClearChannels(requestAddress, responseAddress);
}
}
public void Close(string portName)
{
if (broadcasters.TryRemove(portName, out var sirtBroadcaster))
{
var disconnectedEvent = new ManualResetEventSlim();
void SIRTBroadcaster_Disconnected(SIRTBroadcaster _sirtBroadcaster)
{
disconnectedEvent.Set();
this.Disconnected?.Invoke(_sirtBroadcaster);
}
sirtBroadcaster.Disconnected += SIRTBroadcaster_Disconnected;
sirtBroadcaster.Close();
disconnectedEvent.Wait(3000);
sirtBroadcaster.Disconnected -= SIRTBroadcaster_Disconnected;
sirtBroadcaster.StateLogging -= this.Invoke_StateLogging;
sirtBroadcaster.MessageProcessed -= this.Invoke_MessageProcessed;
}
}
public SIRTChannel CreateChannel(int frequency, uint requestAddress, uint responseAddress)
{
var channel = default(SIRTChannel);
foreach (var broadcaster in broadcasters.Values)
{
if (broadcaster.Frequency == frequency)
{
channel = broadcaster.CreateChannel(requestAddress, responseAddress, channel);
}
}
return channel;
}
public bool TryOpen(string portName, out string hexId, out string frequency)
{
hexId = default(string);
frequency = default(string);
var connectedEvent = new ManualResetEventSlim();
var sirtBroadcaster = new SIRTBroadcaster(portName);
void SIRTBroadcaster_Connected(SIRTBroadcaster _)
{
broadcasters.GetOrAdd(portName, sirtBroadcaster);
connectedEvent.Set();
this.Connected?.Invoke(sirtBroadcaster);
}
void SIRTBroadcaster_Disconnected(SIRTBroadcaster _)
{
// broadcasters.TryRemove(portName, out sirtBroadcaster);
connectedEvent.Set();
this.Disconnected?.Invoke(sirtBroadcaster);
}
sirtBroadcaster.Connected += SIRTBroadcaster_Connected;
sirtBroadcaster.Disconnected += SIRTBroadcaster_Disconnected;
sirtBroadcaster.Open();
connectedEvent.Wait(3000);
hexId = sirtBroadcaster.Id;
frequency = sirtBroadcaster.Frequency.ToString();
sirtBroadcaster.Connected -= SIRTBroadcaster_Connected;
sirtBroadcaster.StateLogging += this.Invoke_StateLogging;
sirtBroadcaster.MessageProcessed += this.Invoke_MessageProcessed;
return sirtBroadcaster.IsOpen;
}
public void Run(SIRTTask task)
{
foreach (var broadcaster in broadcasters.Values)
{
broadcaster.Write(task);
}
}
public void Stop()
{
try
{
foreach (var broadcaster in broadcasters.Values.ToList())
{
broadcaster.Close();
}
broadcasters.Clear();
}
catch (Exception e)
{
this.Invoke_StateLogging(e);
}
}
private void Invoke_StateLogging(object state)
=> this.StateLogging?.Invoke($"{nameof(SIRTHub)}|{state}");
private void Invoke_StateLogging(object state, [CallerMemberName] string member = "")
=> this.StateLogging?.Invoke($"{nameof(SIRTHub)}|{member}|{state}");
private void Invoke_MessageProcessed(SIRTMessage message)
=> this.MessageProcessed?.Invoke(message);
}
}
@@ -1,161 +1,123 @@
namespace Common.Hardware.SIRT
{
using Common.Hardware.SIRT.Parameters;
using System;
using static SIRTConstants;
public class SIRTMessage
{
public const byte MIN_LEN = 12;
public const byte PC2SIRT = 0x55;
public const byte SIRT2PC = 0xFF;
public const byte W_PAM = 0x81;
public const byte R_PAM = 0x82;
public const byte W_REG = 0x84;
public const byte R_REG = 0x87;
public const byte FROMAIR = 0x11;
public const byte ACKNANSW = 0x12;
public const byte STOP = 0x16;
public const byte BUP = 0x00;
public const byte LAT = 0x01;
public const byte DEBUG = 0x0B;
public const byte SEMI = 0x08;
private byte[] bytes;
public SIRTMessage()
{
this.bytes = new byte[MIN_LEN];
this.Start = PC2SIRT;
this.Stop = STOP;
this.bytes[0] = PC_SIRT;
}
public SIRTMessage(byte[] bytes) : this()
public SIRTMessage(byte[] bytes)
=> this.bytes = bytes;
public byte Start
public byte Direction
{
get => this.bytes[0];
set => this.bytes[0] = value;
get => this.bytes[DIR_IX];
set => this.bytes[DIR_IX] = value;
}
public byte Cmd
public byte Command
{
get => this.bytes[1];
set => this.bytes[1] = value;
get => this.bytes[CMD_IX];
set => this.bytes[CMD_IX] = value;
}
public byte P1
{
get => this.bytes[2];
set => this.bytes[2] = value;
get => this.bytes[P1_IX];
set => this.bytes[P1_IX] = value;
}
public byte P2
{
get => this.bytes[3];
set => this.bytes[3] = value;
get => this.bytes[P2_IX];
set => this.bytes[P2_IX] = value;
}
public uint Address
{
get => this.bytes.ToUInt32BE(4);
set => value.GetBytesBE().CopyTo(this.bytes, 4);
get => this.bytes.GetAddress(ADDR_IX);
set => this.bytes.SetAddress(ADDR_IX, value);
}
public byte Length
{
get => this.bytes[8];
set => this.bytes[8] = value;
get => this.bytes[LEN_IX];
set => this.bytes[LEN_IX] = value;
}
public byte[] Data
public byte[] Payload
{
get
{
var data = new byte[this.Length];
var payload = new byte[this.Length];
Array.Copy(this.bytes, 9, data, 0, this.Length);
Array.Copy(bytes, DATA_IX, payload, 0, this.Length);
return data;
return payload;
}
set
{
if (value is null)
{
value = new byte[0];
}
this.bytes[8] = (byte)value.Length;
var payload = value ?? Array.Empty<byte>();
this.Length = (byte)payload.Length;
Array.Resize(ref this.bytes, MIN_LEN + this.Length);
Array.Clear(this.bytes, 9, this.bytes.Length - 9);
Array.Copy(value, 0, this.bytes, 9, this.Length);
Array.Clear(this.bytes, DATA_IX, this.bytes.Length - DATA_IX);
Array.Copy(payload, 0, this.bytes, DATA_IX, this.Length);
}
}
public ushort CRC
public ushort Crc
{
get => this.bytes.ToUInt16BE(this.bytes.Length - 3);
set => value.GetBytesBE().CopyTo(this.bytes, this.bytes.Length - 3);
get => this.bytes.GetCrc(this.bytes.Length - 3);
set => this.bytes.SetCrc(this.bytes.Length - 3, value);
}
public byte Stop
public byte End
{
get => this.bytes[this.bytes.Length - 1];
set => this.bytes[this.bytes.Length - 1] = value;
}
public bool IsValid { get; private set; } = true;
public string SirtId { get; set; }
public int Frequency { get; set; }
public DateTimeOffset Timestamp { get; set; } = DateTimeOffset.UtcNow;
public override string ToString()
=> $"{this.Timestamp}|{this.SirtId}|{this.Frequency}|{BitConverter.ToString(this.GetBytes())}";
public byte[] GetBytes()
{
this.CRC = this.bytes.CRCCCITT(1, this.bytes.Length - 3);
this.Stop = STOP;
var crc = this.bytes.CRCCCITT(1, this.bytes.Length - 3);
if (this.Direction == PC_SIRT)
{
this.Crc = crc;
this.End = MSG_END;
}
else
{
this.IsValid = this.Crc == crc;
}
return this.bytes;
}
public override string ToString()
=> BitConverter.ToString(this.bytes);
public static implicit operator byte[] (SIRTMessage message)
=> message.bytes;
public static implicit operator SIRTMessage(byte[] bytes)
=> new SIRTMessage(bytes);
internal static SIRTMessage Activate = new SIRTMessage
{
Cmd = W_REG,
Address = 0x20000000,
P2 = 0x05,
Data = new byte[]
{
new SirtOperating { /* default */ },
new BluetoothOperating { BtOff = true },
new RFModuleOperating { RfOff = true },
new RFModuleOperating { OpMode = OperatingModes.ReceiveF1TransmitSensusRFF3 },
new PamTimeout { Minutes = 1 }
}
};
internal static SIRTMessage Identify = new SIRTMessage
{
Cmd = SIRTMessage.R_REG,
Address = 0x11001820,
P2 = 0x08
};
internal static readonly SIRTMessage ReadPamPool = new SIRTMessage
{
Cmd = R_PAM,
Address = 0xFFFFFFFF
};
internal static SIRTMessage DeleteFromPamPool(uint address) => new SIRTMessage
{
Cmd = W_PAM,
P1 = new P811 { DelPamAdr = true },
Address = address
};
public static implicit operator byte[] (SIRTMessage message)
=> message?.GetBytes() ?? Array.Empty<byte>();
}
}
}
@@ -1,145 +0,0 @@
namespace Common.Hardware.SIRT
{
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO.Ports;
using System.Threading;
public sealed class SIRTPort
{
private static readonly ConcurrentDictionary<string, SerialPort> serialPorts
= new ConcurrentDictionary<string, SerialPort>();
private readonly int baudRate;
private readonly Parity parity;
private readonly int dataBits;
private readonly StopBits stopBits;
public SIRTPort(string portName, int baudRate, Parity parity, int dataBits, StopBits stopBits)
{
this.PortName = portName;
this.baudRate = baudRate;
this.parity = parity;
this.dataBits = dataBits;
this.stopBits = stopBits;
}
public event Action Connected;
public event Action Disconnected;
public event Action<string> Logging;
public string PortName { get; }
public void Close()
{
try
{
var awaiter = new ManualResetEventSlim();
var sp = this.GetOrAddSerialPort();
void disposed(object _, EventArgs _1)
=> awaiter.Set();
sp.Disposed += disposed;
sp.Close();
awaiter.Wait(5000);
sp.Disposed -= disposed;
this.Disconnected?.Invoke();
}
catch (Exception e)
{
this.Logging?.Invoke(e.ToString());
}
serialPorts.TryRemove(this.PortName, out var _);
}
public void Open()
{
var sp = this.GetOrAddSerialPort();
if (sp?.IsOpen == true)
{
this.Close();
}
try
{
sp.Open();
this.Connected?.Invoke();
}
catch (Exception e)
{
this.Logging?.Invoke(e.ToString());
}
}
public IEnumerable<byte[]> ReadBytes()
{
var receiveEvent = new ManualResetEventSlim();
void dataReceived(object _, SerialDataReceivedEventArgs args)
{
if (args.EventType == SerialData.Chars)
{
receiveEvent.Set();
}
}
var sp = this.GetOrAddSerialPort();
sp.DataReceived += dataReceived;
var size = sp.ReadBufferSize;
var buffer = new byte[size];
var length = 0;
while (sp?.IsOpen == true)
{
if (!receiveEvent.IsSet)
{
receiveEvent.Wait();
receiveEvent.Reset();
}
try
{
buffer = new byte[size];
length = sp.Read(buffer, 0, size);
Array.Resize(ref buffer, length);
}
catch (Exception e)
{
this.Logging?.Invoke(e.ToString());
}
receiveEvent.Reset();
yield return buffer;
}
sp.DataReceived -= dataReceived;
}
public void Write(byte[] bytes)
{
try
{
this.GetOrAddSerialPort().Write(bytes, 0, bytes.Length);
}
catch (Exception e)
{
this.Logging?.Invoke(e.ToString());
}
}
private SerialPort GetOrAddSerialPort()
=> serialPorts.GetOrAdd(this.PortName, new SerialPort(this.PortName, this.baudRate, this.parity, this.dataBits, this.stopBits));
public static string[] GetPortNames()
=> SerialPort.GetPortNames();
}
}
@@ -0,0 +1,187 @@
namespace Common.Hardware.SIRT
{
using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Runtime.CompilerServices;
using System.Threading;
public sealed class SIRTStream
{
private readonly SerialPort serialPort;
public SIRTStream(string portName)
=> this.serialPort = new SerialPort(portName, 112500, Parity.None, 8, StopBits.One);
public event Action<SIRTStream> Connected;
public event Action<SIRTStream> Disconnected;
public event Action<object> StateLogging;
public bool IsOpen => this.serialPort.IsOpen;
public void Close()
{
var disposeEvent = new ManualResetEventSlim();
void SerialPort_Disposed(object sender, EventArgs args)
{
disposeEvent.Set();
}
this.serialPort.Disposed += SerialPort_Disposed;
try
{
this.serialPort.Close();
disposeEvent.Wait(5000);
}
catch (Exception e)
{
this.Invoke_StateLogging(e);
}
this.serialPort.Disposed -= SerialPort_Disposed;
this.Disconnected?.Invoke(this);
}
public void Open()
{
this.Close();
try
{
this.serialPort.Open();
this.Connected?.Invoke(this);
}
catch (Exception e)
{
this.Invoke_StateLogging(e);
this.Disconnected?.Invoke(this);
}
}
public IEnumerable<byte[]> Read()
{
var receiveEvent = new ManualResetEventSlim();
void SerialPort_DataReceived(object sender, SerialDataReceivedEventArgs args)
{
if (args.EventType == SerialData.Chars)
{
receiveEvent.Set();
}
}
this.serialPort.DataReceived += SerialPort_DataReceived;
// read variables
var receiveBuffer = new List<byte>();
var receiveBufferCount = default(int);
var readBuffer = default(byte[]);
var readLength = default(int);
// message variables
var startIndex = default(int);
var lengthIndex = default(int);
var length = default(int);
var endIndex = default(int);
var messageLength = default(int);
var message = default(byte[]);
while (this.serialPort.IsOpen)
{
if (!receiveEvent.IsSet)
{
receiveEvent.Wait();
receiveEvent.Reset();
}
try
{
readBuffer = new byte[this.serialPort.ReadBufferSize];
readLength = this.serialPort.Read(readBuffer, 0, readBuffer.Length);
Array.Resize(ref readBuffer, readLength);
receiveBuffer.AddRange(readBuffer);
}
catch (Exception e)
{
this.Invoke_StateLogging(e);
}
receiveBufferCount = receiveBuffer.Count;
while (receiveBufferCount > 0)
{
if (startIndex < 0)
{
startIndex = 0;
}
startIndex = receiveBuffer.IndexOf(SIRTConstants.SIRT_PC, startIndex);
// when no start byte found clear and break
if (startIndex < 0)
{
receiveBuffer.Clear();
break;
}
lengthIndex = startIndex + SIRTConstants.LEN_IX;
// when not enough bytes for the length just break
if (lengthIndex >= receiveBufferCount)
{
break;
}
length = receiveBuffer[lengthIndex];
endIndex = lengthIndex + length + 3;
// when not enough bytes for the end just break
if (endIndex >= receiveBufferCount)
{
break;
}
// when message end not 0x16 try again with next start index
if (receiveBuffer[endIndex] != SIRTConstants.MSG_END)
{
startIndex++;
continue;
}
messageLength = endIndex - startIndex + 1;
message = new byte[messageLength];
receiveBuffer.CopyTo(startIndex, message, 0, messageLength);
receiveBuffer.RemoveRange(0, endIndex + 1);
yield return message;
receiveBufferCount = receiveBuffer.Count;
}
}
this.serialPort.DataReceived -= SerialPort_DataReceived;
}
public void Write(byte[] bytes)
{
try
{
this.serialPort.Write(bytes, 0, bytes.Length);
}
catch (Exception e)
{
this.Invoke_StateLogging(e);
}
}
private void Invoke_StateLogging(object state, [CallerMemberName] string member = "")
=> this.StateLogging?.Invoke($"{nameof(SIRTStream)}|{member}|{this.serialPort.PortName}|{state}");
}
}
@@ -1,76 +0,0 @@
namespace Common.Hardware.SIRT
{
using Common.Hardware.SIRT.Parameters;
using System;
public partial class SIRTTask
{
internal byte[] Start()
{
if (this.State != SIRTTaskState.Cancelled)
{
this.State = SIRTTaskState.Running;
this.timeoutTimer.Stop();
this.timeoutTimer.Start();
return this.ToByteArray();
}
return Array.Empty<byte>();
}
public class AnswerTask : SIRTTask
{
public AnswerTask() : base(0, 3000)
{
}
public byte[] Last { get; private set; }
protected override void ProcessResponse(SIRTMessage response)
{
this.Last = response.Data ?? new byte[] { };
base.ProcessResponse(response);
}
}
public static readonly AnswerTask ActivateSIRT = new AnswerTask
{
Cmd = SIRTMessage.W_REG,
RequestAddress = 0x20000000,
P2 = 0x05,
Data = new byte[]
{
new SirtOperating { /* default */ },
new BluetoothOperating { BtOff = true },
new RFModuleOperating { RfOff = true },
new RFModuleOperating { OpMode = OperatingModes.ReceiveF1TransmitSensusRFF3 },
new PamTimeout { Minutes = 1 }
}
};
internal static readonly AnswerTask IdentifySIRT = new AnswerTask
{
Cmd = SIRTMessage.R_REG,
RequestAddress = 0x11001820,
P2 = 0x08
};
internal static readonly AnswerTask ReadPamPool = new AnswerTask
{
Cmd = SIRTMessage.R_PAM,
RequestAddress = 0xFFFFFFFF
};
internal static AnswerTask DeleteFromPamPool(uint address) => new AnswerTask
{
Cmd = SIRTMessage.W_PAM,
P1 = new P811 { DelPamAdr = true },
RequestAddress = address
};
}
}
@@ -1,126 +0,0 @@
namespace Common.Hardware.SIRT
{
using System;
using System.Collections.Concurrent;
using System.Timers;
public partial class SIRTTask
{
public readonly ConcurrentStack<SIRTMessage> responses;
public readonly SIRTMessage request;
protected readonly Timer timeoutTimer;
public SIRTTask(int frequency, int timeout = 5_000)
{
this.Timeout = timeout;
this.Frequency = frequency;
this.responses = new ConcurrentStack<SIRTMessage>();
this.request = new SIRTMessage();
this.timeoutTimer = new Timer
{
AutoReset = false,
Enabled = false,
Interval = this.Timeout
};
this.timeoutTimer.Elapsed += this.OnTimeout;
}
public event Action<SIRTTask> Completed;
public event Action<SIRTTask> Cancelled;
public event Action<SIRTTask> Timeouted;
public byte Cmd
{
get => this.request.Cmd;
set => this.request.Cmd = value;
}
public byte P1
{
get => this.request.P1;
set => this.request.P1 = value;
}
public byte P2
{
get => this.request.P2;
set => this.request.P2 = value;
}
public uint RequestAddress
{
get => this.request.Address;
set
{
this.request.Address = value;
this.ResponseAddress = value;
}
}
public uint ResponseAddress { get; set; }
public byte[] Data
{
get => this.request.Data;
set => this.request.Data = value;
}
public int Timeout { get; }
public int Frequency { get; }
public SIRTTaskState State { get; set; }
public void PushResponse(SIRTMessage response)
{
if (this.State == SIRTTaskState.Cancelled)
{
this.NotifyCancelled();
}
else
{
this.responses.Push(response);
this.ProcessResponse(response);
}
}
public virtual byte[] ToByteArray() => this.request.GetBytes();
public override string ToString() => BitConverter.ToString(this.ToByteArray());
protected void NotifyCancelled() => this.Cancelled?.Invoke(this);
protected void NotifyCompleted() => this.Completed?.Invoke(this);
protected void NotifyTimeouted() => this.Timeouted?.Invoke(this);
protected virtual void OnTimeout(object sender, ElapsedEventArgs e)
{
this.State = SIRTTaskState.Cancelled;
this.NotifyCancelled();
}
protected virtual void ProcessResponse(SIRTMessage response)
{
if (this.State == SIRTTaskState.Running)
{
if (response.Cmd == SIRTMessage.ACKNANSW || (response.Data.Length > 0 && response.Data[0] == SIRTMessage.SEMI))
{
this.State = SIRTTaskState.Completed;
}
}
if (this.State == SIRTTaskState.Completed)
{
this.timeoutTimer.Stop();
this.NotifyCompleted();
}
else if (this.State == SIRTTaskState.Cancelled)
{
this.timeoutTimer.Stop();
this.NotifyCancelled();
}
}
}
}
@@ -0,0 +1,16 @@
namespace Common.Hardware.SIRT.Tasks
{
using Common.Hardware.SIRT.Parameters;
public class DeleteFromPamPoolTask : SIRTTask
{
public DeleteFromPamPoolTask()
{
this.request.Command = SIRTConstants.W_PAM;
this.request.P1 = new P811 { DelPamAdr = true };
}
public override void Push(SIRTMessage _)
=> this.State = SIRTTaskState.Completed;
}
}
@@ -0,0 +1,25 @@
namespace Common.Hardware.SIRT.Tasks
{
public class ReadPamTask : SIRTTask
{
public ReadPamTask()
=> this.request.Command = SIRTConstants.R_PAM;
public byte Length
{
get => this.request.P2;
set => this.request.P2 = value;
}
public byte[] Payload { get; private set; }
public override void Push(SIRTMessage response)
{
if (response.Command == SIRTConstants.ACKN_ANSW && response.P1 == 0)
{
this.Payload = response.Payload;
this.State = SIRTTaskState.Completed;
}
}
}
}
@@ -0,0 +1,25 @@
namespace Common.Hardware.SIRT.Tasks
{
public class ReadRegisterTask : SIRTTask
{
public ReadRegisterTask()
=> this.request.Command = SIRTConstants.R_REG;
public byte Length
{
get => this.request.P2;
set => this.request.P2 = value;
}
public byte[] Payload { get; private set; }
public override void Push(SIRTMessage response)
{
if (response.Command == SIRTConstants.ACKN_ANSW)
{
this.Payload = response.Payload;
this.State = SIRTTaskState.Completed;
}
}
}
}
@@ -0,0 +1,71 @@
namespace Common.Hardware.SIRT.Tasks
{
using System;
public abstract class SIRTTask
{
protected readonly SIRTMessage request = new SIRTMessage();
public event Action<SIRTTask> StateChanged;
public byte Command => this.request.Command;
private SIRTTaskState state;
public SIRTTaskState State
{
get => this.state;
set
{
this.state = value;
this.StateChanged?.Invoke(this);
}
}
public uint RequestAddress
{
get => this.request.Address;
set
{
this.request.Address = value;
if (this.ResponseAddress == 0)
{
this.ResponseAddress = value;
}
}
}
public uint ResponseAddress { get; set; }
public string SirtId
{
get => this.request.SirtId;
set => this.request.SirtId = value;
}
public int Frequency
{
get => this.request.Frequency;
set => this.request.Frequency = value;
}
public DateTimeOffset Timestamp
{
get => this.request.Timestamp;
set => this.request.Timestamp = value;
}
public abstract void Push(SIRTMessage response);
public virtual byte[] Run()
{
this.State = SIRTTaskState.Running;
this.Timestamp = DateTimeOffset.UtcNow;
return this.request.GetBytes();
}
public static implicit operator SIRTMessage(SIRTTask task) => task.request;
}
}
@@ -1,4 +1,4 @@
namespace Common.Hardware.SIRT
namespace Common.Hardware.SIRT.Tasks
{
public enum SIRTTaskState
{
@@ -0,0 +1,80 @@
namespace Common.Hardware.SIRT.Tasks
{
using Common.Hardware.SIRT.Parameters;
using System;
public class WritePamTask : SIRTTask
{
private readonly P811 p811;
public WritePamTask()
{
this.request.Command = SIRTConstants.W_PAM;
this.p811 = this.request.P1;
}
public bool WakeUpModul
{
get => this.p811.WakeUpModul;
set => this.SetP811(x => x.WakeUpModul = value);
}
public bool WakeUpCmd
{
get => this.p811.WakeUpCmd;
set => this.SetP811(x => x.WakeUpCmd = value);
}
public bool IgnoreTimeout
{
get => this.p811.IgnoreTimeout;
set => this.SetP811(x => x.IgnoreTimeout = value);
}
public bool DelPamSemi
{
get => this.p811.DelPamSemi;
set => this.SetP811(x => x.DelPamSemi = value);
}
public bool DelPamTx
{
get => this.p811.DelPamTx;
set => this.SetP811(x => x.DelPamTx = value);
}
public bool DelPamAdr
{
get => this.p811.DelPamAdr;
set => this.SetP811(x => x.DelPamAdr = value);
}
public bool DelPamAll
{
get => this.p811.DelPamAll;
set => this.SetP811(x => x.DelPamAll = value);
}
public byte[] Data
{
get => this.request.Payload;
set => this.request.Payload = value;
}
private void SetP811(Action<P811> p811Setter)
{
p811Setter.Invoke(this.p811);
this.request.P1 = this.p811;
}
public override void Push(SIRTMessage response)
{
if (response.Length > 0 && response.Payload[0] == SIRTConstants.SEMI)
{
this.State = SIRTTaskState.Completed;
}
}
}
}
@@ -0,0 +1,26 @@
namespace Common.Hardware.SIRT.Tasks
{
public class WriteRegisterTask : SIRTTask
{
public WriteRegisterTask()
=> this.request.Command = SIRTConstants.W_REG;
public byte[] Payload
{
get => this.request.Payload;
set
{
this.request.Payload = value;
this.request.P2 = (byte)value.Length;
}
}
public override void Push(SIRTMessage response)
{
if (response.Command == SIRTConstants.ACKN_ANSW)
{
this.State = SIRTTaskState.Completed;
}
}
}
}
@@ -240,6 +240,7 @@
<Compile Include="CalibFactor.cs" />
<Compile Include="GenesisMeterStreamingQuality.cs" />
<Compile Include="MeterPortScanner.cs" />
<Compile Include="PreadjustmentMeter.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="GenesisConfigReader.cs" />
<Compile Include="Properties\Resources.de.Designer.cs">
@@ -0,0 +1,55 @@
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using Xylem.Common.CommonCore.Configuration;
using Xylem.Common.Hardware.WaterMeter.Genesis.Registers;
using Xylem.Common.Logic.SoftwareAccessHelper;
namespace Xylem.Common.Hardware.WaterMeter.Genesis.GenesisCore
{
public class PreadjustmentMeter : GenesisMeter
{
private settings mySettings = new settings();
public class settings
{
public int Metersize { get; set; } = 2;
}
public void Preparation()
{
//Login
//getRegisterList
Login();
WriteRegister(Register.Genesisflow.CalFactor1, 15625);
WriteRegister(Register.Genesisflow.CalFactor2, 15625);
WriteRegister(Register.Genesisflow.CalFactor3, 15625);
WriteRegister(Register.Genesisflow.ZeroOffset1, 0);
WriteRegister(Register.Genesisflow.ZeroOffset2, 0);
WriteRegister(Register.Genesisflow.ZeroOffset3, 0);
WriteRegister(Register.Genesisflow.LedMode, 6);
WriteRegister(Register.Genesisflow.MeterSize, mySettings.Metersize);
var r = LocalWebRequest.GetRequest($"{ ServiceUrls.GenesisFinalCheckServiceUrl()}GetMetersizeProgrammingData?MeterSize={mySettings.Metersize.GetHashCode().GetHashCode()}", 2000);
var dt = JsonConvert.DeserializeObject<Dictionary<string, UInt32>>(r);
foreach (var item in dt)
{
WriteRegister(item.Key, item.Value);
}
}
public void RunAmp()
{
for (int i = 0; i < 35; i++)
{
}
}
}
}
@@ -1 +1 @@
7df2ad6be70922b931820861acc675522243ee78
c43c40a030005a8f189e6179faf40a6d42bfef5c
@@ -22,7 +22,7 @@
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<NoWarn>IDE0003;IDE0049;</NoWarn>
<NoWarn>IDE0003;IDE0011;IDE0049;</NoWarn>
<Prefer32Bit>false</Prefer32Bit>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
@@ -59,7 +59,7 @@
<Compile Include="Attributes\EregisterFeatureAttribute.cs" />
<Compile Include="Eregister.cs" />
<Compile Include="EregisterChangeMeterTypeTask.cs" />
<Compile Include="EregisterFactory.cs" />
<Compile Include="EregisterBatch.cs" />
<Compile Include="EregisterCheckFinalizationTask.cs" />
<Compile Include="EregisterCheckInitializationTask.cs" />
<Compile Include="EregisterExtensions.cs" />
@@ -145,8 +145,10 @@
<Compile Include="Models\EregisterDebugFeatures.cs" />
<Compile Include="Models\EregisterFeatures.cs" />
<Compile Include="Models\EregisterAvailableParametersParser.cs" />
<Compile Include="Models\EregisterHistory.cs" />
<Compile Include="Models\EregisterProgrammingParameters.cs" />
<Compile Include="Models\EregisterProgrammingParametersList.cs" />
<Compile Include="Models\EregisterState.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="Telegrams\AppCode.cs" />
<Compile Include="Telegrams\BUP.cs" />
@@ -1,7 +1,7 @@
namespace Common.Hardware.WaterMeter.eRegister
{
using Common.Hardware.SIRT;
using Common.Hardware.SIRT.Parameters;
using Common.Hardware.SIRT.Tasks;
using Common.Hardware.WaterMeter.eRegister.Models;
using System;
@@ -16,44 +16,45 @@
{
private readonly ConcurrentQueue<EregisterTask> runningTasks;
private readonly EregisterProgrammingParameters parameters;
private readonly Action<SIRTTask> enqueueTask;
private readonly SIRTChannel sirtChannel;
private readonly EregisterHistory history;
private readonly EregisterState state;
public Eregister(EregisterProgrammingParameters parameters, Action<SIRTTask> enqueueTask)
private string executionType;
public Eregister(EregisterProgrammingParameters parameters, SIRTChannel sirtChannel)
{
this.parameters = parameters;
this.enqueueTask = enqueueTask;
this.sirtChannel = sirtChannel;
this.state = new EregisterState();
this.history = new EregisterHistory();
this.runningTasks = new ConcurrentQueue<EregisterTask>();
}
public uint Address => this.parameters?.RequestAddress ?? 4291189262;
public uint RequestAddress => this.parameters?.RequestAddress ?? 0;
public uint ResponseAddress => this.parameters?.RequestAddress ?? 0;
public void Clear()
{
while (this.runningTasks.TryDequeue(out var _))
{
// Just dequeue all tasks
}
while (this.runningTasks.TryDequeue(out var _)) ;
}
internal IEnumerable<EregisterTask> LoadInspectionInitializationTasks()
{
this.executionType = nameof(LoadInspectionInitializationTasks);
var features = parameters.LoadInspectionInitializationFeatures();
this.LoadProgrammingParameters(features);
var lastTask = this.runningTasks.LastOrDefault();
if (lastTask != null)
if (this.runningTasks.Any())
{
this.runningTasks.Enqueue(new EregisterChangeMeterTypeTask(lastTask.Frequency, lastTask.Timeout)
this.runningTasks.Enqueue(new EregisterChangeMeterTypeTask(features.Frequency)
{
SlotNr = features.SlotNr,
PoNr = features.PoNr,
SerialNr = features.SerialNr,
P1 = new P811
{
DelPamSemi = true,
},
DelPamSemi = true,
RequestAddress = features.RequestAddress,
ResponseAddress = features.ResponseAddress,
EncryptionKey = features.EncryptionKey,
@@ -66,6 +67,7 @@
internal IEnumerable<EregisterTask> LoadInspectionFinalizationTasks()
{
this.executionType = nameof(LoadInspectionFinalizationTasks);
var features = parameters.LoadInspectionFinalizationFeatures();
this.LoadProgrammingParameters(features);
@@ -75,10 +77,7 @@
SlotNr = features.SlotNr,
PoNr = features.PoNr,
SerialNr = features.SerialNr,
P1 = new P811
{
DelPamSemi = true,
},
DelPamSemi = true,
RequestAddress = features.RequestAddress,
ResponseAddress = features.ResponseAddress,
EncryptionKey = features.EncryptionKey
@@ -87,69 +86,114 @@
return this.runningTasks.AsEnumerable();
}
internal void StartProgramming()
internal EregisterHistory GetHistory() => this.history;
internal EregisterState GetState() => this.state;
internal void StartProgrammingAsync()
{
var manualResetEventSlim = new ManualResetEventSlim();
this.history.SerienNr = this.parameters.SerienNr;
this.history.Adresse = this.parameters.Adresse;
this.history.TempAdresse = this.parameters.TempAdresse;
void CompletedOrCancelled(SIRTTask task)
var readEvent = new ManualResetEventSlim();
void messageReceived(SIRTMessage message)
{
task.Completed -= CompletedOrCancelled;
task.Cancelled -= CompletedOrCancelled;
if (task is EregisterTask _task)
if (this.runningTasks.TryPeek(out var task))
{
var numberStyles = NumberStyles.HexNumber | NumberStyles.AllowHexSpecifier;
var cultureInfo = CultureInfo.InvariantCulture;
foreach (var etask in this.runningTasks)
if (task.State != SIRTTaskState.Cancelled && task.State != SIRTTaskState.Completed)
{
if (etask.State != SIRTTaskState.Cancelled && etask.State != SIRTTaskState.Completed)
{
etask.FactoryState = _task.FactoryState;
etask.IsEncrypted = _task.IsEncrypted;
etask.RequestAddress = _task.RequestAddress;
etask.ResponseAddress = _task.ResponseAddress;
}
task.Push(message);
if (etask.RadioFWVersion is null)
if (task.State == SIRTTaskState.Cancelled || task.State == SIRTTaskState.Completed)
{
etask.RadioFWHex = _task.DEBUG?.RadioFWVersion;
if (int.TryParse($"{etask.RadioFWHex}", numberStyles, cultureInfo, out var radioFWVersion))
{
etask.RadioFWVersion = radioFWVersion;
}
readEvent.Set();
}
}
this.history.Push(message);
}
}
this.sirtChannel.MessageReceived += messageReceived;
var lastTask = default(EregisterTask);
while (this.runningTasks.TryPeek(out var task) && task.State != SIRTTaskState.Cancelled)
{
lastTask = task;
while (task.State != SIRTTaskState.Completed)
{
this.sirtChannel.WriteHandler(task);
this.history.Push(task);
readEvent.Wait(4000);
readEvent.Reset();
if (task.State != SIRTTaskState.Completed)
{
var dtask = new DeleteFromPamPoolTask
{
Frequency = task.Frequency,
RequestAddress = task.RequestAddress,
ResponseAddress = task.ResponseAddress,
};
this.sirtChannel.WriteHandler(task);
readEvent.Wait(500);
readEvent.Reset();
}
}
manualResetEventSlim.Set();
}
void TelegramReceived(object telegram)
{
}
while (this.runningTasks.TryPeek(out var task))
{
task.Completed += CompletedOrCancelled;
task.Cancelled += CompletedOrCancelled;
task.Telegram += TelegramReceived;
this.enqueueTask(task);
manualResetEventSlim.Wait();
manualResetEventSlim.Reset();
if (task.State == SIRTTaskState.Completed)
{
var cultureInfo = CultureInfo.InvariantCulture;
var numberStyles = NumberStyles.HexNumber | NumberStyles.AllowHexSpecifier;
foreach (var rtask in this.runningTasks.AsEnumerable())
{
if (rtask.State == SIRTTaskState.Completed)
{
continue;
}
rtask.FactoryState = task.FactoryState;
rtask.IsEncrypted = task.IsEncrypted;
rtask.RequestAddress = task.RequestAddress;
rtask.ResponseAddress = task.ResponseAddress;
if (task.DEBUG != null)
{
rtask.RadioFWHex = task.DEBUG.RadioFWVersion;
if (int.TryParse($"{rtask.RadioFWHex}", numberStyles, cultureInfo, out var radioFWVersion))
{
rtask.RadioFWVersion = radioFWVersion;
}
}
}
this.runningTasks.TryDequeue(out task);
this.runningTasks.TryPeek(out task);
}
else if (task.State == SIRTTaskState.Cancelled)
{
break;
}
}
this.sirtChannel.MessageReceived -= messageReceived;
this.state.Bemerkung = this.executionType;
this.state.BUP = (lastTask.LAT ?? lastTask.BUP)?.ToString()?.Replace('-', '\t');
this.state.DEBUG = lastTask.DEBUG?.ToString()?.Replace('-', '\t');
this.state.Fabrikationsnummer = lastTask.DEBUG?.PCBID;
this.state.SEMI = lastTask.SEMI?.ToString()?.Replace('-', '\t');
this.state.SemiDebugDatum = DateTime.Now;
this.state.Seriennummer = this.parameters.SerienNr;
this.state.TempAdresse = this.parameters.TempAdresse;
if (this.executionType == nameof(LoadInspectionFinalizationTasks))
{
this.state.FunkadresseDatum = DateTime.Now;
this.state.GeschlossenDatum = DateTime.Now;
}
}
@@ -165,31 +209,28 @@
SlotNr = features.SlotNr,
PoNr = features.PoNr,
SerialNr = features.SerialNr,
P1 = new P811
{
DelPamSemi = true,
WakeUpCmd = true,
},
DelPamSemi = true,
WakeUpCmd = true,
RequestAddress = features.RequestAddress,
ResponseAddress = features.ResponseAddress,
EncryptionKey = features.EncryptionKey,
Name = "Dummy PAM"
});
// Determinates the state of the endpoint
this.runningTasks.Enqueue(new EregisterCheckInitializationTask(this.parameters, features.Frequency)
if (this.executionType == nameof(LoadInspectionInitializationTasks))
{
SlotNr = features.SlotNr,
PoNr = features.PoNr,
SerialNr = features.SerialNr,
P1 = new P811
// Determinates the state of the endpoint
this.runningTasks.Enqueue(new EregisterCheckInitializationTask(this.parameters, frequency)
{
SlotNr = features.SlotNr,
PoNr = features.PoNr,
SerialNr = features.SerialNr,
DelPamSemi = true,
},
RequestAddress = features.RequestAddress,
ResponseAddress = features.ResponseAddress,
EncryptionKey = features.EncryptionKey
});
RequestAddress = features.RequestAddress,
ResponseAddress = features.ResponseAddress,
EncryptionKey = features.EncryptionKey,
});
}
foreach (var pam in features.BuildPams())
{
@@ -199,10 +240,7 @@
PoNr = features.PoNr,
SerialNr = features.SerialNr,
Name = pam.Key,
P1 = new P811
{
DelPamSemi = true,
},
DelPamSemi = true,
RequestAddress = features.RequestAddress,
ResponseAddress = features.ResponseAddress,
Data = pam.Value,
@@ -1,21 +1,21 @@
namespace Common.Hardware.WaterMeter.eRegister
{
using Common.Hardware.WaterMeter.eRegister.Models;
using Common.Hardware.SIRT;
using Common.Hardware.WaterMeter.eRegister.Models;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
public class EregisterFactory
public class EregisterBatch
{
private readonly SIRTFactory sirtFactory;
private readonly SIRTHub sirtHub;
private readonly ICollection<Eregister> eregisters;
public EregisterFactory(SIRTFactory broadcaster)
public EregisterBatch(SIRTHub sirtHub)
{
this.sirtFactory = broadcaster;
this.sirtHub = sirtHub;
this.eregisters = new List<Eregister>();
}
@@ -25,10 +25,9 @@
foreach (var parameters in parametersList)
{
var eregister = new Eregister(parameters, this.sirtFactory.EnqueueTask);
var channel = this.sirtHub.CreateChannel(parameters.Frequency, parameters.RequestAddress, parameters.ResponseAddress);
var eregister = new Eregister(parameters, channel);
this.sirtFactory.DequeueTasks(parameters.RequestAddress);
this.sirtFactory.DequeueTasks(parameters.ResponseAddress);
this.eregisters.Add(eregister);
yield return eregister.LoadInspectionFinalizationTasks();
@@ -41,10 +40,9 @@
foreach (var parameters in parametersList)
{
var eregister = new Eregister(parameters, this.sirtFactory.EnqueueTask);
var channel = this.sirtHub.CreateChannel(parameters.Frequency, parameters.RequestAddress, parameters.ResponseAddress);
var eregister = new Eregister(parameters, channel);
this.sirtFactory.DequeueTasks(parameters.RequestAddress);
this.sirtFactory.DequeueTasks(parameters.ResponseAddress);
this.eregisters.Add(eregister);
yield return eregister.LoadInspectionInitializationTasks();
@@ -57,7 +55,7 @@
foreach (var eregister in this.eregisters)
{
tasks.Add(Task.Run((Action)eregister.StartProgramming, cancellationToken));
tasks.Add(Task.Run((Action)eregister.StartProgrammingAsync, cancellationToken));
}
return Task.WhenAll(tasks);
@@ -67,12 +65,28 @@
{
foreach (var eregister in this.eregisters)
{
this.sirtFactory.DequeueTasks(eregister.Address);
this.sirtHub.ClearChannels(eregister.RequestAddress, eregister.ResponseAddress);
eregister.Clear();
}
this.eregisters.Clear();
}
public IEnumerable<EregisterState> GetEregisterStates()
{
foreach (var eregister in this.eregisters)
{
yield return eregister.GetState();
}
}
public IEnumerable<EregisterHistory> GetEregisterHistories()
{
foreach (var eregister in this.eregisters)
{
yield return eregister.GetHistory();
}
}
}
}
@@ -1,28 +1,24 @@
namespace Common.Hardware.WaterMeter.eRegister
{
using Common.Hardware.WaterMeter.eRegister.Features;
using System;
using System.Globalization;
public class EregisterChangeMeterTypeTask : EregisterTask
{
public EregisterChangeMeterTypeTask(int frequency, int timeout = 5000) : base(frequency, timeout)
public EregisterChangeMeterTypeTask(int frequency) : base(frequency)
=> this.Name = "Change meter type";
public override byte[] ToByteArray()
public override byte[] Run()
{
var numberStyles = NumberStyles.HexNumber | NumberStyles.AllowHexSpecifier;
var cultureInfo = CultureInfo.InvariantCulture;
var meterTypeCmd = new SetMeterType
{
Type = MeterTypes.CandI
};
var meterTypeCmd = new SetMeterType { Type = MeterTypes.CandI };
this.Name = $"FW: {this.RadioFWHex} - C & I";
// from Pruef2000.exe
if (int.TryParse($"1108", numberStyles, cultureInfo, out var minFWVersion) && int.TryParse($"110B", numberStyles, cultureInfo, out var exceptFWVersion))
{
if (this.RadioFWVersion < minFWVersion || this.RadioFWVersion != exceptFWVersion)
if (this.RadioFWVersion < minFWVersion || this.RadioFWVersion == exceptFWVersion)
{
meterTypeCmd.Type = MeterTypes.Residential;
this.Name = $"FW: {this.RadioFWHex} - Residential";
@@ -30,15 +26,12 @@
}
this.Data = meterTypeCmd
.Append(new ProvidePin
{
AuthLevel = AuthLevel.III
})
.Append(new ProvidePin { AuthLevel = AuthLevel.III })
.ToByteArray();
this.NotifyChanged();
this.NotifyChanged();
return base.ToByteArray();
return base.Run();
}
}
}
@@ -1,6 +1,7 @@
namespace Common.Hardware.WaterMeter.eRegister
{
using Common.Hardware.SIRT;
using Common.Hardware.SIRT.Tasks;
using Common.Hardware.WaterMeter.eRegister.Attributes;
using Common.Hardware.WaterMeter.eRegister.Features;
using Common.Hardware.WaterMeter.eRegister.Models;
@@ -14,12 +15,9 @@
{
private readonly EregisterProgrammingParameters requestParameters;
private SIRTTaskState pendingState;
public EregisterCheckFinalizationTask(EregisterProgrammingParameters requestParameters, int frequency) : base(frequency)
{
this.requestParameters = requestParameters;
this.pendingState = SIRTTaskState.Completed;
this.Name = "Final Check";
this.Data = new OpticalTelegram
{
@@ -31,13 +29,12 @@
});
}
protected override void EndProcessResponse(SIRTMessage response)
public override void Push(SIRTMessage response)
{
this.timeoutTimer.Stop();
base.Push(response);
if (this.State == this.pendingState)
if (this.State == SIRTTaskState.Completed)
{
this.State = SIRTTaskState.Running;
this.Name = "Final Check - ✓";
var errors = string.Empty;
@@ -86,27 +83,32 @@
if (result == DialogResult.No)
{
this.pendingState = SIRTTaskState.Cancelled;
this.State = SIRTTaskState.Cancelled;
this.Label = nameof(SIRTTaskState.Cancelled);
this.Name = "Final Check ✘";
}
}
}
this.State = this.pendingState;
this.timeoutTimer.Start();
base.EndProcessResponse(response);
}
private EregisterProgrammingParameters GetProgrammingParameters()
{
var alarms = new AlarmsMask(this.SEMI.AlarmActiveInformation);
var dataLogContent = new ChangeDataLoggerSettings();
dataLogContent.SetLogContent(this.SEMI.LogContent);
var fdrLogContent = new ChangeDataLoggerSettings();
fdrLogContent.SetLogContent(this.SEMI.FixedDateReadingContent);
var leakage = this.SEMI.LeakageDetectionParameters;
var leakagePeriod = leakage.GetBitsLE().GetByteLE(0, 3);
var leakageTreshold = (leakage - leakagePeriod) / (int)Math.Pow(2, 3);
var brokenPipe = this.SEMI.BrokenPipeDetectionParameters;
var brokenPipePeriod = brokenPipe.GetBitsLE().GetByteLE(0, 3);
var brokenPipeTreshold = (brokenPipe - brokenPipePeriod) / (int)Math.Pow(2, 3);
var parameters = new EregisterProgrammingParameters
{
VolumePerLedPulse = this.DEBUG.VolumePerLedPulse,
@@ -142,10 +144,10 @@
History_Error_Limits_Days = this.SEMI.HistoricalErrorLimit,
CustomerSpecificText = this.SEMI.CustomerSpecificText,
DisplayVolume = this.SEMI.DisplayVolume,
LeakagePeriod = this.SEMI.LeakageDetectionParameters.GetBitsLE().GetByteLE(0, 3),
// TODO: LeakageThreshold
BrokenPipePeriod = this.SEMI.BrokenPipeDetectionParameters.GetBitsLE().GetByteLE(0, 3),
// TODO: BrokenPipeThreshold
LeakagePeriod = leakagePeriod,
LeakageThreshold = (byte)leakageTreshold,
BrokenPipePeriod = brokenPipePeriod,
BrokenPipeThreshold = (byte)brokenPipeTreshold,
FDR_Day_Of_Data_Reading = this.SEMI.DayOfMonth,
FDR_Alarm_State = fdrLogContent.AlarmState,
FDR_Backward_Volume = fdrLogContent.BackwardVolume,
@@ -160,8 +162,8 @@
FDR_Time_Of_Maximum_Flow = fdrLogContent.TimeOfMaximumFlow,
FDR_Time_Of_Minimum_Flow = fdrLogContent.TimeOfMinimumFlow,
FDR_Time_Of_Peak_Flow = fdrLogContent.TimeOfPeakFlow,
TransmissionIntervalFinal = (byte)this.SEMI.TransmissionInterval,
LATWindowsFinal = this.SEMI.LATInterval,
Transmission_Intervall = (byte)this.SEMI.TransmissionInterval,
LAT_Interval = this.SEMI.LATInterval,
MBusStatus = this.SEMI.MBusStatus,
Adresse = this.SEMI.Address,
};
@@ -1,6 +1,7 @@
namespace Common.Hardware.WaterMeter.eRegister
{
using Common.Hardware.SIRT;
using Common.Hardware.SIRT.Tasks;
using Common.Hardware.WaterMeter.eRegister.Features;
using Common.Hardware.WaterMeter.eRegister.Models;
@@ -12,12 +13,9 @@
{
private readonly EregisterProgrammingParameters parameters;
private SIRTTaskState pendingState;
public EregisterCheckInitializationTask(EregisterProgrammingParameters parameters, int frequency) : base(frequency)
{
this.parameters = parameters;
this.pendingState = SIRTTaskState.Completed;
this.Name = "Initial Check";
this.Data = new OpticalTelegram
{
@@ -29,13 +27,12 @@
});
}
protected override void EndProcessResponse(SIRTMessage response)
public override void Push(SIRTMessage response)
{
this.timeoutTimer.Stop();
base.Push(response);
if (this.State == this.pendingState)
if (this.State == SIRTTaskState.Completed)
{
this.State = SIRTTaskState.Running;
this.Name = "Initial Check - ✓";
var message = new StringBuilder();
@@ -90,8 +87,8 @@
if (message.Length > 10)
{
message.Insert(0, $"Am Einbauplatz: {this.SlotNr}, "
+ $"eingebaute E-Register mit Funkadressen: {this.RequestAddress} | {this.ResponseAddress}, "
message.Insert(0, $"Am Einbauplatz: {this.SlotNr}, "
+ $"eingebaute E-Register mit Funkadressen: {this.RequestAddress} | {this.ResponseAddress}, "
+ $"sind folgenden Fehler sind aufgetreten:");
message.AppendLine();
message.AppendLine("Qualitätssicherung informieren!");
@@ -102,24 +99,16 @@
if (result == DialogResult.No)
{
this.State = SIRTTaskState.Pending;
this.pendingState = SIRTTaskState.Cancelled;
this.Label = nameof(SIRTTaskState.Cancelled);
this.State = SIRTTaskState.Cancelled;
this.Name = "Initial Check ✘";
this.Label = $"{this.State}";
this.Data = new OpticalTelegram
{
Minutes = 0
};
this.Name = "Initial Check ✘";
this.NotifyTimeouted();
}
}
}
this.State = this.pendingState;
this.timeoutTimer.Start();
base.EndProcessResponse(response);
}
}
}
@@ -88,7 +88,7 @@
}
catch (Exception e)
{
Console.WriteLine(e);
}
pamList[singleCmd][authLevel].Add(bytes);
@@ -97,7 +97,7 @@
}
catch (Exception e)
{
Console.WriteLine(e);
}
return pamList
@@ -2,27 +2,27 @@
{
using Common.Hardware.SIRT;
using Common.Hardware.SIRT.Parameters;
using Common.Hardware.SIRT.Tasks;
using Common.Hardware.WaterMeter.eRegister.Features;
using Common.Hardware.WaterMeter.eRegister.Models;
using Common.Hardware.WaterMeter.eRegister.Telegrams;
using System;
using System.Timers;
public class EregisterTask : SIRTTask
public class EregisterTask : WritePamTask
{
private byte[] payload;
private int countFailures;
public EregisterTask(int frequency, int timeout = 5_000)
: base(frequency, timeout)
public EregisterTask(int frequency)
{
this.Cmd = SIRTMessage.W_PAM;
this.Frequency = frequency;
this.RSSI = new RSSI(0, frequency);
this.Label = nameof(SIRTTaskState.Pending);
}
public event Action<EregisterTask> Changed;
public event Action<object> Telegram;
public event Action<byte[]> MessageReceived;
public int SlotNr { get; internal set; }
@@ -60,158 +60,145 @@
public string RadioFWHex { get; set; }
public void Repeat() => this.OnTimeout(null, null);
public override byte[] ToByteArray()
public override byte[] Run()
{
var data = this.request.Data;
var payloadLength = this.request.Payload.Length;
this.payload = new byte[payloadLength];
Array.Copy(this.request.Payload, 0, this.payload, 0, payloadLength);
if (this.FactoryState == FactoryState.Shipment)
{
data = new EregisterAvailableParametersParser(data);
this.payload = new EregisterAvailableParametersParser(payload);
}
if (this.IsEncrypted)
{
data = data.EncryptRequest(this.EncryptionKey, this.RequestAddress);
this.payload = payload.EncryptRequest(this.EncryptionKey, this.RequestAddress);
}
base.Run();
return new SIRTMessage
{
Address = this.request.Address,
Cmd = this.request.Cmd,
Data = data,
Command = this.request.Command,
Payload = this.payload,
Frequency = this.Frequency,
P1 = this.request.P1,
P2 = this.request.P2,
}.GetBytes();
};
}
protected override void OnTimeout(object sender, ElapsedEventArgs e)
{
this.State = SIRTTaskState.Pending;
this.NotifyTimeouted();
}
protected override void ProcessResponse(SIRTMessage response)
public override void Push(SIRTMessage response)
{
if (this.State == SIRTTaskState.Cancelled)
{
this.Label = nameof(SIRTTaskState.Cancelled);
return;
}
if (response.Address != this.RequestAddress)
else
{
var requestAddress = this.RequestAddress;
this.RequestAddress = this.ResponseAddress;
this.ResponseAddress = requestAddress;
}
if (response.Cmd == SIRTMessage.FROMAIR)
{
this.P11 = new P11(response.P1);
this.RSSI = new RSSI(response.P2, (ushort)this.Frequency);
var data = response.Data;
var length = data.Length;
if (this.IsEncrypted)
if (response.Address != this.RequestAddress)
{
data = data.DecryptResponse(this.EncryptionKey);
var requestAddress = this.RequestAddress;
this.RequestAddress = this.ResponseAddress;
this.ResponseAddress = requestAddress;
}
if (length > 0)
this.State = SIRTTaskState.Running;
if (response.Command == SIRTConstants.FROM_AIR)
{
var type = data[0];
this.P11 = new P11(response.P1);
this.RSSI = new RSSI(response.P2, (ushort)this.Frequency);
if (type == SIRTMessage.BUP)
{
this.Label = nameof(SIRTMessage.BUP);
this.BUP = new BUP(data, this.P11);
this.IsEncrypted = this.BUP.Crc != 0;
this.NotifyTelegram(this.BUP);
}
else if (type == SIRTMessage.LAT)
{
this.Label = nameof(SIRTMessage.LAT);
this.LAT = new LAT(data, this.P11);
this.IsEncrypted = this.LAT.Crc != 0;
this.NotifyTelegram(this.LAT);
}
else if (type == SIRTMessage.DEBUG)
{
this.Label = nameof(SIRTMessage.DEBUG);
this.DEBUG = new DEBUG(data, this.P11);
this.IsEncrypted = this.DEBUG.Crc != 0;
this.FactoryState = this.DEBUG.FactoryState;
this.NotifyTelegram(this.DEBUG);
}
else if (type == SIRTMessage.SEMI)
{
this.SEMI = new SEMI(data, this.Frequency, this.P11);
this.IsEncrypted = this.SEMI.Crc != 0;
this.Label = default(string);
var data = response.Payload;
var length = data.Length;
if (this.SEMI.PAMStatus == PAMStatus.OK)
if (this.IsEncrypted)
{
data = data.DecryptResponse(this.EncryptionKey);
}
if (length > 0)
{
var type = data[0];
if (type == SIRTConstants.BUP)
{
if (this.request.Data.Length > 0 && this.request.Data[0] == Pam.GetDebug && this.DEBUG == null)
this.Label = nameof(SIRTConstants.BUP);
this.BUP = new BUP(data, this.P11);
this.IsEncrypted = this.BUP.Crc != 0;
}
else if (type == SIRTConstants.LAT)
{
this.Label = nameof(SIRTConstants.LAT);
this.LAT = new LAT(data, this.P11);
this.IsEncrypted = this.LAT.Crc != 0;
}
else if (type == SIRTConstants.DEBUG)
{
this.Label = nameof(SIRTConstants.DEBUG);
this.DEBUG = new DEBUG(data, this.P11);
this.IsEncrypted = this.DEBUG.Crc != 0;
this.FactoryState = this.DEBUG.FactoryState;
}
else if (type == SIRTConstants.SEMI)
{
this.SEMI = new SEMI(data, this.Frequency, this.P11);
this.IsEncrypted = this.SEMI.Crc != 0;
this.Label = default(string);
if (this.SEMI.PAMStatus == PAMStatus.OK || this.RadioFWVersion < 4352)
{
this.Label = "!DEBUG";
if (this.request.Length > 0 && this.request.Payload[0] == Pam.GetDebug && this.DEBUG == null)
{
this.Label = "!DEBUG";
}
else
{
this.State = SIRTTaskState.Completed;
this.Label = this.SEMI.PAMStatus.ToString();
}
}
else
{
this.State = SIRTTaskState.Completed;
this.Label = this.SEMI.PAMStatus.ToString();
this.EndProcessResponse(response);
if (this.SEMI.PAMStatus == PAMStatus.EXPIREDAUTH)
{
this.State = SIRTTaskState.Cancelled;
}
else if (++this.countFailures > 3)
{
this.State = SIRTTaskState.Cancelled;
}
}
}
else
{
this.Label = this.SEMI.PAMStatus.ToString();
if (this.SEMI.PAMStatus == PAMStatus.EXPIREDAUTH)
{
this.State = SIRTTaskState.Cancelled;
this.timeoutTimer.Stop();
}
else
{
this.countFailures++;
if (countFailures > 3)
{
this.State = SIRTTaskState.Cancelled;
this.EndProcessResponse(response);
}
}
this.Label = "NA";
}
}
else
{
this.Label = "NA";
}
}
else if (response.Command == SIRTConstants.ACKN_ANSW)
{
this.P12 = new P12(response.P1);
this.Label = "ACKN";
}
else
{
this.Label = "NA";
}
this.NotifyChanged();
this.MessageReceived?.Invoke(response);
}
else if (response.Cmd == SIRTMessage.ACKNANSW)
{
this.P12 = new P12(response.P1);
this.Label = "ACKN";
}
else
{
this.Label = "NA";
}
this.NotifyChanged();
}
protected virtual void EndProcessResponse(SIRTMessage response) => base.ProcessResponse(response);
protected void NotifyChanged() => this.Changed?.Invoke(this);
protected void NotifyTelegram(object value) => this.Telegram?.Invoke(value);
public static implicit operator byte[] (EregisterTask task)
=> task.payload ?? Array.Empty<byte>();
}
}
@@ -0,0 +1,17 @@
namespace Common.Hardware.WaterMeter.eRegister.Models
{
using System.Collections.Generic;
public class EregisterHistory
{
public int SerienNr { get; set; }
public long Adresse { get; set; }
public long TempAdresse { get; set; }
public List<byte> Telegrams { get; set; } = new List<byte>();
internal void Push(byte[] message) => this.Telegrams.AddRange(message);
}
}
@@ -14,7 +14,7 @@
[XmlAttribute("P2000_Shared_Id")]
public int SharedId { get; set; }
public int Slotno { get; set; }
public int SlotNr { get; set; }
public int FertigungsauftragNr { get; set; }
@@ -33,10 +33,10 @@
[CompareProperty]
public long Adresse { get; set; }
public int Frequency { get; set; }
public string CSD { get; set; }
public int Frequency { get; set; }
[CompareProperty]
public uint MeterId { get; set; }
@@ -49,28 +49,6 @@
[CompareProperty]
public uint VolumePerLedPulse { get; set; }
[CompareProperty]
public byte OffsetFactor { get; set; }
[CompareProperty]
public byte OffsetTime { get; set; }
[CompareProperty]
public byte FactoryCalibration { get; set; }
public byte TransmissionIntervalInitialization { get; set; }
[CompareProperty]
public byte TransmissionIntervalFinal { get; set; }
[CompareProperty]
public byte MBusStatus { get; set; }
public byte LatWindowsInitialization { get; set; }
[CompareProperty]
public byte LATWindowsFinal { get; set; }
public byte UnitsOfMessure { get; set; }
[CompareProperty]
@@ -78,9 +56,7 @@
public byte DecimalPoint { get; set; }
public byte CandIType { get; set; }
public bool Ruecklaufsperre { get; set; }
public bool DisallowReverseVolume { get; set; }
[CompareProperty]
public bool Alarm_Low_Battery { get; set; }
@@ -203,40 +179,57 @@
[CompareProperty]
public bool FDR_Alarm_State { get; set; }
public byte PowerLevelHex { get; set; }
[CompareProperty]
public byte Transmission_Intervall { get; set; }
[CompareProperty]
public byte LAT_Interval { get; set; }
public float UTC_Offset { get; set; }
public byte Wake_Up_Interval { get; set; }
[CompareProperty]
public byte OffsetFactor { get; set; }
[CompareProperty]
public byte OffsetTime { get; set; }
[CompareProperty]
public byte FactoryCalibration { get; set; }
public byte TransmissionIntervalInitialization { get; set; }
[CompareProperty]
public byte MBusStatus { get; set; }
public byte LatWindowsInitialization { get; set; }
public byte? PowerLevelHex { get; set; }
public byte DisableOTA { get; set; }
public byte ActivationByThreshold { get; set; }
public ushort OpenMeteringTransmissionIntervalSeconds { get; set; }
public float UTC_Offset { get; set; }
public byte Wake_Up_Interval { get; set; }
public ushort OMS_Interval { get; set; }
public uint DisplayVolume { get; set; }
public bool Encrypted { get; set; }
public byte LED_On_Minutes { get; set; }
public string EncryptionKey { get; set; }
public string MinMetrologyFWVersion { get; set; }
public string FWVersionsList { get; set; }
public byte MaxRebootCount { get; set; }
public double MinBatteryRemainingYears { get; set; }
public double MinBatteryVoltage { get; set; }
[CompareProperty]
public string CustomerSpecificText { get; set; }
public byte MaxRebootCount { get; set; }
public bool Sealed { get; set; }
public byte LED_ON_Minutes { get; set; }
public string CustomerSpecificText { get; set; }
public bool IsEbeling { get; set; }
@@ -256,7 +249,7 @@
{
var features = new EregisterFeatures
{
SlotNr = this.Slotno,
SlotNr = this.SlotNr,
SerialNr = this.SerienNr,
PoNr = this.FertigungsauftragNr,
RequestAddress = this.RequestAddress,
@@ -265,140 +258,153 @@
EncryptionKey = this.EncryptionKey.GetEncryptionKey(),
};
if (this.IsValid)
if (!this.IsValid)
{
// TODO:
//if (this.StatusFertigung != 30)
//{
// features.ChangeMeterReading = new ChangeMeterReading(333_333_333);
features.ChangeMeterReading = new ChangeMeterReading(222_222_222);
// return features;
//}
return features;
}
features.Debug = new EregisterDebugFeatures();
// TODO:
this.DisplayVolume = 500;
features.ChangeMeterReading = new ChangeMeterReading(this.DisplayVolume);
features.ChangeRadioId = new ChangeRadioId((uint)this.Adresse);
features.ChangeMeterId = new ChangeMeterId(this.MeterId);
features.DeactivateAlarms = new DeactivateAlarms
if (this.StatusFertigung != 30)
{
features.ChangeMeterReading = new ChangeMeterReading(333_333_333);
features.Debug = new EregisterDebugFeatures
{
Backflow = this.Alarm_Backflow,
BrokenPipe = this.Alarm_Broken_Pipe,
Leak = this.Alarm_Leakage,
LowBattery = this.Alarm_Low_Battery,
MagneticTamper = this.Alarm_Magnetic_Tamper,
MediumAbsent = this.Alarm_Medium_Absent,
MetrologyUnavailable = this.Alarm_Metrology_Unavailable,
SpecificError = this.Alarm_Specific_Error,
};
features.ResetAlarms = new ResetAlarms(0xFF);
features.SetDateAndTime = new SetDateAndTime
{
SecondsSince20000101 = new Epoch20000101
OpticalTelegram = new OpticalTelegram
{
DateTime = DateTime.UtcNow.AddHours(this.UTC_Offset)
Minutes = 0
}
};
features.ChangeCustomerText = new ChangeCustomerText
return features;
}
features.Debug = new EregisterDebugFeatures();
features.ChangeMeterReading = new ChangeMeterReading(this.DisplayVolume);
features.ChangeRadioId = new ChangeRadioId((uint)this.Adresse);
features.ChangeMeterId = new ChangeMeterId(this.MeterId);
features.DeactivateAlarms = new DeactivateAlarms
{
Backflow = this.Alarm_Backflow,
BrokenPipe = this.Alarm_Broken_Pipe,
Leak = this.Alarm_Leakage,
LowBattery = this.Alarm_Low_Battery,
MagneticTamper = this.Alarm_Magnetic_Tamper,
MediumAbsent = this.Alarm_Medium_Absent,
MetrologyUnavailable = this.Alarm_Metrology_Unavailable,
SpecificError = this.Alarm_Specific_Error,
};
features.ResetAlarms = new ResetAlarms(0xFF);
features.SetDateAndTime = new SetDateAndTime
{
SecondsSince20000101 = new Epoch20000101
{
Text = this.CustomerSpecificText
};
features.ParameterizeLeakageDetection = new ParameterizeLeakageDetection
{
Value = (byte)(this.LeakagePeriod | (this.LeakageThreshold * (byte)Math.Pow(2, 3)))
};
features.ParameterizeBrokenPipeDetection = new ParameterizeBrokenPipeDetection
{
Value = (byte)(this.BrokenPipePeriod | (this.BrokenPipeThreshold * (byte)Math.Pow(2, 3)))
};
features.SetHistoricalErrorLimit = new SetHistoricalErrorLimit
{
Value = this.History_Error_Limits_Days
};
features.ChangeDataLoggerSettings = new ChangeDataLoggerSettings
{
TimeInterval = this.Data_Logging_Period,
ForwardCounter = this.Data_Logging_Forward_Counter,
TimeOfMinimumFlow = this.Data_Logging_Time_Of_Minimum_Flow,
MinimumFlow = this.Data_Logging_Minimum_Flow,
TimeOfBrokenPipe = this.Data_Logging_Time_Of_Broken_Pipe,
BrokenPipeFlow = this.Data_Logging_Broken_Pipe_Flow,
CurrentFlow = this.Data_Logging_Current_Flow,
TimeOfPeakFlow = this.Data_Logging_Time_Of_Peak_Flow,
PeakFlow = this.Data_Logging_Peak_Flow,
TimeOfMaximumFlow = this.Data_Logging_Time_Of_Maximum_Flow,
MaximumFlow = this.Data_Logging_Maximum_Flow,
BackwardVolume = this.Data_Logging_Backward_Volume,
Counter = this.Data_Logging_Counter,
AlarmState = this.Data_Logging_Alarm_State,
};
features.ChangeFixedDateReadingSettings = new ChangeFixedDateReadingSettings
{
DayOfMonth = this.FDR_Day_Of_Data_Reading,
ForwardCounter = this.FDR_Forward_Counter,
TimeOfMinimumFlow = this.FDR_Time_Of_Minimum_Flow,
MinimumFlow = this.FDR_Minimum_Flow,
TimeOfBrokenPipe = this.FDR_Time_Of_Broken_Pipe,
BrokenPipeFlow = this.FDR_Broken_Pipe_Flow,
CurrentFlow = this.FDR_Current_Flow,
TimeOfPeakFlow = this.FDR_Time_Of_Peak_Flow,
PeakFlow = this.FDR_Peak_Flow,
TimeOfMaximumFlow = this.FDR_Time_Of_Maximum_Flow,
MaximumFlow = this.FDR_Maximum_Flow,
BackwardVolume = this.FDR_Backward_Volume,
Counter = this.FDR_Counter,
AlarmState = this.FDR_Alarm_State,
};
features.WirelessMBusMode = new WirelessMBusMode(this.MBusStatus);
DateTime = DateTime.UtcNow.AddHours(this.UTC_Offset)
}
};
features.ChangeCustomerText = new ChangeCustomerText
{
Text = this.CustomerSpecificText
};
features.ParameterizeLeakageDetection = new ParameterizeLeakageDetection
{
Value = (byte)(this.LeakagePeriod | (this.LeakageThreshold * (byte)Math.Pow(2, 3)))
};
features.ParameterizeBrokenPipeDetection = new ParameterizeBrokenPipeDetection
{
Value = (byte)(this.BrokenPipePeriod | (this.BrokenPipeThreshold * (byte)Math.Pow(2, 3)))
};
features.SetHistoricalErrorLimit = new SetHistoricalErrorLimit
{
Value = this.History_Error_Limits_Days
};
features.ChangeDataLoggerSettings = new ChangeDataLoggerSettings
{
TimeInterval = this.Data_Logging_Period,
ForwardCounter = this.Data_Logging_Forward_Counter,
TimeOfMinimumFlow = this.Data_Logging_Time_Of_Minimum_Flow,
MinimumFlow = this.Data_Logging_Minimum_Flow,
TimeOfBrokenPipe = this.Data_Logging_Time_Of_Broken_Pipe,
BrokenPipeFlow = this.Data_Logging_Broken_Pipe_Flow,
CurrentFlow = this.Data_Logging_Current_Flow,
TimeOfPeakFlow = this.Data_Logging_Time_Of_Peak_Flow,
PeakFlow = this.Data_Logging_Peak_Flow,
TimeOfMaximumFlow = this.Data_Logging_Time_Of_Maximum_Flow,
MaximumFlow = this.Data_Logging_Maximum_Flow,
BackwardVolume = this.Data_Logging_Backward_Volume,
Counter = this.Data_Logging_Counter,
AlarmState = this.Data_Logging_Alarm_State,
};
features.ChangeFixedDateReadingSettings = new ChangeFixedDateReadingSettings
{
DayOfMonth = this.FDR_Day_Of_Data_Reading,
ForwardCounter = this.FDR_Forward_Counter,
TimeOfMinimumFlow = this.FDR_Time_Of_Minimum_Flow,
MinimumFlow = this.FDR_Minimum_Flow,
TimeOfBrokenPipe = this.FDR_Time_Of_Broken_Pipe,
BrokenPipeFlow = this.FDR_Broken_Pipe_Flow,
CurrentFlow = this.FDR_Current_Flow,
TimeOfPeakFlow = this.FDR_Time_Of_Peak_Flow,
PeakFlow = this.FDR_Peak_Flow,
TimeOfMaximumFlow = this.FDR_Time_Of_Maximum_Flow,
MaximumFlow = this.FDR_Maximum_Flow,
BackwardVolume = this.FDR_Backward_Volume,
Counter = this.FDR_Counter,
AlarmState = this.FDR_Alarm_State,
};
features.WirelessMBusMode = new WirelessMBusMode(this.MBusStatus);
if (this.PowerLevelHex != null)
{
features.SetPowerLevelSensusRF = new SetPowerLevel
{
Value = (byte)(this.PowerLevelHex & 127)
};
features.SetPowerLevelFlexNet = new SetPowerLevel
{
Value = (byte)(this.PowerLevelHex | 128)
};
}
if (!this.IsEbeling && !this.IsFuhzoe)
if (!this.IsEbeling && !this.IsFuhzoe)
{
features.Debug.DisableOTAFirmwareUpdate = new DisableOTAFirmwareUpdate
{
features.Debug.DisableOTAFirmwareUpdate = new DisableOTAFirmwareUpdate
{
Mode = (OTAMode)this.DisableOTA
};
features.Debug.SetActivationByThreshold = new SetActivationByThreshold
{
Rotations = this.ActivationByThreshold
};
features.OpenMeteringTransmitionIntervalWMBus = new OpenMeteringTransmitionIntervalWMBus
{
Seconds = this.OpenMeteringTransmissionIntervalSeconds
};
features.ChangeWakeUp = new ChangeWakeUp
{
Mode = this.Wake_Up_Interval
};
}
Mode = (OTAMode)this.DisableOTA
};
features.Debug.SetActivationByThreshold = new SetActivationByThreshold
{
Rotations = this.ActivationByThreshold
};
features.OpenMeteringTransmitionIntervalWMBus = new OpenMeteringTransmitionIntervalWMBus
{
Seconds = this.OMS_Interval
};
features.ChangeWakeUp = new ChangeWakeUp
{
Mode = this.Wake_Up_Interval
};
}
if (!this.IsEbeling)
if (!this.IsEbeling)
{
features.ChangeTransmissionInterval = new ChangeTransmissionInterval
{
features.ChangeTransmissionInterval = new ChangeTransmissionInterval
{
Seconds = this.TransmissionIntervalFinal,
};
features.ChangeNumberOfLatWindows = new ChangeNumberOfLatWindows
{
N = this.LATWindowsFinal
};
features.ChangeSensusRFEncryptionKey = new ChangeSensusRFEncryptionKey
{
HexKey = this.EncryptionKey
};
features.Debug.ChangeState = new ChangeFactoryState
{
Mode = FactoryState.Shipment
};
}
Seconds = this.Transmission_Intervall,
};
features.ChangeNumberOfLatWindows = new ChangeNumberOfLatWindows
{
N = this.LAT_Interval
};
features.ChangeSensusRFEncryptionKey = new ChangeSensusRFEncryptionKey
{
HexKey = this.EncryptionKey
};
features.Debug.ChangeState = new ChangeFactoryState
{
Mode = FactoryState.Shipment
};
}
return features;
@@ -408,7 +414,7 @@
{
var features = new EregisterFeatures
{
SlotNr = this.Slotno,
SlotNr = this.SlotNr,
SerialNr = this.SerienNr,
PoNr = this.FertigungsauftragNr,
RequestAddress = this.RequestAddress,
@@ -417,33 +423,30 @@
EncryptionKey = this.EncryptionKey.GetEncryptionKey(),
};
if (this.IsValid)
features.ChangeWakeUp = new ChangeWakeUp(WakeUpMode.StayAwake);
features.ChangeTransmissionInterval = new ChangeTransmissionInterval(this.TransmissionIntervalInitialization);
features.ChangeNumberOfLatWindows = new ChangeNumberOfLatWindows(this.LatWindowsInitialization);
features.ChangeMeterReading = new ChangeMeterReading(111_111_111);
features.WirelessMBusMode = new WirelessMBusMode(this.MBusStatus);
features.SetMetrologyParameters = new SetMetrologyParameters
{
features.ChangeWakeUp = new ChangeWakeUp(WakeUpMode.StayAwake);
features.ChangeTransmissionInterval = new ChangeTransmissionInterval(this.TransmissionIntervalInitialization);
features.ChangeNumberOfLatWindows = new ChangeNumberOfLatWindows(this.LatWindowsInitialization);
features.ChangeMeterReading = new ChangeMeterReading(111_111_111);
features.WirelessMBusMode = new WirelessMBusMode(this.MBusStatus);
features.SetMetrologyParameters = new SetMetrologyParameters
UseCandIRules = this.DisallowReverseVolume,
DecimalPoint = (DecimalPointLocations)this.DecimalPoint,
FactoryCalibration = this.FactoryCalibration,
MeterSize = this.MeterSize,
OffsetFactor = this.OffsetFactor,
OffsetTime = this.OffsetTime,
Units = (MessurementUnits)this.UnitsOfMessure,
Vpp = (int)this.VolumePerPulse,
VppLED = this.VolumePerLedPulse
};
features.Debug = new EregisterDebugFeatures
{
OpticalTelegram = new OpticalTelegram
{
UseCandIRules = this.Ruecklaufsperre,
DecimalPoint = (DecimalPointLocations)this.DecimalPoint,
FactoryCalibration = this.FactoryCalibration,
MeterSize = this.MeterSize,
OffsetFactor = this.OffsetFactor,
OffsetTime = this.OffsetTime,
Units = (MessurementUnits)this.UnitsOfMessure,
Vpp = (int)this.VolumePerPulse,
VppLED = (uint)this.VolumePerLedPulse
};
features.Debug = new EregisterDebugFeatures
{
OpticalTelegram = new OpticalTelegram
{
Minutes = 15
}
};
}
Minutes = 240
}
};
return features;
}
@@ -0,0 +1,27 @@
namespace Common.Hardware.WaterMeter.eRegister.Models
{
using System;
public class EregisterState
{
public long? Fabrikationsnummer { get; set; }
public string Bemerkung { get; set; }
public string BUP { get; set; }
public string SEMI { get; set; }
public string DEBUG { get; set; }
public DateTime SemiDebugDatum { get; set; }
public long TempAdresse { get; set; }
public DateTime? GeschlossenDatum { get; set; }
public DateTime? FunkadresseDatum { get; set; }
public long Seriennummer { get; set; }
}
}