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