-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy pathDriverLoader.cs
533 lines (410 loc) · 18.7 KB
/
DriverLoader.cs
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
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
/*
This file is part of libCanopenSimple.
libCanopenSimple is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
libCanopenSimple is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with libCanopenSimple. If not, see <http://www.gnu.org/licenses/>.
Copyright(c) 2017 Robin Cornelius <[email protected]>
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
namespace libCanopenSimple
{
/// <summary> DriverLoader - dynamic pinvoke can festival drivers
/// This class will select the approprate win or mono loader and try to load the requested
/// can festival library
/// Info on pinvoke for win/mono :-
/// http://stackoverflow.com/questions/13461989/p-invoke-to-dynamically-loaded-library-on-mono
/// by gordonmleigh
/// </summary>
public class DriverLoader
{
public static bool IsRunningOnMono()
{
return Type.GetType("Mono.Runtime") != null;
}
/// <summary>
/// Attempt to load the requested can festival driver and return a DriverInstance class
/// </summary>
/// <param name="fileName"> Name of the dynamic library to load, note do not append .dll or .so</param>
/// <returns></returns>
public DriverInstance loaddriver(string fileName)
{
if (IsRunningOnMono())
{
fileName += ".so";
DriverLoaderMono dl = new DriverLoaderMono();
return dl.loaddriver(fileName);
}
else
{
fileName += ".dll";
DriverLoaderWin dl = new DriverLoaderWin();
return dl.loaddriver(fileName);
}
}
}
#region windows
/// <summary>
/// CanFestival driver loader for windows, this class will load kernel32 then attept to use LoadLibrary()
/// and GetProcAddress() to hook the can festival driver functions these are then exposed as delagates
/// for eash C# access
/// </summary>
public class DriverLoaderWin
{
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern IntPtr LoadLibrary(string libname);
[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
private static extern bool FreeLibrary(IntPtr hModule);
[DllImport("kernel32.dll", CharSet = CharSet.Ansi)]
private static extern IntPtr GetProcAddress(IntPtr hModule, string lpProcName);
private IntPtr Handle = IntPtr.Zero;
DriverInstance driver;
/// <summary>
/// Clean up and free the library
/// </summary>
~DriverLoaderWin()
{
if (Handle != IntPtr.Zero)
{
FreeLibrary(Handle);
Handle = IntPtr.Zero;
}
}
/// <summary>
/// Attempt to load the requested can festival driver and return a DriverInstance class
/// </summary>
/// <param name="fileName">Load can festival driver (Windows .Net runtime version) .dll must be appeneded in this case to fileName</param>
/// <returns></returns>
public DriverInstance loaddriver(string fileName)
{
IntPtr Handle = LoadLibrary(fileName);
if (Handle == IntPtr.Zero)
{
int errorCode = Marshal.GetLastWin32Error();
throw new Exception(string.Format("Failed to load library (ErrorCode: {0})", errorCode));
}
IntPtr funcaddr;
funcaddr = GetProcAddress(Handle, "canReceive_driver");
DriverInstance.canReceive_T canReceive = Marshal.GetDelegateForFunctionPointer(funcaddr, typeof(DriverInstance.canReceive_T)) as DriverInstance.canReceive_T;
funcaddr = GetProcAddress(Handle, "canSend_driver");
DriverInstance.canSend_T canSend = Marshal.GetDelegateForFunctionPointer(funcaddr, typeof(DriverInstance.canSend_T)) as DriverInstance.canSend_T; ;
funcaddr = GetProcAddress(Handle, "canOpen_driver");
DriverInstance.canOpen_T canOpen = Marshal.GetDelegateForFunctionPointer(funcaddr, typeof(DriverInstance.canOpen_T)) as DriverInstance.canOpen_T; ;
funcaddr = GetProcAddress(Handle, "canClose_driver");
DriverInstance.canClose_T canClose = Marshal.GetDelegateForFunctionPointer(funcaddr, typeof(DriverInstance.canClose_T)) as DriverInstance.canClose_T; ;
funcaddr = GetProcAddress(Handle, "canChangeBaudRate_driver");
DriverInstance.canChangeBaudRate_T canChangeBaudRate = Marshal.GetDelegateForFunctionPointer(funcaddr, typeof(DriverInstance.canChangeBaudRate_T)) as DriverInstance.canChangeBaudRate_T; ;
funcaddr = GetProcAddress(Handle, "canEnumerate2_driver");
DriverInstance.canEnumerate_T canEnumerate = Marshal.GetDelegateForFunctionPointer(funcaddr, typeof(DriverInstance.canEnumerate_T)) as DriverInstance.canEnumerate_T; ;
driver = new DriverInstance(canReceive, canSend, canOpen, canClose, canChangeBaudRate,canEnumerate);
return driver;
}
}
#endregion
#region mono
/// <summary>
/// CanFestival driver loader for mono, this class will load libdl then attept to use dlopen() and dlsym()
/// and GetProcAddress to hook the can festival driver functions these are then exposed as delagates
/// for eash C# access
/// </summary>
///
public class DriverLoaderMono
{
[DllImport("libdl.so")]
protected static extern IntPtr dlopen(string filename, int flags);
[DllImport("libdl.so")]
protected static extern IntPtr dlsym(IntPtr handle, string symbol);
DriverInstance driver;
const int RTLD_NOW = 2; // for dlopen's flags
/// <summary>
/// Attempt to load the requested can festival driver and return a DriverInstance class
/// </summary>
/// <param name="fileName">Load can festival driver (Mono runtime version) .so must be appeneded in this case to fileName</param>
/// <returns></returns>
public DriverInstance loaddriver(string fileName)
{
IntPtr Handle = dlopen(fileName, RTLD_NOW);
if (Handle == IntPtr.Zero)
{
int errorCode = Marshal.GetLastWin32Error();
throw new Exception(string.Format("Failed to load library (ErrorCode: {0})", errorCode));
}
IntPtr funcaddr;
funcaddr = dlsym(Handle, "canReceive_driver");
DriverInstance.canReceive_T canReceive = Marshal.GetDelegateForFunctionPointer(funcaddr, typeof(DriverInstance.canReceive_T)) as DriverInstance.canReceive_T;
funcaddr = dlsym(Handle, "canSend_driver");
DriverInstance.canSend_T canSend = Marshal.GetDelegateForFunctionPointer(funcaddr, typeof(DriverInstance.canSend_T)) as DriverInstance.canSend_T; ;
funcaddr = dlsym(Handle, "canOpen_driver");
DriverInstance.canOpen_T canOpen = Marshal.GetDelegateForFunctionPointer(funcaddr, typeof(DriverInstance.canOpen_T)) as DriverInstance.canOpen_T; ;
funcaddr = dlsym(Handle, "canClose_driver");
DriverInstance.canClose_T canClose = Marshal.GetDelegateForFunctionPointer(funcaddr, typeof(DriverInstance.canClose_T)) as DriverInstance.canClose_T; ;
funcaddr = dlsym(Handle, "canChangeBaudRate_driver");
DriverInstance.canChangeBaudRate_T canChangeBaudRate = Marshal.GetDelegateForFunctionPointer(funcaddr, typeof(DriverInstance.canChangeBaudRate_T)) as DriverInstance.canChangeBaudRate_T; ;
funcaddr = dlsym(Handle, "canEnumerate_driver");
DriverInstance.canEnumerate_T canEnumerate = Marshal.GetDelegateForFunctionPointer(funcaddr, typeof(DriverInstance.canEnumerate_T)) as DriverInstance.canEnumerate_T; ;
driver = new DriverInstance(canReceive, canSend, canOpen, canClose, canChangeBaudRate,canEnumerate);
return driver;
}
}
#endregion
/// <summary>
/// DriverInstace represents a specific instance of a loaded canfestival driver
/// </summary>
///
public class DriverInstance
{
private bool threadrun = true;
System.Threading.Thread rxthread;
/// <summary>
/// CANOpen message recieved callback, this will be fired upon any recieved complete message on the bus
/// </summary>
/// <param name="msg">The CanOpen message</param>
public delegate void RxMessage(Message msg,bool bridge=false);
public event RxMessage rxmessage;
/// <summary>
/// CanFestival message packet. Note we set data to be a UInt64 as inside canfestival its a fixed char[8] array
/// we cannout use fixed arrays in C# without UNSAFE so instead we just use a UInt64
/// </summary>
[StructLayout(LayoutKind.Sequential, Size = 12, Pack = 1)]
public struct Message
{
public UInt16 cob_source_id; /**< message's ID */
public UInt16 cob_id; /**< message's ID */
public byte rtr; /**< remote transmission request. (0 if not rtr message, 1 if rtr message) */
public byte len; /**< message's length (0 to 8) */
public UInt64 data;
}
/// <summary>
/// This contains the bus name on which the can board is connected and the bit rate of the board
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public struct struct_s_BOARD
{
[MarshalAs(UnmanagedType.LPStr)]
public String busname; /**< The bus name on which the CAN board is connected */
[MarshalAs(UnmanagedType.LPStr)]
public String baudrate; /**< The board baudrate */
};
[StructLayout(LayoutKind.Sequential)]
public struct struct_s_DEVICES
{
public UInt32 id;
[MarshalAs(UnmanagedType.LPStr)]
public string name;
};
[StructLayout(LayoutKind.Sequential)]
public struct UnmanagedStruct
{
[MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.LPStr, SizeConst = 100)]
public IntPtr[] listOfStrings;
public IEnumerable<string> Strings
{
get
{
return listOfStrings.Select(x => Marshal.PtrToStringAnsi(x));
}
}
}
UnmanagedStruct enumerationresult;
public delegate byte canReceive_T(IntPtr handle, IntPtr msg);
private canReceive_T canReceive;
public delegate byte canSend_T(IntPtr handle, IntPtr msg);
private canSend_T canSend;
public delegate IntPtr canOpen_T(IntPtr brd);
private canOpen_T canOpen;
public delegate UInt32 canClose_T(IntPtr handle);
private canClose_T canClose;
public delegate byte canChangeBaudRate_T(IntPtr handle, string rate);
private canChangeBaudRate_T canChangeBaudrate;
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
public delegate void canEnumerateDelegate_T(
[MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.LPStr, SizeParamIndex = 1)]
string[] values,
int valueCount);
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
public delegate void canEnumerate_T(canEnumerateDelegate_T callback);
private canEnumerate_T canEnumerate;
private IntPtr instancehandle = IntPtr.Zero;
IntPtr brdptr;
struct_s_BOARD brd;
/// <summary>
/// Create a new DriverInstance, this class provides a wrapper between the C# world and the C API dlls from canfestival that
/// provide access to the CAN hardware devices. The exposed delegates represent the 5 defined entry points that all can festival
/// drivers expose to form the common driver interface API. Usualy the DriverLoader class will directly call this constructor.
/// </summary>
/// <param name="canReceive">pInvoked delegate for canReceive function</param>
/// <param name="canSend">pInvoked delegate for canSend function</param>
/// <param name="canOpen">pInvoked delegate for canOpen function</param>
/// <param name="canClose">pInvoked delegate for canClose function</param>
/// <param name="canChangeBaudrate">pInvoked delegate for canChangeBaudrate functipn</param>
public DriverInstance(canReceive_T canReceive, canSend_T canSend, canOpen_T canOpen, canClose_T canClose, canChangeBaudRate_T canChangeBaudrate, canEnumerate_T canEnumerate)
{
this.canReceive = canReceive;
this.canSend = canSend;
this.canOpen = canOpen;
this.canClose = canClose;
this.canChangeBaudrate = canChangeBaudrate;
this.canEnumerate = canEnumerate;
StringBuilder[] b = new StringBuilder[2];
instancehandle = IntPtr.Zero;
brdptr = IntPtr.Zero;
}
public static List<string> ports = new List<string>();
public static void PrintReceivedData(string[] values, int valueCount)
{
foreach (var item in values)
ports.Add(item);
}
public void enumerate()
{
ports = new List<string>();
this.canEnumerate(PrintReceivedData);
}
/// <summary>
/// Open the CAN device, the bus ID and bit rate are passed to driver. For Serial/USb Seral pass COMx etc.
/// </summary>
/// <param name="bus">The requested bus ID are provided here.</param>
/// <param name="speed">The requested CAN bit rate</param>
/// <returns>True on succesful opening of device</returns>
public bool open(string bus, BUSSPEED speed)
{
try
{
brd.busname = bus;
// Map BUSSPEED to CanFestival speed options
switch (speed)
{
case BUSSPEED.BUS_10Kbit:
brd.baudrate = "10K";
break;
case BUSSPEED.BUS_20Kbit:
brd.baudrate = "20K";
break;
case BUSSPEED.BUS_50Kbit:
brd.baudrate = "50K";
break;
case BUSSPEED.BUS_100Kbit:
brd.baudrate = "100K";
break;
case BUSSPEED.BUS_125Kbit:
brd.baudrate = "125K";
break;
case BUSSPEED.BUS_250Kbit:
brd.baudrate = "250K";
break;
case BUSSPEED.BUS_500Kbit:
brd.baudrate = "500K";
break;
case BUSSPEED.BUS_1Mbit:
brd.baudrate = "1M";
break;
}
brdptr = Marshal.AllocHGlobal(Marshal.SizeOf(brd));
Marshal.StructureToPtr(brd, brdptr, false);
instancehandle = canOpen(brdptr);
if (instancehandle != IntPtr.Zero)
{
rxthread = new System.Threading.Thread(rxthreadworker);
rxthread.Start();
return true;
}
else
{
return false;
}
}
catch (Exception)
{
return false;
}
}
/// <summary>
/// See if the CAN device is open
/// </summary>
/// <returns>Open status of can device</returns>
public bool isOpen()
{
if (instancehandle == IntPtr.Zero)
return false;
return true;
}
/// <summary>
/// Close the CAN hardware device
/// </summary>
public void close()
{
threadrun = false;
System.Threading.Thread.Sleep(100);
if(rxthread!=null)
while(rxthread.ThreadState == System.Threading.ThreadState.Running)
{
System.Threading.Thread.Sleep(1);
}
if (instancehandle != IntPtr.Zero)
canClose(instancehandle);
instancehandle = IntPtr.Zero;
if (brdptr != IntPtr.Zero)
Marshal.FreeHGlobal(brdptr);
brdptr = IntPtr.Zero;
}
/// <summary>
/// Message pump function. This should be called in a fast loop
/// </summary>
/// <returns></returns>
public Message canreceive()
{
// I think we can do better here and not allocated/deallocate to heap every pump loop
Message msg = new Message();
IntPtr msgptr = Marshal.AllocHGlobal(Marshal.SizeOf(msg));
Marshal.StructureToPtr(msg, msgptr, false);
byte status = canReceive(instancehandle, msgptr);
msg = (Message)Marshal.PtrToStructure(msgptr, typeof(Message));
Marshal.FreeHGlobal(msgptr);
return msg;
}
/// <summary>
/// Send a CanOpen mesasge to the hardware device
/// </summary>
/// <param name="msg">CanOpen message to be sent</param>
public void cansend(Message msg)
{
IntPtr msgptr = Marshal.AllocHGlobal(Marshal.SizeOf(msg));
Marshal.StructureToPtr(msg, msgptr, false);
if(instancehandle!=null)
canSend(instancehandle, msgptr);
Marshal.FreeHGlobal(msgptr);
}
/// <summary>
/// Private worker thread to keep the rxmessage() function pumped
/// </summary>
private void rxthreadworker()
{
try
{
while (threadrun)
{
DriverInstance.Message rxmsg = canreceive();
if (rxmsg.len != 0)
{
if (rxmessage != null)
rxmessage(rxmsg);
}
//System.Threading.Thread.Sleep(0);
}
}
catch
{
}
}
}
}