]> rtime.felk.cvut.cz Git - CanFestival-3.git/blob - objdictgen/gen_cfile.py
Adding support for importing and exporting EDS files
[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 # Format a string for making a C++ variable
41 def FormatName(name):
42     wordlist = [word for word in word_model.findall(name) if word != '']
43     result = ''
44     sep = ''
45     for word in wordlist:
46         result += "%s%s"%(sep,word)
47         sep = '_'
48     return result
49
50 # Extract the informations from a given type name
51 def GetValidTypeInfos(typename):
52     result = type_model.match(typename)
53     if result:
54         values = result.groups()
55         if values[0] == "UNSIGNED" and int(values[1]) in [i * 8 for i in xrange(1, 9)]:
56             return "UNS%s"%values[1], "", "uint%s"%values[1]
57         if values[0] == "INTEGER" and int(values[1]) in [i * 8 for i in xrange(1, 9)]:
58             return "INTEGER%s"%values[1], "", "int%s"%values[1]
59         elif values[0] == "REAL" and int(values[1]) in (32, 64):
60             return "%s%s"%(values[0], values[1]), "", "real%s"%values[1]
61         elif values[0] == "VISIBLE_STRING":
62             if values[1] == "":
63                 return "UNS8", "[10]", "visible_string"
64             else:
65                 return "UNS8", "[%s]"%values[1], "visible_string"
66         elif values[0] == "DOMAIN":
67                 return "UNS8*", "", "domain"
68     return None
69
70 def WriteFile(filepath, content):
71     cfile = open(filepath,"w")
72     cfile.write(content)
73     cfile.close()
74
75 def GenerateFileContent(Manager, headerfilepath):
76     global type
77     texts = {}
78     texts["maxPDOtransmit"] = 0
79     texts["NodeName"], texts["NodeID"], texts["NodeType"] = Manager.GetCurrentNodeInfos()
80     internal_types = {}
81     texts["iam_a_slave"] = 0
82     if (texts["NodeType"] == "slave"):
83         texts["iam_a_slave"] = 1
84     
85     # Compiling lists of indexes
86     rangelist = [idx for name,idx in Manager.GetCurrentValidIndexes(0, 0x260)]
87     listIndex = [idx for name,idx in Manager.GetCurrentValidIndexes(0x1000, 0xFFFF)]
88     communicationlist = [idx for name,idx in Manager.GetCurrentValidIndexes(0x1000, 0x11FF)]
89     sdolist = [idx for name,idx in Manager.GetCurrentValidIndexes(0x1200, 0x12FF)]
90     pdolist = [idx for name,idx in Manager.GetCurrentValidIndexes(0x1400, 0x1BFF)]
91     variablelist = [idx for name,idx in Manager.GetCurrentValidIndexes(0x2000, 0xBFFF)]
92
93 #-------------------------------------------------------------------------------
94 #                       Declaration of the value range types
95 #-------------------------------------------------------------------------------    
96     
97     valueRangeContent = ""
98     strDefine = ""
99     strSwitch = ""
100     num = 0
101     for index in rangelist:
102         rangename = Manager.GetEntryName(index)
103         result = range_model.match(rangename)
104         if result:
105             num += 1
106             internal_types[rangename] = "valueRange_%d"%num
107             typeindex = Manager.GetCurrentEntry(index, 1)
108             typename = Manager.GetTypeName(typeindex)
109             typeinfos = GetValidTypeInfos(typename)
110             if typeinfos == None:
111                 raise ValueError, """!!! %s isn't a valid type for CanFestival."""%typename
112             typename = typeinfos[0]
113             minvalue = str(Manager.GetCurrentEntry(index, 2))
114             maxvalue = str(Manager.GetCurrentEntry(index, 3))
115             strDefine += "\n#define valueRange_%d 0x%02X /* Type %s, %s < value < %s */"%(num,index,typename,minvalue,maxvalue)
116             strSwitch += """    case valueRange_%d:
117       if (*(%s*)Value < (%s)%s) return OD_VALUE_TOO_LOW;
118       if (*(%s*)Value > (%s)%s) return OD_VALUE_TOO_HIGH;
119       break;\n"""%(num,typename,typename,minvalue,typename,typename,maxvalue)
120
121     valueRangeContent += strDefine
122     valueRangeContent += "\nUNS32 %(NodeName)s_valueRangeTest (UNS8 typeValue, void * value)\n{"%texts
123     valueRangeContent += "\n  switch (typeValue) {\n"
124     valueRangeContent += strSwitch
125     valueRangeContent += "  }\n  return 0;\n}\n"
126
127 #-------------------------------------------------------------------------------
128 #            Creation of the mapped variables and object dictionary
129 #-------------------------------------------------------------------------------
130
131     mappedVariableContent = ""
132     strDeclareHeader = ""
133     strDeclareCallback = ""
134     indexContents = {}
135     indexCallbacks = {}
136     for index in listIndex:
137         texts["index"] = index
138         strIndex = ""
139         entry_infos = Manager.GetEntryInfos(index)
140         texts["EntryName"] = entry_infos["name"]
141         values = Manager.GetCurrentEntry(index)
142         callbacks = Manager.HasCurrentEntryCallbacks(index)
143         if index in variablelist:
144             strIndex += "\n/* index 0x%(index)04X :   Mapped variable %(EntryName)s */\n"%texts
145         else:
146             strIndex += "\n/* index 0x%(index)04X :   %(EntryName)s. */\n"%texts
147         if type(values) == ListType:
148             texts["value"] = values[0]
149             strIndex += "                    UNS8 %(NodeName)s_highestSubIndex_obj%(index)04X = %(value)d; /* number of subindex - 1*/\n"%texts
150         
151         # Entry type is VAR
152         if type(values) != ListType:
153             subentry_infos = Manager.GetSubentryInfos(index, 0)
154             typename = Manager.GetTypeName(subentry_infos["type"])
155             typeinfos = GetValidTypeInfos(typename)
156             if typeinfos == None:
157                 raise ValueError, """!!! %s isn't a valid type for CanFestival."""%typename
158             if typename not in internal_types:
159                 internal_types[typename] = typeinfos[2]
160             texts["subIndexType"] = typeinfos[0]
161             texts["suffixe"] = typeinfos[1]
162             if typeinfos[2] == "visible_string":
163                 texts["value"] = "\"%s\""%values
164                 texts["comment"] = ""
165             else:
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
171                 if callbacks:
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
174             else:
175                 strIndex += "                    %(subIndexType)s %(NodeName)s_obj%(index)04X%(suffixe)s = %(value)s;%(comment)s\n"%texts
176             values = [values]
177         else:
178             
179             # Entry type is RECORD
180             if entry_infos["struct"] & OD_IdenticalSubindexes:
181                 subentry_infos = Manager.GetSubentryInfos(index, 1)
182                 typename = Manager.GetTypeName(subentry_infos["type"])
183                 typeinfos = GetValidTypeInfos(typename)
184                 if typeinfos == None:
185                     raise ValueError, """!!! %s isn't a valid type for CanFestival."""%typename
186                 if typename not in internal_types:
187                     internal_types[typename] = typeinfos[2]
188                 texts["subIndexType"] = typeinfos[0]
189                 texts["suffixe"] = typeinfos[1]
190                 texts["length"] = values[0]
191                 if index in variablelist:
192                     texts["name"] = FormatName(entry_infos["name"])
193                     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
194                     if callbacks:
195                         strDeclareHeader += "extern ODCallback_t %(name)s_callbacks[];\t\t/* Callbacks of index0x%(index)04X */\n"%texts
196                     mappedVariableContent += "%(subIndexType)s %(name)s[] =\t\t/* Mapped at index 0x%(index)04X, subindex 0x01 - 0x%(length)02X */\n  {\n"%texts
197                     for subIndex, value in enumerate(values):
198                         sep = ","
199                         comment = ""
200                         if subIndex > 0:
201                             if subIndex == len(values)-1:
202                                 sep = ""
203                             if typeinfos[2] == "visible_string":
204                                 value = "\"%s\""%value
205                             else:
206                                 comment = "\t/* %s */"%str(value)
207                                 value = "0x%X"%value
208                             mappedVariableContent += "    %s%s%s\n"%(value, sep, comment)
209                     mappedVariableContent += "  };\n"
210                 else:
211                     strIndex += "                    %(subIndexType)s %(NodeName)s_obj%(index)04X[] = \n                    {\n"%texts
212                     for subIndex, value in enumerate(values):
213                         sep = ","
214                         comment = ""
215                         if subIndex > 0:
216                             if subIndex == len(values)-1:
217                                 sep = ""
218                             if typeinfos[2] == "visible_string":
219                                 value = "\"%s\""%value
220                             elif typeinfos[2] == "domain":
221                                 value = "\"%s\""%''.join(["\\x%2.2x"%ord(char) for char in value])
222                             else:
223                                 comment = "\t/* %s */"%str(value)
224                                 value = "0x%X"%value
225                             strIndex += "                      %s%s%s\n"%(value, sep, comment)
226                     strIndex += "                    };\n"
227             else:
228                 
229                 texts["parent"] = FormatName(entry_infos["name"])
230                 # Entry type is ARRAY
231                 for subIndex, value in enumerate(values):
232                     texts["subIndex"] = subIndex
233                     if subIndex > 0:
234                         subentry_infos = Manager.GetSubentryInfos(index, subIndex)
235                         typename = Manager.GetTypeName(subentry_infos["type"])
236                         typeinfos = GetValidTypeInfos(typename)
237                         if typeinfos == None:
238                             raise ValueError, """!!! %s isn't a valid type for CanFestival."""%typename
239                         if typename not in internal_types:
240                             internal_types[typename] = typeinfos[2]
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 typename.startswith("VISIBLE_STRING"):
281                 subIndexType = "visible_string"
282             elif typename in internal_types:
283                 subIndexType = internal_types[typename]
284             else:
285                 subIndexType = typename
286             if subIndex == 0:
287                 if entry_infos["struct"] & OD_MultipleSubindexes:
288                     name = "%(NodeName)s_highestSubIndex_obj%(index)04X"%texts
289                 elif index in variablelist:
290                     name = FormatName(subentry_infos["name"])
291                 else:
292                     name = FormatName("%s_obj%04X"%(texts["NodeName"], texts["index"]))
293             elif entry_infos["struct"] & OD_IdenticalSubindexes:
294                 if index in variablelist:
295                     name = "%s[%d]"%(FormatName(entry_infos["name"]), subIndex - 1)
296                 else:
297                     name = "%s_obj%04X[%d]"%(texts["NodeName"], texts["index"], subIndex - 1)
298             else:
299                 if index in variablelist:
300                     name = FormatName("%s_%s"%(entry_infos["name"],subentry_infos["name"]))
301                 else:
302                     name = "%s_obj%04X_%s"%(texts["NodeName"], texts["index"], FormatName(subentry_infos["name"]))
303             if subIndexType in ["visible_string", "domain"]:
304                 sizeof = str(len(values[subIndex]))
305             else:
306                 sizeof = "sizeof (%s)"%typeinfos[0]
307             params = Manager.GetCurrentParamsEntry(index, subIndex)
308             if params["save"]:
309                 save = "|TO_BE_SAVE"
310             else:
311                 save = ""
312             strIndex += "                       { %s%s, %s, %s, (void*)&%s }%s\n"%(subentry_infos["access"].upper(),save,subIndexType,sizeof,name,sep)
313         strIndex += "                     };\n"
314         indexContents[index] = strIndex
315
316 #-------------------------------------------------------------------------------
317 #                     Declaration of Particular Parameters
318 #-------------------------------------------------------------------------------
319
320     if 0x1006 not in communicationlist:
321         entry_infos = Manager.GetEntryInfos(0x1006)
322         texts["EntryName"] = entry_infos["name"]
323         indexContents[0x1006] = """\n/* index 0x1006 :   %(EntryName)s */
324                     UNS32 %(NodeName)s_obj1006 = 0x0;   /* 0 */
325 """%texts
326
327     if 0x1016 in communicationlist:
328         texts["nombre"] = Manager.GetCurrentEntry(0x1016, 0)
329     else:
330         texts["nombre"] = 0
331         entry_infos = Manager.GetEntryInfos(0x1016)
332         texts["EntryName"] = entry_infos["name"]
333         indexContents[0x1016] = """\n/* index 0x1016 :   %(EntryName)s */
334                     UNS8 %(NodeName)s_highestSubIndex_obj1016 = 0;
335                     UNS32 %(NodeName)s_obj1016[]={0};
336 """%texts
337     if texts["nombre"] > 0:
338         strTimers = "TIMER_HANDLE %(NodeName)s_heartBeatTimers[%(nombre)d] = {TIMER_NONE,};\n"%texts
339     else:
340         strTimers = "TIMER_HANDLE %(NodeName)s_heartBeatTimers[1];\n"%texts
341
342     if 0x1017 not in communicationlist:
343         entry_infos = Manager.GetEntryInfos(0x1017)
344         texts["EntryName"] = entry_infos["name"]
345         indexContents[0x1017] = """\n/* index 0x1017 :   %(EntryName)s */ 
346                     UNS16 %(NodeName)s_obj1017 = 0x0;   /* 0 */
347 """%texts
348
349 #-------------------------------------------------------------------------------
350 #               Declaration of navigation in the Object Dictionary
351 #-------------------------------------------------------------------------------
352
353     strDeclareIndex = ""
354     strDeclareSwitch = ""
355     strQuickIndex = ""
356     quick_index = {}
357     for index_cat in index_categories:
358         quick_index[index_cat] = {}
359         for cat, idx_min, idx_max in categories:
360             quick_index[index_cat][cat] = 0
361     maxPDOtransmit = 0
362     for i, index in enumerate(listIndex):
363         texts["index"] = index
364         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
365         strDeclareSwitch += "           case 0x%04X: i = %d;%sbreak;\n"%(index, i, indexCallbacks[index])
366         for cat, idx_min, idx_max in categories:
367             if idx_min <= index <= idx_max:
368                 quick_index["lastIndex"][cat] = i
369                 if quick_index["firstIndex"][cat] == 0:
370                     quick_index["firstIndex"][cat] = i
371                 if cat == "PDO_TRS":
372                     maxPDOtransmit += 1
373     texts["maxPDOtransmit"] = max(1, maxPDOtransmit)
374     for index_cat in index_categories:
375         strQuickIndex += "\nquick_index %s_%s = {\n"%(texts["NodeName"], index_cat)
376         sep = ","
377         for i, (cat, idx_min, idx_max) in enumerate(categories):
378             if i == len(categories) - 1:
379                 sep = ""
380             strQuickIndex += "  %d%s /* %s */\n"%(quick_index[index_cat][cat],sep,cat)
381         strQuickIndex += "};\n"
382
383 #-------------------------------------------------------------------------------
384 #                            Write File Content
385 #-------------------------------------------------------------------------------
386
387     fileContent = generated_tag + """
388 #include "%s"
389 """%(headerfilepath)
390
391     fileContent += """
392 /**************************************************************************/
393 /* Declaration of the mapped variables                                    */
394 /**************************************************************************/
395 """ + mappedVariableContent
396
397     fileContent += """
398 /**************************************************************************/
399 /* Declaration of the value range types                                   */
400 /**************************************************************************/
401 """ + valueRangeContent
402
403     fileContent += """
404 /**************************************************************************/
405 /* The node id                                                            */
406 /**************************************************************************/
407 /* node_id default value.*/
408 UNS8 %(NodeName)s_bDeviceNodeId = 0x%(NodeID)02X;
409
410 /**************************************************************************/
411 /* Array of message processing information */
412
413 const UNS8 %(NodeName)s_iam_a_slave = %(iam_a_slave)d;
414
415 """%texts
416     fileContent += strTimers
417     
418     fileContent += """
419 /*
420 $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
421
422                                OBJECT DICTIONARY
423
424 $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
425 */
426 """%texts
427     contentlist = indexContents.keys()
428     contentlist.sort()
429     for index in contentlist:
430         fileContent += indexContents[index]
431
432     fileContent += """
433 const indextable %(NodeName)s_objdict[] = 
434 {
435 """%texts
436     fileContent += strDeclareIndex
437     fileContent += """};
438
439 const indextable * %(NodeName)s_scanIndexOD (UNS16 wIndex, UNS32 * errorCode, ODCallback_t **callbacks)
440 {
441         int i;
442         *callbacks = NULL;
443         switch(wIndex){
444 """%texts
445     fileContent += strDeclareSwitch
446     fileContent += """          default:
447                         *errorCode = OD_NO_SUCH_OBJECT;
448                         return NULL;
449         }
450         *errorCode = OD_SUCCESSFUL;
451         return &%(NodeName)s_objdict[i];
452 }
453
454 /* To count at which received SYNC a PDO must be sent.
455  * Even if no pdoTransmit are defined, at least one entry is computed
456  * for compilations issues.
457  */
458 UNS8 %(NodeName)s_count_sync[%(maxPDOtransmit)d] = {0,};
459 """%texts
460     fileContent += strQuickIndex
461     fileContent += """
462 UNS16 %(NodeName)s_ObjdictSize = sizeof(%(NodeName)s_objdict)/sizeof(%(NodeName)s_objdict[0]); 
463
464 CO_Data %(NodeName)s_Data = CANOPEN_NODE_DATA_INITIALIZER(%(NodeName)s);
465
466 """%texts
467
468 #-------------------------------------------------------------------------------
469 #                          Write Header File Content
470 #-------------------------------------------------------------------------------
471
472     HeaderFileContent = generated_tag + """
473 #include "data.h"
474
475 /* Prototypes of function provided by object dictionnary */
476 UNS32 %(NodeName)s_valueRangeTest (UNS8 typeValue, void * value);
477 const indextable * %(NodeName)s_scanIndexOD (UNS16 wIndex, UNS32 * errorCode, ODCallback_t **callbacks);
478
479 /* Master node data struct */
480 extern CO_Data %(NodeName)s_Data;
481
482 """%texts
483     HeaderFileContent += strDeclareHeader
484     
485     return fileContent,HeaderFileContent
486
487 #-------------------------------------------------------------------------------
488 #                             Main Function
489 #-------------------------------------------------------------------------------
490
491 def GenerateFile(filepath, manager):
492     headerfilepath = os.path.splitext(filepath)[0]+".h"
493     content, header = GenerateFileContent(manager, os.path.split(headerfilepath)[1])
494     WriteFile(filepath, content)
495     WriteFile(headerfilepath, header)
496     return True