]> rtime.felk.cvut.cz Git - CanFestival-3.git/blob - objdictgen/gen_cfile.py
Bugs on C File generating corrected
[CanFestival-3.git] / objdictgen / gen_cfile.py
1 #!/usr/bin/env python
2 # -*- coding: utf-8 -*-
3
4 #This file is part of CanFestival, a library implementing CanOpen Stack. 
5 #
6 #Copyright (C): Edouard TISSERANT and Francis DUPIN
7 #
8 #See COPYING file for copyrights details.
9 #
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.
14 #
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.
19 #
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
23
24 from node import *
25 from types import *
26
27 import re, os
28
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]*)\]')
32
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"]
37
38 generated_tag = """\n/* File generated by gen_cfile.py. Should not be modified. */\n"""
39
40 internal_types = {}
41
42 # Format a string for making a C++ variable
43 def FormatName(name):
44     wordlist = [word for word in word_model.findall(name) if word != '']
45     result = ''
46     sep = ''
47     for word in wordlist:
48         result += "%s%s"%(sep,word)
49         sep = '_'
50     return result
51
52 # Extract the informations from a given type name
53 def GetValidTypeInfos(typename):
54     if typename in internal_types:
55         return internal_types[typename]
56     else:
57         result = type_model.match(typename)
58         if result:
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":
67                 if values[1] == "":
68                     typeinfos = ("UNS8", "[10]", "visible_string")
69                 else:
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")
75             else:
76                 raise ValueError, """!!! %s isn't a valid type for CanFestival."""%typename
77             internal_types[typename] = typeinfos
78         else:
79             raise ValueError, """!!! %s isn't a valid type for CanFestival."""%typename
80     return typeinfos
81
82 def WriteFile(filepath, content):
83     cfile = open(filepath,"w")
84     cfile.write(content)
85     cfile.close()
86
87 def GenerateFileContent(Manager, headerfilepath):
88     global type
89     global internal_types
90     texts = {}
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
96     
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)]
104
105 #-------------------------------------------------------------------------------
106 #                       Declaration of the value range types
107 #-------------------------------------------------------------------------------    
108     
109     valueRangeContent = ""
110     strDefine = ""
111     strSwitch = ""
112     num = 0
113     for index in rangelist:
114         rangename = Manager.GetEntryName(index)
115         result = range_model.match(rangename)
116         if result:
117             num += 1
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)
129
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"
135
136 #-------------------------------------------------------------------------------
137 #            Creation of the mapped variables and object dictionary
138 #-------------------------------------------------------------------------------
139
140     mappedVariableContent = ""
141     strDeclareHeader = ""
142     strDeclareCallback = ""
143     indexContents = {}
144     indexCallbacks = {}
145     for index in listIndex:
146         texts["index"] = index
147         strIndex = ""
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
154         else:
155             strIndex += "\n/* index 0x%(index)04X :   %(EntryName)s. */\n"%texts
156         
157         # Entry type is VAR
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             else:
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
173                 if callbacks:
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
176             else:
177                 strIndex += "                    %(subIndexType)s %(NodeName)s_obj%(index)04X%(suffixe)s = %(value)s;%(comment)s\n"%texts
178             values = [values]
179         else:
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
186             
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
198                     if callbacks:
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):
202                         sep = ","
203                         comment = ""
204                         if subIndex > 0:
205                             if subIndex == len(values)-1:
206                                 sep = ""
207                             if typeinfos[2] == "visible_string":
208                                 value = "\"%s\""%value
209                             else:
210                                 comment = "\t/* %s */"%str(value)
211                                 value = "0x%X"%value
212                             mappedVariableContent += "    %s%s%s\n"%(value, sep, comment)
213                     mappedVariableContent += "  };\n"
214                 else:
215                     strIndex += "                    %(subIndexType)s %(NodeName)s_obj%(index)04X[] = \n                    {\n"%texts
216                     for subIndex, value in enumerate(values):
217                         sep = ","
218                         comment = ""
219                         if subIndex > 0:
220                             if subIndex == len(values)-1:
221                                 sep = ""
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])
226                             else:
227                                 comment = "\t/* %s */"%str(value)
228                                 value = "0x%X"%value
229                             strIndex += "                      %s%s%s\n"%(value, sep, comment)
230                     strIndex += "                    };\n"
231             else:
232                 
233                 texts["parent"] = FormatName(entry_infos["name"])
234                 # Entry type is ARRAY
235                 for subIndex, value in enumerate(values):
236                     texts["subIndex"] = subIndex
237                     if subIndex > 0:
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                         else:
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
253                         else:
254                             strIndex += "                    %(subIndexType)s %(NodeName)s_obj%(index)04X_%(name)s%(suffixe)s = %(value)s;%(comment)s\n"%texts
255                 if callbacks:
256                     strDeclareHeader += "extern ODCallback_t %(parent)s_callbacks[];\t\t/* Callbacks of index0x%(index)04X */\n"%texts
257         
258         # Generating Dictionary C++ entry
259         if callbacks:
260             if index in variablelist:
261                 name = FormatName(entry_infos["name"])
262             else:
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"
267             strIndex += "                     };\n"
268             indexCallbacks[index] = "*callbacks = %s_callbacks; "%name
269         else:
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:
275                 sep = ","
276             else:
277                 sep = ""
278             typename = Manager.GetTypeName(subentry_infos["type"])
279             typeinfos = GetValidTypeInfos(typename)
280             if subIndex == 0:
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"])
285                 else:
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)
290                 else:
291                     name = "%s_obj%04X[%d]"%(texts["NodeName"], texts["index"], subIndex - 1)
292             else:
293                 if index in variablelist:
294                     name = FormatName("%s_%s"%(entry_infos["name"],subentry_infos["name"]))
295                 else:
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]))
299             else:
300                 sizeof = "sizeof (%s)"%typeinfos[0]
301             params = Manager.GetCurrentParamsEntry(index, subIndex)
302             if params["save"]:
303                 save = "|TO_BE_SAVE"
304             else:
305                 save = ""
306             strIndex += "                       { %s%s, %s, %s, (void*)&%s }%s\n"%(subentry_infos["access"].upper(),save,typeinfos[2],sizeof,name,sep)
307         strIndex += "                     };\n"
308         indexContents[index] = strIndex
309
310 #-------------------------------------------------------------------------------
311 #                     Declaration of Particular Parameters
312 #-------------------------------------------------------------------------------
313
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 */
319 """%texts
320
321     if 0x1016 in communicationlist:
322         texts["nombre"] = Manager.GetCurrentEntry(0x1016, 0)
323     else:
324         texts["nombre"] = 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};
330 """%texts
331     if texts["nombre"] > 0:
332         strTimers = "TIMER_HANDLE %(NodeName)s_heartBeatTimers[%(nombre)d] = {TIMER_NONE,};\n"%texts
333     else:
334         strTimers = "TIMER_HANDLE %(NodeName)s_heartBeatTimers[1];\n"%texts
335
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 */
341 """%texts
342
343 #-------------------------------------------------------------------------------
344 #               Declaration of navigation in the Object Dictionary
345 #-------------------------------------------------------------------------------
346
347     strDeclareIndex = ""
348     strDeclareSwitch = ""
349     strQuickIndex = ""
350     quick_index = {}
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
355     maxPDOtransmit = 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
365                 if cat == "PDO_TRS":
366                     maxPDOtransmit += 1
367     texts["maxPDOtransmit"] = max(1, maxPDOtransmit)
368     for index_cat in index_categories:
369         strQuickIndex += "\nquick_index %s_%s = {\n"%(texts["NodeName"], index_cat)
370         sep = ","
371         for i, (cat, idx_min, idx_max) in enumerate(categories):
372             if i == len(categories) - 1:
373                 sep = ""
374             strQuickIndex += "  %d%s /* %s */\n"%(quick_index[index_cat][cat],sep,cat)
375         strQuickIndex += "};\n"
376
377 #-------------------------------------------------------------------------------
378 #                            Write File Content
379 #-------------------------------------------------------------------------------
380
381     fileContent = generated_tag + """
382 #include "%s"
383 """%(headerfilepath)
384
385     fileContent += """
386 /**************************************************************************/
387 /* Declaration of the mapped variables                                    */
388 /**************************************************************************/
389 """ + mappedVariableContent
390
391     fileContent += """
392 /**************************************************************************/
393 /* Declaration of the value range types                                   */
394 /**************************************************************************/
395 """ + valueRangeContent
396
397     fileContent += """
398 /**************************************************************************/
399 /* The node id                                                            */
400 /**************************************************************************/
401 /* node_id default value.*/
402 UNS8 %(NodeName)s_bDeviceNodeId = 0x%(NodeID)02X;
403
404 /**************************************************************************/
405 /* Array of message processing information */
406
407 const UNS8 %(NodeName)s_iam_a_slave = %(iam_a_slave)d;
408
409 """%texts
410     fileContent += strTimers
411     
412     fileContent += """
413 /*
414 $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
415
416                                OBJECT DICTIONARY
417
418 $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
419 */
420 """%texts
421     contentlist = indexContents.keys()
422     contentlist.sort()
423     for index in contentlist:
424         fileContent += indexContents[index]
425
426     fileContent += """
427 const indextable %(NodeName)s_objdict[] = 
428 {
429 """%texts
430     fileContent += strDeclareIndex
431     fileContent += """};
432
433 const indextable * %(NodeName)s_scanIndexOD (UNS16 wIndex, UNS32 * errorCode, ODCallback_t **callbacks)
434 {
435         int i;
436         *callbacks = NULL;
437         switch(wIndex){
438 """%texts
439     fileContent += strDeclareSwitch
440     fileContent += """          default:
441                         *errorCode = OD_NO_SUCH_OBJECT;
442                         return NULL;
443         }
444         *errorCode = OD_SUCCESSFUL;
445         return &%(NodeName)s_objdict[i];
446 }
447
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.
451  */
452 UNS8 %(NodeName)s_count_sync[%(maxPDOtransmit)d] = {0,};
453 """%texts
454     fileContent += strQuickIndex
455     fileContent += """
456 UNS16 %(NodeName)s_ObjdictSize = sizeof(%(NodeName)s_objdict)/sizeof(%(NodeName)s_objdict[0]); 
457
458 CO_Data %(NodeName)s_Data = CANOPEN_NODE_DATA_INITIALIZER(%(NodeName)s);
459
460 """%texts
461
462 #-------------------------------------------------------------------------------
463 #                          Write Header File Content
464 #-------------------------------------------------------------------------------
465
466     HeaderFileContent = generated_tag + """
467 #include "data.h"
468
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);
472
473 /* Master node data struct */
474 extern CO_Data %(NodeName)s_Data;
475
476 """%texts
477     HeaderFileContent += strDeclareHeader
478     
479     return fileContent,HeaderFileContent
480
481 #-------------------------------------------------------------------------------
482 #                             Main Function
483 #-------------------------------------------------------------------------------
484
485 def GenerateFile(filepath, manager):
486     try:
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)
491         return None
492     except ValueError, message:
493         return "Unable to Generate C File\n%s"%message
494