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 for index in listIndex:
141 texts["index"] = index
143 entry_infos = Manager.GetEntryInfos(index)
144 texts["EntryName"] = entry_infos["name"].encode('ascii','replace')
145 values = Manager.GetCurrentEntry(index)
146 callbacks = Manager.HasCurrentEntryCallbacks(index)
147 if index in variablelist:
148 strIndex += "\n/* index 0x%(index)04X : Mapped variable %(EntryName)s */\n"%texts
150 strIndex += "\n/* index 0x%(index)04X : %(EntryName)s. */\n"%texts
153 if type(values) != ListType:
154 subentry_infos = Manager.GetSubentryInfos(index, 0)
155 typename = Manager.GetTypeName(subentry_infos["type"])
156 typeinfos = GetValidTypeInfos(typename)
157 texts["subIndexType"] = typeinfos[0]
158 texts["suffixe"] = typeinfos[1]
159 if typeinfos[2] == "visible_string":
160 texts["value"] = "\"%s\""%values
161 texts["comment"] = ""
162 elif typeinfos[2] == "domain":
163 texts["value"] = "\"%s\""%''.join(["\\x%2.2x"%ord(char) for char in value])
164 texts["comment"] = ""
166 texts["value"] = "0x%X"%values
167 texts["comment"] = "\t/* %s */"%str(values)
168 if index in variablelist:
169 texts["name"] = FormatName(subentry_infos["name"])
170 strDeclareHeader += "extern %(subIndexType)s %(name)s%(suffixe)s;\t\t/* Mapped at index 0x%(index)04X, subindex 0x00*/\n"%texts
172 strDeclareHeader += "extern ODCallback_t %(name)s_callbacks[];\t\t/* Callbacks of index0x%(index)04X */\n"%texts
173 mappedVariableContent += "%(subIndexType)s %(name)s%(suffixe)s = %(value)s;\t\t/* Mapped at index 0x%(index)04X, subindex 0x00 */\n"%texts
175 strIndex += " %(subIndexType)s %(NodeName)s_obj%(index)04X%(suffixe)s = %(value)s;%(comment)s\n"%texts
178 subentry_infos = Manager.GetSubentryInfos(index, 0)
179 typename = Manager.GetTypeName(subentry_infos["type"])
180 typeinfos = GetValidTypeInfos(typename)
181 texts["value"] = values[0]
182 texts["subIndexType"] = typeinfos[0]
183 strIndex += " %(subIndexType)s %(NodeName)s_highestSubIndex_obj%(index)04X = %(value)d; /* number of subindex - 1*/\n"%texts
185 # Entry type is RECORD
186 if entry_infos["struct"] & OD_IdenticalSubindexes:
187 subentry_infos = Manager.GetSubentryInfos(index, 1)
188 typename = Manager.GetTypeName(subentry_infos["type"])
189 typeinfos = GetValidTypeInfos(typename)
190 texts["subIndexType"] = typeinfos[0]
191 texts["suffixe"] = typeinfos[1]
192 texts["length"] = values[0]
193 if index in variablelist:
194 texts["name"] = FormatName(entry_infos["name"])
195 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
197 strDeclareHeader += "extern ODCallback_t %(name)s_callbacks[];\t\t/* Callbacks of index0x%(index)04X */\n"%texts
198 mappedVariableContent += "%(subIndexType)s %(name)s[] =\t\t/* Mapped at index 0x%(index)04X, subindex 0x01 - 0x%(length)02X */\n {\n"%texts
199 for subIndex, value in enumerate(values):
203 if subIndex == len(values)-1:
205 if typeinfos[2] == "visible_string":
206 value = "\"%s\""%value
207 elif typeinfos[2] == "domain":
208 value = "\"%s\""%''.join(["\\x%2.2x"%ord(char) for char in value])
210 comment = "\t/* %s */"%str(value)
212 mappedVariableContent += " %s%s%s\n"%(value, sep, comment)
213 mappedVariableContent += " };\n"
215 strIndex += " %(subIndexType)s %(NodeName)s_obj%(index)04X[] = \n {\n"%texts
216 for subIndex, value in enumerate(values):
220 if subIndex == len(values)-1:
222 if typeinfos[2] == "visible_string":
223 value = "\"%s\""%value
224 elif typeinfos[2] == "domain":
225 value = "\"%s\""%''.join(["\\x%2.2x"%ord(char) for char in value])
227 comment = "\t/* %s */"%str(value)
229 strIndex += " %s%s%s\n"%(value, sep, comment)
233 texts["parent"] = FormatName(entry_infos["name"])
234 # Entry type is ARRAY
235 for subIndex, value in enumerate(values):
236 texts["subIndex"] = subIndex
238 subentry_infos = Manager.GetSubentryInfos(index, subIndex)
239 typename = Manager.GetTypeName(subentry_infos["type"])
240 typeinfos = GetValidTypeInfos(typename)
241 texts["subIndexType"] = typeinfos[0]
242 texts["suffixe"] = typeinfos[1]
243 if typeinfos[2] == "visible_string":
244 texts["value"] = "\"%s\""%value
245 texts["comment"] = ""
246 elif typeinfos[2] == "domain":
247 texts["value"] = "\"%s\""%''.join(["\\x%2.2x"%ord(char) for char in value])
248 texts["comment"] = ""
250 texts["value"] = "0x%X"%value
251 texts["comment"] = "\t/* %s */"%str(value)
252 texts["name"] = FormatName(subentry_infos["name"])
253 if index in variablelist:
254 strDeclareHeader += "extern %(subIndexType)s %(parent)s_%(name)s%(suffixe)s;\t\t/* Mapped at index 0x%(index)04X, subindex 0x%(subIndex)02X */\n"%texts
255 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
257 strIndex += " %(subIndexType)s %(NodeName)s_obj%(index)04X_%(name)s%(suffixe)s = %(value)s;%(comment)s\n"%texts
259 strDeclareHeader += "extern ODCallback_t %(parent)s_callbacks[];\t\t/* Callbacks of index0x%(index)04X */\n"%texts
261 # Generating Dictionary C++ entry
263 if index in variablelist:
264 name = FormatName(entry_infos["name"])
266 name = "%(NodeName)s_Index%(index)04X"%texts
267 strIndex += " ODCallback_t %s_callbacks[] = \n {\n"%name
268 for subIndex in xrange(len(values)):
269 strIndex += " NULL,\n"
271 indexCallbacks[index] = "*callbacks = %s_callbacks; "%name
273 indexCallbacks[index] = ""
274 strIndex += " subindex %(NodeName)s_Index%(index)04X[] = \n {\n"%texts
275 for subIndex in xrange(len(values)):
276 subentry_infos = Manager.GetSubentryInfos(index, subIndex)
277 if subIndex < len(values) - 1:
281 typename = Manager.GetTypeName(subentry_infos["type"])
282 typeinfos = GetValidTypeInfos(typename)
284 if entry_infos["struct"] & OD_MultipleSubindexes:
285 name = "%(NodeName)s_highestSubIndex_obj%(index)04X"%texts
286 elif index in variablelist:
287 name = FormatName(subentry_infos["name"])
289 name = FormatName("%s_obj%04X"%(texts["NodeName"], texts["index"]))
290 elif entry_infos["struct"] & OD_IdenticalSubindexes:
291 if index in variablelist:
292 name = "%s[%d]"%(FormatName(entry_infos["name"]), subIndex - 1)
294 name = "%s_obj%04X[%d]"%(texts["NodeName"], texts["index"], subIndex - 1)
296 if index in variablelist:
297 name = FormatName("%s_%s"%(entry_infos["name"],subentry_infos["name"]))
299 name = "%s_obj%04X_%s"%(texts["NodeName"], texts["index"], FormatName(subentry_infos["name"]))
300 if typeinfos[2] in ["visible_string", "domain"]:
301 sizeof = str(len(values[subIndex]))
303 sizeof = "sizeof (%s)"%typeinfos[0]
304 params = Manager.GetCurrentParamsEntry(index, subIndex)
309 strIndex += " { %s%s, %s, %s, (void*)&%s }%s\n"%(subentry_infos["access"].upper(),save,typeinfos[2],sizeof,name,sep)
311 indexContents[index] = strIndex
313 #-------------------------------------------------------------------------------
314 # Declaration of Particular Parameters
315 #-------------------------------------------------------------------------------
317 if 0x1006 not in communicationlist:
318 entry_infos = Manager.GetEntryInfos(0x1006)
319 texts["EntryName"] = entry_infos["name"]
320 indexContents[0x1006] = """\n/* index 0x1006 : %(EntryName)s */
321 UNS32 %(NodeName)s_obj1006 = 0x0; /* 0 */
324 if 0x1016 in communicationlist:
325 texts["nombre"] = Manager.GetCurrentEntry(0x1016, 0)
328 entry_infos = Manager.GetEntryInfos(0x1016)
329 texts["EntryName"] = entry_infos["name"]
330 indexContents[0x1016] = """\n/* index 0x1016 : %(EntryName)s */
331 UNS8 %(NodeName)s_highestSubIndex_obj1016 = 0;
332 UNS32 %(NodeName)s_obj1016[]={0};
334 if texts["nombre"] > 0:
335 strTimers = "TIMER_HANDLE %(NodeName)s_heartBeatTimers[%(nombre)d] = {TIMER_NONE,};\n"%texts
337 strTimers = "TIMER_HANDLE %(NodeName)s_heartBeatTimers[1];\n"%texts
339 if 0x1017 not in communicationlist:
340 entry_infos = Manager.GetEntryInfos(0x1017)
341 texts["EntryName"] = entry_infos["name"]
342 indexContents[0x1017] = """\n/* index 0x1017 : %(EntryName)s */
343 UNS16 %(NodeName)s_obj1017 = 0x0; /* 0 */
346 #-------------------------------------------------------------------------------
347 # Declaration of navigation in the Object Dictionary
348 #-------------------------------------------------------------------------------
351 strDeclareSwitch = ""
354 for index_cat in index_categories:
355 quick_index[index_cat] = {}
356 for cat, idx_min, idx_max in categories:
357 quick_index[index_cat][cat] = 0
359 for i, index in enumerate(listIndex):
360 texts["index"] = index
361 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
362 strDeclareSwitch += " case 0x%04X: i = %d;%sbreak;\n"%(index, i, indexCallbacks[index])
363 for cat, idx_min, idx_max in categories:
364 if idx_min <= index <= idx_max:
365 quick_index["lastIndex"][cat] = i
366 if quick_index["firstIndex"][cat] == 0:
367 quick_index["firstIndex"][cat] = i
370 texts["maxPDOtransmit"] = max(1, maxPDOtransmit)
371 for index_cat in index_categories:
372 strQuickIndex += "\nquick_index %s_%s = {\n"%(texts["NodeName"], index_cat)
374 for i, (cat, idx_min, idx_max) in enumerate(categories):
375 if i == len(categories) - 1:
377 strQuickIndex += " %d%s /* %s */\n"%(quick_index[index_cat][cat],sep,cat)
378 strQuickIndex += "};\n"
380 #-------------------------------------------------------------------------------
382 #-------------------------------------------------------------------------------
384 fileContent = generated_tag + """
389 /**************************************************************************/
390 /* Declaration of the mapped variables */
391 /**************************************************************************/
392 """ + mappedVariableContent
395 /**************************************************************************/
396 /* Declaration of the value range types */
397 /**************************************************************************/
398 """ + valueRangeContent
401 /**************************************************************************/
403 /**************************************************************************/
404 /* node_id default value.*/
405 UNS8 %(NodeName)s_bDeviceNodeId = 0x%(NodeID)02X;
407 /**************************************************************************/
408 /* Array of message processing information */
410 const UNS8 %(NodeName)s_iam_a_slave = %(iam_a_slave)d;
413 fileContent += strTimers
417 $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
421 $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
424 contentlist = indexContents.keys()
426 for index in contentlist:
427 fileContent += indexContents[index]
430 const indextable %(NodeName)s_objdict[] =
433 fileContent += strDeclareIndex
436 const indextable * %(NodeName)s_scanIndexOD (UNS16 wIndex, UNS32 * errorCode, ODCallback_t **callbacks)
442 fileContent += strDeclareSwitch
443 fileContent += """ default:
444 *errorCode = OD_NO_SUCH_OBJECT;
447 *errorCode = OD_SUCCESSFUL;
448 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 s_PDO_status %(NodeName)s_PDO_status[%(maxPDOtransmit)d] = {"""%texts
458 fileContent += ",".join(["s_PDO_staus_Initializer"]*texts["maxPDOtransmit"]) + """};
461 fileContent += strQuickIndex
463 UNS16 %(NodeName)s_ObjdictSize = sizeof(%(NodeName)s_objdict)/sizeof(%(NodeName)s_objdict[0]);
465 CO_Data %(NodeName)s_Data = CANOPEN_NODE_DATA_INITIALIZER(%(NodeName)s);
469 #-------------------------------------------------------------------------------
470 # Write Header File Content
471 #-------------------------------------------------------------------------------
473 texts["file_include_name"] = headerfilepath.replace(".", "_").upper()
474 HeaderFileContent = generated_tag + """
475 #ifndef %(file_include_name)s
476 #define %(file_include_name)s
480 /* Prototypes of function provided by object dictionnary */
481 UNS32 %(NodeName)s_valueRangeTest (UNS8 typeValue, void * value);
482 const indextable * %(NodeName)s_scanIndexOD (UNS16 wIndex, UNS32 * errorCode, ODCallback_t **callbacks);
484 /* Master node data struct */
485 extern CO_Data %(NodeName)s_Data;
487 HeaderFileContent += strDeclareHeader
489 HeaderFileContent += "\n#endif // %(file_include_name)s\n"%texts
491 return fileContent,HeaderFileContent
493 #-------------------------------------------------------------------------------
495 #-------------------------------------------------------------------------------
497 def GenerateFile(filepath, manager):
499 headerfilepath = os.path.splitext(filepath)[0]+".h"
500 content, header = GenerateFileContent(manager, os.path.split(headerfilepath)[1])
501 WriteFile(filepath, content)
502 WriteFile(headerfilepath, header)
504 except ValueError, message:
505 return "Unable to Generate C File\n%s"%message