]> rtime.felk.cvut.cz Git - CanFestival-3.git/blob - objdictgen/eds_utils.py
Bugs on cfile generation fixed
[CanFestival-3.git] / objdictgen / eds_utils.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, Francis DUPIN and Laurent BESSARD
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
25 import node
26 from node import nosub, var, array, rec, plurivar, pluriarray, plurirec
27 from sets import *
28 from types import *
29 from time import *
30 import os,re
31
32 # Regular expression for finding index section names
33 index_model = re.compile('([0-9A-F]{1,4})')
34 # Regular expression for finding subindex section names
35 subindex_model = re.compile('([0-9A-F]{1,4})SUB([0-9A-F]{1,2})')
36
37 # Regular expression for finding NodeXPresent keynames
38 nodepresent_model = re.compile('NODE([0-9]{1,3})PRESENT')
39 # Regular expression for finding NodeXName keynames
40 nodename_model = re.compile('NODE([0-9]{1,3})NAME')
41 # Regular expression for finding NodeXDCFName keynames
42 nodedcfname_model = re.compile('NODE([0-9]{1,3})DCFNAME')
43
44 # Dictionary for quickly translate boolean into integer value
45 BOOL_TRANSLATE = {True : "1", False : "0"}
46
47 # Dictionary for quickly translate eds access value into canfestival access value
48 ACCESS_TRANSLATE = {"ro" : "ro", "wo" : "wo", "rw" : "rw", "rwr" : "rw", "rww" : "rw", "const" : "ro"}
49
50 # Function for verifying data values
51 is_integer = lambda x: type(x) in (IntType, LongType)
52 is_string = lambda x: type(x) in (StringType, UnicodeType)
53 is_boolean = lambda x: x in (0, 1)
54
55 # Define checking of value for each attribute
56 ENTRY_ATTRIBUTES = {"SUBNUMBER" : is_integer, "PARAMETERNAME" : is_string, 
57                     "OBJECTTYPE" : lambda x: x in (7, 8, 9), "DATATYPE" : is_integer, 
58                     "LOWLIMIT" : is_integer, "HIGHLIMIT" : is_integer,
59                     "ACCESSTYPE" : lambda x: x in ["ro","wo", "rw", "rwr", "rww", "const"],
60                     "DEFAULTVALUE" : lambda x: True, "PDOMAPPING" : is_boolean,
61                     "OBJFLAGS" : is_integer}
62
63 # Define entry parameters by entry ObjectType number
64 ENTRY_TYPES = {7 : {"name" : " VAR",
65                     "require" : ["PARAMETERNAME", "DATATYPE", "ACCESSTYPE"],
66                     "optional" : ["OBJECTTYPE", "DEFAULTVALUE", "PDOMAPPING", "LOWLIMIT", "HIGHLIMIT", "OBJFLAGS"]},
67                8 : {"name" : "n ARRAY",
68                     "require" : ["PARAMETERNAME", "OBJECTTYPE", "SUBNUMBER"],
69                     "optional" : ["OBJFLAGS"]},
70                9 : {"name" : " RECORD",
71                     "require" : ["PARAMETERNAME", "OBJECTTYPE", "SUBNUMBER"],
72                     "optional" : ["OBJFLAGS"]}}
73
74
75 # Function that search into Node Mappings the informations about an index or a subindex
76 # and return the default value
77 def GetDefaultValue(index, subIndex = None):
78     infos = Node.GetEntryInfos(index)
79     if infos["struct"] & node.OD_MultipleSubindexes:
80         # First case entry is a record
81         if infos["struct"] & node.OD_IdenticalSubindexes:
82             subentry_infos = Node.GetSubentryInfos(index, 1)
83         # Second case entry is an array
84         else:
85             subentry_infos = Node.GetSubentryInfos(index, subIndex)
86         # If a default value is defined for this subindex, returns it
87         if "default" in subentry_infos:
88             return subentry_infos["default"]
89         # If not, returns the default value for the subindex type
90         else:
91             return Node.GetTypeDefaultValue(subentry_infos["type"])
92     # Third case entry is a var
93     else:
94         subentry_infos = Node.GetSubentryInfos(index, 0)
95         # If a default value is defined for this subindex, returns it
96         if "default" in subentry_infos:
97             return subentry_infos["default"]
98         # If not, returns the default value for the subindex type
99         else:
100             return Node.GetTypeDefaultValue(subentry_infos["type"])
101     return None
102
103
104 #-------------------------------------------------------------------------------
105 #                               Parse file
106 #-------------------------------------------------------------------------------
107
108
109 # List of section names that are not index and subindex and that we can meet in
110 # an EDS file
111 SECTION_KEYNAMES = ["FILEINFO", "DEVICEINFO", "DUMMYUSAGE", "COMMENTS", 
112                     "MANDATORYOBJECTS", "OPTIONALOBJECTS", "MANUFACTUREROBJECTS"]
113
114
115 # Function that extract sections from a file and returns a dictionary of the informations
116 def ExtractSections(file):
117     return [(blocktuple[0],                # EntryName : Assignements dict
118              blocktuple[-1].splitlines())  # all the lines
119              for blocktuple in [           # Split the eds files into
120              block.split("]", 1)              # (EntryName,Assignements) tuple
121              for block in                  # for each blocks staring with '['
122              ("\n"+file).split("\n[")]
123              if blocktuple[0].isalnum()]   # if EntryName exists
124     
125
126 # Function that parse an CPJ file and returns a dictionary of the informations
127 def ParseCPJFile(filepath):
128     networks = []
129     # Read file text
130     cpj_file = open(filepath,'r').read()
131     sections = ExtractSections(cpj_file)
132     # Parse assignments for each section
133     for section_name, assignments in sections:
134         
135         # Verify that section name is TOPOLOGY 
136         if section_name.upper() in "TOPOLOGY":
137             
138             # Reset values for topology
139             topology = {"Name" : "", "Nodes" : {}}
140             
141             for assignment in assignments:
142                 # Escape any comment
143                 if assignment.startswith(";"):
144                     pass
145                 # Verify that line is a valid assignment
146                 elif assignment.find('=') > 0:
147                     # Split assignment into the two values keyname and value
148                     keyname, value = assignment.split("=", 1)
149                     
150                     # keyname must be immediately followed by the "=" sign, so we
151                     # verify that there is no whitespace into keyname
152                     if keyname.isalnum():
153                         # value can be preceded and followed by whitespaces, so we escape them
154                         value = value.strip()
155                 
156                         # First case, value starts with "0x", then it's an hexadecimal value
157                         if value.startswith("0x"):
158                             try:
159                                 computed_value = int(value, 16)
160                             except:
161                                 raise SyntaxError, "\"%s\" is not a valid value for attribute \"%s\" of section \"[%s]\""%(value, keyname, section_name)
162                         elif value.isdigit():
163                             # Second case, value is a number and starts with "0", then it's an octal value
164                             if value.startswith("0"):
165                                 computed_value = int(value, 8)
166                             # Third case, value is a number and don't start with "0", then it's a decimal value
167                             else:
168                                 computed_value = int(value)
169                         # In any other case, we keep string value
170                         else:
171                             computed_value = value
172                         
173                         # Search if the section name match any cpj expression
174                         nodepresent_result = nodepresent_model.match(keyname.upper())
175                         nodename_result = nodename_model.match(keyname.upper())
176                         nodedcfname_result = nodedcfname_model.match(keyname.upper())
177                         
178                         if keyname.upper() == "NETNAME":
179                             if not is_string(computed_value):
180                                 raise SyntaxError, "Invalid value \"%s\" for keyname \"%s\" of section \"[%s]\""%(value, keyname, section_name)
181                             topology["Name"] = computed_value
182                         elif keyname.upper() == "NODES":
183                             if not is_integer(computed_value):
184                                 raise SyntaxError, "Invalid value \"%s\" for keyname \"%s\" of section \"[%s]\""%(value, keyname, section_name)
185                             topology["Number"] = computed_value
186                         elif keyname.upper() == "EDSBASENAME":
187                             if not is_string(computed_value):
188                                 raise SyntaxError, "Invalid value \"%s\" for keyname \"%s\" of section \"[%s]\""%(value, keyname, section_name)
189                             topology["Path"] = computed_value
190                         elif nodepresent_result:
191                             if not is_boolean(computed_value):
192                                 raise SyntaxError, "Invalid value \"%s\" for keyname \"%s\" of section \"[%s]\""%(value, keyname, section_name)
193                             nodeid = int(nodepresent_result.groups()[0])
194                             if nodeid not in topology["Nodes"].keys():
195                                 topology["Nodes"][nodeid] = {}
196                             topology["Nodes"][nodeid]["Present"] = computed_value
197                         elif nodename_result:
198                             if not is_string(value):
199                                 raise SyntaxError, "Invalid value \"%s\" for keyname \"%s\" of section \"[%s]\""%(value, keyname, section_name)
200                             nodeid = int(nodename_result.groups()[0])
201                             if nodeid not in topology["Nodes"].keys():
202                                 topology["Nodes"][nodeid] = {}
203                             topology["Nodes"][nodeid]["Name"] = computed_value
204                         elif nodedcfname_result:
205                             if not is_string(computed_value):
206                                 raise SyntaxError, "Invalid value \"%s\" for keyname \"%s\" of section \"[%s]\""%(value, keyname, section_name)
207                             nodeid = int(nodedcfname_result.groups()[0])
208                             if nodeid not in topology["Nodes"].keys():
209                                 topology["Nodes"][nodeid] = {}
210                             topology["Nodes"][nodeid]["DCFName"] = computed_value
211                         else:
212                             raise SyntaxError, "Keyname \"%s\" not recognised for section \"[%s]\""%(keyname, section_name)
213                         
214                 # All lines that are not empty and are neither a comment neither not a valid assignment
215                 elif assignment.strip() != "":
216                     raise SyntaxError, "\"%s\" is not a valid CPJ line"%assignment.strip()
217         
218             if "Number" not in topology.keys():
219                 raise SyntaxError, "\"Nodes\" keyname in \"[%s]\" section is missing"%section_name
220         
221             if topology["Number"] != len(topology["Nodes"]):
222                 raise SyntaxError, "\"Nodes\" value not corresponding to number of nodes defined"
223             
224             for nodeid, node in topology["Nodes"].items():
225                 if "Present" not in node.keys():
226                     raise SyntaxError, "\"Node%dPresent\" keyname in \"[%s]\" section is missing"%(nodeid, section_name)
227             
228             networks.append(topology)
229             
230         # In other case, there is a syntax problem into CPJ file
231         else:
232             raise SyntaxError, "Section \"[%s]\" is unrecognized"%section_name
233     
234     return networks
235
236 # Function that parse an EDS file and returns a dictionary of the informations
237 def ParseEDSFile(filepath):
238     eds_dict = {}
239     # Read file text
240     eds_file = open(filepath,'r').read()
241     sections = ExtractSections(eds_file)
242     
243     # Parse assignments for each section
244     for section_name, assignments in sections:
245         # Reset values of entry
246         values = {}
247         
248         # Search if the section name match an index or subindex expression
249         index_result = index_model.match(section_name.upper())
250         subindex_result = subindex_model.match(section_name.upper())
251         
252         # Compilation of the EDS information dictionary
253         
254         is_entry = False
255         # First case, section name is in SECTION_KEYNAMES 
256         if section_name.upper() in SECTION_KEYNAMES:
257             # Verify that entry is not already defined
258             if section_name.upper() not in eds_dict:
259                 eds_dict[section_name.upper()] = values
260             else:
261                 raise SyntaxError, "\"[%s]\" section is defined two times"%section_name
262         # Second case, section name is a subindex name 
263         elif subindex_result:
264             # Extract index and subindex number
265             index, subindex = [int(value, 16) for value in subindex_result.groups()]
266             # If index hasn't been referenced before, we add an entry into the dictionary
267             # that will be updated later
268             if index not in eds_dict:
269                 eds_dict[index] = {"subindexes" : {}}
270             if subindex not in eds_dict[index]["subindexes"]:
271                 eds_dict[index]["subindexes"][subindex] = values
272             else:
273                 raise SyntaxError, "\"[%s]\" section is defined two times"%section_name
274             is_entry = True
275         # Third case, section name is an index name 
276         elif index_result:
277             # Extract index number
278             index = int(index_result.groups()[0], 16)
279             # If index hasn't been referenced before, we add an entry into the dictionary
280             if index not in eds_dict:
281                 eds_dict[index] = values
282                 eds_dict[index]["subindexes"] = {}
283             elif eds_dict[index].keys() == ["subindexes"]:
284                 values["subindexes"] = eds_dict[index]["subindexes"]
285                 eds_dict[index] = values
286             else:
287                 raise SyntaxError, "\"[%s]\" section is defined two times"%section_name
288             is_entry = True
289         # In any other case, there is a syntax problem into EDS file
290         else:
291             raise SyntaxError, "Section \"[%s]\" is unrecognized"%section_name
292         
293         for assignment in assignments:
294             # Escape any comment
295             if assignment.startswith(";"):
296                 pass
297             # Verify that line is a valid assignment
298             elif assignment.find('=') > 0:
299                 # Split assignment into the two values keyname and value
300                 keyname, value = assignment.split("=", 1)
301                 
302                 # keyname must be immediately followed by the "=" sign, so we
303                 # verify that there is no whitespace into keyname
304                 if keyname.isalnum():
305                     # value can be preceded and followed by whitespaces, so we escape them
306                     value = value.strip()
307                     # First case, value starts with "$NODEID", then it's a formula
308                     if value.startswith("$NODEID"):
309                         try:
310                             test = int(value.replace("$NODEID+", ""), 16)
311                             computed_value = value.replace("$NODEID", "self.ID")
312                         except:
313                             raise SyntaxError, "\"%s\" is not a valid formula for attribute \"%s\" of section \"[%s]\""%(value, keyname, section_name)
314                     # Second case, value starts with "0x", then it's an hexadecimal value
315                     elif value.startswith("0x"):
316                         try:
317                             computed_value = int(value, 16)
318                         except:
319                             raise SyntaxError, "\"%s\" is not a valid value for attribute \"%s\" of section \"[%s]\""%(value, keyname, section_name)
320                     elif value.isdigit():
321                         # Third case, value is a number and starts with "0", then it's an octal value
322                         if value.startswith("0"):
323                             computed_value = int(value, 8)
324                         # Forth case, value is a number and don't start with "0", then it's a decimal value
325                         else:
326                             computed_value = int(value)
327                     # In any other case, we keep string value
328                     else:
329                         computed_value = value
330                     
331                     # Add value to values dictionary
332                     if computed_value != "":
333                         # If entry is an index or a subindex
334                         if is_entry:
335                             # Verify that keyname is a possible attribute
336                             if keyname.upper() not in ENTRY_ATTRIBUTES:
337                                 raise SyntaxError, "Keyname \"%s\" not recognised for section \"[%s]\""%(keyname, section_name)
338                             # Verify that value is valid
339                             elif not ENTRY_ATTRIBUTES[keyname.upper()](computed_value):
340                                 raise SyntaxError, "Invalid value \"%s\" for keyname \"%s\" of section \"[%s]\""%(value, keyname, section_name)
341                             else:
342                                 values[keyname.upper()] = computed_value
343                         else:
344                             values[keyname.upper()] = computed_value
345             # All lines that are not empty and are neither a comment neither not a valid assignment
346             elif assignment.strip() != "":
347                 raise SyntaxError, "\"%s\" is not a valid EDS line"%assignment.strip()
348         
349         # If entry is an index or a subindex
350         if is_entry:
351             # Verify that entry has an ObjectType
352             if "OBJECTTYPE" in values.keys():
353                 # Extract entry ObjectType
354                 objecttype = values["OBJECTTYPE"]
355             else:
356                 # Set ObjectType to VAR by default
357                 objecttype = 7
358             # Extract parameters defined
359             keys = Set(values.keys())
360             keys.discard("subindexes")
361             # Extract possible parameters and parameters required
362             possible = Set(ENTRY_TYPES[objecttype]["require"] + ENTRY_TYPES[objecttype]["optional"])
363             required = Set(ENTRY_TYPES[objecttype]["require"])
364             # Verify that parameters defined contains all the parameters required
365             if not keys.issuperset(required):
366                 missing = required.difference(keys)._data.keys()
367                 if len(missing) > 1:
368                     attributes = "Attributes %s are"%", ".join(["\"%s\""%attribute for attribute in missing])
369                 else:
370                     attributes = "Attribute \"%s\" is"%missing[0]
371                 raise SyntaxError, "Error on section \"[%s]\":\n%s required for a%s entry"%(section_name, attributes, ENTRY_TYPES[objecttype]["name"])
372             # Verify that parameters defined are all in the possible parameters
373             if not keys.issubset(possible):
374                 unsupported = keys.difference(possible)._data.keys()
375                 if len(unsupported) > 1:
376                     attributes = "Attributes %s are"%", ".join(["\"%s\""%attribute for attribute in unsupported])
377                 else:
378                     attributes = "Attribute \"%s\" is"%unsupported[0]
379                 raise SyntaxError, "Error on section \"[%s]\":\n%s unsupported for a%s entry"%(section_name, attributes, ENTRY_TYPES[objecttype]["name"])
380             
381             if "DEFAULTVALUE" in values:
382                 try:
383                     if values["DATATYPE"] in (0x09, 0x0A, 0x0B, 0x0F):
384                         values["DEFAULTVALUE"] = str(values["DEFAULTVALUE"])
385                     elif values["DATATYPE"] in (0x08, 0x11):
386                         values["DEFAULTVALUE"] = float(values["DEFAULTVALUE"])
387                     elif values["DATATYPE"] == 0x01:
388                         values["DEFAULTVALUE"] = {0 : True, 1 : False}[values["DEFAULTVALUE"]]
389                     else:
390                         if type(values["DEFAULTVALUE"]) != IntType and values["DEFAULTVALUE"].find("self.ID") == -1:
391                             raise
392                 except:
393                     raise SyntaxError, "Error on section \"[%s]\":\nDefaultValue incompatible with DataType"%section_name
394             
395     return eds_dict
396
397
398 # Function that write an EDS file after generate it's content
399 def WriteFile(filepath, content):
400     # Open file in write mode
401     cfile = open(filepath,"w")
402     # Write content
403     cfile.write(content)
404     # Close file
405     cfile.close()
406
407
408 # Function that generate the EDS file content for the current node in the manager
409 def GenerateFileContent(filepath):
410     # Dictionary of each index contents
411     indexContents = {}
412     
413     # Extract local time
414     current_time = localtime()
415     # Extract node informations
416     nodename, nodeid, nodetype, description = Manager.GetCurrentNodeInfos()
417     
418     # Compiling lists of indexes defined
419     entries = [idx for name, idx in Manager.GetCurrentValidIndexes(0, 0xFFFF)]
420     
421     # Generate FileInfo section
422     fileContent = "[FileInfo]\n"
423     fileContent += "CreatedBy=CANFestival\n"
424     fileContent += "Description=%s\n"%description
425     fileContent += "CreationTime=%s"%strftime("%I:%M", current_time)
426     # %p option of strftime seems not working, then generate AM/PM by hands
427     if strftime("%I", current_time) == strftime("%H", current_time):
428         fileContent += "AM\n"
429     else:
430         fileContent += "PM\n"
431     fileContent += "CreationDate=%s\n"%strftime("%m-%d-%Y", current_time)
432     fileContent += "FileName=%s\n"%os.path.split(filepath)[-1]
433     fileContent += "FileVersion=1\n"
434     fileContent += "FileRevision=1\n"
435     fileContent += "EDSVersion=3.0\n"
436     
437     # Generate DeviceInfo section
438     fileContent += "\n[DeviceInfo]\n"
439     fileContent += "VendorName=CANFestival\n"
440     # Use information typed by user in Identity entry
441     fileContent += "VendorNumber=0x%8.8X\n"%Manager.GetCurrentEntry(0x1018, 1)
442     fileContent += "ProductName=%s\n"%nodename
443     fileContent += "ProductNumber=0x%8.8X\n"%Manager.GetCurrentEntry(0x1018, 2)
444     fileContent += "RevisionNumber=0x%8.8X\n"%Manager.GetCurrentEntry(0x1018, 3)
445     # CANFestival support all baudrates as soon as driver choosen support them
446     fileContent += "BaudRate_10=1\n"
447     fileContent += "BaudRate_20=1\n"
448     fileContent += "BaudRate_50=1\n"
449     fileContent += "BaudRate_125=1\n"
450     fileContent += "BaudRate_250=1\n"
451     fileContent += "BaudRate_500=1\n"
452     fileContent += "BaudRate_800=1\n"
453     fileContent += "BaudRate_1000=1\n"
454     # Select BootUp type from the informations given by user
455     fileContent += "SimpleBootUpMaster=%s\n"%BOOL_TRANSLATE[nodetype == "master"]
456     fileContent += "SimpleBootUpSlave=%s\n"%BOOL_TRANSLATE[nodetype == "slave"]
457     # CANFestival characteristics
458     fileContent += "Granularity=8\n"
459     fileContent += "DynamicChannelsSupported=0\n"
460     fileContent += "CompactPDO=0\n"
461     fileContent += "GroupMessaging=0\n"
462     # Calculate receive and tranmit PDO numbers with the entry available
463     fileContent += "NrOfRXPDO=%d\n"%len([idx for idx in entries if 0x1400 <= idx <= 0x15FF])
464     fileContent += "NrOfTXPDO=%d\n"%len([idx for idx in entries if 0x1800 <= idx <= 0x19FF])
465     # LSS not supported as soon as DS-302 was not fully implemented
466     fileContent += "LSS_Supported=0\n"
467     
468     # Generate Dummy Usage section
469     fileContent += "\n[DummyUsage]\n"
470     fileContent += "Dummy0001=0\n"
471     fileContent += "Dummy0002=1\n"
472     fileContent += "Dummy0003=1\n"
473     fileContent += "Dummy0004=1\n"
474     fileContent += "Dummy0005=1\n"
475     fileContent += "Dummy0006=1\n"
476     fileContent += "Dummy0007=1\n"
477
478     # Generate Comments section
479     fileContent += "\n[Comments]\n"
480     fileContent += "Lines=0\n"
481     
482     # List of entry by type (Mandatory, Optional or Manufacturer
483     mandatories = []
484     optionals = []
485     manufacturers = []
486     
487     # For each entry, we generate the entry section or sections if there is subindexes
488     for entry in entries:
489         # Extract infos and values for the entry
490         entry_infos = Manager.GetEntryInfos(entry)
491         values = Manager.GetCurrentEntry(entry)
492         # Define section name
493         text = "\n[%X]\n"%entry
494         # If there is only one value, it's a VAR entry
495         if type(values) != ListType:
496             # Extract the informations of the first subindex
497             subentry_infos = Manager.GetSubentryInfos(entry, 0)
498             # Generate EDS informations for the entry
499             text += "ParameterName=%s\n"%subentry_infos["name"]
500             text += "ObjectType=0x7\n"
501             text += "DataType=0x%4.4X\n"%subentry_infos["type"]
502             text += "AccessType=%s\n"%subentry_infos["access"]
503             text += "DefaultValue=%s\n"%values
504             text += "PDOMapping=%s\n"%BOOL_TRANSLATE[subentry_infos["pdo"]]
505         else:
506             # Generate EDS informations for the entry
507             text += "ParameterName=%s\n"%entry_infos["name"]
508             if entry_infos["struct"] & node.OD_IdenticalSubindexes:
509                 text += "ObjectType=0x9\n"
510             else:
511                 text += "ObjectType=0x8\n"
512             
513             # Generate EDS informations for subindexes of the entry in a separate text
514             subtext = ""
515             # Reset number of subindex defined 
516             nb_subentry = 0
517             for subentry, value in enumerate(values):
518                 # Extract the informations of each subindex
519                 subentry_infos = Manager.GetSubentryInfos(entry, subentry)
520                 # If entry is not for the compatibility, generate informations for subindex
521                 if subentry_infos["name"] != "Compatibility Entry":
522                     subtext += "\n[%Xsub%X]\n"%(entry, subentry)
523                     subtext += "ParameterName=%s\n"%subentry_infos["name"]
524                     subtext += "ObjectType=0x7\n"
525                     subtext += "DataType=0x%4.4X\n"%subentry_infos["type"]
526                     subtext += "AccessType=%s\n"%subentry_infos["access"]
527                     subtext += "DefaultValue=%s\n"%value
528                     subtext += "PDOMapping=%s\n"%BOOL_TRANSLATE[subentry_infos["pdo"]]
529                     # Increment number of subindex defined 
530                     nb_subentry += 1
531             # Write number of subindex defined for the entry
532             text += "SubNumber=%d\n"%nb_subentry
533             # Write subindex definitions
534             text += subtext
535         
536         # Then we add the entry in the right list
537         
538         # First case, entry is between 0x2000 and 0x5FFF, then it's a manufacturer entry
539         if 0x2000 <= entry <= 0x5FFF:
540             manufacturers.append(entry)
541         # Second case, entry is required, then it's a mandatory entry
542         elif entry_infos["need"]:
543             mandatories.append(entry)
544         # In any other case, it's an optional entry
545         else:
546             optionals.append(entry)
547         # Save text of the entry in the dictiionary of contents
548         indexContents[entry] = text
549     
550     # Before generate File Content we sort the entry list
551     manufacturers.sort()
552     mandatories.sort()
553     optionals.sort()
554     
555     # Generate Definition of mandatory objects
556     fileContent += "\n[MandatoryObjects]\n"
557     fileContent += "SupportedObjects=%d\n"%len(mandatories)
558     for idx, entry in enumerate(mandatories):
559         fileContent += "%d=0x%4.4X\n"%(idx, entry)
560     # Write mandatory entries
561     for entry in mandatories:
562         fileContent += indexContents[entry]
563     
564     # Generate Definition of optional objects
565     fileContent += "\n[OptionalObjects]\n"
566     fileContent += "SupportedObjects=%d\n"%len(optionals)
567     for idx, entry in enumerate(optionals):
568         fileContent += "%d=0x%4.4X\n"%(idx, entry)
569     # Write optional entries
570     for entry in optionals:
571         fileContent += indexContents[entry]
572
573     # Generate Definition of manufacturer objects
574     fileContent += "\n[ManufacturerObjects]\n"
575     fileContent += "SupportedObjects=%d\n"%len(manufacturers)
576     for idx, entry in enumerate(manufacturers):
577         fileContent += "%d=0x%4.4X\n"%(idx, entry)
578     # Write manufacturer entries
579     for entry in manufacturers:
580         fileContent += indexContents[entry]
581     
582     # Return File Content
583     return fileContent
584
585
586 # Function that generates EDS file from current node edited
587 def GenerateEDSFile(filepath, manager):
588     global Manager
589     Manager = manager
590     try:
591         # Generate file content
592         content = GenerateFileContent(filepath)
593         # Write file
594         WriteFile(filepath, content)
595         return None
596     except ValueError, message:
597         return "Unable to generate EDS file\n%s"%message
598     
599 # Function that generate the CPJ file content for the nodelist
600 def GenerateCPJContent(nodelist):
601     nodes = nodelist.SlaveNodes.keys()
602     nodes.sort()
603     
604     fileContent = "[TOPOLOGY]\n"
605     fileContent += "NetName=%s\n"%nodelist.GetNetworkName()
606     fileContent += "Nodes=0x%2.2X\n"%len(nodes)
607     
608     for nodeid in nodes:
609         fileContent += "Node%dPresent=0x01\n"%nodeid
610         fileContent += "Node%dName=%s\n"%(nodeid, nodelist.SlaveNodes[nodeid]["Name"])
611         fileContent += "Node%dDCFName=%s\n"%(nodeid, nodelist.SlaveNodes[nodeid]["EDS"])
612         
613     fileContent += "EDSBaseName=eds\n"
614     return fileContent
615
616 # Function that generates Node from an EDS file
617 def GenerateNode(filepath, cwd, nodeID = 0):
618     global Node
619     # Create a new node
620     Node = node.Node(id = nodeID)
621     try:
622         # Parse file and extract dictionary of EDS entry
623         eds_dict = ParseEDSFile(filepath)
624         # Extract Profile Number from Device Type entry
625         ProfileNb = eds_dict[0x1000]["DEFAULTVALUE"] & 0x0000ffff
626         # If profile is not DS-301 or DS-302
627         if ProfileNb not in [301, 302]:
628             # Compile Profile name and path to .prf file
629             ProfileName = "DS-%d"%ProfileNb
630             ProfilePath = os.path.join(cwd, "config/%s.prf"%ProfileName)
631             # Verify that profile is available
632             if os.path.isfile(ProfilePath):
633                 try:
634                     # Load Profile
635                     execfile(ProfilePath)
636                     Node.SetProfileName(ProfileName)
637                     Node.SetProfile(Mapping)
638                     Node.SetSpecificMenu(AddMenuEntries)
639                 except:
640                     pass
641         # Read all entries in the EDS dictionary 
642         for entry, values in eds_dict.items():
643             # All sections with a name in keynames are escaped
644             if entry in SECTION_KEYNAMES:
645                 pass
646             else:
647                 # Extract informations for the entry
648                 entry_infos = Node.GetEntryInfos(entry)
649                 
650                 # If no informations are available, then we write them
651                 if not entry_infos:
652                     # First case, entry is a VAR
653                     if values["OBJECTTYPE"] == 7:
654                         # Add mapping for entry
655                         Node.AddMappingEntry(entry, name = values["PARAMETERNAME"], struct = 1)
656                         # Add mapping for first subindex
657                         Node.AddMappingEntry(entry, 0, values = {"name" : values["PARAMETERNAME"], 
658                                                                  "type" : values["DATATYPE"], 
659                                                                  "access" : ACCESS_TRANSLATE[values["ACCESSTYPE"]], 
660                                                                  "pdo" : values.get("PDOMAPPING", 0) == 1})
661                     # Second case, entry is an ARRAY
662                     elif values["OBJECTTYPE"] == 8:
663                         # Extract maximum subindex number defined
664                         try:
665                             max_subindex = values["subindexes"][0]["DEFAULTVALUE"]
666                         except:
667                             raise SyntaxError, "Error on entry 0x%4.4X:\nSubindex 0 must be defined for an ARRAY entry"%entry
668                         # Add mapping for entry
669                         Node.AddMappingEntry(entry, name = values["PARAMETERNAME"], struct = 3)
670                         # Add mapping for first subindex
671                         Node.AddMappingEntry(entry, 0, values = {"name" : "Number of Entries", "type" : 0x05, "access" : "ro", "pdo" : False})
672                         # Add mapping for other subindexes
673                         for subindex in xrange(1, int(max_subindex) + 1):
674                             # if subindex is defined
675                             if subindex in values["subindexes"]:
676                                 Node.AddMappingEntry(entry, subindex, values = {"name" : values["subindexes"][subindex]["PARAMETERNAME"], 
677                                                                                 "type" : values["subindexes"][subindex]["DATATYPE"], 
678                                                                                 "access" : ACCESS_TRANSLATE[values["subindexes"][subindex]["ACCESSTYPE"]], 
679                                                                                 "pdo" : values["subindexes"][subindex].get("PDOMAPPING", 0) == 1})
680                             # if not, we add a mapping for compatibility 
681                             else:
682                                 Node.AddMappingEntry(entry, subindex, values = {"name" : "Compatibility Entry", "type" : 0x05, "access" : "rw", "pdo" : False})
683                     # Third case, entry is an RECORD
684                     elif values["OBJECTTYPE"] == 9:
685                         # Verify that the first subindex is defined
686                         if 0 not in values["subindexes"]:
687                             raise SyntaxError, "Error on entry 0x%4.4X:\nSubindex 0 must be defined for a RECORD entry"%entry
688                         # Add mapping for entry
689                         Node.AddMappingEntry(entry, name = values["PARAMETERNAME"], struct = 7)
690                         # Add mapping for first subindex
691                         Node.AddMappingEntry(entry, 0, values = {"name" : "Number of Entries", "type" : 0x05, "access" : "ro", "pdo" : False})
692                         # Verify that second subindex is defined
693                         if 1 in values:
694                             Node.AddMappingEntry(entry, 1, values = {"name" : values["PARAMETERNAME"] + " %d[(sub)]", 
695                                                                      "type" : values["subindexes"][1]["DATATYPE"], 
696                                                                      "access" : ACCESS_TRANSLATE[values["subindexes"][1]["ACCESSTYPE"]], 
697                                                                      "pdo" : values["subindexes"][1].get("PDOMAPPING", 0) == 1})
698                         else:
699                             raise SyntaxError, "Error on entry 0x%4.4X:\nA RECORD entry must have at least 2 subindexes"%entry
700                 
701                 # Define entry for the new node
702                 
703                 # First case, entry is a VAR
704                 if values["OBJECTTYPE"] == 7:
705                     # Take default value if it is defined
706                     if "DEFAULTVALUE" in values:
707                         value = values["DEFAULTVALUE"]
708                     # Find default value for value type of the entry
709                     else:
710                         value = GetDefaultValue(entry)
711                     Node.AddEntry(entry, 0, value)
712                 # Second case, entry is an ARRAY or a RECORD
713                 elif values["OBJECTTYPE"] in (8, 9):
714                     # Verify that "Subnumber" attribute is defined and has a valid value
715                     if "SUBNUMBER" in values and values["SUBNUMBER"] > 0:
716                         # Extract maximum subindex number defined
717                         try:
718                             max_subindex = values["subindexes"][0]["DEFAULTVALUE"]
719                         except:
720                             raise SyntaxError, "Error on entry 0x%4.4X:\nSubindex 0 must be defined for an ARRAY or a RECORD entry"%entry
721                         # Define value for all subindexes except the first 
722                         for subindex in xrange(1, int(max_subindex) + 1):
723                             # Take default value if it is defined and entry is defined
724                             if subindex in values["subindexes"] and "DEFAULTVALUE" in values["subindexes"][subindex]:
725                                 value = values["subindexes"][subindex]["DEFAULTVALUE"]
726                             # Find default value for value type of the subindex
727                             else:
728                                 value = GetDefaultValue(entry, subindex)
729                             Node.AddEntry(entry, subindex, value)
730                     else:
731                         raise SyntaxError, "Array or Record entry 0x%4.4X must have a \"SubNumber\" attribute"%entry
732         return Node
733     except SyntaxError, message:
734         return "Unable to import EDS file\n%s"%message
735
736 #-------------------------------------------------------------------------------
737 #                             Main Function
738 #-------------------------------------------------------------------------------
739
740 if __name__ == '__main__':
741     print ParseEDSFile("examples/PEAK MicroMod.eds")
742