Files
laatzen/Common/Hardware/Common.Hardware.SIRT/SIRTBroadcaster.cs
T

229 lines
7.2 KiB
C#

namespace Common.Hardware.SIRT
{
using Common.Hardware.SIRT.Tasks;
using System;
using System.Collections.Concurrent;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
public class SIRTBroadcaster
{
private readonly ConcurrentDictionary<uint, SIRTTask> tasks;
private readonly ConcurrentDictionary<byte, uint> pampool;
private readonly SIRTStream sirtStream;
public string AdddressesInPamPool()
{
return string.Join("\t", this.pampool.Values);
}
private CancellationTokenSource cancellationTokenSource;
private CancellationToken cancellationToken;
private Task receiveStream;
private Task pampoolStream;
public SIRTBroadcaster(string portName)
{
this.sirtStream = new SIRTStream(portName);
this.pampool = new ConcurrentDictionary<byte, uint>();
_ = this.pampool.GetOrAdd(0, 0);
_ = this.pampool.GetOrAdd(0, 0);
_ = this.pampool.GetOrAdd(0, 0);
_ = this.pampool.GetOrAdd(0, 0);
_ = this.pampool.GetOrAdd(0, 0);
this.tasks = new ConcurrentDictionary<uint, SIRTTask>();
}
public event Action<SIRTBroadcaster> Connected;
public event Action<SIRTBroadcaster> Disconnected;
public event Action<SIRTMessage> MessageReceived;
public string Id { get; private set; }
public int Frequency { get; private set; }
public bool IsOpen => this.sirtStream.IsOpen;
public string PortName => this.sirtStream.PortName;
public void Close()
{
this.sirtStream.Close();
void Try(Action action)
{
try
{
action();
}
catch (Exception e)
{
SIRTLogger.LogMessage(e);
}
}
Try(this.tasks.Clear);
Try(this.pampool.Clear);
Try((this.cancellationTokenSource ?? new CancellationTokenSource()).Cancel);
var disconnectedEvent = this.Disconnected;
if (disconnectedEvent != null)
{
disconnectedEvent?.Invoke(this);
}
}
public void Open()
{
this.sirtStream.Open();
if (this.sirtStream.IsOpen)
{
this.cancellationTokenSource = new CancellationTokenSource();
this.cancellationToken = this.cancellationTokenSource.Token;
this.receiveStream = Task.Factory
.StartNew(this.ReceiveAsync, this.cancellationToken)
.ContinueWith(this.LogContinuationError);
SIRTLogger.LogState("Activating SIRT");
if (this.TryActivate(out var id, out var frequency))
{
this.Id = id;
this.Frequency = frequency;
this.pampoolStream = Task.Factory
.StartNew(this.PampoolAsync, this.cancellationToken)
.ContinueWith(this.LogContinuationError);
var connectedEvent = this.Connected;
if (connectedEvent != null)
{
connectedEvent?.Invoke(this);
}
SIRTLogger.LogState($"Activated: {frequency} - {id}");
}
else
{
this.Close();
SIRTLogger.LogState("Activation failed");
}
}
}
/// <summary>
/// Checks if the given task can be sent then replaces existing SIRTTask (if any) and starts the new one.
/// </summary>
public bool Start(SIRTTask task)
{
if (task.Frequency == this.Frequency)
{
var address = task.RequestAddress;
var addresses = this.pampool.Values.ToList();
if (addresses.Any(x => x == 0 || x == address))
{
task.SirtId = this.Id;
this.tasks
.AddOrUpdate(task.RequestAddress, addr => task, (addr, oldTask) => task);
var bytes = this.tasks
.AddOrUpdate(task.ResponseAddress, addr => task, (addr, oldTask) => task)
.Start();
this.sirtStream.Write(bytes);
SIRTLogger.LogMessage($"{this.PortName}|TX: {BitConverter.ToString(bytes)}");
return true;
}
else
{
SIRTLogger.LogMessage($"{this.PortName}|PP: {string.Join(", ", addresses)}");
}
}
else
{
SIRTLogger.LogMessage($"{this.PortName}|RF: {task.RequestAddress} -> {task.Frequency} != {this.Frequency}");
}
return false;
}
private void LogContinuationError(Task task)
{
if (task?.Exception != null)
{
SIRTLogger.LogState(task.Exception);
}
}
private async Task PampoolAsync()
{
var task = new ReadPampoolTask(this.Frequency);
var addresses = task.Addresses;
var addressesCount = addresses.Length;
this.pampool.Clear();
for (byte i = 0; i < addressesCount; i++)
{
this.pampool.AddOrUpdate(i, addresses[i], (ix, addr) => addresses[i]);
}
while (this.IsOpen)
{
this.Start(task);
task.Wait();
addresses = task.Addresses;
for (byte i = 0; i < addressesCount; i++)
{
this.pampool.AddOrUpdate(i, addresses[i], (ix, addr) => addresses[i]);
}
await Task.Delay(3000);
}
}
private void ReceiveAsync()
{
SIRTLogger.LogState("Message receiving started");
var cancellationToken = this.cancellationToken;
var messageReceivedEvent = this.MessageReceived;
foreach (SIRTMessage message in this.sirtStream.Read())
{
message.Timestamp = DateTimeOffset.UtcNow;
message.Frequency = this.Frequency;
message.SirtId = this.Id;
if (this.tasks.TryGetValue(message.Address, out var task))
{
task.Push(message);
if (task.State == SIRTTaskState.Completed || task.State == SIRTTaskState.Cancelled)
{
this.tasks.TryRemove(task.RequestAddress, out _);
this.tasks.TryRemove(task.ResponseAddress, out _);
}
}
if (messageReceivedEvent != null)
{
messageReceivedEvent(message);
}
SIRTLogger.LogMessage($"{this.PortName}|RX: {BitConverter.ToString(message)}");
cancellationToken.ThrowIfCancellationRequested();
}
SIRTLogger.LogState("Message receiving stopped");
}
}
}