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