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 if typeinfos[2] not in ["visible_string", "domain"]:
79 internal_types[typename] = typeinfos
81 raise ValueError, """!!! %s isn't a valid type for CanFestival."""%typename
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"):
92 return "0x%X"%value, "\t/* %s */"%str(value)
94 def WriteFile(filepath, content):
95 cfile = open(filepath,"w")
99 def GenerateFileContent(Node, headerfilepath, pointers_dict = {}):
101 pointers_dict = {(Idx,Sidx):"VariableName",...}
104 global internal_types
105 global default_string_size
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
117 default_string_size = Node.GetDefaultStringSize()
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]
127 #-------------------------------------------------------------------------------
128 # Declaration of the value range types
129 #-------------------------------------------------------------------------------
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;
136 internal_types["valueRange_EMC"] = ("UNS8", "", "valueRange_EMC", True)
138 for index in rangelist:
139 rangename = Node.GetEntryName(index)
140 result = range_model.match(rangename)
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"
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"
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"
164 #-------------------------------------------------------------------------------
165 # Creation of the mapped variables and object dictionary
166 #-------------------------------------------------------------------------------
168 mappedVariableContent = ""
169 pointedVariableContent = ""
170 strDeclareHeader = ""
171 strDeclareCallback = ""
174 for index in listIndex:
175 texts["index"] = index
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
184 strIndex += "\n/* index 0x%(index)04X : %(EntryName)s. */\n"%texts
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 if typename is "DOMAIN" and index in variablelist:
193 raise ValueError("\nDomain variable not initialized\nindex : 0x%04X\nsubindex 0x00"%index)
194 texts["subIndexType"] = typeinfos[0]
195 if typeinfos[1] is not None:
196 texts["suffixe"] = "[%d]"%typeinfos[1]
198 texts["suffixe"] = ""
199 texts["value"], texts["comment"] = ComputeValue(typeinfos[2], values)
200 if index in variablelist:
201 texts["name"] = FormatName(subentry_infos["name"])
202 strDeclareHeader += "extern %(subIndexType)s %(name)s%(suffixe)s;\t\t/* Mapped at index 0x%(index)04X, subindex 0x00*/\n"%texts
203 mappedVariableContent += "%(subIndexType)s %(name)s%(suffixe)s = %(value)s;\t\t/* Mapped at index 0x%(index)04X, subindex 0x00 */\n"%texts
205 strIndex += " %(subIndexType)s %(NodeName)s_obj%(index)04X%(suffixe)s = %(value)s;%(comment)s\n"%texts
208 subentry_infos = Node.GetSubentryInfos(index, 0)
209 typename = Node.GetTypeName(subentry_infos["type"])
210 typeinfos = GetValidTypeInfos(typename)
214 texts["value"] = values[0]
215 texts["subIndexType"] = typeinfos[0]
216 strIndex += " %(subIndexType)s %(NodeName)s_highestSubIndex_obj%(index)04X = %(value)d; /* number of subindex - 1*/\n"%texts
218 # Entry type is RECORD
219 if entry_infos["struct"] & OD_IdenticalSubindexes:
220 subentry_infos = Node.GetSubentryInfos(index, 1)
221 typename = Node.GetTypeName(subentry_infos["type"])
222 typeinfos = GetValidTypeInfos(typename, values[1:])
223 texts["subIndexType"] = typeinfos[0]
224 if typeinfos[1] is not None:
225 texts["suffixe"] = "[%d]"%typeinfos[1]
226 texts["type_suffixe"] = "*"
228 texts["suffixe"] = ""
229 texts["type_suffixe"] = ""
230 texts["length"] = values[0]
231 if index in variablelist:
232 texts["name"] = FormatName(entry_infos["name"])
233 strDeclareHeader += "extern %(subIndexType)s%(type_suffixe)s %(name)s[];\t\t/* Mapped at index 0x%(index)04X, subindex 0x01 - 0x%(length)02X */\n"%texts
234 mappedVariableContent += "%(subIndexType)s%(type_suffixe)s %(name)s[] =\t\t/* Mapped at index 0x%(index)04X, subindex 0x01 - 0x%(length)02X */\n {\n"%texts
235 for subIndex, value in enumerate(values):
238 if subIndex == len(values)-1:
240 value, comment = ComputeValue(typeinfos[2], value)
241 if len(value) is 2 and typename is "DOMAIN":
242 raise ValueError("\nDomain variable not initialized\nindex : 0x%04X\nsubindex 0x%02X"%(index, subIndex))
243 mappedVariableContent += " %s%s%s\n"%(value, sep, comment)
244 mappedVariableContent += " };\n"
246 strIndex += " %(subIndexType)s%(type_suffixe)s %(NodeName)s_obj%(index)04X[] = \n {\n"%texts
247 for subIndex, value in enumerate(values):
250 if subIndex == len(values)-1:
252 value, comment = ComputeValue(typeinfos[2], value)
253 strIndex += " %s%s%s\n"%(value, sep, comment)
257 texts["parent"] = FormatName(entry_infos["name"])
258 # Entry type is ARRAY
259 for subIndex, value in enumerate(values):
260 texts["subIndex"] = subIndex
262 subentry_infos = Node.GetSubentryInfos(index, subIndex)
263 typename = Node.GetTypeName(subentry_infos["type"])
264 typeinfos = GetValidTypeInfos(typename, [values[subIndex]])
265 texts["subIndexType"] = typeinfos[0]
266 if typeinfos[1] is not None:
267 texts["suffixe"] = "[%d]"%typeinfos[1]
269 texts["suffixe"] = ""
270 texts["value"], texts["comment"] = ComputeValue(typeinfos[2], value)
271 texts["name"] = FormatName(subentry_infos["name"])
272 if index in variablelist:
273 strDeclareHeader += "extern %(subIndexType)s %(parent)s_%(name)s%(suffixe)s;\t\t/* Mapped at index 0x%(index)04X, subindex 0x%(subIndex)02X */\n"%texts
274 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
276 strIndex += " %(subIndexType)s %(NodeName)s_obj%(index)04X_%(name)s%(suffixe)s = %(value)s;%(comment)s\n"%texts
278 # Generating Dictionary C++ entry
280 if index in variablelist:
281 name = FormatName(entry_infos["name"])
283 name = "%(NodeName)s_Index%(index)04X"%texts
284 strIndex += " ODCallback_t %s_callbacks[] = \n {\n"%name
285 for subIndex in xrange(len(values)):
286 strIndex += " NULL,\n"
288 indexCallbacks[index] = "*callbacks = %s_callbacks; "%name
290 indexCallbacks[index] = ""
291 strIndex += " subindex %(NodeName)s_Index%(index)04X[] = \n {\n"%texts
292 for subIndex in xrange(len(values)):
293 subentry_infos = Node.GetSubentryInfos(index, subIndex)
294 if subIndex < len(values) - 1:
298 typename = Node.GetTypeName(subentry_infos["type"])
299 if entry_infos["struct"] & OD_IdenticalSubindexes:
300 typeinfos = GetValidTypeInfos(typename, values[1:])
302 typeinfos = GetValidTypeInfos(typename, [values[subIndex]])
305 typeinfos = GetValidTypeInfos("valueRange_EMC")
306 if entry_infos["struct"] & OD_MultipleSubindexes:
307 name = "%(NodeName)s_highestSubIndex_obj%(index)04X"%texts
308 elif index in variablelist:
309 name = FormatName(subentry_infos["name"])
311 name = FormatName("%s_obj%04X"%(texts["NodeName"], texts["index"]))
312 elif entry_infos["struct"] & OD_IdenticalSubindexes:
313 if index in variablelist:
314 name = "%s[%d]"%(FormatName(entry_infos["name"]), subIndex - 1)
316 name = "%s_obj%04X[%d]"%(texts["NodeName"], texts["index"], subIndex - 1)
318 if index in variablelist:
319 name = FormatName("%s_%s"%(entry_infos["name"],subentry_infos["name"]))
321 name = "%s_obj%04X_%s"%(texts["NodeName"], texts["index"], FormatName(subentry_infos["name"]))
322 if typeinfos[2] == "visible_string":
323 sizeof = str(max(len(values[subIndex]), default_string_size))
324 elif typeinfos[2] == "domain":
325 sizeof = str(len(values[subIndex]))
327 sizeof = "sizeof (%s)"%typeinfos[0]
328 params = Node.GetParamsEntry(index, subIndex)
333 strIndex += " { %s%s, %s, %s, (void*)&%s }%s\n"%(subentry_infos["access"].upper(),save,typeinfos[2],sizeof,name,sep)
334 pointer_name = pointers_dict.get((index, subIndex), None)
335 if pointer_name is not None:
336 pointedVariableContent += "%s* %s = &%s;\n"%(typeinfos[0], pointer_name, name)
338 indexContents[index] = strIndex
340 #-------------------------------------------------------------------------------
341 # Declaration of Particular Parameters
342 #-------------------------------------------------------------------------------
344 if 0x1003 not in communicationlist:
345 entry_infos = Node.GetEntryInfos(0x1003)
346 texts["EntryName"] = entry_infos["name"]
347 indexContents[0x1003] = """\n/* index 0x1003 : %(EntryName)s */
348 UNS8 %(NodeName)s_highestSubIndex_obj1003 = 0; /* number of subindex - 1*/
349 UNS32 %(NodeName)s_obj1003[] =
353 ODCallback_t %(NodeName)s_Index1003_callbacks[] =
358 subindex %(NodeName)s_Index1003[] =
360 { RW, valueRange_EMC, sizeof (UNS8), (void*)&%(NodeName)s_highestSubIndex_obj1003 },
361 { RO, uint32, sizeof (UNS32), (void*)&%(NodeName)s_obj1003[0] }
365 if 0x1005 not in communicationlist:
366 entry_infos = Node.GetEntryInfos(0x1005)
367 texts["EntryName"] = entry_infos["name"]
368 indexContents[0x1005] = """\n/* index 0x1005 : %(EntryName)s */
369 UNS32 %(NodeName)s_obj1005 = 0x0; /* 0 */
372 if 0x1006 not in communicationlist:
373 entry_infos = Node.GetEntryInfos(0x1006)
374 texts["EntryName"] = entry_infos["name"]
375 indexContents[0x1006] = """\n/* index 0x1006 : %(EntryName)s */
376 UNS32 %(NodeName)s_obj1006 = 0x0; /* 0 */
379 if 0x1014 not in communicationlist:
380 entry_infos = Node.GetEntryInfos(0x1014)
381 texts["EntryName"] = entry_infos["name"]
382 indexContents[0x1014] = """\n/* index 0x1014 : %(EntryName)s */
383 UNS32 %(NodeName)s_obj1014 = 0x80 + 0x%(NodeID)02X; /* 128 + NodeID */
386 if 0x1016 in communicationlist:
387 texts["heartBeatTimers_number"] = Node.GetEntry(0x1016, 0)
389 texts["heartBeatTimers_number"] = 0
390 entry_infos = Node.GetEntryInfos(0x1016)
391 texts["EntryName"] = entry_infos["name"]
392 indexContents[0x1016] = """\n/* index 0x1016 : %(EntryName)s */
393 UNS8 %(NodeName)s_highestSubIndex_obj1016 = 0;
394 UNS32 %(NodeName)s_obj1016[]={0};
397 if 0x1017 not in communicationlist:
398 entry_infos = Node.GetEntryInfos(0x1017)
399 texts["EntryName"] = entry_infos["name"]
400 indexContents[0x1017] = """\n/* index 0x1017 : %(EntryName)s */
401 UNS16 %(NodeName)s_obj1017 = 0x0; /* 0 */
404 #-------------------------------------------------------------------------------
405 # Declaration of navigation in the Object Dictionary
406 #-------------------------------------------------------------------------------
409 strDeclareSwitch = ""
412 for index_cat in index_categories:
413 quick_index[index_cat] = {}
414 for cat, idx_min, idx_max in categories:
415 quick_index[index_cat][cat] = 0
417 for i, index in enumerate(listIndex):
418 texts["index"] = index
419 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
420 strDeclareSwitch += " case 0x%04X: i = %d;%sbreak;\n"%(index, i, indexCallbacks[index])
421 for cat, idx_min, idx_max in categories:
422 if idx_min <= index <= idx_max:
423 quick_index["lastIndex"][cat] = i
424 if quick_index["firstIndex"][cat] == 0:
425 quick_index["firstIndex"][cat] = i
428 texts["maxPDOtransmit"] = max(1, maxPDOtransmit)
429 for index_cat in index_categories:
430 strQuickIndex += "\nconst quick_index %s_%s = {\n"%(texts["NodeName"], index_cat)
432 for i, (cat, idx_min, idx_max) in enumerate(categories):
433 if i == len(categories) - 1:
435 strQuickIndex += " %d%s /* %s */\n"%(quick_index[index_cat][cat],sep,cat)
436 strQuickIndex += "};\n"
438 #-------------------------------------------------------------------------------
440 #-------------------------------------------------------------------------------
442 fileContent = generated_tag + """
447 /**************************************************************************/
448 /* Declaration of mapped variables */
449 /**************************************************************************/
450 """ + mappedVariableContent
453 /**************************************************************************/
454 /* Declaration of value range types */
455 /**************************************************************************/
456 """ + valueRangeContent
459 /**************************************************************************/
461 /**************************************************************************/
462 /* node_id default value.*/
463 UNS8 %(NodeName)s_bDeviceNodeId = 0x%(NodeID)02X;
465 /**************************************************************************/
466 /* Array of message processing information */
468 const UNS8 %(NodeName)s_iam_a_slave = %(iam_a_slave)d;
471 if texts["heartBeatTimers_number"] > 0:
472 declaration = "TIMER_HANDLE %(NodeName)s_heartBeatTimers[%(heartBeatTimers_number)d]"%texts
473 initializer = "{TIMER_NONE" + ",TIMER_NONE" * (texts["heartBeatTimers_number"] - 1) + "}"
474 fileContent += declaration + " = " + initializer + ";\n"
476 fileContent += "TIMER_HANDLE %(NodeName)s_heartBeatTimers[1];\n"%texts
480 $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
484 $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
487 contentlist = indexContents.keys()
489 for index in contentlist:
490 fileContent += indexContents[index]
493 /**************************************************************************/
494 /* Declaration of pointed variables */
495 /**************************************************************************/
496 """ + pointedVariableContent
499 const indextable %(NodeName)s_objdict[] =
502 fileContent += strDeclareIndex
505 const indextable * %(NodeName)s_scanIndexOD (UNS16 wIndex, UNS32 * errorCode, ODCallback_t **callbacks)
511 fileContent += strDeclareSwitch
512 fileContent += """ default:
513 *errorCode = OD_NO_SUCH_OBJECT;
516 *errorCode = OD_SUCCESSFUL;
517 return &%(NodeName)s_objdict[i];
521 * To count at which received SYNC a PDO must be sent.
522 * Even if no pdoTransmit are defined, at least one entry is computed
523 * for compilations issues.
525 s_PDO_status %(NodeName)s_PDO_status[%(maxPDOtransmit)d] = {"""%texts
527 fileContent += ",".join(["s_PDO_status_Initializer"]*texts["maxPDOtransmit"]) + """};
530 fileContent += strQuickIndex
532 const UNS16 %(NodeName)s_ObjdictSize = sizeof(%(NodeName)s_objdict)/sizeof(%(NodeName)s_objdict[0]);
534 CO_Data %(NodeName)s_Data = CANOPEN_NODE_DATA_INITIALIZER(%(NodeName)s);
538 #-------------------------------------------------------------------------------
539 # Write Header File Content
540 #-------------------------------------------------------------------------------
542 texts["file_include_name"] = headerfilepath.replace(".", "_").upper()
543 HeaderFileContent = generated_tag + """
544 #ifndef %(file_include_name)s
545 #define %(file_include_name)s
549 /* Prototypes of function provided by object dictionnary */
550 UNS32 %(NodeName)s_valueRangeTest (UNS8 typeValue, void * value);
551 const indextable * %(NodeName)s_scanIndexOD (UNS16 wIndex, UNS32 * errorCode, ODCallback_t **callbacks);
553 /* Master node data struct */
554 extern CO_Data %(NodeName)s_Data;
556 HeaderFileContent += strDeclareHeader
558 HeaderFileContent += "\n#endif // %(file_include_name)s\n"%texts
560 return fileContent,HeaderFileContent
562 #-------------------------------------------------------------------------------
564 #-------------------------------------------------------------------------------
566 def GenerateFile(filepath, node, pointers_dict = {}):
568 headerfilepath = os.path.splitext(filepath)[0]+".h"
569 content, header = GenerateFileContent(node, os.path.split(headerfilepath)[1], pointers_dict)
570 WriteFile(filepath, content)
571 WriteFile(headerfilepath, header)
573 except ValueError, message:
574 return "Unable to Generate C File\n%s"%message