forked from robincornelius/libedssharp
-
Notifications
You must be signed in to change notification settings - Fork 93
Expand file tree
/
Copy pathCanOpenNodeExporter.cs
More file actions
1742 lines (1359 loc) · 63.4 KB
/
CanOpenNodeExporter.cs
File metadata and controls
1742 lines (1359 loc) · 63.4 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>
based heavily on the files CO_OD.h and CO_OD.c from CANopenNode which are
Copyright(c) 2010 - 2016 Janez Paternoster
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.IO;
using System.Reflection;
namespace libEDSsharp
{
/// <summary>
/// Export .c and .h files for CanOpenNode v1-3
/// </summary>
public class CanOpenNodeExporter : IExporter, IFileExporter
{
private string folderpath;
private string gitVersion;
/// <summary>
/// The eds file set when calling export
/// </summary>
protected EDSsharp eds;
private int enabledcount = 0;
Dictionary<UInt32, string> acceptable_canopen_names = new Dictionary<uint, string>();
//Used for array tracking
Dictionary<string, int> au = new Dictionary<string, int>();
List<UInt16> openings = new List<UInt16>();
List<UInt16> closings = new List<UInt16>();
private byte maxRXmappingsize = 0;
private byte maxTXmappingsize = 0;
ODentry maxRXmappingsOD=null;
ODentry maxTXmappingsOD=null;
/// <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("CanOpenNode", new string[] { ".h", ".c" }, ExporterDescriptor.ExporterFlags.CanOpenNode, delegate (string filepath, List<EDSsharp> edss)
{
var e = new CanOpenNodeExporter();
e.export(filepath, edss[0]);
})
};
}
/// <summary>
/// Register names of index and subindex that need to have standard names to be able to work with CanOpenNode
/// </summary>
public void prepareCanOpenNames()
{
acceptable_canopen_names.Add(0x101800, "identity");
acceptable_canopen_names.Add(0x140000, "RPDOCommunicationParameter");
acceptable_canopen_names.Add(0x160000, "RPDOMappingParameter");
acceptable_canopen_names.Add(0x180000, "TPDOCommunicationParameter");
acceptable_canopen_names.Add(0x1a0000, "TPDOMappingParameter");
acceptable_canopen_names.Add(0x100500, "COB_ID_SYNCMessage");
acceptable_canopen_names.Add(0x101801, "vendorID");
acceptable_canopen_names.Add(0x101802, "productCode");
acceptable_canopen_names.Add(0x101803, "revisionNumber");
acceptable_canopen_names.Add(0x101804, "serialNumber");
acceptable_canopen_names.Add(0x120000, "SDOServerParameter");
acceptable_canopen_names.Add(0x120001, "COB_IDClientToServer");
acceptable_canopen_names.Add(0x120002, "COB_IDServerToClient");
acceptable_canopen_names.Add(0x128000, "SDOClientParameter");
acceptable_canopen_names.Add(0x128001, "COB_IDClientToServer");
acceptable_canopen_names.Add(0x128002, "COB_IDServerToClient");
acceptable_canopen_names.Add(0x102900, "errorBehavior");
}
/// <summary>
/// Export eds into CanOpenNode v1-3 source files (.h and .c)
/// </summary>
/// <param name="filepath">filepath, .c and .h will be added to this to make the mulitiple files</param>
/// <param name="eds">the eds data to be exported</param>
public void export(string filepath, EDSsharp eds)
{
this.folderpath = Path.GetDirectoryName(filepath);
string filename = Path.GetFileNameWithoutExtension(filepath);
var versionAttributes = Assembly
.GetExecutingAssembly()
.GetCustomAttributes(typeof(AssemblyInformationalVersionAttribute), false)
as AssemblyInformationalVersionAttribute[];
this.gitVersion = versionAttributes[0].InformationalVersion;
this.eds = eds;
enabledcount = eds.GetNoEnabledObjects();
prepareCanOpenNames();
countPDOS();
fixcompatentry();
prewalkArrays();
export_h(filename);
export_c(filename);
}
/// <summary>
/// Fixes TPDO compatibility subindex
/// </summary>
/// Handle the TPDO communication parameters in a special way, because of
/// sizeof(OD_TPDOCommunicationParameter_t) != sizeof(CO_TPDOCommPar_t) in CANopen.c
/// the existing CO_TPDOCommPar_t has a compatibility entry so we must export one regardless of if its in the OD or not
private void fixcompatentry()
{
for (UInt16 idx = 0x1800; idx < 0x1900; idx++)
{
if (ObjectActive(idx))
{
ODentry od = eds.ods[idx];
if (!od.Containssubindex(0x04))
{
ODentry compatibility = new ODentry("compatibility entry", idx, DataType.UNSIGNED8, "0", EDSsharp.AccessType.ro, PDOMappingType.no, od);
od.subobjects.Add(0x04, compatibility);
}
}
}
}
/// <summary>
///
/// </summary>
/// <param name="start"></param>
/// <param name="end"></param>
private void specialarraysearch(UInt16 start, UInt16 end)
{
UInt16 lowest = 0xffff;
UInt16 highest = 0x0000;
foreach (KeyValuePair<UInt16, ODentry> kvp in eds.ods)
{
if (kvp.Value.prop.CO_disabled == true)
continue;
if (kvp.Key >= start && kvp.Key <= end)
{
if (kvp.Key > highest)
highest = kvp.Key;
if (kvp.Key < lowest)
lowest = kvp.Key;
}
}
if(lowest!=0xffff && highest!=0x0000)
{
openings.Add(lowest);
closings.Add(highest);
Console.WriteLine(string.Format("New special array detected start 0x{0:X4} end 0x{1:X4}", lowest, highest));
}
}
/// <summary>
/// Returns true of object is not disabled
/// </summary>
/// <param name="index">index to check</param>
/// <returns>true if index object is not disabled</returns>
public bool ObjectActive(UInt16 index)
{
if (eds.ods.ContainsKey(index))
{
return !eds.ods[index].prop.CO_disabled;
}
else return false;
}
protected void prewalkArrays()
{
foreach (KeyValuePair<UInt16, ODentry> kvp in eds.ods)
{
ODentry od = kvp.Value;
if (od.prop.CO_disabled == true)
continue;
string name = make_cname(od.parameter_name,od);
if (au.ContainsKey(name))
{
au[name]++;
}
else
{
au[name] = 1;
}
}
//Handle special arrays
specialarraysearch(0x1301, 0x1340);
specialarraysearch(0x1381, 0x13C0);
//SDO Client parameters
specialarraysearch(0x1200, 0x127F);
//SDO Server Parameters
specialarraysearch(0x1280, 0x12FF);
//PDO Mappings and configs
specialarraysearch(0x1400, 0x15FF);
specialarraysearch(0x1600, 0x17FF);
specialarraysearch(0x1800, 0x19FF);
specialarraysearch(0x1A00, 0x1BFF);
//now find opening and closing points for these arrays
foreach (KeyValuePair<string, int> kvp in au)
{
if ( kvp.Value > 1)
{
string targetname = kvp.Key;
UInt16 lowest=0xffff;
UInt16 highest=0x0000;
foreach (KeyValuePair<UInt16, ODentry> kvp2 in eds.ods)
{
string name = make_cname(kvp2.Value.parameter_name,kvp2.Value);
if(name==targetname)
{
if (kvp2.Key > highest)
highest = kvp2.Key;
if (kvp2.Key < lowest)
lowest = kvp2.Key;
}
}
if (!openings.Contains(lowest))
{
openings.Add(lowest);
closings.Add(highest);
Console.WriteLine(string.Format("New array detected start 0x{0:X4} end 0x{1:X4}", lowest, highest));
}
}
}
//Find maximum no entries in a mapping config to define an appropriate array
maxRXmappingsize = 0;
maxTXmappingsize = 0;
for (ushort x=0x1600;x<0x1800;x++)
{
if(ObjectActive(x))
{
byte maxcount = EDSsharp.ConvertToByte(eds.ods[x].subobjects[0].defaultvalue);
if(maxcount > maxRXmappingsize)
{
maxRXmappingsize = maxcount;
maxRXmappingsOD = eds.ods[x];
}
}
}
for (ushort x = 0x1a00; x < 0x1c00; x++)
{
if (ObjectActive(x))
{
byte maxcount = EDSsharp.ConvertToByte(eds.ods[x].subobjects[0].defaultvalue);
if (maxcount > maxTXmappingsize)
{
maxTXmappingsize = maxcount;
maxTXmappingsOD = eds.ods[x];
}
}
}
}
string lastname = "";
private string print_h_bylocation(string location)
{
StringBuilder sb = new StringBuilder();
lastname = "";
foreach (KeyValuePair<UInt16, ODentry> kvp in eds.ods)
{
ODentry od = kvp.Value;
if (od.prop.CO_disabled == true || od.prop.CO_storageGroup != location)
continue;
sb.Append(print_h_entry(od));
}
return sb.ToString();
}
/// <summary>
/// Return the header part of one object dictionary entry
/// </summary>
/// <param name="od">the OD entry</param>
/// <returns>part of the C header file that impliments the od entry</returns>
protected string print_h_entry(ODentry od)
{
StringBuilder sb = new StringBuilder();
if (od.Nosubindexes == 0)
{
string specialarraylength = "";
if (od.datatype == DataType.VISIBLE_STRING || od.datatype == DataType.OCTET_STRING || od.datatype == DataType.UNICODE_STRING)
{
if (od.Lengthofstring == 0)
{
Warnings.AddWarning(string.Format(" Object 0x{0:X4}/{1:X2} A string must have a default value to set the required datasize for canopen node, i have set this to [1] byte to prevent compile errors", od.Index, od.Subindex),Warnings.warning_class.WARNING_STRING);
specialarraylength = "[1]";
}
else
{
specialarraylength = string.Format("[{0}]", od.Lengthofstring);
}
}
sb.AppendLine($"/*{od.Index:X4} */ {od.datatype.ToString(),-14} {make_cname(od.parameter_name,od)}{specialarraylength};");
}
else
{
//fixme why is this not od.datatype?
DataType t = eds.Getdatatype(od);
//If it not a defined type, and it probably is not for a REC, we must generate a name, this is
//related to the previous code that generated the actual structures.
string objecttypewords = "";
switch (od.objecttype)
{
case ObjectType.RECORD:
objecttypewords = String.Format("OD_{0}_t", make_cname(od.parameter_name,od));
break;
case ObjectType.ARRAY:
objecttypewords = t.ToString(); //this case is handled by the logic in eds.getdatatype();
break;
default:
objecttypewords = t.ToString();
break;
}
string name = make_cname(od.parameter_name,od);
if (au[name] > 1)
{
if (lastname == name)
return "";
lastname = name;
sb.AppendLine($"/*{od.Index:X4} */ {objecttypewords,-15} {make_cname(od.parameter_name,od)}[{au[name]}];");
}
else
{
//Don't put sub indexes on record type in h file unless there are multiples of the same
//in which case its not handled here, we need a special case for the predefined special
//values that arrayspecial() checks for, to generate 1 element arrays if needed
if (od.objecttype == ObjectType.RECORD)
{
if (arrayspecial(od.Index, true))
{
sb.AppendLine($"/*{od.Index:X4} */ {objecttypewords,-15} {make_cname(od.parameter_name,od)}[1];");
}
else
{
sb.AppendLine($"/*{od.Index:X4} */ {objecttypewords,-15} {make_cname(od.parameter_name,od)};");
}
}
else
{
string specialarraylength = "";
if (od.datatype == DataType.VISIBLE_STRING || od.datatype == DataType.OCTET_STRING || od.datatype == DataType.UNICODE_STRING)
{
int maxlength = 0;
foreach (ODentry sub in od.subobjects.Values)
{
if (sub.Lengthofstring> maxlength)
maxlength = sub.Lengthofstring;
}
if (maxlength == 0)
{
Warnings.AddWarning(string.Format(" Object children of 0x{0:X4} A string must have a default value to set the required datasize for canopen node, i have set this to [1] byte to prevent compile errors", od.Index),Warnings.warning_class.WARNING_STRING);
maxlength = 1;
}
specialarraylength = string.Format("[{0}]", maxlength);
}
sb.AppendLine($"/*{od.Index:X4} */ {objecttypewords,-15} {make_cname(od.parameter_name,od)}[{od.Nosubindexes - 1}]{specialarraylength};");
}
}
}
return sb.ToString();
}
private void addHeader(StreamWriter file)
{
file.WriteLine(string.Format(
@"/*******************************************************************************
CANopen Object Dictionary definition for CANopenNode v1 to v2
This file was automatically generated by CANopenEditor {0}
https://github.com/CANopenNode/CANopenNode
https://github.com/CANopenNode/CANopenEditor
DON'T EDIT THIS FILE MANUALLY !!!!
*******************************************************************************/", this.gitVersion));
}
private void export_h(string filename)
{
if (filename == "")
filename = "CO_OD";
StreamWriter file = new StreamWriter(folderpath + Path.DirectorySeparatorChar + filename + ".h");
file.WriteLine("// clang-format off");
addHeader(file);
file.WriteLine("#ifndef CO_OD_H_");
file.WriteLine("#define CO_OD_H_");
file.WriteLine("");
file.WriteLine(@"/*******************************************************************************
CANopen DATA TYPES
*******************************************************************************/
typedef bool_t BOOLEAN;
typedef uint8_t UNSIGNED8;
typedef uint16_t UNSIGNED16;
typedef uint32_t UNSIGNED32;
typedef uint64_t UNSIGNED64;
typedef int8_t INTEGER8;
typedef int16_t INTEGER16;
typedef int32_t INTEGER32;
typedef int64_t INTEGER64;
typedef float32_t REAL32;
typedef float64_t REAL64;
typedef char_t VISIBLE_STRING;
typedef oChar_t OCTET_STRING;
#ifdef DOMAIN
#undef DOMAIN
#endif
typedef domain_t DOMAIN;
");
file.WriteLine("/*******************************************************************************");
file.WriteLine(" FILE INFO:");
file.WriteLine(string.Format(" FileName: {0}", Path.GetFileName(eds.projectFilename)));
file.WriteLine(string.Format(" FileVersion: {0}", eds.fi.fileVersionString));
file.WriteLine(string.Format(" CreationTime: {0}", eds.fi.CreationTime));
file.WriteLine(string.Format(" CreationDate: {0}", eds.fi.CreationDate));
file.WriteLine(string.Format(" CreatedBy: {0}", eds.fi.CreatedBy));
file.WriteLine("*******************************************************************************/");
file.WriteLine("");
file.WriteLine("");
file.WriteLine("/*******************************************************************************");
file.WriteLine(" DEVICE INFO:");
file.WriteLine(string.Format(" VendorName: {0}", eds.di.VendorName));
file.WriteLine(string.Format(" VendorNumber: {0}", eds.di.VendorNumber.ToHexString()));
file.WriteLine(string.Format(" ProductName: {0}", eds.di.ProductName));
file.WriteLine(string.Format(" ProductNumber: {0}", eds.di.ProductNumber.ToHexString()));
file.WriteLine("*******************************************************************************/");
file.WriteLine("");
file.WriteLine("");
file.WriteLine(@"/*******************************************************************************
FEATURES
*******************************************************************************/");
file.WriteLine(string.Format(" #define CO_NO_SYNC {0} //Associated objects: 1005-1007", noSYNC));
file.WriteLine(string.Format(" #define CO_NO_EMERGENCY {0} //Associated objects: 1014, 1015", noEMCY));
file.WriteLine(string.Format(" #define CO_NO_TIME {0} //Associated objects: 1012, 1013", noTIME));
file.WriteLine(string.Format(" #define CO_NO_SDO_SERVER {0} //Associated objects: 1200-127F", noSDOservers));
file.WriteLine(string.Format(" #define CO_NO_SDO_CLIENT {0} //Associated objects: 1280-12FF", noSDOclients));
file.WriteLine(string.Format(" #define CO_NO_GFC {0} //Associated objects: 1300", noGFC));
file.WriteLine(string.Format(" #define CO_NO_SRDO {0} //Associated objects: 1301-1341, 1381-13C0", noSRDO));
int lssServer = 0;
if (eds.di.LSS_Supported == true)
{
lssServer = 1;
}
file.WriteLine(string.Format(" #define CO_NO_LSS_SERVER {0} //LSS Slave", lssServer));
int lssClient = 0;
if (eds.di.LSS_Master == true)
{
lssClient = 1;
}
file.WriteLine(string.Format(" #define CO_NO_LSS_CLIENT {0} //LSS Master", lssClient));
int ngSlave = 0;
if (eds.di.NG_Slave == true)
{
ngSlave = 1;
}
file.WriteLine(string.Format(" #define CO_NODE_GUARDING_SLAVE {0} //NG Slave", ngSlave));
file.WriteLine(string.Format(" #define CO_NODE_GUARDING_MASTER {0} //NG Master", eds.di.NrOfNG_MonitoredNodes));
file.WriteLine(string.Format(" #define CO_NO_RPDO {0} //Associated objects: 14xx, 16xx", noRXpdos));
file.WriteLine(string.Format(" #define CO_NO_TPDO {0} //Associated objects: 18xx, 1Axx", noTXpdos));
bool ismaster = false;
if(ObjectActive(0x1f80))
{
ODentry master = eds.ods[0x1f80];
// we could do with a cut down function that returns a value rather than a string
string meh = formatvaluewithdatatype(master.defaultvalue, master.datatype);
meh = meh.Replace("L", "");
UInt32 NMTStartup = Convert.ToUInt32(meh, 16);
if ((NMTStartup & 0x01) == 0x01)
ismaster = true;
}
file.WriteLine(string.Format(" #define CO_NO_NMT_MASTER {0}", ismaster==true?1:0));
file.WriteLine(string.Format(" #define CO_NO_TRACE 0"));
file.WriteLine("");
file.WriteLine("");
file.WriteLine(@"/*******************************************************************************
OBJECT DICTIONARY
*******************************************************************************/");
file.WriteLine(string.Format(" #define CO_OD_NoOfElements {0}", enabledcount));
file.WriteLine("");
file.WriteLine("");
file.WriteLine(@"/*******************************************************************************
TYPE DEFINITIONS FOR RECORDS
*******************************************************************************/");
//We need to identify all the record types used and generate a struct for each one
//FIXME the original CANopenNode exporter said how many items used this struct in the comments
List<string> structnamelist = new List<string>();
/* make sure, we have all storage groups */
eds.CO_storageGroups.Add("ROM");
eds.CO_storageGroups.Add("EEPROM");
foreach (KeyValuePair<UInt16, ODentry> kvp in eds.ods)
{
ODentry od = kvp.Value;
/* make sure, we have all storage groups */
eds.CO_storageGroups.Add(od.prop.CO_storageGroup);
if (od.objecttype != ObjectType.RECORD)
continue;
string structname = String.Format("OD_{0}_t", make_cname(od.parameter_name,od));
if (structnamelist.Contains(structname))
continue;
structnamelist.Add(structname);
// we need to search the mappings to find the largest or this will not generate correctly
// as can opennode only has 1 structure defined for all mappings see #220
if (kvp.Key>=0x1600 && kvp.Key<0x1800)
{
//switch the OD entry to the largest
od = maxRXmappingsOD;
}
if (kvp.Key >= 0x1A00 && kvp.Key < 0x1C00)
{
//switch the OD entry to the largest
od = maxTXmappingsOD;
}
if (od == null)
continue;
List<string> structmemberlist = new List<string>();
file.WriteLine(string.Format("/*{0:X4} */ typedef struct {{", kvp.Key));
foreach (KeyValuePair<UInt16, ODentry> kvp2 in od.subobjects) // kvp.Value.subobjects)
{
string paramaterarrlen = "";
ODentry subod = kvp2.Value;
string proposedname = make_cname(subod.parameter_name,subod);
int suffix=1;
while (structmemberlist.Contains(proposedname))
{
Warnings.AddWarning(string.Format("STRUCT WARNING; in 0x{0:X4}/{1:X2} Duplicate struct entry name, it has been auto numbered",subod.Index,subod.Subindex),Warnings.warning_class.WARNING_STRUCT);
proposedname = make_cname(subod.parameter_name,subod) + suffix.ToString();
suffix++;
}
structmemberlist.Add(proposedname);
if (subod.datatype==DataType.VISIBLE_STRING || subod.datatype==DataType.OCTET_STRING)
{
paramaterarrlen = String.Format("[{0}]", subod.Lengthofstring);
}
file.WriteLine(string.Format(" {0,-15}{1}{2};", subod.datatype.ToString(), proposedname,paramaterarrlen));
}
file.WriteLine(string.Format(" }} {0};", structname));
}
file.WriteLine(@"
/*******************************************************************************
TYPE DEFINITIONS FOR OBJECT DICTIONARY INDEXES
some of those are redundant with CO_SDO.h CO_ObjDicId_t <Common CiA301 object
dictionary entries>
*******************************************************************************/");
//FIXME how can we get rid of that redundancy?
foreach (KeyValuePair<UInt16, ODentry> kvp in eds.ods)
{
ODentry od = kvp.Value;
if (od.prop.CO_disabled == true)
continue;
DataType t = eds.Getdatatype(od);
switch (od.objecttype)
{
default:
{
file.WriteLine(string.Format("/*{0:X4} */", od.Index));
file.WriteLine(string.Format(" #define {0,-51} 0x{1:X4}", string.Format("OD_{0:X4}_{1}", od.Index, make_cname(od.parameter_name,od)), od.Index, t.ToString()));
file.WriteLine("");
}
break;
case ObjectType.ARRAY:
case ObjectType.RECORD:
{
file.WriteLine(string.Format("/*{0:X4} */", od.Index));
file.WriteLine(string.Format(" #define {0,-51} 0x{1:X4}", string.Format("OD_{0:X4}_{1}", od.Index, make_cname(od.parameter_name,od)), od.Index, t.ToString()));
file.WriteLine("");
//sub indexes
file.WriteLine(string.Format(" #define {0,-51} 0", string.Format("OD_{0:X4}_0_{1}_maxSubIndex", od.Index, make_cname(od.parameter_name,od))));
List<string> ODSIs = new List<string>();
string ODSIout = "";
foreach (KeyValuePair<UInt16, ODentry> kvp2 in od.subobjects)
{
ODentry sub = kvp2.Value;
if (kvp2.Key == 0)
continue;
string ODSI = string.Format("{0}", string.Format("OD_{0:X4}_{1}_{2}_{3}", od.Index, kvp2.Key, make_cname(od.parameter_name,od), make_cname(sub.parameter_name,sub)));
if (ODSIs.Contains(ODSI))
{
continue;
}
ODSIs.Add(ODSI);
ODSIout += ($" #define {ODSI,-51} {kvp2.Key}{Environment.NewLine}");
}
file.Write(ODSIout);
file.WriteLine("");
}
break;
}
}
file.WriteLine(@"/*******************************************************************************
STRUCTURES FOR VARIABLES IN DIFFERENT MEMORY LOCATIONS
*******************************************************************************/
#define CO_OD_FIRST_LAST_WORD 0x55 //Any value from 0x01 to 0xFE. If changed, EEPROM will be reinitialized.
");
foreach (string location in eds.CO_storageGroups)
{
if (location == "Unused")
{
continue;
}
file.Write("/***** Structure for ");
file.Write(location);
file.WriteLine(" variables ********************************************/");
file.Write("struct sCO_OD_");
file.Write(location);
file.Write(@"{
UNSIGNED32 FirstWord;
");
file.Write(print_h_bylocation(location));
file.WriteLine(@"
UNSIGNED32 LastWord;
};
");
}
file.WriteLine(@"/***** Declaration of Object Dictionary variables *****************************/");
foreach (string location in eds.CO_storageGroups)
{
if (location == "Unused")
{
continue;
}
file.Write("extern struct sCO_OD_");
file.Write(location);
file.Write(" CO_OD_");
file.Write(location);
file.WriteLine(@";
");
}
file.WriteLine(@"/*******************************************************************************
ALIASES FOR OBJECT DICTIONARY VARIABLES
*******************************************************************************/");
List<string> constructed_rec_types = new List<string>();
foreach (KeyValuePair<UInt16, ODentry> kvp in eds.ods)
{
ODentry od = kvp.Value;
if (od.prop.CO_disabled == true)
continue;
string loc = "CO_OD_" + od.prop.CO_storageGroup;
DataType t = eds.Getdatatype(od);
switch (od.objecttype)
{
default:
{
file.WriteLine(string.Format("/*{0:X4}, Data Type: {1} */", od.Index, t.ToString()));
file.WriteLine(string.Format(" #define {0,-51} 0x{1:X4}", string.Format("OD_{0}_idx", make_cname(od.parameter_name, od)), od.Index, t.ToString()));
file.WriteLine(string.Format(" #define {0,-51} {1}.{2}", string.Format("OD_{0}", make_cname(od.parameter_name,od)), loc, make_cname(od.parameter_name,od)));
DataType dt = od.datatype;
if (dt == DataType.OCTET_STRING || dt == DataType.VISIBLE_STRING)
{
file.WriteLine(string.Format(" #define {0,-51} {1}", string.Format("ODL_{0}_stringLength", make_cname(od.parameter_name,od)), od.Lengthofstring));
}
file.WriteLine("");
}
break;
case ObjectType.ARRAY:
{
DataType dt = od.datatype;
file.WriteLine(string.Format("/*{0:X4}, Data Type: {1}, Array[{2}] */", od.Index, t.ToString(), od.Nosubindexes - 1));
file.WriteLine(string.Format(" #define {0,-51} 0x{1:X4}", string.Format("OD_{0}_idx", make_cname(od.parameter_name, od)), od.Index, t.ToString()));
file.WriteLine(string.Format(" #define OD_{0,-48} {1}.{2}", make_cname(od.parameter_name,od), loc, make_cname(od.parameter_name,od)));
file.WriteLine(string.Format(" #define {0,-51} {1}", string.Format("ODL_{0}_arrayLength", make_cname(od.parameter_name,od)), od.Nosubindexes - 1));
List<string> ODAs = new List<string>();
string ODAout = "";
foreach (KeyValuePair<UInt16, ODentry> kvp2 in od.subobjects)
{
ODentry sub = kvp2.Value;
if (kvp2.Key == 0)
continue;
string ODA = string.Format("{0}", string.Format("ODA_{0}_{1}", make_cname(od.parameter_name,od), make_cname(sub.parameter_name,sub)));
if (ODAs.Contains(ODA))
{
continue;
}
ODAs.Add(ODA);
//Arrays do not have a size in the raw CO objects, Records do
//so offset by one
if (od.objecttype == ObjectType.ARRAY)
{
ODAout += ($" #define {string.Format("ODA_{0}_{1}", make_cname(od.parameter_name,od), make_cname(sub.parameter_name,sub)),-51} {kvp2.Key - 1}{Environment.NewLine}");
}
else
{
ODAout += ($" #define {string.Format("ODA_{0}_{1}", make_cname(od.parameter_name,od), make_cname(sub.parameter_name,sub)),-51} {kvp2.Key}{Environment.NewLine}");
}
}
file.Write(ODAout);
file.WriteLine("");
}
break;
case ObjectType.RECORD:
{
string rectype = make_cname(od.parameter_name,od);
if (!constructed_rec_types.Contains(rectype))
{
file.WriteLine(string.Format("/*{0:X4}, Data Type: {1}_t */", od.Index, rectype));
file.WriteLine(string.Format(" #define {0,-51} 0x{1:X4}", string.Format("OD_{0}_idx", make_cname(od.parameter_name, od)), od.Index, t.ToString()));
file.WriteLine(string.Format(" #define {0,-51} {1}.{2}", string.Format("OD_{0}", rectype), loc, rectype));
constructed_rec_types.Add(rectype);
file.WriteLine("");
}
}
break;
}
}
file.WriteLine("#endif");
file.WriteLine("// clang-format on");
file.Close();
}
private void export_c(string filename)
{
if (filename == "")
filename = "CO_OD";
StreamWriter file = new StreamWriter(folderpath + Path.DirectorySeparatorChar + filename + ".c");
file.WriteLine("// clang-format off");
addHeader(file);
file.WriteLine(@"// For CANopenNode V2 users, C macro `CO_VERSION_MAJOR=2` has to be added to project options
#ifndef CO_VERSION_MAJOR
#include ""CO_driver.h""
#include """ + Path.GetFileNameWithoutExtension(filename) + @".h""
#include ""CO_SDO.h""
#elif CO_VERSION_MAJOR < 4
#include ""301/CO_driver.h""
#include """ + Path.GetFileNameWithoutExtension(filename) + @".h""
#include ""301/CO_SDOserver.h""
#else
#error This Object dictionary is not compatible with CANopenNode v4.0 and up!
#endif
/*******************************************************************************
DEFINITION AND INITIALIZATION OF OBJECT DICTIONARY VARIABLES
*******************************************************************************/
");
foreach (string location in eds.CO_storageGroups)
{
if (location == "Unused")
{
continue;
}
file.Write("/***** Definition for ");
file.Write(location);
file.WriteLine(" variables *******************************************/");
file.Write("struct sCO_OD_");
file.Write(location);
file.Write(" CO_OD_");
file.Write(location);
file.Write(@" = {
CO_OD_FIRST_LAST_WORD,
");
file.Write(export_OD_def_array(location));
file.WriteLine(@"
CO_OD_FIRST_LAST_WORD,
};
");
}
file.WriteLine(@"
/*******************************************************************************
STRUCTURES FOR RECORD TYPE OBJECTS
*******************************************************************************/
");
file.Write(export_record_types());
file.Write(@"/*******************************************************************************
OBJECT DICTIONARY
*******************************************************************************/
const CO_OD_entry_t CO_OD[CO_OD_NoOfElements] = {
");
file.Write(write_od());
file.WriteLine("};");
file.WriteLine("// clang-format on");
file.Close();
}
bool arrayspecialcase = false;
int arrayspecialcasecount = 0;
string write_od()
{
StringBuilder returndata = new StringBuilder();
foreach (KeyValuePair<UInt16, ODentry> kvp in eds.ods)
{
ODentry od = kvp.Value;
if (od.prop.CO_disabled == true)
continue;
returndata.Append(write_od_line(od));