forked from robincornelius/libedssharp
-
Notifications
You must be signed in to change notification settings - Fork 93
Expand file tree
/
Copy pathCanOpenXDD_1_1.cs
More file actions
2419 lines (2153 loc) · 129 KB
/
CanOpenXDD_1_1.cs
File metadata and controls
2419 lines (2153 loc) · 129 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
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
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
This file is part of libEDSsharp.
libEDSsharp 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.
libEDSsharp 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 libEDSsharp. If not, see <http://www.gnu.org/licenses/>.
Copyright(c) 2016 - 2020 Robin Cornelius <robin.cornelius@gmail.com>
Copyright(c) 2020 Janez Paternoster
*/
using System;
using System.IO;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Xml;
using System.Xml.Serialization;
using CanOpenXSD_1_1;
using LibCanOpen;
using Google.Protobuf;
using Google.Protobuf.WellKnownTypes;
using System.Linq;
using System.Reflection;
namespace libEDSsharp
{
/// <summary>
/// Convert to/from EDSsharp and CanOpenXDD v1.1, it uses the generated source file CanOpenXSD_1_1
/// </summary>
/// <seealso cref="CanOpenXSD_1_1"/>
public class CanOpenXDD_1_1 : IFileExporter
{
/// <summary>
/// Fetches all the different fileexporter types the class supports
/// </summary>
/// <returns>List of the different exporters the class supports</returns>
public ExporterDescriptor[] GetExporters()
{
return new ExporterDescriptor[] {
new ExporterDescriptor("CanOpen XDD v1.1", new string[] { ".xdd" }, 0, delegate (string filepath, List<EDSsharp> edss)
{
var e = new CanOpenXDD_1_1();
e.WriteXML(filepath,edss[0],false,false);
}),
new ExporterDescriptor("CanOpen XDD v1.1 stripped", new string[] { ".xdd" }, 0, delegate (string filepath, List<EDSsharp> edss)
{
var e = new CanOpenXDD_1_1();
e.WriteXML(filepath,edss[0],false,true);
}),
new ExporterDescriptor("CanOpen XDC v1.1", new string[] { ".xdc" }, 0, delegate (string filepath, List<EDSsharp> edss)
{
var e = new CanOpenXDD_1_1();
e.WriteXML(filepath,edss[0],true,true);
}),
new ExporterDescriptor("CanOpen Network XDD v1.1", new string[] { ".nxdd" }, ExporterDescriptor.ExporterFlags.MultipleNodeSupport, delegate (string filepath, List<EDSsharp> edss)
{
var e = new CanOpenXDD_1_1();
e.WriteMultiXML(filepath,edss,false);
}),
new ExporterDescriptor("CanOpen Network XDC v1.1", new string[] { ".nxdc" }, ExporterDescriptor.ExporterFlags.MultipleNodeSupport, delegate (string filepath, List<EDSsharp> edss)
{
var e = new CanOpenXDD_1_1();
e.WriteMultiXML(filepath,edss,true);
}),
new ExporterDescriptor("CanOpenNode Protobuf (json)", new string[] { ".json" }, 0, delegate (string filepath, List<EDSsharp> edss)
{
var e = new CanOpenXDD_1_1();
e.WriteProtobuf(filepath,edss[0],true);
}),
new ExporterDescriptor("CanOpenNode Protobuf (binary)", new string[] { ".binpb" }, 0, delegate (string filepath, List<EDSsharp> edss)
{
var e = new CanOpenXDD_1_1();
e.WriteProtobuf(filepath,edss[0],false);
})
};
}
/// <summary>
/// Read XDD file into EDSsharp object
/// </summary>
/// <param name="file">Name of the xdd file</param>
/// <returns>EDSsharp object</returns>
public EDSsharp ReadXML(string file)
{
ISO15745ProfileContainer dev;
try
{
XmlSerializer serializer = new XmlSerializer(typeof(ISO15745ProfileContainer));
StreamReader reader = new StreamReader(file);
dev = (ISO15745ProfileContainer)serializer.Deserialize(reader);
reader.Close();
}
catch (Exception e)
{
if (e is System.InvalidOperationException)
{
Warnings.warning_list.Add(String.Format("{0} {1} Action aborted!", e.Message, e.InnerException.Message));
}
else
{
Warnings.warning_list.Add(String.Format("{0} Action aborted!", e.ToString()));
}
return null;
}
return Convert(dev);
}
/// <summary>
/// Read custom multi xdd file (multiple standard xdd files inside one xml container)
/// </summary>
/// <param name="file">Name of the multi xdd file</param>
/// <returns>List of EDSsharp objects</returns>
public List<EDSsharp> ReadMultiXML(string file )
{
List<EDSsharp> edss = new List<EDSsharp>();
try
{
XmlSerializer serializer = new XmlSerializer(typeof(CanOpenProject_1_1));
StreamReader reader = new StreamReader(file);
CanOpenProject_1_1 oep = (CanOpenProject_1_1)serializer.Deserialize(reader);
foreach(ISO15745ProfileContainer cont in oep.ISO15745ProfileContainer)
{
edss.Add(Convert(cont));
}
reader.Close();
return edss;
}
catch (Exception)
{
return null;
}
}
/// <summary>
/// Write custom multi xdd file (multiple standard xdd files inside one xml container)
/// </summary>
/// <param name="file">Name of the multi xdd file</param>
/// <param name="edss">List of EDSsharp objects</param>
/// <param name="deviceCommissioning">If true, device commisioning, denotations and actual values will be included</param>
public void WriteMultiXML(string file, List<EDSsharp> edss, bool deviceCommissioning)
{
var versionAttributes = Assembly
.GetExecutingAssembly()
.GetCustomAttributes(typeof(AssemblyInformationalVersionAttribute), false)
as AssemblyInformationalVersionAttribute[];
string gitVersion = versionAttributes[0].InformationalVersion;
List<ISO15745ProfileContainer> devs = new List<ISO15745ProfileContainer>();
foreach (EDSsharp eds in edss)
{
ISO15745ProfileContainer dev = Convert(eds, Path.GetFileName(file), deviceCommissioning, false);
devs.Add(dev);
}
CanOpenProject_1_1 oep = new CanOpenProject_1_1
{
Version = "1.1",
ISO15745ProfileContainer = devs
};
XmlSerializer serializer = new XmlSerializer(typeof(CanOpenProject_1_1));
StreamWriter stream = new StreamWriter(file);
stream.NewLine = "\n";
XmlWriter writer = XmlWriter.Create(stream, new XmlWriterSettings { Indent = true, NewLineChars = "\n" });
writer.WriteStartDocument();
writer.WriteComment(string.Format("CANopen Project file in custom format. It contains multiple standard CANopen device description files.", gitVersion));
writer.WriteComment(string.Format("File is generated by CANopenEditor {0}, URL: https://github.com/CANopenNode/CANopenEditor", gitVersion));
writer.WriteComment("File includes additional custom properties for CANopenNode, CANopen protocol stack, URL: https://github.com/CANopenNode/CANopenNode");
serializer.Serialize(writer, oep);
writer.WriteEndDocument();
writer.Close();
stream.Close();
}
/// <summary>
/// Write XDD file from EDSsharp object
/// </summary>
/// <param name="file">Name of the xdd file</param>
/// <param name="eds">EDSsharp object</param>
/// <param name="deviceCommissioning">If true, device commisioning, denotations and actual values will be included</param>
/// <param name="stripped">If true, then all CANopenNode specific parameters and all disabled objects will be stripped</param>
public void WriteXML(string file, EDSsharp eds, bool deviceCommissioning, bool stripped)
{
ISO15745ProfileContainer dev = Convert(eds, Path.GetFileName(file), deviceCommissioning, stripped);
XmlSerializer serializer = new XmlSerializer(typeof(ISO15745ProfileContainer));
StreamWriter stream = new StreamWriter(file);
stream.NewLine = "\n";
XmlWriter writer = XmlWriter.Create(stream, new XmlWriterSettings { Indent = true, NewLineChars = "\n" });
writer.WriteStartDocument();
var versionAttributes = Assembly
.GetExecutingAssembly()
.GetCustomAttributes(typeof(AssemblyInformationalVersionAttribute), false)
as AssemblyInformationalVersionAttribute[];
string gitVersion = versionAttributes[0].InformationalVersion;
writer.WriteComment(string.Format("File is generated by CANopenEditor {0}, URL: https://github.com/CANopenNode/CANopenEditor", gitVersion));
if (!stripped)
writer.WriteComment("File includes additional custom properties for CANopenNode, CANopen protocol stack, URL: https://github.com/CANopenNode/CANopenNode");
serializer.Serialize(writer, dev);
writer.WriteEndDocument();
writer.Close();
stream.Close();
}
/// <summary>
/// Read protobuffer file into EDSsharp object
/// </summary>
/// <param name="file">Name of the protobuffer file</param>
/// <param name="json">read as JSON string or binary wireformat</param>
/// <returns>EDSsharp object</returns>
public EDSsharp ReadProtobuf(string file, bool json)
{
CanOpenDevice devCanOpen;
// read the protobuffer message in json format or binary wireformat
if (json)
{
var parserConfig = new JsonParser.Settings(100);
var parser = new JsonParser(parserConfig);
devCanOpen = parser.Parse<CanOpenDevice>(System.IO.File.ReadAllText(file));
}
else
{
using (var input = System.IO.File.OpenRead(file))
{
devCanOpen = CanOpenDevice.Parser.ParseFrom(input);
}
}
/* first convert to XDD, then to EDSsharp (for now) */
ISO15745ProfileContainer devXdd = ConvertFromProtobuf(devCanOpen, file, true, false);
return Convert(devXdd);
}
/// <summary>
/// Write protobuffer file from EDSsharp object
/// </summary>
/// <param name="file">Name of the protobuffer file</param>
/// <param name="eds">EDSsharp object</param>
/// <param name="json">write as JSON string or binary wireformat</param>
public void WriteProtobuf(string file, EDSsharp eds, bool json)
{
/* first convert to XDD, then to protobuffer (for now) */
ISO15745ProfileContainer devXdd = Convert(eds, Path.GetFileName(file), true, false);
CanOpenDevice dev = ConvertToProtobuf(devXdd);
// write the protobuffer message in json format or binary wireformat
if (json)
{
var formatterConfig = new JsonFormatter.Settings(true).WithIndentation().WithFormatDefaultValues(true);
var formatter = new JsonFormatter(formatterConfig);
var rawJsonString = formatter.Format(dev);
System.IO.File.WriteAllText(file, rawJsonString);
}
else
{
using (var output = System.IO.File.Create(file))
{
dev.WriteTo(output);
}
}
}
private parameterTemplateAccess ConvertAccessType(EDSsharp.AccessType edsAccessType)
{
switch (edsAccessType)
{
case EDSsharp.AccessType.@const: return parameterTemplateAccess.@const;
case EDSsharp.AccessType.ro: return parameterTemplateAccess.read;
case EDSsharp.AccessType.rw: return parameterTemplateAccess.readWrite;
case EDSsharp.AccessType.rwr: return parameterTemplateAccess.readWriteInput;
case EDSsharp.AccessType.rww: return parameterTemplateAccess.readWriteOutput;
case EDSsharp.AccessType.wo: return parameterTemplateAccess.write;
default: return parameterTemplateAccess.noAccess;
}
}
private parameterTemplateAccess ConvertAccessType(OdSubObject subEntry)
{
switch (subEntry.Sdo)
{
case LibCanOpen.OdSubObject.Types.AccessSDO.Ro: return parameterTemplateAccess.read;
case LibCanOpen.OdSubObject.Types.AccessSDO.Wo: return parameterTemplateAccess.write;
case LibCanOpen.OdSubObject.Types.AccessSDO.Rw:
switch (subEntry.Pdo)
{
case LibCanOpen.OdSubObject.Types.AccessPDO.R: return parameterTemplateAccess.readWriteInput;
case LibCanOpen.OdSubObject.Types.AccessPDO.T: return parameterTemplateAccess.readWriteOutput;
default: return parameterTemplateAccess.readWrite;
}
default: return parameterTemplateAccess.noAccess;
}
}
private EDSsharp.AccessType ConvertAccessType(parameterTemplateAccess xddAccessType)
{
switch (xddAccessType)
{
case parameterTemplateAccess.@const: return EDSsharp.AccessType.@const;
case parameterTemplateAccess.read: return EDSsharp.AccessType.ro;
case parameterTemplateAccess.readWrite: return EDSsharp.AccessType.rw;
case parameterTemplateAccess.readWriteInput: return EDSsharp.AccessType.rwr;
case parameterTemplateAccess.readWriteOutput: return EDSsharp.AccessType.rww;
case parameterTemplateAccess.write: return EDSsharp.AccessType.wo;
default: return EDSsharp.AccessType.UNKNOWN;
}
}
private void ConvertAccessType(parameterTemplateAccess xddAccessType, OdSubObject subEntry)
{
switch (xddAccessType)
{
case parameterTemplateAccess.@const:
case parameterTemplateAccess.read:
subEntry.Sdo = LibCanOpen.OdSubObject.Types.AccessSDO.Ro;
break;
case parameterTemplateAccess.readWrite:
subEntry.Sdo = LibCanOpen.OdSubObject.Types.AccessSDO.Rw;
break;
case parameterTemplateAccess.readWriteInput:
subEntry.Sdo = LibCanOpen.OdSubObject.Types.AccessSDO.Rw;
subEntry.Pdo = LibCanOpen.OdSubObject.Types.AccessPDO.T;
break;
case parameterTemplateAccess.readWriteOutput:
subEntry.Sdo = LibCanOpen.OdSubObject.Types.AccessSDO.Rw;
subEntry.Pdo = LibCanOpen.OdSubObject.Types.AccessPDO.R;
break;
case parameterTemplateAccess.write:
subEntry.Sdo = LibCanOpen.OdSubObject.Types.AccessSDO.Wo;
break;
default:
subEntry.Sdo = LibCanOpen.OdSubObject.Types.AccessSDO.No;
break;
}
}
private Items1ChoiceType ConvertDataType (ODentry od)
{
UInt32 byteLength;
bool signed = false;
var dt = od.datatype;
if (dt == DataType.UNKNOWN && od.parent != null)
dt = od.parent.datatype;
switch (dt)
{
case DataType.BOOLEAN: return Items1ChoiceType.BOOL;
case DataType.INTEGER8: return Items1ChoiceType.SINT;
case DataType.INTEGER16: return Items1ChoiceType.INT;
case DataType.INTEGER32: return Items1ChoiceType.DINT;
case DataType.INTEGER64: return Items1ChoiceType.LINT;
case DataType.UNSIGNED8: return Items1ChoiceType.USINT;
case DataType.UNSIGNED16: return Items1ChoiceType.UINT;
case DataType.UNSIGNED32: return Items1ChoiceType.UDINT;
case DataType.UNSIGNED64: return Items1ChoiceType.ULINT;
case DataType.REAL32: return Items1ChoiceType.REAL;
case DataType.REAL64: return Items1ChoiceType.LREAL;
case DataType.VISIBLE_STRING: return Items1ChoiceType.STRING;
case DataType.OCTET_STRING: return Items1ChoiceType.BITSTRING;
case DataType.UNICODE_STRING: return Items1ChoiceType.WSTRING;
case DataType.DOMAIN:
od.defaultvalue = "";
return Items1ChoiceType.BITSTRING;
default:
od.datatype = DataType.INTEGER32;
return Items1ChoiceType.DINT;
// transform other non standard values to OCTET_STRING
case DataType.INTEGER24: byteLength = 3; signed = true; break;
case DataType.INTEGER40: byteLength = 5; signed = true; break;
case DataType.INTEGER48: byteLength = 6; signed = true; break;
case DataType.INTEGER56: byteLength = 7; signed = true; break;
case DataType.UNSIGNED24: byteLength = 3; break;
case DataType.UNSIGNED40: byteLength = 5; break;
case DataType.UNSIGNED48:
case DataType.TIME_OF_DAY:
case DataType.TIME_DIFFERENCE: byteLength = 6; break;
case DataType.UNSIGNED56: byteLength = 7; break;
}
// set datatype OCTET_STRING and write default value as a sequence of bytes, little endian, like "56 34 12"
UInt64 value;
try
{
value = signed ? (UInt64)((Int64)new System.ComponentModel.Int64Converter().ConvertFromString(od.defaultvalue))
: (UInt64) new System.ComponentModel.UInt64Converter().ConvertFromString(od.defaultvalue);
}
catch (Exception)
{
value = 0;
}
List<string> bytes = new List<string>();
for (UInt32 i = 0; i < byteLength; i++)
{
bytes.Add(String.Format("{0:X2}", value & 0xFF));
value >>= 8;
}
od.datatype = DataType.OCTET_STRING;
od.defaultvalue = string.Join(" ", bytes);
return Items1ChoiceType.BITSTRING;
}
private DataType ConvertDataType(Items1ChoiceType choiceType, string defaultValue)
{
switch (choiceType)
{
case Items1ChoiceType.BOOL: return DataType.BOOLEAN;
case Items1ChoiceType.CHAR:
case Items1ChoiceType.SINT: return DataType.INTEGER8;
case Items1ChoiceType.INT: return DataType.INTEGER16;
case Items1ChoiceType.DINT: return DataType.INTEGER32;
case Items1ChoiceType.LINT: return DataType.INTEGER64;
case Items1ChoiceType.BYTE:
case Items1ChoiceType.USINT: return DataType.UNSIGNED8;
case Items1ChoiceType.WORD:
case Items1ChoiceType.UINT: return DataType.UNSIGNED16;
case Items1ChoiceType.DWORD:
case Items1ChoiceType.UDINT: return DataType.UNSIGNED32;
case Items1ChoiceType.LWORD:
case Items1ChoiceType.ULINT: return DataType.UNSIGNED64;
case Items1ChoiceType.REAL: return DataType.REAL32;
case Items1ChoiceType.LREAL: return DataType.REAL64;
case Items1ChoiceType.STRING: return DataType.VISIBLE_STRING;
case Items1ChoiceType.WSTRING: return DataType.UNICODE_STRING;
case Items1ChoiceType.BITSTRING:
return defaultValue == "" ? DataType.DOMAIN : DataType.OCTET_STRING;
default:
return DataType.INTEGER32;
}
}
private Items1ChoiceType ConvertDataType(OdSubObject subEntry)
{
UInt32 byteLength;
bool signed = false;
var dt = subEntry.DataType;
switch (dt)
{
case LibCanOpen.OdSubObject.Types.DataType.Boolean: return Items1ChoiceType.BOOL;
case LibCanOpen.OdSubObject.Types.DataType.Integer8: return Items1ChoiceType.SINT;
case LibCanOpen.OdSubObject.Types.DataType.Integer16: return Items1ChoiceType.INT;
case LibCanOpen.OdSubObject.Types.DataType.Integer32: return Items1ChoiceType.DINT;
case LibCanOpen.OdSubObject.Types.DataType.Integer64: return Items1ChoiceType.LINT;
case LibCanOpen.OdSubObject.Types.DataType.Unsigned8: return Items1ChoiceType.USINT;
case LibCanOpen.OdSubObject.Types.DataType.Unsigned16: return Items1ChoiceType.UINT;
case LibCanOpen.OdSubObject.Types.DataType.Unsigned32: return Items1ChoiceType.UDINT;
case LibCanOpen.OdSubObject.Types.DataType.Unsigned64: return Items1ChoiceType.ULINT;
case LibCanOpen.OdSubObject.Types.DataType.Real32: return Items1ChoiceType.REAL;
case LibCanOpen.OdSubObject.Types.DataType.Real64: return Items1ChoiceType.LREAL;
case LibCanOpen.OdSubObject.Types.DataType.VisibleString: return Items1ChoiceType.STRING;
case LibCanOpen.OdSubObject.Types.DataType.OctetString: return Items1ChoiceType.BITSTRING;
case LibCanOpen.OdSubObject.Types.DataType.UnicodeString: return Items1ChoiceType.WSTRING;
case LibCanOpen.OdSubObject.Types.DataType.Domain:
subEntry.DefaultValue = "";
return Items1ChoiceType.BITSTRING;
default:
subEntry.DataType = LibCanOpen.OdSubObject.Types.DataType.Integer32;
return Items1ChoiceType.DINT;
// transform other non standard values to OCTET_STRING
case LibCanOpen.OdSubObject.Types.DataType.Integer24: byteLength = 3; signed = true; break;
case LibCanOpen.OdSubObject.Types.DataType.Integer40: byteLength = 5; signed = true; break;
case LibCanOpen.OdSubObject.Types.DataType.Integer48: byteLength = 6; signed = true; break;
case LibCanOpen.OdSubObject.Types.DataType.Integer56: byteLength = 7; signed = true; break;
case LibCanOpen.OdSubObject.Types.DataType.Unsigned24: byteLength = 3; break;
case LibCanOpen.OdSubObject.Types.DataType.Unsigned40: byteLength = 5; break;
case LibCanOpen.OdSubObject.Types.DataType.Unsigned48:
case LibCanOpen.OdSubObject.Types.DataType.TimeOfDay:
case LibCanOpen.OdSubObject.Types.DataType.TimeDifference: byteLength = 6; break;
case LibCanOpen.OdSubObject.Types.DataType.Unsigned56: byteLength = 7; break;
}
// set datatype OCTET_STRING and write default value as a sequence of bytes, little endian, like "56 34 12"
UInt64 value;
try
{
value = signed ? (UInt64)((Int64)new System.ComponentModel.Int64Converter().ConvertFromString(subEntry.DefaultValue))
: (UInt64)new System.ComponentModel.UInt64Converter().ConvertFromString(subEntry.DefaultValue);
}
catch (Exception)
{
value = 0;
}
List<string> bytes = new List<string>();
for (UInt32 i = 0; i < byteLength; i++)
{
bytes.Add(String.Format("{0:X2}", value & 0xFF));
value >>= 8;
}
subEntry.DataType = LibCanOpen.OdSubObject.Types.DataType.OctetString;
subEntry.DefaultValue = string.Join(" ", bytes);
return Items1ChoiceType.BITSTRING;
}
private void ConvertDataType(Items1ChoiceType choiceType, OdSubObject OdSubObject)
{
switch (choiceType)
{
case Items1ChoiceType.BOOL:
OdSubObject.DataType = LibCanOpen.OdSubObject.Types.DataType.Boolean;
break;
case Items1ChoiceType.CHAR:
case Items1ChoiceType.SINT:
OdSubObject.DataType = LibCanOpen.OdSubObject.Types.DataType.Integer8;
break;
case Items1ChoiceType.INT:
OdSubObject.DataType = LibCanOpen.OdSubObject.Types.DataType.Integer16;
break;
case Items1ChoiceType.DINT:
OdSubObject.DataType = LibCanOpen.OdSubObject.Types.DataType.Integer32;
break;
case Items1ChoiceType.LINT:
OdSubObject.DataType = LibCanOpen.OdSubObject.Types.DataType.Integer64;
break;
case Items1ChoiceType.BYTE:
case Items1ChoiceType.USINT:
OdSubObject.DataType = LibCanOpen.OdSubObject.Types.DataType.Unsigned8;
break;
case Items1ChoiceType.WORD:
case Items1ChoiceType.UINT:
OdSubObject.DataType = LibCanOpen.OdSubObject.Types.DataType.Unsigned16;
break;
case Items1ChoiceType.DWORD:
case Items1ChoiceType.UDINT:
OdSubObject.DataType = LibCanOpen.OdSubObject.Types.DataType.Unsigned32;
break;
case Items1ChoiceType.LWORD:
case Items1ChoiceType.ULINT:
OdSubObject.DataType = LibCanOpen.OdSubObject.Types.DataType.Unsigned64;
break;
case Items1ChoiceType.REAL:
OdSubObject.DataType = LibCanOpen.OdSubObject.Types.DataType.Real32;
break;
case Items1ChoiceType.LREAL:
OdSubObject.DataType = LibCanOpen.OdSubObject.Types.DataType.Real64;
break;
case Items1ChoiceType.STRING:
OdSubObject.DataType = LibCanOpen.OdSubObject.Types.DataType.VisibleString;
break;
case Items1ChoiceType.WSTRING:
OdSubObject.DataType = LibCanOpen.OdSubObject.Types.DataType.UnicodeString;
break;
case Items1ChoiceType.BITSTRING:
OdSubObject.DataType = OdSubObject.DefaultValue == "" ? LibCanOpen.OdSubObject.Types.DataType.Domain : LibCanOpen.OdSubObject.Types.DataType.OctetString;
break;
default:
OdSubObject.DataType = LibCanOpen.OdSubObject.Types.DataType.Integer32;
break;
}
}
private void WriteVar(parameter devPar, ODentry od)
{
if (od.accesstype == EDSsharp.AccessType.UNKNOWN && od.parent != null && od.parent.objecttype == ObjectType.ARRAY)
od.accesstype = od.parent.accesstype;
devPar.access = ConvertAccessType(od.accesstype);
devPar.Items1 = new object[] { new object() };
devPar.Items1ElementName = new Items1ChoiceType[] { ConvertDataType(od) };
if (od.defaultvalue != null && od.defaultvalue != "")
devPar.defaultValue = new defaultValue { value = od.defaultvalue };
if (od.LowLimit != null && od.LowLimit != "" && od.HighLimit != null && od.HighLimit != "")
{
devPar.allowedValues = new allowedValues
{
range = new range[]
{
new range
{
minValue = new rangeMinValue { value = od.LowLimit },
maxValue = new rangeMaxValue { value = od.HighLimit }
}
}
};
}
}
private void WriteVar(parameter devPar, OdSubObject subEntry)
{
devPar.access = ConvertAccessType(subEntry);
devPar.Items1 = new object[] { new object() };
devPar.Items1ElementName = new Items1ChoiceType[] { ConvertDataType(subEntry) };
if (subEntry.DefaultValue != null && subEntry.DefaultValue != "")
devPar.defaultValue = new defaultValue { value = subEntry.DefaultValue };
if (subEntry.LowLimit != null && subEntry.LowLimit != "" && subEntry.HighLimit != null && subEntry.HighLimit != "")
{
devPar.allowedValues = new allowedValues
{
range = new range[]
{
new range
{
minValue = new rangeMinValue { value = subEntry.LowLimit },
maxValue = new rangeMaxValue { value = subEntry.HighLimit }
}
}
};
}
}
private void ConvertXddProperties(property[] properties, OdObject entry, OdSubObject subEntry)
{
if (properties != null)
{
foreach (property prop in properties)
{
switch (prop.name)
{
case "CO_disabled": entry.Disabled = prop.value == "true"; break;
case "CO_countLabel": entry.CountLabel = prop.value ?? ""; break;
case "CO_storageGroup": entry.StorageGroup = prop.value ?? ""; break;
case "CO_flagsPDO": entry.FlagsPDO = prop.value == "true"; break;
case "CO_accessSRDO":
if (prop.value != null)
switch (prop.value)
{
case "rx": subEntry.Srdo = LibCanOpen.OdSubObject.Types.AccessSRDO.Rx; break;
case "tx": subEntry.Srdo = LibCanOpen.OdSubObject.Types.AccessSRDO.Tx; break;
case "trx": subEntry.Srdo = LibCanOpen.OdSubObject.Types.AccessSRDO.Trx; break;
case "no": subEntry.Srdo = LibCanOpen.OdSubObject.Types.AccessSRDO.No; break;
}
break;
case "CO_stringLengthMin":
try { subEntry.StringLengthMin = System.Convert.ToUInt16(prop.value); }
catch (Exception) { subEntry.StringLengthMin = 0; }
break;
}
}
}
}
private property[] ConvertXddProperties(OdObject entry)
{
var props = new List<property>();
if (entry.Disabled)
props.Add(new property { name = "CO_disabled", value = "true" });
if (entry.CountLabel != "")
props.Add(new property { name = "CO_countLabel", value = entry.CountLabel });
if (entry.StorageGroup != "RAM" && entry.StorageGroup != "")
props.Add(new property { name = "CO_storageGroup", value = entry.StorageGroup });
if (entry.FlagsPDO)
props.Add(new property { name = "CO_flagsPDO", value = "true" });
return props.ToArray();
}
private property[] ConvertXddProperties(OdSubObject subEntry)
{
var props = new List<property>();
string val;
switch (subEntry.Srdo)
{
case LibCanOpen.OdSubObject.Types.AccessSRDO.Rx: val = "rx"; break;
case LibCanOpen.OdSubObject.Types.AccessSRDO.Tx: val = "tx"; break;
case LibCanOpen.OdSubObject.Types.AccessSRDO.Trx: val = "trx"; break;
default: val = "no"; break;
}
props.Add(new property { name = "CO_accessSRDO", value = val });
if (subEntry.StringLengthMin != 0)
props.Add(new property { name = "CO_stringLengthMin", value = subEntry.StringLengthMin.ToString() });
return props.ToArray();
}
private ISO15745ProfileContainer Convert(EDSsharp eds, string fileName, bool deviceCommissioning, bool stripped)
{
// Get xdd template from eds (if memorized on xdd file open)
ISO15745ProfileContainer container = eds.xddTemplate;
ProfileBody_Device_CANopen body_device = null;
ProfileBody_CommunicationNetwork_CANopen body_network = null;
List<string> mappingErrors = eds.VerifyPDOMapping();
if (mappingErrors.Count > 0)
Warnings.AddWarning($"Errors in PDO mappings:\r\n " + string.Join("\r\n ", mappingErrors), Warnings.warning_class.WARNING_BUILD);
eds.fi.ModificationDateTime = DateTime.Now;
#region base_elements
// create required xml objects, where necessay
if (container == null)
container = new ISO15745ProfileContainer();
if (container.ISO15745Profile == null
|| container.ISO15745Profile.Length < 2
|| container.ISO15745Profile[0] == null
|| container.ISO15745Profile[1] == null)
{
container.ISO15745Profile = new ISO15745Profile[]
{
new ISO15745Profile(),
new ISO15745Profile(),
};
}
// get headers and bodies
if (container.ISO15745Profile[0].ProfileHeader != null
&& container.ISO15745Profile[0].ProfileBody != null
&& container.ISO15745Profile[1].ProfileHeader != null
&& container.ISO15745Profile[1].ProfileBody != null)
{
foreach (ISO15745Profile item in container.ISO15745Profile)
{
if (item.ProfileBody.GetType() == typeof(ProfileBody_Device_CANopen))
body_device = (ProfileBody_Device_CANopen)item.ProfileBody;
else if (item.ProfileBody.GetType() == typeof(ProfileBody_CommunicationNetwork_CANopen))
body_network = (ProfileBody_CommunicationNetwork_CANopen)item.ProfileBody;
}
}
if (body_network == null || body_device == null)
{
container.ISO15745Profile[0].ProfileHeader = new ProfileHeader_DataType
{
ProfileIdentification = "CANopen device profile",
ProfileRevision = "1.1",
ProfileName = "",
ProfileSource = "",
ProfileClassID = ProfileClassID_DataType.Device,
ISO15745Reference = new ISO15745Reference_DataType
{
ISO15745Part = "1",
ISO15745Edition = "1",
ProfileTechnology = "CANopen"
}
};
container.ISO15745Profile[0].ProfileBody = new ProfileBody_Device_CANopen();
body_device = (ProfileBody_Device_CANopen)container.ISO15745Profile[0].ProfileBody;
container.ISO15745Profile[1].ProfileHeader = new ProfileHeader_DataType
{
ProfileIdentification = "CANopen communication network profile",
ProfileRevision = "1.1",
ProfileName = "",
ProfileSource = "",
ProfileClassID = ProfileClassID_DataType.CommunicationNetwork,
ISO15745Reference = new ISO15745Reference_DataType
{
ISO15745Part = "1",
ISO15745Edition = "1",
ProfileTechnology = "CANopen"
}
};
container.ISO15745Profile[1].ProfileBody = new ProfileBody_CommunicationNetwork_CANopen();
body_network = (ProfileBody_CommunicationNetwork_CANopen)container.ISO15745Profile[1].ProfileBody;
}
#endregion
#region ObjectDictionary
var body_network_objectList = new List<CANopenObjectListCANopenObject>();
var body_device_parameterList = new List<parameter>();
var body_device_arrayList = new List<array>();
var body_device_structList = new List<@struct>();
foreach (ODentry od in eds.ods.Values)
{
if (stripped && od.prop.CO_disabled == true)
continue;
string uid = string.Format("{0:X4}", od.Index);
var netObj = new CANopenObjectListCANopenObject
{
index = new byte[] { (byte)(od.Index >> 8), (byte)(od.Index & 0xFF) },
name = od.parameter_name,
objectType = (byte)od.objecttype,
uniqueIDRef = "UID_OBJ_" + uid
};
body_network_objectList.Add(netObj);
var devPar = new parameter { uniqueID = "UID_OBJ_" + uid };
if (od.Description != null && od.Description != "")
{
devPar.Items = new object[] { new vendorTextDescription { lang = "en", Value = od.Description } };
}
else
{
// Add at least label made from parameter name, because g_labels is required by schema
devPar.Items = new object[] { new vendorTextLabel { lang = "en", Value = od.parameter_name } };
}
if (deviceCommissioning && od.denotation != null && od.denotation != "")
{
devPar.denotation = new denotation
{
Items = new object[] { new vendorTextLabel { lang = "en", Value = od.denotation } }
};
}
body_device_parameterList.Add(devPar);
if (od.objecttype == ObjectType.VAR)
{
try { netObj.PDOmapping = (CANopenObjectListCANopenObjectPDOmapping)System.Enum.Parse(typeof(CANopenObjectListCANopenObjectPDOmapping), od.PDOtype.ToString()); }
catch (Exception) { netObj.PDOmapping = CANopenObjectListCANopenObjectPDOmapping.no; }
netObj.PDOmappingSpecified = true;
if (!stripped)
{
var propOd = od.prop.OdeXdd();
var propSub = od.prop.SubOdeXdd();
devPar.property = new property[propOd.Length + propSub.Length];
propOd.CopyTo(devPar.property, 0);
propSub.CopyTo(devPar.property, propOd.Length);
}
WriteVar(devPar, od);
if (deviceCommissioning && od.actualvalue != null && od.actualvalue != "")
devPar.actualValue = new actualValue { value = od.actualvalue };
}
else if ((od.objecttype == ObjectType.ARRAY || od.objecttype == ObjectType.RECORD) && od.subobjects != null && od.subobjects.Count > 0)
{
netObj.subNumber = (byte)od.subobjects.Count;
netObj.subNumberSpecified = true;
if (!stripped)
devPar.property = od.prop.OdeXdd();
var netSubObjList = new List<CANopenObjectListCANopenObjectCANopenSubObject>();
var devStructSubList = new List<varDeclaration>();
foreach (KeyValuePair<UInt16, ODentry> kvp in od.subobjects)
{
ODentry subod = kvp.Value;
UInt16 subindex = kvp.Key;
string subUid = string.Format("{0:X4}{1:X2}", od.Index, subindex);
var netSubObj = new CANopenObjectListCANopenObjectCANopenSubObject
{
subIndex = new byte[] { (byte)(subindex & 0xFF) },
name = subod.parameter_name,
objectType = (byte)ObjectType.VAR,
PDOmappingSpecified = true,
uniqueIDRef = "UID_SUB_" + subUid
};
try { netSubObj.PDOmapping = (CANopenObjectListCANopenObjectCANopenSubObjectPDOmapping)System.Enum.Parse(typeof(CANopenObjectListCANopenObjectCANopenSubObjectPDOmapping), subod.PDOtype.ToString()); }
catch (Exception) { netSubObj.PDOmapping = CANopenObjectListCANopenObjectCANopenSubObjectPDOmapping.no; }
var devSubPar = new parameter {
uniqueID = "UID_SUB_" + subUid
};
if (subod.Description != null && subod.Description != "")
{
devSubPar.Items = new object[] { new vendorTextDescription { lang = "en", Value = subod.Description } };
}
else
{
// Add at least label made from parameter name, because g_labels is required by schema
devSubPar.Items = new object[] { new vendorTextLabel { lang = "en", Value = subod.parameter_name } };
}
if (!stripped)
devSubPar.property = subod.prop.SubOdeXdd();
if (deviceCommissioning && subod.denotation != null && subod.denotation != "")
{
devPar.denotation = new denotation
{
Items = new object[] { new vendorTextLabel { lang = "en", Value = subod.denotation } }
};
}
WriteVar(devSubPar, subod);
if (deviceCommissioning && subod.actualvalue != null && subod.actualvalue != "")
devPar.actualValue = new actualValue { value = subod.actualvalue };
if (od.objecttype == ObjectType.RECORD)
{
devStructSubList.Add(new varDeclaration
{
name = subod.parameter_name,
uniqueID = "UID_RECSUB_" + subUid,
Item = new object(),
ItemElementName = (ItemChoiceType1)ConvertDataType(subod)
});
}
body_device_parameterList.Add(devSubPar);
netSubObjList.Add(netSubObj);
}
// add refference to data type definition and definition of array or struct data type (schema requirement)
if (od.objecttype == ObjectType.ARRAY)
{
devPar.Items1 = new object[] { new dataTypeIDRef { uniqueIDRef = "UID_ARR_" + uid } };
devPar.Items1ElementName = new Items1ChoiceType[] { Items1ChoiceType.dataTypeIDRef };
body_device_arrayList.Add(new array
{
uniqueID = "UID_ARR_" + uid,
name = od.parameter_name,
Item = new object(),
ItemElementName = (ItemChoiceType)ConvertDataType(od),
subrange = new subrange[] { new subrange { lowerLimit = 0, upperLimit = od.subobjects.Count - 1 } }
});
}
else
{
devPar.Items1 = new object[] { new dataTypeIDRef { uniqueIDRef = "UID_REC_" + uid } };
devPar.Items1ElementName = new Items1ChoiceType[] { Items1ChoiceType.dataTypeIDRef };
body_device_structList.Add(new @struct
{
uniqueID = "UID_REC_" + uid,
name = od.parameter_name,
varDeclaration = devStructSubList.ToArray()
});
}
netObj.CANopenSubObject = netSubObjList.ToArray();
}
}
#endregion
#region body_device
body_device.fileName = fileName;
body_device.fileCreator = eds.fi.CreatedBy;
body_device.fileCreationDate = eds.fi.CreationDateTime;
body_device.fileCreationTime = eds.fi.CreationDateTime;
body_device.fileCreationTimeSpecified = true;
body_device.fileVersion = eds.fi.FileVersion;
body_device.fileModifiedBy = eds.fi.ModifiedBy;
body_device.fileModificationDate = eds.fi.ModificationDateTime;
body_device.fileModificationTime = eds.fi.ModificationDateTime;
body_device.fileModificationDateSpecified = true;
body_device.fileModificationTimeSpecified = true;
body_device.supportedLanguages = "en";
// Device identity
if (body_device.DeviceIdentity == null)
body_device.DeviceIdentity = new DeviceIdentity();
body_device.DeviceIdentity.vendorName = new vendorName { Value = eds.di.VendorName };
body_device.DeviceIdentity.vendorID = new vendorID { Value = eds.di.VendorNumber };
body_device.DeviceIdentity.productName = new productName { Value = eds.di.ProductName };
body_device.DeviceIdentity.productID = new productID { Value = eds.di.ProductNumber };
if (eds.fi.Description != null && eds.fi.Description != "")
{
body_device.DeviceIdentity.productText = new productText
{
Items = new object[]
{
new vendorTextDescription { lang = "en", Value = eds.fi.Description }
}
};
}
// version is optional element, make a template if empty
if (body_device.DeviceIdentity.version == null)
{
body_device.DeviceIdentity.version = new version[]
{
new version { versionType = versionVersionType.SW, Value = "0" },
new version { versionType = versionVersionType.FW, Value = "0" },
new version { versionType = versionVersionType.HW, Value = "0" }
};
}
// DeviceFunction is required by schema, make a template if empty.
if (body_device.DeviceFunction == null)
{
// This is just a template for somehow complex xml structure. Users can edit the
// xdd file directly to write characteristics of own devices or use generic xml
// editing tool. External editing will be preserved anyway, if xdd file will be
// later opened and saved back in EDSEditor.
// EDSEditor curerently does not have interface for editing the characteristics.
body_device.DeviceFunction = new DeviceFunction[]
{
new DeviceFunction
{