-
Notifications
You must be signed in to change notification settings - Fork 23
/
libCanopenSimple.cs
733 lines (608 loc) · 25.4 KB
/
libCanopenSimple.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
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
/*
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 <robin.cornelius@gmail.com>
*/
using System;
using System.Collections.Generic;
using System.Threading;
using System.Collections.Concurrent;
using System.Runtime.CompilerServices;
namespace libCanopenSimple
{
public enum BUSSPEED
{
BUS_10Kbit = 0,
BUS_20Kbit,
BUS_50Kbit,
BUS_100Kbit,
BUS_125Kbit,
BUS_250Kbit,
BUS_500Kbit,
BUS_800Kbit,
BUS_1Mbit,
}
public enum debuglevel
{
DEBUG_ALL,
DEBUG_NONE
}
/// <summary>
/// C# representation of a CanPacket, containing the COB the length and the data. RTR is not supported
/// as its prettly much not used on CanOpen, but this could be added later if necessary
/// </summary>
public class canpacket
{
public UInt16 cob;
public byte len;
public byte[] data;
public bool bridge = false;
public canpacket()
{
}
/// <summary>
/// Construct C# Canpacket from a CanFestival message
/// </summary>
/// <param name="msg">A CanFestival message struct</param>
public canpacket(DriverInstance.Message msg,bool bridge=false)
{
cob = msg.cob_id;
len = msg.len;
data = new byte[len];
this.bridge = bridge;
byte[] temp = BitConverter.GetBytes(msg.data);
Array.Copy(temp, data, msg.len);
}
/// <summary>
/// Convert to a CanFestival message
/// </summary>
/// <returns>CanFestival message</returns>
public DriverInstance.Message ToMsg()
{
DriverInstance.Message msg = new DriverInstance.Message();
msg.cob_id = cob;
msg.len = len;
msg.rtr = 0;
byte[] temp = new byte[8];
Array.Copy(data, temp, len);
msg.data = BitConverter.ToUInt64(temp, 0);
return msg;
}
/// <summary>
/// Dump current packet to string
/// </summary>
/// <returns>Formatted string of current packet</returns>
public override string ToString()
{
string output = string.Format("{0:x3} {1:x1}", cob, len);
for (int x = 0; x < len; x++)
{
output += string.Format(" {0:x2}", data[x]);
}
return output;
}
}
/// <summary>
/// A simple can open class providing callbacks for each of the message classes and allowing one to send messages to the bus
/// Also supports some NMT helper functions and can act as a SDO Client
/// It is not a CanDevice and does not respond to any message (other than the required SDO client handshakes) and it does not
/// contain an object dictionary
/// </summary>
public class libCanopenSimple
{
public debuglevel dbglevel = debuglevel.DEBUG_NONE;
DriverInstance driver;
Dictionary<UInt16, NMTState> nmtstate = new Dictionary<ushort, NMTState>();
private Queue<SDO> sdo_queue = new Queue<SDO>();
DriverLoader loader = new DriverLoader();
public bool echo = true;
public libCanopenSimple()
{
//preallocate all NMT guards
for (byte x = 0; x < 0x80; x++)
{
NMTState nmt = new NMTState();
nmtstate[x] = nmt;
}
}
#region driverinterface
/// <summary>
/// Open the CAN hardware device via the CanFestival driver, NB this is currently a simple version that will
/// not work with drivers that have more complex bus ids so only supports com port (inc usb serial) devices for the moment
/// </summary>
/// <param name="comport">COM PORT number</param>
/// <param name="speed">CAN Bit rate</param>
/// <param name="drivername">Driver to use</param>
public bool open(string comport, BUSSPEED speed, string drivername)
{
driver = loader.loaddriver(drivername);
if (driver.open(string.Format("{0}", comport), speed) == false)
return false;
driver.rxmessage += Driver_rxmessage;
threadrun = true;
Thread thread = new Thread(new ThreadStart(asyncprocess));
thread.Name = "CAN Open worker";
thread.Start();
if (connectionevent != null) connectionevent(this, new ConnectionChangedEventArgs(true));
return true;
}
public Dictionary<string, List<string>> ports = new Dictionary<string, List<string>>();
public Dictionary<string, DriverInstance> drivers = new Dictionary<string, DriverInstance>();
public void enumerate(string drivername)
{
if (!ports.ContainsKey(drivername))
ports.Add(drivername, new List<string>());
//Keep a cache of open drivers or else if we try to close
//on a hot plug event we have lost the handle and we will never close the port
if (!drivers.ContainsKey(drivername))
{
driver = loader.loaddriver(drivername);
drivers.Add(drivername, driver);
}
DriverInstance di = drivers[drivername];
di.enumerate();
ports[drivername] = DriverInstance.ports;
}
/// <summary>
/// Is the driver open
/// </summary>
/// <returns>true = driver open and ready to use</returns>
public bool isopen()
{
if (driver == null)
return false;
return driver.isOpen();
}
/// <summary>
/// Send a Can packet on the bus
/// </summary>
/// <param name="p"></param>
public void SendPacket(canpacket p, bool bridge=false)
{
DriverInstance.Message msg = p.ToMsg();
driver.cansend(msg);
if (echo == true)
{
Driver_rxmessage(msg,bridge);
}
}
/// <summary>
/// Recieved message callback handler
/// </summary>
/// <param name="msg">CanOpen message recieved from the bus</param>
private void Driver_rxmessage(DriverInstance.Message msg,bool bridge=false)
{
packetqueue.Enqueue(new canpacket(msg,bridge));
}
/// <summary>
/// Close the CanOpen CanFestival driver
/// </summary>
public void close()
{
threadrun = false;
if (driver == null)
return;
driver.close();
if (connectionevent != null) connectionevent(this, new ConnectionChangedEventArgs(false));
}
#endregion
Dictionary<UInt16, Action<byte[]>> PDOcallbacks = new Dictionary<ushort, Action<byte[]>>();
public Dictionary<UInt16, SDO> SDOcallbacks = new Dictionary<ushort, SDO>();
ConcurrentQueue<canpacket> packetqueue = new ConcurrentQueue<canpacket>();
public delegate void ConnectionEvent(object sender, EventArgs e);
public event ConnectionEvent connectionevent;
public delegate void PacketEvent(canpacket p, DateTime dt);
public event PacketEvent packetevent;
public delegate void SDOEvent(canpacket p, DateTime dt);
public event SDOEvent sdoevent;
public delegate void NMTEvent(canpacket p, DateTime dt);
public event NMTEvent nmtevent;
public delegate void NMTECEvent(canpacket p, DateTime dt);
public event NMTECEvent nmtecevent;
public delegate void PDOEvent(canpacket[] p,DateTime dt);
public event PDOEvent pdoevent;
public delegate void EMCYEvent(canpacket p, DateTime dt);
public event EMCYEvent emcyevent;
public delegate void LSSEvent(canpacket p, DateTime dt);
public event LSSEvent lssevent;
public delegate void TIMEEvent(canpacket p, DateTime dt);
public event TIMEEvent timeevent;
public delegate void SYNCEvent(canpacket p, DateTime dt);
public event SYNCEvent syncevent;
bool threadrun = true;
/// <summary>
/// Register a parser handler for a PDO, if a PDO is recieved with a matching COB this function will be called
/// so that additional messages can be added for bus decoding and monitoring
/// </summary>
/// <param name="cob">COB to match</param>
/// <param name="handler">function(byte[] data]{} function to invoke</param>
public void registerPDOhandler(UInt16 cob, Action<byte[]> handler)
{
PDOcallbacks[cob] = handler;
}
/// <summary>
/// Main process loop, used to get latest packets from buffer and also keep the SDO events pumped
/// When packets are recieved they will be matched to any approprate callback handlers for this specific COB type
/// and that handler invoked.
/// </summary>
void asyncprocess()
{
while (threadrun)
{
canpacket cp;
List<canpacket> pdos = new List<canpacket>();
while (threadrun && packetqueue.IsEmpty && pdos.Count==0 && sdo_queue.Count==0 && SDO.isEmpty())
{
System.Threading.Thread.Sleep(0);
}
while (packetqueue.TryDequeue(out cp))
{
if (cp.bridge == false)
{
if(packetevent!=null)
packetevent(cp, DateTime.Now);
}
//PDO 0x180 -- 0x57F
if (cp.cob >= 0x180 && cp.cob <= 0x57F)
{
if (PDOcallbacks.ContainsKey(cp.cob))
PDOcallbacks[cp.cob](cp.data);
pdos.Add(cp);
}
//SDO replies 0x601-0x67F
if (cp.cob >= 0x580 && cp.cob < 0x600)
{
if (cp.len != 8)
return;
lock (sdo_queue)
{
if (SDOcallbacks.ContainsKey(cp.cob))
{
if (SDOcallbacks[cp.cob].SDOProcess(cp))
{
SDOcallbacks.Remove(cp.cob);
}
}
if (sdoevent != null)
sdoevent(cp, DateTime.Now);
}
}
if (cp.cob >= 0x600 && cp.cob < 0x680)
{
if (sdoevent != null)
sdoevent(cp,DateTime.Now);
}
//NMT
if (cp.cob > 0x700 && cp.cob <= 0x77f)
{
byte node = (byte)(cp.cob & 0x07F);
nmtstate[node].changestate((NMTState.e_NMTState)cp.data[0]);
nmtstate[node].lastping = DateTime.Now;
if (nmtecevent != null)
nmtecevent(cp, DateTime.Now);
}
if (cp.cob == 000)
{
if (nmtevent != null)
nmtevent(cp, DateTime.Now);
}
if (cp.cob == 0x80)
{
if (syncevent != null)
syncevent(cp, DateTime.Now);
}
if (cp.cob > 0x080 && cp.cob <= 0xFF)
{
if (emcyevent != null)
{
emcyevent(cp, DateTime.Now);
}
}
if (cp.cob == 0x100)
{
if (timeevent != null)
timeevent(cp, DateTime.Now);
}
if (cp.cob > 0x7E4 && cp.cob <= 0x7E5)
{
if (lssevent != null)
lssevent(cp, DateTime.Now);
}
}
if (pdos.Count > 0)
{
if (pdoevent != null)
pdoevent(pdos.ToArray(),DateTime.Now);
}
SDO.kick_SDO();
lock (sdo_queue)
{
if (sdo_queue.Count > 0)
{
SDO sdoobj = sdo_queue.Peek();
if (!SDOcallbacks.ContainsKey((UInt16)(sdoobj.node + 0x580)))
{
sdoobj = sdo_queue.Dequeue();
SDOcallbacks.Add((UInt16)(sdoobj.node + 0x580), sdoobj);
sdoobj.sendSDO();
}
}
}
}
}
#region SDOHelpers
/// <summary>
/// Write to a node via SDO
/// </summary>
/// <param name="node">Node ID</param>
/// <param name="index">Object Dictionary Index</param>
/// <param name="subindex">Object Dictionary sub index</param>
/// <param name="udata">UInt32 data to send</param>
/// <param name="completedcallback">Call back on finished/error event</param>
/// <returns>SDO class that is used to perform the packet handshake, contains error/status codes</returns>
public SDO SDOwrite(byte node, UInt16 index, byte subindex, UInt32 udata, Action<SDO> completedcallback)
{
byte[] bytes = BitConverter.GetBytes(udata);
return SDOwrite(node, index, subindex, bytes, completedcallback);
}
/// <summary>
/// Write to a node via SDO
/// </summary>
/// <param name="node">Node ID</param>
/// <param name="index">Object Dictionary Index</param>
/// <param name="subindex">Object Dictionary sub index</param>
/// <param name="udata">Int64 data to send</param>
/// <param name="completedcallback">Call back on finished/error event</param>
/// <returns>SDO class that is used to perform the packet handshake, contains error/status codes</returns>
public SDO SDOwrite(byte node, UInt16 index, byte subindex, Int64 udata, Action<SDO> completedcallback)
{
byte[] bytes = BitConverter.GetBytes(udata);
return SDOwrite(node, index, subindex, bytes, completedcallback);
}
/// <summary>
/// Write to a node via SDO
/// </summary>
/// <param name="node">Node ID</param>
/// <param name="index">Object Dictionary Index</param>
/// <param name="subindex">Object Dictionary sub index</param>
/// <param name="udata">UInt64 data to send</param>
/// <param name="completedcallback">Call back on finished/error event</param>
/// <returns>SDO class that is used to perform the packet handshake, contains error/status codes</returns>
public SDO SDOwrite(byte node, UInt16 index, byte subindex, UInt64 udata, Action<SDO> completedcallback)
{
byte[] bytes = BitConverter.GetBytes(udata);
return SDOwrite(node, index, subindex, bytes, completedcallback);
}
/// <summary>
/// Write to a node via SDO
/// </summary>
/// <param name="node">Node ID</param>
/// <param name="index">Object Dictionary Index</param>
/// <param name="subindex">Object Dictionary sub index</param>
/// <param name="udata">Int32 data to send</param>
/// <param name="completedcallback">Call back on finished/error event</param>
/// <returns>SDO class that is used to perform the packet handshake, contains error/status codes</returns>
public SDO SDOwrite(byte node, UInt16 index, byte subindex, Int32 udata, Action<SDO> completedcallback)
{
byte[] bytes = BitConverter.GetBytes(udata);
return SDOwrite(node, index, subindex, bytes, completedcallback);
}
/// <summary>
/// Write to a node via SDO
/// </summary>
/// <param name="node">Node ID</param>
/// <param name="index">Object Dictionary Index</param>
/// <param name="subindex">Object Dictionary sub index</param>
/// <param name="udata">UInt16 data to send</param>
/// <param name="completedcallback">Call back on finished/error event</param>
/// <returns>SDO class that is used to perform the packet handshake, contains error/status codes</returns>
public SDO SDOwrite(byte node, UInt16 index, byte subindex, Int16 udata, Action<SDO> completedcallback)
{
byte[] bytes = BitConverter.GetBytes(udata);
return SDOwrite(node, index, subindex, bytes, completedcallback);
}
/// <summary>
/// Write to a node via SDO
/// </summary>
/// <param name="node">Node ID</param>
/// <param name="index">Object Dictionary Index</param>
/// <param name="subindex">Object Dictionary sub index</param>
/// <param name="udata">UInt16 data to send</param>
/// <param name="completedcallback">Call back on finished/error event</param>
/// <returns>SDO class that is used to perform the packet handshake, contains error/status codes</returns>
public SDO SDOwrite(byte node, UInt16 index, byte subindex, UInt16 udata, Action<SDO> completedcallback)
{
byte[] bytes = BitConverter.GetBytes(udata);
return SDOwrite(node, index, subindex, bytes, completedcallback);
}
/// <summary>
/// Write to a node via SDO
/// </summary>
/// <param name="node">Node ID</param>
/// <param name="index">Object Dictionary Index</param>
/// <param name="subindex">Object Dictionary sub index</param>
/// <param name="udata">float data to send</param>
/// <param name="completedcallback">Call back on finished/error event</param>
/// <returns>SDO class that is used to perform the packet handshake, contains error/status codes</returns>
public SDO SDOwrite(byte node, UInt16 index, byte subindex, float ddata, Action<SDO> completedcallback)
{
byte[] bytes = BitConverter.GetBytes(ddata);
return SDOwrite(node, index, subindex, bytes, completedcallback);
}
/// <summary>
/// Write to a node via SDO
/// </summary>
/// <param name="node">Node ID</param>
/// <param name="index">Object Dictionary Index</param>
/// <param name="subindex">Object Dictionary sub index</param>
/// <param name="udata">a byte of data to send</param>
/// <param name="completedcallback">Call back on finished/error event</param>
/// <returns>SDO class that is used to perform the packet handshake, contains error/status codes</returns>
public SDO SDOwrite(byte node, UInt16 index, byte subindex, byte udata, Action<SDO> completedcallback)
{
byte[] bytes = new byte[1];
bytes[0] = udata;
return SDOwrite(node, index, subindex, bytes, completedcallback);
}
/// <summary>
/// Write to a node via SDO
/// </summary>
/// <param name="node">Node ID</param>
/// <param name="index">Object Dictionary Index</param>
/// <param name="subindex">Object Dictionary sub index</param>
/// <param name="udata">a byte of unsigned data to send</param>
/// <param name="completedcallback">Call back on finished/error event</param>
/// <returns>SDO class that is used to perform the packet handshake, contains error/status codes</returns>
public SDO SDOwrite(byte node, UInt16 index, byte subindex, sbyte udata, Action<SDO> completedcallback)
{
byte[] bytes = new byte[1];
bytes[0] = (byte)udata;
return SDOwrite(node, index, subindex, bytes, completedcallback);
}
/// <summary>
/// Write to a node via SDO
/// </summary>
/// <param name="node">Node ID</param>
/// <param name="index">Object Dictionary Index</param>
/// <param name="subindex">Object Dictionary sub index</param>
/// <param name="udata">byte[] of data (1-8 bytes) to send</param>
/// <param name="completedcallback">Call back on finished/error event</param>
/// <returns>SDO class that is used to perform the packet handshake, contains error/status codes</returns>
public SDO SDOwrite(byte node, UInt16 index, byte subindex, byte[] data, Action<SDO> completedcallback)
{
SDO sdo = new SDO(this, node, index, subindex, SDO.direction.SDO_WRITE, completedcallback, data);
lock(sdo_queue)
sdo_queue.Enqueue(sdo);
return sdo;
}
/// <summary>
/// Read from a remote node via SDO
/// </summary>
/// <param name="node">Node ID to read from</param>
/// <param name="index">Object Dictionary Index</param>
/// <param name="subindex">Object Dictionary sub index</param>
/// <param name="completedcallback">Call back on finished/error event</param>
/// <returns>SDO class that is used to perform the packet handshake, contains returned data and error/status codes</returns>
public SDO SDOread(byte node, UInt16 index, byte subindex, Action<SDO> completedcallback)
{
SDO sdo = new SDO(this, node, index, subindex, SDO.direction.SDO_READ, completedcallback, null);
lock (sdo_queue)
sdo_queue.Enqueue(sdo);
return sdo;
}
/// <summary>
/// Get the current length of Enqueued items
/// </summary>
/// <returns></returns>
public int getSDOQueueSize()
{
return sdo_queue.Count;
}
/// <summary>
/// Flush the SDO queue
/// </summary>
public void flushSDOqueue()
{
lock (sdo_queue)
sdo_queue.Clear();
}
#endregion
#region NMTHelpers
public void NMT_start(byte nodeid = 0)
{
canpacket p = new canpacket();
p.cob = 000;
p.len = 2;
p.data = new byte[2];
p.data[0] = 0x01;
p.data[1] = nodeid;
SendPacket(p);
}
public void NMT_preop(byte nodeid = 0)
{
canpacket p = new canpacket();
p.cob = 000;
p.len = 2;
p.data = new byte[2];
p.data[0] = 0x80;
p.data[1] = nodeid;
SendPacket(p);
}
public void NMT_stop(byte nodeid = 0)
{
canpacket p = new canpacket();
p.cob = 000;
p.len = 2;
p.data = new byte[2];
p.data[0] = 0x02;
p.data[1] = nodeid;
SendPacket(p);
}
public void NMT_ResetNode(byte nodeid = 0)
{
canpacket p = new canpacket();
p.cob = 000;
p.len = 2;
p.data = new byte[2];
p.data[0] = 0x81;
p.data[1] = nodeid;
SendPacket(p);
}
public void NMT_ResetComms(byte nodeid = 0)
{
canpacket p = new canpacket();
p.cob = 000;
p.len = 2;
p.data = new byte[2];
p.data[0] = 0x82;
p.data[1] = nodeid;
SendPacket(p);
}
public void NMT_SetStateTransitionCallback(byte node, Action<NMTState.e_NMTState> callback)
{
nmtstate[node].NMT_boot = callback;
}
public bool NMT_isNodeFound(byte node)
{
return nmtstate[node].state != NMTState.e_NMTState.INVALID;
}
public void NMT_ReseCommunication(byte nodeid = 0)
{
canpacket p = new canpacket();
p.cob = 000;
p.len = 2;
p.data = new byte[2];
p.data[0] = 0x81;
p.data[1] = nodeid;
SendPacket(p);
}
public bool checkguard(int node, TimeSpan maxspan)
{
if (DateTime.Now - nmtstate[(ushort)node].lastping > maxspan)
return false;
return true;
}
#endregion
#region PDOhelpers
public void writePDO(UInt16 cob, byte[] payload)
{
canpacket p = new canpacket();
p.cob = cob;
p.len = (byte)payload.Length;
p.data = new byte[p.len];
for (int x = 0; x < payload.Length; x++)
p.data[x] = payload[x];
SendPacket(p);
}
#endregion
}
}