82 lines
3.1 KiB
C#
82 lines
3.1 KiB
C#
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();
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|