]> rtime.felk.cvut.cz Git - CanFestival-3.git/blob - objdictgen/gen_cfile.py
LGPL copyright on generated files removed
[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] in ("UNSIGNED", "INTEGER") and eval(values[1]) in [i * 8 for i in xrange(1, 9)]:
56             return "UNS%s"%values[1], "", "uint%s"%values[1]
57         elif values[0] == "REAL" and eval(values[1]) in (32, 64):
58             return "%s%s"%(values[0], values[1]), "", "real%s"%values[1]
59         elif values[0] == "VISIBLE_STRING":
60             if values[1] == "":
61                 return "UNS8", "[10]", "visible_string"
62             else:
63                 return "UNS8", "[%s]"%values[1], "visible_string"
64     return None
65
66 def WriteFile(filepath, content):
67     cfile = open(filepath,"w")
68     cfile.write(content)
69     cfile.close()
70
71 def GenerateFileContent(Manager, headerfilepath):
72     global type
73     texts = {}
74     texts["maxPDOtransmit"] = 0
75     texts["NodeName"], texts["NodeID"], texts["NodeType"] = Manager.GetCurrentNodeInfos()
76     internal_types = {}
77     texts["iam_a_slave"] = 0
78     if (texts["NodeType"] == "slave"):
79         texts["iam_a_slave"] = 1
80     
81     # Compiling lists of indexes
82     rangelist = [idx for name,idx in Manager.GetCurrentValidIndexes(0, 0x260)]
83     listIndex = [idx for name,idx in Manager.GetCurrentValidIndexes(0x1000, 0xFFFF)]
84     communicationlist = [idx for name,idx in Manager.GetCurrentValidIndexes(0x1000, 0x11FF)]
85     sdolist = [idx for name,idx in Manager.GetCurrentValidIndexes(0x1200, 0x12FF)]
86     pdolist = [idx for name,idx in Manager.GetCurrentValidIndexes(0x1400, 0x1BFF)]
87     variablelist = [idx for name,idx in Manager.GetCurrentValidIndexes(0x2000, 0xBFFF)]
88
89 #-------------------------------------------------------------------------------
90 #                       Declaration of the value range types
91 #-------------------------------------------------------------------------------    
92     
93     valueRangeContent = ""
94     strDefine = ""
95     strSwitch = ""
96     num = 0
97     for index in rangelist:
98         rangename = Manager.GetEntryName(index)
99         result = range_model.match(rangename)
100         if result:
101             num += 1
102             internal_types[rangename] = "valueRange_%d"%num
103             typeindex = Manager.GetCurrentEntry(index, 1)
104             typename = Manager.GetTypeName(typeindex)
105             typeinfos = GetValidTypeInfos(typename)
106             if typeinfos == None:
107                 raise ValueError, """!!! %s isn't a valid type for CanFestival."""%typename
108             typename = typeinfos[0]
109             minvalue = str(Manager.GetCurrentEntry(index, 2))
110             maxvalue = str(Manager.GetCurrentEntry(index, 3))
111             strDefine += "\n#define valueRange_%d 0x%02X /* Type %s, %s < value < %s */"%(num,index,typename,minvalue,maxvalue)
112             strSwitch += """    case valueRange_%d:
113       if (*(%s*)Value < (%s)%s) return OD_VALUE_TOO_LOW;
114       if (*(%s*)Value > (%s)%s) return OD_VALUE_TOO_HIGH;
115       break;\n"""%(num,typename,typename,minvalue,typename,typename,maxvalue)
116
117     valueRangeContent += strDefine
118     valueRangeContent += "\nUNS32 %(NodeName)s_valueRangeTest (UNS8 typeValue, void * value)\n{"%texts
119     valueRangeContent += "\n  switch (typeValue) {\n"
120     valueRangeContent += strSwitch
121     valueRangeContent += "  }\n  return 0;\n}\n"
122
123 #-------------------------------------------------------------------------------
124 #            Creation of the mapped variables and object dictionary
125 #-------------------------------------------------------------------------------
126
127     mappedVariableContent = ""
128     strDeclareHeader = ""
129     strDeclareCallback = ""
130     indexContents = {}
131     indexCallbacks = {}
132     for index in listIndex:
133         texts["index"] = index
134         strIndex = ""
135         entry_infos = Manager.GetEntryInfos(index)
136         texts["EntryName"] = entry_infos["name"]
137         values = Manager.GetCurrentEntry(index)
138         callbacks = Manager.HasCurrentEntryCallbacks(index)
139         if index in variablelist:
140             strIndex += "\n/* index 0x%(index)04X :   Mapped variable %(EntryName)s */\n"%texts
141         else:
142             strIndex += "\n/* index 0x%(index)04X :   %(EntryName)s. */\n"%texts
143         if type(values) == ListType:
144             texts["value"] = values[0]
145             strIndex += "                    UNS8 %(NodeName)s_highestSubIndex_obj%(index)04X = %(value)d; // number of subindex - 1\n"%texts
146         
147         # Entry type is VAR
148         if type(values) != ListType:
149             subentry_infos = Manager.GetSubentryInfos(index, 0)
150             typename = Manager.GetTypeName(subentry_infos["type"])
151             typeinfos = GetValidTypeInfos(typename)
152             if typeinfos == None:
153                 raise ValueError, """!!! %s isn't a valid type for CanFestival."""%typename
154             if typename not in internal_types:
155                 internal_types[typename] = typeinfos[2]
156             texts["subIndexType"] = typeinfos[0]
157             texts["suffixe"] = typeinfos[1]
158             if typeinfos[2] == "visible_string":
159                 texts["value"] = "\"%s\""%values
160                 texts["comment"] = ""
161             else:
162                 texts["value"] = "0x%X"%values
163                 texts["comment"] = "\t// %s"%str(values)
164             if index in variablelist:
165                 texts["name"] = FormatName(subentry_infos["name"])
166                 strDeclareHeader += "extern %(subIndexType)s %(name)s%(suffixe)s;\t\t// Mapped at index 0x%(index)04X, subindex 0x00\n"%texts
167                 if callbacks:
168                     strDeclareHeader += "extern ODCallback_t %(name)s_callbacks[];\t\t// Callbacks of index0x%(index)04X\n"%texts
169                 mappedVariableContent += "%(subIndexType)s %(name)s%(suffixe)s = %(value)s;\t\t// Mapped at index 0x%(index)04X, subindex 0x00\n"%texts
170             else:
171                 strIndex += "                    %(subIndexType)s %(NodeName)s_obj%(index)04X%(suffixe)s = %(value)s;%(comment)s\n"%texts
172             values = [values]
173         else:
174             
175             # Entry type is RECORD
176             if entry_infos["struct"] & OD_IdenticalSubindexes:
177                 subentry_infos = Manager.GetSubentryInfos(index, 1)
178                 typename = Manager.GetTypeName(subentry_infos["type"])
179                 typeinfos = GetValidTypeInfos(typename)
180                 if typeinfos == None:
181                     raise ValueError, """!!! %s isn't a valid type for CanFestival."""%typename
182                 if typename not in internal_types:
183                     internal_types[typename] = typeinfos[2]
184                 texts["subIndexType"] = typeinfos[0]
185                 texts["suffixe"] = typeinfos[1]
186                 texts["length"] = values[0]
187                 if index in variablelist:
188                     texts["name"] = FormatName(entry_infos["name"])
189                     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
190                     if callbacks:
191                         strDeclareHeader += "extern ODCallback_t %(name)s_callbacks[];\t\t// Callbacks of index0x%(index)04X\n"%texts
192                     mappedVariableContent += "%(subIndexType)s %(name)s[] =\t\t// Mapped at index 0x%(index)04X, subindex 0x01 - 0x%(length)02X\n  {\n"%texts
193                     for subIndex, value in enumerate(values):
194                         sep = ","
195                         comment = ""
196                         if subIndex > 0:
197                             if subIndex == len(values)-1:
198                                 sep = ""
199                             if typeinfos[2] == "visible_string":
200                                 value = "\"%s\""%value
201                             else:
202                                 comment = "\t// %s"%str(value)
203                                 value = "0x%X"%value
204                             mappedVariableContent += "    %s%s%s\n"%(value, sep, comment)
205                     mappedVariableContent += "  };\n"
206                 else:
207                     strIndex += "                    %(subIndexType)s %(NodeName)s_obj%(index)04X[] = \n                    {\n"%texts
208                     for subIndex, value in enumerate(values):
209                         sep = ","
210                         comment = ""
211                         if subIndex > 0:
212                             if subIndex == len(values)-1:
213                                 sep = ""
214                             if typeinfos[2] == "visible_string":
215                                 value = "\"%s\""%value
216                             else:
217                                 comment = "\t// %s"%str(value)
218                                 value = "0x%X"%value
219                             strIndex += "                      %s%s%s\n"%(value, sep, comment)
220                     strIndex += "                    };\n"
221             else:
222                 
223                 texts["parent"] = FormatName(entry_infos["name"])
224                 # Entry type is ARRAY
225                 for subIndex, value in enumerate(values):
226                     texts["subIndex"] = subIndex
227                     if subIndex > 0:
228                         subentry_infos = Manager.GetSubentryInfos(index, subIndex)
229                         typename = Manager.GetTypeName(subentry_infos["type"])
230                         typeinfos = GetValidTypeInfos(typename)
231                         if typeinfos == None:
232                             raise ValueError, """!!! %s isn't a valid type for CanFestival."""%typename
233                         if typename not in internal_types:
234                             internal_types[typename] = typeinfos[2]
235                         texts["subIndexType"] = typeinfos[0]
236                         texts["suffixe"] = typeinfos[1]
237                         if typeinfos[2] == "visible_string":
238                             texts["value"] = "\"%s\""%value
239                             texts["comment"] = ""
240                         else:
241                             texts["value"] = "0x%X"%value
242                             texts["comment"] = "\t// %s"%str(value)
243                         texts["name"] = FormatName(subentry_infos["name"])
244                         if index in variablelist:
245                             strDeclareHeader += "extern %(subIndexType)s %(parent)s_%(name)s%(suffixe)s;\t\t// Mapped at index 0x%(index)04X, subindex 0x%(subIndex)02X\n"%texts
246                             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
247                         else:
248                             strIndex += "                    %(subIndexType)s %(NodeName)s_obj%(index)04X_%(name)s%(suffixe)s = %(value)s;%(comment)s\n"%texts
249                 if callbacks:
250                     strDeclareHeader += "extern ODCallback_t %(parent)s_callbacks[];\t\t// Callbacks of index0x%(index)04X\n"%texts
251         
252         # Generating Dictionary C++ entry
253         if callbacks:
254             if index in variablelist:
255                 name = FormatName(entry_infos["name"])
256             else:
257                 name = "%(NodeName)s_Index%(index)04X"%texts
258             strIndex += "                    ODCallback_t %s_callbacks[] = \n                     {\n"%name
259             for subIndex in xrange(len(values)):
260                 strIndex += "                       NULL,\n"
261             strIndex += "                     };\n"
262             indexCallbacks[index] = "*callbacks = %s_callbacks; "%name
263         else:
264             indexCallbacks[index] = ""
265         strIndex += "                    subindex %(NodeName)s_Index%(index)04X[] = \n                     {\n"%texts
266         for subIndex in xrange(len(values)):
267             subentry_infos = Manager.GetSubentryInfos(index, subIndex)
268             if subIndex < len(values) - 1:
269                 sep = ","
270             else:
271                 sep = ""
272             typename = Manager.GetTypeName(subentry_infos["type"])
273             typeinfos = GetValidTypeInfos(typename)
274             if typename.startswith("VISIBLE_STRING"):
275                 subIndexType = "visible_string"
276             elif typename in internal_types:
277                 subIndexType = internal_types[typename]
278             else:
279                 subIndexType = 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 subIndexType == "visible_string":
298                 sizeof = name
299             else:
300                 sizeof = 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, sizeof (%s), (void*)&%s }%s\n"%(subentry_infos["access"].upper(),save,subIndexType,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[];
330                     subindex %(NodeName)s_Index1016[];
331 """%texts
332     if texts["nombre"] > 0:
333         strTimers = "TIMER_HANDLE %(NodeName)s_heartBeatTimers[%(nombre)d] = {TIMER_NONE,};\n"%texts
334     else:
335         strTimers = "TIMER_HANDLE %(NodeName)s_heartBeatTimers[0];\n"%texts
336
337     if 0x1017 not in communicationlist:
338         entry_infos = Manager.GetEntryInfos(0x1017)
339         texts["EntryName"] = entry_infos["name"]
340         indexContents[0x1017] = """\n/* index 0x1017 :   %(EntryName)s */ 
341                     UNS16 %(NodeName)s_obj1017 = 0x0;   // 0
342 """%texts
343
344 #-------------------------------------------------------------------------------
345 #               Declaration of navigation in the Object Dictionary
346 #-------------------------------------------------------------------------------
347
348     strDeclareIndex = ""
349     strDeclareSwitch = ""
350     strQuickIndex = ""
351     quick_index = {}
352     for index_cat in index_categories:
353         quick_index[index_cat] = {}
354         for cat, idx_min, idx_max in categories:
355             quick_index[index_cat][cat] = 0
356     maxPDOtransmit = 0
357     for i, index in enumerate(listIndex):
358         texts["index"] = index
359         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
360         strDeclareSwitch += "           case 0x%04X: i = %d;%sbreak;\n"%(index, i, indexCallbacks[index])
361         for cat, idx_min, idx_max in categories:
362             if idx_min <= index <= idx_max:
363                 quick_index["lastIndex"][cat] = i
364                 if quick_index["firstIndex"][cat] == 0:
365                     quick_index["firstIndex"][cat] = i
366                 if cat == "PDO_TRS":
367                     maxPDOtransmit += 1
368     texts["maxPDOtransmit"] = max(1, maxPDOtransmit)
369     for index_cat in index_categories:
370         strQuickIndex += "\nquick_index %s_%s = {\n"%(texts["NodeName"], index_cat)
371         sep = ","
372         for i, (cat, idx_min, idx_max) in enumerate(categories):
373             if i == len(categories) - 1:
374                 sep = ""
375             strQuickIndex += "  %s : %d%s\n"%(cat, quick_index[index_cat][cat], sep)
376         strQuickIndex += "};\n"
377
378 #-------------------------------------------------------------------------------
379 #                            Write File Content
380 #-------------------------------------------------------------------------------
381
382     fileContent = generated_tag + """
383 #include "%s"
384 """%(headerfilepath)
385
386     fileContent += """
387 /**************************************************************************/
388 /* Declaration of the mapped variables                                    */
389 /**************************************************************************/
390 """ + mappedVariableContent
391
392     fileContent += """
393 /**************************************************************************/
394 /* Declaration of the value range types                                   */
395 /**************************************************************************/
396 """ + valueRangeContent
397
398     fileContent += """
399 /**************************************************************************/
400 /* The node id                                                            */
401 /**************************************************************************/
402 /* node_id default value.*/
403 UNS8 %(NodeName)s_bDeviceNodeId = 0x%(NodeID)02X;
404
405 //*****************************************************************************/
406 /* Array of message processing information */
407
408 const UNS8 %(NodeName)s_iam_a_slave = %(iam_a_slave)d;
409
410 """%texts
411     fileContent += strTimers
412     
413     fileContent += """
414 //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
415 //
416 //                             OBJECT DICTIONARY
417 //
418 //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
419 """%texts
420     contentlist = indexContents.keys()
421     contentlist.sort()
422     for index in contentlist:
423         fileContent += indexContents[index]
424
425     fileContent += """
426 const indextable %(NodeName)s_objdict[] = 
427 {
428 """%texts
429     fileContent += strDeclareIndex
430     fileContent += """};
431
432 const indextable * %(NodeName)s_scanIndexOD (UNS16 wIndex, UNS32 * errorCode, ODCallback_t **callbacks)
433 {
434         int i;
435         *callbacks = NULL;
436         switch(wIndex){
437 """%texts
438     fileContent += strDeclareSwitch
439     fileContent += """          default:
440                         *errorCode = OD_NO_SUCH_OBJECT;
441                         return NULL;
442         }
443         *errorCode = OD_SUCCESSFUL;
444         return &%(NodeName)s_objdict[i];
445 }
446
447 // To count at which received SYNC a PDO must be sent.
448 // Even if no pdoTransmit are defined, at least one entry is computed
449 // for compilations issues.
450 UNS8 %(NodeName)s_count_sync[%(maxPDOtransmit)d] = {0,};
451 """%texts
452     fileContent += strQuickIndex
453     fileContent += """
454 UNS16 %(NodeName)s_ObjdictSize = sizeof(%(NodeName)s_objdict)/sizeof(%(NodeName)s_objdict[0]); 
455
456 CO_Data %(NodeName)s_Data = CANOPEN_NODE_DATA_INITIALIZER(%(NodeName)s);
457
458 """%texts
459
460 #-------------------------------------------------------------------------------
461 #                          Write Header File Content
462 #-------------------------------------------------------------------------------
463
464     HeaderFileContent = generated_tag + """
465 #include "data.h"
466
467 // prototypes of function provided by object dictionnary
468 UNS32 %(NodeName)s_valueRangeTest (UNS8 typeValue, void * value);
469 const indextable * %(NodeName)s_scanIndexOD (UNS16 wIndex, UNS32 * errorCode, ODCallback_t **callbacks);
470
471 // prototypes of function to be filled by app
472 void %(NodeName)s_SDOtimeoutError(UNS8 line);
473 void %(NodeName)s_heartbeatError(UNS8);
474
475 UNS8 %(NodeName)s_canSend(Message *);
476
477 void %(NodeName)s_initialisation(void);
478 void %(NodeName)s_preOperational(void);
479 void %(NodeName)s_operational(void);
480 void %(NodeName)s_stopped(void);
481
482 void %(NodeName)s_post_sync(void);
483 void %(NodeName)s_post_TPDO(void);
484
485 // Master node data struct
486 extern CO_Data %(NodeName)s_Data;
487
488 """%texts
489     HeaderFileContent += strDeclareHeader
490     
491     return fileContent,HeaderFileContent
492
493 #-------------------------------------------------------------------------------
494 #                             Main Function
495 #-------------------------------------------------------------------------------
496
497 def GenerateFile(filepath, manager):
498     headerfilepath = os.path.splitext(filepath)[0]+".h"
499     content, header = GenerateFileContent(manager, os.path.split(headerfilepath)[1])
500     WriteFile(filepath, content)
501     WriteFile(headerfilepath, header)
502     return True