SIRT Broadcaster - tasks handling

This commit is contained in:
Stoyan Zlatev
2024-07-16 12:21:12 +02:00
parent 836b3be8c4
commit 941263d5bd
12 changed files with 231 additions and 141 deletions
@@ -21,7 +21,7 @@
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<NoWarn>IDE0003;IDE0049;</NoWarn>
<NoWarn>IDE0003;IDE0017;IDE0049;</NoWarn>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
@@ -54,12 +54,12 @@
<Compile Include="Parameters\SirtOperating.cs" />
<Compile Include="Requests\ReadPamRequest.cs" />
<Compile Include="Requests\ReadRegRequest.cs" />
<Compile Include="Requests\SIRTRequest.cs" />
<Compile Include="SIRTRequest.cs" />
<Compile Include="Requests\WritePamRequest.cs" />
<Compile Include="Requests\WriteRegRequest.cs" />
<Compile Include="Responses\AcknOrAnswerResponse.cs" />
<Compile Include="Responses\FromAirResponse.cs" />
<Compile Include="Responses\SIRTResponse.cs" />
<Compile Include="SIRTResponse.cs" />
<Compile Include="SIRTMessage.cs" />
<Compile Include="SIRTBroadcaster.cs" />
<Compile Include="SIRTConstants.cs" />
@@ -1,4 +1,4 @@
namespace Common.Hardware.Interfaces.Ports.SIRT.Requests
namespace Common.Hardware.Interfaces.Ports.SIRT
{
using System;
@@ -1,4 +1,4 @@
namespace Common.Hardware.Interfaces.Ports.SIRT.Responses
namespace Common.Hardware.Interfaces.Ports.SIRT
{
using Common.Hardware.Interfaces.Ports.SIRT.Parameters;
@@ -6,20 +6,27 @@
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
public class SIRTBroadcaster : SIRTSerialPort
{
private static readonly ConcurrentDictionary<UInt32, DateTime> availableDevices
= new ConcurrentDictionary<UInt32, DateTime>();
private static readonly ConcurrentDictionary<UInt32, Queue<SIRTTask>> tasks
= new ConcurrentDictionary<UInt32, Queue<SIRTTask>>();
private static readonly ConcurrentDictionary<Byte, UInt32> pamPool
= new ConcurrentDictionary<Byte, UInt32>();
private readonly ConcurrentDictionary<UInt32, DateTime> endpoints;
private readonly ConcurrentDictionary<UInt32, Queue<SIRTTask>> tasks;
private readonly ConcurrentDictionary<Byte, UInt32> pamPool;
public SIRTBroadcaster(SerialPortSettings settings) : base(settings)
=> this.DataReceived += this.SirtBroadcaster_DataReceived;
private CancellationTokenSource cancellationTokenSource;
private CancellationToken cancellationToken;
public SIRTBroadcaster(SerialPortSettings settings) : base(settings)
{
this.endpoints = new ConcurrentDictionary<UInt32, DateTime>();
this.tasks = new ConcurrentDictionary<UInt32, Queue<SIRTTask>>();
this.pamPool = new ConcurrentDictionary<Byte, UInt32>();
this.DataReceived += this.SirtBroadcaster_DataReceived;
}
public String SIRTID { get; private set; }
@@ -31,19 +38,40 @@
public event Action<UInt32> DeviceUnavailable;
public event Action<String> Exception;
public event Action<UInt32[]> PamPoolChanged;
public void AddTask(SIRTTask task)
=> this.tasks
.GetOrAdd(task.Address, new Queue<SIRTTask>())
.Enqueue(task);
public override void Close()
{
try
{
this.cancellationTokenSource.Cancel();
}
catch (Exception e)
{
this.Notify(e.ToString());
}
base.Close();
}
public override void Open()
{
base.Open();
this.Activate();
if (this.Activated)
this.cancellationTokenSource = new CancellationTokenSource();
this.cancellationToken = this.cancellationTokenSource.Token;
this.StartExecutingPendingTasksAsync();
this.StartTrackingUnavailableDevicesAsync();
if (this.Activate())
{
this.RemoveUnavailableDevices();
this.StartPamPoolTracking();
this.StartPamPoolTrackingAsync();
}
else
{
@@ -51,17 +79,6 @@
}
}
public void Send(SIRTTask task)
{
task.Done += this.Task_Done;
tasks
.GetOrAdd(task.Address, new Queue<SIRTTask>())
.Enqueue(task);
this.Task_Done(task);
}
private Boolean Activate()
{
var manuelResetEventSlim = new ManualResetEventSlim();
@@ -74,7 +91,7 @@
manuelResetEventSlim.Set();
};
this.Send(activationTask);
this.AddTask(activationTask);
manuelResetEventSlim.Wait();
manuelResetEventSlim.Reset();
@@ -97,37 +114,41 @@
}
};
this.Send(identificationTask);
this.AddTask(identificationTask);
manuelResetEventSlim.Wait();
manuelResetEventSlim.Reset();
return this.Activated;
}
private void RemoveUnavailableDevices()
private void StartTrackingUnavailableDevicesAsync()
{
Task.Factory
.StartNew(state =>
{
if (state is SIRTBroadcaster broadcaster)
{
while (true)
var awaiter = new ManualResetEventSlim();
while (!broadcaster.cancellationToken.IsCancellationRequested)
{
var devices = broadcaster.endpoints;
var now = DateTime.Now;
foreach (var address in availableDevices.Keys)
foreach (var address in devices.Keys)
{
if (availableDevices.TryGetValue(address, out var timestamp) && (now - timestamp).TotalSeconds > 30)
if (devices.TryGetValue(address, out var timestamp) && (now - timestamp).TotalSeconds > 30)
{
availableDevices.TryRemove(address, out var _);
devices.TryRemove(address, out var _);
broadcaster.DeviceUnavailable?.Invoke(address);
}
}
Thread.Sleep(10000);
awaiter.Wait(1000, broadcaster.cancellationToken);
awaiter.Reset();
}
}
}, this, CancellationToken.None)
}, this, this.cancellationToken)
.ContinueWith(task =>
{
if (task.Exception != null && task.AsyncState is SIRTBroadcaster broadcaster)
@@ -135,90 +156,86 @@
var exception = task.Exception.ToString();
broadcaster.Notify(exception);
broadcaster.Exception?.Invoke(exception);
broadcaster.Close();
}
}, CancellationToken.None);
}, this.cancellationToken);
}
private void SirtBroadcaster_DataReceived(Byte[] data)
{
var address = default(UInt32);
var dataType = data[1];
if (data[1] == SIRTConstants.FromAir)
if (dataType == SIRTConstants.FromAir)
{
var response = new FromAirResponse(data);
response.MHz = this.Frequency;
address = response.Address;
if (tasks.TryGetValue(address, out var queue) && queue.Count > 0)
if (this.tasks.TryGetValue(address, out var queue) && queue.Count > 0)
{
queue.Peek().BeginAddResponse(response);
}
}
else if (data[1] == SIRTConstants.AcknOrAnswer)
else if (dataType == SIRTConstants.AcknOrAnswer)
{
var response = new AcknOrAnswerResponse(data);
address = response.Address;
if (tasks.TryGetValue(address, out var queue) && queue.Count > 0)
if (this.tasks.TryGetValue(address, out var queue) && queue.Count > 0)
{
queue.Peek().BeginAddResponse(response);
}
}
else
{
var response = new SIRTResponse(data);
address = response.Address;
}
if (this.Activated)
{
availableDevices.AddOrUpdate(address,
addValueFactory: key =>
{
this.DeviceAvailable?.Invoke(key);
this.endpoints.AddOrUpdate(address
, addValueFactory: key =>
{
this.DeviceAvailable?.Invoke(key);
return DateTime.Now;
},
updateValueFactory: (_1, _2) => DateTime.Now);
}
return DateTime.Now;
}
, updateValueFactory: (_1, _2) => DateTime.Now);
}
private void StartPamPoolTracking()
private void StartPamPoolTrackingAsync()
{
Task.Factory
.StartNew(state =>
{
if (state is SIRTBroadcaster broadcaster)
{
var task = default(ReadPamPoolSIRTTask);
var awaiter = new ManualResetEventSlim();
while (true)
while (!broadcaster.cancellationToken.IsCancellationRequested)
{
task = new ReadPamPoolSIRTTask();
var task = new ReadPamPoolSIRTTask();
task.Cancelled += _ => awaiter.Set();
task.Done += _ => awaiter.Set();
task.AddressesParsed += addresses =>
{
for (Byte i = 1; i <= 5; i++)
{
var address = addresses[i - 1];
broadcaster.PamPoolChanged?.Invoke(addresses);
pamPool.AddOrUpdate(i, address, (_, _1) => address);
var length = addresses.Length;
for (Byte i = 0; i < length; i++)
{
var address = addresses[i];
broadcaster.pamPool.AddOrUpdate(i, address, (k, v) => address);
}
broadcaster.PamPoolChanged?.Invoke(addresses);
Thread.Sleep(1);
awaiter.Set();
};
this.Send(task);
awaiter.Wait();
broadcaster.AddTask(task);
awaiter.Wait(broadcaster.cancellationToken);
awaiter.Reset();
Thread.Sleep(1000);
}
}
}, this, CancellationToken.None)
}, this, this.cancellationToken)
.ContinueWith(task =>
{
if (task.Exception != null && task.AsyncState is SIRTBroadcaster broadcaster)
@@ -226,34 +243,68 @@
var exception = task.Exception.ToString();
broadcaster.Notify(exception);
broadcaster.Exception?.Invoke(exception);
broadcaster.Close();
}
}, CancellationToken.None);
}, this.cancellationToken);
}
private void Task_Done(SIRTTask task)
private void StartExecutingPendingTasksAsync()
{
if (tasks.TryGetValue(task, out var queue))
{
while (queue.Count > 0)
Task.Factory
.StartNew(state =>
{
var _task = queue.Peek();
if (_task.IsDone || _task.IsCancelled)
if (state is SIRTBroadcaster broadcaster)
{
queue.Dequeue();
var awaiter = new ManualResetEventSlim();
while (!broadcaster.cancellationToken.IsCancellationRequested)
{
foreach (var tasks in broadcaster.tasks.Values.ToArray())
{
while (tasks.Count > 0)
{
var current = tasks.Peek();
if (current.IsDone || current.IsCancelled)
{
tasks.Dequeue();
continue;
}
else if (!current.IsRunning)
{
var notWritePamTask = current.Type != SIRTConstants.WritePam;
var notInPamPool = !broadcaster.pamPool.Values.ToArray().Any(x => x == current.Address);
if (notWritePamTask || notInPamPool)
{
current.IsRunning = true;
broadcaster.Write(current);
}
}
break;
}
}
awaiter.Wait(250, broadcaster.cancellationToken);
awaiter.Reset();
}
}
else
}, this, this.cancellationToken)
.ContinueWith(task =>
{
if (task.Exception != null && task.AsyncState is SIRTBroadcaster broadcaster)
{
_task.Mhz = this.Frequency;
var exception = task.Exception.ToString();
base.Write(_task);
break;
broadcaster.Notify(exception);
broadcaster.Close();
}
}
}
}, this.cancellationToken);
}
}
}
@@ -1,6 +1,5 @@
namespace Common.Hardware.Interfaces.Ports.SIRT
{
using Common.Hardware.Interfaces.Ports.SIRT.Requests;
using Common.Hardware.Interfaces.Ports.SIRT.Responses;
using System;
@@ -9,24 +8,27 @@
{
protected readonly SIRTRequest request;
private DateTime? timestamp;
public SIRTTask(SIRTRequest request)
{
this.request = request;
this.Type = this.request.message.Cmd;
this.Address = this.request.Address;
}
public UInt32 Address { get; }
public event Action<SIRTTask> Done;
public event Action<SIRTTask> Cancelled;
public UInt16 Mhz { get; internal set; }
public Byte Type { get; }
public UInt32 Address { get; }
public Boolean IsCancelled { get; protected set; }
public Boolean IsDone { get; protected set; }
public event Action<SIRTTask> Done;
public event Action<SIRTTask> Cancelled;
protected DateTime? Timestamp { get; set; }
public Boolean IsRunning { get; internal set; }
internal void BeginAddResponse(FromAirResponse response)
{
@@ -35,11 +37,9 @@
return;
}
response.MHz = this.Mhz;
if (this.timestamp is null)
if (this.Timestamp is null)
{
this.timestamp = DateTime.Now;
this.Timestamp = DateTime.Now;
}
var done = this.FromAirReceived(response);
@@ -54,9 +54,9 @@
return;
}
if (this.timestamp is null)
if (this.Timestamp is null)
{
this.timestamp = DateTime.Now;
this.Timestamp = DateTime.Now;
}
var done = this.AcknOrAnswerReceived(response);
@@ -64,6 +64,18 @@
this.EndAddResponse(done);
}
internal void NotifyRemoved()
{
if (this.IsDone)
{
this.NotifyDone();
}
else
{
this.NotifyCancelled();
}
}
protected virtual Boolean AcknOrAnswerReceived(AcknOrAnswerResponse response)
{
return false;
@@ -94,16 +106,12 @@
{
this.NotifyDone();
}
else if ((DateTime.Now - this.timestamp.Value).TotalSeconds > 15)
else if ((DateTime.Now - this.Timestamp.Value).TotalSeconds > 15)
{
this.NotifyCancelled();
}
}
public static implicit operator SIRTRequest(SIRTTask task) => task.request;
public static implicit operator Byte[] (SIRTTask task) => task.request;
public static implicit operator UInt32(SIRTTask task) => task.Address;
}
}
@@ -55,5 +55,13 @@
return parsed;
}
internal void Reset()
{
this.IsDone = false;
this.IsCancelled = false;
this.IsRunning = false;
this.Timestamp = null;
}
}
}