2 # -*- coding: utf-8 -*-
4 #This file is part of CanFestival, a library implementing CanOpen Stack.
6 #Copyright (C): Edouard TISSERANT and Francis DUPIN
8 #See COPYING file for copyrights details.
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.
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.
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
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]*)\]')
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"]
38 generated_tag = """\n/* File generated by gen_cfile.py. Should not be modified. */\n"""
42 # Format a string for making a C++ variable
44 wordlist = [word for word in word_model.findall(name) if word != '']
45 return "_".join(wordlist)
47 # Extract the informations from a given type name
48 def GetValidTypeInfos(typename):
49 if typename in internal_types:
50 return internal_types[typename]
52 result = type_model.match(typename)
54 values = result.groups()
55 if values[0] == "UNSIGNED" and int(values[1]) in [i * 8 for i in xrange(1, 9)]:
56 typeinfos = ("UNS%s"%values[1], "", "uint%s"%values[1])
57 elif values[0] == "INTEGER" and int(values[1]) in [i * 8 for i in xrange(1, 9)]:
58 typeinfos = ("INTEGER%s"%values[1], "", "int%s"%values[1])
59 elif values[0] == "REAL" and int(values[1]) in (32, 64):
60 typeinfos = ("%s%s"%(values[0], values[1]), "", "real%s"%values[1])
61 elif values[0] == "VISIBLE_STRING":
63 typeinfos = ("UNS8", "[10]", "visible_string")
65 typeinfos = ("UNS8", "[%s]"%values[1], "visible_string")
66 elif values[0] == "DOMAIN":
67 typeinfos = ("UNS8*", "", "domain")
68 elif values[0] == "BOOLEAN":
69 typeinfos = ("UNS8", "", "boolean")
71 raise ValueError, """!!! %s isn't a valid type for CanFestival."""%typename
72 internal_types[typename] = typeinfos
74 raise ValueError, """!!! %s isn't a valid type for CanFestival."""%typename
77 def WriteFile(filepath, content):
78 cfile = open(filepath,"w")
82 def GenerateFileContent(Manager, headerfilepath):
86 texts["maxPDOtransmit"] = 0
87 texts["NodeName"], texts["NodeID"], texts["NodeType"], texts["Description"] = Manager.GetCurrentNodeInfos()
88 texts["iam_a_slave"] = 0
89 if (texts["NodeType"] == "slave"):
90 texts["iam_a_slave"] = 1
92 # Compiling lists of indexes
93 rangelist = [idx for name,idx in Manager.GetCurrentValidIndexes(0, 0x260)]
94 listIndex = [idx for name,idx in Manager.GetCurrentValidIndexes(0x1000, 0xFFFF)]
95 communicationlist = [idx for name,idx in Manager.GetCurrentValidIndexes(0x1000, 0x11FF)]
96 sdolist = [idx for name,idx in Manager.GetCurrentValidIndexes(0x1200, 0x12FF)]
97 pdolist = [idx for name,idx in Manager.GetCurrentValidIndexes(0x1400, 0x1BFF)]
98 variablelist = [idx for name,idx in Manager.GetCurrentValidIndexes(0x2000, 0xBFFF)]
100 #-------------------------------------------------------------------------------
101 # Declaration of the value range types
102 #-------------------------------------------------------------------------------
104 valueRangeContent = ""
108 for index in rangelist:
109 rangename = Manager.GetEntryName(index)
110 result = range_model.match(rangename)
113 typeindex = Manager.GetCurrentEntry(index, 1)
114 typename = Manager.GetTypeName(typeindex)
115 typeinfos = GetValidTypeInfos(typename)
116 internal_types[rangename] = (typeinfos[0], typeinfos[1], "valueRange_%d"%num)
117 minvalue = str(Manager.GetCurrentEntry(index, 2))
118 maxvalue = str(Manager.GetCurrentEntry(index, 3))
119 strDefine += "\n#define valueRange_%d 0x%02X /* Type %s, %s < value < %s */"%(num,index,typeinfos[0],minvalue,maxvalue)
120 strSwitch += """ case valueRange_%d:
121 if (*(%s*)Value < (%s)%s) return OD_VALUE_TOO_LOW;
122 if (*(%s*)Value > (%s)%s) return OD_VALUE_TOO_HIGH;
123 break;\n"""%(num,typeinfos[0],typeinfos[0],minvalue,typeinfos[0],typeinfos[0],maxvalue)
125 valueRangeContent += strDefine
126 valueRangeContent += "\nUNS32 %(NodeName)s_valueRangeTest (UNS8 typeValue, void * value)\n{"%texts
127 valueRangeContent += "\n switch (typeValue) {\n"
128 valueRangeContent += strSwitch
129 valueRangeContent += " }\n return 0;\n}\n"
131 #-------------------------------------------------------------------------------
132 # Creation of the mapped variables and object dictionary
133 #-------------------------------------------------------------------------------
135 mappedVariableContent = ""
136 strDeclareHeader = ""
137 strDeclareCallback = ""
140 translate_characters = "".join([chr(i) for i in xrange(128)] + ["_" for i in xrange(128)])
141 for index in listIndex:
142 texts["index"] = index
144 entry_infos = Manager.GetEntryInfos(index)
145 texts["EntryName"] = entry_infos["name"].translate(translate_characters)
146 values = Manager.GetCurrentEntry(index)
147 callbacks = Manager.HasCurrentEntryCallbacks(index)
148 if index in variablelist:
149 strIndex += "\n/* index 0x%(index)04X : Mapped variable %(EntryName)s */\n"%texts
151 strIndex += "\n/* index 0x%(index)04X : %(EntryName)s. */\n"%texts
154 if type(values) != ListType:
155 subentry_infos = Manager.GetSubentryInfos(index, 0)
156 typename = Manager.GetTypeName(subentry_infos["type"])
157 typeinfos = GetValidTypeInfos(typename)
158 texts["subIndexType"] = typeinfos[0]
159 texts["suffixe"] = typeinfos[1]
160 if typeinfos[2] == "visible_string":
161 texts["value"] = "\"%s\""%values
162 texts["comment"] = ""
163 elif typeinfos[2] == "domain":
164 texts["value"] = "\"%s\""%''.join(["\\x%2.2x"%ord(char) for char in value])
165 texts["comment"] = ""
167 texts["value"] = "0x%X"%values
168 texts["comment"] = "\t/* %s */"%str(values)
169 if index in variablelist:
170 texts["name"] = FormatName(subentry_infos["name"])
171 strDeclareHeader += "extern %(subIndexType)s %(name)s%(suffixe)s;\t\t/* Mapped at index 0x%(index)04X, subindex 0x00*/\n"%texts
173 strDeclareHeader += "extern ODCallback_t %(name)s_callbacks[];\t\t/* Callbacks of index0x%(index)04X */\n"%texts
174 mappedVariableContent += "%(subIndexType)s %(name)s%(suffixe)s = %(value)s;\t\t/* Mapped at index 0x%(index)04X, subindex 0x00 */\n"%texts
176 strIndex += " %(subIndexType)s %(NodeName)s_obj%(index)04X%(suffixe)s = %(value)s;%(comment)s\n"%texts
179 subentry_infos = Manager.GetSubentryInfos(index, 0)
180 typename = Manager.GetTypeName(subentry_infos["type"])
181 typeinfos = GetValidTypeInfos(typename)
182 texts["value"] = values[0]
183 texts["subIndexType"] = typeinfos[0]
184 strIndex += " %(subIndexType)s %(NodeName)s_highestSubIndex_obj%(index)04X = %(value)d; /* number of subindex - 1*/\n"%texts
186 # Entry type is RECORD
187 if entry_infos["struct"] & OD_IdenticalSubindexes:
188 subentry_infos = Manager.GetSubentryInfos(index, 1)
189 typename = Manager.GetTypeName(subentry_infos["type"])
190 typeinfos = GetValidTypeInfos(typename)
191 texts["subIndexType"] = typeinfos[0]
192 texts["suffixe"] = typeinfos[1]
193 texts["length"] = values[0]
194 if index in variablelist:
195 texts["name"] = FormatName(entry_infos["name"])
196 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
198 strDeclareHeader += "extern ODCallback_t %(name)s_callbacks[];\t\t/* Callbacks of index0x%(index)04X */\n"%texts
199 mappedVariableContent += "%(subIndexType)s %(name)s[] =\t\t/* Mapped at index 0x%(index)04X, subindex 0x01 - 0x%(length)02X */\n {\n"%texts
200 for subIndex, value in enumerate(values):
204 if subIndex == len(values)-1:
206 if typeinfos[2] == "visible_string":
207 value = "\"%s\""%value
208 elif typeinfos[2] == "domain":
209 value = "\"%s\""%''.join(["\\x%2.2x"%ord(char) for char in value])
211 comment = "\t/* %s */"%str(value)
213 mappedVariableContent += " %s%s%s\n"%(value, sep, comment)
214 mappedVariableContent += " };\n"
216 strIndex += " %(subIndexType)s %(NodeName)s_obj%(index)04X[] = \n {\n"%texts
217 for subIndex, value in enumerate(values):
221 if subIndex == len(values)-1:
223 if typeinfos[2] == "visible_string":
224 value = "\"%s\""%value
225 elif typeinfos[2] == "domain":
226 value = "\"%s\""%''.join(["\\x%2.2x"%ord(char) for char in value])
228 comment = "\t/* %s */"%str(value)
230 strIndex += " %s%s%s\n"%(value, sep, comment)
234 texts["parent"] = FormatName(entry_infos["name"])
235 # Entry type is ARRAY
236 for subIndex, value in enumerate(values):
237 texts["subIndex"] = subIndex
239 subentry_infos = Manager.GetSubentryInfos(index, subIndex)
240 typename = Manager.GetTypeName(subentry_infos["type"])
241 typeinfos = GetValidTypeInfos(typename)
242 texts["subIndexType"] = typeinfos[0]
243 texts["suffixe"] = typeinfos[1]
244 if typeinfos[2] == "visible_string":
245 texts["value"] = "\"%s\""%value
246 texts["comment"] = ""
247 elif typeinfos[2] == "domain":
248 texts["value"] = "\"%s\""%''.join(["\\x%2.2x"%ord(char) for char in value])
249 texts["comment"] = ""
251 texts["value"] = "0x%X"%value
252 texts["comment"] = "\t/* %s */"%str(value)
253 texts["name"] = FormatName(subentry_infos["name"])
254 if index in variablelist:
255 strDeclareHeader += "extern %(subIndexType)s %(parent)s_%(name)s%(suffixe)s;\t\t/* Mapped at index 0x%(index)04X, subindex 0x%(subIndex)02X */\n"%texts
256 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
258 strIndex += " %(subIndexType)s %(NodeName)s_obj%(index)04X_%(name)s%(suffixe)s = %(value)s;%(comment)s\n"%texts
260 strDeclareHeader += "extern ODCallback_t %(parent)s_callbacks[];\t\t/* Callbacks of index0x%(index)04X */\n"%texts
262 # Generating Dictionary C++ entry
264 if index in variablelist:
265 name = FormatName(entry_infos["name"])
267 name = "%(NodeName)s_Index%(index)04X"%texts
268 strIndex += " ODCallback_t %s_callbacks[] = \n {\n"%name
269 for subIndex in xrange(len(values)):
270 strIndex += " NULL,\n"
272 indexCallbacks[index] = "*callbacks = %s_callbacks; "%name
274 indexCallbacks[index] = ""
275 strIndex += " subindex %(NodeName)s_Index%(index)04X[] = \n {\n"%texts
276 for subIndex in xrange(len(values)):
277 subentry_infos = Manager.GetSubentryInfos(index, subIndex)
278 if subIndex < len(values) - 1:
282 typename = Manager.GetTypeName(subentry_infos["type"])
283 typeinfos = GetValidTypeInfos(typename)
285 if entry_infos["struct"] & OD_MultipleSubindexes:
286 name = "%(NodeName)s_highestSubIndex_obj%(index)04X"%texts
287 elif index in variablelist:
288 name = FormatName(subentry_infos["name"])
290 name = FormatName("%s_obj%04X"%(texts["NodeName"], texts["index"]))
291 elif entry_infos["struct"] & OD_IdenticalSubindexes:
292 if index in variablelist:
293 name = "%s[%d]"%(FormatName(entry_infos["name"]), subIndex - 1)
295 name = "%s_obj%04X[%d]"%(texts["NodeName"], texts["index"], subIndex - 1)
297 if index in variablelist:
298 name = FormatName("%s_%s"%(entry_infos["name"],subentry_infos["name"]))
300 name = "%s_obj%04X_%s"%(texts["NodeName"], texts["index"], FormatName(subentry_infos["name"]))
301 if typeinfos[2] in ["visible_string", "domain"]:
302 sizeof = str(len(values[subIndex]))
304 sizeof = "sizeof (%s)"%typeinfos[0]
305 params = Manager.GetCurrentParamsEntry(index, subIndex)
310 strIndex += " { %s%s, %s, %s, (void*)&%s }%s\n"%(subentry_infos["access"].upper(),save,typeinfos[2],sizeof,name,sep)
312 indexContents[index] = strIndex
314 #-------------------------------------------------------------------------------
315 # Declaration of Particular Parameters
316 #-------------------------------------------------------------------------------
318 if 0x1006 not in communicationlist:
319 entry_infos = Manager.GetEntryInfos(0x1006)
320 texts["EntryName"] = entry_infos["name"]
321 indexContents[0x1006] = """\n/* index 0x1006 : %(EntryName)s */
322 UNS32 %(NodeName)s_obj1006 = 0x0; /* 0 */
325 if 0x1016 in communicationlist:
326 texts["nombre"] = Manager.GetCurrentEntry(0x1016, 0)
329 entry_infos = Manager.GetEntryInfos(0x1016)
330 texts["EntryName"] = entry_infos["name"]
331 indexContents[0x1016] = """\n/* index 0x1016 : %(EntryName)s */
332 UNS8 %(NodeName)s_highestSubIndex_obj1016 = 0;
333 UNS32 %(NodeName)s_obj1016[]={0};
335 if texts["nombre"] > 0:
336 strTimers = "TIMER_HANDLE %(NodeName)s_heartBeatTimers[%(nombre)d] = {TIMER_NONE,};\n"%texts
338 strTimers = "TIMER_HANDLE %(NodeName)s_heartBeatTimers[1];\n"%texts
340 if 0x1017 not in communicationlist:
341 entry_infos = Manager.GetEntryInfos(0x1017)
342 texts["EntryName"] = entry_infos["name"]
343 indexContents[0x1017] = """\n/* index 0x1017 : %(EntryName)s */
344 UNS16 %(NodeName)s_obj1017 = 0x0; /* 0 */
347 #-------------------------------------------------------------------------------
348 # Declaration of navigation in the Object Dictionary
349 #-------------------------------------------------------------------------------
352 strDeclareSwitch = ""
355 for index_cat in index_categories:
356 quick_index[index_cat] = {}
357 for cat, idx_min, idx_max in categories:
358 quick_index[index_cat][cat] = 0
360 for i, index in enumerate(listIndex):
361 texts["index"] = index
362 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
363 strDeclareSwitch += " case 0x%04X: i = %d;%sbreak;\n"%(index, i, indexCallbacks[index])
364 for cat, idx_min, idx_max in categories:
365 if idx_min <= index <= idx_max:
366 quick_index["lastIndex"][cat] = i
367 if quick_index["firstIndex"][cat] == 0:
368 quick_index["firstIndex"][cat] = i
371 texts["maxPDOtransmit"] = max(1, maxPDOtransmit)
372 for index_cat in index_categories:
373 strQuickIndex += "\nquick_index %s_%s = {\n"%(texts["NodeName"], index_cat)
375 for i, (cat, idx_min, idx_max) in enumerate(categories):
376 if i == len(categories) - 1:
378 strQuickIndex += " %d%s /* %s */\n"%(quick_index[index_cat][cat],sep,cat)
379 strQuickIndex += "};\n"
381 #-------------------------------------------------------------------------------
383 #-------------------------------------------------------------------------------
385 fileContent = generated_tag + """
390 /**************************************************************************/
391 /* Declaration of the mapped variables */
392 /**************************************************************************/
393 """ + mappedVariableContent
396 /**************************************************************************/
397 /* Declaration of the value range types */
398 /**************************************************************************/
399 """ + valueRangeContent
402 /**************************************************************************/
404 /**************************************************************************/
405 /* node_id default value.*/
406 UNS8 %(NodeName)s_bDeviceNodeId = 0x%(NodeID)02X;
408 /**************************************************************************/
409 /* Array of message processing information */
411 const UNS8 %(NodeName)s_iam_a_slave = %(iam_a_slave)d;
414 fileContent += strTimers
418 $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
422 $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
425 contentlist = indexContents.keys()
427 for index in contentlist:
428 fileContent += indexContents[index]
431 const indextable %(NodeName)s_objdict[] =
434 fileContent += strDeclareIndex
437 const indextable * %(NodeName)s_scanIndexOD (UNS16 wIndex, UNS32 * errorCode, ODCallback_t **callbacks)
443 fileContent += strDeclareSwitch
444 fileContent += """ default:
445 *errorCode = OD_NO_SUCH_OBJECT;
448 *errorCode = OD_SUCCESSFUL;
449 return &%(NodeName)s_objdict[i];
452 /* To count at which received SYNC a PDO must be sent.
453 * Even if no pdoTransmit are defined, at least one entry is computed
454 * for compilations issues.
456 UNS8 %(NodeName)s_count_sync[%(maxPDOtransmit)d] = {0,};
458 fileContent += strQuickIndex
460 UNS16 %(NodeName)s_ObjdictSize = sizeof(%(NodeName)s_objdict)/sizeof(%(NodeName)s_objdict[0]);
462 CO_Data %(NodeName)s_Data = CANOPEN_NODE_DATA_INITIALIZER(%(NodeName)s);
466 #-------------------------------------------------------------------------------
467 # Write Header File Content
468 #-------------------------------------------------------------------------------
470 texts["file_include_name"] = headerfilepath.replace(".", "_").upper()
471 HeaderFileContent = generated_tag + """
472 #ifndef %(file_include_name)s
473 #define %(file_include_name)s
477 /* Prototypes of function provided by object dictionnary */
478 UNS32 %(NodeName)s_valueRangeTest (UNS8 typeValue, void * value);
479 const indextable * %(NodeName)s_scanIndexOD (UNS16 wIndex, UNS32 * errorCode, ODCallback_t **callbacks);
481 /* Master node data struct */
482 extern CO_Data %(NodeName)s_Data;
484 HeaderFileContent += strDeclareHeader
486 HeaderFileContent += "\n#endif // %(file_include_name)s\n"%texts
488 return fileContent,HeaderFileContent
490 #-------------------------------------------------------------------------------
492 #-------------------------------------------------------------------------------
494 def GenerateFile(filepath, manager):
496 headerfilepath = os.path.splitext(filepath)[0]+".h"
497 content, header = GenerateFileContent(manager, os.path.split(headerfilepath)[1])
498 WriteFile(filepath, content)
499 WriteFile(headerfilepath, header)
501 except ValueError, message:
502 return "Unable to Generate C File\n%s"%message