just some refactoring

This commit is contained in:
Stoyan Zlatev
2024-07-05 11:00:24 +02:00
parent c5ecb784bb
commit 736bfb6ba1
46 changed files with 779 additions and 241 deletions
@@ -21,6 +21,7 @@
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<NoWarn>IDE0003;IDE0049;</NoWarn>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
@@ -59,15 +60,17 @@
<Compile Include="Messages\Payloads\Semi.cs" />
<Compile Include="Requests\ReadPamRequest.cs" />
<Compile Include="Requests\ReadRegRequest.cs" />
<Compile Include="Requests\SIRTRequest.cs" />
<Compile Include="Requests\WritePamRequest.cs" />
<Compile Include="Requests\WriteRegRequest.cs" />
<Compile Include="Responses\AckOrAnswerResponse.cs" />
<Compile Include="Responses\FromAirResponse.cs" />
<Compile Include="SirtMessage.cs" />
<Compile Include="SirtBroadcaster.cs" />
<Compile Include="SirtConstants.cs" />
<Compile Include="Responses\SIRTResponse.cs" />
<Compile Include="SIRTMessage.cs" />
<Compile Include="SIRTBroadcaster.cs" />
<Compile Include="SIRTConstants.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="SirtTask.cs" />
<Compile Include="SIRTTask.cs" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Common.Hardware.Interfaces.Ports\Common.Hardware.Interfaces.Ports.csproj">
@@ -4,7 +4,7 @@
using System;
public class ReadPamRequest : SirtMessage
public class ReadPamRequest : SIRTRequest
{
/// <summary>
/// <list>
@@ -20,16 +20,16 @@
/// </summary>
public Boolean PamStruct
{
get => this.P1 == 1;
set => this.P1 = (Byte)(value ? 1 : 0);
get => this.message.P1 == 1;
set => this.message.P1 = (Byte)(value ? 1 : 0);
}
protected override Byte[] ToByteArray()
{
this.Start = SirtConstants.Pc2Sirt;
this.Cmd = SirtConstants.ReadPam;
this.message.Start = SIRTConstants.Pc2Sirt;
this.message.Cmd = SIRTConstants.ReadPam;
return base.ToByteArray();
return this.message.ToByteArray();
}
}
}
@@ -4,21 +4,20 @@
using System;
public class ReadRegRequest : SirtMessage
public class ReadRegRequest : SIRTRequest
{
public Byte ReadLength
{
get => this.P2;
set => this.P2 = value;
get => this.message.P2;
set => this.message.P2 = value;
}
protected override Byte[] ToByteArray()
{
this.Start = SirtConstants.Pc2Sirt;
this.Cmd = SirtConstants.ReadReg;
this.P2 = this.ReadLength;
this.message.Start = SIRTConstants.Pc2Sirt;
this.message.Cmd = SIRTConstants.ReadReg;
return base.ToByteArray();
return this.message.ToByteArray();
}
}
}
@@ -0,0 +1,26 @@
namespace Common.Hardware.Interfaces.Ports.SIRT.Requests
{
using System;
public abstract class SIRTRequest
{
internal readonly SIRTMessage message = new SIRTMessage();
public UInt32 Address
{
get => this.message.Address;
set => this.message.Address = value;
}
public Byte[] Payload
{
get => this.message.Payload;
set => this.message.Payload = value;
}
protected abstract Byte[] ToByteArray();
public static implicit operator Byte[] (SIRTRequest request)
=> request.ToByteArray();
}
}
@@ -5,10 +5,13 @@
using System;
public class WritePamRequest : SirtMessage
public class WritePamRequest : SIRTRequest
{
private readonly P811 parameter811 = default(Byte);
public WritePamRequest()
=> this.parameter811 = this.message.P1;
/// <summary>
/// <inheritdoc cref="P811.WakeUpModul"/>
/// </summary>
@@ -74,11 +77,11 @@
protected override Byte[] ToByteArray()
{
this.Start = SirtConstants.Pc2Sirt;
this.Cmd = SirtConstants.WritePam;
this.P1 = this.parameter811;
this.message.Start = SIRTConstants.Pc2Sirt;
this.message.Cmd = SIRTConstants.WritePam;
this.message.P1 = this.parameter811;
return base.ToByteArray();
return this.message.ToByteArray();
}
}
}
@@ -4,15 +4,20 @@
using System;
public class WriteRegRequest : SirtMessage
public class WriteRegRequest : SIRTRequest
{
public Byte WriteLength
{
get => this.message.P2;
set => this.message.P2 = value;
}
protected override Byte[] ToByteArray()
{
this.Start = SirtConstants.Pc2Sirt;
this.Cmd = SirtConstants.WriteReg;
this.P2 = this.Length;
this.message.Start = SIRTConstants.Pc2Sirt;
this.message.Cmd = SIRTConstants.WriteReg;
return base.ToByteArray();
return this.message.ToByteArray();
}
}
}
@@ -4,12 +4,12 @@
using System;
public class AckOrAnswerResponse : SirtMessage
public class AckOrAnswerResponse : SIRTResponse
{
private readonly P12 parameterP12;
public AckOrAnswerResponse(Byte[] bytes) : base(bytes)
=> this.parameterP12 = this.P1;
=> this.parameterP12 = this.message.P1;
/// <summary>
/// <inheritdoc cref="P12.BufFull"/>
@@ -51,6 +51,6 @@
/// </summary>
public Boolean WildCardAddr => this.parameterP12.WildCardAddr;
public Byte LastCmd => this.P2;
public Byte LastCmd => this.message.P2;
}
}
@@ -4,14 +4,14 @@
using System;
public class FromAirResponse : SirtMessage
public class FromAirResponse : SIRTResponse
{
private readonly P11 parameterP11;
private Int32 mhz;
public FromAirResponse(Byte[] bytes) : base(bytes)
=> this.parameterP11 = this.P1;
=> this.parameterP11 = this.message.P1;
/// <summary>
/// <inheritdoc cref="P11.SrcChannel"/>
@@ -59,8 +59,8 @@
set
{
this.mhz = value;
this.ReceivePowerDbm = this.CalculateReceivePowerDbm(this.mhz, this.P2);
this.ReceivePowerPer = this.CalculateReceivePowerPer(this.mhz, this.P2);
this.ReceivePowerDbm = this.CalculateReceivePowerDbm(this.mhz, this.message.P2);
this.ReceivePowerPer = this.CalculateReceivePowerPer(this.mhz, this.message.P2);
}
}
@@ -0,0 +1,17 @@
namespace Common.Hardware.Interfaces.Ports.SIRT.Responses
{
using System;
public class SIRTResponse
{
internal readonly SIRTMessage message;
public SIRTResponse(Byte[] bytes) => this.message = new SIRTMessage(bytes);
public Byte Cmd => this.message.Cmd;
public UInt32 Address => this.message.Address;
public Byte[] Payload => this.message.Payload;
}
}
@@ -2,18 +2,22 @@
{
using Common.Hardware.Interfaces.Ports.SIRT.Parameters;
using Common.Hardware.Interfaces.Ports.SIRT.Requests;
using Common.Hardware.Interfaces.Ports.SIRT.Responses;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
public class SirtBroadcaster : SirtSerialPort
public class SIRTBroadcaster : SIRTSerialPort
{
private static readonly ConcurrentDictionary<UInt32, Queue<SirtTask>> tasks
= new ConcurrentDictionary<UInt32, Queue<SirtTask>>();
private static readonly ConcurrentDictionary<UInt32, DateTime> availableDevices
= new ConcurrentDictionary<UInt32, DateTime>();
private static readonly ConcurrentDictionary<UInt32, Queue<SIRTTask>> tasks
= new ConcurrentDictionary<UInt32, Queue<SIRTTask>>();
public SirtBroadcaster(SerialPortSettings settings) : base(settings)
public SIRTBroadcaster(SerialPortSettings settings) : base(settings)
=> this.DataReceived += this.SirtBroadcaster_DataReceived;
public String SirtId { get; private set; }
@@ -22,11 +26,15 @@
public Boolean Ready { get; private set; }
public event Action<UInt32> DeviceAvailable;
public event Action<UInt32> DeviceUnavailable;
public override void Open()
{
base.Open();
_ = this.Write(new WriteRegRequest
_ = this.Send(new WriteRegRequest
{
Address = 0x20000000,
Payload = new Byte[]
@@ -55,7 +63,7 @@
});
var manuelResetEventSlim = new ManualResetEventSlim();
var sirtTask = this.Write(new ReadRegRequest
var sirtTask = this.Send(new ReadRegRequest
{
ReadLength = 8,
Address = 0x11001820
@@ -79,21 +87,25 @@
manuelResetEventSlim.Set();
};
manuelResetEventSlim.Wait();
manuelResetEventSlim.Wait(10000);
if (!this.Ready)
{
this.Close();
}
else
{
this.RemoveUnavailableDevices();
}
}
public SirtTask Write(SirtMessage request)
public SIRTTask Send(SIRTRequest request)
{
var task = new SirtTask(request);
var task = new SIRTTask(request);
task.Done += Task_Done;
var queue = tasks
.GetOrAdd(task.Address, new Queue<SirtTask>());
.GetOrAdd(task.Address, new Queue<SIRTTask>());
queue.Enqueue(task);
if (queue.Count == 1)
@@ -104,7 +116,60 @@
return task;
}
private void Task_Done(SirtTask task)
private void RemoveUnavailableDevices()
{
Task.Factory
.StartNew(state =>
{
if (state is SIRTBroadcaster broadcaster)
{
while (true)
{
var now = DateTime.Now;
foreach (var address in availableDevices.Keys)
{
if (availableDevices.TryGetValue(address, out var timestamp) && (now - timestamp).TotalSeconds > 30)
{
availableDevices.TryRemove(address, out var _);
broadcaster.DeviceUnavailable?.Invoke(address);
}
}
Thread.Sleep(10000);
}
}
}, this, CancellationToken.None)
.ContinueWith(task =>
{
if (task.Exception != null && task.AsyncState is SIRTBroadcaster broadcaster)
{
broadcaster.Notify(task.Exception.ToString());
}
}, CancellationToken.None);
}
private void SirtBroadcaster_DataReceived(Byte[] data)
{
var response = new SIRTResponse(data);
var address = response.Address;
if (tasks.TryGetValue(address, out var queue) && queue.Count > 0)
{
queue.Peek().AddResponse(response);
}
availableDevices.AddOrUpdate(address,
addValueFactory: key =>
{
this.DeviceAvailable?.Invoke(key);
return DateTime.Now;
},
updateValueFactory: (_1, _2) => DateTime.Now);
}
private void Task_Done(SIRTTask task)
{
if (tasks.TryGetValue(task.Address, out var queue))
{
@@ -123,15 +188,5 @@
}
}
}
private void SirtBroadcaster_DataReceived(Byte[] data)
{
var response = new SirtMessage(data);
if (tasks.TryGetValue(response.Address, out var queue) && queue.Count > 0)
{
queue.Peek().AddResponse(response);
}
}
}
}
@@ -2,7 +2,7 @@
{
using System;
public static class SirtConstants
public static class SIRTConstants
{
public const Int32 CmdIndex = 1;
public const Int32 LengthIndex = 8;
@@ -4,18 +4,18 @@
using System;
public class SirtMessage
internal class SIRTMessage
{
private Byte[] bytes;
private Int32 bytesLength;
public SirtMessage()
public SIRTMessage()
{
this.bytes = new Byte[SirtConstants.MinLength];
this.bytes = new Byte[SIRTConstants.MinLength];
this.bytesLength = this.bytes.Length;
}
public SirtMessage(Byte[] bytes)
public SIRTMessage(Byte[] bytes)
{
this.bytes = bytes;
this.bytesLength = this.bytes.Length;
@@ -71,7 +71,7 @@
set
{
this.bytes[8] = value;
var newLength = SirtConstants.MinLength + value;
var newLength = SIRTConstants.MinLength + value;
Array.Resize(ref this.bytes, newLength);
this.bytesLength = this.bytes.Length;
@@ -96,7 +96,7 @@
}
this.Length = (Byte)value.Length;
var newLength = SirtConstants.MinLength + this.Length;
var newLength = SIRTConstants.MinLength + this.Length;
Array.Resize(ref this.bytes, newLength);
Array.Copy(value, 0, this.bytes, 9, this.Length);
@@ -116,24 +116,24 @@
public override String ToString()
=> BitConverter.ToString(this.ToByteArray());
protected virtual Byte[] ToByteArray()
internal Byte[] ToByteArray()
{
var crc = CRC1021.CalculateCRC1021(this.bytes, 1, this.bytesLength - 3);
this.bytes[this.bytesLength - 3] = crc.MSB;
this.bytes[this.bytesLength - 2] = crc.LSB;
this.bytes[this.bytesLength - 1] = SirtConstants.StopByte;
this.bytes[this.bytesLength - 1] = SIRTConstants.StopByte;
return this.bytes;
}
public static implicit operator SirtMessage(Byte[] bytes)
=> new SirtMessage(bytes);
public static implicit operator SIRTMessage(Byte[] bytes)
=> new SIRTMessage(bytes);
public static implicit operator Byte[](SirtMessage message)
public static implicit operator Byte[](SIRTMessage message)
=> message.ToByteArray();
public static implicit operator String (SirtMessage message)
public static implicit operator String (SIRTMessage message)
=> message.ToString();
}
}
@@ -1,29 +1,32 @@
namespace Common.Hardware.Interfaces.Ports.SIRT
{
using Common.Hardware.Interfaces.Ports.SIRT.Requests;
using Common.Hardware.Interfaces.Ports.SIRT.Responses;
using System;
using System.Collections.Generic;
public class SirtTask
public class SIRTTask
{
private readonly SirtMessage request;
private readonly ICollection<SirtMessage> responses;
private readonly SIRTRequest request;
private readonly ICollection<SIRTResponse> responses;
public SirtTask(SirtMessage request)
internal SIRTTask(SIRTRequest request)
{
this.request = request;
this.Address = this.request.Address;
this.responses = new List<SirtMessage>();
this.responses = new List<SIRTResponse>();
}
public event Action<SirtTask> Done;
public event Action<SIRTTask> Done;
public UInt32 Address { get; }
public Boolean IsDone { get; private set; }
public SirtMessage Last { get; private set; }
public SIRTResponse Last { get; private set; }
internal void AddResponse(SirtMessage response)
internal void AddResponse(SIRTResponse response)
{
if (!this.IsDone)
{
@@ -32,8 +35,8 @@
this.responses.Add(response);
if ((response.Cmd == SirtConstants.FromAir && response.Payload[0] == SirtConstants.Semi)
|| (response.Cmd == SirtConstants.AckOrAnswer && response.Payload.Length > 0))
if ((response.Cmd == SIRTConstants.FromAir && response.Payload[0] == SIRTConstants.Semi)
|| (response.Cmd == SIRTConstants.AckOrAnswer && response.Payload.Length > 0))
{
this.IsDone = true;
@@ -41,7 +44,7 @@
}
}
public static implicit operator Byte[](SirtTask task)
public static implicit operator Byte[](SIRTTask task)
=> task.request;
}
}
@@ -21,6 +21,7 @@
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<NoWarn>IDE0003;IDE0049;</NoWarn>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
@@ -40,7 +41,7 @@
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="IrdaSerialPort.cs" />
<Compile Include="IRDASerialPort.cs" />
<Compile Include="SerialPort.cs" />
<Compile Include="SerialPortBase.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
@@ -50,7 +51,7 @@
<Compile Include="SerialPortParity.cs" />
<Compile Include="SerialPortSettings.cs" />
<Compile Include="SerialPortStopBits.cs" />
<Compile Include="SirtSerialPort.cs" />
<Compile Include="SIRTSerialPort.cs" />
<Compile Include="UniProSerialPort.cs" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
@@ -3,9 +3,9 @@
using System;
using System.Threading;
public class IrdaSerialPort : SerialPort
public class IRDASerialPort : SerialPort
{
public IrdaSerialPort(SerialPortSettings settings) : base(settings)
public IRDASerialPort(SerialPortSettings settings) : base(settings)
{
}
@@ -15,7 +15,7 @@
if (data.TryParseToIrda(out var bytes))
{
for (int i = 0; i < 3; i++)
for (var i = 0; i < 3; i++)
{
this.serialPortBase.Write(new Byte[] { 0x01, 0x01, 0x01, 0x01 }, 0, 4);
@@ -28,6 +28,8 @@
}
}
protected void Notify(String message) => this.serialPortBase.Notify(message);
public virtual void Open() => this.serialPortBase.Open();
public abstract Byte[] Write(params Byte[] data);
@@ -42,21 +42,21 @@
serialPort.Dispose();
serialPort = null;
this.NotifyInfoMessage($"Disconnected: {this}");
this.Notify($"Disconnected: {this}");
}
else
{
this.NotifyInfoMessage($"{this.PortName} is null!");
this.Notify($"{this.PortName} is null!");
}
}
else
{
this.NotifyInfoMessage($"{this.PortName} dose not exists!");
this.Notify($"{this.PortName} dose not exists!");
}
}
catch (Exception e)
{
this.NotifyInfoMessage(e.ToString());
this.Notify(e.ToString());
}
}
@@ -83,16 +83,16 @@
{
serialPort.Open();
this.NotifyInfoMessage($"Connected: {this}");
this.Notify($"Connected: {this}");
}
else
{
this.NotifyInfoMessage($"{this.PortName} cann't be addedd!");
this.Notify($"{this.PortName} cann't be addedd!");
}
}
catch (Exception e)
{
this.NotifyInfoMessage(e.ToString());
this.Notify(e.ToString());
}
}
@@ -113,11 +113,11 @@
Buffer.BlockCopy(buffer, 0, bytes, 0, bytesToCopy);
this.NotifyInfoMessage($"RX|{BitConverter.ToString(bytes)}");
this.Notify($"RX|{BitConverter.ToString(bytes)}");
}
catch (Exception e)
{
this.NotifyInfoMessage(e.ToString());
this.Notify(e.ToString());
}
}
@@ -150,16 +150,16 @@
serialPort.Write(bytes, start, length);
}
this.NotifyInfoMessage($"TX|{BitConverter.ToString(bytes)}");
this.Notify($"TX|{BitConverter.ToString(bytes)}");
}
catch (Exception e)
{
this.NotifyInfoMessage(e.ToString());
this.Notify(e.ToString());
}
}
}
public void NotifyInfoMessage(String state)
public void Notify(String state)
=> this.Logging?.Invoke(state);
}
}
@@ -4,14 +4,14 @@
using System.Threading;
using System.Threading.Tasks;
public class SirtSerialPort : SerialPort
public class SIRTSerialPort : SerialPort
{
private CancellationTokenSource cancellationTokenSource;
private CancellationToken cancellationToken;
private Task listener;
private bool listening;
public SirtSerialPort(SerialPortSettings settings) : base(settings)
public SIRTSerialPort(SerialPortSettings settings) : base(settings)
{
}
@@ -56,7 +56,7 @@
this.cancellationToken = this.cancellationTokenSource.Token;
this.listener = Task.Factory.StartNew(asyncState =>
{
if (asyncState is SirtSerialPort sirtSerialPort)
if (asyncState is SIRTSerialPort sirtSerialPort)
{
sirtSerialPort.listening = true;
@@ -115,11 +115,11 @@
}, this, this.cancellationToken)
.ContinueWith(task =>
{
if (task.AsyncState is SirtSerialPort sirtSerialPort)
if (task.AsyncState is SIRTSerialPort sirtSerialPort)
{
if (task.Exception != null)
{
sirtSerialPort.serialPortBase.NotifyInfoMessage(task.Exception.ToString());
sirtSerialPort.serialPortBase.Notify(task.Exception.ToString());
}
sirtSerialPort.listening = false;
@@ -137,7 +137,7 @@
}
catch (Exception e)
{
this.serialPortBase.NotifyInfoMessage(e.ToString());
this.serialPortBase.Notify(e.ToString());
}
}
}