Files
testcan/CanMaster/CanSender.cs
2026-08-20 14:56:23 +07:00

75 lines
2.9 KiB
C#

using System.Collections.Concurrent;
using CanCommon;
namespace CanMaster;
/// <summary>
/// Tight transmit loop: pushes the same pre-built frame as fast as the driver
/// accepts it, batching <c>N</c> frames per <c>sendmmsg</c> syscall so the CAN
/// controller's tx FIFO never drains between frames. No per-frame delay and no
/// application-level ACK/response — the tx queue provides the back-pressure that
/// caps us at the real bus rate (this is what "max bandwidth" means here).
/// </summary>
public sealed class CanSender
{
private readonly CanTxBatch _batch;
private readonly Statistics _stats;
private readonly int _payloadBytes;
private readonly bool _realtime;
private readonly int _rtPriority;
// Per-errno tally of rejected sends, so a run can say *why* it failed
// (105 ENOBUFS = tx queue full, 100 ENETDOWN = link down, etc.).
private readonly ConcurrentDictionary<int, long> _errnoCounts = new();
// null until the worker starts; then null == RT engaged, else the reason it wasn't.
private volatile string? _rtStatus = "pending";
public CanSender(CanTxBatch batch, Statistics stats, int payloadBytes, bool realtime, int rtPriority)
{
_batch = batch;
_stats = stats;
_payloadBytes = payloadBytes;
_realtime = realtime;
_rtPriority = rtPriority;
}
/// <summary>errno -> number of failed sendmmsg calls carrying that errno.</summary>
public IReadOnlyDictionary<int, long> ErrnoCounts => _errnoCounts;
/// <summary>After the worker starts: null = SCHED_FIFO engaged, otherwise the reason it isn't.</summary>
public string? RealtimeStatus => _rtStatus;
private const int EINTR = 4;
public void Run(CancellationToken token)
{
// Elevate THIS thread (the one doing the sends) — must run on the worker.
_rtStatus = _realtime ? RealtimeScheduler.TryEngage(_rtPriority) : "disabled";
while (!token.IsCancellationRequested)
{
int n = _batch.Send();
if (n > 0)
{
// Kernel accepted n of Count frames; the remainder (if any) is retried
// on the next iteration — the payload is fixed so re-sending is fine.
_stats.AddFrames(n, _payloadBytes);
if (n == _batch.Count) continue;
}
if (n < 0)
{
int errno = _batch.LastErrno;
if (errno == EINTR) continue; // interrupted -> retry immediately
_stats.AddError();
_errnoCounts.AddOrUpdate(errno, 1, (_, c) => c + 1);
// Bus-off / queue-full / link-down: back off briefly so we don't spin at
// 100% CPU while the controller recovers, but keep pushing to measure max rate.
if (errno is 105 /*ENOBUFS*/ or 100 /*ENETDOWN*/)
Thread.SpinWait(200);
}
}
}
}