seit lange nicht mehr commited!

This commit is contained in:
Stoyan Zlatev
2025-03-13 13:55:56 +01:00
parent 8a9e7aaa78
commit 2f61122ea5
140 changed files with 1293 additions and 6740 deletions
@@ -57,14 +57,12 @@
<Compile Include="Parameters\SirtOperating.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="SerialDataExtensions.cs" />
<Compile Include="SerialPort.cs" />
<Compile Include="SIRTPort.cs" />
<Compile Include="SIRTBroadcaster.Internal.cs" />
<Compile Include="SIRTFactory.cs" />
<Compile Include="SIRTBroadcaster.Public.cs" />
<Compile Include="SIRTKey.cs" />
<Compile Include="SIRTMessage.cs" />
<Compile Include="SIRTStream.cs" />
<Compile Include="SIRTStreamFactory.cs" />
<Compile Include="SIRTTask.Public.cs" />
<Compile Include="SIRTTaskState.cs" />
</ItemGroup>
@@ -4,20 +4,50 @@
public class PAMStatus
{
private byte _byte;
private readonly byte[] bits;
public PAMStatus(byte _byte)
=> this.bits = _byte.GetBitsLE();
{
this._byte = _byte;
this.bits = _byte.GetBitsLE();
}
public bool CMD_UNKNOWN => this.bits[0] == 1;
public bool IsOK
{
get => this._byte == 0;
set => this._byte = (byte)(value ? 0 : 0xFF);
}
public bool WRONG_AUTH => this.bits[1] == 1;
public bool CMD_UNKNOWN
{
get => this.bits[0] == 1;
set => this.bits[0] = (byte)(value ? 1 : 0);
}
public bool EXPIRED_AUTH => this.bits[2] == 1;
public bool WRONG_AUTH
{
get => this.bits[1] == 1;
set => this.bits[1] = (byte)(value ? 1 : 0);
}
public bool MIXED_TYPES => this.bits[3] == 1;
public bool EXPIRED_AUTH
{
get => this.bits[2] == 1;
set => this.bits[2] = (byte)(value ? 1 : 0);
}
public bool OUT_OF_RANGE => this.bits[4] == 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 override string ToString()
{
@@ -12,8 +12,7 @@
private readonly ConcurrentDictionary<uint, ConcurrentQueue<SIRTTask>> tasks
= new ConcurrentDictionary<uint, ConcurrentQueue<SIRTTask>>();
private readonly ManualResetEventSlim tasksAwaiter = new ManualResetEventSlim();
private readonly IList<bool> tasksInPampool = new List<bool>();
private readonly SerialPort serialPort;
private readonly SIRTPort serialPort;
private CancellationTokenSource cancellationTokenSource;
private CancellationToken cancellationToken;
@@ -169,23 +168,10 @@
{
while (!this.cancellationToken.IsCancellationRequested)
{
if (this.tasksInPampool.Count >= 5)
{
this.tasksAwaiter.Wait();
this.tasksAwaiter.Reset();
}
foreach (var tasksQueue in this.tasks.Values.ToArray())
{
if (this.tasksInPampool.Count >= 5)
{
this.tasksAwaiter.Wait();
this.tasksAwaiter.Reset();
}
if (tasksQueue.TryPeek(out var task) && task.State == SIRTTaskState.Pending)
{
this.tasksInPampool.Add(true);
this.serialPort.Write(task.Start());
this.Logging?.Invoke(task.ToString());
}
@@ -281,13 +267,6 @@
task.Completed -= this.OnStateChanged;
task.Timeouted -= this.OnTaskTimeout;
var lastIX = this.tasksInPampool.Count - 1;
if (lastIX >= 0)
{
this.tasksInPampool.RemoveAt(lastIX);
}
this.tasksAwaiter.Set();
}
@@ -10,7 +10,7 @@
{
public SIRTBroadcaster(string comPort)
{
this.serialPort = new SerialPort(comPort, 115200, Parity.None, 8, StopBits.One);
this.serialPort = new SIRTPort(comPort, 115200, Parity.None, 8, StopBits.One);
this.tasks = new ConcurrentDictionary<uint, ConcurrentQueue<SIRTTask>>();
}
@@ -20,7 +20,7 @@
public event Action<string> Logging;
public event Action<SIRTMessage> MessageReceived;
public string COMPort => this.serialPort.COMPort;
public string COMPort => this.serialPort.PortName;
public string HexId { get; protected set; }
@@ -45,16 +45,13 @@
public void Open()
{
if (!this.serialPort.IsOpen)
{
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.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.serialPort.Open();
}
this.serialPort.Open();
}
public void DequeueTasks(uint address)
@@ -84,8 +81,5 @@
}
}
}
public void RemoveConnection()
=> this.serialPort.Remove();
}
}
@@ -29,7 +29,7 @@
}
}
public void ConnectSIRT(string portName, Action<SIRTBroadcaster> callback)
public SIRTBroadcaster ConnectSIRT(string portName)
{
if (!this.broadcasters.TryGetValue(portName, out var broadcaster))
{
@@ -38,16 +38,19 @@
if (!this.broadcasters.TryAdd(portName, broadcaster))
{
this.NotifyMessage($"Cannot add SIRT on {portName}");
broadcaster = null;
}
}
if (broadcaster?.IsActivated == false)
if (broadcaster != null)
{
broadcaster?.Close();
broadcaster?.Open();
}
callback(broadcaster);
return broadcaster;
}
public void EnqueueTask(SIRTTask task)
@@ -64,8 +67,9 @@
{
if (this.broadcasters.TryRemove(key, out var broadcaster))
{
broadcaster.Close();
broadcaster.Logging -= this.NotifyMessage;
broadcaster.RemoveConnection();
}
}
}
@@ -0,0 +1,145 @@
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 awaiter = new ManualResetEventSlim();
void dataReceived(object _, SerialDataReceivedEventArgs args)
{
if (args.EventType == SerialData.Chars)
{
awaiter.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 (!awaiter.IsSet)
{
awaiter.Wait();
awaiter.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());
}
awaiter.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();
}
}
@@ -1,263 +0,0 @@
namespace Common.Hardware.SIRT
{
using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Threading;
using System.Threading.Tasks;
using SystemSerialPort = System.IO.Ports.SerialPort;
public class SIRTStream
{
private readonly SystemSerialPort serialPort = new SystemSerialPort
{
BaudRate = 112500,
DataBits = 8,
Parity = Parity.None,
StopBits = StopBits.One
};
public bool IsRunning { get; private set; }
public string Identity { get; private set; }
public int Frecuency { get; private set; }
public SIRTKey Key { get; private set; }
public string PortName => this.serialPort.PortName;
public void Close(int timeout = 3000)
{
var disposeAwaiter = new ManualResetEventSlim();
void Disposed(object _, EventArgs _1)
{
this.serialPort.Disposed -= Disposed;
disposeAwaiter.Set();
}
try
{
this.serialPort.Disposed += Disposed;
this.serialPort.Close();
disposeAwaiter.Wait(timeout);
}
catch // TODO: (Exception e)
{
this.serialPort.Disposed -= Disposed;
disposeAwaiter.Set();
}
}
public void Open(string portName, int timeout = 3000)
{
if (this.serialPort.IsOpen)
{
this.IsRunning = false;
this.Close();
}
this.serialPort.PortName = portName;
try
{
this.serialPort.Open();
}
catch // TODO: (Exception e)
{
return;
}
var sirtRequest = default(SIRTMessage);
var sirtRequestBytes = default(byte[]);
var sirtResponse = default(SIRTMessage);
var sirtResponseAwaiter = new ManualResetEventSlim();
var cancellationTokenSource = new CancellationTokenSource();
var cancellationToken = cancellationTokenSource.Token;
var cancellationTask = Task.Run(() =>
{
foreach (var message in this.ReadStream())
{
var sameAddress = message.Address == sirtRequest?.Address;
var isAnswer = message.Cmd == SIRTMessage.ACKNANSW;
var withNoErrors = message.P1 == 0;
var readOrWrite = message.P2 == SIRTMessage.W_REG || message.P2 == SIRTMessage.R_REG;
if (sameAddress && isAnswer && withNoErrors && readOrWrite)
{
sirtResponse = message;
sirtResponseAwaiter.Set();
}
}
}, cancellationToken);
try
{
sirtResponse = null;
sirtRequest = SIRTMessage.Activate;
sirtRequestBytes = sirtRequest.GetBytes();
for (var i = 0; i < 5; i++)
{
this.Write(sirtRequestBytes);
sirtResponseAwaiter.Wait(timeout);
sirtResponseAwaiter.Reset();
if (sirtResponse != null)
{
break;
}
}
sirtResponse = null;
sirtRequest = SIRTMessage.Identify;
sirtRequestBytes = sirtRequest.GetBytes();
for (var i = 0; i < 5; i++)
{
this.Write(sirtRequestBytes);
sirtResponseAwaiter.Wait(timeout);
sirtResponseAwaiter.Reset();
if (sirtResponse != null)
{
this.IsRunning = true;
this.Identity = BitConverter.ToString(sirtResponse.Data ?? Array.Empty<byte>());
this.Frecuency = string.IsNullOrWhiteSpace(this.Identity)
? -1
: this.Identity[10] == '0'
? 868
: 433;
this.Key = new SIRTKey(this.Identity, this.Frecuency);
break;
}
}
cancellationTokenSource.Cancel();
}
catch // TODO: (Exception e)
{
return;
}
}
public IEnumerable<SIRTMessage> ReadStream()
{
var readAwaiter = new ManualResetEventSlim();
void DataReceived(object _, SerialDataReceivedEventArgs args)
{
if (args.EventType == SerialData.Chars)
{
readAwaiter.Set();
}
}
this.serialPort.DataReceived += DataReceived;
var buffer = new List<byte>();
var bytes = default(byte[]);
var length = default(int);
while (this.serialPort.IsOpen)
{
readAwaiter.Wait();
readAwaiter.Reset();
bytes = new byte[this.serialPort.BytesToRead];
length = this.serialPort.Read(bytes, 0, bytes.Length);
if (length <= 0)
{
continue;
}
buffer.AddRange(bytes);
while (this.TryParseMessage(buffer, out var message))
{
yield return message;
}
}
this.serialPort.DataReceived -= DataReceived;
}
public void Write(byte[] bytes)
{
if (this.serialPort.IsOpen && bytes?.Length > 0)
{
this.serialPort.Write(bytes, 0, bytes.Length);
}
}
private bool TryParseMessage(List<Byte> buffer, out SIRTMessage message)
{
message = default(SIRTMessage);
var bufferLength = buffer.Count;
if (bufferLength <= 0)
{
return false;
}
var msgLength = 0;
var msg = default(byte[]);
var startIX = buffer.IndexOf(SIRTMessage.SIRT2PC);
if (startIX < 0)
{
buffer.Clear();
return false;
}
var lengthIX = startIX + 8;
if (lengthIX >= bufferLength)
{
return false;
}
var dataLength = buffer[lengthIX];
var stopIX = lengthIX + dataLength + 3;
if (stopIX >= bufferLength)
{
return false;
}
if (buffer[stopIX] != SIRTMessage.STOP)
{
startIX = buffer.IndexOf(SIRTMessage.SIRT2PC, startIX + 1);
if (startIX >= 0)
{
buffer.RemoveRange(0, startIX + 1);
}
else
{
buffer.Clear();
}
return false;
}
msgLength = stopIX - startIX + 1;
msg = new byte[msgLength];
buffer.CopyTo(startIX, msg, 0, msgLength);
buffer.RemoveRange(0, startIX + msgLength);
message = new SIRTMessage(msg);
return true;
}
}
}
@@ -1,81 +0,0 @@
namespace Common.Hardware.SIRT
{
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
public class SIRTStreamFactory
{
private readonly ConcurrentDictionary<SIRTKey, SIRTStream> streams = new ConcurrentDictionary<SIRTKey, SIRTStream>();
private readonly ConcurrentDictionary<SIRTKey, List<bool>> pams = new ConcurrentDictionary<SIRTKey, List<bool>>();
private readonly ConcurrentDictionary<SIRTKey, Task> readers = new ConcurrentDictionary<SIRTKey, Task>();
private readonly ConcurrentDictionary<uint, PamChanel> chanels
= new ConcurrentDictionary<uint, PamChanel>();
private readonly ConcurrentDictionary<uint, ConcurrentBag<SIRTKey>> addresses
= new ConcurrentDictionary<uint, ConcurrentBag<SIRTKey>>();
private CancellationTokenSource cancellationTokenSource;
private CancellationToken cancellationToken;
private Task cancellationTaks;
public void ConnectSirts(params string[] portNames)
{
this.cancellationTokenSource = new CancellationTokenSource();
this.cancellationToken = this.cancellationTokenSource.Token;
var tasks = new List<Task>();
foreach (var portName in portNames.Intersect(SerialPort.GetPortNames()))
{
var task = Task.Run(() =>
{
var sirtStream = new SIRTStream();
sirtStream.Open(portName);
if (sirtStream.IsRunning)
{
this.streams.GetOrAdd(sirtStream.Key, sirtStream);
this.pams.GetOrAdd(sirtStream.Key, new List<bool>());
this.readers.GetOrAdd(sirtStream.Key, Task.Run(() =>
{
var stream = sirtStream;
var key = stream.Key;
foreach (var message in stream.ReadStream())
{
var address = message.Address;
this.addresses
.GetOrAdd(address, new ConcurrentBag<SIRTKey>())
.Add(key);
this.chanels
.GetOrAdd(message.Address, new PamChanel())
.Push(message);
}
}
, this.cancellationToken));
}
});
tasks.Add(task);
}
Task.WaitAll(tasks.ToArray());
this.cancellationTaks = Task.Run((Action)this.StartSendingPams, this.cancellationToken);
}
private void StartSendingPams()
{
while (!this.cancellationToken.IsCancellationRequested)
{
foreach (var chanel in this.chanels.Values)
{
chanel.Pop();
}
}
}
}
}
@@ -1,207 +0,0 @@
namespace Common.Hardware.SIRT
{
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO.Ports;
using System.Threading;
using SysSerialPort = System.IO.Ports.SerialPort;
public sealed class SerialPort
{
private static readonly ConcurrentDictionary<string, SysSerialPort> serialPorts
= new ConcurrentDictionary<string, SysSerialPort>();
private readonly ManualResetEventSlim readAwaiter;
private readonly ManualResetEventSlim closeAwaiter;
public SerialPort(string name, int baudRate, Parity parity, int dataBits, StopBits stopBits)
{
this.COMPort = name;
this.readAwaiter = new ManualResetEventSlim();
this.closeAwaiter = new ManualResetEventSlim();
var sp = new SysSerialPort(this.COMPort, baudRate, parity, dataBits, stopBits);
serialPorts.AddOrUpdate(this.COMPort, sp, (key, value) =>
{
value?.Close();
return sp;
});
}
public event Action Connected;
public event Action Disconnected;
public event Action<string> Logging;
public string COMPort { get; }
public bool IsOpen => serialPorts.TryGetValue(this.COMPort, out var sp) && sp.IsOpen;
public void Close()
{
if (serialPorts.TryGetValue(this.COMPort, out var sp))
{
try
{
sp.Close();
this.closeAwaiter.Wait(5000);
this.closeAwaiter.Reset();
sp.DataReceived -= this.SP_DataReceived;
sp.Disposed -= this.SP_Disposed;
}
catch (Exception e)
{
this.Logging?.Invoke(e.ToString());
}
}
}
public void Open()
{
if (serialPorts.TryGetValue(this.COMPort, out var sp) && !sp.IsOpen)
{
try
{
sp.DataReceived += this.SP_DataReceived;
sp.Disposed += this.SP_Disposed;
sp.Open();
this.Connected?.Invoke();
}
catch (Exception e)
{
this.Logging?.Invoke(e.ToString());
}
}
}
public IEnumerable<byte[]> ReadBytes()
{
var sp = this.GetOpenedSP();
var size = sp.ReadBufferSize;
var buffer = new byte[size];
var length = 0;
using (sp)
{
while (sp.IsOpen)
{
this.readAwaiter.Wait();
try
{
buffer = new byte[size];
length = sp.Read(buffer, 0, size);
Array.Resize(ref buffer, length);
}
catch (Exception e)
{
this.Logging?.Invoke(e.ToString());
}
this.readAwaiter.Reset();
yield return buffer;
}
sp.Close();
}
}
public IEnumerable<string> ReadLines()
{
var sp = this.GetOpenedSP();
var text = default(string);
using (sp)
{
while (sp.IsOpen)
{
this.readAwaiter.Wait();
try
{
text = sp.ReadLine();
}
catch (Exception e)
{
this.Logging?.Invoke(e.ToString());
}
this.readAwaiter.Reset();
yield return text;
}
}
}
public void Remove()
{
if (serialPorts.TryRemove(this.COMPort, out var sp))
{
sp.Close();
}
}
public void Write(byte[] bytes)
{
var sp = this.GetOpenedSP();
try
{
sp.Write(bytes, 0, bytes.Length);
}
catch (Exception e)
{
this.Logging?.Invoke(e.ToString());
}
}
public void Write(string text)
{
var sp = this.GetOpenedSP();
try
{
sp.Write(text);
}
catch (Exception e)
{
this.Logging?.Invoke(e.ToString());
}
}
private SysSerialPort GetOpenedSP()
{
if (!serialPorts.TryGetValue(this.COMPort, out var sp))
{
throw new InvalidOperationException($"{nameof(SerialPort)} on {this.COMPort} dose not exists!");
}
if (!sp.IsOpen)
{
this.Close();
this.Open();
}
return sp;
}
private void SP_DataReceived(object _, SerialDataReceivedEventArgs args)
=> this.readAwaiter.Set();
private void SP_Disposed(object _, EventArgs _1)
{
this.closeAwaiter.Set();
this.Disconnected?.Invoke();
}
public static string[] GetPortNames()
=> SysSerialPort.GetPortNames();
}
}