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"""
41 default_string_size = 10
43 # Format a string for making a C++ variable
45 wordlist = [word for word in word_model.findall(name) if word != '']
46 return "_".join(wordlist)
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]
53 result = type_model.match(typename)
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
65 size = max(size, len(item))
67 size = max(size, int(values[1]))
68 typeinfos = ("UNS8", size, "visible_string", False)
69 elif values[0] == "DOMAIN":
72 size = max(size, len(item))
73 typeinfos = ("UNS8*", size, "domain", False)
74 elif values[0] == "BOOLEAN":
75 typeinfos = ("UNS8", None, "boolean", False)
77 raise ValueError, """!!! %s isn't a valid type for CanFestival."""%typename
78 internal_types[typename] = typeinfos
80 raise ValueError, """!!! %s isn't a valid type for CanFestival."""%typename
83 def WriteFile(filepath, content):
84 cfile = open(filepath,"w")
88 def GenerateFileContent(Node, headerfilepath):
91 global default_string_size
94 texts["maxPDOtransmit"] = 0
95 texts["NodeName"] = Node.GetNodeName()
96 texts["NodeID"] = Node.GetNodeID()
97 texts["NodeType"] = Node.GetNodeType()
98 texts["Description"] = Node.GetNodeDescription()
99 texts["iam_a_slave"] = 0
100 if (texts["NodeType"] == "slave"):
101 texts["iam_a_slave"] = 1
103 default_string_size = Node.GetDefaultStringSize()
105 # Compiling lists of indexes
106 rangelist = [idx for idx in Node.GetIndexes() if 0 <= idx <= 0x260]
107 listIndex = [idx for idx in Node.GetIndexes() if 0x1000 <= idx <= 0xFFFF]
108 communicationlist = [idx for idx in Node.GetIndexes() if 0x1000 <= idx <= 0x11FF]
109 sdolist = [idx for idx in Node.GetIndexes() if 0x1200 <= idx <= 0x12FF]
110 pdolist = [idx for idx in Node.GetIndexes() if 0x1400 <= idx <= 0x1BFF]
111 variablelist = [idx for idx in Node.GetIndexes() if 0x2000 <= idx <= 0xBFFF]
113 #-------------------------------------------------------------------------------
114 # Declaration of the value range types
115 #-------------------------------------------------------------------------------
117 valueRangeContent = ""
118 strDefine = "\n#define valueRange_EMC 0x9F /* Type for index 0x1003 subindex 0x00 (only set of value 0 is possible) */"
119 strSwitch = """ case valueRange_EMC:
120 if (*(UNS8*)value != (UNS8)0) return OD_VALUE_RANGE_EXCEEDED;
122 internal_types["valueRange_EMC"] = ("UNS8", "", "valueRange_EMC", True)
124 for index in rangelist:
125 rangename = Node.GetEntryName(index)
126 result = range_model.match(rangename)
129 typeindex = Node.GetEntry(index, 1)
130 typename = Node.GetTypeName(typeindex)
131 typeinfos = GetValidTypeInfos(typename)
132 internal_types[rangename] = (typeinfos[0], typeinfos[1], "valueRange_%d"%num)
133 minvalue = Node.GetEntry(index, 2)
134 maxvalue = Node.GetEntry(index, 3)
135 strDefine += "\n#define valueRange_%d 0x%02X /* Type %s, %s < value < %s */"%(num,index,typeinfos[0],str(minvalue),str(maxvalue))
136 strSwitch += " case valueRange_%d:\n"%(num)
137 if typeinfos[3] and minvalue <= 0:
138 strSwitch += " /* Negative or null low limit ignored because of unsigned type */;\n"
140 strSwitch += " if (*(%s*)value < (%s)%s) return OD_VALUE_TOO_LOW;\n"%(typeinfos[0],typeinfos[0],str(minvalue))
141 strSwitch += " if (*(%s*)value > (%s)%s) return OD_VALUE_TOO_HIGH;\n"%(typeinfos[0],typeinfos[0],str(maxvalue))
142 strSwitch += " break;\n"
144 valueRangeContent += strDefine
145 valueRangeContent += "\nUNS32 %(NodeName)s_valueRangeTest (UNS8 typeValue, void * value)\n{"%texts
146 valueRangeContent += "\n switch (typeValue) {\n"
147 valueRangeContent += strSwitch
148 valueRangeContent += " }\n return 0;\n}\n"
150 #-------------------------------------------------------------------------------
151 # Creation of the mapped variables and object dictionary
152 #-------------------------------------------------------------------------------
154 mappedVariableContent = ""
155 strDeclareHeader = ""
156 strDeclareCallback = ""
159 for index in listIndex:
160 texts["index"] = index
162 entry_infos = Node.GetEntryInfos(index)
163 texts["EntryName"] = entry_infos["name"].encode('ascii','replace')
164 values = Node.GetEntry(index)
165 callbacks = Node.HasEntryCallbacks(index)
166 if index in variablelist:
167 strIndex += "\n/* index 0x%(index)04X : Mapped variable %(EntryName)s */\n"%texts
169 strIndex += "\n/* index 0x%(index)04X : %(EntryName)s. */\n"%texts
172 if type(values) != ListType:
173 subentry_infos = Node.GetSubentryInfos(index, 0)
174 typename = Node.GetTypeName(subentry_infos["type"])
175 typeinfos = GetValidTypeInfos(typename, [values])
176 texts["subIndexType"] = typeinfos[0]
177 if typeinfos[1] is not None:
178 texts["suffixe"] = "[%d]"%typeinfos[1]
180 texts["suffixe"] = ""
181 if typeinfos[2] == "visible_string":
182 texts["value"] = "\"%s\""%values
183 texts["comment"] = ""
184 elif typeinfos[2] == "domain":
185 texts["value"] = "\"%s\""%''.join(["\\x%2.2x"%ord(char) for char in value])
186 texts["comment"] = ""
188 texts["value"] = "0x%X"%values
189 texts["comment"] = "\t/* %s */"%str(values)
190 if index in variablelist:
191 texts["name"] = FormatName(subentry_infos["name"])
192 strDeclareHeader += "extern %(subIndexType)s %(name)s%(suffixe)s;\t\t/* Mapped at index 0x%(index)04X, subindex 0x00*/\n"%texts
194 strDeclareHeader += "extern ODCallback_t %(name)s_callbacks[];\t\t/* Callbacks of index0x%(index)04X */\n"%texts
195 mappedVariableContent += "%(subIndexType)s %(name)s%(suffixe)s = %(value)s;\t\t/* Mapped at index 0x%(index)04X, subindex 0x00 */\n"%texts
197 strIndex += " %(subIndexType)s %(NodeName)s_obj%(index)04X%(suffixe)s = %(value)s;%(comment)s\n"%texts
200 subentry_infos = Node.GetSubentryInfos(index, 0)
201 typename = Node.GetTypeName(subentry_infos["type"])
202 typeinfos = GetValidTypeInfos(typename)
206 texts["value"] = values[0]
207 texts["subIndexType"] = typeinfos[0]
208 strIndex += " %(subIndexType)s %(NodeName)s_highestSubIndex_obj%(index)04X = %(value)d; /* number of subindex - 1*/\n"%texts
210 # Entry type is RECORD
211 if entry_infos["struct"] & OD_IdenticalSubindexes:
212 subentry_infos = Node.GetSubentryInfos(index, 1)
213 typename = Node.GetTypeName(subentry_infos["type"])
214 typeinfos = GetValidTypeInfos(typename, values[1:])
215 texts["subIndexType"] = typeinfos[0]
216 if typeinfos[1] is not None:
217 texts["suffixe"] = "[%d]"%typeinfos[1]
219 texts["suffixe"] = ""
220 texts["length"] = values[0]
221 if index in variablelist:
222 texts["name"] = FormatName(entry_infos["name"])
223 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
225 strDeclareHeader += "extern ODCallback_t %(name)s_callbacks[];\t\t/* Callbacks of index0x%(index)04X */\n"%texts
226 mappedVariableContent += "%(subIndexType)s %(name)s[] =\t\t/* Mapped at index 0x%(index)04X, subindex 0x01 - 0x%(length)02X */\n {\n"%texts
227 for subIndex, value in enumerate(values):
231 if subIndex == len(values)-1:
233 if typeinfos[2] == "visible_string":
234 value = "\"%s%s\""%(value, "\\0" * (default_string_size - len(value)))
235 elif typeinfos[2] == "domain":
236 value = "\"%s\""%''.join(["\\x%2.2x"%ord(char) for char in value])
238 comment = "\t/* %s */"%str(value)
240 mappedVariableContent += " %s%s%s\n"%(value, sep, comment)
241 mappedVariableContent += " };\n"
243 strIndex += " %(subIndexType)s %(NodeName)s_obj%(index)04X[] = \n {\n"%texts
244 for subIndex, value in enumerate(values):
248 if subIndex == len(values)-1:
250 if typeinfos[2] == "visible_string":
251 value = "\"%s%s\""%(value, "\\0" * (default_string_size - len(value)))
252 elif typeinfos[2] == "domain":
253 value = "\"%s\""%''.join(["\\x%2.2x"%ord(char) for char in value])
255 comment = "\t/* %s */"%str(value)
257 strIndex += " %s%s%s\n"%(value, sep, comment)
261 texts["parent"] = FormatName(entry_infos["name"])
262 # Entry type is ARRAY
263 for subIndex, value in enumerate(values):
264 texts["subIndex"] = subIndex
266 subentry_infos = Node.GetSubentryInfos(index, subIndex)
267 typename = Node.GetTypeName(subentry_infos["type"])
268 typeinfos = GetValidTypeInfos(typename, [values[subIndex]])
269 texts["subIndexType"] = typeinfos[0]
270 if typeinfos[1] is not None:
271 texts["suffixe"] = "[%d]"%typeinfos[1]
273 texts["suffixe"] = ""
274 if typeinfos[2] == "visible_string":
275 texts["value"] = "\"%s%s\""%(value, "\\0" * (default_string_size - len(value)))
276 texts["comment"] = ""
277 elif typeinfos[2] == "domain":
278 texts["value"] = "\"%s\""%''.join(["\\x%2.2x"%ord(char) for char in value])
279 texts["comment"] = ""
281 texts["value"] = "0x%X"%value
282 texts["comment"] = "\t/* %s */"%str(value)
283 texts["name"] = FormatName(subentry_infos["name"])
284 if index in variablelist:
285 strDeclareHeader += "extern %(subIndexType)s %(parent)s_%(name)s%(suffixe)s;\t\t/* Mapped at index 0x%(index)04X, subindex 0x%(subIndex)02X */\n"%texts
286 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
288 strIndex += " %(subIndexType)s %(NodeName)s_obj%(index)04X_%(name)s%(suffixe)s = %(value)s;%(comment)s\n"%texts
290 strDeclareHeader += "extern ODCallback_t %(parent)s_callbacks[];\t\t/* Callbacks of index0x%(index)04X */\n"%texts
292 # Generating Dictionary C++ entry
294 if index in variablelist:
295 name = FormatName(entry_infos["name"])
297 name = "%(NodeName)s_Index%(index)04X"%texts
298 strIndex += " ODCallback_t %s_callbacks[] = \n {\n"%name
299 for subIndex in xrange(len(values)):
300 strIndex += " NULL,\n"
302 indexCallbacks[index] = "*callbacks = %s_callbacks; "%name
304 indexCallbacks[index] = ""
305 strIndex += " subindex %(NodeName)s_Index%(index)04X[] = \n {\n"%texts
306 for subIndex in xrange(len(values)):
307 subentry_infos = Node.GetSubentryInfos(index, subIndex)
308 if subIndex < len(values) - 1:
312 typename = Node.GetTypeName(subentry_infos["type"])
313 if entry_infos["struct"] & OD_IdenticalSubindexes:
314 typeinfos = GetValidTypeInfos(typename, values)
316 typeinfos = GetValidTypeInfos(typename, [values[subIndex]])
319 typeinfos = GetValidTypeInfos("valueRange_EMC")
320 if entry_infos["struct"] & OD_MultipleSubindexes:
321 name = "%(NodeName)s_highestSubIndex_obj%(index)04X"%texts
322 elif index in variablelist:
323 name = FormatName(subentry_infos["name"])
325 name = FormatName("%s_obj%04X"%(texts["NodeName"], texts["index"]))
326 elif entry_infos["struct"] & OD_IdenticalSubindexes:
327 if index in variablelist:
328 name = "%s[%d]"%(FormatName(entry_infos["name"]), subIndex - 1)
330 name = "%s_obj%04X[%d]"%(texts["NodeName"], texts["index"], subIndex - 1)
332 if index in variablelist:
333 name = FormatName("%s_%s"%(entry_infos["name"],subentry_infos["name"]))
335 name = "%s_obj%04X_%s"%(texts["NodeName"], texts["index"], FormatName(subentry_infos["name"]))
336 if typeinfos[2] == "visible_string":
337 sizeof = str(max(len(values[subIndex]), default_string_size))
338 elif typeinfos[2] == "domain":
339 sizeof = str(len(values[subIndex]))
341 sizeof = "sizeof (%s)"%typeinfos[0]
342 params = Node.GetParamsEntry(index, subIndex)
347 strIndex += " { %s%s, %s, %s, (void*)&%s }%s\n"%(subentry_infos["access"].upper(),save,typeinfos[2],sizeof,name,sep)
349 indexContents[index] = strIndex
351 #-------------------------------------------------------------------------------
352 # Declaration of Particular Parameters
353 #-------------------------------------------------------------------------------
355 if 0x1003 not in communicationlist:
356 entry_infos = Node.GetEntryInfos(0x1003)
357 texts["EntryName"] = entry_infos["name"]
358 indexContents[0x1003] = """\n/* index 0x1003 : %(EntryName)s */
359 UNS8 %(NodeName)s_highestSubIndex_obj1003 = 0; /* number of subindex - 1*/
360 UNS32 %(NodeName)s_obj1003[] =
364 ODCallback_t %(NodeName)s_Index1003_callbacks[] =
369 subindex %(NodeName)s_Index1003[] =
371 { RW, valueRange_EMC, sizeof (UNS8), (void*)&%(NodeName)s_highestSubIndex_obj1003 },
372 { RO, uint32, sizeof (UNS32), (void*)&%(NodeName)s_obj1003[0] }
376 if 0x1005 not in communicationlist:
377 entry_infos = Node.GetEntryInfos(0x1005)
378 texts["EntryName"] = entry_infos["name"]
379 indexContents[0x1005] = """\n/* index 0x1005 : %(EntryName)s */
380 UNS32 %(NodeName)s_obj1005 = 0x0; /* 0 */
383 if 0x1006 not in communicationlist:
384 entry_infos = Node.GetEntryInfos(0x1006)
385 texts["EntryName"] = entry_infos["name"]
386 indexContents[0x1006] = """\n/* index 0x1006 : %(EntryName)s */
387 UNS32 %(NodeName)s_obj1006 = 0x0; /* 0 */
390 if 0x1014 not in communicationlist:
391 entry_infos = Node.GetEntryInfos(0x1014)
392 texts["EntryName"] = entry_infos["name"]
393 indexContents[0x1014] = """\n/* index 0x1014 : %(EntryName)s */
394 UNS32 %(NodeName)s_obj1014 = 0x0; /* 0 */
397 if 0x1016 in communicationlist:
398 texts["heartBeatTimers_number"] = Node.GetEntry(0x1016, 0)
400 texts["heartBeatTimers_number"] = 0
401 entry_infos = Node.GetEntryInfos(0x1016)
402 texts["EntryName"] = entry_infos["name"]
403 indexContents[0x1016] = """\n/* index 0x1016 : %(EntryName)s */
404 UNS8 %(NodeName)s_highestSubIndex_obj1016 = 0;
405 UNS32 %(NodeName)s_obj1016[]={0};
408 if 0x1017 not in communicationlist:
409 entry_infos = Node.GetEntryInfos(0x1017)
410 texts["EntryName"] = entry_infos["name"]
411 indexContents[0x1017] = """\n/* index 0x1017 : %(EntryName)s */
412 UNS16 %(NodeName)s_obj1017 = 0x0; /* 0 */
415 #-------------------------------------------------------------------------------
416 # Declaration of navigation in the Object Dictionary
417 #-------------------------------------------------------------------------------
420 strDeclareSwitch = ""
423 for index_cat in index_categories:
424 quick_index[index_cat] = {}
425 for cat, idx_min, idx_max in categories:
426 quick_index[index_cat][cat] = 0
428 for i, index in enumerate(listIndex):
429 texts["index"] = index
430 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
431 strDeclareSwitch += " case 0x%04X: i = %d;%sbreak;\n"%(index, i, indexCallbacks[index])
432 for cat, idx_min, idx_max in categories:
433 if idx_min <= index <= idx_max:
434 quick_index["lastIndex"][cat] = i
435 if quick_index["firstIndex"][cat] == 0:
436 quick_index["firstIndex"][cat] = i
439 texts["maxPDOtransmit"] = max(1, maxPDOtransmit)
440 for index_cat in index_categories:
441 strQuickIndex += "\nquick_index %s_%s = {\n"%(texts["NodeName"], index_cat)
443 for i, (cat, idx_min, idx_max) in enumerate(categories):
444 if i == len(categories) - 1:
446 strQuickIndex += " %d%s /* %s */\n"%(quick_index[index_cat][cat],sep,cat)
447 strQuickIndex += "};\n"
449 #-------------------------------------------------------------------------------
451 #-------------------------------------------------------------------------------
453 fileContent = generated_tag + """
458 /**************************************************************************/
459 /* Declaration of the mapped variables */
460 /**************************************************************************/
461 """ + mappedVariableContent
464 /**************************************************************************/
465 /* Declaration of the value range types */
466 /**************************************************************************/
467 """ + valueRangeContent
470 /**************************************************************************/
472 /**************************************************************************/
473 /* node_id default value.*/
474 UNS8 %(NodeName)s_bDeviceNodeId = 0x%(NodeID)02X;
476 /**************************************************************************/
477 /* Array of message processing information */
479 const UNS8 %(NodeName)s_iam_a_slave = %(iam_a_slave)d;
482 if texts["heartBeatTimers_number"] > 0:
483 fileContent += "TIMER_HANDLE %(NodeName)s_heartBeatTimers[%(heartBeatTimers_number)d] = {TIMER_NONE,};\n"%texts
485 fileContent += "TIMER_HANDLE %(NodeName)s_heartBeatTimers[1];\n"%texts
489 $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
493 $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
496 contentlist = indexContents.keys()
498 for index in contentlist:
499 fileContent += indexContents[index]
502 const indextable %(NodeName)s_objdict[] =
505 fileContent += strDeclareIndex
508 const indextable * %(NodeName)s_scanIndexOD (UNS16 wIndex, UNS32 * errorCode, ODCallback_t **callbacks)
514 fileContent += strDeclareSwitch
515 fileContent += """ default:
516 *errorCode = OD_NO_SUCH_OBJECT;
519 *errorCode = OD_SUCCESSFUL;
520 return &%(NodeName)s_objdict[i];
524 * To count at which received SYNC a PDO must be sent.
525 * Even if no pdoTransmit are defined, at least one entry is computed
526 * for compilations issues.
528 s_PDO_status %(NodeName)s_PDO_status[%(maxPDOtransmit)d] = {"""%texts
530 fileContent += ",".join(["s_PDO_status_Initializer"]*texts["maxPDOtransmit"]) + """};
533 fileContent += strQuickIndex
535 UNS16 %(NodeName)s_ObjdictSize = sizeof(%(NodeName)s_objdict)/sizeof(%(NodeName)s_objdict[0]);
537 CO_Data %(NodeName)s_Data = CANOPEN_NODE_DATA_INITIALIZER(%(NodeName)s);
541 #-------------------------------------------------------------------------------
542 # Write Header File Content
543 #-------------------------------------------------------------------------------
545 texts["file_include_name"] = headerfilepath.replace(".", "_").upper()
546 HeaderFileContent = generated_tag + """
547 #ifndef %(file_include_name)s
548 #define %(file_include_name)s
552 /* Prototypes of function provided by object dictionnary */
553 UNS32 %(NodeName)s_valueRangeTest (UNS8 typeValue, void * value);
554 const indextable * %(NodeName)s_scanIndexOD (UNS16 wIndex, UNS32 * errorCode, ODCallback_t **callbacks);
556 /* Master node data struct */
557 extern CO_Data %(NodeName)s_Data;
559 HeaderFileContent += strDeclareHeader
561 HeaderFileContent += "\n#endif // %(file_include_name)s\n"%texts
563 return fileContent,HeaderFileContent
565 #-------------------------------------------------------------------------------
567 #-------------------------------------------------------------------------------
569 def GenerateFile(filepath, node):
571 headerfilepath = os.path.splitext(filepath)[0]+".h"
572 content, header = GenerateFileContent(node, os.path.split(headerfilepath)[1])
573 WriteFile(filepath, content)
574 WriteFile(headerfilepath, header)
576 except ValueError, message:
577 return "Unable to Generate C File\n%s"%message