forked from robincornelius/libedssharp
-
Notifications
You must be signed in to change notification settings - Fork 93
Expand file tree
/
Copy pathCanOpenEDS.cs
More file actions
1447 lines (1217 loc) · 54.1 KB
/
CanOpenEDS.cs
File metadata and controls
1447 lines (1217 loc) · 54.1 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 - 2019 Robin Cornelius <robin.cornelius@gmail.com>
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Text.RegularExpressions;
namespace libEDSsharp
{
public partial class InfoSection
{
public virtual void Parse(Dictionary<string, string> section, string sectionname)
{
this.section = section;
FieldInfo[] fields = this.GetType().GetFields();
foreach (FieldInfo f in fields)
{
if (Attribute.IsDefined(f, typeof(EdsExport)))
GetField(f.Name, f.Name);
if (Attribute.IsDefined(f, typeof(DcfExport)))
GetField(f.Name, f.Name);
}
}
/// <summary>
/// Write object to stream
/// </summary>
/// <param name="writer">stream to write the data to</param>
/// <param name="ft">file type</param>
public void Write(StreamWriter writer, Filetype ft)
{
writer.WriteLine("[" + edssection + "]");
Type tx = this.GetType();
FieldInfo[] fields = this.GetType().GetFields();
foreach (FieldInfo f in fields)
{
if ((ft == Filetype.File_EDS) && (!Attribute.IsDefined(f, typeof(EdsExport))))
continue;
if ((ft == Filetype.File_DCF) && (!(Attribute.IsDefined(f, typeof(DcfExport)) || Attribute.IsDefined(f, typeof(EdsExport)))))
continue;
if (f.GetValue(this) == null)
continue;
EdsExport ex = (EdsExport)f.GetCustomAttribute(typeof(EdsExport));
bool comment = ex.IsReadOnly();
if (f.FieldType.Name == "Boolean")
{
writer.WriteLine(string.Format("{2}{0}={1}", f.Name, ((bool)f.GetValue(this)) == true ? 1 : 0, comment == true ? ";" : ""));
}
else if (f.FieldType.Name == "UInt32")
{
writer.WriteLine(string.Format("{2}{0}={1}", f.Name, string.Format("0x{0:x8}", f.GetValue(this)), comment == true ? ";" : ""));
}
else
{
writer.WriteLine(string.Format("{2}{0}={1}", f.Name, f.GetValue(this).ToString(), comment == true ? ";" : ""));
}
}
writer.WriteLine("");
}
}
public partial class MandatoryObjects : SupportedObjects
{
public MandatoryObjects(Dictionary<string, string> section)
: this()
{
Parse(section);
}
}
public partial class OptionalObjects : SupportedObjects
{
public OptionalObjects(Dictionary<string, string> section)
: this()
{
Parse(section);
}
}
public partial class ManufacturerObjects : SupportedObjects
{
public ManufacturerObjects(Dictionary<string, string> section)
: this()
{
Parse(section);
}
}
public partial class TypeDefinitions : SupportedObjects
{
public TypeDefinitions(Dictionary<string, string> section)
{
Parse(section);
}
}
public partial class SupportedObjects
{
public virtual void Parse(Dictionary<string, string> section)
{
objectlist = new Dictionary<int, int>();
foreach (KeyValuePair<string, string> kvp in section)
{
if (kvp.Key.ToLower() == "supportedobjects")
continue;
if (kvp.Key.ToLower() == "nrofentries")
continue;
int count = Convert.ToInt16(kvp.Key, EDSsharp.Getbase(kvp.Key));
int target = Convert.ToInt16(kvp.Value, EDSsharp.Getbase(kvp.Value));
objectlist.Add(count, target);
}
}
/// <summary>
/// Write object to stream
/// </summary>
/// <param name="writer">stream to write the data to</param>
public void Write(StreamWriter writer)
{
writer.WriteLine("[" + edssection + "]");
writer.WriteLine(string.Format("{0}={1}", countmsg, objectlist.Count));
foreach (KeyValuePair<int, int> kvp in objectlist)
{
writer.WriteLine(string.Format("{0}=0x{1:X4}", kvp.Key, kvp.Value));
}
writer.WriteLine("");
}
}
public partial class Comments
{
public Comments(Dictionary<string, string> section)
{
Parse(section);
}
public virtual void Parse(Dictionary<string, string> section)
{
comments = new List<string>();
foreach (KeyValuePair<string, string> kvp in section)
{
if (kvp.Key == "Lines")
continue;
comments.Add(kvp.Value);
}
}
/// <summary>
/// Write object to stream
/// </summary>
/// <param name="writer">stream to write the data to</param>
public void Write(StreamWriter writer)
{
if (comments == null)
{
comments = new List<string>();
}
writer.WriteLine("[" + edssection + "]");
writer.WriteLine(string.Format("Lines={0}", comments.Count));
int count = 1;
foreach (string s in comments)
{
writer.WriteLine(string.Format("Line{0}={1}", count, s));
count++;
}
writer.WriteLine("");
}
}
public partial class Dummyusage : InfoSection
{
public Dummyusage(Dictionary<string, string> section) : this()
{
Parse(section, edssection);
}
}
/// <summary>
/// FileInfo section as described in CiA 306
/// </summary>
public partial class FileInfo : InfoSection
{
public FileInfo(Dictionary<string, string> section) : this()
{
Parse(section, edssection);
}
override public void Parse(Dictionary<string, string> section, string sectionname)
{
base.Parse(section, edssection);
string dtcombined = "";
try
{
if (section.ContainsKey("CreationTime") && section.ContainsKey("CreationDate"))
{
dtcombined = section["CreationTime"].Replace(" ", "") + " " + section["CreationDate"];
CreationDateTime = DateTime.ParseExact(dtcombined, "h:mmtt MM-dd-yyyy", CultureInfo.InvariantCulture);
}
}
catch (Exception e)
{
if (e is System.FormatException)
{
Warnings.warning_list.Add(String.Format("EDS Error: Section [{1}] Unable to parse DateTime {0} for CreationTime, not in DS306 format", dtcombined, sectionname));
}
}
try
{
if (section.ContainsKey("ModificationTime") && section.ContainsKey("ModificationTime"))
{
dtcombined = section["ModificationTime"].Replace(" ", "") + " " + section["ModificationDate"];
ModificationDateTime = DateTime.ParseExact(dtcombined, "h:mmtt MM-dd-yyyy", CultureInfo.InvariantCulture);
}
}
catch (Exception e)
{
if (e is System.FormatException)
{
Warnings.warning_list.Add(String.Format("EDS Error: Section [{1}] Unable to parse DateTime {0} for ModificationTime, not in DS306 format", dtcombined, sectionname));
}
}
try
{
if (section.ContainsKey("EDSVersion"))
{
string[] bits = section["EDSVersion"].Split('.');
if (bits.Length >= 1)
EDSVersionMajor = Convert.ToByte(bits[0]);
if (bits.Length >= 2)
EDSVersionMinor = Convert.ToByte(bits[1]);
//EDSVersion = String.Format("{0}.{1}", EDSVersionMajor, EDSVersionMinor);
}
}
catch
{
Warnings.warning_list.Add(String.Format("Unable to parse EDS version {0}", section["EDSVersion"]));
}
}
}
public partial class DeviceInfo : InfoSection
{
public DeviceInfo(Dictionary<string, string> section) : this()
{
Parse(section, edssection);
}
}
public partial class DeviceCommissioning : InfoSection
{
public DeviceCommissioning(Dictionary<string, string> section) : this()
{
Parse(section, edssection);
}
}
public partial class SupportedModules : InfoSection
{
public SupportedModules(Dictionary<string, string> section) : this()
{
Parse(section, edssection);
}
}
public partial class ConnectedModules : SupportedObjects
{
public ConnectedModules(Dictionary<string, string> section) : this()
{
Parse(section);
foreach (KeyValuePair<int, int> kvp in this.objectlist)
{
UInt16 K = (UInt16)kvp.Value;
UInt16 V = (UInt16)kvp.Key;
connectedmodulelist.Add(K, V);
}
}
}
public partial class MxFixedObjects : SupportedObjects
{
public MxFixedObjects(Dictionary<string, string> section, UInt16 modindex) : this(modindex)
{
Parse(section);
foreach (KeyValuePair<int, int> kvp in this.objectlist)
{
connectedmodulelist.Add((UInt16)kvp.Value, (UInt16)kvp.Key);
}
}
}
public partial class ModuleInfo : InfoSection
{
public ModuleInfo(Dictionary<string, string> section, UInt16 moduleindex) : this(moduleindex)
{
Parse(section, edssection);
}
}
public partial class ModuleComments : Comments
{
public ModuleComments(Dictionary<string, string> section, UInt16 moduleindex) : this(moduleindex)
{
Parse(section);
}
}
public partial class ModuleSubExtends : SupportedObjects
{
public ModuleSubExtends(Dictionary<string, string> section, UInt16 moduleindex)
: this(moduleindex)
{
Parse(section);
}
}
public partial class ODentry
{
/// <summary>
/// Write out this Object dictionary entry to an EDS/DCF file using correct formatting
/// </summary>
/// <param name="writer">Handle to the stream writer to write to</param>
/// <param name="ft">File type being written</param>
/// <param name="odt">OD type to write</param>
/// <param name="module">module</param>
public void Write(StreamWriter writer, InfoSection.Filetype ft, Odtype odt = Odtype.NORMAL, int module = 0)
{
string fixedmodheader = "";
if (odt == Odtype.FIXED)
{
fixedmodheader = string.Format("M{0}Fixed", module);
}
if (odt == Odtype.SUBEXT)
{
fixedmodheader = string.Format("M{0}SubExt", module);
}
if (parent != null)
{
writer.WriteLine(string.Format("[{0}{1:X}sub{2:X}]", fixedmodheader, Index, Subindex));
}
else
{
writer.WriteLine(string.Format("[{0}{1:X}]", fixedmodheader, Index));
}
writer.WriteLine(string.Format("ParameterName={0}", parameter_name));
if (ft == InfoSection.Filetype.File_DCF)
{
writer.WriteLine(string.Format("Denotation={0}", denotation));
}
writer.WriteLine(string.Format("ObjectType=0x{0:X}", (int)objecttype));
writer.WriteLine(string.Format(";StorageLocation={0}", prop.CO_storageGroup));
if (objecttype == ObjectType.ARRAY)
{
writer.WriteLine(string.Format("SubNumber=0x{0:X}", Nosubindexes));
}
if (objecttype == ObjectType.RECORD)
{
writer.WriteLine(string.Format("SubNumber=0x{0:X}", Nosubindexes));
}
if (objecttype == ObjectType.VAR)
{
DataType dt = datatype;
if (dt == DataType.UNKNOWN && this.parent != null)
dt = parent.datatype;
writer.WriteLine(string.Format("DataType=0x{0:X4}", (int)dt));
writer.WriteLine(string.Format("AccessType={0}", accesstype.ToString()));
if (HighLimit != null && HighLimit != "")
{
writer.WriteLine(string.Format("HighLimit={0}", Formatoctetstring(HighLimit)));
}
if (LowLimit != null && LowLimit != "")
{
writer.WriteLine(string.Format("LowLimit={0}", Formatoctetstring(LowLimit)));
}
writer.WriteLine(string.Format("DefaultValue={0}", Formatoctetstring(defaultvalue)));
//TODO If the ObjectType is domain (0x2) the value of the object may be stored in a file,UploadFile and DownloadFile
if (ft == InfoSection.Filetype.File_DCF)
{
writer.WriteLine(string.Format("ParameterValue={0}", Formatoctetstring(actualvalue)));
}
writer.WriteLine(string.Format("PDOMapping={0}", PDOMapping == true ? 1 : 0));
if (prop.CO_flagsPDO == true)
{
writer.WriteLine(";TPDODetectCos=1");
}
}
//Count is for modules in the [MxSubExtxxxx]
//Should we export this on EDS only, or DCF or both?
if (odt == Odtype.SUBEXT)
{
writer.WriteLine(string.Format("Count={0}", count));
writer.WriteLine(string.Format("ObjExtend={0}", ObjExtend));
}
//ObjectFlags is always optional (Page 15, DSP306) and used for DCF writing to nodes
//also recommended not to write if it is already 0
if (ObjFlags != 0)
{
writer.WriteLine(string.Format("ObjFlags={0}", ObjFlags));
}
writer.WriteLine("");
}
}
public partial class EDSsharp
{
public void Parseline(string linex, int no)
{
string key = "";
string value = "";
string line = linex.TrimStart(';');
bool custom_extension = false;
if (linex == null || linex == "")
return;
if (linex[0] == ';')
custom_extension = true;
//extract sections
{
string pat = @"^\[([a-z0-9]+)\]";
Regex r = new Regex(pat, RegexOptions.IgnoreCase);
Match m = r.Match(line);
if (m.Success)
{
Group g = m.Groups[1];
sectionname = g.ToString();
if (!eds.ContainsKey(sectionname))
{
eds.Add(sectionname, new Dictionary<string, string>());
}
else
{
Warnings.warning_list.Add(string.Format("EDS Error on Line {0} : Duplicate section [{1}] ", no, sectionname));
}
}
}
//extract keyvalues
{
//Bug #70 Eat whitespace!
string pat = @"^([a-z0-9_]+)[ ]*=[ ]*(.*)";
Regex r = new Regex(pat, RegexOptions.IgnoreCase);
Match m = r.Match(line);
if (m.Success)
{
key = m.Groups[1].ToString();
value = m.Groups[2].ToString();
value = value.TrimEnd(' ', '\t', '\n', '\r');
//not sure how we actually get here with out a section being in the dictionary already..
//suspect this is dead code.
if (!eds.ContainsKey(sectionname))
{
eds.Add(sectionname, new Dictionary<string, string>());
}
if (custom_extension == false)
{
try
{
eds[sectionname].Add(key, value);
}
catch (Exception)
{
Warnings.warning_list.Add(string.Format("EDS Error on Line {3} : Duplicate key \"{0}\" value \"{1}\" in section [{2}]", key, value, sectionname, no));
}
}
else
//Only allow our own extensions to populate the key/value pair
{
if (key == "StorageLocation" || key == "TPDODetectCos")
{
try
{
eds[sectionname].Add(key, value);
}
catch (Exception)
{
Warnings.warning_list.Add(string.Format("EDS Error on Line {3} : Duplicate custom key \"{0}\" value \"{1}\" in section [{2}]", key, value, sectionname, no));
}
}
}
}
}
}
public void ParseEDSentry(KeyValuePair<string, Dictionary<string, string>> kvp)
{
string section = kvp.Key;
string pat = @"^(M[0-9a-fA-F]+(Fixed|SubExt))?([a-fA-F0-9]+)(sub)?([0-9a-fA-F]*)$";
Regex r = new Regex(pat);
Match m = r.Match(section);
if (m.Success)
{
SortedDictionary<UInt16, ODentry> target = this.ods;
//** MODULE DCF SUPPORT
string pat2 = @"^M([0-9a-fA-F]+)(Fixed|SubExt)([0-9a-fA-F]+)";
Regex r2 = new Regex(pat2, RegexOptions.IgnoreCase);
Match m2 = r2.Match(m.Groups[0].ToString());
if (m2.Success)
{
UInt16 modindex = 0, odindex = 0;
try { modindex = Convert.ToUInt16(m2.Groups[1].Value); }
catch (Exception) { Console.WriteLine("** ALL GONE WRONG **" + m2.Groups[1].Value); }
//Indexes in the EDS are always in hex format without the pre 0x
try { odindex = Convert.ToUInt16(m2.Groups[3].Value, 16); }
catch (Exception) { Console.WriteLine("** ALL GONE WRONG **" + m2.Groups[3].Value); }
if (!modules.ContainsKey(modindex))
modules.Add(modindex, new Module(modindex));
if (m2.Groups[2].ToString() == "SubExt")
{
target = modules[modindex].modulesubext;
}
else
{
target = modules[modindex].modulefixedobjects;
}
}
ODentry od = new ODentry
{
//Indexes in the EDS are always in hex format without the pre 0x
Index = Convert.ToUInt16(m.Groups[3].ToString(), 16)
};
//Parameter name, mandatory always
if (!kvp.Value.ContainsKey("ParameterName"))
throw new ParameterException("Missing required field ParameterName on" + section);
od.parameter_name = kvp.Value["ParameterName"];
//Object type, assumed to be VAR unless specified
if (kvp.Value.ContainsKey("ObjectType"))
{
int type = Convert.ToInt16(kvp.Value["ObjectType"], Getbase(kvp.Value["ObjectType"]));
od.objecttype = (ObjectType)type;
}
else
{
od.objecttype = ObjectType.VAR;
}
if (kvp.Value.ContainsKey("CompactSubObj"))
{
od.CompactSubObj = Convert.ToByte(kvp.Value["CompactSubObj"], Getbase(kvp.Value["CompactSubObj"]));
}
if (kvp.Value.ContainsKey("ObjFlags"))
{
od.ObjFlags = Convert.ToUInt32(kvp.Value["ObjFlags"], Getbase(kvp.Value["ObjFlags"]));
}
else
{
od.ObjFlags = 0;
}
//Access Type
if (kvp.Value.ContainsKey("StorageLocation"))
{
od.prop.CO_storageGroup = kvp.Value["StorageLocation"];
}
if (kvp.Value.ContainsKey("TPDODetectCos"))
{
string test = kvp.Value["TPDODetectCos"].ToLower();
if (test == "1" || test == "true")
{
od.prop.CO_flagsPDO = true;
}
else
od.prop.CO_flagsPDO = false;
}
if (kvp.Value.ContainsKey("Count"))
{
/* FIXME: The format of "Count" is Unsigned8[; Unsigned8] according DS306
* Count:
Number of extended Sub-Indexes with this description that are created per module. The format is Unsigned8 [; Unsigned8].
If one or more Sub - Indexes are created per attached module to build a new sub- index, then Count is that
Number. In example 32 bit module creates 4 Sub - Indexes each having 8 Bit: Count = 4
If several modules are gathered to form a new Sub- Index, then the number is 0, followed by semicolon and the
number of bits that are created per module to build a new Sub-Index.In example 2 bit modules with 8 bit objects: The
first Sub - Index is built upon modules 1 - 4, the next upon modules 5 - 8 etc.: Count = 0; 2.The objects are created,
when a new byte begins: Module 1 creates the Sub - Index 1; modules 2 - 4 fill it up; module 5 creates Sub-Index 2 and
so forth.
*/
pat2 = @"\s*([0-9a-fA-F]+)\s*;\s*([0-9a-fA-F]+)";
r2 = new Regex(pat2, RegexOptions.IgnoreCase);
m2 = r2.Match(kvp.Value["Count"]);
if (m2.Success)
{
Console.WriteLine("** FIXME Count format not supported ** Count: " + kvp.Value["Count"]);
int found = kvp.Value["Count"].IndexOf(";");
string s = kvp.Value["Count"].Substring(found + 1);
try { od.count = Convert.ToByte(s, Getbase(s)); }
catch (Exception) { Console.WriteLine("** ALL GONE WRONG ** Count" + kvp.Value["Count"]); }
}
else
{
try { od.count = Convert.ToByte(kvp.Value["Count"], Getbase(kvp.Value["Count"])); }
catch (Exception) { Console.WriteLine("** ALL GONE WRONG ** Count" + kvp.Value["Count"]); }
}
}
if (kvp.Value.ContainsKey("ObjExtend"))
{
try { od.ObjExtend = Convert.ToByte(kvp.Value["ObjExtend"]); }
catch (Exception) { Console.WriteLine("** ALL GONE WRONG ** ObjExtend:" + kvp.Value["ObjExtend"]); }
}
if (od.objecttype == ObjectType.VAR)
{
if (kvp.Value.ContainsKey("CompactSubObj"))
throw new ParameterException("CompactSubObj not valid for a VAR Object, section: " + section);
if (kvp.Value.ContainsKey("ParameterValue"))
{
try { od.actualvalue = kvp.Value["ParameterValue"]; }
catch (Exception) { Console.WriteLine("** ALL GONE WRONG ** ParameterValue:" + kvp.Value["ParameterValue"]); }
}
if (kvp.Value.ContainsKey("HighLimit"))
{
try { od.HighLimit = kvp.Value["HighLimit"]; }
catch (Exception) { Console.WriteLine("** ALL GONE WRONG ** HighLimit:" + kvp.Value["HighLimit"]); }
}
if (kvp.Value.ContainsKey("LowLimit"))
{
try { od.LowLimit = kvp.Value["LowLimit"]; }
catch (Exception) { Console.WriteLine("** ALL GONE WRONG ** LowLimit:" + kvp.Value["LowLimit"]); }
}
if (kvp.Value.ContainsKey("Denotation"))
{
try { od.denotation = kvp.Value["Denotation"]; }
catch (Exception) { Console.WriteLine("** ALL GONE WRONG ** Denotation:" + kvp.Value["Denotation"]); }
}
if (m.Groups[5].Length != 0)
{
//FIXME are subindexes in hex always?
UInt16 subindex = Convert.ToUInt16(m.Groups[5].ToString(), 16);
od.parent = target[od.Index];
target[od.Index].subobjects.Add(subindex, od);
}
if (!kvp.Value.ContainsKey("DataType"))
throw new ParameterException("Missing required field DataType on" + section);
od.datatype = (DataType)Convert.ToInt16(kvp.Value["DataType"], Getbase(kvp.Value["DataType"]));
if (!kvp.Value.ContainsKey("AccessType"))
throw new ParameterException("Missing required AccessType on" + section);
string accesstype = kvp.Value["AccessType"].ToLower();
if (Enum.IsDefined(typeof(AccessType), accesstype))
{
od.accesstype = (AccessType)Enum.Parse(typeof(AccessType), accesstype);
}
else
{
throw new ParameterException("Unknown AccessType on" + section);
}
if (kvp.Value.ContainsKey("DefaultValue"))
od.defaultvalue = kvp.Value["DefaultValue"];
od.PDOtype = PDOMappingType.no;
if (kvp.Value.ContainsKey("PDOMapping"))
{
bool pdo = Convert.ToInt16(kvp.Value["PDOMapping"], Getbase(kvp.Value["PDOMapping"])) == 1;
if (pdo == true)
od.PDOtype = PDOMappingType.optional;
}
}
if (od.objecttype == ObjectType.RECORD || od.objecttype == ObjectType.ARRAY || od.objecttype == ObjectType.DEFSTRUCT)
{
if (od.CompactSubObj != 0)
{
if (!kvp.Value.ContainsKey("DataType"))
throw new ParameterException("Missing required field DataType on" + section);
od.datatype = (DataType)Convert.ToInt16(kvp.Value["DataType"], Getbase(kvp.Value["DataType"]));
if (!kvp.Value.ContainsKey("AccessType"))
throw new ParameterException("Missing required AccessType on" + section);
string accesstype = kvp.Value["AccessType"];
if (Enum.IsDefined(typeof(AccessType), accesstype))
{
od.accesstype = (AccessType)Enum.Parse(typeof(AccessType), accesstype);
}
else
{
throw new ParameterException("Unknown AccessType on" + section);
}
//now we generate CompactSubObj number of var objects below this parent
if (od.CompactSubObj >= 0xfe)
{
od.CompactSubObj = 0xfe;
}
ODentry subi = new ODentry("NrOfObjects", od.Index, DataType.UNSIGNED8, String.Format("0x{0:x2}", od.CompactSubObj), AccessType.ro, PDOMappingType.no, od);
od.subobjects.Add(0x00, subi);
for (int x = 1; x <= od.CompactSubObj; x++)
{
string parameter_name = string.Format("{0}{1:x2}", od.parameter_name, x);
ODentry sub = new ODentry(parameter_name, od.Index, od.datatype, od.defaultvalue, od.accesstype, od.PDOtype, od);
if (kvp.Value.ContainsKey("HighLimit"))
sub.HighLimit = kvp.Value["HighLimit"];
if (kvp.Value.ContainsKey("LowLimit"))
sub.HighLimit = kvp.Value["LowLimit"];
od.subobjects.Add((ushort)(x), sub);
}
}
else
{
if (!kvp.Value.ContainsKey("SubNumber"))
throw new ParameterException("Missing SubNumber on Array for" + section);
}
}
if (od.objecttype == ObjectType.DOMAIN)
{
od.datatype = DataType.DOMAIN;
od.accesstype = AccessType.rw;
if (kvp.Value.ContainsKey("DefaultValue"))
od.defaultvalue = kvp.Value["DefaultValue"];
}
//Only add top level to this list
if (m.Groups[5].Length == 0)
{
target.Add(od.Index, od);
}
}
}
public void Loadfile(string filename)
{
projectFilename = filename;
if (Path.GetExtension(filename).ToLower() == ".eds")
{
edsfilename = filename;
}
if (Path.GetExtension(filename).ToLower() == ".dcf")
{
dcffilename = filename;
}
int lineno = 1;
foreach (string linex in System.IO.File.ReadLines(filename))
{
Parseline(linex, lineno);
lineno++;
}
di = new DeviceInfo(eds["DeviceInfo"]);
foreach (KeyValuePair<string, Dictionary<string, string>> kvp in eds)
{
try { ParseEDSentry(kvp); }
catch (Exception) { Console.WriteLine("** ALL GONE WRONG **" + kvp); }
}
fi = new FileInfo(eds["FileInfo"]);
if (eds.ContainsKey("DummyUsage"))
du = new Dummyusage(eds["DummyUsage"]);
md = new MandatoryObjects(eds["MandatoryObjects"]);
if (eds.ContainsKey("OptionalObjects"))
oo = new OptionalObjects(eds["OptionalObjects"]);
if (eds.ContainsKey("ManufacturerObjects"))
mo = new ManufacturerObjects(eds["ManufacturerObjects"]);
if (eds.ContainsKey("TypeDefinitions"))
td = new TypeDefinitions(eds["TypeDefinitions"]);
//Only DCF not EDS files
dc = new DeviceCommissioning();
string strSection = "";
if (eds.ContainsKey("DeviceCommissioning")) // wrong section name as defined in the DSP302, but right spelling (for compabiltiy to some tools)
strSection = "DeviceCommissioning";
else if (eds.ContainsKey("DeviceComissioning")) // right section name as defined in the DSP302, (wrong spelling)
strSection = "DeviceComissioning";
if (strSection != "")
{
dc.Parse(eds[strSection], "DeviceCommissioning");
edsfilename = fi.LastEDS;
}
c = new Comments();
if (eds.ContainsKey("Comments"))
c.Parse(eds["Comments"]);
//Modules
//FIXME
//we don't parse or support [MxFixedObjects] with MxFixedxxxx and MxFixedxxxxsubx
if (eds.ContainsKey("SupportedModules"))
{
sm = new SupportedModules(eds["SupportedModules"]);
//find MxModuleInfo
foreach (string s in eds.Keys)
{
String pat = @"M([0-9]+)ModuleInfo";
Regex r = new Regex(pat, RegexOptions.IgnoreCase);
Match m = r.Match(s);
if (m.Success)
{
UInt16 modindex = Convert.ToUInt16(m.Groups[1].Value);
ModuleInfo mi = new ModuleInfo(eds[s], modindex);
if (!modules.ContainsKey(modindex))
modules.Add(modindex, new Module(modindex));
modules[modindex].mi = mi;
}
pat = @"M([0-9]+)Comments";
r = new Regex(pat, RegexOptions.IgnoreCase);
m = r.Match(s);
if (m.Success)
{
UInt16 modindex = Convert.ToUInt16(m.Groups[1].Value);
ModuleComments mc = new ModuleComments(eds[s], modindex);
if (!modules.ContainsKey(modindex))
modules.Add(modindex, new Module(modindex));
modules[modindex].mc = mc;
}
pat = @"M([0-9]+)SubExtends";
r = new Regex(pat, RegexOptions.IgnoreCase);
m = r.Match(s);
if (m.Success)
{
UInt16 modindex = Convert.ToUInt16(m.Groups[1].Value);
ModuleSubExtends mse = new ModuleSubExtends(eds[s], modindex);
if (!modules.ContainsKey(modindex))
modules.Add(modindex, new Module(modindex));
modules[modindex].mse = mse;
}
//DCF only
pat = @"M([0-9]+)FixedObjects";
r = new Regex(pat, RegexOptions.IgnoreCase);
m = r.Match(s);
if (m.Success)
{
UInt16 modindex = Convert.ToUInt16(m.Groups[1].Value);
MxFixedObjects mxf = new MxFixedObjects(eds[s], modindex);
if (!modules.ContainsKey(modindex))
modules.Add(modindex, new Module(modindex));
modules[modindex].mxfo = mxf;
}
}
if (eds.ContainsKey("ConnectedModules"))
{
cm = new ConnectedModules(eds["ConnectedModules"]);
}
//COMPACT PDO
if (di.CompactPDO != 0)
{
for (UInt16 index = 0x1400; index < 0x1600; index++)
{
ApplycompactPDO(index);
}
for (UInt16 index = 0x1800; index < 0x1A00; index++)
{
ApplycompactPDO(index);
}
}
ApplyimplicitPDO();
}
// catch(Exception e)
//{
// Console.WriteLine("** ALL GONE WRONG **" + e.ToString());
// }
}
void ApplycompactPDO(UInt16 index)
{
if (ods.ContainsKey(index))
{
if ((!ods[index].Containssubindex(1)) && ((this.di.CompactPDO & 0x01) == 0))
{
//Fill in cob ID
//FIX ME i'm really sure this is not correct, what default values should be used???
string cob = string.Format("$NODEID + 0x180");
ODentry subod = new ODentry("COB-ID", index, DataType.UNSIGNED32, cob, AccessType.rw, PDOMappingType.no, ods[index]);
ods[index].subobjects.Add(0x05, subod);
}
if ((!ods[index].Containssubindex(2)) && ((this.di.CompactPDO & 0x02) == 0))
{
//Fill in type
ODentry subod = new ODentry("Type", index, DataType.UNSIGNED8, "0xff", AccessType.rw, PDOMappingType.no, ods[index]);
ods[index].subobjects.Add(0x02, subod);
}