]> rtime.felk.cvut.cz Git - CanFestival-3.git/blob - objdictgen/gen_cfile.py
e87ccd8a6f7d64d71cbfebb0999dec236deda8bb
[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 = default_string_size
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             texts["subIndexType"] = typeinfos[0]
192             if typeinfos[1] is not None:
193                 texts["suffixe"] = "[%d]"%typeinfos[1]
194             else:
195                 texts["suffixe"] = ""
196             texts["value"], texts["comment"] = ComputeValue(typeinfos[2], values)
197             if index in variablelist:
198                 texts["name"] = FormatName(subentry_infos["name"])
199                 strDeclareHeader += "extern %(subIndexType)s %(name)s%(suffixe)s;\t\t/* Mapped at index 0x%(index)04X, subindex 0x00*/\n"%texts
200                 mappedVariableContent += "%(subIndexType)s %(name)s%(suffixe)s = %(value)s;\t\t/* Mapped at index 0x%(index)04X, subindex 0x00 */\n"%texts
201             else:
202                 strIndex += "                    %(subIndexType)s %(NodeName)s_obj%(index)04X%(suffixe)s = %(value)s;%(comment)s\n"%texts
203             values = [values]
204         else:
205             subentry_infos = Node.GetSubentryInfos(index, 0)
206             typename = Node.GetTypeName(subentry_infos["type"])
207             typeinfos = GetValidTypeInfos(typename)
208             if index == 0x1003:
209                 texts["value"] = 0
210             else:
211                 texts["value"] = values[0]
212             texts["subIndexType"] = typeinfos[0]
213             strIndex += "                    %(subIndexType)s %(NodeName)s_highestSubIndex_obj%(index)04X = %(value)d; /* number of subindex - 1*/\n"%texts
214             
215             # Entry type is RECORD
216             if entry_infos["struct"] & OD_IdenticalSubindexes:
217                 subentry_infos = Node.GetSubentryInfos(index, 1)
218                 typename = Node.GetTypeName(subentry_infos["type"])
219                 typeinfos = GetValidTypeInfos(typename, values[1:])
220                 texts["subIndexType"] = typeinfos[0]
221                 if typeinfos[1] is not None:
222                     texts["suffixe"] = "[%d]"%typeinfos[1]
223                     texts["type_suffixe"] = "*"
224                 else:
225                     texts["suffixe"] = ""
226                     texts["type_suffixe"] = ""
227                 texts["length"] = values[0]
228                 if index in variablelist:
229                     texts["name"] = FormatName(entry_infos["name"])
230                     strDeclareHeader += "extern %(subIndexType)s%(type_suffixe)s %(name)s[];\t\t/* Mapped at index 0x%(index)04X, subindex 0x01 - 0x%(length)02X */\n"%texts
231                     mappedVariableContent += "%(subIndexType)s%(type_suffixe)s %(name)s[] =\t\t/* Mapped at index 0x%(index)04X, subindex 0x01 - 0x%(length)02X */\n  {\n"%texts
232                     for subIndex, value in enumerate(values):
233                         sep = ","
234                         if subIndex > 0:
235                             if subIndex == len(values)-1:
236                                 sep = ""
237                             value, comment = ComputeValue(typeinfos[2], value)
238                             mappedVariableContent += "    %s%s%s\n"%(value, sep, comment)
239                     mappedVariableContent += "  };\n"
240                 else:
241                     strIndex += "                    %(subIndexType)s%(type_suffixe)s %(NodeName)s_obj%(index)04X[] = \n                    {\n"%texts
242                     for subIndex, value in enumerate(values):
243                         sep = ","
244                         if subIndex > 0:
245                             if subIndex == len(values)-1:
246                                 sep = ""
247                             value, comment = ComputeValue(typeinfos[2], value)
248                             strIndex += "                      %s%s%s\n"%(value, sep, comment)
249                     strIndex += "                    };\n"
250             else:
251                 
252                 texts["parent"] = FormatName(entry_infos["name"])
253                 # Entry type is ARRAY
254                 for subIndex, value in enumerate(values):
255                     texts["subIndex"] = subIndex
256                     if subIndex > 0:
257                         subentry_infos = Node.GetSubentryInfos(index, subIndex)
258                         typename = Node.GetTypeName(subentry_infos["type"])
259                         typeinfos = GetValidTypeInfos(typename, [values[subIndex]])
260                         texts["subIndexType"] = typeinfos[0]
261                         if typeinfos[1] is not None:
262                             texts["suffixe"] = "[%d]"%typeinfos[1]
263                         else:
264                             texts["suffixe"] = ""
265                         texts["value"], texts["comment"] = ComputeValue(typeinfos[2], value)
266                         texts["name"] = FormatName(subentry_infos["name"])
267                         if index in variablelist:
268                             strDeclareHeader += "extern %(subIndexType)s %(parent)s_%(name)s%(suffixe)s;\t\t/* Mapped at index 0x%(index)04X, subindex 0x%(subIndex)02X */\n"%texts
269                             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
270                         else:
271                             strIndex += "                    %(subIndexType)s %(NodeName)s_obj%(index)04X_%(name)s%(suffixe)s = %(value)s;%(comment)s\n"%texts
272         
273         # Generating Dictionary C++ entry
274         if callbacks:
275             if index in variablelist:
276                 name = FormatName(entry_infos["name"])
277             else:
278                 name = "%(NodeName)s_Index%(index)04X"%texts
279             strIndex += "                    ODCallback_t %s_callbacks[] = \n                     {\n"%name
280             for subIndex in xrange(len(values)):
281                 strIndex += "                       NULL,\n"
282             strIndex += "                     };\n"
283             indexCallbacks[index] = "*callbacks = %s_callbacks; "%name
284         else:
285             indexCallbacks[index] = ""
286         strIndex += "                    subindex %(NodeName)s_Index%(index)04X[] = \n                     {\n"%texts
287         for subIndex in xrange(len(values)):
288             subentry_infos = Node.GetSubentryInfos(index, subIndex)
289             if subIndex < len(values) - 1:
290                 sep = ","
291             else:
292                 sep = ""
293             typename = Node.GetTypeName(subentry_infos["type"])
294             if entry_infos["struct"] & OD_IdenticalSubindexes:
295                 typeinfos = GetValidTypeInfos(typename, values[1:])
296             else:
297                 typeinfos = GetValidTypeInfos(typename, [values[subIndex]])
298             if subIndex == 0:
299                 if index == 0x1003:
300                     typeinfos = GetValidTypeInfos("valueRange_EMC")
301                 if entry_infos["struct"] & OD_MultipleSubindexes:
302                     name = "%(NodeName)s_highestSubIndex_obj%(index)04X"%texts
303                 elif index in variablelist:
304                     name = FormatName(subentry_infos["name"])
305                 else:
306                     name = FormatName("%s_obj%04X"%(texts["NodeName"], texts["index"]))
307             elif entry_infos["struct"] & OD_IdenticalSubindexes:
308                 if index in variablelist:
309                     name = "%s[%d]"%(FormatName(entry_infos["name"]), subIndex - 1)
310                 else:
311                     name = "%s_obj%04X[%d]"%(texts["NodeName"], texts["index"], subIndex - 1)
312             else:
313                 if index in variablelist:
314                     name = FormatName("%s_%s"%(entry_infos["name"],subentry_infos["name"]))
315                 else:
316                     name = "%s_obj%04X_%s"%(texts["NodeName"], texts["index"], FormatName(subentry_infos["name"]))
317             if typeinfos[2] == "visible_string":
318                 sizeof = str(max(len(values[subIndex]), default_string_size))
319             elif typeinfos[2] == "domain":
320                 sizeof = str(len(values[subIndex]))
321             else:
322                 sizeof = "sizeof (%s)"%typeinfos[0]
323             params = Node.GetParamsEntry(index, subIndex)
324             if params["save"]:
325                 save = "|TO_BE_SAVE"
326             else:
327                 save = ""
328             strIndex += "                       { %s%s, %s, %s, (void*)&%s }%s\n"%(subentry_infos["access"].upper(),save,typeinfos[2],sizeof,name,sep)
329             pointer_name = pointers_dict.get((index, subIndex), None)
330             if pointer_name is not None:
331                 pointedVariableContent += "%s* %s = &%s;\n"%(typeinfos[0], pointer_name, name)
332         strIndex += "                     };\n"
333         indexContents[index] = strIndex
334         
335 #-------------------------------------------------------------------------------
336 #                     Declaration of Particular Parameters
337 #-------------------------------------------------------------------------------
338
339     if 0x1003 not in communicationlist:
340         entry_infos = Node.GetEntryInfos(0x1003)
341         texts["EntryName"] = entry_infos["name"]
342         indexContents[0x1003] = """\n/* index 0x1003 :   %(EntryName)s */
343                     UNS8 %(NodeName)s_highestSubIndex_obj1003 = 0; /* number of subindex - 1*/
344                     UNS32 %(NodeName)s_obj1003[] = 
345                     {
346                       0x0       /* 0 */
347                     };
348                     ODCallback_t %(NodeName)s_Index1003_callbacks[] = 
349                      {
350                        NULL,
351                        NULL,
352                      };
353                     subindex %(NodeName)s_Index1003[] = 
354                      {
355                        { RW, valueRange_EMC, sizeof (UNS8), (void*)&%(NodeName)s_highestSubIndex_obj1003 },
356                        { RO, uint32, sizeof (UNS32), (void*)&%(NodeName)s_obj1003[0] }
357                      };
358 """%texts
359
360     if 0x1005 not in communicationlist:
361         entry_infos = Node.GetEntryInfos(0x1005)
362         texts["EntryName"] = entry_infos["name"]
363         indexContents[0x1005] = """\n/* index 0x1005 :   %(EntryName)s */
364                     UNS32 %(NodeName)s_obj1005 = 0x0;   /* 0 */
365 """%texts
366
367     if 0x1006 not in communicationlist:
368         entry_infos = Node.GetEntryInfos(0x1006)
369         texts["EntryName"] = entry_infos["name"]
370         indexContents[0x1006] = """\n/* index 0x1006 :   %(EntryName)s */
371                     UNS32 %(NodeName)s_obj1006 = 0x0;   /* 0 */
372 """%texts
373
374     if 0x1014 not in communicationlist:
375         entry_infos = Node.GetEntryInfos(0x1014)
376         texts["EntryName"] = entry_infos["name"]
377         indexContents[0x1014] = """\n/* index 0x1014 :   %(EntryName)s */
378                     UNS32 %(NodeName)s_obj1014 = 0x80 + 0x%(NodeID)02X;   /* 128 + NodeID */
379 """%texts
380
381     if 0x1016 in communicationlist:
382         texts["heartBeatTimers_number"] = Node.GetEntry(0x1016, 0)
383     else:
384         texts["heartBeatTimers_number"] = 0
385         entry_infos = Node.GetEntryInfos(0x1016)
386         texts["EntryName"] = entry_infos["name"]
387         indexContents[0x1016] = """\n/* index 0x1016 :   %(EntryName)s */
388                     UNS8 %(NodeName)s_highestSubIndex_obj1016 = 0;
389                     UNS32 %(NodeName)s_obj1016[]={0};
390 """%texts
391     
392     if 0x1017 not in communicationlist:
393         entry_infos = Node.GetEntryInfos(0x1017)
394         texts["EntryName"] = entry_infos["name"]
395         indexContents[0x1017] = """\n/* index 0x1017 :   %(EntryName)s */ 
396                     UNS16 %(NodeName)s_obj1017 = 0x0;   /* 0 */
397 """%texts
398
399 #-------------------------------------------------------------------------------
400 #               Declaration of navigation in the Object Dictionary
401 #-------------------------------------------------------------------------------
402
403     strDeclareIndex = ""
404     strDeclareSwitch = ""
405     strQuickIndex = ""
406     quick_index = {}
407     for index_cat in index_categories:
408         quick_index[index_cat] = {}
409         for cat, idx_min, idx_max in categories:
410             quick_index[index_cat][cat] = 0
411     maxPDOtransmit = 0
412     for i, index in enumerate(listIndex):
413         texts["index"] = index
414         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
415         strDeclareSwitch += "           case 0x%04X: i = %d;%sbreak;\n"%(index, i, indexCallbacks[index])
416         for cat, idx_min, idx_max in categories:
417             if idx_min <= index <= idx_max:
418                 quick_index["lastIndex"][cat] = i
419                 if quick_index["firstIndex"][cat] == 0:
420                     quick_index["firstIndex"][cat] = i
421                 if cat == "PDO_TRS":
422                     maxPDOtransmit += 1
423     texts["maxPDOtransmit"] = max(1, maxPDOtransmit)
424     for index_cat in index_categories:
425         strQuickIndex += "\nconst quick_index %s_%s = {\n"%(texts["NodeName"], index_cat)
426         sep = ","
427         for i, (cat, idx_min, idx_max) in enumerate(categories):
428             if i == len(categories) - 1:
429                 sep = ""
430             strQuickIndex += "  %d%s /* %s */\n"%(quick_index[index_cat][cat],sep,cat)
431         strQuickIndex += "};\n"
432
433 #-------------------------------------------------------------------------------
434 #                            Write File Content
435 #-------------------------------------------------------------------------------
436
437     fileContent = generated_tag + """
438 #include "%s"
439 """%(headerfilepath)
440
441     fileContent += """
442 /**************************************************************************/
443 /* Declaration of mapped variables                                        */
444 /**************************************************************************/
445 """ + mappedVariableContent
446
447     fileContent += """
448 /**************************************************************************/
449 /* Declaration of value range types                                       */
450 /**************************************************************************/
451 """ + valueRangeContent
452
453     fileContent += """
454 /**************************************************************************/
455 /* The node id                                                            */
456 /**************************************************************************/
457 /* node_id default value.*/
458 UNS8 %(NodeName)s_bDeviceNodeId = 0x%(NodeID)02X;
459
460 /**************************************************************************/
461 /* Array of message processing information */
462
463 const UNS8 %(NodeName)s_iam_a_slave = %(iam_a_slave)d;
464
465 """%texts
466     if texts["heartBeatTimers_number"] > 0:
467         declaration = "TIMER_HANDLE %(NodeName)s_heartBeatTimers[%(heartBeatTimers_number)d]"%texts
468         initializer = "{TIMER_NONE" + ",TIMER_NONE" * (texts["heartBeatTimers_number"] - 1) + "}"
469         fileContent += declaration + " = " + initializer + ";\n"
470     else:
471         fileContent += "TIMER_HANDLE %(NodeName)s_heartBeatTimers[1];\n"%texts
472     
473     fileContent += """
474 /*
475 $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
476
477                                OBJECT DICTIONARY
478
479 $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
480 */
481 """%texts
482     contentlist = indexContents.keys()
483     contentlist.sort()
484     for index in contentlist:
485         fileContent += indexContents[index]
486
487     fileContent += """
488 /**************************************************************************/
489 /* Declaration of pointed variables                                       */
490 /**************************************************************************/
491 """ + pointedVariableContent
492
493     fileContent += """
494 const indextable %(NodeName)s_objdict[] = 
495 {
496 """%texts
497     fileContent += strDeclareIndex
498     fileContent += """};
499
500 const indextable * %(NodeName)s_scanIndexOD (UNS16 wIndex, UNS32 * errorCode, ODCallback_t **callbacks)
501 {
502         int i;
503         *callbacks = NULL;
504         switch(wIndex){
505 """%texts
506     fileContent += strDeclareSwitch
507     fileContent += """          default:
508                         *errorCode = OD_NO_SUCH_OBJECT;
509                         return NULL;
510         }
511         *errorCode = OD_SUCCESSFUL;
512         return &%(NodeName)s_objdict[i];
513 }
514
515 /* 
516  * To count at which received SYNC a PDO must be sent.
517  * Even if no pdoTransmit are defined, at least one entry is computed
518  * for compilations issues.
519  */
520 s_PDO_status %(NodeName)s_PDO_status[%(maxPDOtransmit)d] = {"""%texts
521
522     fileContent += ",".join(["s_PDO_status_Initializer"]*texts["maxPDOtransmit"]) + """};
523 """
524
525     fileContent += strQuickIndex
526     fileContent += """
527 const UNS16 %(NodeName)s_ObjdictSize = sizeof(%(NodeName)s_objdict)/sizeof(%(NodeName)s_objdict[0]); 
528
529 CO_Data %(NodeName)s_Data = CANOPEN_NODE_DATA_INITIALIZER(%(NodeName)s);
530
531 """%texts
532
533 #-------------------------------------------------------------------------------
534 #                          Write Header File Content
535 #-------------------------------------------------------------------------------
536
537     texts["file_include_name"] = headerfilepath.replace(".", "_").upper()
538     HeaderFileContent = generated_tag + """
539 #ifndef %(file_include_name)s
540 #define %(file_include_name)s
541
542 #include "data.h"
543
544 /* Prototypes of function provided by object dictionnary */
545 UNS32 %(NodeName)s_valueRangeTest (UNS8 typeValue, void * value);
546 const indextable * %(NodeName)s_scanIndexOD (UNS16 wIndex, UNS32 * errorCode, ODCallback_t **callbacks);
547
548 /* Master node data struct */
549 extern CO_Data %(NodeName)s_Data;
550 """%texts
551     HeaderFileContent += strDeclareHeader
552     
553     HeaderFileContent += "\n#endif // %(file_include_name)s\n"%texts
554     
555     return fileContent,HeaderFileContent
556
557 #-------------------------------------------------------------------------------
558 #                             Main Function
559 #-------------------------------------------------------------------------------
560
561 def GenerateFile(filepath, node, pointers_dict = {}):
562     try:
563         headerfilepath = os.path.splitext(filepath)[0]+".h"
564         content, header = GenerateFileContent(node, os.path.split(headerfilepath)[1], pointers_dict)
565         WriteFile(filepath, content)
566         WriteFile(headerfilepath, header)
567         return None
568     except ValueError, message:
569         return "Unable to Generate C File\n%s"%message
570