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"] = ""
168 texts["value"] = "0x%X"%values
169 texts["comment"] = "\t/* %s */"%str(values)
170 if index in variablelist:
171 texts["name"] = FormatName(subentry_infos["name"])
172 strDeclareHeader += "extern %(subIndexType)s %(name)s%(suffixe)s;\t\t/* Mapped at index 0x%(index)04X, subindex 0x00*/\n"%texts
174 strDeclareHeader += "extern ODCallback_t %(name)s_callbacks[];\t\t/* Callbacks of index0x%(index)04X */\n"%texts
175 mappedVariableContent += "%(subIndexType)s %(name)s%(suffixe)s = %(value)s;\t\t/* Mapped at index 0x%(index)04X, subindex 0x00 */\n"%texts
177 strIndex += " %(subIndexType)s %(NodeName)s_obj%(index)04X%(suffixe)s = %(value)s;%(comment)s\n"%texts
180 subentry_infos = Manager.GetSubentryInfos(index, 0)
181 typename = Manager.GetTypeName(subentry_infos["type"])
182 typeinfos = GetValidTypeInfos(typename)
183 texts["value"] = values[0]
184 texts["subIndexType"] = typeinfos[0]
185 strIndex += " %(subIndexType)s %(NodeName)s_highestSubIndex_obj%(index)04X = %(value)d; /* number of subindex - 1*/\n"%texts
187 # Entry type is RECORD
188 if entry_infos["struct"] & OD_IdenticalSubindexes:
189 subentry_infos = Manager.GetSubentryInfos(index, 1)
190 typename = Manager.GetTypeName(subentry_infos["type"])
191 typeinfos = GetValidTypeInfos(typename)
192 texts["subIndexType"] = typeinfos[0]
193 texts["suffixe"] = typeinfos[1]
194 texts["length"] = values[0]
195 if index in variablelist:
196 texts["name"] = FormatName(entry_infos["name"])
197 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
199 strDeclareHeader += "extern ODCallback_t %(name)s_callbacks[];\t\t/* Callbacks of index0x%(index)04X */\n"%texts
200 mappedVariableContent += "%(subIndexType)s %(name)s[] =\t\t/* Mapped at index 0x%(index)04X, subindex 0x01 - 0x%(length)02X */\n {\n"%texts
201 for subIndex, value in enumerate(values):
205 if subIndex == len(values)-1:
207 if typeinfos[2] == "visible_string":
208 value = "\"%s\""%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"] = ""
247 texts["value"] = "0x%X"%value
248 texts["comment"] = "\t/* %s */"%str(value)
249 texts["name"] = FormatName(subentry_infos["name"])
250 if index in variablelist:
251 strDeclareHeader += "extern %(subIndexType)s %(parent)s_%(name)s%(suffixe)s;\t\t/* Mapped at index 0x%(index)04X, subindex 0x%(subIndex)02X */\n"%texts
252 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
254 strIndex += " %(subIndexType)s %(NodeName)s_obj%(index)04X_%(name)s%(suffixe)s = %(value)s;%(comment)s\n"%texts
256 strDeclareHeader += "extern ODCallback_t %(parent)s_callbacks[];\t\t/* Callbacks of index0x%(index)04X */\n"%texts
258 # Generating Dictionary C++ entry
260 if index in variablelist:
261 name = FormatName(entry_infos["name"])
263 name = "%(NodeName)s_Index%(index)04X"%texts
264 strIndex += " ODCallback_t %s_callbacks[] = \n {\n"%name
265 for subIndex in xrange(len(values)):
266 strIndex += " NULL,\n"
268 indexCallbacks[index] = "*callbacks = %s_callbacks; "%name
270 indexCallbacks[index] = ""
271 strIndex += " subindex %(NodeName)s_Index%(index)04X[] = \n {\n"%texts
272 for subIndex in xrange(len(values)):
273 subentry_infos = Manager.GetSubentryInfos(index, subIndex)
274 if subIndex < len(values) - 1:
278 typename = Manager.GetTypeName(subentry_infos["type"])
279 typeinfos = GetValidTypeInfos(typename)
281 if entry_infos["struct"] & OD_MultipleSubindexes:
282 name = "%(NodeName)s_highestSubIndex_obj%(index)04X"%texts
283 elif index in variablelist:
284 name = FormatName(subentry_infos["name"])
286 name = FormatName("%s_obj%04X"%(texts["NodeName"], texts["index"]))
287 elif entry_infos["struct"] & OD_IdenticalSubindexes:
288 if index in variablelist:
289 name = "%s[%d]"%(FormatName(entry_infos["name"]), subIndex - 1)
291 name = "%s_obj%04X[%d]"%(texts["NodeName"], texts["index"], subIndex - 1)
293 if index in variablelist:
294 name = FormatName("%s_%s"%(entry_infos["name"],subentry_infos["name"]))
296 name = "%s_obj%04X_%s"%(texts["NodeName"], texts["index"], FormatName(subentry_infos["name"]))
297 if typeinfos[2] in ["visible_string", "domain"]:
298 sizeof = str(len(values[subIndex]))
300 sizeof = "sizeof (%s)"%typeinfos[0]
301 params = Manager.GetCurrentParamsEntry(index, subIndex)
306 strIndex += " { %s%s, %s, %s, (void*)&%s }%s\n"%(subentry_infos["access"].upper(),save,typeinfos[2],sizeof,name,sep)
308 indexContents[index] = strIndex
310 #-------------------------------------------------------------------------------
311 # Declaration of Particular Parameters
312 #-------------------------------------------------------------------------------
314 if 0x1006 not in communicationlist:
315 entry_infos = Manager.GetEntryInfos(0x1006)
316 texts["EntryName"] = entry_infos["name"]
317 indexContents[0x1006] = """\n/* index 0x1006 : %(EntryName)s */
318 UNS32 %(NodeName)s_obj1006 = 0x0; /* 0 */
321 if 0x1016 in communicationlist:
322 texts["nombre"] = Manager.GetCurrentEntry(0x1016, 0)
325 entry_infos = Manager.GetEntryInfos(0x1016)
326 texts["EntryName"] = entry_infos["name"]
327 indexContents[0x1016] = """\n/* index 0x1016 : %(EntryName)s */
328 UNS8 %(NodeName)s_highestSubIndex_obj1016 = 0;
329 UNS32 %(NodeName)s_obj1016[]={0};
331 if texts["nombre"] > 0:
332 strTimers = "TIMER_HANDLE %(NodeName)s_heartBeatTimers[%(nombre)d] = {TIMER_NONE,};\n"%texts
334 strTimers = "TIMER_HANDLE %(NodeName)s_heartBeatTimers[1];\n"%texts
336 if 0x1017 not in communicationlist:
337 entry_infos = Manager.GetEntryInfos(0x1017)
338 texts["EntryName"] = entry_infos["name"]
339 indexContents[0x1017] = """\n/* index 0x1017 : %(EntryName)s */
340 UNS16 %(NodeName)s_obj1017 = 0x0; /* 0 */
343 #-------------------------------------------------------------------------------
344 # Declaration of navigation in the Object Dictionary
345 #-------------------------------------------------------------------------------
348 strDeclareSwitch = ""
351 for index_cat in index_categories:
352 quick_index[index_cat] = {}
353 for cat, idx_min, idx_max in categories:
354 quick_index[index_cat][cat] = 0
356 for i, index in enumerate(listIndex):
357 texts["index"] = index
358 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
359 strDeclareSwitch += " case 0x%04X: i = %d;%sbreak;\n"%(index, i, indexCallbacks[index])
360 for cat, idx_min, idx_max in categories:
361 if idx_min <= index <= idx_max:
362 quick_index["lastIndex"][cat] = i
363 if quick_index["firstIndex"][cat] == 0:
364 quick_index["firstIndex"][cat] = i
367 texts["maxPDOtransmit"] = max(1, maxPDOtransmit)
368 for index_cat in index_categories:
369 strQuickIndex += "\nquick_index %s_%s = {\n"%(texts["NodeName"], index_cat)
371 for i, (cat, idx_min, idx_max) in enumerate(categories):
372 if i == len(categories) - 1:
374 strQuickIndex += " %d%s /* %s */\n"%(quick_index[index_cat][cat],sep,cat)
375 strQuickIndex += "};\n"
377 #-------------------------------------------------------------------------------
379 #-------------------------------------------------------------------------------
381 fileContent = generated_tag + """
386 /**************************************************************************/
387 /* Declaration of the mapped variables */
388 /**************************************************************************/
389 """ + mappedVariableContent
392 /**************************************************************************/
393 /* Declaration of the value range types */
394 /**************************************************************************/
395 """ + valueRangeContent
398 /**************************************************************************/
400 /**************************************************************************/
401 /* node_id default value.*/
402 UNS8 %(NodeName)s_bDeviceNodeId = 0x%(NodeID)02X;
404 /**************************************************************************/
405 /* Array of message processing information */
407 const UNS8 %(NodeName)s_iam_a_slave = %(iam_a_slave)d;
410 fileContent += strTimers
414 $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
418 $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
421 contentlist = indexContents.keys()
423 for index in contentlist:
424 fileContent += indexContents[index]
427 const indextable %(NodeName)s_objdict[] =
430 fileContent += strDeclareIndex
433 const indextable * %(NodeName)s_scanIndexOD (UNS16 wIndex, UNS32 * errorCode, ODCallback_t **callbacks)
439 fileContent += strDeclareSwitch
440 fileContent += """ default:
441 *errorCode = OD_NO_SUCH_OBJECT;
444 *errorCode = OD_SUCCESSFUL;
445 return &%(NodeName)s_objdict[i];
448 /* To count at which received SYNC a PDO must be sent.
449 * Even if no pdoTransmit are defined, at least one entry is computed
450 * for compilations issues.
452 UNS8 %(NodeName)s_count_sync[%(maxPDOtransmit)d] = {0,};
454 fileContent += strQuickIndex
456 UNS16 %(NodeName)s_ObjdictSize = sizeof(%(NodeName)s_objdict)/sizeof(%(NodeName)s_objdict[0]);
458 CO_Data %(NodeName)s_Data = CANOPEN_NODE_DATA_INITIALIZER(%(NodeName)s);
462 #-------------------------------------------------------------------------------
463 # Write Header File Content
464 #-------------------------------------------------------------------------------
466 HeaderFileContent = generated_tag + """
469 /* Prototypes of function provided by object dictionnary */
470 UNS32 %(NodeName)s_valueRangeTest (UNS8 typeValue, void * value);
471 const indextable * %(NodeName)s_scanIndexOD (UNS16 wIndex, UNS32 * errorCode, ODCallback_t **callbacks);
473 /* Master node data struct */
474 extern CO_Data %(NodeName)s_Data;
477 HeaderFileContent += strDeclareHeader
479 return fileContent,HeaderFileContent
481 #-------------------------------------------------------------------------------
483 #-------------------------------------------------------------------------------
485 def GenerateFile(filepath, manager):
487 headerfilepath = os.path.splitext(filepath)[0]+".h"
488 content, header = GenerateFileContent(manager, os.path.split(headerfilepath)[1])
489 WriteFile(filepath, content)
490 WriteFile(headerfilepath, header)
492 except ValueError, message:
493 return "Unable to Generate C File\n%s"%message