45 lines
1.6 KiB
C#
45 lines
1.6 KiB
C#
using System.Diagnostics;
|
|
|
|
namespace CanCommon;
|
|
|
|
/// <summary>
|
|
/// Optional helper that sets a SocketCAN interface bitrate via `ip link`
|
|
/// (requires root / sudo). Kept separate from the socket I/O so the backend
|
|
/// stays portable; on non-SocketCAN backends this is simply not used.
|
|
/// </summary>
|
|
public static class InterfaceConfigurator
|
|
{
|
|
public static void SetBitrate(string ifName, int bitrate, int txqueuelen = 1000)
|
|
{
|
|
// Bring down, set bitrate, raise tx queue, bring up.
|
|
Run("ip", $"link set {ifName} down");
|
|
Run("ip", $"link set {ifName} type can bitrate {bitrate} restart-ms 100");
|
|
Run("ip", $"link set {ifName} txqueuelen {txqueuelen}");
|
|
Run("ip", $"link set {ifName} up");
|
|
}
|
|
|
|
private static void Run(string file, string args)
|
|
{
|
|
// Prefer sudo if we are not already root.
|
|
bool root = Environment.GetEnvironmentVariable("USER") == "root" ||
|
|
(OperatingSystem.IsLinux() && geteuid() == 0);
|
|
var psi = new ProcessStartInfo
|
|
{
|
|
FileName = root ? file : "sudo",
|
|
Arguments = root ? args : $"{file} {args}",
|
|
RedirectStandardError = true,
|
|
RedirectStandardOutput = true,
|
|
UseShellExecute = false,
|
|
};
|
|
using var p = Process.Start(psi)!;
|
|
string err = p.StandardError.ReadToEnd();
|
|
p.WaitForExit();
|
|
if (p.ExitCode != 0)
|
|
throw new InvalidOperationException(
|
|
$"`{psi.FileName} {psi.Arguments}` failed (exit {p.ExitCode}): {err.Trim()}");
|
|
}
|
|
|
|
[System.Runtime.InteropServices.DllImport("libc")]
|
|
private static extern uint geteuid();
|
|
}
|