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