2 # -*- coding: utf-8 -*-
4 #This file is part of CanFestival, a library implementing CanOpen Stack.
6 #Copyright (C): Edouard TISSERANT, Francis DUPIN and Laurent BESSARD
8 #See COPYING file for copyrights details.
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.
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.
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
24 from gnosis.xml.pickle import *
25 from gnosis.xml.pickle.util import setParanoia
29 import eds_in, gen_cfile
36 type_model = re.compile('([\_A-Z]*)([0-9]*)')
37 range_model = re.compile('([\_A-Z]*)([0-9]*)\[([\-0-9]*)-([\-0-9]*)\]')
38 name_model = re.compile('(.*)\[(.*)\]')
40 def IsOfType(object, typedef):
41 return type(object) == typedef
43 #-------------------------------------------------------------------------------
44 # Formating Name of an Entry
45 #-------------------------------------------------------------------------------
48 Format the text given with the index and subindex defined
51 def StringFormat(text, idx, sub):
52 result = name_model.match(text)
54 format = result.groups()
55 return format[0]%eval(format[1])
59 #-------------------------------------------------------------------------------
60 # Search in a Mapping Dictionary
61 #-------------------------------------------------------------------------------
64 Return the index of the informations in the Object Dictionary in case of identical
67 def FindIndex(index, mappingdictionary):
68 if index in mappingdictionary:
71 listpluri = [idx for idx in mappingdictionary.keys() if mappingdictionary[idx]["struct"] & OD_IdenticalIndexes]
74 nb_max = mappingdictionary[idx]["nbmax"]
75 incr = mappingdictionary[idx]["incr"]
76 if idx < index < idx + incr * nb_max and (index - idx)%incr == 0:
81 Return the index of the typename given by searching in mappingdictionary
83 def FindTypeIndex(typename, mappingdictionary):
85 for index, values in mappingdictionary.iteritems():
87 testdic[values["name"]] = index
88 if typename in testdic:
89 return testdic[typename]
93 Return the name of the type by searching in mappingdictionary
95 def FindTypeName(typeindex, mappingdictionary):
96 if typeindex < 0x1000 and typeindex in mappingdictionary:
97 return mappingdictionary[typeindex]["name"]
101 Return the default value of the type by searching in mappingdictionary
103 def FindTypeDefaultValue(typeindex, mappingdictionary):
104 if typeindex < 0x1000 and typeindex in mappingdictionary:
105 return mappingdictionary[typeindex]["default"]
109 Return the list of types defined in mappingdictionary
111 def FindTypeList(mappingdictionary):
113 for index in mappingdictionary.keys():
115 list.append((index, mappingdictionary[index]["name"]))
119 Return the name of an entry by searching in mappingdictionary
121 def FindEntryName(index, mappingdictionary):
122 base_index = FindIndex(index, mappingdictionary)
124 infos = mappingdictionary[base_index]
125 if infos["struct"] & OD_IdenticalIndexes:
126 return StringFormat(infos["name"], (index - base_index) / infos["incr"] + 1, 0)
132 Return the informations of one entry by searching in mappingdictionary
134 def FindEntryInfos(index, mappingdictionary):
135 base_index = FindIndex(index, mappingdictionary)
137 copy = mappingdictionary[base_index].copy()
138 if copy["struct"] & OD_IdenticalIndexes:
139 copy["name"] = StringFormat(copy["name"], (index - base_index) / copy["incr"] + 1, 0)
145 Return the informations of one subentry of an entry by searching in mappingdictionary
147 def FindSubentryInfos(index, subIndex, mappingdictionary):
148 base_index = FindIndex(index, mappingdictionary)
150 struct = mappingdictionary[base_index]["struct"]
151 if struct & OD_Subindex:
152 if struct & OD_IdenticalSubindexes:
153 if struct & OD_IdenticalIndexes:
154 incr = mappingdictionary[base_index]["incr"]
158 return mappingdictionary[base_index]["values"][0].copy()
159 elif 0 < subIndex <= mappingdictionary[base_index]["values"][1]["nbmax"]:
160 copy = mappingdictionary[base_index]["values"][1].copy()
161 copy["name"] = StringFormat(copy["name"], (index - base_index) / incr + 1, subIndex)
163 elif struct & OD_MultipleSubindexes and 0 <= subIndex < len(mappingdictionary[base_index]["values"]):
164 return mappingdictionary[base_index]["values"][subIndex].copy()
166 return mappingdictionary[base_index]["values"][0].copy()
170 Return the list of variables that can be mapped defined in mappingdictionary
172 def FindMapVariableList(mappingdictionary, Manager):
174 for index in mappingdictionary.iterkeys():
175 if Manager.IsCurrentEntry(index):
176 for subIndex, values in enumerate(mappingdictionary[index]["values"]):
177 if mappingdictionary[index]["values"][subIndex]["pdo"]:
178 infos = Manager.GetEntryInfos(mappingdictionary[index]["values"][subIndex]["type"])
179 if mappingdictionary[index]["struct"] & OD_IdenticalSubindexes:
180 values = Manager.GetCurrentEntry(index)
181 for i in xrange(len(values) - 1):
182 list.append((index, i + 1, infos["size"], StringFormat(mappingdictionary[index]["values"][subIndex]["name"],1,i+1)))
184 list.append((index, subIndex, infos["size"], mappingdictionary[index]["values"][subIndex]["name"]))
188 Return the list of mandatory indexes defined in mappingdictionary
190 def FindMandatoryIndexes(mappingdictionary):
192 for index in mappingdictionary.iterkeys():
193 if index >= 0x1000 and mappingdictionary[index]["need"]:
199 Class implementing a buffer of changes made on the current editing Object Dictionary
205 Constructor initialising buffer
207 def __init__(self, currentstate, issaved = False):
209 self.CurrentIndex = -1
212 # if current state is defined
214 self.CurrentIndex = 0
217 # Initialising buffer with currentstate at the first place
218 for i in xrange(UndoBufferLength):
220 self.Buffer.append(currentstate)
222 self.Buffer.append(None)
223 # Initialising index of state saved
230 Add a new state in buffer
232 def Buffering(self, currentstate):
233 self.CurrentIndex = (self.CurrentIndex + 1) % UndoBufferLength
234 self.Buffer[self.CurrentIndex] = currentstate
235 # Actualising buffer limits
236 self.MaxIndex = self.CurrentIndex
237 if self.MinIndex == self.CurrentIndex:
238 # If the removed state was the state saved, there is no state saved in the buffer
239 if self.LastSave == self.MinIndex:
241 self.MinIndex = (self.MinIndex + 1) % UndoBufferLength
242 self.MinIndex = max(self.MinIndex, 0)
245 Return current state of buffer
248 return self.Buffer[self.CurrentIndex]
251 Change current state to previous in buffer and return new current state
254 if self.CurrentIndex != self.MinIndex:
255 self.CurrentIndex = (self.CurrentIndex - 1) % UndoBufferLength
256 return self.Buffer[self.CurrentIndex]
260 Change current state to next in buffer and return new current state
263 if self.CurrentIndex != self.MaxIndex:
264 self.CurrentIndex = (self.CurrentIndex + 1) % UndoBufferLength
265 return self.Buffer[self.CurrentIndex]
269 Return True if current state is the first in buffer
272 return self.CurrentIndex == self.MinIndex
275 Return True if current state is the last in buffer
278 return self.CurrentIndex == self.MaxIndex
281 Note that current state is saved
283 def CurrentSaved(self):
284 self.LastSave = self.CurrentIndex
287 Return True if current state is saved
289 def IsCurrentSaved(self):
290 return self.LastSave == self.CurrentIndex
295 Class which control the operations made on the node and answer to view requests
304 self.LastNewIndex = 0
308 self.CurrentNode = None
309 self.UndoBuffers = []
311 #-------------------------------------------------------------------------------
312 # Type and Map Variable Lists
313 #-------------------------------------------------------------------------------
316 Generate the list of types defined for the current node
318 def GenerateTypeList(self):
320 self.TypeTranslation = {}
321 list = self.GetTypeList()
323 for index, name in list:
324 self.TypeList += "%s%s"%(sep,name)
325 self.TypeTranslation[name] = index
329 Generate the list of variables that can be mapped for the current node
331 def GenerateMapList(self):
332 self.MapList = "None"
333 self.NameTranslation = {"None" : "00000000"}
334 self.MapTranslation = {"00000000" : "None"}
335 list = self.GetMapVariableList()
336 for index, subIndex, size, name in list:
337 self.MapList += ",%s"%name
338 map = "%04X%02X%02X"%(index,subIndex,size)
339 self.NameTranslation[name] = map
340 self.MapTranslation[map] = name
343 Return the list of types defined for the current node
345 def GetCurrentTypeList(self):
349 Return the list of variables that can be mapped for the current node
351 def GetCurrentMapList(self):
354 #-------------------------------------------------------------------------------
355 # Create Load and Save Functions
356 #-------------------------------------------------------------------------------
359 Create a new node and add a new buffer for storing it
361 def CreateNewNode(self, name, id, type, profile, filepath, NMT, options):
364 # Try to load profile given
365 result = self.LoadProfile(profile, filepath, node)
366 if not IsOfType(result, StringType):
367 # if success, initialising node
368 self.CurrentNode = node
369 self.CurrentNode.SetNodeName(name)
370 self.CurrentNode.SetNodeID(id)
371 self.CurrentNode.SetNodeType(type)
372 AddIndexList = self.GetMandatoryIndexes()
373 if NMT == "NodeGuarding":
374 AddIndexList.extend([0x100C, 0x100D])
375 elif NMT == "Heartbeat":
376 AddIndexList.append(0x1017)
377 for option in options:
378 if option == "DS302":
379 # Charging DS-302 profile if choosen by user
380 if os.path.isfile("config/DS-302.prf"):
382 execfile("config/DS-302.prf")
383 self.CurrentNode.SetDS302Profile(Mapping)
384 self.CurrentNode.ExtendSpecificMenu(AddMenuEntries)
386 return "Problem with DS-302! Syntax Error."
388 return "Couldn't find DS-302 in 'config' folder!"
389 elif option == "GenSYNC":
390 AddIndexList.extend([0x1005, 0x1006])
391 elif option == "Emergency":
392 AddIndexList.append(0x1014)
393 elif option == "SaveConfig":
394 AddIndexList.extend([0x1010, 0x1011, 0x1020])
395 elif option == "StoreEDS":
396 AddIndexList.extend([0x1021, 0x1022])
399 self.SetCurrentFilePath("")
400 # Add Mandatory indexes
401 self.ManageEntriesOfCurrent(AddIndexList, [])
403 self.GenerateTypeList()
404 self.GenerateMapList()
410 Load a profile in node
412 def LoadProfile(self, profile, filepath, node):
413 if profile != "None":
414 # Try to charge the profile given
417 node.SetProfileName(profile)
418 node.SetProfile(Mapping)
419 node.SetSpecificMenu(AddMenuEntries)
422 return "Bad OD Profile file!\nSyntax Error."
425 node.SetProfileName("None")
427 node.SetSpecificMenu([])
431 Open a file and store it in a new buffer
433 def OpenFileInCurrent(self, filepath):
435 file = open(filepath, "r")
438 self.CurrentNode = node
439 # Add a new buffer and defining current state
440 self.AddNodeBuffer(self.CurrentNode.Copy(), True)
441 self.SetCurrentFilePath(filepath)
443 self.GenerateTypeList()
444 self.GenerateMapList()
448 Save current node in a file
450 def SaveCurrentInFile(self, filepath = None):
451 # if no filepath given, verify if current node has a filepath defined
453 filepath = self.GetCurrentFilePath()
457 file = open(filepath, "w")
458 dump(self.CurrentNode, file)
460 self.SetCurrentFilePath(filepath)
461 # Update saved state in buffer
462 self.UndoBuffers[self.NodeIndex].CurrentSaved()
468 def CloseCurrent(self, ignore = False):
469 # Verify if it's not forced that the current node is saved before closing it
470 if self.UndoBuffers[self.NodeIndex].IsCurrentSaved() or ignore:
471 self.RemoveNodeBuffer(self.NodeIndex)
476 Import a xml file and store it in a new buffer if no node edited
478 def ImportCurrentFromFile(self, filepath):
479 # Generate node from definition in a xml file
480 node = eds_in.GenerateNode(filepath, self)
482 self.CurrentNode = node
483 self.GenerateTypeList()
484 self.GenerateMapList()
485 if len(self.UndoBuffers) == 0:
487 self.SetCurrentFilePath("")
488 self.BufferCurrentNode()
492 Build the C definition of Object Dictionary for current node
494 def ExportCurrentToFile(self, filepath):
495 return gen_cfile.GenerateFile(filepath, self)
497 #-------------------------------------------------------------------------------
498 # Add Entries to Current Functions
499 #-------------------------------------------------------------------------------
502 Add the specified number of subentry for the given entry. Verify that total
503 number of subentry (except 0) doesn't exceed nbmax defined
505 def AddSubentriesToCurrent(self, index, number):
506 # Informations about entry
507 length = self.CurrentNode.GetEntry(index, 0)
508 infos = self.GetEntryInfos(index)
509 subentry_infos = self.GetSubentryInfos(index, 1)
510 # Get default value for subindex
511 if "default" in subentry_infos:
512 default = subentry_infos["default"]
514 default = self.GetTypeDefaultValue(subentry_infos["type"])
515 # First case entry is record
516 if infos["struct"] & OD_IdenticalSubindexes:
517 for i in xrange(1, min(number,subentry_infos["nbmax"]-length) + 1):
518 self.CurrentNode.AddEntry(index, length + i, default)
519 self.BufferCurrentNode()
520 # Second case entry is array, only possible for manufacturer specific
521 elif infos["struct"] & OD_MultipleSubindexes and 0x2000 <= index <= 0x5FFF:
522 values = {"name" : "Undefined", "type" : 5, "access" : "rw", "pdo" : True}
523 for i in xrange(1, min(number,0xFE-length) + 1):
524 self.CurrentNode.AddMappingEntry(index, length + i, values = values.copy())
525 self.CurrentNode.AddEntry(index, length + i, 0)
526 self.BufferCurrentNode()
529 Remove the specified number of subentry for the given entry. Verify that total
530 number of subentry (except 0) isn't less than 1
532 def RemoveSubentriesFromCurrent(self, index, number):
533 # Informations about entry
534 infos = self.GetEntryInfos(index)
535 length = self.CurrentNode.GetEntry(index, 0)
536 # Entry is a record, or is an array of manufacturer specific
537 if infos["struct"] & OD_IdenticalSubindexes or 0x2000 <= index <= 0x5FFF and infos["struct"] & OD_IdenticalSubindexes:
538 for i in xrange(min(number, length - 1)):
539 self.RemoveCurrentVariable(index, length - i)
540 self.BufferCurrentNode()
543 Add a SDO Server to current node
545 def AddSDOServerToCurrent(self):
546 # An SDO Server is already defined at index 0x1200
547 if self.CurrentNode.IsEntry(0x1200):
548 indexlist = [self.GetLineFromIndex(0x1201)]
549 if None not in indexlist:
550 self.ManageEntriesOfCurrent(indexlist, [])
551 # Add an SDO Server at index 0x1200
553 self.ManageEntriesOfCurrent([0x1200], [])
556 Add a SDO Server to current node
558 def AddSDOClientToCurrent(self):
559 indexlist = [self.GetLineFromIndex(0x1280)]
560 if None not in indexlist:
561 self.ManageEntriesOfCurrent(indexlist, [])
564 Add a Transmit PDO to current node
566 def AddPDOTransmitToCurrent(self):
567 indexlist = [self.GetLineFromIndex(0x1800),self.GetLineFromIndex(0x1A00)]
568 if None not in indexlist:
569 self.ManageEntriesOfCurrent(indexlist, [])
572 Add a Receive PDO to current node
574 def AddPDOReceiveToCurrent(self):
575 indexlist = [self.GetLineFromIndex(0x1400),self.GetLineFromIndex(0x1600)]
576 if None not in indexlist:
577 self.ManageEntriesOfCurrent(indexlist, [])
580 Add a list of entries defined in profile for menu item selected to current node
582 def AddSpecificEntryToCurrent(self, menuitem):
584 for menu, indexes in self.CurrentNode.GetSpecificMenu():
586 for index in indexes:
587 indexlist.append(self.GetLineFromIndex(index))
588 if None not in indexlist:
589 self.ManageEntriesOfCurrent(indexlist, [])
592 Search the first index available for a pluri entry from base_index
594 def GetLineFromIndex(self, base_index):
597 infos = self.GetEntryInfos(base_index)
598 while index < base_index + infos["incr"]*infos["nbmax"] and not found:
599 if not self.CurrentNode.IsEntry(index):
602 index += infos["incr"]
608 Add entries specified in addinglist and remove entries specified in removinglist
610 def ManageEntriesOfCurrent(self, addinglist, removinglist):
611 # Add all the entries in addinglist
612 for index in addinglist:
613 infos = self.GetEntryInfos(index)
614 if infos["struct"] & OD_MultipleSubindexes:
615 # First case entry is a record
616 if infos["struct"] & OD_IdenticalSubindexes:
617 subentry_infos = self.GetSubentryInfos(index, 1)
618 if "default" in subentry_infos:
619 default = subentry_infos["default"]
621 default = self.GetTypeDefaultValue(subentry_infos["type"])
622 self.CurrentNode.AddEntry(index, 1, default)
623 # Second case entry is a record
626 subentry_infos = self.GetSubentryInfos(index, i)
627 while subentry_infos:
628 if "default" in subentry_infos:
629 default = subentry_infos["default"]
631 default = self.GetTypeDefaultValue(subentry_infos["type"])
632 self.CurrentNode.AddEntry(index, i, default)
634 subentry_infos = self.GetSubentryInfos(index, i)
635 # Third case entry is a record
637 subentry_infos = self.GetSubentryInfos(index, 0)
638 if "default" in subentry_infos:
639 default = subentry_infos["default"]
641 default = self.GetTypeDefaultValue(subentry_infos["type"])
642 self.CurrentNode.AddEntry(index, 0, default)
643 # Remove all the entries in removinglist
644 for index in removinglist:
645 self.RemoveCurrentVariable(index)
646 self.BufferCurrentNode()
649 Remove an entry from current node. Analize the index to perform the correct
652 def RemoveCurrentVariable(self, index, subIndex = None):
653 Mappings = self.CurrentNode.GetMappings()
654 if index < 0x1000 and subIndex == None:
655 type = self.CurrentNode.GetEntry(index, 1)
656 for i in Mappings[-1]:
657 for value in Mappings[-1][i]["values"]:
658 if value["type"] == index:
660 self.CurrentNode.RemoveMappingEntry(index)
661 self.CurrentNode.RemoveEntry(index)
662 elif index == 0x1200 and subIndex == None:
663 self.CurrentNode.RemoveEntry(0x1200)
664 elif 0x1201 <= index <= 0x127F and subIndex == None:
665 self.CurrentNode.RemoveLine(index, 0x127F)
666 elif 0x1280 <= index <= 0x12FF and subIndex == None:
667 self.CurrentNode.RemoveLine(index, 0x12FF)
668 elif 0x1400 <= index <= 0x15FF or 0x1600 <= index <= 0x17FF and subIndex == None:
669 if 0x1600 <= index <= 0x17FF and subIndex == None:
671 self.CurrentNode.RemoveLine(index, 0x15FF)
672 self.CurrentNode.RemoveLine(index + 0x200, 0x17FF)
673 elif 0x1800 <= index <= 0x19FF or 0x1A00 <= index <= 0x1BFF and subIndex == None:
674 if 0x1A00 <= index <= 0x1BFF:
676 self.CurrentNode.RemoveLine(index, 0x19FF)
677 self.CurrentNode.RemoveLine(index + 0x200, 0x1BFF)
680 for menu,list in self.CurrentNode.GetSpecificMenu():
682 iinfos = self.GetEntryInfos(i)
683 indexes = [i + incr * iinfos["incr"] for incr in xrange(iinfos["nbmax"])]
688 jinfos = self.GetEntryInfos(j)
689 self.CurrentNode.RemoveLine(j + diff, j + jinfos["incr"]*jinfos["nbmax"], jinfos["incr"])
690 self.CurrentNode.RemoveMapVariable(index, subIndex)
692 infos = self.GetEntryInfos(index)
693 if not infos["need"]:
694 self.CurrentNode.RemoveEntry(index, subIndex)
695 if index in Mappings[-1]:
696 self.CurrentNode.RemoveMappingEntry(index, subIndex)
697 self.GenerateMapList()
699 def AddMapVariableToCurrent(self, index, name, struct, number):
700 if 0x2000 <= index <= 0x5FFF:
701 if not self.CurrentNode.IsEntry(index):
702 self.CurrentNode.AddMappingEntry(index, name = name, struct = struct)
704 values = {"name" : name, "type" : 5, "access" : "rw", "pdo" : True}
705 self.CurrentNode.AddMappingEntry(index, 0, values = values)
706 self.CurrentNode.AddEntry(index, 0, 0)
708 values = {"name" : "Number of Entries", "type" : 2, "access" : "ro", "pdo" : False}
709 self.CurrentNode.AddMappingEntry(index, 0, values = values)
711 values = {"name" : name + " %d[(sub)]", "type" : 5, "access" : "rw", "pdo" : True, "nbmax" : 0xFE}
712 self.CurrentNode.AddMappingEntry(index, 1, values = values)
713 for i in xrange(number):
714 self.CurrentNode.AddEntry(index, i + 1, 0)
716 for i in xrange(number):
717 values = {"name" : "Undefined", "type" : 5, "access" : "rw", "pdo" : True}
718 self.CurrentNode.AddMappingEntry(index, i + 1, values = values)
719 self.CurrentNode.AddEntry(index, i + 1, 0)
720 self.GenerateMapList()
721 self.BufferCurrentNode()
724 return "Index 0x%04X already defined!"%index
726 return "Index 0x%04X isn't a valid index for Map Variable!"%index
728 def AddUserTypeToCurrent(self, type, min, max, length):
730 while index < 0x100 and self.CurrentNode.IsEntry(index):
733 customisabletypes = self.GetCustomisableTypes()
734 name, valuetype = customisabletypes[type]
735 size = self.GetEntryInfos(type)["size"]
736 default = self.GetTypeDefaultValue(type)
738 self.CurrentNode.AddMappingEntry(index, name = "%s[%d-%d]"%(name, min, max), struct = 3, size = size, default = default)
739 self.CurrentNode.AddMappingEntry(index, 0, values = {"name" : "Number of Entries", "type" : 0x02, "access" : "ro", "pdo" : False})
740 self.CurrentNode.AddMappingEntry(index, 1, values = {"name" : "Type", "type" : 0x02, "access" : "ro", "pdo" : False})
741 self.CurrentNode.AddMappingEntry(index, 2, values = {"name" : "Minimum Value", "type" : type, "access" : "ro", "pdo" : False})
742 self.CurrentNode.AddMappingEntry(index, 3, values = {"name" : "Maximum Value", "type" : type, "access" : "ro", "pdo" : False})
743 self.CurrentNode.AddEntry(index, 1, type)
744 self.CurrentNode.AddEntry(index, 2, min)
745 self.CurrentNode.AddEntry(index, 3, max)
747 self.CurrentNode.AddMappingEntry(index, name = "%s%d"%(name, length), struct = 3, size = length * size, default = default)
748 self.CurrentNode.AddMappingEntry(index, 0, values = {"name" : "Number of Entries", "type" : 0x02, "access" : "ro", "pdo" : False})
749 self.CurrentNode.AddMappingEntry(index, 1, values = {"name" : "Type", "type" : 0x02, "access" : "ro", "pdo" : False})
750 self.CurrentNode.AddMappingEntry(index, 2, values = {"name" : "Length", "type" : 0x02, "access" : "ro", "pdo" : False})
751 self.CurrentNode.AddEntry(index, 1, type)
752 self.CurrentNode.AddEntry(index, 2, length)
753 self.GenerateTypeList()
754 self.BufferCurrentNode()
757 return "Too many User Types have already been defined!"
759 #-------------------------------------------------------------------------------
760 # Modify Entry and Mapping Functions
761 #-------------------------------------------------------------------------------
763 def SetCurrentEntryCallbacks(self, index, value):
764 if self.CurrentNode and self.CurrentNode.IsEntry(index):
765 entry_infos = self.GetEntryInfos(index)
766 if "callback" not in entry_infos:
767 self.CurrentNode.SetParamsEntry(index, None, callback = value)
768 self.BufferCurrentNode()
770 def SetCurrentEntry(self, index, subIndex, value, name, editor):
771 if self.CurrentNode and self.CurrentNode.IsEntry(index):
774 value = eval("0x%s"%self.NameTranslation[value])
775 self.CurrentNode.SetEntry(index, subIndex, value)
776 elif editor == "bool":
777 value = value == "True"
778 self.CurrentNode.SetEntry(index, subIndex, value)
779 elif editor == "time":
780 self.CurrentNode.SetEntry(index, subIndex, value)
781 elif editor == "domain":
783 if len(value) % 2 != 0:
785 value = value.decode('hex_codec')
786 self.CurrentNode.SetEntry(index, subIndex, value)
790 subentry_infos = self.GetSubentryInfos(index, subIndex)
791 type = subentry_infos["type"]
793 for typeindex, typevalue in CustomisableTypes:
794 dic[typeindex] = typevalue
796 type = self.CurrentNode.GetEntry(type)[1]
799 value = eval(value, {})
800 self.CurrentNode.SetEntry(index, subIndex, value)
804 self.CurrentNode.SetEntry(index, subIndex, value)
805 elif name in ["comment", "save"]:
806 if editor == "option":
807 value = value == "Yes"
809 self.CurrentNode.SetParamsEntry(index, subIndex, save = value)
810 elif name == "comment":
811 self.CurrentNode.SetParamsEntry(index, subIndex, comment = value)
814 value = self.TypeTranslation[value]
815 size = self.GetEntryInfos(value)["size"]
816 self.CurrentNode.UpdateMapVariable(index, subIndex, size)
817 elif editor in ["access","raccess"]:
819 for abbrev,access in AccessType.iteritems():
822 if editor == "raccess" and not self.CurrentNode.IsMappingEntry(index):
823 entry_infos = self.GetEntryInfos(index)
824 self.CurrentNode.AddMappingEntry(index, name = entry_infos["name"], struct = 7)
825 self.CurrentNode.AddMappingEntry(index, 0, values = self.GetSubentryInfos(index, 0, False).copy())
826 self.CurrentNode.AddMappingEntry(index, 1, values = self.GetSubentryInfos(index, 1, False).copy())
827 self.CurrentNode.SetMappingEntry(index, subIndex, values = {name : value})
828 if name == "name" or editor == "type":
829 self.GenerateMapList()
830 self.BufferCurrentNode()
832 def SetCurrentEntryName(self, index, name):
833 self.CurrentNode.SetMappingEntry(index, name=name)
834 self.BufferCurrentNode()
836 def SetCurrentUserType(self, index, type, min, max, length):
837 customisabletypes = self.GetCustomisableTypes()
838 values, valuetype = self.GetCustomisedTypeValues(index)
839 name, new_valuetype = customisabletypes[type]
840 size = self.GetEntryInfos(type)["size"]
841 default = self.GetTypeDefaultValue(type)
842 if new_valuetype == 0:
843 self.CurrentNode.SetMappingEntry(index, name = "%s[%d-%d]"%(name, min, max), struct = 3, size = size, default = default)
845 self.CurrentNode.SetMappingEntry(index, 2, values = {"name" : "Minimum Value", "type" : type, "access" : "ro", "pdo" : False})
846 self.CurrentNode.AddMappingEntry(index, 3, values = {"name" : "Maximum Value", "type" : type, "access" : "ro", "pdo" : False})
847 self.CurrentNode.SetEntry(index, 1, type)
848 self.CurrentNode.SetEntry(index, 2, min)
850 self.CurrentNode.AddEntry(index, 3, max)
852 self.CurrentNode.SetEntry(index, 3, max)
853 elif new_valuetype == 1:
854 self.CurrentNode.SetMappingEntry(index, name = "%s%d"%(name, length), struct = 3, size = size, default = default)
856 self.CurrentNode.SetMappingEntry(index, 2, values = {"name" : "Length", "type" : 0x02, "access" : "ro", "pdo" : False})
857 self.CurrentNode.RemoveMappingEntry(index, 3)
858 self.CurrentNode.SetEntry(index, 1, type)
859 self.CurrentNode.SetEntry(index, 2, length)
861 self.CurrentNode.RemoveEntry(index, 3)
862 self.BufferCurrentNode()
864 #-------------------------------------------------------------------------------
865 # Current Buffering Management Functions
866 #-------------------------------------------------------------------------------
868 def BufferCurrentNode(self):
869 self.UndoBuffers[self.NodeIndex].Buffering(self.CurrentNode.Copy())
871 def CurrentIsSaved(self):
872 return self.UndoBuffers[self.NodeIndex].IsCurrentSaved()
874 def OneFileHasChanged(self):
876 for buffer in self.UndoBuffers:
877 result |= not buffer.IsCurrentSaved()
880 def GetBufferNumber(self):
881 return len(self.UndoBuffers)
883 def LoadCurrentPrevious(self):
884 self.CurrentNode = self.UndoBuffers[self.NodeIndex].Previous().Copy()
886 def LoadCurrentNext(self):
887 self.CurrentNode = self.UndoBuffers[self.NodeIndex].Next().Copy()
889 def AddNodeBuffer(self, currentstate = None, issaved = False):
890 self.NodeIndex = len(self.UndoBuffers)
891 self.UndoBuffers.append(UndoBuffer(currentstate, issaved))
892 self.FilePaths.append("")
893 self.FileNames.append("")
895 def ChangeCurrentNode(self, index):
896 if index < len(self.UndoBuffers):
897 self.NodeIndex = index
898 self.CurrentNode = self.UndoBuffers[self.NodeIndex].Current().Copy()
899 self.GenerateTypeList()
900 self.GenerateMapList()
902 def RemoveNodeBuffer(self, index):
903 self.UndoBuffers.pop(index)
904 self.FilePaths.pop(index)
905 self.FileNames.pop(index)
906 self.NodeIndex = min(self.NodeIndex, len(self.UndoBuffers) - 1)
907 if len(self.UndoBuffers) > 0:
908 self.CurrentNode = self.UndoBuffers[self.NodeIndex].Current().Copy()
909 self.GenerateTypeList()
910 self.GenerateMapList()
912 self.CurrentNode = None
914 def GetCurrentNodeIndex(self):
915 return self.NodeIndex
917 def GetCurrentFilename(self):
918 return self.GetFilename(self.NodeIndex)
920 def GetAllFilenames(self):
922 for i in xrange(len(self.UndoBuffers)):
923 filenames.append(self.GetFilename(i))
926 def GetFilename(self, index):
927 if self.UndoBuffers[index].IsCurrentSaved():
928 return self.FileNames[index]
930 return "~%s~"%self.FileNames[index]
932 def SetCurrentFilePath(self, filepath):
933 self.FilePaths[self.NodeIndex] = filepath
935 self.LastNewIndex += 1
936 self.FileNames[self.NodeIndex] = "Unnamed%d"%self.LastNewIndex
938 self.FileNames[self.NodeIndex] = os.path.splitext(os.path.basename(filepath))[0]
940 def GetCurrentFilePath(self):
941 if len(self.FilePaths) > 0:
942 return self.FilePaths[self.NodeIndex]
946 def GetCurrentBufferState(self):
947 first = self.UndoBuffers[self.NodeIndex].IsFirst()
948 last = self.UndoBuffers[self.NodeIndex].IsLast()
949 return not first, not last
951 #-------------------------------------------------------------------------------
952 # Profiles Management Functions
953 #-------------------------------------------------------------------------------
955 def GetCurrentCommunicationLists(self):
957 for index in MappingDictionary.iterkeys():
958 if 0x1000 <= index < 0x1200:
960 return self.GetProfileLists(MappingDictionary, list)
962 def GetCurrentDS302Lists(self):
963 return self.GetSpecificProfileLists(self.CurrentNode.GetDS302Profile())
965 def GetCurrentProfileLists(self):
966 return self.GetSpecificProfileLists(self.CurrentNode.GetProfile())
968 def GetSpecificProfileLists(self, mappingdictionary):
971 for name, list in self.CurrentNode.GetSpecificMenu():
972 exclusionlist.extend(list)
973 for index in mappingdictionary.iterkeys():
974 if index not in exclusionlist:
975 validlist.append(index)
976 return self.GetProfileLists(mappingdictionary, validlist)
978 def GetProfileLists(self, mappingdictionary, list):
982 dictionary[index] = (mappingdictionary[index]["name"], mappingdictionary[index]["need"])
983 if self.CurrentNode.IsEntry(index):
984 current.append(index)
985 return dictionary, current
987 def GetCurrentNextMapIndex(self):
990 while self.CurrentNode.IsEntry(index) and index < 0x5FFF:
997 def CurrentDS302Defined(self):
999 return len(self.CurrentNode.GetDS302Profile()) > 0
1002 #-------------------------------------------------------------------------------
1003 # Node State and Values Functions
1004 #-------------------------------------------------------------------------------
1006 def GetCurrentNodeInfos(self):
1007 name = self.CurrentNode.GetNodeName()
1008 id = self.CurrentNode.GetNodeID()
1009 type = self.CurrentNode.GetNodeType()
1010 return name, id, type
1012 def SetCurrentNodeInfos(self, name, id, type):
1013 self.CurrentNode.SetNodeName(name)
1014 self.CurrentNode.SetNodeID(id)
1015 self.CurrentNode.SetNodeType(type)
1016 self.BufferCurrentNode()
1018 def GetCurrentProfileName(self):
1019 if self.CurrentNode:
1020 return self.CurrentNode.GetProfileName()
1023 def IsCurrentEntry(self, index):
1024 if self.CurrentNode:
1025 return self.CurrentNode.IsEntry(index)
1028 def GetCurrentEntry(self, index, subIndex = None):
1029 if self.CurrentNode:
1030 return self.CurrentNode.GetEntry(index, subIndex)
1033 def GetCurrentParamsEntry(self, index, subIndex = None):
1034 if self.CurrentNode:
1035 return self.CurrentNode.GetParamsEntry(index, subIndex)
1038 def GetCurrentValidIndexes(self, min, max):
1040 for index in self.CurrentNode.GetIndexes():
1041 if min <= index <= max:
1042 validindexes.append((self.GetEntryName(index), index))
1045 def GetCurrentValidChoices(self, min, max):
1048 for menu, indexes in self.CurrentNode.GetSpecificMenu():
1049 exclusionlist.extend(indexes)
1051 for index in indexes:
1052 good &= min <= index <= max
1054 validchoices.append((menu, None))
1055 list = [index for index in MappingDictionary.keys() if index >= 0x1000]
1056 profiles = self.CurrentNode.GetMappings(False)
1057 for profile in profiles:
1058 list.extend(profile.keys())
1061 if min <= index <= max and not self.CurrentNode.IsEntry(index) and index not in exclusionlist:
1062 validchoices.append((self.GetEntryName(index), index))
1065 def HasCurrentEntryCallbacks(self, index):
1066 if self.CurrentNode and self.CurrentNode.IsEntry(index):
1067 entry_infos = self.GetEntryInfos(index)
1068 if "callback" in entry_infos:
1069 return entry_infos["callback"]
1070 return self.CurrentNode.HasEntryCallbacks(index)
1073 def GetCurrentEntryValues(self, index):
1074 if self.CurrentNode and self.CurrentNode.IsEntry(index):
1075 entry_infos = self.GetEntryInfos(index)
1078 values = self.CurrentNode.GetEntry(index)
1079 params = self.CurrentNode.GetParamsEntry(index)
1080 if type(values) == ListType:
1081 for i, value in enumerate(values):
1082 data.append({"value" : value})
1083 data[-1].update(params[i])
1085 data.append({"value" : values})
1086 data[-1].update(params)
1087 for i, dic in enumerate(data):
1088 infos = self.GetSubentryInfos(index, i)
1089 dic["subindex"] = "0x%02X"%i
1090 dic["name"] = infos["name"]
1091 dic["type"] = self.GetTypeName(infos["type"])
1092 dic["access"] = AccessType[infos["access"]]
1093 dic["save"] = OptionType[dic["save"]]
1094 editor = {"subindex" : None, "save" : "option", "callback" : "option", "comment" : "string"}
1095 if type(values) == ListType and i == 0:
1096 editor["name"] = None
1097 editor["type"] = None
1098 if 0x1600 <= index <= 0x17FF or 0x1A00 <= index <= 0x1C00:
1099 editor["access"] = "raccess"
1101 editor["access"] = None
1102 editor["value"] = None
1104 if infos["user_defined"]:
1105 if entry_infos["struct"] & OD_IdenticalSubindexes:
1106 editor["name"] = None
1108 editor["type"] = None
1109 editor["access"] = None
1111 editor["type"] = "type"
1112 editor["access"] = "access"
1114 if entry_infos["struct"] & OD_MultipleSubindexes:
1115 editor["name"] = "string"
1117 editor["name"] = None
1118 editor["type"] = "type"
1119 editor["access"] = "access"
1121 editor["name"] = None
1122 editor["type"] = None
1123 editor["access"] = None
1125 editor["value"] = None
1127 dic["value"] = self.GetTypeName(dic["value"])
1128 elif 0x1600 <= index <= 0x17FF or 0x1A00 <= index <= 0x1C00:
1129 editor["value"] = "map"
1130 dic["value"] = self.MapTranslation["%08X"%dic["value"]]
1132 if dic["type"].startswith("VISIBLE_STRING"):
1133 editor["value"] = "string"
1134 elif dic["type"] in ["TIME_OF_DAY","TIME_DIFFERENCE"]:
1135 editor["value"] = "time"
1136 elif dic["type"] == "DOMAIN":
1137 editor["value"] = "domain"
1138 dic["value"] = dic["value"].encode('hex_codec')
1139 elif dic["type"] == "BOOLEAN":
1140 editor["value"] = "bool"
1141 dic["value"] = BoolType[dic["value"]]
1142 result = type_model.match(dic["type"])
1144 values = result.groups()
1145 if values[0] in ["INTEGER", "UNSIGNED"]:
1146 format = "0x%0" + str(int(values[1])/4) + "X"
1147 dic["value"] = format%dic["value"]
1148 editor["value"] = "string"
1149 elif values[0] == "REAL":
1150 editor["value"] = "float"
1151 elif values[0] == "VISIBLE_STRING":
1152 editor["length"] = values[0]
1153 result = range_model.match(dic["type"])
1155 values = result.groups()
1156 if values[0] in ("UNSIGNED", "REAL"):
1157 editor["min"] = values[2]
1158 editor["max"] = values[3]
1159 editors.append(editor)
1160 return data, editors
1164 #-------------------------------------------------------------------------------
1165 # Node Informations Functions
1166 #-------------------------------------------------------------------------------
1168 def GetCustomisedTypeValues(self, index):
1169 values = self.CurrentNode.GetEntry(index)
1170 customisabletypes = self.GetCustomisableTypes()
1171 return values, customisabletypes[values[1]][1]
1173 def GetEntryName(self, index, node = True):
1176 NodeMappings = self.CurrentNode.GetMappings()
1178 while not result and i < len(NodeMappings):
1179 result = FindEntryName(index, NodeMappings[i])
1182 result = FindEntryName(index, MappingDictionary)
1185 def GetEntryInfos(self, index, node = True):
1188 NodeMappings = self.CurrentNode.GetMappings()
1190 while not result and i < len(NodeMappings):
1191 result = FindEntryInfos(index, NodeMappings[i])
1194 result = FindEntryInfos(index, MappingDictionary)
1197 def GetSubentryInfos(self, index, subIndex, node = True):
1200 NodeMappings = self.CurrentNode.GetMappings()
1202 while not result and i < len(NodeMappings):
1203 result = FindSubentryInfos(index, subIndex, NodeMappings[i])
1205 result["user_defined"] = i == len(NodeMappings) - 1 and index >= 0x1000
1208 result = FindSubentryInfos(index, subIndex, MappingDictionary)
1210 result["user_defined"] = False
1213 def GetTypeIndex(self, typename, node = True):
1216 NodeMappings = self.CurrentNode.GetMappings()
1218 while not result and i < len(NodeMappings):
1219 result = FindTypeIndex(typename, NodeMappings[i])
1222 result = FindTypeIndex(typename, MappingDictionary)
1225 def GetTypeName(self, typeindex, node = True):
1228 NodeMappings = self.CurrentNode.GetMappings()
1230 while not result and i < len(NodeMappings):
1231 result = FindTypeName(typeindex, NodeMappings[i])
1234 result = FindTypeName(typeindex, MappingDictionary)
1237 def GetTypeDefaultValue(self, typeindex, node = True):
1240 NodeMappings = self.CurrentNode.GetMappings()
1242 while not result and i < len(NodeMappings):
1243 result = FindTypeDefaultValue(typeindex, NodeMappings[i])
1246 result = FindTypeDefaultValue(typeindex, MappingDictionary)
1249 def GetTypeList(self, node = True):
1250 list = FindTypeList(MappingDictionary)
1252 for NodeMapping in self.CurrentNode.GetMappings():
1253 list.extend(FindTypeList(NodeMapping))
1257 def GetMapVariableList(self):
1258 list = FindMapVariableList(MappingDictionary, self)
1259 for NodeMapping in self.CurrentNode.GetMappings():
1260 list.extend(FindMapVariableList(NodeMapping, self))
1264 def GetMandatoryIndexes(self, node = True):
1265 list = FindMandatoryIndexes(MappingDictionary)
1267 for NodeMapping in self.CurrentNode.GetMappings():
1268 list.extend(FindMandatoryIndexes(NodeMapping))
1271 def GetCustomisableTypes(self):
1273 for index, valuetype in CustomisableTypes:
1274 name = self.GetTypeName(index)
1275 dic[index] = [name, valuetype]
1278 def GetCurrentSpecificMenu(self):
1279 if self.CurrentNode:
1280 return self.CurrentNode.GetSpecificMenu()