-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathSocketCanUtils.cs
More file actions
291 lines (262 loc) · 11.8 KB
/
Copy pathSocketCanUtils.cs
File metadata and controls
291 lines (262 loc) · 11.8 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
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
#region License
/*
BSD 3-Clause License
Copyright (c) 2021, 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.Runtime.InteropServices;
using System.Collections.ObjectModel;
using System.Collections.Generic;
using System.Net.NetworkInformation;
namespace SocketCANSharp
{
/// <summary>
/// Set of SocketCAN utility functions.
/// </summary>
public static class SocketCanUtils
{
/// <summary>
/// Returns CAN XL Header Size.
/// </summary>
public static int CanXlHeaderSize { get { return Marshal.OffsetOf<CanXlFrame>("Data").ToInt32(); } }
/// <summary>
/// Validates the SocketCAN CAN Identifier structure.
/// </summary>
/// <param name="canId">CAN Identifier structure</param>
/// <exception cref="ArgumentException">CAN_EFF_FLAG not set on a CAN ID that exceeds 11 bits.</exception>
public static void ThrowIfCanIdStructureInvalid(uint canId)
{
uint rawId = canId & SocketCanConstants.CAN_EFF_MASK; // remove ERR, RTR, and EFF flags
if (rawId > 0x7ff && (canId & (uint)CanIdFlags.CAN_EFF_FLAG) == 0)
{
throw new ArgumentException("CAN_EFF_FLAG must be set when CAN ID exceeds 11 bits.", nameof(canId));
}
}
/// <summary>
/// CAN FD data length to Data Length Code (DLC).
/// </summary>
/// <param name="length">CAN FD data length</param>
/// <returns>Data Length Code (DLC) corresponding to the CAN FD data length</returns>
public static byte CanFdLengthToDlc(byte length)
{
switch (length)
{
case 0:
return 0;
case 1:
return 1;
case 2:
return 2;
case 3:
return 3;
case 4:
return 4;
case 5:
return 5;
case 6:
return 6;
case 7:
return 7;
case 8:
return 8;
case 12:
return 9;
case 16:
return 10;
case 20:
return 11;
case 24:
return 12;
case 32:
return 13;
case 48:
return 14;
case 64:
return 15;
default:
throw new ArgumentOutOfRangeException(nameof(length), $"Unsupported CAN FD Data Length: {length}.");
}
}
/// <summary>
/// CAN FD Data Length Code (DLC) to CAN data length.
/// </summary>
/// <param name="dlc">CAN FD Data Length Code (DLC)</param>
/// <returns>CAN data length corresponding to the CAN FD Data Length Code (DLC)</returns>
public static byte CanFdDlcToLength(byte dlc)
{
if (dlc > 15)
throw new ArgumentException("CAN FD DLC cannot exceed 15.", nameof(dlc));
var dlc2Len = new ReadOnlyCollection<byte>(
new byte[] {
0, 1, 2, 3, 4, 5, 6, 7,
8, 12, 16, 20, 24, 32, 48, 64});
return dlc2Len[dlc];
}
/// <summary>
/// Classical CAN Data Length Code (DLC) to CAN data length.
/// </summary>
/// <param name="dlc">Classical CAN Data Length Code (DLC)</param>
/// <returns>CAN data length corresponding to the Classical Data Length Code (DLC)</returns>
public static byte CanDlcToLength(byte dlc)
{
if (dlc > 15)
throw new ArgumentException("Classical CAN DLC cannot exceed 15.", nameof(dlc));
var dlc2Len = new ReadOnlyCollection<byte>(
new byte[] {
0, 1, 2, 3, 4, 5, 6, 7,
8, 8, 8, 8, 8, 8, 8, 8});
return dlc2Len[dlc];
}
/// <summary>
/// Extracts the Raw CAN ID from a CAN ID that contains embedded flags.
/// </summary>
/// <param name="canIdWithFlags">CAN ID with embedded flags</param>
/// <returns>Raw CAN ID value</returns>
public static uint ExtractRawCanId(uint canIdWithFlags)
{
if ((canIdWithFlags & (uint)CanIdFlags.CAN_EFF_FLAG) == 0)
return (SocketCanConstants.CAN_SFF_MASK & canIdWithFlags);
else
return (SocketCanConstants.CAN_EFF_MASK & canIdWithFlags);
}
/// <summary>
/// Creates the CAN ID with embedded flags (EFF, RTR, ERR).
/// </summary>
/// <param name="rawCanId">Raw CAN ID</param>
/// <param name="isEff">Is Extended Frame Format</param>
/// <param name="isRtr">Is Remote Transmission Request</param>
/// <param name="isErr">Is Error Frame</param>
/// <returns>CAN ID with embedded flags (EFF, RTR, ERR)</returns>
/// <exception cref="ArgumentException">Raw CAN ID exceeds 11 bits, but EFF is not set to true.</exception>
public static uint CreateCanIdWithFlags(uint rawCanId, bool isEff, bool isRtr, bool isErr)
{
if (rawCanId > SocketCanConstants.CAN_SFF_MASK && isEff == false)
{
throw new ArgumentException("Must set EFF flag on a CAN ID that exceeds 11 bits.");
}
uint canIdWithFlags = rawCanId;
if (isEff)
canIdWithFlags |= (uint)CanIdFlags.CAN_EFF_FLAG;
if (isRtr)
canIdWithFlags |= (uint)CanIdFlags.CAN_RTR_FLAG;
if (isErr)
canIdWithFlags |= (uint)CanIdFlags.CAN_ERR_FLAG;
return canIdWithFlags;
}
/// <summary>
/// Configures the raw CAN ID with the Format Flag. This shortcut method assumes Standard Frame Format for CAN IDs that are 11-bit and under and Extended Frame Format for CAN IDs over 11-bit.
/// Note: For fine-grain CAN ID configuration use <c>CreateCanIdWithFlags</c>.
/// </summary>
/// <param name="rawCanId">Raw CAN ID</param>
/// <returns>CAN ID with embedded frame format flag set when appropriate</returns>
/// <exception cref="ArgumentException">Raw CAN IDs cannot exceed size of 29-bit.</exception>
public static uint CreateCanIdWithFormatFlag(uint rawCanId)
{
if (rawCanId > SocketCanConstants.CAN_EFF_MASK)
{
throw new ArgumentException("Raw CAN IDs cannot exceed size of 29-bit.");
}
if (rawCanId > SocketCanConstants.CAN_SFF_MASK)
return ((uint)CanIdFlags.CAN_EFF_FLAG | rawCanId);
else
return rawCanId;
}
/// <summary>
/// Helper method to set the Priority ID sub-element on the provided Priority composite element.
/// </summary>
/// <param name="priority">Priority composite element</param>
/// <param name="priorityId">11-bit Priority ID</param>
/// <returns>Priority composite element with the 11-bit Priority ID set to the provided value.</returns>
/// <exception cref="ArgumentException">Priority ID cannot exceed 11 bits.</exception>
public static uint SetCanXlPriorityId(uint priority, ushort priorityId)
{
if (priorityId > 0x7ff)
throw new ArgumentException("Priority ID cannot exceed 11 bits.", nameof(priorityId));
priority &= SocketCanConstants.CANXL_VCID_MASK;
priority |= priorityId;
return priority;
}
/// <summary>
/// Helper method to get the Priority ID sub-element from the provided Priority composite element.
/// </summary>
/// <param name="priority">Priority composite element</param>
/// <returns>11-bit Priority ID from the Priority composite element.</returns>
public static ushort GetCanXlPriorityId(uint priority)
{
return (ushort)(priority & SocketCanConstants.CANXL_PRIO_MASK);
}
/// <summary>
/// Helper method to set the VCID sub-element on the provided Priority composite element.
/// </summary>
/// <param name="priority">Priority composite element</param>
/// <param name="vcid">8-bit Virtual CAN network ID</param>
/// <returns>Priority composite element with the 8-bit Virtual CAN network ID set to the provided value.</returns>
public static uint SetCanXlVCID(uint priority, byte vcid)
{
priority &= SocketCanConstants.CANXL_PRIO_MASK;
priority |= (uint)(vcid << SocketCanConstants.CANXL_VCID_OFFSET);
return priority;
}
/// <summary>
/// Helper method to get the VCID sub-element from the provided Priority composite element.
/// </summary>
/// <param name="priority">Priority composite element</param>
/// <returns>8-bit Virtual CAN network ID from the Priority composite element.</returns>
public static byte GetCanXlVCID(uint priority)
{
return (byte)((priority & SocketCanConstants.CANXL_VCID_MASK) >> SocketCanConstants.CANXL_VCID_OFFSET);
}
/// <summary>
/// Returns all network interfaces currently available on the host.
/// </summary>
/// <returns>Collection of network interfaces.</returns>
/// <exception cref="NetworkInformationException">The if_nameindex function call fails.</exception>
public static IEnumerable<IfNameIndex> GetAllInterfaces()
{
IntPtr ptr = LibcNativeMethods.IfNameIndex();
if (ptr == IntPtr.Zero)
{
throw new NetworkInformationException(LibcNativeMethods.Errno);
}
var ifList = new List<IfNameIndex>();
IntPtr iteratorPtr = ptr;
try
{
IfNameIndex i = Marshal.PtrToStructure<IfNameIndex>(iteratorPtr);
while (i.Index != 0 && i.Name != null)
{
ifList.Add(i);
iteratorPtr = IntPtr.Add(iteratorPtr, Marshal.SizeOf(typeof(IfNameIndex)));
i = Marshal.PtrToStructure<IfNameIndex>(iteratorPtr);
}
}
finally
{
LibcNativeMethods.IfFreeNameIndex(ptr);
}
return ifList;
}
}
}