-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathProgram.cs
More file actions
243 lines (224 loc) · 10.6 KB
/
Copy pathProgram.cs
File metadata and controls
243 lines (224 loc) · 10.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
#region License
/*
BSD 3-Clause License
Copyright (c) 2024, Derek Will
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#endregion
using System;
using System.Linq;
using System.Collections.Generic;
using SocketCANSharp.Capabilities;
using SocketCANSharp.Network;
using SocketCANSharp.Network.Netlink;
using SocketCANSharp;
namespace CanNetlinkReader
{
class Program
{
static void Main(string[] args)
{
IEnumerable<CanNetworkInterface> collection = CanNetworkInterface.GetAllInterfaces(true);
var iface = collection.FirstOrDefault(i => i.Name.Equals("can0"));
if (iface == null)
{
Console.WriteLine("can0 interface not found and is required for this demo!");
return;
}
if (CapabilityUtils.IsCurrentProcessCapable(Capability.CAP_NET_ADMIN) == false)
{
Console.WriteLine("Cannot run the demonstration as the current process lacks suffucient privileges (CAP_NET_ADMIN).");
return;
}
using (var rtNetlinkSocket = new RoutingNetlinkSocket())
{
rtNetlinkSocket.ReceiveBufferSize = 32768;
rtNetlinkSocket.SendBufferSize = 32768;
rtNetlinkSocket.ReceiveTimeout = 1000;
rtNetlinkSocket.Bind(new SockAddrNetlink(0, 0));
Console.WriteLine("Stopping Interface...");
SetInterfaceDown(rtNetlinkSocket, iface);
Console.WriteLine("Configuring Interface...");
SetDeviceProperties(rtNetlinkSocket, iface);
Console.WriteLine("Starting Interface...");
SetInterfaceUp(rtNetlinkSocket, iface);
}
Console.WriteLine("Using Interface class...");
Console.WriteLine("Bringing Link Down...");
iface.SetLinkDown();
Console.WriteLine("Configuring...");
iface.BitTiming = new CanBitTiming() { BitRate = 125000 };
iface.CanControllerModeFlags = CanControllerModeFlags.CAN_CTRLMODE_LOOPBACK | CanControllerModeFlags.CAN_CTRLMODE_LISTENONLY;
iface.AutoRestartDelay = 0;
iface.MaximumTransmissionUnit = SocketCanConstants.CAN_MTU;
if (iface.TerminationResistance != null)
{
iface.TerminationResistance = 120;
}
else
{
Console.WriteLine("Note: CAN controller does not support switchable termination resistance.");
}
Console.WriteLine("Bringing Link Up...");
iface.SetLinkUp();
Console.WriteLine($"Inteface Device Flags: {iface.DeviceFlags}");
Console.WriteLine($"Inteface Operational Status: {iface.OperationalStatus}");
Console.WriteLine($"Controller State: {iface.CanControllerState}");
Console.WriteLine($"Auto-Restart Delay: {iface.AutoRestartDelay} ms");
Console.WriteLine("Attempting to Restart CAN Controller...");
try
{
iface.Restart();
}
catch (SocketCanException ex)
{
if (ex.ErrorCode == 16 || ex.ErrorCode == 22) // EBUSY when not BUS OFF, EINVAL when not 0 ms delay
{
if (iface.CanControllerState != CanState.CAN_STATE_BUS_OFF || iface.AutoRestartDelay != 0)
{
Console.WriteLine("Expected CAN controller restart to fail.");;
}
else
{
Console.WriteLine("Did not expect CAN controller restart to fail...");
}
}
else
{
Console.WriteLine($"Trigger Restart resulted in unexpected Error Code {ex.ErrorCode}");
}
}
Console.WriteLine($"Bit Timing: {iface.BitTiming.BitRate} bit/s");
Console.WriteLine($"Controller Mode Flags: {iface.CanControllerModeFlags}");
Console.WriteLine($"Termination Resistance: {(iface.TerminationResistance.HasValue ? iface.TerminationResistance.Value.ToString() : "N/A")} Ohm");
Console.WriteLine($"MTU: {iface.MaximumTransmissionUnit}");
}
private static void SetDeviceProperties(RoutingNetlinkSocket rtNetlinkSocket, CanNetworkInterface iface)
{
var canDevProps = new CanDeviceProperties()
{
LinkKind = "can",
RestartDelay = 100, // restart-ms 100
BitTiming = new CanBitTiming()
{
BitRate = 250000, // bitrate 250000
},
ControllerMode = new CanControllerMode()
{
Mask = 0xffffffff,
Flags = CanControllerModeFlags.CAN_CTRLMODE_LISTENONLY,
},
};
NetworkInterfaceModifierRequest modReq = NetlinkUtils.GenerateRequestForLinkModifierByIndex(iface.Index, canDevProps, null);
int bytesWritten = rtNetlinkSocket.Write(modReq);
if (bytesWritten > 0)
{
byte[] rxBuffer = new byte[8192];
int numBytes = rtNetlinkSocket.Read(rxBuffer);
if (numBytes >= 36)
{
NetlinkMessageError nlMsgErr = NetlinkMessageError.FromBytes(rxBuffer);
if (nlMsgErr.MessageHeader.MessageType == NetlinkMessageType.NLMSG_ERROR)
{
if (nlMsgErr.Error == 0) // Success
{
Console.WriteLine($"Bitrate: {iface.BitTiming.BitRate} bit/s");
Console.WriteLine($"Auto-Restart Delay: {iface.AutoRestartDelay} ms");
Console.WriteLine($"Controller Mode Flags: {iface.CanControllerModeFlags}");
}
else
{
Console.WriteLine($"Errno Set on Netlink Response: {-1 * nlMsgErr.Error}.");
return;
}
}
else
{
Console.WriteLine($"Unexpected Netlink message received: {nlMsgErr.MessageHeader.MessageType}.");
return;
}
}
else
{
Console.WriteLine("Read insufficient bytes from the rtnetlink socket.");
return;
}
}
else
{
Console.WriteLine($"Failed to write Netlink message: {LibcNativeMethods.Errno}.");
return;
}
}
private static void SetInterfaceDown(RoutingNetlinkSocket rtNetlinkSocket, CanNetworkInterface iface)
{
InterfaceStartStop(rtNetlinkSocket, iface, false);
}
private static void SetInterfaceUp(RoutingNetlinkSocket rtNetlinkSocket, CanNetworkInterface iface)
{
InterfaceStartStop(rtNetlinkSocket, iface, true);
}
private static void InterfaceStartStop(RoutingNetlinkSocket rtNetlinkSocket, CanNetworkInterface iface, bool start)
{
NetworkInterfaceModifierRequest modReq = NetlinkUtils.GenerateRequestForLinkModifierByIndex(iface.Index, null, start);
int bytesWritten = rtNetlinkSocket.Write(modReq);
if (bytesWritten > 0)
{
byte[] rxBuffer = new byte[8192];
int numBytes = rtNetlinkSocket.Read(rxBuffer);
if (numBytes >= 36)
{
NetlinkMessageError nlMsgErr = NetlinkMessageError.FromBytes(rxBuffer);
if (nlMsgErr.MessageHeader.MessageType == NetlinkMessageType.NLMSG_ERROR)
{
if (nlMsgErr.Error == 0) // Success
{
Console.WriteLine($"Inteface Device Flags: {iface.DeviceFlags}");
Console.WriteLine($"Inteface Operational Status: {iface.OperationalStatus}");
}
else
{
Console.WriteLine($"Errno Set on Netlink Response: {-1 * nlMsgErr.Error}.");
return;
}
}
else
{
Console.WriteLine($"Unexpected Netlink message received: {nlMsgErr.MessageHeader.MessageType}.");
return;
}
}
else
{
Console.WriteLine("Read insufficient bytes from the rtnetlink socket.");
return;
}
}
else
{
Console.WriteLine($"Failed to write Netlink message: {LibcNativeMethods.Errno}.");
return;
}
}
}
}