eRegister programming execute tasks in a row

This commit is contained in:
Stoyan Zlatev
2024-09-09 16:37:07 +02:00
parent 3522432831
commit 7bf23ce60c
8 changed files with 301 additions and 324 deletions
@@ -2,17 +2,14 @@
{
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using System.Diagnostics;
using System.Timers;
public class JustSirtProxy
{
private readonly JustSerialPort serialPort;
private readonly List<Byte> buffer;
private Task listener;
private CancellationToken cancellationToken;
private CancellationTokenSource cancellationTokenSource;
private readonly Timer timer;
public JustSirtProxy(String portName)
{
@@ -26,6 +23,7 @@
};
this.serialPort = new JustSerialPort(settings);
this.buffer = new List<Byte>();
this.timer = new Timer();
}
public event Action<JustSirtMessage> MessageReceived;
@@ -46,13 +44,10 @@
try
{
this.cancellationTokenSource.Cancel();
this.timer.Stop();
this.serialPort.TryClose();
this.listener = null;
this.cancellationTokenSource = null;
this.cancellationToken = CancellationToken.None;
closed = this.serialPort.TryClose();
closed = true;
}
catch (Exception e)
{
@@ -68,7 +63,12 @@
if (opened)
{
opened = this.StartListening();
this.timer.Elapsed += this.Timer_Elapsed;
this.timer.AutoReset = true;
this.timer.Interval = 50;
this.timer.Start();
opened = true;
}
return opened;
@@ -77,85 +77,59 @@
public void WriteBytes(params Byte[] bytes)
=> this.serialPort.WriteBytes(bytes);
private Boolean StartListening()
private Byte[] bytes;
private Int32 bytesLength;
private Int32 bufferLength;
private Int32 start;
private Int32 lengthIX;
private Byte length;
private Int32 stopIX;
private void Timer_Elapsed(Object sender, ElapsedEventArgs _1)
{
this.cancellationTokenSource = new CancellationTokenSource();
this.cancellationToken = this.cancellationTokenSource.Token;
this.listener = Task.Factory.StartNew(state =>
this.bytes = this.serialPort.ReadBytes();
this.bytesLength = this.bytes.Length;
if (this.bytesLength > 0)
{
if (state is JustSirtProxy proxy)
{
var serialPort = proxy.serialPort;
var bytes = new Byte[] { };
while (serialPort.IsOpen)
{
bytes = serialPort.ReadBytes();
proxy.TryParseMessage(bytes);
}
}
}, this, this.cancellationToken)
.ContinueWith(task =>
{
if (task.Exception != null && task.AsyncState is JustSirtProxy proxy)
{
proxy.Log(task.Exception);
}
});
return this.listener.Status == TaskStatus.WaitingForActivation
|| this.listener.Status == TaskStatus.WaitingToRun
|| this.listener.Status == TaskStatus.Running;
}
private void TryParseMessage(Byte[] bytes)
{
var bytesLength = bytes?.Length ?? 0;
if (bytesLength > 0)
{
this.buffer.AddRange(bytes);
this.buffer.AddRange(this.bytes);
}
var bufferLength = this.buffer.Count;
var start = this.buffer.IndexOf(JustSirtMessage.SIRT2PC);
this.bufferLength = this.buffer.Count;
this.start = this.buffer.IndexOf(JustSirtMessage.SIRT2PC);
if (start < 0)
if (this.start < 0)
{
this.buffer.Clear();
return;
}
var lengthIX = start + 8;
this.lengthIX = this.start + 8;
if (lengthIX >= bufferLength)
if (this.lengthIX >= this.bufferLength)
{
return;
}
var length = this.buffer[lengthIX];
var stopIX = lengthIX + length + 3;
this.length = this.buffer[this.lengthIX];
this.stopIX = this.lengthIX + this.length + 3;
if (stopIX >= bufferLength)
if (this.stopIX >= this.bufferLength)
{
return;
}
else if (this.buffer[stopIX] != JustSirtMessage.STOP)
else if (this.buffer[this.stopIX] != JustSirtMessage.STOP)
{
return;
}
bytesLength = stopIX - start + 1;
bytes = new Byte[bytesLength];
this.bytesLength = this.stopIX - this.start + 1;
this.bytes = new Byte[this.bytesLength];
this.buffer.CopyTo(start, bytes, 0, bytesLength);
var message = new JustSirtMessage(bytes);
this.MessageReceived?.Invoke(message);
this.buffer.RemoveRange(0, start + bytesLength);
this.buffer.CopyTo(this.start, this.bytes, 0, this.bytesLength);
this.buffer.RemoveRange(0, this.start + this.bytesLength);
this.MessageReceived?.Invoke(new JustSirtMessage(this.bytes));
}
}
}
@@ -23,6 +23,7 @@
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<NoWarn>IDE0003;IDE0049;</NoWarn>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
@@ -4,19 +4,18 @@
using System;
using System.Collections.Concurrent;
using System.Threading;
public class JustSirtBroadcaster
{
private static readonly ConcurrentDictionary<UInt32, JustSirtTask> runningTasks
= new ConcurrentDictionary<UInt32, JustSirtTask>();
private readonly JustSirtProxy proxy;
private readonly UInt32[] pampool;
public JustSirtBroadcaster(String portName)
{
this.proxy = new JustSirtProxy(portName);
this.proxy.MessageReceived += this.Proxy_MessageReceived;
this.pampool = new UInt32[5];
}
public event Action<String> Logging
@@ -38,30 +37,49 @@
if (activated)
{
runningTasks.Clear();
Array.Clear(this.pampool, 0, 5);
}
var awaiter = new ManualResetEventSlim();
var task = JustSirtTask.ActivateSIRT;
task.Cancelled += _ => awaiter.Set();
task.Completed += _task =>
{
activated = _task.Status == JustTaskStatus.Completed;
if (activated)
{
awaiter.Set();
}
};
task = runningTasks.AddOrUpdate(task.Address, task, (a, t) => task);
task.PrepareForRun();
this.proxy.WriteBytes(task);
task.Wait();
this.Log(task);
activated = task.Status == JustTaskStatus.Completed;
awaiter.Wait();
awaiter.Reset();
if (activated)
{
task = JustSirtTask.IdentifySIRT;
task.Cancelled += _ => awaiter.Set();
task.Completed += _task =>
{
activated = _task.Status == JustTaskStatus.Completed;
if (activated)
{
awaiter.Set();
}
};
task = runningTasks.AddOrUpdate(task.Address, task, (a, t) => task);
task.PrepareForRun();
this.proxy.WriteBytes(task);
task.Wait();
this.Log(task);
activated = task.Status == JustTaskStatus.Completed;
awaiter.Wait();
awaiter.Reset();
if (activated)
{
@@ -80,9 +98,6 @@
return this.proxy.TryClose();
}
public Boolean TryRemove(UInt32 address, out JustSirtTask task)
=> runningTasks.TryRemove(address, out task);
public JustTaskStatus TryRun(JustSirtTask task)
{
if (!this.proxy.IsOpen)
@@ -92,26 +107,41 @@
var address = task.Address;
if (runningTasks.TryGetValue(address, out var runningTask))
if (runningTasks.TryGetValue(address, out var runningTask) && runningTask != null)
{
return JustTaskStatus.InRunningTasks;
}
this.UpdatePamPool();
var countInPamPool = 0;
if (Array.Exists(this.pampool, x => x == address))
foreach (var _task in runningTasks.Values)
{
return JustTaskStatus.InPamPool;
if (_task != null && _task.Cmd == JustSirtMessage.W_PAM)
{
countInPamPool++;
}
}
else if (!Array.Exists(this.pampool, x => 0 == x || x == UInt32.MaxValue))
if (countInPamPool >= 5)
{
return JustTaskStatus.PamPoolIsFull;
}
task = runningTasks.AddOrUpdate(address, task, (a, t) => task);
if (task.Status == JustTaskStatus.Completed)
{
this.Task_DismissFromRunningTasks(task);
return JustTaskStatus.Completed;
}
task.Cancelled += this.Task_DismissFromRunningTasks;
task.Completed += this.Task_DismissFromRunningTasks;
task.PrepareForRun();
runningTasks.AddOrUpdate(address, task, (a, t) => task);
this.proxy.WriteBytes(task);
this.Log($"REQUEST|{BitConverter.ToString(task)}");
this.Log(BitConverter.ToString(task));
return JustTaskStatus.Sent;
}
@@ -120,57 +150,19 @@
{
var address = message.Address;
if (runningTasks.TryGetValue(address, out var task))
if (runningTasks.TryGetValue(address, out var task) && task != null)
{
task.ReceiveMessage(message);
this.Log($"RESPONSE|{BitConverter.ToString(message)}");
if (task.Status == JustTaskStatus.Completed)
{
_ = runningTasks.TryRemove(address, out var _);
}
else if (task.Status == JustTaskStatus.Cancelled)
{
this.proxy.WriteBytes(JustSirtTask.DeleteFromPamPool(address));
}
task.ReceiveMessage(message, this.MHz);
this.Log(message);
}
this.Log(message);
}
private void UpdatePamPool()
private void Task_DismissFromRunningTasks(JustSirtTask task)
{
Array.Clear(this.pampool, 0, 5);
task.Cancelled -= this.Task_DismissFromRunningTasks;
task.Completed -= this.Task_DismissFromRunningTasks;
if (!this.proxy.IsOpen)
{
return;
}
var task = JustSirtTask.ReadPamPool;
task = runningTasks.AddOrUpdate(task.Address, task, (a, t) => task);
task.PrepareForRun();
this.proxy.WriteBytes(task);
task.Wait();
this.Log(task);
var address = 0U;
var addressesBytes = task.LastPayload;
var addressesBytesLength = addressesBytes.Length;
for (Int32 i = 0, x = 0; i < addressesBytesLength && x < 5;)
{
address = 0U;
address ^= (UInt32)addressesBytes[i++] << 24;
address ^= (UInt32)addressesBytes[i++] << 16;
address ^= (UInt32)addressesBytes[i++] << 8;
address ^= (UInt32)addressesBytes[i++] << 0;
this.pampool[x++] = address;
}
this.Log($"PAM POOL|{BitConverter.ToString(addressesBytes)}");
runningTasks.TryRemove(task.Address, out var _);
}
}
}
@@ -5,14 +5,17 @@
using System;
using System.Collections.Concurrent;
using System.Threading;
using System.Timers;
public class JustSirtTask
{
private readonly Timer timer = new Timer();
private readonly JustSirtMessage request = new JustSirtMessage();
private readonly ManualResetEventSlim awaiter = new ManualResetEventSlim();
private readonly ConcurrentStack<JustSirtMessage> responses = new ConcurrentStack<JustSirtMessage>();
public event Action<JustSirtTask> Completed;
public event Action<JustSirtTask> Cancelled;
public Byte Cmd
{
get => this.request.Cmd;
@@ -50,7 +53,7 @@
? response.Data
: new Byte[0];
public virtual void ReceiveMessage(JustSirtMessage response)
public virtual void ReceiveMessage(JustSirtMessage response, Int32 mhz)
{
this.responses.Push(response);
@@ -70,16 +73,24 @@
if (this.Status == JustTaskStatus.Completed)
{
this.awaiter.Set();
this.Completed?.Invoke(this);
this.timer.Stop();
}
}
public virtual void PrepareForRun()
{
this.Status = JustTaskStatus.Pending;
this.responses.Clear();
this.awaiter.Reset();
this.Status = JustTaskStatus.Pending;
this.timer.AutoReset = false;
this.timer.Interval = 10_000;
this.timer.Elapsed += (sender, _1) =>
{
this.Status = JustTaskStatus.Cancelled;
this.Cancelled?.Invoke(this);
};
this.timer.Start();
}
public virtual Byte[] ToByteArray()
@@ -88,16 +99,6 @@
public override String ToString()
=> BitConverter.ToString(this.ToByteArray());
public void Wait(Int32 timeout = 5_000)
{
this.awaiter.Wait(timeout);
if (this.Status != JustTaskStatus.Completed)
{
this.Status = JustTaskStatus.Cancelled;
}
}
public static implicit operator Byte[] (JustSirtTask task)
=> task?.ToByteArray() ?? new Byte[] { };
@@ -105,7 +106,7 @@
{
Cmd = JustSirtMessage.W_REG,
Address = 0x20000000,
P2 = 0x05, // The data length
P2 = 0x05,
Data = new Byte[]
{
new SirtOperating { /* default */ },
@@ -29,7 +29,7 @@
public event Action<String> Logging;
public void Log(Object message)
=> this.Logging?.Invoke($"{DateTime.Now:yyyy-MM-dd|HH:mm:ss.fff}|{this.portName}|{message}");
=> this.Logging?.Invoke($"{this.portName}|{message}");
public Boolean TryClose()
{
@@ -67,6 +67,8 @@
Parity = this.serialPortSettings.Parity,
PortName = this.serialPortSettings.PortName,
StopBits = this.serialPortSettings.StopBits,
WriteTimeout = 100,
ReadTimeout = 100,
};
if (serialPorts.TryAdd(this.portName, serialPort))
@@ -9,7 +9,6 @@
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
public class JusteRegisterProgrammingBatch
{
@@ -17,15 +16,15 @@
= new Dictionary<Int32, JusteRegisterParameterSet>();
private readonly Dictionary<Int32, Queue<JusteRegisterProgrammingTask>> programmingTasks
= new Dictionary<Int32, Queue<JusteRegisterProgrammingTask>>();
private readonly Dictionary<Int32, Queue<JusteRegisterProgrammingTask>> completedTasks
= new Dictionary<Int32, Queue<JusteRegisterProgrammingTask>>();
private readonly ILogger logger = CreateNLogger("SIRT");
private JustSirtBroadcaster broadcaster;
public event Action<Int32, Int32, String, JusteRegisterTaskState> OnProgress;
public void Add(JusteRegisterParameterSet parameterSet)
{
this.programmingParameters[parameterSet.Slotno] = parameterSet;
}
public void Add(JusteRegisterParameterSet parameterSet)
=> this.programmingParameters[parameterSet.Slotno] = parameterSet;
public void InitializeCalibration()
{
@@ -94,63 +93,54 @@
public void Run()
{
var slotno = default(Int32);
var tasksLeft = default(Int32);
var task = default(Task);
var tasks = new List<Task>();
var queue = default(Queue<JusteRegisterProgrammingTask>);
var tasks = default(List<JusteRegisterProgrammingTask>);
var allDone = true;
do
{
tasks.Clear();
tasksLeft = 0;
tasks = new List<JusteRegisterProgrammingTask>();
foreach (var kvp in this.programmingTasks)
foreach (var queue in this.programmingTasks.Values)
{
slotno = kvp.Key;
queue = kvp.Value;
if (queue.Count > 0)
{
var programmingTask = queue.Peek();
if (programmingTask.Status == JustTaskStatus.Pending)
{
task = Task.Factory.StartNew(() =>
{
this.Run(programmingTask);
programmingTask.Wait();
});
tasks.Add(task);
tasksLeft++;
}
tasks.Add(queue.Dequeue());
}
}
if (tasks.Count > 0)
do
{
Task.WaitAll(tasks.ToArray());
}
allDone = true;
foreach (var _queue in this.programmingTasks.Values)
{
if (_queue.Count > 0)
foreach (var task in tasks)
{
var _task = _queue.Peek();
if (task.Status != JustTaskStatus.Completed)
{
this.broadcaster.TryRun(task);
if (_task.Status == JustTaskStatus.Completed)
{
_queue.Dequeue();
}
else if (_task.Status == JustTaskStatus.Cancelled)
{
this.OnProgress?.Invoke(_task.Slotno, _task.Rowno, "ERROR", JusteRegisterTaskState.Error);
Thread.Sleep(100);
allDone = false;
}
}
Thread.Sleep(100);
} while (!allDone);
foreach (var task in tasks)
{
var slotno = task.Slotno;
if (!this.completedTasks.ContainsKey(slotno))
{
this.completedTasks[slotno] = new Queue<JusteRegisterProgrammingTask>();
}
this.completedTasks[slotno].Enqueue(task);
}
}
while (tasksLeft > 0);
} while (tasks.Count > 0);
}
public void Run(JusteRegisterProgrammingTask task)
@@ -172,7 +162,7 @@
this.Stop();
this.broadcaster = new JustSirtBroadcaster(portName);
this.broadcaster.Logging += text => this.logger.Debug(text);
this.broadcaster.Logging += Console.WriteLine; // this.logger.Debug(text);
return this.broadcaster.TryActivate();
}
@@ -4,9 +4,25 @@
using Common.Hardware.Interfaces.Ports.SirtBroadcaster;
using System;
using System.Timers;
public class JusteRegisterProgrammingTask : JustSirtTask
{
private readonly Timer timer = new Timer();
public JusteRegisterProgrammingTask() : base()
{
this.timer = new Timer();
this.timer.AutoReset = true;
this.timer.Interval = 500;
this.timer.Interval = 500;
this.timer.Elapsed += (_, _1) =>
{
this.OnProgress?.Invoke(this.Slotno, this.Rowno, this.Label, this.State);
};
this.timer.Start();
}
public event Action<Int32, Int32, String, JusteRegisterTaskState> OnProgress;
public Byte[] EncryptionKey { get; set; }
@@ -15,6 +31,10 @@
public Int32 Rowno { get; internal set; }
public String Label { get; private set; }
public JusteRegisterTaskState State { get; private set; } = JusteRegisterTaskState.None;
public override void PrepareForRun()
{
this.OnProgress?.Invoke(this.Slotno, this.Rowno, "PENDING", JusteRegisterTaskState.None);
@@ -22,7 +42,7 @@
base.PrepareForRun();
}
public override void ReceiveMessage(JustSirtMessage response)
public override void ReceiveMessage(JustSirtMessage response, Int32 mhz)
{
if (this.EncryptionKey != null && this.EncryptionKey.Length == 16)
{
@@ -33,38 +53,34 @@
{
var type = response.Data[0];
var telegram = new object();
var label = default(String);
var state = JusteRegisterTaskState.None;
if (type == JustSirtMessage.SEMI)
{
label = nameof(JustSirtMessage.SEMI);
state = JusteRegisterTaskState.Success;
telegram = new SEMI(response.Data, 433);
this.Label = nameof(JustSirtMessage.SEMI);
this.State = JusteRegisterTaskState.Success;
telegram = new SEMI(response.Data, (UInt16)mhz);
}
else if (type == JustSirtMessage.BUP)
{
label = nameof(JustSirtMessage.BUP);
state = JusteRegisterTaskState.Warning;
this.Label = nameof(JustSirtMessage.BUP);
this.State = JusteRegisterTaskState.Warning;
telegram = new BUP(response.Data);
}
else if (type == JustSirtMessage.LAT)
{
label = nameof(JustSirtMessage.LAT);
state = JusteRegisterTaskState.Warning;
this.Label = nameof(JustSirtMessage.LAT);
this.State = JusteRegisterTaskState.Warning;
telegram = new LAT(response.Data);
}
else if (type == JustSirtMessage.DEBUG)
{
label = nameof(JustSirtMessage.DEBUG);
state = JusteRegisterTaskState.Warning;
this.Label = nameof(JustSirtMessage.DEBUG);
this.State = JusteRegisterTaskState.Warning;
telegram = new DEBUG(response.Data);
}
this.OnProgress?.Invoke(this.Slotno, this.Rowno, label, state);
}
base.ReceiveMessage(response);
base.ReceiveMessage(response, mhz);
}
public override Byte[] ToByteArray()