save
This commit is contained in:
160
CanCommon/SocketCanChannel.cs
Normal file
160
CanCommon/SocketCanChannel.cs
Normal file
@@ -0,0 +1,160 @@
|
||||
using System.Diagnostics;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Text;
|
||||
|
||||
namespace CanCommon;
|
||||
|
||||
/// <summary>
|
||||
/// SocketCAN backend (Linux <c>PF_CAN / CAN_RAW</c>) implemented over libc P/Invoke.
|
||||
/// Works for any SocketCAN device, including the PEAK/SJA1000 PCI card and the
|
||||
/// IPC's built-in CAN module — the benchmark does not know or care which.
|
||||
/// </summary>
|
||||
public sealed class SocketCanChannel : ICanChannel
|
||||
{
|
||||
// address families / socket types
|
||||
private const int AF_CAN = 29;
|
||||
private const int SOCK_RAW = 3;
|
||||
private const int CAN_RAW = 1;
|
||||
|
||||
// setsockopt levels / options
|
||||
private const int SOL_SOCKET = 1;
|
||||
private const int SO_RCVTIMEO = 20;
|
||||
private const int SOL_CAN_RAW = 101;
|
||||
private const int CAN_RAW_ERR_FILTER = 2;
|
||||
|
||||
// ioctl
|
||||
private const uint SIOCGIFINDEX = 0x8933;
|
||||
|
||||
private const int EAGAIN = 11; // receive timeout (EWOULDBLOCK)
|
||||
private const int EINTR = 4;
|
||||
|
||||
[DllImport("libc", SetLastError = true)] private static extern int socket(int domain, int type, int protocol);
|
||||
[DllImport("libc", SetLastError = true)] private static extern int bind(int fd, byte[] addr, int addrlen);
|
||||
[DllImport("libc", SetLastError = true, EntryPoint = "ioctl")] private static extern int ioctl(int fd, uint request, byte[] arg);
|
||||
[DllImport("libc", SetLastError = true)] private static extern int setsockopt(int fd, int level, int optname, byte[] optval, int optlen);
|
||||
[DllImport("libc", SetLastError = true)] private static extern nint read(int fd, byte[] buf, nuint count);
|
||||
[DllImport("libc", SetLastError = true)] private static extern nint write(int fd, byte[] buf, nuint count);
|
||||
[DllImport("libc", SetLastError = true)] private static extern int close(int fd);
|
||||
|
||||
private readonly string _ifName;
|
||||
private readonly int _rcvTimeoutMs;
|
||||
private readonly bool _wantErrorFrames;
|
||||
private int _fd = -1;
|
||||
|
||||
public string Name => _ifName;
|
||||
public int LastErrno { get; private set; }
|
||||
|
||||
/// <param name="ifName">SocketCAN interface, e.g. <c>can_com3</c>.</param>
|
||||
/// <param name="rcvTimeoutMs">Blocking-receive timeout so loops can check for shutdown.</param>
|
||||
/// <param name="wantErrorFrames">Deliver bus error frames to the reader (for error counting).</param>
|
||||
public SocketCanChannel(string ifName, int rcvTimeoutMs = 200, bool wantErrorFrames = false)
|
||||
{
|
||||
_ifName = ifName;
|
||||
_rcvTimeoutMs = rcvTimeoutMs;
|
||||
_wantErrorFrames = wantErrorFrames;
|
||||
}
|
||||
|
||||
public void Open()
|
||||
{
|
||||
_fd = socket(AF_CAN, SOCK_RAW, CAN_RAW);
|
||||
if (_fd < 0) throw Fail("socket(PF_CAN, SOCK_RAW, CAN_RAW)");
|
||||
|
||||
int ifindex = ResolveIfIndex(_fd, _ifName);
|
||||
|
||||
// struct sockaddr_can { u16 can_family; int can_ifindex; ... } -> 16 bytes.
|
||||
var addr = new byte[16];
|
||||
BitConverter.TryWriteBytes(addr.AsSpan(0, 2), (ushort)AF_CAN);
|
||||
BitConverter.TryWriteBytes(addr.AsSpan(4, 4), ifindex);
|
||||
if (bind(_fd, addr, addr.Length) != 0) throw Fail($"bind({_ifName})");
|
||||
|
||||
if (_wantErrorFrames)
|
||||
{
|
||||
// Ask the kernel to also deliver bus error frames (all classes).
|
||||
var mask = BitConverter.GetBytes(CanFrame.CAN_ERR_MASK);
|
||||
setsockopt(_fd, SOL_CAN_RAW, CAN_RAW_ERR_FILTER, mask, mask.Length);
|
||||
}
|
||||
|
||||
if (_rcvTimeoutMs > 0)
|
||||
{
|
||||
// struct timeval { long tv_sec; long tv_usec; } -> 16 bytes on 64-bit.
|
||||
var tv = new byte[16];
|
||||
long sec = _rcvTimeoutMs / 1000;
|
||||
long usec = (_rcvTimeoutMs % 1000) * 1000L;
|
||||
BitConverter.TryWriteBytes(tv.AsSpan(0, 8), sec);
|
||||
BitConverter.TryWriteBytes(tv.AsSpan(8, 8), usec);
|
||||
setsockopt(_fd, SOL_SOCKET, SO_RCVTIMEO, tv, tv.Length);
|
||||
}
|
||||
}
|
||||
|
||||
public bool Send(byte[] frame16)
|
||||
{
|
||||
nint n = write(_fd, frame16, (nuint)CanFrame.Size);
|
||||
if (n == CanFrame.Size) { LastErrno = 0; return true; }
|
||||
LastErrno = Marshal.GetLastPInvokeError();
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Create a reusable batched sender that pushes <paramref name="count"/> copies of
|
||||
/// <paramref name="frame16"/> per <c>sendmmsg</c> syscall. The channel must be open.
|
||||
/// </summary>
|
||||
public CanTxBatch CreateTxBatch(byte[] frame16, int count)
|
||||
{
|
||||
if (_fd < 0) throw new InvalidOperationException("channel is not open");
|
||||
return new CanTxBatch(_fd, frame16, count);
|
||||
}
|
||||
|
||||
public int Receive(byte[] frame16, out bool timedOut)
|
||||
{
|
||||
timedOut = false;
|
||||
while (true)
|
||||
{
|
||||
nint n = read(_fd, frame16, (nuint)CanFrame.Size);
|
||||
if (n == CanFrame.Size) { LastErrno = 0; return CanFrame.Size; }
|
||||
int err = Marshal.GetLastPInvokeError();
|
||||
if (err == EINTR) continue; // interrupted -> retry
|
||||
if (err == EAGAIN) { timedOut = true; return 0; } // rcv timeout
|
||||
LastErrno = err;
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
|
||||
public void Close()
|
||||
{
|
||||
if (_fd >= 0) { close(_fd); _fd = -1; }
|
||||
}
|
||||
|
||||
public void Dispose() => Close();
|
||||
|
||||
private static int ResolveIfIndex(int fd, string ifName)
|
||||
{
|
||||
// struct ifreq is 40 bytes on 64-bit; name in [0..15], ifr_ifindex (int) at 16.
|
||||
var ifr = new byte[40];
|
||||
byte[] name = Encoding.ASCII.GetBytes(ifName);
|
||||
if (name.Length >= 16) throw new ArgumentException($"Interface name too long: {ifName}");
|
||||
Array.Copy(name, ifr, name.Length);
|
||||
if (ioctl(fd, SIOCGIFINDEX, ifr) != 0)
|
||||
{
|
||||
int err = Marshal.GetLastPInvokeError();
|
||||
throw new IOException($"ioctl(SIOCGIFINDEX, {ifName}) failed (errno {err}: {Strerror(err)}). Is the interface up?");
|
||||
}
|
||||
return BitConverter.ToInt32(ifr, 16);
|
||||
}
|
||||
|
||||
private IOException Fail(string what)
|
||||
{
|
||||
int err = Marshal.GetLastPInvokeError();
|
||||
LastErrno = err;
|
||||
return new IOException($"{what} failed (errno {err}: {Strerror(err)})");
|
||||
}
|
||||
|
||||
public static string Strerror(int errno) => errno switch
|
||||
{
|
||||
1 => "EPERM (need CAP_NET_RAW: run with sudo or setcap cap_net_raw+ep)",
|
||||
11 => "EAGAIN/EWOULDBLOCK",
|
||||
19 => "ENODEV (no such device)",
|
||||
100 => "ENETDOWN (interface is down)",
|
||||
105 => "ENOBUFS (tx queue full / bus-off)",
|
||||
_ => $"errno {errno}",
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user