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 != '']
48 result += "%s%s"%(sep,word)
52 # Extract the informations from a given type name
53 def GetValidTypeInfos(typename):
54 if typename in internal_types:
55 return internal_types[typename]
57 result = type_model.match(typename)
59 values = result.groups()
60 if values[0] == "UNSIGNED" and int(values[1]) in [i * 8 for i in xrange(1, 9)]:
61 typeinfos = ("UNS%s"%values[1], "", "uint%s"%values[1])
62 elif values[0] == "INTEGER" and int(values[1]) in [i * 8 for i in xrange(1, 9)]:
63 typeinfos = ("INTEGER%s"%values[1], "", "int%s"%values[1])
64 elif values[0] == "REAL" and int(values[1]) in (32, 64):
65 typeinfos = ("%s%s"%(values[0], values[1]), "", "real%s"%values[1])
66 elif values[0] == "VISIBLE_STRING":
68 typeinfos = ("UNS8", "[10]", "visible_string")
70 typeinfos = ("UNS8", "[%s]"%values[1], "visible_string")
71 elif values[0] == "DOMAIN":
72 typeinfos = ("UNS8*", "", "domain")
73 elif values[0] == "BOOLEAN":
74 typeinfos = ("UNS8", "", "boolean")
76 raise ValueError, """!!! %s isn't a valid type for CanFestival."""%typename
77 internal_types[typename] = typeinfos
79 raise ValueError, """!!! %s isn't a valid type for CanFestival."""%typename
82 def WriteFile(filepath, content):
83 cfile = open(filepath,"w")
87 def GenerateFileContent(Manager, headerfilepath):
91 texts["maxPDOtransmit"] = 0
92 texts["NodeName"], texts["NodeID"], texts["NodeType"], texts["Description"] = Manager.GetCurrentNodeInfos()
93 texts["iam_a_slave"] = 0
94 if (texts["NodeType"] == "slave"):
95 texts["iam_a_slave"] = 1
97 # Compiling lists of indexes
98 rangelist = [idx for name,idx in Manager.GetCurrentValidIndexes(0, 0x260)]
99 listIndex = [idx for name,idx in Manager.GetCurrentValidIndexes(0x1000, 0xFFFF)]
100 communicationlist = [idx for name,idx in Manager.GetCurrentValidIndexes(0x1000, 0x11FF)]
101 sdolist = [idx for name,idx in Manager.GetCurrentValidIndexes(0x1200, 0x12FF)]
102 pdolist = [idx for name,idx in Manager.GetCurrentValidIndexes(0x1400, 0x1BFF)]
103 variablelist = [idx for name,idx in Manager.GetCurrentValidIndexes(0x2000, 0xBFFF)]
105 #-------------------------------------------------------------------------------
106 # Declaration of the value range types
107 #-------------------------------------------------------------------------------
109 valueRangeContent = ""
113 for index in rangelist:
114 rangename = Manager.GetEntryName(index)
115 result = range_model.match(rangename)
118 typeindex = Manager.GetCurrentEntry(index, 1)
119 typename = Manager.GetTypeName(typeindex)
120 typeinfos = GetValidTypeInfos(typename)
121 internal_types[rangename] = (typeinfos[0], typeinfos[1], "valueRange_%d"%num)
122 minvalue = str(Manager.GetCurrentEntry(index, 2))
123 maxvalue = str(Manager.GetCurrentEntry(index, 3))
124 strDefine += "\n#define valueRange_%d 0x%02X /* Type %s, %s < value < %s */"%(num,index,typeinfos[0],minvalue,maxvalue)
125 strSwitch += """ case valueRange_%d:
126 if (*(%s*)Value < (%s)%s) return OD_VALUE_TOO_LOW;
127 if (*(%s*)Value > (%s)%s) return OD_VALUE_TOO_HIGH;
128 break;\n"""%(num,typeinfos[0],typeinfos[0],minvalue,typeinfos[0],typeinfos[0],maxvalue)
130 valueRangeContent += strDefine
131 valueRangeContent += "\nUNS32 %(NodeName)s_valueRangeTest (UNS8 typeValue, void * value)\n{"%texts
132 valueRangeContent += "\n switch (typeValue) {\n"
133 valueRangeContent += strSwitch
134 valueRangeContent += " }\n return 0;\n}\n"
136 #-------------------------------------------------------------------------------
137 # Creation of the mapped variables and object dictionary
138 #-------------------------------------------------------------------------------
140 mappedVariableContent = ""
141 strDeclareHeader = ""
142 strDeclareCallback = ""
145 for index in listIndex:
146 texts["index"] = index
148 entry_infos = Manager.GetEntryInfos(index)
149 texts["EntryName"] = entry_infos["name"]
150 values = Manager.GetCurrentEntry(index)
151 callbacks = Manager.HasCurrentEntryCallbacks(index)
152 if index in variablelist:
153 strIndex += "\n/* index 0x%(index)04X : Mapped variable %(EntryName)s */\n"%texts
155 strIndex += "\n/* index 0x%(index)04X : %(EntryName)s. */\n"%texts
158 if type(values) != ListType:
159 subentry_infos = Manager.GetSubentryInfos(index, 0)
160 typename = Manager.GetTypeName(subentry_infos["type"])
161 typeinfos = GetValidTypeInfos(typename)
162 texts["subIndexType"] = typeinfos[0]
163 texts["suffixe"] = typeinfos[1]
164 if typeinfos[2] == "visible_string":
165 texts["value"] = "\"%s\""%values
166 texts["comment"] = ""
167 elif typeinfos[2] == "domain":
168 texts["value"] = "\"%s\""%''.join(["\\x%2.2x"%ord(char) for char in value])
169 texts["comment"] = ""
171 texts["value"] = "0x%X"%values
172 texts["comment"] = "\t/* %s */"%str(values)
173 if index in variablelist:
174 texts["name"] = FormatName(subentry_infos["name"])
175 strDeclareHeader += "extern %(subIndexType)s %(name)s%(suffixe)s;\t\t/* Mapped at index 0x%(index)04X, subindex 0x00*/\n"%texts
177 strDeclareHeader += "extern ODCallback_t %(name)s_callbacks[];\t\t/* Callbacks of index0x%(index)04X */\n"%texts
178 mappedVariableContent += "%(subIndexType)s %(name)s%(suffixe)s = %(value)s;\t\t/* Mapped at index 0x%(index)04X, subindex 0x00 */\n"%texts
180 strIndex += " %(subIndexType)s %(NodeName)s_obj%(index)04X%(suffixe)s = %(value)s;%(comment)s\n"%texts
183 subentry_infos = Manager.GetSubentryInfos(index, 0)
184 typename = Manager.GetTypeName(subentry_infos["type"])
185 typeinfos = GetValidTypeInfos(typename)
186 texts["value"] = values[0]
187 texts["subIndexType"] = typeinfos[0]
188 strIndex += " %(subIndexType)s %(NodeName)s_highestSubIndex_obj%(index)04X = %(value)d; /* number of subindex - 1*/\n"%texts
190 # Entry type is RECORD
191 if entry_infos["struct"] & OD_IdenticalSubindexes:
192 subentry_infos = Manager.GetSubentryInfos(index, 1)
193 typename = Manager.GetTypeName(subentry_infos["type"])
194 typeinfos = GetValidTypeInfos(typename)
195 texts["subIndexType"] = typeinfos[0]
196 texts["suffixe"] = typeinfos[1]
197 texts["length"] = values[0]
198 if index in variablelist:
199 texts["name"] = FormatName(entry_infos["name"])
200 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
202 strDeclareHeader += "extern ODCallback_t %(name)s_callbacks[];\t\t/* Callbacks of index0x%(index)04X */\n"%texts
203 mappedVariableContent += "%(subIndexType)s %(name)s[] =\t\t/* Mapped at index 0x%(index)04X, subindex 0x01 - 0x%(length)02X */\n {\n"%texts
204 for subIndex, value in enumerate(values):
208 if subIndex == len(values)-1:
210 if typeinfos[2] == "visible_string":
211 value = "\"%s\""%value
212 elif typeinfos[2] == "domain":
213 value = "\"%s\""%''.join(["\\x%2.2x"%ord(char) for char in value])
215 comment = "\t/* %s */"%str(value)
217 mappedVariableContent += " %s%s%s\n"%(value, sep, comment)
218 mappedVariableContent += " };\n"
220 strIndex += " %(subIndexType)s %(NodeName)s_obj%(index)04X[] = \n {\n"%texts
221 for subIndex, value in enumerate(values):
225 if subIndex == len(values)-1:
227 if typeinfos[2] == "visible_string":
228 value = "\"%s\""%value
229 elif typeinfos[2] == "domain":
230 value = "\"%s\""%''.join(["\\x%2.2x"%ord(char) for char in value])
232 comment = "\t/* %s */"%str(value)
234 strIndex += " %s%s%s\n"%(value, sep, comment)
238 texts["parent"] = FormatName(entry_infos["name"])
239 # Entry type is ARRAY
240 for subIndex, value in enumerate(values):
241 texts["subIndex"] = subIndex
243 subentry_infos = Manager.GetSubentryInfos(index, subIndex)
244 typename = Manager.GetTypeName(subentry_infos["type"])
245 typeinfos = GetValidTypeInfos(typename)
246 texts["subIndexType"] = typeinfos[0]
247 texts["suffixe"] = typeinfos[1]
248 if typeinfos[2] == "visible_string":
249 texts["value"] = "\"%s\""%value
250 texts["comment"] = ""
251 elif typeinfos[2] == "domain":
252 texts["value"] = "\"%s\""%''.join(["\\x%2.2x"%ord(char) for char in value])
253 texts["comment"] = ""
255 texts["value"] = "0x%X"%value
256 texts["comment"] = "\t/* %s */"%str(value)
257 texts["name"] = FormatName(subentry_infos["name"])
258 if index in variablelist:
259 strDeclareHeader += "extern %(subIndexType)s %(parent)s_%(name)s%(suffixe)s;\t\t/* Mapped at index 0x%(index)04X, subindex 0x%(subIndex)02X */\n"%texts
260 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
262 strIndex += " %(subIndexType)s %(NodeName)s_obj%(index)04X_%(name)s%(suffixe)s = %(value)s;%(comment)s\n"%texts
264 strDeclareHeader += "extern ODCallback_t %(parent)s_callbacks[];\t\t/* Callbacks of index0x%(index)04X */\n"%texts
266 # Generating Dictionary C++ entry
268 if index in variablelist:
269 name = FormatName(entry_infos["name"])
271 name = "%(NodeName)s_Index%(index)04X"%texts
272 strIndex += " ODCallback_t %s_callbacks[] = \n {\n"%name
273 for subIndex in xrange(len(values)):
274 strIndex += " NULL,\n"
276 indexCallbacks[index] = "*callbacks = %s_callbacks; "%name
278 indexCallbacks[index] = ""
279 strIndex += " subindex %(NodeName)s_Index%(index)04X[] = \n {\n"%texts
280 for subIndex in xrange(len(values)):
281 subentry_infos = Manager.GetSubentryInfos(index, subIndex)
282 if subIndex < len(values) - 1:
286 typename = Manager.GetTypeName(subentry_infos["type"])
287 typeinfos = GetValidTypeInfos(typename)
289 if entry_infos["struct"] & OD_MultipleSubindexes:
290 name = "%(NodeName)s_highestSubIndex_obj%(index)04X"%texts
291 elif index in variablelist:
292 name = FormatName(subentry_infos["name"])
294 name = FormatName("%s_obj%04X"%(texts["NodeName"], texts["index"]))
295 elif entry_infos["struct"] & OD_IdenticalSubindexes:
296 if index in variablelist:
297 name = "%s[%d]"%(FormatName(entry_infos["name"]), subIndex - 1)
299 name = "%s_obj%04X[%d]"%(texts["NodeName"], texts["index"], subIndex - 1)
301 if index in variablelist:
302 name = FormatName("%s_%s"%(entry_infos["name"],subentry_infos["name"]))
304 name = "%s_obj%04X_%s"%(texts["NodeName"], texts["index"], FormatName(subentry_infos["name"]))
305 if typeinfos[2] in ["visible_string", "domain"]:
306 sizeof = str(len(values[subIndex]))
308 sizeof = "sizeof (%s)"%typeinfos[0]
309 params = Manager.GetCurrentParamsEntry(index, subIndex)
314 strIndex += " { %s%s, %s, %s, (void*)&%s }%s\n"%(subentry_infos["access"].upper(),save,typeinfos[2],sizeof,name,sep)
316 indexContents[index] = strIndex
318 #-------------------------------------------------------------------------------
319 # Declaration of Particular Parameters
320 #-------------------------------------------------------------------------------
322 if 0x1006 not in communicationlist:
323 entry_infos = Manager.GetEntryInfos(0x1006)
324 texts["EntryName"] = entry_infos["name"]
325 indexContents[0x1006] = """\n/* index 0x1006 : %(EntryName)s */
326 UNS32 %(NodeName)s_obj1006 = 0x0; /* 0 */
329 if 0x1016 in communicationlist:
330 texts["nombre"] = Manager.GetCurrentEntry(0x1016, 0)
333 entry_infos = Manager.GetEntryInfos(0x1016)
334 texts["EntryName"] = entry_infos["name"]
335 indexContents[0x1016] = """\n/* index 0x1016 : %(EntryName)s */
336 UNS8 %(NodeName)s_highestSubIndex_obj1016 = 0;
337 UNS32 %(NodeName)s_obj1016[]={0};
339 if texts["nombre"] > 0:
340 strTimers = "TIMER_HANDLE %(NodeName)s_heartBeatTimers[%(nombre)d] = {TIMER_NONE,};\n"%texts
342 strTimers = "TIMER_HANDLE %(NodeName)s_heartBeatTimers[1];\n"%texts
344 if 0x1017 not in communicationlist:
345 entry_infos = Manager.GetEntryInfos(0x1017)
346 texts["EntryName"] = entry_infos["name"]
347 indexContents[0x1017] = """\n/* index 0x1017 : %(EntryName)s */
348 UNS16 %(NodeName)s_obj1017 = 0x0; /* 0 */
351 #-------------------------------------------------------------------------------
352 # Declaration of navigation in the Object Dictionary
353 #-------------------------------------------------------------------------------
356 strDeclareSwitch = ""
359 for index_cat in index_categories:
360 quick_index[index_cat] = {}
361 for cat, idx_min, idx_max in categories:
362 quick_index[index_cat][cat] = 0
364 for i, index in enumerate(listIndex):
365 texts["index"] = index
366 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
367 strDeclareSwitch += " case 0x%04X: i = %d;%sbreak;\n"%(index, i, indexCallbacks[index])
368 for cat, idx_min, idx_max in categories:
369 if idx_min <= index <= idx_max:
370 quick_index["lastIndex"][cat] = i
371 if quick_index["firstIndex"][cat] == 0:
372 quick_index["firstIndex"][cat] = i
375 texts["maxPDOtransmit"] = max(1, maxPDOtransmit)
376 for index_cat in index_categories:
377 strQuickIndex += "\nquick_index %s_%s = {\n"%(texts["NodeName"], index_cat)
379 for i, (cat, idx_min, idx_max) in enumerate(categories):
380 if i == len(categories) - 1:
382 strQuickIndex += " %d%s /* %s */\n"%(quick_index[index_cat][cat],sep,cat)
383 strQuickIndex += "};\n"
385 #-------------------------------------------------------------------------------
387 #-------------------------------------------------------------------------------
389 fileContent = generated_tag + """
394 /**************************************************************************/
395 /* Declaration of the mapped variables */
396 /**************************************************************************/
397 """ + mappedVariableContent
400 /**************************************************************************/
401 /* Declaration of the value range types */
402 /**************************************************************************/
403 """ + valueRangeContent
406 /**************************************************************************/
408 /**************************************************************************/
409 /* node_id default value.*/
410 UNS8 %(NodeName)s_bDeviceNodeId = 0x%(NodeID)02X;
412 /**************************************************************************/
413 /* Array of message processing information */
415 const UNS8 %(NodeName)s_iam_a_slave = %(iam_a_slave)d;
418 fileContent += strTimers
422 $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
426 $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
429 contentlist = indexContents.keys()
431 for index in contentlist:
432 fileContent += indexContents[index]
435 const indextable %(NodeName)s_objdict[] =
438 fileContent += strDeclareIndex
441 const indextable * %(NodeName)s_scanIndexOD (UNS16 wIndex, UNS32 * errorCode, ODCallback_t **callbacks)
447 fileContent += strDeclareSwitch
448 fileContent += """ default:
449 *errorCode = OD_NO_SUCH_OBJECT;
452 *errorCode = OD_SUCCESSFUL;
453 return &%(NodeName)s_objdict[i];
456 /* To count at which received SYNC a PDO must be sent.
457 * Even if no pdoTransmit are defined, at least one entry is computed
458 * for compilations issues.
460 UNS8 %(NodeName)s_count_sync[%(maxPDOtransmit)d] = {0,};
462 fileContent += strQuickIndex
464 UNS16 %(NodeName)s_ObjdictSize = sizeof(%(NodeName)s_objdict)/sizeof(%(NodeName)s_objdict[0]);
466 CO_Data %(NodeName)s_Data = CANOPEN_NODE_DATA_INITIALIZER(%(NodeName)s);
470 #-------------------------------------------------------------------------------
471 # Write Header File Content
472 #-------------------------------------------------------------------------------
474 texts["file_include_name"] = headerfilepath.replace(".", "_").upper()
475 HeaderFileContent = generated_tag + """
476 #ifndef %(file_include_name)s
477 #define %(file_include_name)s
481 /* Prototypes of function provided by object dictionnary */
482 UNS32 %(NodeName)s_valueRangeTest (UNS8 typeValue, void * value);
483 const indextable * %(NodeName)s_scanIndexOD (UNS16 wIndex, UNS32 * errorCode, ODCallback_t **callbacks);
485 /* Master node data struct */
486 extern CO_Data %(NodeName)s_Data;
488 HeaderFileContent += strDeclareHeader
490 HeaderFileContent += "\n#endif // %(file_include_name)s\n"%texts
492 return fileContent,HeaderFileContent
494 #-------------------------------------------------------------------------------
496 #-------------------------------------------------------------------------------
498 def GenerateFile(filepath, manager):
500 headerfilepath = os.path.splitext(filepath)[0]+".h"
501 content, header = GenerateFileContent(manager, os.path.split(headerfilepath)[1])
502 WriteFile(filepath, content)
503 WriteFile(headerfilepath, header)
505 except ValueError, message:
506 return "Unable to Generate C File\n%s"%message