]> rtime.felk.cvut.cz Git - CanFestival-3.git/blob - objdictgen/gen_cfile.py
Problem with String size in C file generated fixed
[CanFestival-3.git] / objdictgen / gen_cfile.py
1 #!/usr/bin/env python
2 # -*- coding: utf-8 -*-
3
4 #This file is part of CanFestival, a library implementing CanOpen Stack. 
5 #
6 #Copyright (C): Edouard TISSERANT and Francis DUPIN
7 #
8 #See COPYING file for copyrights details.
9 #
10 #This library is free software; you can redistribute it and/or
11 #modify it under the terms of the GNU Lesser General Public
12 #License as published by the Free Software Foundation; either
13 #version 2.1 of the License, or (at your option) any later version.
14 #
15 #This library is distributed in the hope that it will be useful,
16 #but WITHOUT ANY WARRANTY; without even the implied warranty of
17 #MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
18 #Lesser General Public License for more details.
19 #
20 #You should have received a copy of the GNU Lesser General Public
21 #License along with this library; if not, write to the Free Software
22 #Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
23
24 from node import *
25 from types import *
26
27 import re, os
28
29 word_model = re.compile('([a-zA-Z_0-9]*)')
30 type_model = re.compile('([\_A-Z]*)([0-9]*)')
31 range_model = re.compile('([\_A-Z]*)([0-9]*)\[([\-0-9]*)-([\-0-9]*)\]')
32
33 categories = [("SDO_SVR", 0x1200, 0x127F), ("SDO_CLT", 0x1280, 0x12FF),
34               ("PDO_RCV", 0x1400, 0x15FF), ("PDO_RCV_MAP", 0x1600, 0x17FF),
35               ("PDO_TRS", 0x1800, 0x19FF), ("PDO_TRS_MAP", 0x1A00, 0x1BFF)]
36 index_categories = ["firstIndex", "lastIndex"]
37
38 generated_tag = """\n/* File generated by gen_cfile.py. Should not be modified. */\n"""
39
40 internal_types = {}
41 default_string_size = 10
42
43 # Format a string for making a C++ variable
44 def FormatName(name):
45     wordlist = [word for word in word_model.findall(name) if word != '']
46     return "_".join(wordlist)
47
48 # Extract the informations from a given type name
49 def GetValidTypeInfos(typename, items=[]):
50     if typename in internal_types:
51         return internal_types[typename]
52     else:
53         result = type_model.match(typename)
54         if result:
55             values = result.groups()
56             if values[0] == "UNSIGNED" and int(values[1]) in [i * 8 for i in xrange(1, 9)]:
57                 typeinfos = ("UNS%s"%values[1], None, "uint%s"%values[1], True)
58             elif values[0] == "INTEGER" and int(values[1]) in [i * 8 for i in xrange(1, 9)]:
59                 typeinfos = ("INTEGER%s"%values[1], None, "int%s"%values[1], False)
60             elif values[0] == "REAL" and int(values[1]) in (32, 64):
61                 typeinfos = ("%s%s"%(values[0], values[1]), None, "real%s"%values[1], False)
62             elif values[0] == "VISIBLE_STRING":
63                 size = default_string_size
64                 for item in items:
65                     size = max(size, len(item))
66                 if values[1] != "":
67                     size = max(size, int(values[1]))
68                 typeinfos = ("UNS8", size, "visible_string", False)
69             elif values[0] == "DOMAIN":
70                 typeinfos = ("UNS8*", None, "domain", False)
71             elif values[0] == "BOOLEAN":
72                 typeinfos = ("UNS8", None, "boolean", False)
73             else:
74                 raise ValueError, """!!! %s isn't a valid type for CanFestival."""%typename
75             internal_types[typename] = typeinfos
76         else:
77             raise ValueError, """!!! %s isn't a valid type for CanFestival."""%typename
78     return typeinfos
79
80 def WriteFile(filepath, content):
81     cfile = open(filepath,"w")
82     cfile.write(content)
83     cfile.close()
84
85 def GenerateFileContent(Node, headerfilepath):
86     global type
87     global internal_types
88     global default_string_size
89     
90     texts = {}
91     texts["maxPDOtransmit"] = 0
92     texts["NodeName"] = Node.GetNodeName()
93     texts["NodeID"] = Node.GetNodeID()
94     texts["NodeType"] = Node.GetNodeType()
95     texts["Description"] = Node.GetNodeDescription()
96     texts["iam_a_slave"] = 0
97     if (texts["NodeType"] == "slave"):
98         texts["iam_a_slave"] = 1
99     
100     default_string_size = Node.GetDefaultStringSize()
101     
102     # Compiling lists of indexes
103     rangelist = [idx for idx in Node.GetIndexes() if 0 <= idx <= 0x260]
104     listIndex = [idx for idx in Node.GetIndexes() if 0x1000 <= idx <= 0xFFFF]
105     communicationlist = [idx for idx in Node.GetIndexes() if 0x1000 <= idx <= 0x11FF]
106     sdolist = [idx for idx in Node.GetIndexes() if 0x1200 <= idx <= 0x12FF]
107     pdolist = [idx for idx in Node.GetIndexes() if 0x1400 <= idx <= 0x1BFF]
108     variablelist = [idx for idx in Node.GetIndexes() if 0x2000 <= idx <= 0xBFFF]
109
110 #-------------------------------------------------------------------------------
111 #                       Declaration of the value range types
112 #-------------------------------------------------------------------------------    
113     
114     valueRangeContent = ""
115     strDefine = "\n#define valueRange_EMC 0x9F /* Type for index 0x1003 subindex 0x00 (only set of value 0 is possible) */"
116     strSwitch = """    case valueRange_EMC:
117       if (*(UNS8*)value != (UNS8)0) return OD_VALUE_RANGE_EXCEEDED;
118       break;\n"""
119     internal_types["valueRange_EMC"] = ("UNS8", "", "valueRange_EMC", True)
120     num = 0
121     for index in rangelist:
122         rangename = Node.GetEntryName(index)
123         result = range_model.match(rangename)
124         if result:
125             num += 1
126             typeindex = Node.GetEntry(index, 1)
127             typename = Node.GetTypeName(typeindex)
128             typeinfos = GetValidTypeInfos(typename)
129             internal_types[rangename] = (typeinfos[0], typeinfos[1], "valueRange_%d"%num)
130             minvalue = Node.GetEntry(index, 2)
131             maxvalue = Node.GetEntry(index, 3)
132             strDefine += "\n#define valueRange_%d 0x%02X /* Type %s, %s < value < %s */"%(num,index,typeinfos[0],str(minvalue),str(maxvalue))
133             strSwitch += "    case valueRange_%d:\n"%(num)
134             if typeinfos[3] and minvalue <= 0:
135                 strSwitch += "      /* Negative or null low limit ignored because of unsigned type */;\n"
136             else:
137                 strSwitch += "      if (*(%s*)value < (%s)%s) return OD_VALUE_TOO_LOW;\n"%(typeinfos[0],typeinfos[0],str(minvalue))
138             strSwitch += "      if (*(%s*)value > (%s)%s) return OD_VALUE_TOO_HIGH;\n"%(typeinfos[0],typeinfos[0],str(maxvalue))
139             strSwitch += "    break;\n"
140
141     valueRangeContent += strDefine
142     valueRangeContent += "\nUNS32 %(NodeName)s_valueRangeTest (UNS8 typeValue, void * value)\n{"%texts
143     valueRangeContent += "\n  switch (typeValue) {\n"
144     valueRangeContent += strSwitch
145     valueRangeContent += "  }\n  return 0;\n}\n"
146
147 #-------------------------------------------------------------------------------
148 #            Creation of the mapped variables and object dictionary
149 #-------------------------------------------------------------------------------
150
151     mappedVariableContent = ""
152     strDeclareHeader = ""
153     strDeclareCallback = ""
154     indexContents = {}
155     indexCallbacks = {}
156     for index in listIndex:
157         texts["index"] = index
158         strIndex = ""
159         entry_infos = Node.GetEntryInfos(index)
160         texts["EntryName"] = entry_infos["name"].encode('ascii','replace')
161         values = Node.GetEntry(index)
162         callbacks = Node.HasEntryCallbacks(index)
163         if index in variablelist:
164             strIndex += "\n/* index 0x%(index)04X :   Mapped variable %(EntryName)s */\n"%texts
165         else:
166             strIndex += "\n/* index 0x%(index)04X :   %(EntryName)s. */\n"%texts
167         
168         # Entry type is VAR
169         if type(values) != ListType:
170             subentry_infos = Node.GetSubentryInfos(index, 0)
171             typename = Node.GetTypeName(subentry_infos["type"])
172             typeinfos = GetValidTypeInfos(typename, [values])
173             texts["subIndexType"] = typeinfos[0]
174             if typeinfos[1] is not None:
175                 texts["suffixe"] = "[%d]"%typeinfos[1]
176             else:
177                 texts["suffixe"] = ""
178             if typeinfos[2] == "visible_string":
179                 texts["value"] = "\"%s\""%values
180                 texts["comment"] = ""
181             elif typeinfos[2] == "domain":
182                 texts["value"] = "\"%s\""%''.join(["\\x%2.2x"%ord(char) for char in value])
183                 texts["comment"] = ""
184             else:
185                 texts["value"] = "0x%X"%values
186                 texts["comment"] = "\t/* %s */"%str(values)
187             if index in variablelist:
188                 texts["name"] = FormatName(subentry_infos["name"])
189                 strDeclareHeader += "extern %(subIndexType)s %(name)s%(suffixe)s;\t\t/* Mapped at index 0x%(index)04X, subindex 0x00*/\n"%texts
190                 if callbacks:
191                     strDeclareHeader += "extern ODCallback_t %(name)s_callbacks[];\t\t/* Callbacks of index0x%(index)04X */\n"%texts
192                 mappedVariableContent += "%(subIndexType)s %(name)s%(suffixe)s = %(value)s;\t\t/* Mapped at index 0x%(index)04X, subindex 0x00 */\n"%texts
193             else:
194                 strIndex += "                    %(subIndexType)s %(NodeName)s_obj%(index)04X%(suffixe)s = %(value)s;%(comment)s\n"%texts
195             values = [values]
196         else:
197             subentry_infos = Node.GetSubentryInfos(index, 0)
198             typename = Node.GetTypeName(subentry_infos["type"])
199             typeinfos = GetValidTypeInfos(typename)
200             if index == 0x1003:
201                 texts["value"] = 0
202             else:
203                 texts["value"] = values[0]
204             texts["subIndexType"] = typeinfos[0]
205             strIndex += "                    %(subIndexType)s %(NodeName)s_highestSubIndex_obj%(index)04X = %(value)d; /* number of subindex - 1*/\n"%texts
206             
207             # Entry type is RECORD
208             if entry_infos["struct"] & OD_IdenticalSubindexes:
209                 subentry_infos = Node.GetSubentryInfos(index, 1)
210                 typename = Node.GetTypeName(subentry_infos["type"])
211                 typeinfos = GetValidTypeInfos(typename, values[1:])
212                 texts["subIndexType"] = typeinfos[0]
213                 if typeinfos[1] is not None:
214                     texts["suffixe"] = "[%d]"%typeinfos[1]
215                 else:
216                     texts["suffixe"] = ""
217                 texts["length"] = values[0]
218                 if index in variablelist:
219                     texts["name"] = FormatName(entry_infos["name"])
220                     strDeclareHeader += "extern %(subIndexType)s %(name)s[%(length)d]%(suffixe)s;\t\t/* Mapped at index 0x%(index)04X, subindex 0x01 - 0x%(length)02X */\n"%texts
221                     if callbacks:
222                         strDeclareHeader += "extern ODCallback_t %(name)s_callbacks[];\t\t/* Callbacks of index0x%(index)04X */\n"%texts
223                     mappedVariableContent += "%(subIndexType)s %(name)s[] =\t\t/* Mapped at index 0x%(index)04X, subindex 0x01 - 0x%(length)02X */\n  {\n"%texts
224                     for subIndex, value in enumerate(values):
225                         sep = ","
226                         comment = ""
227                         if subIndex > 0:
228                             if subIndex == len(values)-1:
229                                 sep = ""
230                             if typeinfos[2] == "visible_string":
231                                 value = "\"%s\""%value
232                             elif typeinfos[2] == "domain":
233                                 value = "\"%s\""%''.join(["\\x%2.2x"%ord(char) for char in value])
234                             else:
235                                 comment = "\t/* %s */"%str(value)
236                                 value = "0x%X"%value
237                             mappedVariableContent += "    %s%s%s\n"%(value, sep, comment)
238                     mappedVariableContent += "  };\n"
239                 else:
240                     strIndex += "                    %(subIndexType)s %(NodeName)s_obj%(index)04X[] = \n                    {\n"%texts
241                     for subIndex, value in enumerate(values):
242                         sep = ","
243                         comment = ""
244                         if subIndex > 0:
245                             if subIndex == len(values)-1:
246                                 sep = ""
247                             if typeinfos[2] == "visible_string":
248                                 value = "\"%s\""%value
249                             elif typeinfos[2] == "domain":
250                                 value = "\"%s\""%''.join(["\\x%2.2x"%ord(char) for char in value])
251                             else:
252                                 comment = "\t/* %s */"%str(value)
253                                 value = "0x%X"%value
254                             strIndex += "                      %s%s%s\n"%(value, sep, comment)
255                     strIndex += "                    };\n"
256             else:
257                 
258                 texts["parent"] = FormatName(entry_infos["name"])
259                 # Entry type is ARRAY
260                 for subIndex, value in enumerate(values):
261                     texts["subIndex"] = subIndex
262                     if subIndex > 0:
263                         subentry_infos = Node.GetSubentryInfos(index, subIndex)
264                         typename = Node.GetTypeName(subentry_infos["type"])
265                         typeinfos = GetValidTypeInfos(typename, [values[subIndex]])
266                         texts["subIndexType"] = typeinfos[0]
267                         if typeinfos[1] is not None:
268                             texts["suffixe"] = "[%d]"%typeinfos[1]
269                         else:
270                             texts["suffixe"] = ""
271                         if typeinfos[2] == "visible_string":
272                             texts["value"] = "\"%s\""%value
273                             texts["comment"] = ""
274                         elif typeinfos[2] == "domain":
275                             texts["value"] = "\"%s\""%''.join(["\\x%2.2x"%ord(char) for char in value])
276                             texts["comment"] = ""                       
277                         else:
278                             texts["value"] = "0x%X"%value
279                             texts["comment"] = "\t/* %s */"%str(value)
280                         texts["name"] = FormatName(subentry_infos["name"])
281                         if index in variablelist:
282                             strDeclareHeader += "extern %(subIndexType)s %(parent)s_%(name)s%(suffixe)s;\t\t/* Mapped at index 0x%(index)04X, subindex 0x%(subIndex)02X */\n"%texts
283                             mappedVariableContent += "%(subIndexType)s %(parent)s_%(name)s%(suffixe)s = %(value)s;\t\t/* Mapped at index 0x%(index)04X, subindex 0x%(subIndex)02X */\n"%texts
284                         else:
285                             strIndex += "                    %(subIndexType)s %(NodeName)s_obj%(index)04X_%(name)s%(suffixe)s = %(value)s;%(comment)s\n"%texts
286                 if callbacks:
287                     strDeclareHeader += "extern ODCallback_t %(parent)s_callbacks[];\t\t/* Callbacks of index0x%(index)04X */\n"%texts
288         
289         # Generating Dictionary C++ entry
290         if callbacks:
291             if index in variablelist:
292                 name = FormatName(entry_infos["name"])
293             else:
294                 name = "%(NodeName)s_Index%(index)04X"%texts
295             strIndex += "                    ODCallback_t %s_callbacks[] = \n                     {\n"%name
296             for subIndex in xrange(len(values)):
297                 strIndex += "                       NULL,\n"
298             strIndex += "                     };\n"
299             indexCallbacks[index] = "*callbacks = %s_callbacks; "%name
300         else:
301             indexCallbacks[index] = ""
302         strIndex += "                    subindex %(NodeName)s_Index%(index)04X[] = \n                     {\n"%texts
303         for subIndex in xrange(len(values)):
304             subentry_infos = Node.GetSubentryInfos(index, subIndex)
305             if subIndex < len(values) - 1:
306                 sep = ","
307             else:
308                 sep = ""
309             typename = Node.GetTypeName(subentry_infos["type"])
310             if entry_infos["struct"] & OD_IdenticalSubindexes:
311                 typeinfos = GetValidTypeInfos(typename, values)
312             else:
313                 typeinfos = GetValidTypeInfos(typename, [values[subIndex]])
314             if subIndex == 0:
315                 if index == 0x1003:
316                     typeinfos = GetValidTypeInfos("valueRange_EMC")
317                 if entry_infos["struct"] & OD_MultipleSubindexes:
318                     name = "%(NodeName)s_highestSubIndex_obj%(index)04X"%texts
319                 elif index in variablelist:
320                     name = FormatName(subentry_infos["name"])
321                 else:
322                     name = FormatName("%s_obj%04X"%(texts["NodeName"], texts["index"]))
323             elif entry_infos["struct"] & OD_IdenticalSubindexes:
324                 if index in variablelist:
325                     name = "%s[%d]"%(FormatName(entry_infos["name"]), subIndex - 1)
326                 else:
327                     name = "%s_obj%04X[%d]"%(texts["NodeName"], texts["index"], subIndex - 1)
328             else:
329                 if index in variablelist:
330                     name = FormatName("%s_%s"%(entry_infos["name"],subentry_infos["name"]))
331                 else:
332                     name = "%s_obj%04X_%s"%(texts["NodeName"], texts["index"], FormatName(subentry_infos["name"]))
333             if typeinfos[2] in ["visible_string", "domain"]:
334                 sizeof = typeinfos[1]
335             else:
336                 sizeof = "sizeof (%s)"%typeinfos[0]
337             params = Node.GetParamsEntry(index, subIndex)
338             if params["save"]:
339                 save = "|TO_BE_SAVE"
340             else:
341                 save = ""
342             strIndex += "                       { %s%s, %s, %s, (void*)&%s }%s\n"%(subentry_infos["access"].upper(),save,typeinfos[2],sizeof,name,sep)
343         strIndex += "                     };\n"
344         indexContents[index] = strIndex
345
346 #-------------------------------------------------------------------------------
347 #                     Declaration of Particular Parameters
348 #-------------------------------------------------------------------------------
349
350     if 0x1003 not in communicationlist:
351         entry_infos = Node.GetEntryInfos(0x1003)
352         texts["EntryName"] = entry_infos["name"]
353         indexContents[0x1003] = """\n/* index 0x1003 :   %(EntryName)s */
354                     UNS8 %(NodeName)s_highestSubIndex_obj1003 = 0; /* number of subindex - 1*/
355                     UNS32 %(NodeName)s_obj1003[] = 
356                     {
357                       0x0       /* 0 */
358                     };
359                     ODCallback_t %(NodeName)s_Index1003_callbacks[] = 
360                      {
361                        NULL,
362                        NULL,
363                      };
364                     subindex %(NodeName)s_Index1003[] = 
365                      {
366                        { RW, valueRange_EMC, sizeof (UNS8), (void*)&%(NodeName)s_highestSubIndex_obj1003 },
367                        { RO, uint32, sizeof (UNS32), (void*)&%(NodeName)s_obj1003[0] }
368                      };
369 """%texts
370
371     if 0x1005 not in communicationlist:
372         entry_infos = Node.GetEntryInfos(0x1005)
373         texts["EntryName"] = entry_infos["name"]
374         indexContents[0x1005] = """\n/* index 0x1005 :   %(EntryName)s */
375                     UNS32 %(NodeName)s_obj1005 = 0x0;   /* 0 */
376 """%texts
377
378     if 0x1006 not in communicationlist:
379         entry_infos = Node.GetEntryInfos(0x1006)
380         texts["EntryName"] = entry_infos["name"]
381         indexContents[0x1006] = """\n/* index 0x1006 :   %(EntryName)s */
382                     UNS32 %(NodeName)s_obj1006 = 0x0;   /* 0 */
383 """%texts
384
385     if 0x1014 not in communicationlist:
386         entry_infos = Node.GetEntryInfos(0x1014)
387         texts["EntryName"] = entry_infos["name"]
388         indexContents[0x1014] = """\n/* index 0x1014 :   %(EntryName)s */
389                     UNS32 %(NodeName)s_obj1014 = 0x0;   /* 0 */
390 """%texts
391
392     if 0x1016 in communicationlist:
393         texts["heartBeatTimers_number"] = Node.GetEntry(0x1016, 0)
394     else:
395         texts["heartBeatTimers_number"] = 0
396         entry_infos = Node.GetEntryInfos(0x1016)
397         texts["EntryName"] = entry_infos["name"]
398         indexContents[0x1016] = """\n/* index 0x1016 :   %(EntryName)s */
399                     UNS8 %(NodeName)s_highestSubIndex_obj1016 = 0;
400                     UNS32 %(NodeName)s_obj1016[]={0};
401 """%texts
402     
403     if 0x1017 not in communicationlist:
404         entry_infos = Node.GetEntryInfos(0x1017)
405         texts["EntryName"] = entry_infos["name"]
406         indexContents[0x1017] = """\n/* index 0x1017 :   %(EntryName)s */ 
407                     UNS16 %(NodeName)s_obj1017 = 0x0;   /* 0 */
408 """%texts
409
410 #-------------------------------------------------------------------------------
411 #               Declaration of navigation in the Object Dictionary
412 #-------------------------------------------------------------------------------
413
414     strDeclareIndex = ""
415     strDeclareSwitch = ""
416     strQuickIndex = ""
417     quick_index = {}
418     for index_cat in index_categories:
419         quick_index[index_cat] = {}
420         for cat, idx_min, idx_max in categories:
421             quick_index[index_cat][cat] = 0
422     maxPDOtransmit = 0
423     for i, index in enumerate(listIndex):
424         texts["index"] = index
425         strDeclareIndex += "  { (subindex*)%(NodeName)s_Index%(index)04X,sizeof(%(NodeName)s_Index%(index)04X)/sizeof(%(NodeName)s_Index%(index)04X[0]), 0x%(index)04X},\n"%texts
426         strDeclareSwitch += "           case 0x%04X: i = %d;%sbreak;\n"%(index, i, indexCallbacks[index])
427         for cat, idx_min, idx_max in categories:
428             if idx_min <= index <= idx_max:
429                 quick_index["lastIndex"][cat] = i
430                 if quick_index["firstIndex"][cat] == 0:
431                     quick_index["firstIndex"][cat] = i
432                 if cat == "PDO_TRS":
433                     maxPDOtransmit += 1
434     texts["maxPDOtransmit"] = max(1, maxPDOtransmit)
435     for index_cat in index_categories:
436         strQuickIndex += "\nquick_index %s_%s = {\n"%(texts["NodeName"], index_cat)
437         sep = ","
438         for i, (cat, idx_min, idx_max) in enumerate(categories):
439             if i == len(categories) - 1:
440                 sep = ""
441             strQuickIndex += "  %d%s /* %s */\n"%(quick_index[index_cat][cat],sep,cat)
442         strQuickIndex += "};\n"
443
444 #-------------------------------------------------------------------------------
445 #                            Write File Content
446 #-------------------------------------------------------------------------------
447
448     fileContent = generated_tag + """
449 #include "%s"
450 """%(headerfilepath)
451
452     fileContent += """
453 /**************************************************************************/
454 /* Declaration of the mapped variables                                    */
455 /**************************************************************************/
456 """ + mappedVariableContent
457
458     fileContent += """
459 /**************************************************************************/
460 /* Declaration of the value range types                                   */
461 /**************************************************************************/
462 """ + valueRangeContent
463
464     fileContent += """
465 /**************************************************************************/
466 /* The node id                                                            */
467 /**************************************************************************/
468 /* node_id default value.*/
469 UNS8 %(NodeName)s_bDeviceNodeId = 0x%(NodeID)02X;
470
471 /**************************************************************************/
472 /* Array of message processing information */
473
474 const UNS8 %(NodeName)s_iam_a_slave = %(iam_a_slave)d;
475
476 """%texts
477     if texts["heartBeatTimers_number"] > 0:
478         fileContent += "TIMER_HANDLE %(NodeName)s_heartBeatTimers[%(heartBeatTimers_number)d] = {TIMER_NONE,};\n"%texts
479     else:
480         fileContent += "TIMER_HANDLE %(NodeName)s_heartBeatTimers[1];\n"%texts
481     
482     fileContent += """
483 /*
484 $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
485
486                                OBJECT DICTIONARY
487
488 $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
489 */
490 """%texts
491     contentlist = indexContents.keys()
492     contentlist.sort()
493     for index in contentlist:
494         fileContent += indexContents[index]
495
496     fileContent += """
497 const indextable %(NodeName)s_objdict[] = 
498 {
499 """%texts
500     fileContent += strDeclareIndex
501     fileContent += """};
502
503 const indextable * %(NodeName)s_scanIndexOD (UNS16 wIndex, UNS32 * errorCode, ODCallback_t **callbacks)
504 {
505         int i;
506         *callbacks = NULL;
507         switch(wIndex){
508 """%texts
509     fileContent += strDeclareSwitch
510     fileContent += """          default:
511                         *errorCode = OD_NO_SUCH_OBJECT;
512                         return NULL;
513         }
514         *errorCode = OD_SUCCESSFUL;
515         return &%(NodeName)s_objdict[i];
516 }
517
518 /* 
519  * To count at which received SYNC a PDO must be sent.
520  * Even if no pdoTransmit are defined, at least one entry is computed
521  * for compilations issues.
522  */
523 s_PDO_status %(NodeName)s_PDO_status[%(maxPDOtransmit)d] = {"""%texts
524
525     fileContent += ",".join(["s_PDO_status_Initializer"]*texts["maxPDOtransmit"]) + """};
526 """
527
528     fileContent += strQuickIndex
529     fileContent += """
530 UNS16 %(NodeName)s_ObjdictSize = sizeof(%(NodeName)s_objdict)/sizeof(%(NodeName)s_objdict[0]); 
531
532 CO_Data %(NodeName)s_Data = CANOPEN_NODE_DATA_INITIALIZER(%(NodeName)s);
533
534 """%texts
535
536 #-------------------------------------------------------------------------------
537 #                          Write Header File Content
538 #-------------------------------------------------------------------------------
539
540     texts["file_include_name"] = headerfilepath.replace(".", "_").upper()
541     HeaderFileContent = generated_tag + """
542 #ifndef %(file_include_name)s
543 #define %(file_include_name)s
544
545 #include "data.h"
546
547 /* Prototypes of function provided by object dictionnary */
548 UNS32 %(NodeName)s_valueRangeTest (UNS8 typeValue, void * value);
549 const indextable * %(NodeName)s_scanIndexOD (UNS16 wIndex, UNS32 * errorCode, ODCallback_t **callbacks);
550
551 /* Master node data struct */
552 extern CO_Data %(NodeName)s_Data;
553 """%texts
554     HeaderFileContent += strDeclareHeader
555     
556     HeaderFileContent += "\n#endif // %(file_include_name)s\n"%texts
557     
558     return fileContent,HeaderFileContent
559
560 #-------------------------------------------------------------------------------
561 #                             Main Function
562 #-------------------------------------------------------------------------------
563
564 def GenerateFile(filepath, node):
565     try:
566         headerfilepath = os.path.splitext(filepath)[0]+".h"
567         content, header = GenerateFileContent(node, os.path.split(headerfilepath)[1])
568         WriteFile(filepath, content)
569         WriteFile(headerfilepath, header)
570         return None
571     except ValueError, message:
572         return "Unable to Generate C File\n%s"%message
573