67 lines
2.4 KiB
C#
67 lines
2.4 KiB
C#
using CanCommon;
|
|
|
|
namespace CanSlave;
|
|
|
|
/// <summary>
|
|
/// Receive-only loop. Validates each frame against the expected benchmark frame
|
|
/// (ID 0x123, DLC 8, payload all 0xAA) and counts valid / invalid / error frames.
|
|
/// Never transmits — no ACK, no response — so it does not consume bus bandwidth.
|
|
/// </summary>
|
|
public sealed class CanReceiver
|
|
{
|
|
private readonly ICanChannel _channel;
|
|
private readonly Statistics _stats;
|
|
private readonly uint _expectId;
|
|
private readonly int _expectDlc;
|
|
private readonly byte _expectFill;
|
|
private readonly bool _realtime;
|
|
private readonly int _rtPriority;
|
|
|
|
// null until Run starts; then null == RT engaged, else the reason it wasn't.
|
|
private volatile string? _rtStatus = "pending";
|
|
|
|
public CanReceiver(ICanChannel channel, Statistics stats, uint expectId, int expectDlc, byte expectFill,
|
|
bool realtime = true, int rtPriority = 80)
|
|
{
|
|
_channel = channel;
|
|
_stats = stats;
|
|
_expectId = expectId;
|
|
_expectDlc = expectDlc;
|
|
_expectFill = expectFill;
|
|
_realtime = realtime;
|
|
_rtPriority = rtPriority;
|
|
}
|
|
|
|
/// <summary>After Run starts: null = SCHED_FIFO engaged, otherwise the reason it isn't.</summary>
|
|
public string? RealtimeStatus => _rtStatus;
|
|
|
|
public void Run(CancellationToken token)
|
|
{
|
|
// Elevate THIS thread so RX keeps up under a fully saturated bus.
|
|
_rtStatus = _realtime ? RealtimeScheduler.TryEngage(_rtPriority) : "disabled";
|
|
|
|
var buf = new byte[CanFrame.Size];
|
|
while (!token.IsCancellationRequested)
|
|
{
|
|
int n = _channel.Receive(buf, out bool timedOut);
|
|
if (timedOut) continue; // periodic wakeup to re-check the token
|
|
if (n <= 0) { _stats.AddError(); continue; }
|
|
|
|
if (CanFrame.IsError(buf))
|
|
{
|
|
// Bus error frame reported by the controller (needs err filter enabled).
|
|
_stats.AddError();
|
|
continue;
|
|
}
|
|
|
|
bool valid = !CanFrame.IsExtended(buf)
|
|
&& CanFrame.GetStandardId(buf) == _expectId
|
|
&& CanFrame.GetDlc(buf) == _expectDlc
|
|
&& CanFrame.PayloadAllEqual(buf, _expectDlc, _expectFill);
|
|
|
|
if (valid) _stats.AddValid(_expectDlc);
|
|
else _stats.AddInvalid();
|
|
}
|
|
}
|
|
}
|