# HG changeset patch # User Edouard Tisserant # Date 1384744351 -32400 # Node ID 02fe382c451166eb77197406ebcaf46416ce1cbc # Parent 72a826dfcfbb15c6412cf49ce93a77499d1dd0cc# Parent dc94c71a2f2512cc667335b298a878179ff1b018 RC5 diff -r 72a826dfcfbb -r 02fe382c4511 Beremiz.py --- a/Beremiz.py Wed Jul 31 10:45:07 2013 +0900 +++ b/Beremiz.py Mon Nov 18 12:12:31 2013 +0900 @@ -141,7 +141,6 @@ from editors.EditorPanel import EditorPanel from editors.Viewer import Viewer from editors.TextViewer import TextViewer -from editors.GraphicViewer import GraphicViewer from editors.ResourceEditor import ConfigurationEditor, ResourceEditor from editors.DataTypeEditor import DataTypeEditor from util.MiniTextControler import MiniTextControler @@ -150,34 +149,11 @@ from controls.CustomStyledTextCtrl import CustomStyledTextCtrl from PLCControler import LOCATION_CONFNODE, LOCATION_MODULE, LOCATION_GROUP, LOCATION_VAR_INPUT, LOCATION_VAR_OUTPUT, LOCATION_VAR_MEMORY, ITEM_PROJECT, ITEM_RESOURCE -from ProjectController import ProjectController, MATIEC_ERROR_MODEL, ITEM_CONFNODE +from ProjectController import ProjectController, GetAddMenuItems, MATIEC_ERROR_MODEL, ITEM_CONFNODE MAX_RECENT_PROJECTS = 10 -class GenStaticBitmap(wx.lib.statbmp.GenStaticBitmap): - """ Customized GenStaticBitmap, fix transparency redraw bug on wx2.8/win32, - and accept image name as __init__ parameter, fail silently if file do not exist""" - def __init__(self, parent, ID, bitmapname, - pos = wx.DefaultPosition, size = wx.DefaultSize, - style = 0, - name = "genstatbmp"): - - wx.lib.statbmp.GenStaticBitmap.__init__(self, parent, ID, - GetBitmap(bitmapname), - pos, size, - style, - name) - - def OnPaint(self, event): - dc = wx.PaintDC(self) - colour = self.GetParent().GetBackgroundColour() - dc.SetPen(wx.Pen(colour)) - dc.SetBrush(wx.Brush(colour )) - dc.DrawRectangle(0, 0, *dc.GetSizeTuple()) - if self._bitmap: - dc.DrawBitmap(self._bitmap, 0, 0, True) - if wx.Platform == '__WXMSW__': faces = { 'mono' : 'Courier New', @@ -300,14 +276,7 @@ def isatty(self): return False -[ID_BEREMIZ, ID_BEREMIZMAINSPLITTER, - ID_BEREMIZPLCCONFIG, ID_BEREMIZLOGCONSOLE, - ID_BEREMIZINSPECTOR] = [wx.NewId() for _init_ctrls in range(5)] - -[ID_FILEMENURECENTPROJECTS, -] = [wx.NewId() for _init_ctrls in range(1)] - -CONFNODEMENU_POSITION = 3 +ID_FILEMENURECENTPROJECTS = wx.NewId() class Beremiz(IDEFrame): @@ -360,6 +329,19 @@ (wx.ID_SAVEAS, "saveas", _(u'Save As...'), None), (wx.ID_PRINT, "print", _(u'Print'), None)]) + def _RecursiveAddMenuItems(self, menu, items): + for name, text, help, children in items: + new_id = wx.NewId() + if len(children) > 0: + new_menu = wx.Menu(title='') + menu.AppendMenu(new_id, text, new_menu) + self._RecursiveAddMenuItems(new_menu, children) + else: + AppendMenu(menu, help=help, id=new_id, + kind=wx.ITEM_NORMAL, text=text) + self.Bind(wx.EVT_MENU, self.GetAddConfNodeFunction(name), + id=new_id) + def _init_coll_AddMenu_Items(self, parent): IDEFrame._init_coll_AddMenu_Items(self, parent, False) @@ -369,11 +351,7 @@ # kind=wx.ITEM_NORMAL, text=_(u'&Resource')) #self.Bind(wx.EVT_MENU, self.AddResourceMenu, id=new_id) - for name, XSDClass, help in ProjectController.CTNChildrenTypes: - new_id = wx.NewId() - AppendMenu(parent, help='', id=new_id, - kind=wx.ITEM_NORMAL, text=help) - self.Bind(wx.EVT_MENU, self.GetAddConfNodeFunction(name), id=new_id) + self._RecursiveAddMenuItems(parent, GetAddMenuItems()) def _init_coll_HelpMenu_Items(self, parent): parent.Append(help='', id=wx.ID_ABOUT, @@ -394,8 +372,9 @@ self.EditMenuSize = self.EditMenu.GetMenuItemCount() - self.Bind(wx.EVT_MENU, self.OnOpenWidgetInspector, id=ID_BEREMIZINSPECTOR) - accels = [wx.AcceleratorEntry(wx.ACCEL_CTRL|wx.ACCEL_ALT, ord('I'), ID_BEREMIZINSPECTOR)] + inspectorID = wx.NewId() + self.Bind(wx.EVT_MENU, self.OnOpenWidgetInspector, id=inspectorID) + accels = [wx.AcceleratorEntry(wx.ACCEL_CTRL|wx.ACCEL_ALT, ord('I'), inspectorID)] for method,shortcut in [("Stop", wx.WXK_F4), ("Run", wx.WXK_F5), ("Transfer", wx.WXK_F6), @@ -413,7 +392,7 @@ self.SetAcceleratorTable(wx.AcceleratorTable(accels)) - self.LogConsole = CustomStyledTextCtrl(id=ID_BEREMIZLOGCONSOLE, + self.LogConsole = CustomStyledTextCtrl( name='LogConsole', parent=self.BottomNoteBook, pos=wx.Point(0, 0), size=wx.Size(0, 0)) self.LogConsole.Bind(wx.EVT_SET_FOCUS, self.OnLogConsoleFocusChanged) @@ -637,7 +616,6 @@ if (isinstance(tab, EditorPanel) and not isinstance(tab, (Viewer, TextViewer, - GraphicViewer, ResourceEditor, ConfigurationEditor, DataTypeEditor))): diff -r 72a826dfcfbb -r 02fe382c4511 CodeFileTreeNode.py --- a/CodeFileTreeNode.py Wed Jul 31 10:45:07 2013 +0900 +++ b/CodeFileTreeNode.py Mon Nov 18 12:12:31 2013 +0900 @@ -1,13 +1,15 @@ -import os -from xml.dom import minidom -import cPickle - -from xmlclass import GenerateClassesFromXSDstring, UpdateXMLClassGlobals +import os, re, traceback + +from copy import deepcopy +from lxml import etree +from xmlclass import GenerateParserFromXSDstring from PLCControler import UndoBuffer +from ConfigTreeNode import XSDSchemaErrorMessage CODEFILE_XSD = """ - + @@ -65,22 +67,36 @@ [SECTION_TAG_ELEMENT % name for name in self.SECTIONS_NAMES if name != "includes"]) - self.CodeFileClasses = GenerateClassesFromXSDstring( + self.CodeFileParser = GenerateParserFromXSDstring( CODEFILE_XSD % sections_str) + self.CodeFileVariables = etree.XPath("variables/variable") filepath = self.CodeFileName() - self.CodeFile = self.CodeFileClasses[self.CODEFILE_NAME]() if os.path.isfile(filepath): xmlfile = open(filepath, 'r') - tree = minidom.parse(xmlfile) + codefile_xml = xmlfile.read() xmlfile.close() - for child in tree.childNodes: - if child.nodeType == tree.ELEMENT_NODE and child.nodeName in [self.CODEFILE_NAME]: - self.CodeFile.loadXMLTree(child, ["xmlns", "xmlns:xsi", "xsi:schemaLocation"]) - self.CreateCodeFileBuffer(True) + codefile_xml = codefile_xml.replace( + '<%s>' % self.CODEFILE_NAME, + '<%s xmlns:xhtml="http://www.w3.org/1999/xhtml">' % self.CODEFILE_NAME) + for cre, repl in [ + (re.compile("(?)(?:)(?!)"), "]]>")]: + codefile_xml = cre.sub(repl, codefile_xml) + + try: + self.CodeFile, error = self.CodeFileParser.LoadXMLString(codefile_xml) + if error is not None: + self.GetCTRoot().logger.write_warning( + XSDSchemaErrorMessage % ((self.CODEFILE_NAME,) + error)) + self.CreateCodeFileBuffer(True) + except Exception, exc: + self.GetCTRoot().logger.write_error(_("Couldn't load confnode parameters %s :\n %s") % (CTNName, unicode(exc))) + self.GetCTRoot().logger.write_error(traceback.format_exc()) else: + self.CodeFile = self.CodeFileParser.CreateRoot() self.CreateCodeFileBuffer(False) self.OnCTNSave() @@ -99,7 +115,7 @@ def SetVariables(self, variables): self.CodeFile.variables.setvariable([]) for var in variables: - variable = self.CodeFileClasses["variables_variable"]() + variable = self.CodeFileParser.CreateElement("variable", "variables") variable.setname(var["Name"]) variable.settype(var["Type"]) variable.setinitial(var["Initial"]) @@ -107,7 +123,7 @@ def GetVariables(self): datas = [] - for var in self.CodeFile.variables.getvariable(): + for var in self.CodeFileVariables(self.CodeFile): datas.append({"Name" : var.getname(), "Type" : var.gettype(), "Initial" : var.getinitial()}) @@ -117,10 +133,10 @@ for section in self.SECTIONS_NAMES: section_code = parts.get(section) if section_code is not None: - getattr(self.CodeFile, section).settext(section_code) + getattr(self.CodeFile, section).setanyText(section_code) def GetTextParts(self): - return dict([(section, getattr(self.CodeFile, section).gettext()) + return dict([(section, getattr(self.CodeFile, section).getanyText()) for section in self.SECTIONS_NAMES]) def CTNTestModified(self): @@ -129,11 +145,12 @@ def OnCTNSave(self, from_project_path=None): filepath = self.CodeFileName() - text = "\n" - text += self.CodeFile.generateXMLText(self.CODEFILE_NAME, 0) - xmlfile = open(filepath,"w") - xmlfile.write(text.encode("utf-8")) + xmlfile.write(etree.tostring( + self.CodeFile, + pretty_print=True, + xml_declaration=True, + encoding='utf-8')) xmlfile.close() self.MarkCodeFileAsSaved() @@ -144,39 +161,31 @@ return [(variable.getname(), variable.gettype(), variable.getinitial()) - for variable in self.CodeFile.variables.variable] + for variable in self.CodeFileVariables(self.CodeFile)] #------------------------------------------------------------------------------- # Current Buffering Management Functions #------------------------------------------------------------------------------- - def cPickle_loads(self, str_obj): - UpdateXMLClassGlobals(self.CodeFileClasses) - return cPickle.loads(str_obj) - - def cPickle_dumps(self, obj): - UpdateXMLClassGlobals(self.CodeFileClasses) - return cPickle.dumps(obj) - """ Return a copy of the codefile model """ def Copy(self, model): - return self.cPickle_loads(self.cPickle_dumps(model)) + return deepcopy(model) def CreateCodeFileBuffer(self, saved): self.Buffering = False - self.CodeFileBuffer = UndoBuffer(self.cPickle_dumps(self.CodeFile), saved) + self.CodeFileBuffer = UndoBuffer(self.CodeFileParser.Dumps(self.CodeFile), saved) def BufferCodeFile(self): - self.CodeFileBuffer.Buffering(self.cPickle_dumps(self.CodeFile)) + self.CodeFileBuffer.Buffering(self.CodeFileParser.Dumps(self.CodeFile)) def StartBuffering(self): self.Buffering = True def EndBuffering(self): if self.Buffering: - self.CodeFileBuffer.Buffering(self.cPickle_dumps(self.CodeFile)) + self.CodeFileBuffer.Buffering(self.CodeFileParser.Dumps(self.CodeFile)) self.Buffering = False def MarkCodeFileAsSaved(self): @@ -188,10 +197,10 @@ def LoadPrevious(self): self.EndBuffering() - self.CodeFile = self.cPickle_loads(self.CodeFileBuffer.Previous()) + self.CodeFile = self.CodeFileParser.Loads(self.CodeFileBuffer.Previous()) def LoadNext(self): - self.CodeFile = self.cPickle_loads(self.CodeFileBuffer.Next()) + self.CodeFile = self.CodeFileParser.Loads(self.CodeFileBuffer.Next()) def GetBufferState(self): first = self.CodeFileBuffer.IsFirst() and not self.Buffering diff -r 72a826dfcfbb -r 02fe382c4511 ConfigTreeNode.py --- a/ConfigTreeNode.py Wed Jul 31 10:45:07 2013 +0900 +++ b/ConfigTreeNode.py Mon Nov 18 12:12:31 2013 +0900 @@ -9,15 +9,15 @@ import os,traceback,types import shutil -from xml.dom import minidom - -from xmlclass import GenerateClassesFromXSDstring +from lxml import etree + +from xmlclass import GenerateParserFromXSDstring from util.misc import GetClassImporter from PLCControler import PLCControler, LOCATION_CONFNODE from editors.ConfTreeNodeEditor import ConfTreeNodeEditor -_BaseParamsClass = GenerateClassesFromXSDstring(""" +_BaseParamsParser = GenerateParserFromXSDstring(""" @@ -26,9 +26,10 @@ - """)["BaseParams"] + """) NameTypeSeparator = '@' +XSDSchemaErrorMessage = _("%s XML file doesn't follow XSD schema at line %d:\n%s") class ConfigTreeNode: """ @@ -46,17 +47,15 @@ def _AddParamsMembers(self): self.CTNParams = None if self.XSD: - self.Classes = GenerateClassesFromXSDstring(self.XSD) - Classes = [(name, XSDclass) for name, XSDclass in self.Classes.items() if XSDclass.IsBaseClass] - if len(Classes) == 1: - name, XSDclass = Classes[0] - obj = XSDclass() - self.CTNParams = (name, obj) - setattr(self, name, obj) + self.Parser = GenerateParserFromXSDstring(self.XSD) + obj = self.Parser.CreateRoot() + name = obj.getLocalTag() + self.CTNParams = (name, obj) + setattr(self, name, obj) def __init__(self): # Create BaseParam - self.BaseParams = _BaseParamsClass() + self.BaseParams = _BaseParamsParser.CreateRoot() self.MandatoryParams = ("BaseParams", self.BaseParams) self._AddParamsMembers() self.Children = {} @@ -170,15 +169,21 @@ # generate XML for base XML parameters controller of the confnode if self.MandatoryParams: BaseXMLFile = open(self.ConfNodeBaseXmlFilePath(),'w') - BaseXMLFile.write("\n") - BaseXMLFile.write(self.MandatoryParams[1].generateXMLText(self.MandatoryParams[0], 0).encode("utf-8")) + BaseXMLFile.write(etree.tostring( + self.MandatoryParams[1], + pretty_print=True, + xml_declaration=True, + encoding='utf-8')) BaseXMLFile.close() # generate XML for XML parameters controller of the confnode if self.CTNParams: XMLFile = open(self.ConfNodeXmlFilePath(),'w') - XMLFile.write("\n") - XMLFile.write(self.CTNParams[1].generateXMLText(self.CTNParams[0], 0).encode("utf-8")) + XMLFile.write(etree.tostring( + self.CTNParams[1], + pretty_print=True, + xml_declaration=True, + encoding='utf-8')) XMLFile.close() # Call the confnode specific OnCTNSave method @@ -577,26 +582,36 @@ if os.path.isfile(methode_name): execfile(methode_name) + ConfNodeName = CTNName if CTNName is not None else self.CTNName() + # Get the base xml tree if self.MandatoryParams: try: basexmlfile = open(self.ConfNodeBaseXmlFilePath(CTNName), 'r') - basetree = minidom.parse(basexmlfile) - self.MandatoryParams[1].loadXMLTree(basetree.childNodes[0]) + self.BaseParams, error = _BaseParamsParser.LoadXMLString(basexmlfile.read()) + if error is not None: + self.GetCTRoot().logger.write_warning( + XSDSchemaErrorMessage % ((ConfNodeName + " BaseParams",) + error)) + self.MandatoryParams = ("BaseParams", self.BaseParams) basexmlfile.close() except Exception, exc: - self.GetCTRoot().logger.write_error(_("Couldn't load confnode base parameters %s :\n %s") % (CTNName, unicode(exc))) + self.GetCTRoot().logger.write_error(_("Couldn't load confnode base parameters %s :\n %s") % (ConfNodeName, unicode(exc))) self.GetCTRoot().logger.write_error(traceback.format_exc()) # Get the xml tree if self.CTNParams: try: xmlfile = open(self.ConfNodeXmlFilePath(CTNName), 'r') - tree = minidom.parse(xmlfile) - self.CTNParams[1].loadXMLTree(tree.childNodes[0]) + obj, error = self.Parser.LoadXMLString(xmlfile.read()) + if error is not None: + self.GetCTRoot().logger.write_warning( + XSDSchemaErrorMessage % ((ConfNodeName,) + error)) + name = obj.getLocalTag() + setattr(self, name, obj) + self.CTNParams = (name, obj) xmlfile.close() except Exception, exc: - self.GetCTRoot().logger.write_error(_("Couldn't load confnode parameters %s :\n %s") % (CTNName, unicode(exc))) + self.GetCTRoot().logger.write_error(_("Couldn't load confnode parameters %s :\n %s") % (ConfNodeName, unicode(exc))) self.GetCTRoot().logger.write_error(traceback.format_exc()) def LoadChildren(self): diff -r 72a826dfcfbb -r 02fe382c4511 IDEFrame.py --- a/IDEFrame.py Wed Jul 31 10:45:07 2013 +0900 +++ b/IDEFrame.py Mon Nov 18 12:12:31 2013 +0900 @@ -6,19 +6,11 @@ import wx, wx.grid import wx.aui -try: - import matplotlib - matplotlib.use('WX') - USE_MPL = True -except: - USE_MPL = False - from editors.EditorPanel import EditorPanel from editors.SFCViewer import SFC_Viewer from editors.LDViewer import LD_Viewer from editors.TextViewer import TextViewer from editors.Viewer import Viewer, ZOOM_FACTORS -from editors.GraphicViewer import GraphicViewer from editors.ResourceEditor import ConfigurationEditor, ResourceEditor from editors.DataTypeEditor import DataTypeEditor from PLCControler import * @@ -1952,11 +1944,7 @@ elif instance_category in ITEMS_VARIABLE: if self.Controler.IsNumType(instance_type, True): - if USE_MPL: - self.AddDebugVariable(instance_path, True) - else: - new_window = GraphicViewer(self.TabsOpened, self, self.Controler, instance_path) - icon = GetBitmap("GRAPH") + self.AddDebugVariable(instance_path, True) else: bodytype = self.Controler.GetEditedElementBodyType(instance_type, True) @@ -1996,10 +1984,6 @@ def ResetGraphicViewers(self): if self.EnableDebug: - for i in xrange(self.TabsOpened.GetPageCount()): - editor = self.TabsOpened.GetPage(i) - if isinstance(editor, GraphicViewer): - editor.ResetView() self.DebugVariablePanel.ResetGraphicsValues() def CloseObsoleteDebugTabs(self): @@ -2008,12 +1992,10 @@ idxs.reverse() for idx in idxs: editor = self.TabsOpened.GetPage(idx) - if isinstance(editor, (Viewer, GraphicViewer)) and editor.IsDebugging(): + if isinstance(editor, Viewer) and editor.IsDebugging(): instance_infos = self.Controler.GetInstanceInfos(editor.GetInstancePath(), self.EnableDebug) if instance_infos is None: self.TabsOpened.DeletePage(idx) - elif isinstance(editor, GraphicViewer): - editor.ResetView(True) else: editor.SubscribeAllDataConsumers() elif editor.IsDebugging(): @@ -2074,7 +2056,7 @@ menu = None if selected != -1: window = self.TabsOpened.GetPage(selected) - if isinstance(window, (Viewer, TextViewer, GraphicViewer)): + if isinstance(window, (Viewer, TextViewer)): if not window.IsDebugging(): menu = self.Controler.GetEditedElementBodyType(window.GetTagName()) else: @@ -2302,7 +2284,6 @@ if tagname is not None: self._Refresh(TITLE, FILEMENU, EDITMENU, PROJECTTREE, POUINSTANCEVARIABLESPANEL) self.EditProjectElement(ITEM_CONFIGURATION, tagname) - dialog.Destroy() def GenerateAddResourceFunction(self, config_name): def OnAddResourceMenu(event): diff -r 72a826dfcfbb -r 02fe382c4511 PLCControler.py --- a/PLCControler.py Wed Jul 31 10:45:07 2013 +0900 +++ b/PLCControler.py Mon Nov 18 12:12:31 2013 +0900 @@ -24,13 +24,14 @@ from xml.dom import minidom from types import StringType, UnicodeType, TupleType -import cPickle +from lxml import etree +from copy import deepcopy import os,sys,re import datetime from time import localtime - -from plcopen import plcopen -from plcopen.structures import * +from collections import OrderedDict, namedtuple + +from plcopen import * from graphics.GraphicCommons import * from PLCGenerator import * @@ -66,14 +67,14 @@ ITEM_VAR_INOUT ] = range(17, 24) -VAR_CLASS_INFOS = {"Local" : (plcopen.interface_localVars, ITEM_VAR_LOCAL), - "Global" : (plcopen.interface_globalVars, ITEM_VAR_GLOBAL), - "External" : (plcopen.interface_externalVars, ITEM_VAR_EXTERNAL), - "Temp" : (plcopen.interface_tempVars, ITEM_VAR_TEMP), - "Input" : (plcopen.interface_inputVars, ITEM_VAR_INPUT), - "Output" : (plcopen.interface_outputVars, ITEM_VAR_OUTPUT), - "InOut" : (plcopen.interface_inOutVars, ITEM_VAR_INOUT) - } +VAR_CLASS_INFOS = { + "Local": ("localVars", ITEM_VAR_LOCAL), + "Global": ("globalVars", ITEM_VAR_GLOBAL), + "External": ("externalVars", ITEM_VAR_EXTERNAL), + "Temp": ("tempVars", ITEM_VAR_TEMP), + "Input": ("inputVars", ITEM_VAR_INPUT), + "Output": ("outputVars", ITEM_VAR_OUTPUT), + "InOut": ("inOutVars", ITEM_VAR_INOUT)} POU_TYPES = {"program": ITEM_PROGRAM, "functionBlock": ITEM_FUNCTIONBLOCK, @@ -100,6 +101,332 @@ RESOURCES, PROPERTIES] = UNEDITABLE_NAMES #------------------------------------------------------------------------------- +# Helper object for loading library in xslt stylesheets +#------------------------------------------------------------------------------- + +class LibraryResolver(etree.Resolver): + + def __init__(self, controller, debug=False): + self.Controller = controller + self.Debug = debug + + def resolve(self, url, pubid, context): + lib_name = os.path.basename(url) + if lib_name in ["project", "stdlib", "extensions"]: + lib_el = etree.Element(lib_name) + if lib_name == "project": + lib_el.append(deepcopy(self.Controller.GetProject(self.Debug))) + elif lib_name == "stdlib": + for lib in [StdBlockLibrary, AddnlBlockLibrary]: + lib_el.append(deepcopy(lib)) + else: + for ctn in self.Controller.ConfNodeTypes: + lib_el.append(deepcopy(ctn["types"])) + return self.resolve_string(etree.tostring(lib_el), context) + +#------------------------------------------------------------------------------- +# Helpers functions for translating list of arguments +# from xslt to valid arguments +#------------------------------------------------------------------------------- + +_BoolValue = lambda x: x in ["true", "0"] + +def _translate_args(translations, args): + return [translate(arg[0]) if len(arg) > 0 else None + for translate, arg in + zip(translations, args)] + +#------------------------------------------------------------------------------- +# Helpers object for generating pou var list +#------------------------------------------------------------------------------- + +class _VariableInfos(object): + __slots__ = ["Name", "Class", "Option", "Location", "InitialValue", + "Edit", "Documentation", "Type", "Tree", "Number"] + def __init__(self, *args): + for attr, value in zip(self.__slots__, args): + setattr(self, attr, value if value is not None else "") + def copy(self): + return _VariableInfos(*[getattr(self, attr) for attr in self.__slots__]) + +class VariablesInfosFactory: + + def __init__(self, variables): + self.Variables = variables + self.TreeStack = [] + self.Type = None + self.Dimensions = None + + def SetType(self, context, *args): + self.Type = args[0][0] + + def GetType(self): + if len(self.Dimensions) > 0: + return ("array", self.Type, self.Dimensions) + return self.Type + + def GetTree(self): + return (self.TreeStack.pop(-1), self.Dimensions) + + def AddDimension(self, context, *args): + self.Dimensions.append(tuple( + _translate_args([str] * 2, args))) + + def AddTree(self, context, *args): + self.TreeStack.append([]) + self.Dimensions = [] + + def AddVarToTree(self, context, *args): + var = (args[0][0], self.Type, self.GetTree()) + self.TreeStack[-1].append(var) + + def AddVariable(self, context, *args): + self.Variables.append(_VariableInfos(*(_translate_args( + [str] * 5 + [_BoolValue] + [str], args) + + [self.GetType(), self.GetTree()]))) + +#------------------------------------------------------------------------------- +# Helpers object for generating pou variable instance list +#------------------------------------------------------------------------------- + +def class_extraction(value): + class_type = { + "configuration": ITEM_CONFIGURATION, + "resource": ITEM_RESOURCE, + "action": ITEM_ACTION, + "transition": ITEM_TRANSITION, + "program": ITEM_PROGRAM}.get(value) + if class_type is not None: + return class_type + + pou_type = POU_TYPES.get(value) + if pou_type is not None: + return pou_type + + var_type = VAR_CLASS_INFOS.get(value) + if var_type is not None: + return var_type[1] + + return None + +class _VariablesTreeItemInfos(object): + __slots__ = ["name", "var_class", "type", "edit", "debug", "variables"] + def __init__(self, *args): + for attr, value in zip(self.__slots__, args): + setattr(self, attr, value if value is not None else "") + def copy(self): + return _VariableTreeItem(*[getattr(self, attr) for attr in self.__slots__]) + +class VariablesTreeInfosFactory: + + def __init__(self): + self.Root = None + + def GetRoot(self): + return self.Root + + def SetRoot(self, context, *args): + self.Root = _VariablesTreeItemInfos( + *([''] + _translate_args( + [class_extraction, str] + [_BoolValue] * 2, + args) + [[]])) + + def AddVariable(self, context, *args): + if self.Root is not None: + self.Root.variables.append(_VariablesTreeItemInfos( + *(_translate_args( + [str, class_extraction, str] + [_BoolValue] * 2, + args) + [[]]))) + +#------------------------------------------------------------------------------- +# Helpers object for generating instances path list +#------------------------------------------------------------------------------- + +class InstancesPathFactory: + + def __init__(self, instances): + self.Instances = instances + + def AddInstance(self, context, *args): + self.Instances.append(args[0][0]) + +#------------------------------------------------------------------------------- +# Helpers object for generating instance tagname +#------------------------------------------------------------------------------- + +class InstanceTagName: + + def __init__(self, controller): + self.Controller = controller + self.TagName = None + + def GetTagName(self): + return self.TagName + + def ConfigTagName(self, context, *args): + self.TagName = self.Controller.ComputeConfigurationName(args[0][0]) + + def ResourceTagName(self, context, *args): + self.TagName = self.Controller.ComputeConfigurationResourceName(args[0][0], args[1][0]) + + def PouTagName(self, context, *args): + self.TagName = self.Controller.ComputePouName(args[0][0]) + + def ActionTagName(self, context, *args): + self.TagName = self.Controller.ComputePouActionName(args[0][0], args[0][1]) + + def TransitionTagName(self, context, *args): + self.TagName = self.Controller.ComputePouTransitionName(args[0][0], args[0][1]) + +#------------------------------------------------------------------------------- +# Helpers object for generating pou block instances list +#------------------------------------------------------------------------------- + +_Point = namedtuple("Point", ["x", "y"]) + +_BlockInstanceInfos = namedtuple("BlockInstanceInfos", + ["type", "id", "x", "y", "width", "height", "specific_values", "inputs", "outputs"]) + +_BlockSpecificValues = ( + namedtuple("BlockSpecificValues", + ["name", "execution_order"]), + [str, int]) +_VariableSpecificValues = ( + namedtuple("VariableSpecificValues", + ["name", "value_type", "execution_order"]), + [str, str, int]) +_ConnectionSpecificValues = ( + namedtuple("ConnectionSpecificValues", ["name"]), + [str]) + +_PowerRailSpecificValues = ( + namedtuple("PowerRailSpecificValues", ["connectors"]), + [int]) + +_LDElementSpecificValues = ( + namedtuple("LDElementSpecificValues", + ["name", "negated", "edge", "storage", "execution_order"]), + [str, _BoolValue, str, str, int]) + +_DivergenceSpecificValues = ( + namedtuple("DivergenceSpecificValues", ["connectors"]), + [int]) + +_SpecificValuesTuples = { + "comment": ( + namedtuple("CommentSpecificValues", ["content"]), + [str]), + "input": _VariableSpecificValues, + "output": _VariableSpecificValues, + "inout": _VariableSpecificValues, + "connector": _ConnectionSpecificValues, + "continuation": _ConnectionSpecificValues, + "leftPowerRail": _PowerRailSpecificValues, + "rightPowerRail": _PowerRailSpecificValues, + "contact": _LDElementSpecificValues, + "coil": _LDElementSpecificValues, + "step": ( + namedtuple("StepSpecificValues", ["name", "initial", "action"]), + [str, _BoolValue, lambda x: x]), + "transition": ( + namedtuple("TransitionSpecificValues", + ["priority", "condition_type", "condition", "connection"]), + [int, str, str, lambda x: x]), + "selectionDivergence": _DivergenceSpecificValues, + "selectionConvergence": _DivergenceSpecificValues, + "simultaneousDivergence": _DivergenceSpecificValues, + "simultaneousConvergence": _DivergenceSpecificValues, + "jump": ( + namedtuple("JumpSpecificValues", ["target"]), + [str]), + "actionBlock": ( + namedtuple("ActionBlockSpecificValues", ["actions"]), + [lambda x: x]), +} + +_InstanceConnectionInfos = namedtuple("InstanceConnectionInfos", + ["name", "negated", "edge", "position", "links"]) + +_ConnectionLinkInfos = namedtuple("ConnectionLinkInfos", + ["refLocalId", "formalParameter", "points"]) + +class _ActionInfos(object): + __slots__ = ["qualifier", "type", "value", "duration", "indicator"] + def __init__(self, *args): + for attr, value in zip(self.__slots__, args): + setattr(self, attr, value if value is not None else "") + def copy(self): + return _ActionInfos(*[getattr(self, attr) for attr in self.__slots__]) + +class BlockInstanceFactory: + + def __init__(self, block_instances): + self.BlockInstances = block_instances + self.CurrentInstance = None + self.SpecificValues = None + self.CurrentConnection = None + self.CurrentLink = None + + def SetSpecificValues(self, context, *args): + self.SpecificValues = list(args) + self.CurrentInstance = None + self.CurrentConnection = None + self.CurrentLink = None + + def AddBlockInstance(self, context, *args): + specific_values_tuple, specific_values_translation = \ + _SpecificValuesTuples.get(args[0][0], _BlockSpecificValues) + + if (args[0][0] == "step" and len(self.SpecificValues) < 3 or + args[0][0] == "transition" and len(self.SpecificValues) < 4): + self.SpecificValues.append([None]) + elif args[0][0] == "actionBlock" and len(self.SpecificValues) < 1: + self.SpecificValues.append([[]]) + specific_values = specific_values_tuple(*_translate_args( + specific_values_translation, self.SpecificValues)) + self.SpecificValues = None + + self.CurrentInstance = _BlockInstanceInfos( + *(_translate_args([str, int] + [float] * 4, args) + + [specific_values, [], []])) + + self.BlockInstances[self.CurrentInstance.id] = self.CurrentInstance + + def AddInstanceConnection(self, context, *args): + connection_args = _translate_args( + [str, str, _BoolValue, str, float, float], args) + + self.CurrentConnection = _InstanceConnectionInfos( + *(connection_args[1:4] + [ + _Point(*connection_args[4:6]), []])) + + if self.CurrentInstance is not None: + if connection_args[0] == "input": + self.CurrentInstance.inputs.append(self.CurrentConnection) + else: + self.CurrentInstance.outputs.append(self.CurrentConnection) + else: + self.SpecificValues.append([self.CurrentConnection]) + + def AddConnectionLink(self, context, *args): + self.CurrentLink = _ConnectionLinkInfos( + *(_translate_args([int, str], args) + [[]])) + self.CurrentConnection.links.append(self.CurrentLink) + + def AddLinkPoint(self, context, *args): + self.CurrentLink.points.append(_Point( + *_translate_args([float] * 2, args))) + + def AddAction(self, context, *args): + if len(self.SpecificValues) == 0: + self.SpecificValues.append([[]]) + translated_args = _translate_args([str] * 5, args) + self.SpecificValues[0][0].append(_ActionInfos(*translated_args)) + +pou_block_instances_xslt = etree.parse( + os.path.join(ScriptDirectory, "plcopen", "pou_block_instances.xslt")) + +#------------------------------------------------------------------------------- # Undo Buffer for PLCOpenEditor #------------------------------------------------------------------------------- @@ -210,10 +537,12 @@ self.NextCompiledProject = None self.CurrentCompiledProject = None self.ConfNodeTypes = [] + self.TotalTypesDict = StdBlckDct.copy() + self.TotalTypes = StdBlckLst[:] self.ProgramFilePath = "" - + def GetQualifierTypes(self): - return plcopen.QualifierList + return QualifierList def GetProject(self, debug = False): if debug and self.CurrentCompiledProject is not None: @@ -232,11 +561,12 @@ # Create a new project by replacing the current one def CreateNewProject(self, properties): # Create the project - self.Project = plcopen.project() + self.Project = PLCOpenParser.CreateRoot() properties["creationDateTime"] = datetime.datetime(*localtime()[:6]) self.Project.setfileHeader(properties) self.Project.setcontentHeader(properties) self.SetFilePath("") + # Initialize the project buffer self.CreateProjectBuffer(False) self.ProgramChunks = [] @@ -273,7 +603,7 @@ if project is not None: for pou in project.getpous(): if pou_name is None or pou_name == pou.getname(): - variables.extend([var["Name"] for var in self.GetPouInterfaceVars(pou, debug)]) + variables.extend([var.Name for var in self.GetPouInterfaceVars(pou, debug=debug)]) for transition in pou.gettransitionList(): variables.append(transition.getname()) for action in pou.getactionList(): @@ -386,223 +716,61 @@ return infos return None - def GetPouVariableInfos(self, project, variable, var_class, debug=False): - vartype_content = variable.gettype().getcontent() - if vartype_content["name"] == "derived": - var_type = vartype_content["value"].getname() - pou_type = None - pou = project.getpou(var_type) - if pou is not None: - pou_type = pou.getpouType() - edit = debug = pou_type is not None - if pou_type is None: - block_infos = self.GetBlockType(var_type, debug = debug) - if block_infos is not None: - pou_type = block_infos["type"] - if pou_type is not None: - var_class = None - if pou_type == "program": - var_class = ITEM_PROGRAM - elif pou_type != "function": - var_class = ITEM_FUNCTIONBLOCK - if var_class is not None: - return {"name": variable.getname(), - "type": var_type, - "class": var_class, - "edit": edit, - "debug": debug} - elif var_type in self.GetDataTypes(debug = debug): - return {"name": variable.getname(), - "type": var_type, - "class": var_class, - "edit": False, - "debug": False} - elif vartype_content["name"] in ["string", "wstring"]: - return {"name": variable.getname(), - "type": vartype_content["name"].upper(), - "class": var_class, - "edit": False, - "debug": True} - else: - return {"name": variable.getname(), - "type": vartype_content["name"], - "class": var_class, - "edit": False, - "debug": True} - return None - def GetPouVariables(self, tagname, debug = False): - vars = [] pou_type = None project = self.GetProject(debug) if project is not None: + factory = VariablesTreeInfosFactory() + + parser = etree.XMLParser() + parser.resolvers.add(LibraryResolver(self, debug)) + + pou_variable_xslt_tree = etree.XSLT( + etree.parse( + os.path.join(ScriptDirectory, "plcopen", "pou_variables.xslt"), + parser), + extensions = {("pou_vars_ns", name): getattr(factory, name) + for name in ["SetRoot", "AddVariable"]}) + + obj = None words = tagname.split("::") if words[0] == "P": - pou = project.getpou(words[1]) - if pou is not None: - pou_type = pou.getpouType() - if (pou_type in ["program", "functionBlock"] and - pou.interface is not None): - # Extract variables from every varLists - for varlist_type, varlist in pou.getvars(): - var_infos = VAR_CLASS_INFOS.get(varlist_type, None) - if var_infos is not None: - var_class = var_infos[1] - else: - var_class = ITEM_VAR_LOCAL - for variable in varlist.getvariable(): - var_infos = self.GetPouVariableInfos(project, variable, var_class, debug) - if var_infos is not None: - vars.append(var_infos) - if pou.getbodyType() == "SFC": - for transition in pou.gettransitionList(): - vars.append({ - "name": transition.getname(), - "type": None, - "class": ITEM_TRANSITION, - "edit": True, - "debug": True}) - for action in pou.getactionList(): - vars.append({ - "name": action.getname(), - "type": None, - "class": ITEM_ACTION, - "edit": True, - "debug": True}) - return {"class": POU_TYPES[pou_type], - "type": words[1], - "variables": vars, - "edit": True, - "debug": True} - else: - block_infos = self.GetBlockType(words[1], debug = debug) - if (block_infos is not None and - block_infos["type"] in ["program", "functionBlock"]): - for varname, vartype, varmodifier in block_infos["inputs"]: - vars.append({"name" : varname, - "type" : vartype, - "class" : ITEM_VAR_INPUT, - "edit": False, - "debug": True}) - for varname, vartype, varmodifier in block_infos["outputs"]: - vars.append({"name" : varname, - "type" : vartype, - "class" : ITEM_VAR_OUTPUT, - "edit": False, - "debug": True}) - return {"class": POU_TYPES[block_infos["type"]], - "type": None, - "variables": vars, - "edit": False, - "debug": False} - elif words[0] in ['A', 'T']: - pou_vars = self.GetPouVariables(self.ComputePouName(words[1]), debug) - if pou_vars is not None: - if words[0] == 'A': - element_type = ITEM_ACTION - elif words[0] == 'T': - element_type = ITEM_TRANSITION - return {"class": element_type, - "type": None, - "variables": [var for var in pou_vars["variables"] - if var["class"] not in [ITEM_ACTION, ITEM_TRANSITION]], - "edit": True, - "debug": True} - elif words[0] in ['C', 'R']: - if words[0] == 'C': - element_type = ITEM_CONFIGURATION - element = project.getconfiguration(words[1]) - if element is not None: - for resource in element.getresource(): - vars.append({"name": resource.getname(), - "type": None, - "class": ITEM_RESOURCE, - "edit": True, - "debug": False}) - elif words[0] == 'R': - element_type = ITEM_RESOURCE - element = project.getconfigurationResource(words[1], words[2]) - if element is not None: - for task in element.gettask(): - for pou in task.getpouInstance(): - vars.append({"name": pou.getname(), - "type": pou.gettypeName(), - "class": ITEM_PROGRAM, - "edit": True, - "debug": True}) - for pou in element.getpouInstance(): - vars.append({"name": pou.getname(), - "type": pou.gettypeName(), - "class": ITEM_PROGRAM, - "edit": True, - "debug": True}) - if element is not None: - for varlist in element.getglobalVars(): - for variable in varlist.getvariable(): - var_infos = self.GetPouVariableInfos(project, variable, ITEM_VAR_GLOBAL, debug) - if var_infos is not None: - vars.append(var_infos) - return {"class": element_type, - "type": None, - "variables": vars, - "edit": True, - "debug": False} + obj = self.GetPou(words[1], debug) + elif words[0] != "D": + obj = self.GetEditedElement(tagname, debug) + if obj is not None: + pou_variable_xslt_tree(obj) + return factory.GetRoot() + return None - def RecursiveSearchPouInstances(self, project, pou_type, parent_path, varlists, debug = False): + def GetInstanceList(self, root, name, debug = False): instances = [] - for varlist in varlists: - for variable in varlist.getvariable(): - vartype_content = variable.gettype().getcontent() - if vartype_content["name"] == "derived": - var_path = "%s.%s" % (parent_path, variable.getname()) - var_type = vartype_content["value"].getname() - if var_type == pou_type: - instances.append(var_path) - else: - pou = project.getpou(var_type) - if pou is not None and project.ElementIsUsedBy(pou_type, var_type): - instances.extend( - self.RecursiveSearchPouInstances( - project, pou_type, var_path, - [varlist for type, varlist in pou.getvars()], - debug)) + project = self.GetProject(debug) + if project is not None: + factory = InstancesPathFactory(instances) + + parser = etree.XMLParser() + parser.resolvers.add(LibraryResolver(self, debug)) + + instances_path_xslt_tree = etree.XSLT( + etree.parse( + os.path.join(ScriptDirectory, "plcopen", "instances_path.xslt"), + parser), + extensions = { + ("instances_ns", "AddInstance"): factory.AddInstance}) + + instances_path_xslt_tree(root, + instance_type=etree.XSLT.strparam(name)) + return instances - + def SearchPouInstances(self, tagname, debug = False): project = self.GetProject(debug) if project is not None: words = tagname.split("::") if words[0] == "P": - instances = [] - for config in project.getconfigurations(): - config_name = config.getname() - instances.extend( - self.RecursiveSearchPouInstances( - project, words[1], config_name, - config.getglobalVars(), debug)) - for resource in config.getresource(): - res_path = "%s.%s" % (config_name, resource.getname()) - instances.extend( - self.RecursiveSearchPouInstances( - project, words[1], res_path, - resource.getglobalVars(), debug)) - pou_instances = resource.getpouInstance()[:] - for task in resource.gettask(): - pou_instances.extend(task.getpouInstance()) - for pou_instance in pou_instances: - pou_path = "%s.%s" % (res_path, pou_instance.getname()) - pou_type = pou_instance.gettypeName() - if pou_type == words[1]: - instances.append(pou_path) - pou = project.getpou(pou_type) - if pou is not None and project.ElementIsUsedBy(words[1], pou_type): - instances.extend( - self.RecursiveSearchPouInstances( - project, words[1], pou_path, - [varlist for type, varlist in pou.getvars()], - debug)) - return instances + return self.GetInstanceList(project, words[1]) elif words[0] == 'C': return [words[1]] elif words[0] == 'R': @@ -613,114 +781,40 @@ self.ComputePouName(words[1]), debug)] return [] - def RecursiveGetPouInstanceTagName(self, project, pou_type, parts, debug = False): - pou = project.getpou(pou_type) - if pou is not None: - if len(parts) == 0: - return self.ComputePouName(pou_type) - - for varlist_type, varlist in pou.getvars(): - for variable in varlist.getvariable(): - if variable.getname() == parts[0]: - vartype_content = variable.gettype().getcontent() - if vartype_content["name"] == "derived": - return self.RecursiveGetPouInstanceTagName( - project, - vartype_content["value"].getname(), - parts[1:], debug) - - if pou.getbodyType() == "SFC" and len(parts) == 1: - for action in pou.getactionList(): - if action.getname() == parts[0]: - return self.ComputePouActionName(pou_type, parts[0]) - for transition in pou.gettransitionList(): - if transition.getname() == parts[0]: - return self.ComputePouTransitionName(pou_type, parts[0]) - else: - block_infos = self.GetBlockType(pou_type, debug=debug) - if (block_infos is not None and - block_infos["type"] in ["program", "functionBlock"]): - - if len(parts) == 0: - return self.ComputePouName(pou_type) - - for varname, vartype, varmodifier in block_infos["inputs"] + block_infos["outputs"]: - if varname == parts[0]: - return self.RecursiveGetPouInstanceTagName(project, vartype, parts[1:], debug) - return None - - def GetGlobalInstanceTagName(self, project, element, parts, debug = False): - for varlist in element.getglobalVars(): - for variable in varlist.getvariable(): - if variable.getname() == parts[0]: - vartype_content = variable.gettype().getcontent() - if vartype_content["name"] == "derived": - if len(parts) == 1: - return self.ComputePouName( - vartype_content["value"].getname()) - else: - return self.RecursiveGetPouInstanceTagName( - project, - vartype_content["value"].getname(), - parts[1:], debug) - return None - def GetPouInstanceTagName(self, instance_path, debug = False): project = self.GetProject(debug) - parts = instance_path.split(".") - if len(parts) == 1: - return self.ComputeConfigurationName(parts[0]) - elif len(parts) == 2: - for config in project.getconfigurations(): - if config.getname() == parts[0]: - result = self.GetGlobalInstanceTagName(project, - config, - parts[1:], - debug) - if result is not None: - return result - return self.ComputeConfigurationResourceName(parts[0], parts[1]) - else: - for config in project.getconfigurations(): - if config.getname() == parts[0]: - for resource in config.getresource(): - if resource.getname() == parts[1]: - pou_instances = resource.getpouInstance()[:] - for task in resource.gettask(): - pou_instances.extend(task.getpouInstance()) - for pou_instance in pou_instances: - if pou_instance.getname() == parts[2]: - if len(parts) == 3: - return self.ComputePouName( - pou_instance.gettypeName()) - else: - return self.RecursiveGetPouInstanceTagName( - project, - pou_instance.gettypeName(), - parts[3:], debug) - return self.GetGlobalInstanceTagName(project, - resource, - parts[2:], - debug) - return self.GetGlobalInstanceTagName(project, - config, - parts[1:], - debug) - return None + factory = InstanceTagName(self) + + parser = etree.XMLParser() + parser.resolvers.add(LibraryResolver(self, debug)) + + instance_tagname_xslt_tree = etree.XSLT( + etree.parse( + os.path.join(ScriptDirectory, "plcopen", "instance_tagname.xslt"), + parser), + extensions = {("instance_tagname_ns", name): getattr(factory, name) + for name in ["ConfigTagName", "ResourceTagName", + "PouTagName", "ActionTagName", + "TransitionTagName"]}) + + instance_tagname_xslt_tree(project, + instance_path=etree.XSLT.strparam(instance_path)) + + return factory.GetTagName() def GetInstanceInfos(self, instance_path, debug = False): tagname = self.GetPouInstanceTagName(instance_path) if tagname is not None: infos = self.GetPouVariables(tagname, debug) - infos["type"] = tagname + infos.type = tagname return infos else: pou_path, var_name = instance_path.rsplit(".", 1) tagname = self.GetPouInstanceTagName(pou_path) if tagname is not None: pou_infos = self.GetPouVariables(tagname, debug) - for var_infos in pou_infos["variables"]: - if var_infos["name"] == var_name: + for var_infos in pou_infos.variables: + if var_infos.name == var_name: return var_infos return None @@ -728,21 +822,21 @@ def DataTypeIsUsed(self, name, debug = False): project = self.GetProject(debug) if project is not None: - return project.ElementIsUsed(name) or project.DataTypeIsDerived(name) + return len(self.GetInstanceList(project, name, debug)) > 0 return False # Return if pou given by name is used by another pou def PouIsUsed(self, name, debug = False): project = self.GetProject(debug) if project is not None: - return project.ElementIsUsed(name) + return len(self.GetInstanceList(project, name, debug)) > 0 return False # Return if pou given by name is directly or undirectly used by the reference pou def PouIsUsedBy(self, name, reference, debug = False): - project = self.GetProject(debug) - if project is not None: - return project.ElementIsUsedBy(name, reference) + pou_infos = self.GetPou(reference, debug) + if pou_infos is not None: + return len(self.GetInstanceList(pou_infos, name, debug)) > 0 return False def GenerateProgram(self, filepath=None): @@ -830,14 +924,13 @@ pou = self.Project.getpou(name) if pou is not None: pou.setpouType(pou_type) - self.Project.RefreshCustomBlockTypes() self.BufferProject() def GetPouXml(self, pou_name): if self.Project is not None: pou = self.Project.getpou(pou_name) if pou is not None: - return pou.generateXMLText('pou', 0) + return pou.tostring() return None def PastePou(self, pou_type, pou_xml): @@ -845,47 +938,42 @@ Adds the POU defined by 'pou_xml' to the current project with type 'pou_type' ''' try: - tree = minidom.parseString(pou_xml.encode("utf-8")) - root = tree.childNodes[0] + new_pou, error = LoadPou(pou_xml) except: + error = "" + if error is not None: return _("Couldn't paste non-POU object.") - - if root.nodeName == "pou": - new_pou = plcopen.pous_pou() - new_pou.loadXMLTree(root) - - name = new_pou.getname() + + name = new_pou.getname() + + idx = 0 + new_name = name + while self.Project.getpou(new_name): + # a POU with that name already exists. + # make a new name and test if a POU with that name exists. + # append an incrementing numeric suffix to the POU name. + idx += 1 + new_name = "%s%d" % (name, idx) - idx = 0 - new_name = name - while self.Project.getpou(new_name): - # a POU with that name already exists. - # make a new name and test if a POU with that name exists. - # append an incrementing numeric suffix to the POU name. - idx += 1 - new_name = "%s%d" % (name, idx) - - # we've found a name that does not already exist, use it - new_pou.setname(new_name) + # we've found a name that does not already exist, use it + new_pou.setname(new_name) + + if pou_type is not None: + orig_type = new_pou.getpouType() + + # prevent violations of POU content restrictions: + # function blocks cannot be pasted as functions, + # programs cannot be pasted as functions or function blocks + if orig_type == 'functionBlock' and pou_type == 'function' or \ + orig_type == 'program' and pou_type in ['function', 'functionBlock']: + return _('''%s "%s" can't be pasted as a %s.''') % (orig_type, name, pou_type) - if pou_type is not None: - orig_type = new_pou.getpouType() - - # prevent violations of POU content restrictions: - # function blocks cannot be pasted as functions, - # programs cannot be pasted as functions or function blocks - if orig_type == 'functionBlock' and pou_type == 'function' or \ - orig_type == 'program' and pou_type in ['function', 'functionBlock']: - return _('''%s "%s" can't be pasted as a %s.''') % (orig_type, name, pou_type) - - new_pou.setpouType(pou_type) - - self.Project.insertpou(-1, new_pou) - self.BufferProject() - - return self.ComputePouName(new_name), - else: - return _("Couldn't paste non-POU object.") + new_pou.setpouType(pou_type) + + self.Project.insertpou(-1, new_pou) + self.BufferProject() + + return self.ComputePouName(new_name), # Remove a Pou from project def ProjectRemovePou(self, pou_name): @@ -980,8 +1068,6 @@ if datatype is not None: datatype.setname(new_name) self.Project.updateElementName(old_name, new_name) - self.Project.RefreshElementUsingTree() - self.Project.RefreshDataTypeHierarchy() self.BufferProject() # Change the name of a pou @@ -992,8 +1078,6 @@ if pou is not None: pou.setname(new_name) self.Project.updateElementName(old_name, new_name) - self.Project.RefreshElementUsingTree() - self.Project.RefreshCustomBlockTypes() self.BufferProject() # Change the name of a pou transition @@ -1030,7 +1114,6 @@ for var in varlist.getvariable(): if var.getname() == old_name: var.setname(new_name) - self.Project.RefreshCustomBlockTypes() self.BufferProject() # Change the name of a configuration @@ -1069,7 +1152,6 @@ pou = project.getpou(name) if pou is not None: pou.setdescription(description) - project.RefreshCustomBlockTypes() self.BufferProject() # Return the type of the pou given by its name @@ -1157,152 +1239,114 @@ current_varlist = None current_type = None for var in vars: - next_type = (var["Class"], - var["Option"], - var["Location"] in ["", None] or + next_type = (var.Class, + var.Option, + var.Location in ["", None] or # When declaring globals, located # and not located variables are # in the same declaration block - var["Class"] == "Global") + var.Class == "Global") if current_type != next_type: current_type = next_type - infos = VAR_CLASS_INFOS.get(var["Class"], None) + infos = VAR_CLASS_INFOS.get(var.Class, None) if infos is not None: - current_varlist = infos[0]() + current_varlist = PLCOpenParser.CreateElement(infos[0], "interface") else: - current_varlist = plcopen.varList() - varlist_list.append((var["Class"], current_varlist)) - if var["Option"] == "Constant": + current_varlist = PLCOpenParser.CreateElement("varList") + varlist_list.append((var.Class, current_varlist)) + if var.Option == "Constant": current_varlist.setconstant(True) - elif var["Option"] == "Retain": + elif var.Option == "Retain": current_varlist.setretain(True) - elif var["Option"] == "Non-Retain": + elif var.Option == "Non-Retain": current_varlist.setnonretain(True) # Create variable and change its properties - tempvar = plcopen.varListPlain_variable() - tempvar.setname(var["Name"]) + tempvar = PLCOpenParser.CreateElement("variable", "varListPlain") + tempvar.setname(var.Name) - var_type = plcopen.dataType() - if isinstance(var["Type"], TupleType): - if var["Type"][0] == "array": - array_type, base_type_name, dimensions = var["Type"] - array = plcopen.derivedTypes_array() + var_type = PLCOpenParser.CreateElement("type", "variable") + if isinstance(var.Type, TupleType): + if var.Type[0] == "array": + array_type, base_type_name, dimensions = var.Type + array = PLCOpenParser.CreateElement("array", "dataType") + baseType = PLCOpenParser.CreateElement("baseType", "array") + array.setbaseType(baseType) for i, dimension in enumerate(dimensions): - dimension_range = plcopen.rangeSigned() - dimension_range.setlower(dimension[0]) - dimension_range.setupper(dimension[1]) + dimension_range = PLCOpenParser.CreateElement("dimension", "array") if i == 0: array.setdimension([dimension_range]) else: array.appenddimension(dimension_range) + dimension_range.setlower(dimension[0]) + dimension_range.setupper(dimension[1]) if base_type_name in self.GetBaseTypes(): - if base_type_name == "STRING": - array.baseType.setcontent({"name" : "string", "value" : plcopen.elementaryTypes_string()}) - elif base_type_name == "WSTRING": - array.baseType.setcontent({"name" : "wstring", "value" : plcopen.wstring()}) - else: - array.baseType.setcontent({"name" : base_type_name, "value" : None}) + baseType.setcontent(PLCOpenParser.CreateElement( + base_type_name.lower() + if base_type_name in ["STRING", "WSTRING"] + else base_type_name, "dataType")) else: - derived_datatype = plcopen.derivedTypes_derived() + derived_datatype = PLCOpenParser.CreateElement("derived", "dataType") derived_datatype.setname(base_type_name) - array.baseType.setcontent({"name" : "derived", "value" : derived_datatype}) - var_type.setcontent({"name" : "array", "value" : array}) - elif var["Type"] in self.GetBaseTypes(): - if var["Type"] == "STRING": - var_type.setcontent({"name" : "string", "value" : plcopen.elementaryTypes_string()}) - elif var["Type"] == "WSTRING": - var_type.setcontent({"name" : "wstring", "value" : plcopen.elementaryTypes_wstring()}) - else: - var_type.setcontent({"name" : var["Type"], "value" : None}) + baseType.setcontent(derived_datatype) + var_type.setcontent(array) + elif var.Type in self.GetBaseTypes(): + var_type.setcontent(PLCOpenParser.CreateElement( + var.Type.lower() + if var.Type in ["STRING", "WSTRING"] + else var.Type, "dataType")) else: - derived_type = plcopen.derivedTypes_derived() - derived_type.setname(var["Type"]) - var_type.setcontent({"name" : "derived", "value" : derived_type}) + derived_type = PLCOpenParser.CreateElement("derived", "dataType") + derived_type.setname(var.Type) + var_type.setcontent(derived_type) tempvar.settype(var_type) - if var["Initial Value"] != "": - value = plcopen.value() - value.setvalue(var["Initial Value"]) + if var.InitialValue != "": + value = PLCOpenParser.CreateElement("initialValue", "variable") + value.setvalue(var.InitialValue) tempvar.setinitialValue(value) - if var["Location"] != "": - tempvar.setaddress(var["Location"]) + if var.Location != "": + tempvar.setaddress(var.Location) else: tempvar.setaddress(None) - if var['Documentation'] != "": - ft = plcopen.formattedText() - ft.settext(var['Documentation']) + if var.Documentation != "": + ft = PLCOpenParser.CreateElement("documentation", "variable") + ft.setanyText(var.Documentation) tempvar.setdocumentation(ft) # Add variable to varList current_varlist.appendvariable(tempvar) return varlist_list - def GetVariableDictionary(self, varlist, var): - ''' - convert a PLC variable to the dictionary representation - returned by Get*Vars) - ''' - - tempvar = {"Name": var.getname()} - - vartype_content = var.gettype().getcontent() - if vartype_content["name"] == "derived": - tempvar["Type"] = vartype_content["value"].getname() - elif vartype_content["name"] == "array": - dimensions = [] - for dimension in vartype_content["value"].getdimension(): - dimensions.append((dimension.getlower(), dimension.getupper())) - base_type = vartype_content["value"].baseType.getcontent() - if base_type["value"] is None or base_type["name"] in ["string", "wstring"]: - base_type_name = base_type["name"].upper() - else: - base_type_name = base_type["value"].getname() - tempvar["Type"] = ("array", base_type_name, dimensions) - elif vartype_content["name"] in ["string", "wstring"]: - tempvar["Type"] = vartype_content["name"].upper() - else: - tempvar["Type"] = vartype_content["name"] - - tempvar["Edit"] = True - - initial = var.getinitialValue() - if initial: - tempvar["Initial Value"] = initial.getvalue() - else: - tempvar["Initial Value"] = "" - - address = var.getaddress() - if address: - tempvar["Location"] = address - else: - tempvar["Location"] = "" - - if varlist.getconstant(): - tempvar["Option"] = "Constant" - elif varlist.getretain(): - tempvar["Option"] = "Retain" - elif varlist.getnonretain(): - tempvar["Option"] = "Non-Retain" - else: - tempvar["Option"] = "" - - doc = var.getdocumentation() - if doc: - tempvar["Documentation"] = doc.gettext() - else: - tempvar["Documentation"] = "" - - return tempvar - + def GetVariableDictionary(self, object_with_vars, tree=False, debug=False): + variables = [] + factory = VariablesInfosFactory(variables) + + parser = etree.XMLParser() + parser.resolvers.add(LibraryResolver(self, debug)) + + variables_infos_xslt_tree = etree.XSLT( + etree.parse( + os.path.join(ScriptDirectory, "plcopen", "variables_infos.xslt"), + parser), + extensions = {("var_infos_ns", name): getattr(factory, name) + for name in ["SetType", "AddDimension", "AddTree", + "AddVarToTree", "AddVariable"]}) + variables_infos_xslt_tree(object_with_vars, + tree=etree.XSLT.strparam(str(tree))) + + return variables + # Add a global var to configuration to configuration - def AddConfigurationGlobalVar(self, config_name, type, var_name, + def AddConfigurationGlobalVar(self, config_name, var_type, var_name, location="", description=""): if self.Project is not None: # Found the configuration corresponding to name configuration = self.Project.getconfiguration(config_name) if configuration is not None: # Set configuration global vars - configuration.addglobalVar(type, var_name, location, description) + configuration.addglobalVar( + self.GetVarTypeObject(var_type), + var_name, location, description) # Replace the configuration globalvars by those given def SetConfigurationGlobalVars(self, name, vars): @@ -1311,25 +1355,21 @@ configuration = self.Project.getconfiguration(name) if configuration is not None: # Set configuration global vars - configuration.setglobalVars([]) - for vartype, varlist in self.ExtractVarLists(vars): - configuration.globalVars.append(varlist) + configuration.setglobalVars([ + varlist for vartype, varlist + in self.ExtractVarLists(vars)]) # Return the configuration globalvars def GetConfigurationGlobalVars(self, name, debug = False): - vars = [] project = self.GetProject(debug) if project is not None: # Found the configuration corresponding to name configuration = project.getconfiguration(name) if configuration is not None: - # Extract variables from every varLists - for varlist in configuration.getglobalVars(): - for var in varlist.getvariable(): - tempvar = self.GetVariableDictionary(varlist, var) - tempvar["Class"] = "Global" - vars.append(tempvar) - return vars + # Extract variables defined in configuration + return self.GetVariableDictionary(configuration, debug) + + return [] # Return configuration variable names def GetConfigurationVariableNames(self, config_name = None, debug = False): @@ -1352,25 +1392,21 @@ resource = self.Project.getconfigurationResource(config_name, name) # Set resource global vars if resource is not None: - resource.setglobalVars([]) - for vartype, varlist in self.ExtractVarLists(vars): - resource.globalVars.append(varlist) + resource.setglobalVars([ + varlist for vartype, varlist + in self.ExtractVarLists(vars)]) # Return the resource globalvars def GetConfigurationResourceGlobalVars(self, config_name, name, debug = False): - vars = [] project = self.GetProject(debug) if project is not None: # Found the resource corresponding to name resource = project.getconfigurationResource(config_name, name) - if resource: - # Extract variables from every varLists - for varlist in resource.getglobalVars(): - for var in varlist.getvariable(): - tempvar = self.GetVariableDictionary(varlist, var) - tempvar["Class"] = "Global" - vars.append(tempvar) - return vars + if resource is not None: + # Extract variables defined in configuration + return self.GetVariableDictionary(resource, debug) + + return [] # Return resource variable names def GetConfigurationResourceVariableNames(self, @@ -1388,73 +1424,15 @@ for varlist in resource.globalVars], [])]) return variables - - # Recursively generate element name tree for a structured variable - def GenerateVarTree(self, typename, debug = False): - project = self.GetProject(debug) - if project is not None: - blocktype = self.GetBlockType(typename, debug = debug) - if blocktype is not None: - tree = [] - en = False - eno = False - for var_name, var_type, var_modifier in blocktype["inputs"] + blocktype["outputs"]: - en |= var_name.upper() == "EN" - eno |= var_name.upper() == "ENO" - tree.append((var_name, var_type, self.GenerateVarTree(var_type, debug))) - if not eno: - tree.insert(0, ("ENO", "BOOL", ([], []))) - if not en: - tree.insert(0, ("EN", "BOOL", ([], []))) - return tree, [] - datatype = project.getdataType(typename) - if datatype is None: - datatype = self.GetConfNodeDataType(typename) - if datatype is not None: - tree = [] - basetype_content = datatype.baseType.getcontent() - if basetype_content["name"] == "derived": - return self.GenerateVarTree(basetype_content["value"].getname()) - elif basetype_content["name"] == "array": - dimensions = [] - base_type = basetype_content["value"].baseType.getcontent() - if base_type["name"] == "derived": - tree = self.GenerateVarTree(base_type["value"].getname()) - if len(tree[1]) == 0: - tree = tree[0] - for dimension in basetype_content["value"].getdimension(): - dimensions.append((dimension.getlower(), dimension.getupper())) - return tree, dimensions - elif basetype_content["name"] == "struct": - for element in basetype_content["value"].getvariable(): - element_type = element.type.getcontent() - if element_type["name"] == "derived": - tree.append((element.getname(), element_type["value"].getname(), self.GenerateVarTree(element_type["value"].getname()))) - else: - tree.append((element.getname(), element_type["name"], ([], []))) - return tree, [] - return [], [] # Return the interface for the given pou - def GetPouInterfaceVars(self, pou, debug = False): - vars = [] + def GetPouInterfaceVars(self, pou, tree=False, debug = False): + interface = pou.interface # Verify that the pou has an interface - if pou.interface is not None: - # Extract variables from every varLists - for type, varlist in pou.getvars(): - for var in varlist.getvariable(): - tempvar = self.GetVariableDictionary(varlist, var) - - tempvar["Class"] = type - tempvar["Tree"] = ([], []) - - vartype_content = var.gettype().getcontent() - if vartype_content["name"] == "derived": - tempvar["Edit"] = not pou.hasblock(tempvar["Name"]) - tempvar["Tree"] = self.GenerateVarTree(tempvar["Type"], debug) - - vars.append(tempvar) - return vars + if interface is not None: + # Extract variables defined in interface + return self.GetVariableDictionary(interface, tree, debug) + return [] # Replace the Pou interface by the one given def SetPouInterfaceVars(self, name, vars): @@ -1463,99 +1441,98 @@ pou = self.Project.getpou(name) if pou is not None: if pou.interface is None: - pou.interface = plcopen.pou_interface() + pou.interface = PLCOpenParser.CreateElement("interface", "pou") # Set Pou interface - pou.setvars(self.ExtractVarLists(vars)) - self.Project.RefreshElementUsingTree() - self.Project.RefreshCustomBlockTypes() - + pou.setvars([varlist for varlist_type, varlist in self.ExtractVarLists(vars)]) + # Replace the return type of the pou given by its name (only for functions) - def SetPouInterfaceReturnType(self, name, type): + def SetPouInterfaceReturnType(self, name, return_type): if self.Project is not None: pou = self.Project.getpou(name) if pou is not None: if pou.interface is None: - pou.interface = plcopen.pou_interface() + pou.interface = PLCOpenParser.CreateElement("interface", "pou") # If there isn't any return type yet, add it - return_type = pou.interface.getreturnType() - if not return_type: - return_type = plcopen.dataType() - pou.interface.setreturnType(return_type) + return_type_obj = pou.interface.getreturnType() + if return_type_obj is None: + return_type_obj = PLCOpenParser.CreateElement("returnType", "interface") + pou.interface.setreturnType(return_type_obj) # Change return type - if type in self.GetBaseTypes(): - if type == "STRING": - return_type.setcontent({"name" : "string", "value" : plcopen.elementaryTypes_string()}) - elif type == "WSTRING": - return_type.setcontent({"name" : "wstring", "value" : plcopen.elementaryTypes_wstring()}) - else: - return_type.setcontent({"name" : type, "value" : None}) + if return_type in self.GetBaseTypes(): + return_type_obj.setcontent(PLCOpenParser.CreateElement( + return_type.lower() + if return_type in ["STRING", "WSTRING"] + else return_type, "dataType")) else: - derived_type = plcopen.derivedTypes_derived() - derived_type.setname(type) - return_type.setcontent({"name" : "derived", "value" : derived_type}) - self.Project.RefreshElementUsingTree() - self.Project.RefreshCustomBlockTypes() - + derived_type = PLCOpenParser.CreateElement("derived", "dataType") + derived_type.setname(return_type) + return_type.setcontent(derived_type) + def UpdateProjectUsedPous(self, old_name, new_name): - if self.Project: + if self.Project is not None: self.Project.updateElementName(old_name, new_name) def UpdateEditedElementUsedVariable(self, tagname, old_name, new_name): pou = self.GetEditedElement(tagname) - if pou: + if pou is not None: pou.updateElementName(old_name, new_name) - # Return the return type of the pou given by its name - def GetPouInterfaceReturnTypeByName(self, name): - project = self.GetProject(debug) - if project is not None: - # Found the pou correponding to name and return the return type - pou = project.getpou(name) - if pou is not None: - return self.GetPouInterfaceReturnType(pou) - return False - # Return the return type of the given pou - def GetPouInterfaceReturnType(self, pou): + def GetPouInterfaceReturnType(self, pou, tree=False, debug=False): # Verify that the pou has an interface if pou.interface is not None: # Return the return type if there is one return_type = pou.interface.getreturnType() - if return_type: - returntype_content = return_type.getcontent() - if returntype_content["name"] == "derived": - return returntype_content["value"].getname() - elif returntype_content["name"] in ["string", "wstring"]: - return returntype_content["name"].upper() - else: - return returntype_content["name"] + if return_type is not None: + factory = VariablesInfosFactory([]) + + parser = etree.XMLParser() + if tree: + parser.resolvers.add(LibraryResolver(self)) + + return_type_infos_xslt_tree = etree.XSLT( + etree.parse( + os.path.join(ScriptDirectory, "plcopen", "variables_infos.xslt"), + parser), + extensions = {("var_infos_ns", name): getattr(factory, name) + for name in ["SetType", "AddDimension", + "AddTree", "AddVarToTree"]}) + return_type_infos_xslt_tree(return_type, + tree=etree.XSLT.strparam(str(tree))) + if tree: + return [factory.GetType(), factory.GetTree()] + return factory.GetType() + + if tree: + return [None, ([], [])] return None # Function that add a new confnode to the confnode list def AddConfNodeTypesList(self, typeslist): self.ConfNodeTypes.extend(typeslist) + addedcat = [{"name": _("%s POUs") % confnodetypes["name"], + "list": [pou.getblockInfos() + for pou in confnodetypes["types"].getpous()]} + for confnodetypes in typeslist] + self.TotalTypes.extend(addedcat) + for cat in addedcat: + for desc in cat["list"]: + BlkLst = self.TotalTypesDict.setdefault(desc["name"],[]) + BlkLst.append((section["name"], desc)) # Function that clear the confnode list def ClearConfNodeTypes(self): - for i in xrange(len(self.ConfNodeTypes)): - self.ConfNodeTypes.pop(0) - - def GetConfNodeBlockTypes(self): - return [{"name": _("%s POUs") % confnodetypes["name"], - "list": confnodetypes["types"].GetCustomBlockTypes()} + self.ConfNodeTypes = [] + self.TotalTypesDict = StdBlckDct.copy() + self.TotalTypes = StdBlckLst[:] + + def GetConfNodeDataTypes(self, exclude = None, only_locatables = False): + return [{"name": _("%s Data Types") % confnodetypes["name"], + "list": [ + datatype.getname() + for datatype in confnodetypes["types"].getdataTypes() + if not only_locatables or self.IsLocatableDataType(datatype, debug)]} for confnodetypes in self.ConfNodeTypes] - - def GetConfNodeDataTypes(self, exclude = "", only_locatables = False): - return [{"name": _("%s Data Types") % confnodetypes["name"], - "list": [datatype["name"] for datatype in confnodetypes["types"].GetCustomDataTypes(exclude, only_locatables)]} - for confnodetypes in self.ConfNodeTypes] - - def GetConfNodeDataType(self, type): - for confnodetype in self.ConfNodeTypes: - datatype = confnodetype["types"].getdataType(type) - if datatype is not None: - return datatype - return None def GetVariableLocationTree(self): return [] @@ -1566,25 +1543,23 @@ def GetConfigurationExtraVariables(self): global_vars = [] for var_name, var_type, var_initial in self.GetConfNodeGlobalInstances(): - tempvar = plcopen.varListPlain_variable() + tempvar = PLCOpenParser.CreateElement("variable", "globalVars") tempvar.setname(var_name) - tempvartype = plcopen.dataType() + tempvartype = PLCOpenParser.CreateElement("type", "variable") if var_type in self.GetBaseTypes(): - if var_type == "STRING": - tempvartype.setcontent({"name" : "string", "value" : plcopen.elementaryTypes_string()}) - elif var_type == "WSTRING": - tempvartype.setcontent({"name" : "wstring", "value" : plcopen.elementaryTypes_wstring()}) - else: - tempvartype.setcontent({"name" : var_type, "value" : None}) + tempvartype.setcontent(PLCOpenParser.CreateElement( + var_type.lower() + if var_type in ["STRING", "WSTRING"] + else var_type, "dataType")) else: - tempderivedtype = plcopen.derivedTypes_derived() + tempderivedtype = PLCOpenParser.CreateElement("derived", "dataType") tempderivedtype.setname(var_type) - tempvartype.setcontent({"name" : "derived", "value" : tempderivedtype}) + tempvartype.setcontent(tempderivedtype) tempvar.settype(tempvartype) if var_initial != "": - value = plcopen.value() + value = PLCOpenParser.CreateElement("initialValue", "variable") value.setvalue(var_initial) tempvar.setinitialValue(value) @@ -1592,82 +1567,96 @@ return global_vars # Function that returns the block definition associated to the block type given - def GetBlockType(self, type, inputs = None, debug = False): + def GetBlockType(self, typename, inputs = None, debug = False): result_blocktype = None - for category in BlockTypes + self.GetConfNodeBlockTypes(): - for blocktype in category["list"]: - if blocktype["name"] == type: - if inputs is not None and inputs != "undefined": - block_inputs = tuple([var_type for name, var_type, modifier in blocktype["inputs"]]) - if reduce(lambda x, y: x and y, map(lambda x: x[0] == "ANY" or self.IsOfType(*x), zip(inputs, block_inputs)), True): - return blocktype + for sectioname, blocktype in self.TotalTypesDict.get(typename,[]): + if inputs is not None and inputs != "undefined": + block_inputs = tuple([var_type for name, var_type, modifier in blocktype["inputs"]]) + if reduce(lambda x, y: x and y, map(lambda x: x[0] == "ANY" or self.IsOfType(*x), zip(inputs, block_inputs)), True): + return blocktype + else: + if result_blocktype is not None: + if inputs == "undefined": + return None else: - if result_blocktype is not None: - if inputs == "undefined": - return None - else: - result_blocktype["inputs"] = [(i[0], "ANY", i[2]) for i in result_blocktype["inputs"]] - result_blocktype["outputs"] = [(o[0], "ANY", o[2]) for o in result_blocktype["outputs"]] - return result_blocktype - result_blocktype = blocktype.copy() + result_blocktype["inputs"] = [(i[0], "ANY", i[2]) for i in result_blocktype["inputs"]] + result_blocktype["outputs"] = [(o[0], "ANY", o[2]) for o in result_blocktype["outputs"]] + return result_blocktype + result_blocktype = blocktype.copy() if result_blocktype is not None: return result_blocktype project = self.GetProject(debug) if project is not None: - return project.GetCustomBlockType(type, inputs) + blocktype = project.getpou(typename) + if blocktype is not None: + blocktype_infos = blocktype.getblockInfos() + if inputs in [None, "undefined"]: + return blocktype_infos + + if inputs == tuple([var_type + for name, var_type, modifier in blocktype_infos["inputs"]]): + return blocktype_infos + return None # Return Block types checking for recursion def GetBlockTypes(self, tagname = "", debug = False): - type = None + typename = None words = tagname.split("::") - if self.Project: - name = "" + name = None + project = self.GetProject(debug) + if project is not None: + pou_type = None if words[0] in ["P","T","A"]: name = words[1] - type = self.GetPouType(name, debug) - if type == "function": - blocktypes = [] - for category in BlockTypes + self.GetConfNodeBlockTypes(): - cat = {"name" : category["name"], "list" : []} - for block in category["list"]: - if block["type"] == "function": - cat["list"].append(block) - if len(cat["list"]) > 0: - blocktypes.append(cat) - else: - blocktypes = [category for category in BlockTypes + self.GetConfNodeBlockTypes()] - project = self.GetProject(debug) - if project is not None: - blocktypes.append({"name" : USER_DEFINED_POUS, "list": project.GetCustomBlockTypes(name, type == "function" or words[0] == "T")}) - return blocktypes + pou_type = self.GetPouType(name, debug) + filter = (["function"] + if pou_type == "function" or words[0] == "T" + else ["functionBlock", "function"]) + blocktypes = [ + {"name": category["name"], + "list": [block for block in category["list"] + if block["type"] in filter]} + for category in self.TotalTypes] + blocktypes.append({"name" : USER_DEFINED_POUS, + "list": [pou.getblockInfos() + for pou in project.getpous(name, filter) + if (name is None or + len(self.GetInstanceList(pou, name, debug)) == 0)]}) + return blocktypes + return self.TotalTypes # Return Function Block types checking for recursion def GetFunctionBlockTypes(self, tagname = "", debug = False): + project = self.GetProject(debug) + words = tagname.split("::") + name = None + if project is not None and words[0] in ["P","T","A"]: + name = words[1] blocktypes = [] - for category in BlockTypes + self.GetConfNodeBlockTypes(): - for block in category["list"]: + for blocks in self.TotalTypesDict.itervalues(): + for sectioname,block in blocks: if block["type"] == "functionBlock": blocktypes.append(block["name"]) - project = self.GetProject(debug) - if project is not None: - name = "" - words = tagname.split("::") - if words[0] in ["P","T","A"]: - name = words[1] - blocktypes.extend(project.GetCustomFunctionBlockTypes(name)) + if project is not None: + blocktypes.extend([pou.getname() + for pou in project.getpous(name, ["functionBlock"]) + if (name is None or + len(self.GetInstanceList(pou, name, debug)) == 0)]) return blocktypes # Return Block types checking for recursion def GetBlockResource(self, debug = False): blocktypes = [] - for category in BlockTypes[:-1]: + for category in StdBlckLst[:-1]: for blocktype in category["list"]: if blocktype["type"] == "program": blocktypes.append(blocktype["name"]) project = self.GetProject(debug) if project is not None: - blocktypes.extend(project.GetCustomBlockResource()) + blocktypes.extend( + [pou.getname() + for pou in project.getpous(filter=["program"])]) return blocktypes # Return Data Types checking for recursion @@ -1677,30 +1666,80 @@ else: datatypes = [] project = self.GetProject(debug) - if project is not None: - name = "" + name = None + if project is not None: words = tagname.split("::") if words[0] in ["D"]: name = words[1] - datatypes.extend([datatype["name"] for datatype in project.GetCustomDataTypes(name, only_locatables)]) + datatypes.extend([ + datatype.getname() + for datatype in project.getdataTypes(name) + if (not only_locatables or self.IsLocatableDataType(datatype, debug)) + and (name is None or + len(self.GetInstanceList(datatype, name, debug)) == 0)]) if confnodetypes: for category in self.GetConfNodeDataTypes(name, only_locatables): datatypes.extend(category["list"]) return datatypes - # Return Base Type of given possible derived type - def GetBaseType(self, type, debug = False): - project = self.GetProject(debug) - if project is not None: - result = project.GetBaseType(type) + # Return Data Type Object + def GetPou(self, typename, debug = False): + project = self.GetProject(debug) + if project is not None: + result = project.getpou(typename) + if result is not None: + return result + for standardlibrary in [StdBlockLibrary, AddnlBlockLibrary]: + result = standardlibrary.getpou(typename) if result is not None: return result for confnodetype in self.ConfNodeTypes: - result = confnodetype["types"].GetBaseType(type) + result = confnodetype["types"].getpou(typename) if result is not None: return result return None + + # Return Data Type Object + def GetDataType(self, typename, debug = False): + project = self.GetProject(debug) + if project is not None: + result = project.getdataType(typename) + if result is not None: + return result + for confnodetype in self.ConfNodeTypes: + result = confnodetype["types"].getdataType(typename) + if result is not None: + return result + return None + + # Return Data Type Object Base Type + def GetDataTypeBaseType(self, datatype): + basetype_content = datatype.baseType.getcontent() + basetype_content_type = basetype_content.getLocalTag() + if basetype_content_type in ["array", "subrangeSigned", "subrangeUnsigned"]: + basetype = basetype_content.baseType.getcontent() + basetype_type = basetype.getLocalTag() + return (basetype.getname() if basetype_type == "derived" + else basetype_type.upper()) + return (basetype_content.getname() if basetype_content_type == "derived" + else basetype_content_type.upper()) + return None + + # Return Base Type of given possible derived type + def GetBaseType(self, typename, debug = False): + if TypeHierarchy.has_key(typename): + return typename + + datatype = self.GetDataType(typename, debug) + if datatype is not None: + basetype = self.GetDataTypeBaseType(datatype) + if basetype is not None: + return self.GetBaseType(basetype, debug) + return typename + + return None + def GetBaseTypes(self): ''' return the list of datatypes defined in IEC 61131-3. @@ -1709,93 +1748,131 @@ ''' return [x for x,y in TypeHierarchy_list if not x.startswith("ANY")] - def IsOfType(self, type, reference, debug = False): - if reference is None: + def IsOfType(self, typename, reference, debug = False): + if reference is None or typename == reference: return True - elif type == reference: - return True - elif type in TypeHierarchy: - return self.IsOfType(TypeHierarchy[type], reference) - else: - project = self.GetProject(debug) - if project is not None and project.IsOfType(type, reference): - return True - for confnodetype in self.ConfNodeTypes: - if confnodetype["types"].IsOfType(type, reference): - return True + + basetype = TypeHierarchy.get(typename) + if basetype is not None: + return self.IsOfType(basetype, reference) + + datatype = self.GetDataType(typename, debug) + if datatype is not None: + basetype = self.GetDataTypeBaseType(datatype) + if basetype is not None: + return self.IsOfType(basetype, reference, debug) + return False - def IsEndType(self, type): - if type is not None: - return not type.startswith("ANY") + def IsEndType(self, typename): + if typename is not None: + return not typename.startswith("ANY") return True - def IsLocatableType(self, type, debug = False): - if isinstance(type, TupleType): - return False - if self.GetBlockType(type) is not None: + def IsLocatableDataType(self, datatype, debug = False): + basetype_content = datatype.baseType.getcontent() + basetype_content_type = basetype_content.getLocalTag() + if basetype_content_type in ["enum", "struct"]: return False - project = self.GetProject(debug) - if project is not None: - datatype = project.getdataType(type) - if datatype is None: - datatype = self.GetConfNodeDataType(type) - if datatype is not None: - return project.IsLocatableType(datatype) + elif basetype_content_type == "derived": + return self.IsLocatableType(basetype_content.getname()) + elif basetype_content_type == "array": + array_base_type = basetype_content.baseType.getcontent() + if array_base_type.getLocalTag() == "derived": + return self.IsLocatableType(array_base_type.getname(), debug) return True - - def IsEnumeratedType(self, type, debug = False): - project = self.GetProject(debug) - if project is not None: - datatype = project.getdataType(type) - if datatype is None: - datatype = self.GetConfNodeDataType(type) - if datatype is not None: - basetype_content = datatype.baseType.getcontent() - return basetype_content["name"] == "enum" + + def IsLocatableType(self, typename, debug = False): + if isinstance(typename, TupleType) or self.GetBlockType(typename) is not None: + return False + + datatype = self.GetDataType(typename, debug) + if datatype is not None: + return self.IsLocatableDataType(datatype) + return True + + def IsEnumeratedType(self, typename, debug = False): + if isinstance(typename, TupleType): + typename = typename[1] + datatype = self.GetDataType(typename, debug) + if datatype is not None: + basetype_content = datatype.baseType.getcontent() + basetype_content_type = basetype_content.getLocalTag() + if basetype_content_type == "derived": + return self.IsEnumeratedType(basetype_content_type, debug) + return basetype_content_type == "enum" return False - def IsNumType(self, type, debug = False): - return self.IsOfType(type, "ANY_NUM", debug) or\ - self.IsOfType(type, "ANY_BIT", debug) + def IsSubrangeType(self, typename, exclude=None, debug = False): + if typename == exclude: + return False + if isinstance(typename, TupleType): + typename = typename[1] + datatype = self.GetDataType(typename, debug) + if datatype is not None: + basetype_content = datatype.baseType.getcontent() + basetype_content_type = basetype_content.getLocalTag() + if basetype_content_type == "derived": + return self.IsSubrangeType(basetype_content_type, exclude, debug) + elif basetype_content_type in ["subrangeSigned", "subrangeUnsigned"]: + return not self.IsOfType( + self.GetDataTypeBaseType(datatype), exclude) + return False + + def IsNumType(self, typename, debug = False): + return self.IsOfType(typename, "ANY_NUM", debug) or\ + self.IsOfType(typename, "ANY_BIT", debug) - def GetDataTypeRange(self, type, debug = False): - if type in DataTypeRange: - return DataTypeRange[type] + def GetDataTypeRange(self, typename, debug = False): + range = DataTypeRange.get(typename) + if range is not None: + return range + datatype = self.GetDataType(typename, debug) + if datatype is not None: + basetype_content = datatype.baseType.getcontent() + basetype_content_type = basetype_content.getLocalTag() + if basetype_content_type in ["subrangeSigned", "subrangeUnsigned"]: + return (basetype_content.range.getlower(), + basetype_content.range.getupper()) + elif basetype_content_type == "derived": + return self.GetDataTypeRange(basetype_content.getname(), debug) + return None + + # Return Subrange types + def GetSubrangeBaseTypes(self, exclude, debug = False): + subrange_basetypes = DataTypeRange.keys() + project = self.GetProject(debug) + if project is not None: + subrange_basetypes.extend( + [datatype.getname() for datatype in project.getdataTypes() + if self.IsSubrangeType(datatype.getname(), exclude, debug)]) + for confnodetype in self.ConfNodeTypes: + subrange_basetypes.extend( + [datatype.getname() for datatype in confnodetype["types"].getdataTypes() + if self.IsSubrangeType(datatype.getname(), exclude, debug)]) + return subrange_basetypes + + # Return Enumerated Values + def GetEnumeratedDataValues(self, typename = None, debug = False): + values = [] + if typename is not None: + datatype_obj = self.GetDataType(typename, debug) + if datatype_obj is not None: + basetype_content = datatype_obj.baseType.getcontent() + basetype_content_type = basetype_content.getLocalTag() + if basetype_content_type == "enum": + return [value.getname() + for value in basetype_content.xpath( + "ppx:values/ppx:value", + namespaces=PLCOpenParser.NSMAP)] + elif basetype_content_type == "derived": + return self.GetEnumeratedDataValues(basetype_content.getname(), debug) else: project = self.GetProject(debug) if project is not None: - result = project.GetDataTypeRange(type) - if result is not None: - return result + values.extend(project.GetEnumeratedDataTypeValues()) for confnodetype in self.ConfNodeTypes: - result = confnodetype["types"].GetDataTypeRange(type) - if result is not None: - return result - return None - - # Return Subrange types - def GetSubrangeBaseTypes(self, exclude, debug = False): - subrange_basetypes = [] - project = self.GetProject(debug) - if project is not None: - subrange_basetypes.extend(project.GetSubrangeBaseTypes(exclude)) - for confnodetype in self.ConfNodeTypes: - subrange_basetypes.extend(confnodetype["types"].GetSubrangeBaseTypes(exclude)) - return DataTypeRange.keys() + subrange_basetypes - - # Return Enumerated Values - def GetEnumeratedDataValues(self, type = None, debug = False): - values = [] - project = self.GetProject(debug) - if project is not None: - values.extend(project.GetEnumeratedDataTypeValues(type)) - if type is None and len(values) > 0: - return values - for confnodetype in self.ConfNodeTypes: - values.extend(confnodetype["types"].GetEnumeratedDataTypeValues(type)) - if type is None and len(values) > 0: - return values + values.extend(confnodetype["types"].GetEnumeratedDataTypeValues()) return values #------------------------------------------------------------------------------- @@ -1847,62 +1924,64 @@ if datatype is None: return None basetype_content = datatype.baseType.getcontent() - if basetype_content["value"] is None or basetype_content["name"] in ["string", "wstring"]: - infos["type"] = "Directly" - infos["base_type"] = basetype_content["name"].upper() - elif basetype_content["name"] == "derived": - infos["type"] = "Directly" - infos["base_type"] = basetype_content["value"].getname() - elif basetype_content["name"] in ["subrangeSigned", "subrangeUnsigned"]: + basetype_content_type = basetype_content.getLocalTag() + if basetype_content_type in ["subrangeSigned", "subrangeUnsigned"]: infos["type"] = "Subrange" - infos["min"] = basetype_content["value"].range.getlower() - infos["max"] = basetype_content["value"].range.getupper() - base_type = basetype_content["value"].baseType.getcontent() - if base_type["value"] is None: - infos["base_type"] = base_type["name"] - else: - infos["base_type"] = base_type["value"].getname() - elif basetype_content["name"] == "enum": + infos["min"] = basetype_content.range.getlower() + infos["max"] = basetype_content.range.getupper() + base_type = basetype_content.baseType.getcontent() + base_type_type = base_type.getLocalTag() + infos["base_type"] = (base_type.getname() + if base_type_type == "derived" + else base_type_type) + elif basetype_content_type == "enum": infos["type"] = "Enumerated" infos["values"] = [] - for value in basetype_content["value"].values.getvalue(): + for value in basetype_content.xpath("ppx:values/ppx:value", namespaces=PLCOpenParser.NSMAP): infos["values"].append(value.getname()) - elif basetype_content["name"] == "array": + elif basetype_content_type == "array": infos["type"] = "Array" infos["dimensions"] = [] - for dimension in basetype_content["value"].getdimension(): + for dimension in basetype_content.getdimension(): infos["dimensions"].append((dimension.getlower(), dimension.getupper())) - base_type = basetype_content["value"].baseType.getcontent() - if base_type["value"] is None or base_type["name"] in ["string", "wstring"]: - infos["base_type"] = base_type["name"].upper() - else: - infos["base_type"] = base_type["value"].getname() - elif basetype_content["name"] == "struct": + base_type = basetype_content.baseType.getcontent() + base_type_type = base_type.getLocalTag() + infos["base_type"] = (base_type.getname() + if base_type_type == "derived" + else base_type_type.upper()) + elif basetype_content_type == "struct": infos["type"] = "Structure" infos["elements"] = [] - for element in basetype_content["value"].getvariable(): + for element in basetype_content.getvariable(): element_infos = {} element_infos["Name"] = element.getname() element_type = element.type.getcontent() - if element_type["value"] is None or element_type["name"] in ["string", "wstring"]: - element_infos["Type"] = element_type["name"].upper() - elif element_type["name"] == "array": + element_type_type = element_type.getLocalTag() + if element_type_type == "array": dimensions = [] - for dimension in element_type["value"].getdimension(): + for dimension in element_type.getdimension(): dimensions.append((dimension.getlower(), dimension.getupper())) - base_type = element_type["value"].baseType.getcontent() - if base_type["value"] is None or base_type["name"] in ["string", "wstring"]: - base_type_name = base_type["name"].upper() - else: - base_type_name = base_type["value"].getname() - element_infos["Type"] = ("array", base_type_name, dimensions) + base_type = element_type.baseType.getcontent() + base_type_type = element_type.getLocalTag() + element_infos["Type"] = ("array", + base_type.getname() + if base_type_type == "derived" + else base_type_type.upper(), dimensions) + elif element_type_type == "derived": + element_infos["Type"] = element_type.getname() else: - element_infos["Type"] = element_type["value"].getname() + element_infos["Type"] = element_type_type.upper() if element.initialValue is not None: element_infos["Initial Value"] = str(element.initialValue.getvalue()) else: element_infos["Initial Value"] = "" infos["elements"].append(element_infos) + else: + infos["type"] = "Directly" + infos["base_type"] = (basetype_content.getname() + if basetype_content_type == "derived" + else basetype_content_type.upper()) + if datatype.initialValue is not None: infos["initial"] = str(datatype.initialValue.getvalue()) else: @@ -1917,45 +1996,46 @@ datatype = self.Project.getdataType(words[1]) if infos["type"] == "Directly": if infos["base_type"] in self.GetBaseTypes(): - if infos["base_type"] == "STRING": - datatype.baseType.setcontent({"name" : "string", "value" : plcopen.elementaryTypes_string()}) - elif infos["base_type"] == "WSTRING": - datatype.baseType.setcontent({"name" : "wstring", "value" : plcopen.elementaryTypes_wstring()}) - else: - datatype.baseType.setcontent({"name" : infos["base_type"], "value" : None}) + datatype.baseType.setcontent(PLCOpenParser.CreateElement( + infos["base_type"].lower() + if infos["base_type"] in ["STRING", "WSTRING"] + else infos["base_type"], "dataType")) else: - derived_datatype = plcopen.derivedTypes_derived() + derived_datatype = PLCOpenParser.CreateElement("derived", "dataType") derived_datatype.setname(infos["base_type"]) - datatype.baseType.setcontent({"name" : "derived", "value" : derived_datatype}) + datatype.baseType.setcontent(derived_datatype) elif infos["type"] == "Subrange": - if infos["base_type"] in GetSubTypes("ANY_UINT"): - subrange = plcopen.derivedTypes_subrangeUnsigned() - datatype.baseType.setcontent({"name" : "subrangeUnsigned", "value" : subrange}) - else: - subrange = plcopen.derivedTypes_subrangeSigned() - datatype.baseType.setcontent({"name" : "subrangeSigned", "value" : subrange}) + subrange = PLCOpenParser.CreateElement( + "subrangeUnsigned" + if infos["base_type"] in GetSubTypes("ANY_UINT") + else "subrangeSigned", "dataType") + datatype.baseType.setcontent(subrange) subrange.range.setlower(infos["min"]) subrange.range.setupper(infos["max"]) if infos["base_type"] in self.GetBaseTypes(): - subrange.baseType.setcontent({"name" : infos["base_type"], "value" : None}) + subrange.baseType.setcontent( + PLCOpenParser.CreateElement(infos["base_type"], "dataType")) else: - derived_datatype = plcopen.derivedTypes_derived() + derived_datatype = PLCOpenParser.CreateElement("derived", "dataType") derived_datatype.setname(infos["base_type"]) - subrange.baseType.setcontent({"name" : "derived", "value" : derived_datatype}) + subrange.baseType.setcontent(derived_datatype) elif infos["type"] == "Enumerated": - enumerated = plcopen.derivedTypes_enum() + enumerated = PLCOpenParser.CreateElement("enum", "dataType") + datatype.baseType.setcontent(enumerated) + values = PLCOpenParser.CreateElement("values", "enum") + enumerated.setvalues(values) for i, enum_value in enumerate(infos["values"]): - value = plcopen.values_value() + value = PLCOpenParser.CreateElement("value", "values") value.setname(enum_value) if i == 0: - enumerated.values.setvalue([value]) + values.setvalue([value]) else: - enumerated.values.appendvalue(value) - datatype.baseType.setcontent({"name" : "enum", "value" : enumerated}) + values.appendvalue(value) elif infos["type"] == "Array": - array = plcopen.derivedTypes_array() + array = PLCOpenParser.CreateElement("array", "dataType") + datatype.baseType.setcontent(array) for i, dimension in enumerate(infos["dimensions"]): - dimension_range = plcopen.rangeSigned() + dimension_range = PLCOpenParser.CreateElement("dimension", "array") dimension_range.setlower(dimension[0]) dimension_range.setupper(dimension[1]) if i == 0: @@ -1963,28 +2043,28 @@ else: array.appenddimension(dimension_range) if infos["base_type"] in self.GetBaseTypes(): - if infos["base_type"] == "STRING": - array.baseType.setcontent({"name" : "string", "value" : plcopen.elementaryTypes_string()}) - elif infos["base_type"] == "WSTRING": - array.baseType.setcontent({"name" : "wstring", "value" : plcopen.wstring()}) - else: - array.baseType.setcontent({"name" : infos["base_type"], "value" : None}) + array.baseType.setcontent(PLCOpenParser.CreateElement( + infos["base_type"].lower() + if infos["base_type"] in ["STRING", "WSTRING"] + else infos["base_type"], "dataType")) else: - derived_datatype = plcopen.derivedTypes_derived() + derived_datatype = PLCOpenParser.CreateElement("derived", "dataType") derived_datatype.setname(infos["base_type"]) - array.baseType.setcontent({"name" : "derived", "value" : derived_datatype}) - datatype.baseType.setcontent({"name" : "array", "value" : array}) + array.baseType.setcontent(derived_datatype) elif infos["type"] == "Structure": - struct = plcopen.varListPlain() + struct = PLCOpenParser.CreateElement("struct", "dataType") + datatype.baseType.setcontent(struct) for i, element_infos in enumerate(infos["elements"]): - element = plcopen.varListPlain_variable() + element = PLCOpenParser.CreateElement("variable", "struct") element.setname(element_infos["Name"]) + element_type = PLCOpenParser.CreateElement("type", "variable") if isinstance(element_infos["Type"], TupleType): if element_infos["Type"][0] == "array": array_type, base_type_name, dimensions = element_infos["Type"] - array = plcopen.derivedTypes_array() + array = PLCOpenParser.CreateElement("array", "dataType") + element_type.setcontent(array) for j, dimension in enumerate(dimensions): - dimension_range = plcopen.rangeSigned() + dimension_range = PLCOpenParser.CreateElement("dimension", "array") dimension_range.setlower(dimension[0]) dimension_range.setupper(dimension[1]) if j == 0: @@ -1992,45 +2072,39 @@ else: array.appenddimension(dimension_range) if base_type_name in self.GetBaseTypes(): - if base_type_name == "STRING": - array.baseType.setcontent({"name" : "string", "value" : plcopen.elementaryTypes_string()}) - elif base_type_name == "WSTRING": - array.baseType.setcontent({"name" : "wstring", "value" : plcopen.wstring()}) - else: - array.baseType.setcontent({"name" : base_type_name, "value" : None}) + array.baseType.setcontent(PLCOpenParser.CreateElement( + base_type_name.lower() + if base_type_name in ["STRING", "WSTRING"] + else base_type_name, "dataType")) else: - derived_datatype = plcopen.derivedTypes_derived() + derived_datatype = PLCOpenParser.CreateElement("derived", "dataType") derived_datatype.setname(base_type_name) - array.baseType.setcontent({"name" : "derived", "value" : derived_datatype}) - element.type.setcontent({"name" : "array", "value" : array}) + array.baseType.setcontent(derived_datatype) elif element_infos["Type"] in self.GetBaseTypes(): - if element_infos["Type"] == "STRING": - element.type.setcontent({"name" : "string", "value" : plcopen.elementaryTypes_string()}) - elif element_infos["Type"] == "WSTRING": - element.type.setcontent({"name" : "wstring", "value" : plcopen.wstring()}) - else: - element.type.setcontent({"name" : element_infos["Type"], "value" : None}) + element_type.setcontent( + PLCOpenParser.CreateElement( + element_infos["Type"].lower() + if element_infos["Type"] in ["STRING", "WSTRING"] + else element_infos["Type"], "dataType")) else: - derived_datatype = plcopen.derivedTypes_derived() + derived_datatype = PLCOpenParser.CreateElement("derived", "dataType") derived_datatype.setname(element_infos["Type"]) - element.type.setcontent({"name" : "derived", "value" : derived_datatype}) + element_type.setcontent(derived_datatype) + element.settype(element_type) if element_infos["Initial Value"] != "": - value = plcopen.value() + value = PLCOpenParser.CreateElement("initialValue", "variable") value.setvalue(element_infos["Initial Value"]) element.setinitialValue(value) if i == 0: struct.setvariable([element]) else: struct.appendvariable(element) - datatype.baseType.setcontent({"name" : "struct", "value" : struct}) if infos["initial"] != "": if datatype.initialValue is None: - datatype.initialValue = plcopen.value() + datatype.initialValue = PLCOpenParser.CreateElement("initialValue", "dataType") datatype.initialValue.setvalue(infos["initial"]) else: datatype.initialValue = None - self.Project.RefreshDataTypeHierarchy() - self.Project.RefreshElementUsingTree() self.BufferProject() #------------------------------------------------------------------------------- @@ -2087,25 +2161,25 @@ return None # Return the edited element variables - def GetEditedElementInterfaceVars(self, tagname, debug = False): + def GetEditedElementInterfaceVars(self, tagname, tree=False, debug = False): words = tagname.split("::") if words[0] in ["P","T","A"]: project = self.GetProject(debug) if project is not None: pou = project.getpou(words[1]) if pou is not None: - return self.GetPouInterfaceVars(pou, debug) + return self.GetPouInterfaceVars(pou, tree, debug) return [] # Return the edited element return type - def GetEditedElementInterfaceReturnType(self, tagname, debug = False): + def GetEditedElementInterfaceReturnType(self, tagname, tree=False, debug = False): words = tagname.split("::") if words[0] == "P": project = self.GetProject(debug) if project is not None: pou = self.Project.getpou(words[1]) if pou is not None: - return self.GetPouInterfaceReturnType(pou) + return self.GetPouInterfaceReturnType(pou, tree, debug) elif words[0] == 'T': return "BOOL" return None @@ -2116,7 +2190,6 @@ element = self.GetEditedElement(tagname) if element is not None: element.settext(text) - self.Project.RefreshElementUsingTree() # Return the edited element text def GetEditedElementText(self, tagname, debug = False): @@ -2161,22 +2234,28 @@ def GetEditedElementCopy(self, tagname, debug = False): element = self.GetEditedElement(tagname, debug) if element is not None: - name = element.__class__.__name__ - return element.generateXMLText(name.split("_")[-1], 0) + return element.tostring() return "" def GetEditedElementInstancesCopy(self, tagname, blocks_id = None, wires = None, debug = False): element = self.GetEditedElement(tagname, debug) text = "" if element is not None: - wires = dict([(wire, True) for wire in wires if wire[0] in blocks_id and wire[1] in blocks_id]) + wires = dict([(wire, True) + for wire in wires + if wire[0] in blocks_id and wire[1] in blocks_id]) + copy_body = PLCOpenParser.CreateElement("body", "pou") + element.append(copy_body) + copy_body.setcontent( + PLCOpenParser.CreateElement(element.getbodyType(), "body")) for id in blocks_id: instance = element.getinstance(id) if instance is not None: - instance_copy = self.Copy(instance) + copy_body.appendcontentInstance(self.Copy(instance)) + instance_copy = copy_body.getcontentInstance(id) instance_copy.filterConnections(wires) - name = instance_copy.__class__.__name__ - text += instance_copy.generateXMLText(name.split("_")[-1], 0) + text += instance_copy.tostring() + element.remove(copy_body) return text def GenerateNewName(self, tagname, name, format, start_idx=0, exclude={}, debug=False): @@ -2189,9 +2268,10 @@ element = self.GetEditedElement(tagname, debug) if element is not None and element.getbodyType() not in ["ST", "IL"]: for instance in element.getinstances(): - if isinstance(instance, (plcopen.sfcObjects_step, - plcopen.commonObjects_connector, - plcopen.commonObjects_continuation)): + if isinstance(instance, + (PLCOpenParser.GetElementClass("step", "sfcObjects"), + PLCOpenParser.GetElementClass("connector", "commonObjects"), + PLCOpenParser.GetElementClass("continuation", "commonObjects"))): names[instance.getname().upper()] = True else: project = self.GetProject(debug) @@ -2200,8 +2280,8 @@ names[datatype.getname().upper()] = True for pou in project.getpous(): names[pou.getname().upper()] = True - for var in self.GetPouInterfaceVars(pou, debug): - names[var["Name"].upper()] = True + for var in self.GetPouInterfaceVars(pou, debug=debug): + names[var.Name.upper()] = True for transition in pou.gettransitionList(): names[transition.getname().upper()] = True for action in pou.getactionList(): @@ -2217,10 +2297,6 @@ i += 1 return name - CheckPasteCompatibility = {"SFC": lambda name: True, - "LD": lambda name: not name.startswith("sfcObjects"), - "FBD": lambda name: name.startswith("fbdObjects") or name.startswith("commonObjects")} - def PasteEditedElementInstances(self, tagname, text, new_pos, middle=False, debug=False): element = self.GetEditedElement(tagname, debug) element_name, element_type = self.GetEditedElementType(tagname, debug) @@ -2238,62 +2314,47 @@ used_id = dict([(instance.getlocalId(), True) for instance in element.getinstances()]) new_id = {} - text = "%s"%text + try: + instances, error = LoadPouInstances(text.encode("utf-8"), bodytype) + except: + instances, error = [], "" + if error is not None or len(instances) == 0: + return _("Invalid plcopen element(s)!!!") - try: - tree = minidom.parseString(text.encode("utf-8")) - except: - return _("Invalid plcopen element(s)!!!") - instances = [] exclude = {} - for root in tree.childNodes: - if root.nodeType == tree.ELEMENT_NODE and root.nodeName == "paste": - for child in root.childNodes: - if child.nodeType == tree.ELEMENT_NODE: - if not child.nodeName in plcopen.ElementNameToClass: - return _("\"%s\" element can't be pasted here!!!")%child.nodeName - - classname = plcopen.ElementNameToClass[child.nodeName] - if not self.CheckPasteCompatibility[bodytype](classname): - return _("\"%s\" element can't be pasted here!!!")%child.nodeName - - classobj = getattr(plcopen, classname, None) - if classobj is not None: - instance = classobj() - instance.loadXMLTree(child) - if child.nodeName == "block": - blockname = instance.getinstanceName() - if blockname is not None: - blocktype = instance.gettypeName() - if element_type == "function": - return _("FunctionBlock \"%s\" can't be pasted in a Function!!!")%blocktype - blockname = self.GenerateNewName(tagname, - blockname, - "%s%%d"%blocktype, - debug=debug) - exclude[blockname] = True - instance.setinstanceName(blockname) - self.AddEditedElementPouVar(tagname, blocktype, blockname) - elif child.nodeName == "step": - stepname = self.GenerateNewName(tagname, - instance.getname(), - "Step%d", - exclude=exclude, - debug=debug) - exclude[stepname] = True - instance.setname(stepname) - localid = instance.getlocalId() - if not used_id.has_key(localid): - new_id[localid] = True - instances.append((child.nodeName, instance)) - - if len(instances) == 0: - return _("Invalid plcopen element(s)!!!") + for instance in instances: + element.addinstance(instance) + instance_type = instance.getLocalTag() + if instance_type == "block": + blocktype = instance.gettypeName() + blocktype_infos = self.GetBlockType(blocktype) + blockname = instance.getinstanceName() + if blocktype_infos["type"] != "function" and blockname is not None: + if element_type == "function": + return _("FunctionBlock \"%s\" can't be pasted in a Function!!!")%blocktype + blockname = self.GenerateNewName(tagname, + blockname, + "%s%%d"%blocktype, + debug=debug) + exclude[blockname] = True + instance.setinstanceName(blockname) + self.AddEditedElementPouVar(tagname, blocktype, blockname) + elif instance_type == "step": + stepname = self.GenerateNewName(tagname, + instance.getname(), + "Step%d", + exclude=exclude, + debug=debug) + exclude[stepname] = True + instance.setname(stepname) + localid = instance.getlocalId() + if not used_id.has_key(localid): + new_id[localid] = True idx = 1 translate_id = {} - bbox = plcopen.rect() - for name, instance in instances: + bbox = rect() + for instance in instances: localId = instance.getlocalId() bbox.union(instance.getBoundingBox()) if used_id.has_key(localId): @@ -2323,36 +2384,33 @@ max(miny, round(new_pos[1] / scaling[1]) * scaling[1])) else: new_pos = (max(30, new_pos[0]), max(30, new_pos[1])) - diff = (new_pos[0] - x, new_pos[1] - y) + diff = (int(new_pos[0] - x), int(new_pos[1] - y)) connections = {} - for name, instance in instances: + for instance in instances: connections.update(instance.updateConnectionsId(translate_id)) if getattr(instance, "setexecutionOrderId", None) is not None: instance.setexecutionOrderId(0) instance.translate(*diff) - element.addinstance(name, instance) return new_id, connections - - # Return the current pou editing informations - def GetEditedElementInstanceInfos(self, tagname, id = None, exclude = [], debug = False): - infos = {} - instance = None + + def GetEditedElementInstancesInfos(self, tagname, debug = False): + element_instances = OrderedDict() element = self.GetEditedElement(tagname, debug) if element is not None: - # if id is defined - if id is not None: - instance = element.getinstance(id) - else: - instance = element.getrandomInstance(exclude) - if instance is not None: - infos = instance.getinfos() - if infos["type"] in ["input", "output", "inout"]: - var_type = self.GetEditedElementVarValueType(tagname, infos["specific_values"]["name"], debug) - infos["specific_values"]["value_type"] = var_type - return infos - return None + factory = BlockInstanceFactory(element_instances) + + pou_block_instances_xslt_tree = etree.XSLT( + pou_block_instances_xslt, + extensions = { + ("pou_block_instances_ns", name): getattr(factory, name) + for name in ["AddBlockInstance", "SetSpecificValues", + "AddInstanceConnection", "AddConnectionLink", + "AddLinkPoint", "AddAction"]}) + + pou_block_instances_xslt_tree(element) + return element_instances def ClearEditedElementExecutionOrder(self, tagname): element = self.GetEditedElement(tagname) @@ -2364,30 +2422,6 @@ if element is not None: element.compileexecutionOrder() - # Return the variable type of the given pou - def GetEditedElementVarValueType(self, tagname, varname, debug = False): - project = self.GetProject(debug) - if project is not None: - words = tagname.split("::") - if words[0] in ["P","T","A"]: - pou = self.Project.getpou(words[1]) - if pou is not None: - if words[0] == "T" and varname == words[2]: - return "BOOL" - if words[1] == varname: - return self.GetPouInterfaceReturnType(pou) - for type, varlist in pou.getvars(): - for var in varlist.getvariable(): - if var.getname() == varname: - vartype_content = var.gettype().getcontent() - if vartype_content["name"] == "derived": - return vartype_content["value"].getname() - elif vartype_content["name"] in ["string", "wstring"]: - return vartype_content["name"].upper() - else: - return vartype_content["name"] - return None - def SetConnectionWires(self, connection, connector): wires = connector.GetWires() idx = 0 @@ -2410,21 +2444,36 @@ connection.setconnectionParameter(idx, None) idx += 1 - def AddEditedElementPouVar(self, tagname, type, name, location="", description=""): + def GetVarTypeObject(self, var_type): + var_type_obj = PLCOpenParser.CreateElement("type", "variable") + if not var_type.startswith("ANY") and TypeHierarchy.get(var_type): + var_type_obj.setcontent(PLCOpenParser.CreateElement( + var_type.lower() if var_type in ["STRING", "WSTRING"] + else var_type, "dataType")) + else: + derived_type = PLCOpenParser.CreateElement("derived", "dataType") + derived_type.setname(var_type) + var_type_obj.setcontent(derived_type) + return var_type_obj + + def AddEditedElementPouVar(self, tagname, var_type, name, location="", description=""): if self.Project is not None: words = tagname.split("::") if words[0] in ['P', 'T', 'A']: pou = self.Project.getpou(words[1]) if pou is not None: - pou.addpouLocalVar(type, name, location, description) - - def AddEditedElementPouExternalVar(self, tagname, type, name): + pou.addpouLocalVar( + self.GetVarTypeObject(var_type), + name, location, description) + + def AddEditedElementPouExternalVar(self, tagname, var_type, name): if self.Project is not None: words = tagname.split("::") if words[0] in ['P', 'T', 'A']: pou = self.Project.getpou(words[1]) if pou is not None: - pou.addpouExternalVar(type, name) + pou.addpouExternalVar( + self.GetVarTypeObject(var_type), name) def ChangeEditedElementPouVar(self, tagname, old_type, old_name, new_type, new_name): if self.Project is not None: @@ -2445,15 +2494,14 @@ def AddEditedElementBlock(self, tagname, id, blocktype, blockname = None): element = self.GetEditedElement(tagname) if element is not None: - block = plcopen.fbdObjects_block() + block = PLCOpenParser.CreateElement("block", "fbdObjects") block.setlocalId(id) block.settypeName(blocktype) blocktype_infos = self.GetBlockType(blocktype) if blocktype_infos["type"] != "function" and blockname is not None: block.setinstanceName(blockname) self.AddEditedElementPouVar(tagname, blocktype, blockname) - element.addinstance("block", block) - self.Project.RefreshElementUsingTree() + element.addinstance(block) def SetEditedElementBlockInfos(self, tagname, id, infos): element = self.GetEditedElement(tagname) @@ -2481,7 +2529,10 @@ self.ChangeEditedElementPouVar(tagname, old_type, old_name, new_type, new_name) for param, value in infos.items(): if param == "name": - block.setinstanceName(value) + if value != "": + block.setinstanceName(value) + else: + block.attrib.pop("instanceName", None) elif param == "type": block.settypeName(value) elif param == "executionOrder" and block.getexecutionOrderId() != value: @@ -2498,7 +2549,8 @@ block.inputVariables.setvariable([]) block.outputVariables.setvariable([]) for connector in value["inputs"]: - variable = plcopen.inputVariables_variable() + variable = PLCOpenParser.CreateElement("variable", "inputVariables") + block.inputVariables.appendvariable(variable) variable.setformalParameter(connector.GetName()) if connector.IsNegated(): variable.setnegated(True) @@ -2507,9 +2559,9 @@ position = connector.GetRelPosition() variable.connectionPointIn.setrelPositionXY(position.x, position.y) self.SetConnectionWires(variable.connectionPointIn, connector) - block.inputVariables.appendvariable(variable) for connector in value["outputs"]: - variable = plcopen.outputVariables_variable() + variable = PLCOpenParser.CreateElement("variable", "outputVariables") + block.outputVariables.appendvariable(variable) variable.setformalParameter(connector.GetName()) if connector.IsNegated(): variable.setnegated(True) @@ -2518,23 +2570,17 @@ position = connector.GetRelPosition() variable.addconnectionPointOut() variable.connectionPointOut.setrelPositionXY(position.x, position.y) - block.outputVariables.appendvariable(variable) - self.Project.RefreshElementUsingTree() - - def AddEditedElementVariable(self, tagname, id, type): + block.tostring() + + def AddEditedElementVariable(self, tagname, id, var_type): element = self.GetEditedElement(tagname) - if element is not None: - if type == INPUT: - name = "inVariable" - variable = plcopen.fbdObjects_inVariable() - elif type == OUTPUT: - name = "outVariable" - variable = plcopen.fbdObjects_outVariable() - elif type == INOUT: - name = "inOutVariable" - variable = plcopen.fbdObjects_inOutVariable() + if element is not None: + variable = PLCOpenParser.CreateElement( + {INPUT: "inVariable", + OUTPUT: "outVariable", + INOUT: "inOutVariable"}[var_type], "fbdObjects") variable.setlocalId(id) - element.addinstance(name, variable) + element.addinstance(variable) def SetEditedElementVariableInfos(self, tagname, id, infos): element = self.GetEditedElement(tagname) @@ -2544,7 +2590,7 @@ return for param, value in infos.items(): if param == "name": - variable.setexpression(value) + variable.setexpression(value) elif param == "executionOrder" and variable.getexecutionOrderId() != value: element.setelementExecutionOrder(variable, value) elif param == "height": @@ -2580,17 +2626,14 @@ variable.connectionPointIn.setrelPositionXY(position.x, position.y) self.SetConnectionWires(variable.connectionPointIn, input) - def AddEditedElementConnection(self, tagname, id, type): + def AddEditedElementConnection(self, tagname, id, connection_type): element = self.GetEditedElement(tagname) if element is not None: - if type == CONNECTOR: - name = "connector" - connection = plcopen.commonObjects_connector() - elif type == CONTINUATION: - name = "continuation" - connection = plcopen.commonObjects_continuation() + connection = PLCOpenParser.CreateElement( + {CONNECTOR: "connector", + CONTINUATION: "continuation"}[connection_type], "commonObjects") connection.setlocalId(id) - element.addinstance(name, connection) + element.addinstance(connection) def SetEditedElementConnectionInfos(self, tagname, id, infos): element = self.GetEditedElement(tagname) @@ -2611,10 +2654,10 @@ connection.sety(value) elif param == "connector": position = value.GetRelPosition() - if isinstance(connection, plcopen.commonObjects_continuation): + if isinstance(connection, PLCOpenParser.GetElementClass("continuation", "commonObjects")): connection.addconnectionPointOut() connection.connectionPointOut.setrelPositionXY(position.x, position.y) - elif isinstance(connection, plcopen.commonObjects_connector): + elif isinstance(connection, PLCOpenParser.GetElementClass("connector", "commonObjects")): connection.addconnectionPointIn() connection.connectionPointIn.setrelPositionXY(position.x, position.y) self.SetConnectionWires(connection.connectionPointIn, value) @@ -2622,9 +2665,9 @@ def AddEditedElementComment(self, tagname, id): element = self.GetEditedElement(tagname) if element is not None: - comment = plcopen.commonObjects_comment() + comment = PLCOpenParser.CreateElement("comment", "commonObjects") comment.setlocalId(id) - element.addinstance("comment", comment) + element.addinstance(comment) def SetEditedElementCommentInfos(self, tagname, id, infos): element = self.GetEditedElement(tagname) @@ -2642,17 +2685,14 @@ elif param == "y": comment.sety(value) - def AddEditedElementPowerRail(self, tagname, id, type): + def AddEditedElementPowerRail(self, tagname, id, powerrail_type): element = self.GetEditedElement(tagname) if element is not None: - if type == LEFTRAIL: - name = "leftPowerRail" - powerrail = plcopen.ldObjects_leftPowerRail() - elif type == RIGHTRAIL: - name = "rightPowerRail" - powerrail = plcopen.ldObjects_rightPowerRail() + powerrail = PLCOpenParser.CreateElement( + {LEFTRAIL: "leftPowerRail", + RIGHTRAIL: "rightPowerRail"}[powerrail_type], "ldObjects") powerrail.setlocalId(id) - element.addinstance(name, powerrail) + element.addinstance(powerrail) def SetEditedElementPowerRailInfos(self, tagname, id, infos): element = self.GetEditedElement(tagname) @@ -2670,28 +2710,28 @@ elif param == "y": powerrail.sety(value) elif param == "connectors": - if isinstance(powerrail, plcopen.ldObjects_leftPowerRail): + if isinstance(powerrail, PLCOpenParser.GetElementClass("leftPowerRail", "ldObjects")): powerrail.setconnectionPointOut([]) for connector in value["outputs"]: position = connector.GetRelPosition() - connection = plcopen.leftPowerRail_connectionPointOut() + connection = PLCOpenParser.CreateElement("connectionPointOut", "leftPowerRail") + powerrail.appendconnectionPointOut(connection) connection.setrelPositionXY(position.x, position.y) - powerrail.connectionPointOut.append(connection) - elif isinstance(powerrail, plcopen.ldObjects_rightPowerRail): + elif isinstance(powerrail, PLCOpenParser.GetElementClass("rightPowerRail", "ldObjects")): powerrail.setconnectionPointIn([]) for connector in value["inputs"]: position = connector.GetRelPosition() - connection = plcopen.connectionPointIn() + connection = PLCOpenParser.CreateElement("connectionPointIn", "rightPowerRail") + powerrail.appendconnectionPointIn(connection) connection.setrelPositionXY(position.x, position.y) self.SetConnectionWires(connection, connector) - powerrail.connectionPointIn.append(connection) - + def AddEditedElementContact(self, tagname, id): element = self.GetEditedElement(tagname) if element is not None: - contact = plcopen.ldObjects_contact() + contact = PLCOpenParser.CreateElement("contact", "ldObjects") contact.setlocalId(id) - element.addinstance("contact", contact) + element.addinstance(contact) def SetEditedElementContactInfos(self, tagname, id, infos): element = self.GetEditedElement(tagname) @@ -2703,18 +2743,13 @@ if param == "name": contact.setvariable(value) elif param == "type": - if value == CONTACT_NORMAL: - contact.setnegated(False) - contact.setedge("none") - elif value == CONTACT_REVERSE: - contact.setnegated(True) - contact.setedge("none") - elif value == CONTACT_RISING: - contact.setnegated(False) - contact.setedge("rising") - elif value == CONTACT_FALLING: - contact.setnegated(False) - contact.setedge("falling") + negated, edge = { + CONTACT_NORMAL: (False, "none"), + CONTACT_REVERSE: (True, "none"), + CONTACT_RISING: (False, "rising"), + CONTACT_FALLING: (False, "falling")}[value] + contact.setnegated(negated) + contact.setedge(edge) elif param == "height": contact.setheight(value) elif param == "width": @@ -2737,9 +2772,9 @@ def AddEditedElementCoil(self, tagname, id): element = self.GetEditedElement(tagname) if element is not None: - coil = plcopen.ldObjects_coil() + coil = PLCOpenParser.CreateElement("coil", "ldObjects") coil.setlocalId(id) - element.addinstance("coil", coil) + element.addinstance(coil) def SetEditedElementCoilInfos(self, tagname, id, infos): element = self.GetEditedElement(tagname) @@ -2751,30 +2786,16 @@ if param == "name": coil.setvariable(value) elif param == "type": - if value == COIL_NORMAL: - coil.setnegated(False) - coil.setstorage("none") - coil.setedge("none") - elif value == COIL_REVERSE: - coil.setnegated(True) - coil.setstorage("none") - coil.setedge("none") - elif value == COIL_SET: - coil.setnegated(False) - coil.setstorage("set") - coil.setedge("none") - elif value == COIL_RESET: - coil.setnegated(False) - coil.setstorage("reset") - coil.setedge("none") - elif value == COIL_RISING: - coil.setnegated(False) - coil.setstorage("none") - coil.setedge("rising") - elif value == COIL_FALLING: - coil.setnegated(False) - coil.setstorage("none") - coil.setedge("falling") + negated, storage, edge = { + COIL_NORMAL: (False, "none", "none"), + COIL_REVERSE: (True, "none", "none"), + COIL_SET: (False, "set", "none"), + COIL_RESET: (False, "reset", "none"), + COIL_RISING: (False, "none", "rising"), + COIL_FALLING: (False, "none", "falling")}[value] + coil.setnegated(negated) + coil.setstorage(storage) + coil.setedge(edge) elif param == "height": coil.setheight(value) elif param == "width": @@ -2797,9 +2818,9 @@ def AddEditedElementStep(self, tagname, id): element = self.GetEditedElement(tagname) if element is not None: - step = plcopen.sfcObjects_step() + step = PLCOpenParser.CreateElement("step", "sfcObjects") step.setlocalId(id) - element.addinstance("step", step) + element.addinstance(step) def SetEditedElementStepInfos(self, tagname, id, infos): element = self.GetEditedElement(tagname) @@ -2847,9 +2868,9 @@ def AddEditedElementTransition(self, tagname, id): element = self.GetEditedElement(tagname) if element is not None: - transition = plcopen.sfcObjects_transition() + transition = PLCOpenParser.CreateElement("transition", "sfcObjects") transition.setlocalId(id) - element.addinstance("transition", transition) + element.addinstance(transition) def SetEditedElementTransitionInfos(self, tagname, id, infos): element = self.GetEditedElement(tagname) @@ -2885,25 +2906,31 @@ transition.connectionPointOut.setrelPositionXY(position.x, position.y) elif infos.get("type", None) == "connection" and param == "connection" and value: transition.setconditionContent("connection", None) - self.SetConnectionWires(transition.condition.content["value"], value) - - def AddEditedElementDivergence(self, tagname, id, type): + self.SetConnectionWires(transition.condition.content, value) + + def AddEditedElementDivergence(self, tagname, id, divergence_type): element = self.GetEditedElement(tagname) if element is not None: - if type == SELECTION_DIVERGENCE: - name = "selectionDivergence" - divergence = plcopen.sfcObjects_selectionDivergence() - elif type == SELECTION_CONVERGENCE: - name = "selectionConvergence" - divergence = plcopen.sfcObjects_selectionConvergence() - elif type == SIMULTANEOUS_DIVERGENCE: - name = "simultaneousDivergence" - divergence = plcopen.sfcObjects_simultaneousDivergence() - elif type == SIMULTANEOUS_CONVERGENCE: - name = "simultaneousConvergence" - divergence = plcopen.sfcObjects_simultaneousConvergence() + divergence = PLCOpenParser.CreateElement( + {SELECTION_DIVERGENCE: "selectionDivergence", + SELECTION_CONVERGENCE: "selectionConvergence", + SIMULTANEOUS_DIVERGENCE: "simultaneousDivergence", + SIMULTANEOUS_CONVERGENCE: "simultaneousConvergence"}.get( + divergence_type), "sfcObjects") divergence.setlocalId(id) - element.addinstance(name, divergence) + element.addinstance(divergence) + + DivergenceTypes = [ + (divergence_type, + PLCOpenParser.GetElementClass(divergence_type, "sfcObjects")) + for divergence_type in ["selectionDivergence", "simultaneousDivergence", + "selectionConvergence", "simultaneousConvergence"]] + + def GetDivergenceType(self, divergence): + for divergence_type, divergence_class in self.DivergenceTypes: + if isinstance(divergence, divergence_class): + return divergence_type + return None def SetEditedElementDivergenceInfos(self, tagname, id, infos): element = self.GetEditedElement(tagname) @@ -2922,7 +2949,8 @@ divergence.sety(value) elif param == "connectors": input_connectors = value["inputs"] - if isinstance(divergence, (plcopen.sfcObjects_selectionDivergence, plcopen.sfcObjects_simultaneousDivergence)): + divergence_type = self.GetDivergenceType(divergence) + if divergence_type in ["selectionDivergence", "simultaneousDivergence"]: position = input_connectors[0].GetRelPosition() divergence.addconnectionPointIn() divergence.connectionPointIn.setrelPositionXY(position.x, position.y) @@ -2931,15 +2959,12 @@ divergence.setconnectionPointIn([]) for input_connector in input_connectors: position = input_connector.GetRelPosition() - if isinstance(divergence, plcopen.sfcObjects_selectionConvergence): - connection = plcopen.selectionConvergence_connectionPointIn() - else: - connection = plcopen.connectionPointIn() + connection = PLCOpenParser.CreateElement("connectionPointIn", divergence_type) + divergence.appendconnectionPointIn(connection) connection.setrelPositionXY(position.x, position.y) self.SetConnectionWires(connection, input_connector) - divergence.appendconnectionPointIn(connection) output_connectors = value["outputs"] - if isinstance(divergence, (plcopen.sfcObjects_selectionConvergence, plcopen.sfcObjects_simultaneousConvergence)): + if divergence_type in ["selectionConvergence", "simultaneousConvergence"]: position = output_connectors[0].GetRelPosition() divergence.addconnectionPointOut() divergence.connectionPointOut.setrelPositionXY(position.x, position.y) @@ -2947,19 +2972,16 @@ divergence.setconnectionPointOut([]) for output_connector in output_connectors: position = output_connector.GetRelPosition() - if isinstance(divergence, plcopen.sfcObjects_selectionDivergence): - connection = plcopen.selectionDivergence_connectionPointOut() - else: - connection = plcopen.simultaneousDivergence_connectionPointOut() + connection = PLCOpenParser.CreateElement("connectionPointOut", divergence_type) + divergence.appendconnectionPointOut(connection) connection.setrelPositionXY(position.x, position.y) - divergence.appendconnectionPointOut(connection) - + def AddEditedElementJump(self, tagname, id): element = self.GetEditedElement(tagname) if element is not None: - jump = plcopen.sfcObjects_jumpStep() + jump = PLCOpenParser.CreateElement("jumpStep", "sfcObjects") jump.setlocalId(id) - element.addinstance("jumpStep", jump) + element.addinstance(jump) def SetEditedElementJumpInfos(self, tagname, id, infos): element = self.GetEditedElement(tagname) @@ -2987,9 +3009,9 @@ def AddEditedElementActionBlock(self, tagname, id): element = self.GetEditedElement(tagname) if element is not None: - actionBlock = plcopen.commonObjects_actionBlock() + actionBlock = PLCOpenParser.CreateElement("actionBlock", "commonObjects") actionBlock.setlocalId(id) - element.addinstance("actionBlock", actionBlock) + element.addinstance(actionBlock) def SetEditedElementActionBlockInfos(self, tagname, id, infos): element = self.GetEditedElement(tagname) @@ -3018,20 +3040,19 @@ element = self.GetEditedElement(tagname) if element is not None: instance = element.getinstance(id) - if isinstance(instance, plcopen.fbdObjects_block): + if isinstance(instance, PLCOpenParser.GetElementClass("block", "fbdObjects")): self.RemoveEditedElementPouVar(tagname, instance.gettypeName(), instance.getinstanceName()) element.removeinstance(id) - self.Project.RefreshElementUsingTree() def GetEditedResourceVariables(self, tagname, debug = False): varlist = [] words = tagname.split("::") for var in self.GetConfigurationGlobalVars(words[1], debug): - if var["Type"] == "BOOL": - varlist.append(var["Name"]) + if var.Type == "BOOL": + varlist.append(var.Name) for var in self.GetConfigurationResourceGlobalVars(words[1], words[2], debug): - if var["Type"] == "BOOL": - varlist.append(var["Name"]) + if var.Type == "BOOL": + varlist.append(var.Name) return varlist def SetEditedResourceInfos(self, tagname, tasks, instances): @@ -3041,7 +3062,8 @@ resource.setpouInstance([]) task_list = {} for task in tasks: - new_task = plcopen.resource_task() + new_task = PLCOpenParser.CreateElement("task", "resource") + resource.appendtask(new_task) new_task.setname(task["Name"]) if task["Triggering"] == "Interrupt": new_task.setsingle(task["Single"]) @@ -3061,12 +3083,16 @@ new_task.setpriority(int(task["Priority"])) if task["Name"] != "": task_list[task["Name"]] = new_task - resource.appendtask(new_task) for instance in instances: - new_instance = plcopen.pouInstance() + task = task_list.get(instance["Task"]) + if task is not None: + new_instance = PLCOpenParser.CreateElement("pouInstance", "task") + task.appendpouInstance(new_instance) + else: + new_instance = PLCOpenParser.CreateElement("pouInstance", "resource") + resource.appendpouInstance(new_instance) new_instance.setname(instance["Name"]) new_instance.settypeName(instance["Type"]) - task_list.get(instance["Task"], resource).appendpouInstance(new_instance) def GetEditedResourceInfos(self, tagname, debug = False): resource = self.GetEditedElement(tagname, debug) @@ -3124,31 +3150,19 @@ return tasks_data, instances_data def OpenXMLFile(self, filepath): - xmlfile = open(filepath, 'r') - tree = minidom.parse(xmlfile) - xmlfile.close() - - self.Project = plcopen.project() - for child in tree.childNodes: - if child.nodeType == tree.ELEMENT_NODE and child.nodeName == "project": - try: - result = self.Project.loadXMLTree(child) - except ValueError, e: - return _("Project file syntax error:\n\n") + str(e) - self.SetFilePath(filepath) - self.Project.RefreshElementUsingTree() - self.Project.RefreshDataTypeHierarchy() - self.Project.RefreshCustomBlockTypes() - self.CreateProjectBuffer(True) - self.ProgramChunks = [] - self.ProgramOffset = 0 - self.NextCompiledProject = self.Copy(self.Project) - self.CurrentCompiledProject = None - self.Buffering = False - self.CurrentElementEditing = None - return None - return _("No PLC project found") - + self.Project, error = LoadProject(filepath) + if self.Project is None: + return _("Project file syntax error:\n\n") + error + self.SetFilePath(filepath) + self.CreateProjectBuffer(True) + self.ProgramChunks = [] + self.ProgramOffset = 0 + self.NextCompiledProject = self.Copy(self.Project) + self.CurrentCompiledProject = None + self.Buffering = False + self.CurrentElementEditing = None + return error + def SaveXMLFile(self, filepath = None): if not filepath and self.FilePath == "": return False @@ -3156,19 +3170,11 @@ contentheader = {"modificationDateTime": datetime.datetime(*localtime()[:6])} self.Project.setcontentHeader(contentheader) - text = "\n" - extras = {"xmlns" : "http://www.plcopen.org/xml/tc6.xsd", - "xmlns:xhtml" : "http://www.w3.org/1999/xhtml", - "xmlns:xsi" : "http://www.w3.org/2001/XMLSchema-instance", - "xsi:schemaLocation" : "http://www.plcopen.org/xml/tc6.xsd"} - text += self.Project.generateXMLText("project", 0, extras) + if filepath: + SaveProject(self.Project, filepath) + else: + SaveProject(self.Project, self.FilePath) - if filepath: - xmlfile = open(filepath,"w") - else: - xmlfile = open(self.FilePath,"w") - xmlfile.write(text.encode("utf-8")) - xmlfile.close() self.MarkProjectAsSaved() if filepath: self.SetFilePath(filepath) @@ -3195,11 +3201,11 @@ Return a copy of the project """ def Copy(self, model): - return cPickle.loads(cPickle.dumps(model)) + return deepcopy(model) def CreateProjectBuffer(self, saved): if self.ProjectBufferEnabled: - self.ProjectBuffer = UndoBuffer(cPickle.dumps(self.Project), saved) + self.ProjectBuffer = UndoBuffer(PLCOpenParser.Dumps(self.Project), saved) else: self.ProjectBuffer = None self.ProjectSaved = saved @@ -3218,7 +3224,7 @@ def BufferProject(self): if self.ProjectBuffer is not None: - self.ProjectBuffer.Buffering(cPickle.dumps(self.Project)) + self.ProjectBuffer.Buffering(PLCOpenParser.Dumps(self.Project)) else: self.ProjectSaved = False @@ -3230,7 +3236,7 @@ def EndBuffering(self): if self.ProjectBuffer is not None and self.Buffering: - self.ProjectBuffer.Buffering(cPickle.dumps(self.Project)) + self.ProjectBuffer.Buffering(PLCOpenParser.Dumps(self.Project)) self.Buffering = False def MarkProjectAsSaved(self): @@ -3250,11 +3256,11 @@ def LoadPrevious(self): self.EndBuffering() if self.ProjectBuffer is not None: - self.Project = cPickle.loads(self.ProjectBuffer.Previous()) + self.Project = PLCOpenParser.Loads(self.ProjectBuffer.Previous()) def LoadNext(self): if self.ProjectBuffer is not None: - self.Project = cPickle.loads(self.ProjectBuffer.Next()) + self.Project = PLCOpenParser.Loads(self.ProjectBuffer.Next()) def GetBufferState(self): if self.ProjectBuffer is not None: diff -r 72a826dfcfbb -r 02fe382c4511 PLCGenerator.py --- a/PLCGenerator.py Wed Jul 31 10:45:07 2013 +0900 +++ b/PLCGenerator.py Mon Nov 18 12:12:31 2013 +0900 @@ -22,7 +22,7 @@ #License along with this library; if not, write to the Free Software #Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -from plcopen import plcopen +from plcopen import PLCOpenParser from plcopen.structures import * from types import * import re @@ -75,6 +75,13 @@ else: return cmp(ay, by) +# Helper for emulate join on element list +def JoinList(separator, mylist): + if len(mylist) > 0 : + return reduce(lambda x, y: x + separator + y, mylist) + else : + return mylist + #------------------------------------------------------------------------------- # Specific exception for PLC generating errors #------------------------------------------------------------------------------- @@ -126,26 +133,25 @@ (datatype.getname(), (tagname, "name")), (" : ", ())] basetype_content = datatype.baseType.getcontent() - # Data type derived directly from a string type - if basetype_content["name"] in ["string", "wstring"]: - datatype_def += [(basetype_content["name"].upper(), (tagname, "base"))] + basetype_content_type = basetype_content.getLocalTag() # Data type derived directly from a user defined type - elif basetype_content["name"] == "derived": - basetype_name = basetype_content["value"].getname() + if basetype_content_type == "derived": + basetype_name = basetype_content.getname() self.GenerateDataType(basetype_name) datatype_def += [(basetype_name, (tagname, "base"))] # Data type is a subrange - elif basetype_content["name"] in ["subrangeSigned", "subrangeUnsigned"]: - base_type = basetype_content["value"].baseType.getcontent() + elif basetype_content_type in ["subrangeSigned", "subrangeUnsigned"]: + base_type = basetype_content.baseType.getcontent() + base_type_type = base_type.getLocalTag() # Subrange derived directly from a user defined type - if base_type["name"] == "derived": - basetype_name = base_type["value"].getname() + if base_type_type == "derived": + basetype_name = base_type_type.getname() self.GenerateDataType(basetype_name) # Subrange derived directly from an elementary type else: - basetype_name = base_type["name"] - min_value = basetype_content["value"].range.getlower() - max_value = basetype_content["value"].range.getupper() + basetype_name = base_type_type + min_value = basetype_content.range.getlower() + max_value = basetype_content.range.getupper() datatype_def += [(basetype_name, (tagname, "base")), (" (", ()), ("%s"%min_value, (tagname, "lower")), @@ -153,63 +159,59 @@ ("%s"%max_value, (tagname, "upper")), (")",())] # Data type is an enumerated type - elif basetype_content["name"] == "enum": + elif basetype_content_type == "enum": values = [[(value.getname(), (tagname, "value", i))] - for i, value in enumerate(basetype_content["value"].values.getvalue())] + for i, value in enumerate( + basetype_content.xpath("ppx:values/ppx:value", + namespaces=PLCOpenParser.NSMAP))] datatype_def += [("(", ())] datatype_def += JoinList([(", ", ())], values) datatype_def += [(")", ())] # Data type is an array - elif basetype_content["name"] == "array": - base_type = basetype_content["value"].baseType.getcontent() + elif basetype_content_type == "array": + base_type = basetype_content.baseType.getcontent() + base_type_type = base_type.getLocalTag() # Array derived directly from a user defined type - if base_type["name"] == "derived": - basetype_name = base_type["value"].getname() + if base_type_type == "derived": + basetype_name = base_type.getname() self.GenerateDataType(basetype_name) - # Array derived directly from a string type - elif base_type["name"] in ["string", "wstring"]: - basetype_name = base_type["name"].upper() # Array derived directly from an elementary type else: - basetype_name = base_type["name"] + basetype_name = base_type_type.upper() dimensions = [[("%s"%dimension.getlower(), (tagname, "range", i, "lower")), ("..", ()), ("%s"%dimension.getupper(), (tagname, "range", i, "upper"))] - for i, dimension in enumerate(basetype_content["value"].getdimension())] + for i, dimension in enumerate(basetype_content.getdimension())] datatype_def += [("ARRAY [", ())] datatype_def += JoinList([(",", ())], dimensions) datatype_def += [("] OF " , ()), (basetype_name, (tagname, "base"))] # Data type is a structure - elif basetype_content["name"] == "struct": + elif basetype_content_type == "struct": elements = [] - for i, element in enumerate(basetype_content["value"].getvariable()): + for i, element in enumerate(basetype_content.getvariable()): element_type = element.type.getcontent() + element_type_type = element_type.getLocalTag() # Structure element derived directly from a user defined type - if element_type["name"] == "derived": - elementtype_name = element_type["value"].getname() + if element_type_type == "derived": + elementtype_name = element_type.getname() self.GenerateDataType(elementtype_name) - elif element_type["name"] == "array": - base_type = element_type["value"].baseType.getcontent() + elif element_type_type == "array": + base_type = element_type.baseType.getcontent() + base_type_type = base_type.getLocalTag() # Array derived directly from a user defined type - if base_type["name"] == "derived": - basetype_name = base_type["value"].getname() + if base_type_type == "derived": + basetype_name = base_type.getname() self.GenerateDataType(basetype_name) - # Array derived directly from a string type - elif base_type["name"] in ["string", "wstring"]: - basetype_name = base_type["name"].upper() # Array derived directly from an elementary type else: - basetype_name = base_type["name"] + basetype_name = base_type_type.upper() dimensions = ["%s..%s" % (dimension.getlower(), dimension.getupper()) - for dimension in element_type["value"].getdimension()] + for dimension in element_type.getdimension()] elementtype_name = "ARRAY [%s] OF %s" % (",".join(dimensions), basetype_name) - # Structure element derived directly from a string type - elif element_type["name"] in ["string", "wstring"]: - elementtype_name = element_type["name"].upper() # Structure element derived directly from an elementary type else: - elementtype_name = element_type["name"] + elementtype_name = element_type_type.upper() element_text = [("\n ", ()), (element.getname(), (tagname, "struct", i, "name")), (" : ", ()), @@ -224,7 +226,7 @@ datatype_def += [("\n END_STRUCT", ())] # Data type derived directly from a elementary type else: - datatype_def += [(basetype_content["name"], (tagname, "base"))] + datatype_def += [(basetype_content_type.upper(), (tagname, "base"))] # Data type has an initial value if datatype.initialValue is not None: datatype_def += [(" := ", ()), @@ -269,10 +271,15 @@ varlists = [(varlist, varlist.getvariable()[:]) for varlist in configuration.getglobalVars()] extra_variables = self.Controler.GetConfigurationExtraVariables() - if len(extra_variables) > 0: - if len(varlists) == 0: - varlists = [(plcopen.interface_globalVars(), [])] - varlists[-1][1].extend(extra_variables) + extra_global_vars = None + if len(extra_variables) > 0 and len(varlists) == 0: + extra_global_vars = PLCOpenParser.CreateElement("globalVars", "interface") + configuration.setglobalVars([extra_global_vars]) + varlists = [(extra_global_vars, [])] + + for variable in extra_variables: + varlists[-1][0].appendvariable(variable) + varlists[-1][1].append(variable) # Generate any global variable in configuration for varlist, varlist_variables in varlists: @@ -289,8 +296,8 @@ # Generate any variable of this block for var in varlist_variables: vartype_content = var.gettype().getcontent() - if vartype_content["name"] == "derived": - var_type = vartype_content["value"].getname() + if vartype_content.getLocalTag() == "derived": + var_type = vartype_content.getname() self.GenerateDataType(var_type) else: var_type = var.gettypeAsText() @@ -308,12 +315,19 @@ (var.gettypeAsText(), (tagname, variable_type, var_number, "type"))] # Generate variable initial value if exists initial = var.getinitialValue() - if initial: + if initial is not None: config += [(" := ", ()), (self.ComputeValue(initial.getvalue(), var_type), (tagname, variable_type, var_number, "initial value"))] config += [(";\n", ())] var_number += 1 config += [(" END_VAR\n", ())] + + if extra_global_vars is not None: + configuration.remove(extra_global_vars) + else: + for variable in extra_variables: + varlists[-1][0].remove(variable) + # Generate any resource in the configuration for resource in configuration.getresource(): config += self.GenerateResource(resource, configuration.getname()) @@ -342,8 +356,8 @@ # Generate any variable of this block for var in varlist.getvariable(): vartype_content = var.gettype().getcontent() - if vartype_content["name"] == "derived": - var_type = vartype_content["value"].getname() + if vartype_content.getLocalTag() == "derived": + var_type = vartype_content.getname() self.GenerateDataType(var_type) else: var_type = var.gettypeAsText() @@ -361,7 +375,7 @@ (var.gettypeAsText(), (tagname, variable_type, var_number, "type"))] # Generate variable initial value if exists initial = var.getinitialValue() - if initial: + if initial is not None: resrce += [(" := ", ()), (self.ComputeValue(initial.getvalue(), var_type), (tagname, variable_type, var_number, "initial value"))] resrce += [(";\n", ())] @@ -378,13 +392,13 @@ args = [] single = task.getsingle() # Single argument if exists - if single: + if single is not None: resrce += [("SINGLE := ", ()), (single, (tagname, "task", task_number, "single")), (",", ())] # Interval argument if exists interval = task.getinterval() - if interval: + if interval is not None: resrce += [("INTERVAL := ", ()), (interval, (tagname, "task", task_number, "interval")), (",", ())] @@ -458,6 +472,24 @@ # Generator of POU programs #------------------------------------------------------------------------------- +[ConnectorClass, ContinuationClass, ActionBlockClass] = [ + PLCOpenParser.GetElementClass(instance_name, "commonObjects") + for instance_name in ["connector", "continuation", "actionBlock"]] +[InVariableClass, InOutVariableClass, OutVariableClass, BlockClass] = [ + PLCOpenParser.GetElementClass(instance_name, "fbdObjects") + for instance_name in ["inVariable", "inOutVariable", "outVariable", "block"]] +[ContactClass, CoilClass, LeftPowerRailClass, RightPowerRailClass] = [ + PLCOpenParser.GetElementClass(instance_name, "ldObjects") + for instance_name in ["contact", "coil", "leftPowerRail", "rightPowerRail"]] +[StepClass, TransitionClass, JumpStepClass, + SelectionConvergenceClass, SelectionDivergenceClass, + SimultaneousConvergenceClass, SimultaneousDivergenceClass] = [ + PLCOpenParser.GetElementClass(instance_name, "sfcObjects") + for instance_name in ["step", "transition", "jumpStep", + "selectionConvergence", "selectionDivergence", + "simultaneousConvergence", "simultaneousDivergence"]] +TransitionObjClass = PLCOpenParser.GetElementClass("transition", "transitions") +ActionObjClass = PLCOpenParser.GetElementClass("action", "actions") class PouProgramGenerator: @@ -541,16 +573,17 @@ # Return connectors linked by a connection to the given connector def GetConnectedConnector(self, connector, body): links = connector.getconnections() - if links and len(links) == 1: + if links is not None and len(links) == 1: return self.GetLinkedConnector(links[0], body) return None def GetLinkedConnector(self, link, body): parameter = link.getformalParameter() instance = body.getcontentInstance(link.getrefLocalId()) - if isinstance(instance, (plcopen.fbdObjects_inVariable, plcopen.fbdObjects_inOutVariable, plcopen.commonObjects_continuation, plcopen.ldObjects_contact, plcopen.ldObjects_coil)): + if isinstance(instance, (InVariableClass, InOutVariableClass, + ContinuationClass, ContactClass, CoilClass)): return instance.connectionPointOut - elif isinstance(instance, plcopen.fbdObjects_block): + elif isinstance(instance, BlockClass): outputvariables = instance.outputVariables.getvariable() if len(outputvariables) == 1: return outputvariables[0].connectionPointOut @@ -565,7 +598,7 @@ blockposition = instance.getposition() if point.x == blockposition.x + relposition[0] and point.y == blockposition.y + relposition[1]: return variable.connectionPointOut - elif isinstance(instance, plcopen.ldObjects_leftPowerRail): + elif isinstance(instance, LeftPowerRailClass): outputconnections = instance.getconnectionPointOut() if len(outputconnections) == 1: return outputconnections[0] @@ -591,49 +624,42 @@ if isinstance(body, ListType): body = body[0] body_content = body.getcontent() + body_type = body_content.getLocalTag() if self.Type == "FUNCTION": returntype_content = interface.getreturnType().getcontent() - if returntype_content["name"] == "derived": - self.ReturnType = returntype_content["value"].getname() - elif returntype_content["name"] in ["string", "wstring"]: - self.ReturnType = returntype_content["name"].upper() - else: - self.ReturnType = returntype_content["name"] + returntype_content_type = returntype_content.getLocalTag() + if returntype_content_type == "derived": + self.ReturnType = returntype_content.getname() + else: + self.ReturnType = returntype_content_type.upper() for varlist in interface.getcontent(): variables = [] located = [] - for var in varlist["value"].getvariable(): + varlist_type = varlist.getLocalTag() + for var in varlist.getvariable(): vartype_content = var.gettype().getcontent() - if vartype_content["name"] == "derived": - var_type = vartype_content["value"].getname() + if vartype_content.getLocalTag() == "derived": + var_type = vartype_content.getname() blocktype = self.GetBlockType(var_type) if blocktype is not None: self.ParentGenerator.GeneratePouProgram(var_type) - if body_content["name"] in ["FBD", "LD", "SFC"]: - block = pou.getinstanceByName(var.getname()) - else: - block = None - for variable in blocktype["initialise"](var_type, var.getname(), block): - if variable[2] is not None: - located.append(variable) - else: - variables.append(variable) + variables.append((var_type, var.getname(), None, None)) else: self.ParentGenerator.GenerateDataType(var_type) initial = var.getinitialValue() - if initial: + if initial is not None: initial_value = initial.getvalue() else: initial_value = None address = var.getaddress() if address is not None: - located.append((vartype_content["value"].getname(), var.getname(), address, initial_value)) + located.append((vartype_content.getname(), var.getname(), address, initial_value)) else: - variables.append((vartype_content["value"].getname(), var.getname(), None, initial_value)) + variables.append((vartype_content.getname(), var.getname(), None, initial_value)) else: var_type = var.gettypeAsText() initial = var.getinitialValue() - if initial: + if initial is not None: initial_value = initial.getvalue() else: initial_value = None @@ -642,18 +668,18 @@ located.append((var_type, var.getname(), address, initial_value)) else: variables.append((var_type, var.getname(), None, initial_value)) - if varlist["value"].getconstant(): + if varlist.getconstant(): option = "CONSTANT" - elif varlist["value"].getretain(): + elif varlist.getretain(): option = "RETAIN" - elif varlist["value"].getnonretain(): + elif varlist.getnonretain(): option = "NON_RETAIN" else: option = None if len(variables) > 0: - self.Interface.append((varTypeNames[varlist["name"]], option, False, variables)) + self.Interface.append((varTypeNames[varlist_type], option, False, variables)) if len(located) > 0: - self.Interface.append((varTypeNames[varlist["name"]], option, True, located)) + self.Interface.append((varTypeNames[varlist_type], option, True, located)) LITERAL_TYPES = { "T": "TIME", @@ -669,24 +695,25 @@ if isinstance(body, ListType): body = body[0] body_content = body.getcontent() - body_type = body_content["name"] + body_type = body_content.getLocalTag() if body_type in ["FBD", "LD", "SFC"]: undefined_blocks = [] for instance in body.getcontentInstances(): - if isinstance(instance, (plcopen.fbdObjects_inVariable, plcopen.fbdObjects_outVariable, plcopen.fbdObjects_inOutVariable)): + if isinstance(instance, (InVariableClass, OutVariableClass, + InOutVariableClass)): expression = instance.getexpression() var_type = self.GetVariableType(expression) - if isinstance(pou, plcopen.transitions_transition) and expression == pou.getname(): + if (isinstance(pou, TransitionObjClass) + and expression == pou.getname()): var_type = "BOOL" - elif (not isinstance(pou, (plcopen.transitions_transition, plcopen.actions_action)) and + elif (not isinstance(pou, (TransitionObjClass, ActionObjClass)) and pou.getpouType() == "function" and expression == pou.getname()): returntype_content = pou.interface.getreturnType().getcontent() - if returntype_content["name"] == "derived": - var_type = returntype_content["value"].getname() - elif returntype_content["name"] in ["string", "wstring"]: - var_type = returntype_content["name"].upper() + returntype_content_type = returntype_content.getLocalTag() + if returntype_content_type == "derived": + var_type = returntype_content.getname() else: - var_type = returntype_content["name"] + var_type = returntype_content_type.upper() elif var_type is None: parts = expression.split("#") if len(parts) > 1: @@ -698,54 +725,58 @@ elif expression.startswith('"'): var_type = "WSTRING" if var_type is not None: - if isinstance(instance, (plcopen.fbdObjects_inVariable, plcopen.fbdObjects_inOutVariable)): + if isinstance(instance, (InVariableClass, InOutVariableClass)): for connection in self.ExtractRelatedConnections(instance.connectionPointOut): self.ConnectionTypes[connection] = var_type - if isinstance(instance, (plcopen.fbdObjects_outVariable, plcopen.fbdObjects_inOutVariable)): + if isinstance(instance, (OutVariableClass, InOutVariableClass)): self.ConnectionTypes[instance.connectionPointIn] = var_type connected = self.GetConnectedConnector(instance.connectionPointIn, body) - if connected and not self.ConnectionTypes.has_key(connected): - for connection in self.ExtractRelatedConnections(connected): - self.ConnectionTypes[connection] = var_type - elif isinstance(instance, (plcopen.ldObjects_contact, plcopen.ldObjects_coil)): + if connected is not None and not self.ConnectionTypes.has_key(connected): + for related in self.ExtractRelatedConnections(connected): + self.ConnectionTypes[related] = var_type + elif isinstance(instance, (ContactClass, CoilClass)): for connection in self.ExtractRelatedConnections(instance.connectionPointOut): self.ConnectionTypes[connection] = "BOOL" self.ConnectionTypes[instance.connectionPointIn] = "BOOL" - connected = self.GetConnectedConnector(instance.connectionPointIn, body) - if connected and not self.ConnectionTypes.has_key(connected): - for connection in self.ExtractRelatedConnections(connected): - self.ConnectionTypes[connection] = "BOOL" - elif isinstance(instance, plcopen.ldObjects_leftPowerRail): + for link in instance.connectionPointIn.getconnections(): + connected = self.GetLinkedConnector(link, body) + if connected is not None and not self.ConnectionTypes.has_key(connected): + for related in self.ExtractRelatedConnections(connected): + self.ConnectionTypes[related] = "BOOL" + elif isinstance(instance, LeftPowerRailClass): for connection in instance.getconnectionPointOut(): for related in self.ExtractRelatedConnections(connection): self.ConnectionTypes[related] = "BOOL" - elif isinstance(instance, plcopen.ldObjects_rightPowerRail): + elif isinstance(instance, RightPowerRailClass): for connection in instance.getconnectionPointIn(): self.ConnectionTypes[connection] = "BOOL" - connected = self.GetConnectedConnector(connection, body) - if connected and not self.ConnectionTypes.has_key(connected): - for connection in self.ExtractRelatedConnections(connected): - self.ConnectionTypes[connection] = "BOOL" - elif isinstance(instance, plcopen.sfcObjects_transition): - content = instance.condition.getcontent() - if content["name"] == "connection" and len(content["value"]) == 1: - connected = self.GetLinkedConnector(content["value"][0], body) - if connected and not self.ConnectionTypes.has_key(connected): - for connection in self.ExtractRelatedConnections(connected): - self.ConnectionTypes[connection] = "BOOL" - elif isinstance(instance, plcopen.commonObjects_continuation): + for link in connection.getconnections(): + connected = self.GetLinkedConnector(link, body) + if connected is not None and not self.ConnectionTypes.has_key(connected): + for related in self.ExtractRelatedConnections(connected): + self.ConnectionTypes[related] = "BOOL" + elif isinstance(instance, TransitionClass): + content = instance.getconditionContent() + if content["type"] == "connection": + self.ConnectionTypes[content["value"]] = "BOOL" + for link in content["value"].getconnections(): + connected = self.GetLinkedConnector(link, body) + if connected is not None and not self.ConnectionTypes.has_key(connected): + for related in self.ExtractRelatedConnections(connected): + self.ConnectionTypes[related] = "BOOL" + elif isinstance(instance, ContinuationClass): name = instance.getname() connector = None var_type = "ANY" for element in body.getcontentInstances(): - if isinstance(element, plcopen.commonObjects_connector) and element.getname() == name: + if isinstance(element, ConnectorClass) and element.getname() == name: if connector is not None: raise PLCGenException, _("More than one connector found corresponding to \"%s\" continuation in \"%s\" POU")%(name, self.Name) connector = element if connector is not None: undefined = [instance.connectionPointOut, connector.connectionPointIn] connected = self.GetConnectedConnector(connector.connectionPointIn, body) - if connected: + if connected is not None: undefined.append(connected) related = [] for connection in undefined: @@ -760,7 +791,7 @@ self.ConnectionTypes[connection] = var_type else: raise PLCGenException, _("No connector found corresponding to \"%s\" continuation in \"%s\" POU")%(name, self.Name) - elif isinstance(instance, plcopen.fbdObjects_block): + elif isinstance(instance, BlockClass): block_infos = self.GetBlockType(instance.gettypeName(), "undefined") if block_infos is not None: self.ComputeBlockInputTypes(instance, block_infos, body) @@ -822,11 +853,11 @@ if not undefined.has_key(itype): undefined[itype] = [] undefined[itype].append(variable.connectionPointIn) - if connected: + if connected is not None: undefined[itype].append(connected) else: self.ConnectionTypes[variable.connectionPointIn] = itype - if connected and not self.ConnectionTypes.has_key(connected): + if connected is not None and not self.ConnectionTypes.has_key(connected): for connection in self.ExtractRelatedConnections(connected): self.ConnectionTypes[connection] = itype for var_type, connections in undefined.items(): @@ -848,22 +879,22 @@ if isinstance(body, ListType): body = body[0] body_content = body.getcontent() - body_type = body_content["name"] + body_type = body_content.getLocalTag() if body_type in ["IL","ST"]: - text = body_content["value"].gettext() + text = body_content.getanyText() self.ParentGenerator.GeneratePouProgramInText(text.upper()) self.Program = [(ReIndentText(text, len(self.CurrentIndent)), (self.TagName, "body", len(self.CurrentIndent)))] elif body_type == "SFC": self.IndentRight() for instance in body.getcontentInstances(): - if isinstance(instance, plcopen.sfcObjects_step): + if isinstance(instance, StepClass): self.GenerateSFCStep(instance, pou) - elif isinstance(instance, plcopen.commonObjects_actionBlock): + elif isinstance(instance, ActionBlockClass): self.GenerateSFCStepActions(instance, pou) - elif isinstance(instance, plcopen.sfcObjects_transition): + elif isinstance(instance, TransitionClass): self.GenerateSFCTransition(instance, pou) - elif isinstance(instance, plcopen.sfcObjects_jumpStep): + elif isinstance(instance, JumpStepClass): self.GenerateSFCJump(instance, pou) if len(self.InitialSteps) > 0 and len(self.SFCComputedBlocks) > 0: action_name = "COMPUTE_FUNCTION_BLOCKS" @@ -878,17 +909,17 @@ otherInstances = {"outVariables&coils" : [], "blocks" : [], "connectors" : []} orderedInstances = [] for instance in body.getcontentInstances(): - if isinstance(instance, (plcopen.fbdObjects_outVariable, plcopen.fbdObjects_inOutVariable, plcopen.fbdObjects_block)): + if isinstance(instance, (OutVariableClass, InOutVariableClass, BlockClass)): executionOrderId = instance.getexecutionOrderId() if executionOrderId > 0: orderedInstances.append((executionOrderId, instance)) - elif isinstance(instance, (plcopen.fbdObjects_outVariable, plcopen.fbdObjects_inOutVariable)): + elif isinstance(instance, (OutVariableClass, InOutVariableClass)): otherInstances["outVariables&coils"].append(instance) - elif isinstance(instance, plcopen.fbdObjects_block): + elif isinstance(instance, BlockClass): otherInstances["blocks"].append(instance) - elif isinstance(instance, plcopen.commonObjects_connector): + elif isinstance(instance, ConnectorClass): otherInstances["connectors"].append(instance) - elif isinstance(instance, plcopen.ldObjects_coil): + elif isinstance(instance, CoilClass): otherInstances["outVariables&coils"].append(instance) orderedInstances.sort() otherInstances["outVariables&coils"].sort(SortInstances) @@ -896,7 +927,7 @@ instances = [instance for (executionOrderId, instance) in orderedInstances] instances.extend(otherInstances["outVariables&coils"] + otherInstances["blocks"] + otherInstances["connectors"]) for instance in instances: - if isinstance(instance, (plcopen.fbdObjects_outVariable, plcopen.fbdObjects_inOutVariable)): + if isinstance(instance, (OutVariableClass, InOutVariableClass)): connections = instance.connectionPointIn.getconnections() if connections is not None: expression = self.ComputeExpression(body, connections) @@ -906,7 +937,7 @@ (" := ", ())] self.Program += expression self.Program += [(";\n", ())] - elif isinstance(instance, plcopen.fbdObjects_block): + elif isinstance(instance, BlockClass): block_type = instance.gettypeName() self.ParentGenerator.GeneratePouProgram(block_type) block_infos = self.GetBlockType(block_type, tuple([self.ConnectionTypes.get(variable.connectionPointIn, "ANY") for variable in instance.inputVariables.getvariable() if variable.getformalParameter() != "EN"])) @@ -915,17 +946,17 @@ if block_infos is None: raise PLCGenException, _("Undefined block type \"%s\" in \"%s\" POU")%(block_type, self.Name) try: - block_infos["generate"](self, instance, block_infos, body, None) + self.GenerateBlock(instance, block_infos, body, None) except ValueError, e: raise PLCGenException, e.message - elif isinstance(instance, plcopen.commonObjects_connector): + elif isinstance(instance, ConnectorClass): connector = instance.getname() if self.ComputedConnectors.get(connector, None): continue expression = self.ComputeExpression(body, instance.connectionPointIn.getconnections()) if expression is not None: self.ComputedConnectors[connector] = expression - elif isinstance(instance, plcopen.ldObjects_coil): + elif isinstance(instance, CoilClass): connections = instance.connectionPointIn.getconnections() if connections is not None: coil_info = (self.TagName, "coil", instance.getlocalId()) @@ -963,16 +994,201 @@ factorized_paths.sort() return factorized_paths + def GenerateBlock(self, block, block_infos, body, link, order=False, to_inout=False): + body_type = body.getcontent().getLocalTag() + name = block.getinstanceName() + type = block.gettypeName() + executionOrderId = block.getexecutionOrderId() + input_variables = block.inputVariables.getvariable() + output_variables = block.outputVariables.getvariable() + inout_variables = {} + for input_variable in input_variables: + for output_variable in output_variables: + if input_variable.getformalParameter() == output_variable.getformalParameter(): + inout_variables[input_variable.getformalParameter()] = "" + input_names = [input[0] for input in block_infos["inputs"]] + output_names = [output[0] for output in block_infos["outputs"]] + if block_infos["type"] == "function": + if not self.ComputedBlocks.get(block, False) and not order: + self.ComputedBlocks[block] = True + connected_vars = [] + if not block_infos["extensible"]: + input_connected = dict([("EN", None)] + + [(input_name, None) for input_name in input_names]) + for variable in input_variables: + parameter = variable.getformalParameter() + if input_connected.has_key(parameter): + input_connected[parameter] = variable + if input_connected["EN"] is None: + input_connected.pop("EN") + input_parameters = input_names + else: + input_parameters = ["EN"] + input_names + else: + input_connected = dict([(variable.getformalParameter(), variable) + for variable in input_variables]) + input_parameters = [variable.getformalParameter() + for variable in input_variables] + one_input_connected = False + all_input_connected = True + for i, parameter in enumerate(input_parameters): + variable = input_connected.get(parameter) + if variable is not None: + input_info = (self.TagName, "block", block.getlocalId(), "input", i) + connections = variable.connectionPointIn.getconnections() + if connections is not None: + if parameter != "EN": + one_input_connected = True + if inout_variables.has_key(parameter): + expression = self.ComputeExpression(body, connections, executionOrderId > 0, True) + if expression is not None: + inout_variables[parameter] = value + else: + expression = self.ComputeExpression(body, connections, executionOrderId > 0) + if expression is not None: + connected_vars.append(([(parameter, input_info), (" := ", ())], + self.ExtractModifier(variable, expression, input_info))) + else: + all_input_connected = False + else: + all_input_connected = False + if len(output_variables) > 1 or not all_input_connected: + vars = [name + value for name, value in connected_vars] + else: + vars = [value for name, value in connected_vars] + if one_input_connected: + for i, variable in enumerate(output_variables): + parameter = variable.getformalParameter() + if not inout_variables.has_key(parameter) and parameter in output_names + ["", "ENO"]: + if variable.getformalParameter() == "": + variable_name = "%s%d"%(type, block.getlocalId()) + else: + variable_name = "%s%d_%s"%(type, block.getlocalId(), parameter) + if self.Interface[-1][0] != "VAR" or self.Interface[-1][1] is not None or self.Interface[-1][2]: + self.Interface.append(("VAR", None, False, [])) + if variable.connectionPointOut in self.ConnectionTypes: + self.Interface[-1][3].append((self.ConnectionTypes[variable.connectionPointOut], variable_name, None, None)) + else: + self.Interface[-1][3].append(("ANY", variable_name, None, None)) + if len(output_variables) > 1 and parameter not in ["", "OUT"]: + vars.append([(parameter, (self.TagName, "block", block.getlocalId(), "output", i)), + (" => %s"%variable_name, ())]) + else: + output_info = (self.TagName, "block", block.getlocalId(), "output", i) + output_name = variable_name + self.Program += [(self.CurrentIndent, ()), + (output_name, output_info), + (" := ", ()), + (type, (self.TagName, "block", block.getlocalId(), "type")), + ("(", ())] + self.Program += JoinList([(", ", ())], vars) + self.Program += [(");\n", ())] + else: + self.Warnings.append(_("\"%s\" function cancelled in \"%s\" POU: No input connected")%(type, self.TagName.split("::")[-1])) + elif block_infos["type"] == "functionBlock": + if not self.ComputedBlocks.get(block, False) and not order: + self.ComputedBlocks[block] = True + vars = [] + offset_idx = 0 + for variable in input_variables: + parameter = variable.getformalParameter() + if parameter in input_names or parameter == "EN": + if parameter == "EN": + input_idx = 0 + offset_idx = 1 + else: + input_idx = offset_idx + input_names.index(parameter) + input_info = (self.TagName, "block", block.getlocalId(), "input", input_idx) + connections = variable.connectionPointIn.getconnections() + if connections is not None: + expression = self.ComputeExpression(body, connections, executionOrderId > 0, inout_variables.has_key(parameter)) + if expression is not None: + vars.append([(parameter, input_info), + (" := ", ())] + self.ExtractModifier(variable, expression, input_info)) + self.Program += [(self.CurrentIndent, ()), + (name, (self.TagName, "block", block.getlocalId(), "name")), + ("(", ())] + self.Program += JoinList([(", ", ())], vars) + self.Program += [(");\n", ())] + + if link is not None: + connectionPoint = link.getposition()[-1] + output_parameter = link.getformalParameter() + else: + connectionPoint = None + output_parameter = None + + output_variable = None + output_idx = 0 + if output_parameter is not None: + if output_parameter in output_names or output_parameter == "ENO": + for variable in output_variables: + if variable.getformalParameter() == output_parameter: + output_variable = variable + if output_parameter != "ENO": + output_idx = output_names.index(output_parameter) + else: + for i, variable in enumerate(output_variables): + blockPointx, blockPointy = variable.connectionPointOut.getrelPositionXY() + if (connectionPoint is None or + block.getx() + blockPointx == connectionPoint.getx() and + block.gety() + blockPointy == connectionPoint.gety()): + output_variable = variable + output_parameter = variable.getformalParameter() + output_idx = i + + if output_variable is not None: + if block_infos["type"] == "function": + output_info = (self.TagName, "block", block.getlocalId(), "output", output_idx) + if inout_variables.has_key(output_parameter): + output_value = inout_variables[output_parameter] + else: + if output_parameter == "": + output_name = "%s%d"%(type, block.getlocalId()) + else: + output_name = "%s%d_%s"%(type, block.getlocalId(), output_parameter) + output_value = [(output_name, output_info)] + return self.ExtractModifier(output_variable, output_value, output_info) + + if block_infos["type"] == "functionBlock": + output_info = (self.TagName, "block", block.getlocalId(), "output", output_idx) + output_name = self.ExtractModifier(output_variable, [("%s.%s"%(name, output_parameter), output_info)], output_info) + if to_inout: + variable_name = "%s_%s"%(name, output_parameter) + if not self.IsAlreadyDefined(variable_name): + if self.Interface[-1][0] != "VAR" or self.Interface[-1][1] is not None or self.Interface[-1][2]: + self.Interface.append(("VAR", None, False, [])) + if variable.connectionPointOut in self.ConnectionTypes: + self.Interface[-1][3].append( + (self.ConnectionTypes[output_variable.connectionPointOut], variable_name, None, None)) + else: + self.Interface[-1][3].append(("ANY", variable_name, None, None)) + self.Program += [(self.CurrentIndent, ()), + ("%s := "%variable_name, ())] + self.Program += output_name + self.Program += [(";\n", ())] + return [(variable_name, ())] + return output_name + if link is not None: + if output_parameter is None: + output_parameter = "" + if name: + blockname = "%s(%s)" % (name, type) + else: + blockname = type + raise ValueError, _("No output %s variable found in block %s in POU %s. Connection must be broken") % \ + (output_parameter, blockname, self.Name) + def GeneratePaths(self, connections, body, order = False, to_inout = False): paths = [] for connection in connections: localId = connection.getrefLocalId() next = body.getcontentInstance(localId) - if isinstance(next, plcopen.ldObjects_leftPowerRail): + if isinstance(next, LeftPowerRailClass): paths.append(None) - elif isinstance(next, (plcopen.fbdObjects_inVariable, plcopen.fbdObjects_inOutVariable)): + elif isinstance(next, (InVariableClass, InOutVariableClass)): paths.append(str([(next.getexpression(), (self.TagName, "io_variable", localId, "expression"))])) - elif isinstance(next, plcopen.fbdObjects_block): + elif isinstance(next, BlockClass): block_type = next.gettypeName() self.ParentGenerator.GeneratePouProgram(block_type) block_infos = self.GetBlockType(block_type, tuple([self.ConnectionTypes.get(variable.connectionPointIn, "ANY") for variable in next.inputVariables.getvariable() if variable.getformalParameter() != "EN"])) @@ -981,10 +1197,10 @@ if block_infos is None: raise PLCGenException, _("Undefined block type \"%s\" in \"%s\" POU")%(block_type, self.Name) try: - paths.append(str(block_infos["generate"](self, next, block_infos, body, connection, order, to_inout))) + paths.append(str(self.GenerateBlock(next, block_infos, body, connection, order, to_inout))) except ValueError, e: raise PLCGenException, e.message - elif isinstance(next, plcopen.commonObjects_continuation): + elif isinstance(next, ContinuationClass): name = next.getname() computed_value = self.ComputedConnectors.get(name, None) if computed_value != None: @@ -992,7 +1208,7 @@ else: connector = None for instance in body.getcontentInstances(): - if isinstance(instance, plcopen.commonObjects_connector) and instance.getname() == name: + if isinstance(instance, ConnectorClass) and instance.getname() == name: if connector is not None: raise PLCGenException, _("More than one connector found corresponding to \"%s\" continuation in \"%s\" POU")%(name, self.Name) connector = instance @@ -1005,7 +1221,7 @@ paths.append(str(expression)) else: raise PLCGenException, _("No connector found corresponding to \"%s\" continuation in \"%s\" POU")%(name, self.Name) - elif isinstance(next, plcopen.ldObjects_contact): + elif isinstance(next, ContactClass): contact_info = (self.TagName, "contact", next.getlocalId()) variable = str(self.ExtractModifier(next, [(next.getvariable(), contact_info + ("reference",))], contact_info)) result = self.GeneratePaths(next.connectionPointIn.getconnections(), body, order) @@ -1021,7 +1237,7 @@ paths.append([variable, result[0]]) else: paths.append(variable) - elif isinstance(next, plcopen.ldObjects_coil): + elif isinstance(next, CoilClass): paths.append(str(self.GeneratePaths(next.connectionPointIn.getconnections(), body, order))) return paths @@ -1092,7 +1308,7 @@ def ExtractDivergenceInput(self, divergence, pou): connectionPointIn = divergence.getconnectionPointIn() - if connectionPointIn: + if connectionPointIn is not None: connections = connectionPointIn.getconnections() if connections is not None and len(connections) == 1: instanceLocalId = connections[0].getrefLocalId() @@ -1124,7 +1340,7 @@ "transitions" : [], "actions" : []} self.SFCNetworks["Steps"][step_name] = step_infos - if step.connectionPointIn: + if step.connectionPointIn is not None: instances = [] connections = step.connectionPointIn.getconnections() if connections is not None and len(connections) == 1: @@ -1133,16 +1349,16 @@ if isinstance(body, ListType): body = body[0] instance = body.getcontentInstance(instanceLocalId) - if isinstance(instance, plcopen.sfcObjects_transition): + if isinstance(instance, TransitionClass): instances.append(instance) - elif isinstance(instance, plcopen.sfcObjects_selectionConvergence): + elif isinstance(instance, SelectionConvergenceClass): instances.extend(self.ExtractConvergenceInputs(instance, pou)) - elif isinstance(instance, plcopen.sfcObjects_simultaneousDivergence): + elif isinstance(instance, SimultaneousDivergenceClass): transition = self.ExtractDivergenceInput(instance, pou) - if transition: - if isinstance(transition, plcopen.sfcObjects_transition): + if transition is not None: + if isinstance(transition, TransitionClass): instances.append(transition) - elif isinstance(transition, plcopen.sfcObjects_selectionConvergence): + elif isinstance(transition, SelectionConvergenceClass): instances.extend(self.ExtractConvergenceInputs(transition, pou)) for instance in instances: self.GenerateSFCTransition(instance, pou) @@ -1152,7 +1368,7 @@ def GenerateSFCJump(self, jump, pou): jump_target = jump.gettargetName() - if jump.connectionPointIn: + if jump.connectionPointIn is not None: instances = [] connections = jump.connectionPointIn.getconnections() if connections is not None and len(connections) == 1: @@ -1161,16 +1377,16 @@ if isinstance(body, ListType): body = body[0] instance = body.getcontentInstance(instanceLocalId) - if isinstance(instance, plcopen.sfcObjects_transition): + if isinstance(instance, TransitionClass): instances.append(instance) - elif isinstance(instance, plcopen.sfcObjects_selectionConvergence): + elif isinstance(instance, SelectionConvergenceClass): instances.extend(self.ExtractConvergenceInputs(instance, pou)) - elif isinstance(instance, plcopen.sfcObjects_simultaneousDivergence): + elif isinstance(instance, SimultaneousDivergenceClass): transition = self.ExtractDivergenceInput(instance, pou) - if transition: - if isinstance(transition, plcopen.sfcObjects_transition): + if transition is not None: + if isinstance(transition, TransitionClass): instances.append(transition) - elif isinstance(transition, plcopen.sfcObjects_selectionConvergence): + elif isinstance(transition, SelectionConvergenceClass): instances.extend(self.ExtractConvergenceInputs(transition, pou)) for instance in instances: self.GenerateSFCTransition(instance, pou) @@ -1212,7 +1428,7 @@ def GenerateSFCAction(self, action_name, pou): if action_name not in self.SFCNetworks["Actions"].keys(): actionContent = pou.getaction(action_name) - if actionContent: + if actionContent is not None: previous_tagname = self.TagName self.TagName = self.ParentGenerator.Controler.ComputePouActionName(self.Name, action_name) self.ComputeProgram(actionContent) @@ -1230,21 +1446,22 @@ if isinstance(body, ListType): body = body[0] instance = body.getcontentInstance(instanceLocalId) - if isinstance(instance, plcopen.sfcObjects_step): + if isinstance(instance, StepClass): steps.append(instance) - elif isinstance(instance, plcopen.sfcObjects_selectionDivergence): + elif isinstance(instance, SelectionDivergenceClass): step = self.ExtractDivergenceInput(instance, pou) - if step: - if isinstance(step, plcopen.sfcObjects_step): + if step is not None: + if isinstance(step, StepClass): steps.append(step) - elif isinstance(step, plcopen.sfcObjects_simultaneousConvergence): + elif isinstance(step, SimultaneousConvergenceClass): steps.extend(self.ExtractConvergenceInputs(step, pou)) - elif isinstance(instance, plcopen.sfcObjects_simultaneousConvergence): + elif isinstance(instance, SimultaneousConvergenceClass): steps.extend(self.ExtractConvergenceInputs(instance, pou)) transition_infos = {"id" : transition.getlocalId(), "priority": transition.getpriority(), "from": [], - "to" : []} + "to" : [], + "content": []} self.SFCNetworks["Transitions"][transition] = transition_infos transitionValues = transition.getconditionContent() if transitionValues["type"] == "inline": @@ -1259,14 +1476,14 @@ self.TagName = self.ParentGenerator.Controler.ComputePouTransitionName(self.Name, transitionValues["value"]) if transitionType == "IL": transition_infos["content"] = [(":\n", ()), - (ReIndentText(transitionBody.gettext(), len(self.CurrentIndent)), (self.TagName, "body", len(self.CurrentIndent)))] + (ReIndentText(transitionBody.getanyText(), len(self.CurrentIndent)), (self.TagName, "body", len(self.CurrentIndent)))] elif transitionType == "ST": transition_infos["content"] = [("\n", ()), - (ReIndentText(transitionBody.gettext(), len(self.CurrentIndent)), (self.TagName, "body", len(self.CurrentIndent)))] + (ReIndentText(transitionBody.getanyText(), len(self.CurrentIndent)), (self.TagName, "body", len(self.CurrentIndent)))] else: for instance in transitionBody.getcontentInstances(): - if isinstance(instance, plcopen.fbdObjects_outVariable) and instance.getexpression() == transitionValues["value"]\ - or isinstance(instance, plcopen.ldObjects_coil) and instance.getvariable() == transitionValues["value"]: + if isinstance(instance, OutVariableClass) and instance.getexpression() == transitionValues["value"]\ + or isinstance(instance, CoilClass) and instance.getvariable() == transitionValues["value"]: connections = instance.connectionPointIn.getconnections() if connections is not None: expression = self.ComputeExpression(transitionBody, connections) @@ -1281,7 +1498,7 @@ body = pou.getbody() if isinstance(body, ListType): body = body[0] - connections = transition.getconnections() + connections = transitionValues["value"].getconnections() if connections is not None: expression = self.ComputeExpression(body, connections) if expression is not None: @@ -1335,7 +1552,7 @@ action_content, action_info = self.SFCNetworks["Actions"].pop(action_name) self.Program += [("%sACTION "%self.CurrentIndent, ()), (action_name, action_info), - (" :\n", ())] + (":\n", ())] self.Program += action_content self.Program += [("%sEND_ACTION\n\n"%self.CurrentIndent, ())] @@ -1377,7 +1594,7 @@ program = [("%s "%self.Type, ()), (self.Name, (self.TagName, "name"))] - if self.ReturnType: + if self.ReturnType is not None: program += [(" : ", ()), (self.ReturnType, (self.TagName, "return"))] program += [("\n", ())] diff -r 72a826dfcfbb -r 02fe382c4511 PLCOpenEditor.py --- a/PLCOpenEditor.py Wed Jul 31 10:45:07 2013 +0900 +++ b/PLCOpenEditor.py Mon Nov 18 12:12:31 2013 +0900 @@ -182,12 +182,11 @@ # Create a new controller controler = PLCControler() result = controler.OpenXMLFile(fileOpen) - if result is None: - self.Controler = controler - self.LibraryPanel.SetController(controler) - self.ProjectTree.Enable(True) - self.PouInstanceVariablesPanel.SetController(controler) - self._Refresh(PROJECTTREE, POUINSTANCEVARIABLESPANEL, LIBRARYTREE) + self.Controler = controler + self.LibraryPanel.SetController(controler) + self.ProjectTree.Enable(True) + self.PouInstanceVariablesPanel.SetController(controler) + self._Refresh(PROJECTTREE, POUINSTANCEVARIABLESPANEL, LIBRARYTREE) # Define PLCOpenEditor icon self.SetIcon(wx.Icon(os.path.join(CWD, "images", "poe.ico"),wx.BITMAP_TYPE_ICO)) @@ -197,7 +196,8 @@ self._Refresh(TITLE, EDITORTOOLBAR, FILEMENU, EDITMENU, DISPLAYMENU) if result is not None: - self.ShowErrorMessage(result) + self.ShowErrorMessage( + _("PLC syntax error at line %d:\n%s") % result) def OnCloseFrame(self, event): if self.Controler is None or self.CheckSaveBeforeClosing(_("Close Application")): @@ -276,6 +276,7 @@ self.Controler = PLCControler() self.Controler.CreateNewProject(properties) self.LibraryPanel.SetController(self.Controler) + self.ProjectTree.Enable(True) self._Refresh(TITLE, FILEMENU, EDITMENU, PROJECTTREE, POUINSTANCEVARIABLESPANEL, LIBRARYTREE) @@ -299,17 +300,17 @@ self.ResetView() controler = PLCControler() result = controler.OpenXMLFile(filepath) - if result is None: - self.Controler = controler - self.LibraryPanel.SetController(controler) - self.ProjectTree.Enable(True) - self.PouInstanceVariablesPanel.SetController(controler) - self._Refresh(PROJECTTREE, LIBRARYTREE) + self.Controler = controler + self.LibraryPanel.SetController(controler) + self.ProjectTree.Enable(True) + self.PouInstanceVariablesPanel.SetController(controler) + self._Refresh(PROJECTTREE, LIBRARYTREE) self._Refresh(TITLE, EDITORTOOLBAR, FILEMENU, EDITMENU) dialog.Destroy() if result is not None: - self.ShowErrorMessage(result) + self.ShowErrorMessage( + _("PLC syntax error at line %d:\n%s") % result) def OnCloseProjectMenu(self, event): if not self.CheckSaveBeforeClosing(): @@ -331,9 +332,9 @@ header, icon = _("Done"), wx.ICON_INFORMATION if os.path.isdir(os.path.dirname(filepath)): program, errors, warnings = self.Controler.GenerateProgram(filepath) - message_text += "".join([_("warning: %s\n") for warning in warnings]) + message_text += "".join([_("warning: %s\n") % warning for warning in warnings]) if len(errors) > 0: - message_text += "".join([_("error: %s\n") for error in errors]) + message_text += "".join([_("error: %s\n") % error for error in errors]) message_text += _("Can't generate program to file %s!")%filepath header, icon = _("Error"), wx.ICON_ERROR else: diff -r 72a826dfcfbb -r 02fe382c4511 ProjectController.py --- a/ProjectController.py Wed Jul 31 10:45:07 2013 +0900 +++ b/ProjectController.py Mon Nov 18 12:12:31 2013 +0900 @@ -7,6 +7,8 @@ import shutil import wx import re, tempfile +from math import ceil +from types import ListType from threading import Timer, Lock, Thread from time import localtime from datetime import datetime @@ -21,12 +23,12 @@ from editors.FileManagementPanel import FileManagementPanel from editors.ProjectNodeEditor import ProjectNodeEditor from editors.IECCodeViewer import IECCodeViewer -from editors.DebugViewer import DebugViewer +from editors.DebugViewer import DebugViewer, REFRESH_PERIOD from dialogs import DiscoveryDialog from PLCControler import PLCControler from plcopen.structures import IEC_KEYWORDS from targets.typemapping import DebugTypesSize, LogLevelsCount, LogLevels -from ConfigTreeNode import ConfigTreeNode +from ConfigTreeNode import ConfigTreeNode, XSDSchemaErrorMessage base_folder = os.path.split(sys.path[0])[0] @@ -37,6 +39,28 @@ ITEM_CONFNODE = 25 +def ExtractChildrenTypesFromCatalog(catalog): + children_types = [] + for n,d,h,c in catalog: + if isinstance(c, ListType): + children_types.extend(ExtractChildrenTypesFromCatalog(c)) + else: + children_types.append((n, GetClassImporter(c), d)) + return children_types + +def ExtractMenuItemsFromCatalog(catalog): + menu_items = [] + for n,d,h,c in catalog: + if isinstance(c, ListType): + children = ExtractMenuItemsFromCatalog(c) + else: + children = [] + menu_items.append((n, d, h, children)) + return menu_items + +def GetAddMenuItems(): + return ExtractMenuItemsFromCatalog(features.catalog) + class ProjectController(ConfigTreeNode, PLCControler): """ This class define Root object of the confnode tree. @@ -50,7 +74,7 @@ """ # For root object, available Children Types are modules of the confnode packages. - CTNChildrenTypes = [(n, GetClassImporter(c), d) for n,d,h,c in features.catalog] + CTNChildrenTypes = ExtractChildrenTypesFromCatalog(features.catalog) XSD = """ @@ -87,6 +111,9 @@ self.MandatoryParams = None self._builder = None self._connector = None + self.DispatchDebugValuesTimer = None + self.DebugValuesBuffers = [] + self.DebugTicks = [] self.SetAppFrame(frame, logger) self.iec2c_path = os.path.join(base_folder, "matiec", "iec2c"+(".exe" if wx.Platform == '__WXMSW__' else "")) @@ -116,6 +143,11 @@ # copy ConfNodeMethods so that it can be later customized self.StatusMethods = [dic.copy() for dic in self.StatusMethods] + def __del__(self): + if self.DebugTimer: + self.DebugTimer.cancel() + self.KillDebugThread() + def LoadLibraries(self): self.Libraries = [] TypeStack=[] @@ -124,25 +156,28 @@ Lib = GetClassImporter(clsname)()(self, libname, TypeStack) TypeStack.append(Lib.GetTypes()) self.Libraries.append(Lib) - - def __del__(self): - if self.DebugTimer: - self.DebugTimer.cancel() - self.KillDebugThread() def SetAppFrame(self, frame, logger): self.AppFrame = frame self.logger = logger self.StatusTimer = None + if self.DispatchDebugValuesTimer is not None: + self.DispatchDebugValuesTimer.Stop() + self.DispatchDebugValuesTimer = None if frame is not None: frame.LogViewer.SetLogSource(self._connector) # Timer to pull PLC status - ID_STATUSTIMER = wx.NewId() - self.StatusTimer = wx.Timer(self.AppFrame, ID_STATUSTIMER) - self.AppFrame.Bind(wx.EVT_TIMER, self.PullPLCStatusProc, self.StatusTimer) - + self.StatusTimer = wx.Timer(self.AppFrame, -1) + self.AppFrame.Bind(wx.EVT_TIMER, + self.PullPLCStatusProc, self.StatusTimer) + + # Timer to dispatch debug values to consumers + self.DispatchDebugValuesTimer = wx.Timer(self.AppFrame, -1) + self.AppFrame.Bind(wx.EVT_TIMER, + self.DispatchDebugValuesProc, self.DispatchDebugValuesTimer) + self.RefreshConfNodesBlockLists() def ResetAppFrame(self, logger): @@ -198,9 +233,11 @@ def GetTarget(self): target = self.BeremizRoot.getTargetType() if target.getcontent() is None: - target = self.Classes["BeremizRoot_TargetType"]() + temp_root = self.Parser.CreateRoot() + target = self.Parser.CreateElement("TargetType", "BeremizRoot") + temp_root.setTargetType(target) target_name = self.GetDefaultTargetName() - target.setcontent({"name": target_name, "value": self.Classes["TargetType_%s"%target_name]()}) + target.setcontent(self.Parser.CreateElement(target_name, "TargetType")) return target def GetParamsAttributes(self, path = None): @@ -293,9 +330,13 @@ if not os.path.isfile(plc_file): return _("Chosen folder doesn't contain a program. It's not a valid project!") # Load PLCOpen file - result = self.OpenXMLFile(plc_file) - if result: - return result + error = self.OpenXMLFile(plc_file) + if error is not None: + if self.Project is not None: + self.logger.write_warning( + XSDSchemaErrorMessage % (("PLC",) + error)) + else: + return error if len(self.GetProjectConfigNames()) == 0: self.AddProjectDefaultConfiguration() # Change XSD into class members @@ -636,7 +677,7 @@ Return a Builder (compile C code into machine code) """ # Get target, module and class name - targetname = self.GetTarget().getcontent()["name"] + targetname = self.GetTarget().getcontent().getLocalTag() targetclass = targets.GetBuilder(targetname) # if target already @@ -838,7 +879,7 @@ "init_calls":"\n", "cleanup_calls":"\n" } - plc_main_code += targets.GetTargetCode(self.GetTarget().getcontent()["name"]) + plc_main_code += targets.GetTargetCode(self.GetTarget().getcontent().getLocalTag()) plc_main_code += targets.GetCode("plc_main_tail") return plc_main_code @@ -1148,6 +1189,12 @@ def PullPLCStatusProc(self, event): self.UpdateMethodsFromPLCStatus() + def SnapshotAndResetDebugValuesBuffers(self): + buffers, self.DebugValuesBuffers = (self.DebugValuesBuffers, + [list() for iec_path in self.TracedIECPath]) + ticks, self.DebugTicks = self.DebugTicks, [] + return ticks, buffers + def RegisterDebugVarToConnector(self): self.DebugTimer=None Idxs = [] @@ -1156,7 +1203,7 @@ self.IECdebug_lock.acquire() IECPathsToPop = [] for IECPath,data_tuple in self.IECdebug_datas.iteritems(): - WeakCallableDict, data_log, status, fvalue = data_tuple + WeakCallableDict, data_log, status, fvalue, buffer_list = data_tuple if len(WeakCallableDict) == 0: # Callable Dict is empty. # This variable is not needed anymore! @@ -1181,11 +1228,12 @@ else: self.TracedIECPath = [] self._connector.SetTraceVariablesList([]) + self.SnapshotAndResetDebugValuesBuffers() self.IECdebug_lock.release() def IsPLCStarted(self): return self.previous_plcstate == "Started" - + def ReArmDebugRegisterTimer(self): if self.DebugTimer is not None: self.DebugTimer.cancel() @@ -1204,7 +1252,7 @@ Idx, IEC_Type = self._IECPathToIdx.get(IECPath,(None,None)) return IEC_Type - def SubscribeDebugIECVariable(self, IECPath, callableobj, *args, **kwargs): + def SubscribeDebugIECVariable(self, IECPath, callableobj, buffer_list=False, *args, **kwargs): """ Dispatching use a dictionnary linking IEC variable paths to a WeakKeyDictionary linking @@ -1221,10 +1269,13 @@ WeakKeyDictionary(), # Callables [], # Data storage [(tick, data),...] "Registered", # Variable status - None] # Forced value + None, + buffer_list] # Forced value self.IECdebug_datas[IECPath] = IECdebug_data - - IECdebug_data[0][callableobj]=(args, kwargs) + else: + IECdebug_data[4] |= buffer_list + + IECdebug_data[0][callableobj]=(buffer_list, args, kwargs) self.IECdebug_lock.release() @@ -1239,6 +1290,12 @@ IECdebug_data[0].pop(callableobj,None) if len(IECdebug_data[0]) == 0: self.IECdebug_datas.pop(IECPath) + else: + IECdebug_data[4] = reduce( + lambda x, y: x|y, + [buffer_list for buffer_list,args,kwargs + in IECdebug_data[0].itervalues()], + False) self.IECdebug_lock.release() self.ReArmDebugRegisterTimer() @@ -1283,16 +1340,15 @@ def CallWeakcallables(self, IECPath, function_name, *cargs): data_tuple = self.IECdebug_datas.get(IECPath, None) if data_tuple is not None: - WeakCallableDict, data_log, status, fvalue = data_tuple + WeakCallableDict, data_log, status, fvalue, buffer_list = data_tuple #data_log.append((debug_tick, value)) - for weakcallable,(args,kwargs) in WeakCallableDict.iteritems(): + for weakcallable,(buffer_list,args,kwargs) in WeakCallableDict.iteritems(): function = getattr(weakcallable, function_name, None) if function is not None: - if status == "Forced" and cargs[1] == fvalue: - function(*(cargs + (True,) + args), **kwargs) + if buffer_list: + function(*(cargs + args), **kwargs) else: - function(*(cargs + args), **kwargs) - # This will block thread if more than one call is waiting + function(*(tuple([lst[-1] for lst in cargs]) + args), **kwargs) def GetTicktime(self): return self._Ticktime @@ -1318,14 +1374,20 @@ #print [dict.keys() for IECPath, (dict, log, status, fvalue) in self.IECdebug_datas.items()] if plc_status == "Started": self.IECdebug_lock.acquire() - if len(debug_vars) == len(self.TracedIECPath): + if (len(debug_vars) == len(self.DebugValuesBuffers) and + len(debug_vars) == len(self.TracedIECPath)): if debug_getvar_retry > DEBUG_RETRIES_WARN: self.logger.write(_("... debugger recovered\n")) debug_getvar_retry = 0 - for IECPath,value in zip(self.TracedIECPath, debug_vars): - if value is not None: - self.CallWeakcallables(IECPath, "NewValue", debug_tick, value) - self.CallWeakcallables("__tick__", "NewDataAvailable", debug_tick) + for IECPath, values_buffer, value in zip(self.TracedIECPath, self.DebugValuesBuffers, debug_vars): + IECdebug_data = self.IECdebug_datas.get(IECPath, None) + if IECdebug_data is not None and value is not None: + forced = IECdebug_data[2:4] == ["Forced", value] + if not IECdebug_data[4] and len(values_buffer) > 0: + values_buffer[-1] = (value, forced) + else: + values_buffer.append((value, forced)) + self.DebugTicks.append(debug_tick) self.IECdebug_lock.release() if debug_getvar_retry == DEBUG_RETRIES_WARN: self.logger.write(_("Waiting debugger to recover...\n")) @@ -1339,6 +1401,27 @@ self.debug_break = True self.logger.write(_("Debugger disabled\n")) self.DebugThread = None + if self.DispatchDebugValuesTimer is not None: + self.DispatchDebugValuesTimer.Stop() + + def DispatchDebugValuesProc(self, event): + self.IECdebug_lock.acquire() + debug_ticks, buffers = self.SnapshotAndResetDebugValuesBuffers() + self.IECdebug_lock.release() + start_time = time.time() + if len(self.TracedIECPath) == len(buffers): + for IECPath, values in zip(self.TracedIECPath, buffers): + if len(values) > 0: + self.CallWeakcallables(IECPath, "NewValues", debug_ticks, values) + if len(debug_ticks) > 0: + self.CallWeakcallables("__tick__", "NewDataAvailable", debug_ticks) + + delay = time.time() - start_time + next_refresh = max(REFRESH_PERIOD - delay, 0.2 * delay) + if self.DispatchDebugValuesTimer is not None and self.DebugThread is not None: + self.DispatchDebugValuesTimer.Start( + int(next_refresh * 1000), oneShot=True) + event.Skip() def KillDebugThread(self): tmp_debugthread = self.DebugThread @@ -1351,12 +1434,17 @@ else: self.logger.write(_("Debugger stopped.\n")) self.DebugThread = None + if self.DispatchDebugValuesTimer is not None: + self.DispatchDebugValuesTimer.Stop() def _connect_debug(self): self.previous_plcstate = None if self.AppFrame: self.AppFrame.ResetGraphicViewers() self.RegisterDebugVarToConnector() + if self.DispatchDebugValuesTimer is not None: + self.DispatchDebugValuesTimer.Start( + int(REFRESH_PERIOD * 1000), oneShot=True) if self.DebugThread is None: self.DebugThread = Thread(target=self.DebugThreadProc) self.DebugThread.start() diff -r 72a826dfcfbb -r 02fe382c4511 c_ext/c_ext.py --- a/c_ext/c_ext.py Wed Jul 31 10:45:07 2013 +0900 +++ b/c_ext/c_ext.py Mon Nov 18 12:12:31 2013 +0900 @@ -25,9 +25,6 @@ "publishFunction"] EditorType = CFileEditor - def GenerateClassesFromXSDstring(self, xsd_string): - return GenerateClassesFromXSDstring(xsd_string) - def GetIconName(self): return "Cfile" @@ -56,7 +53,7 @@ # Adding includes text += "/* User includes */\n" - text += self.CodeFile.includes.gettext().strip() + text += self.CodeFile.includes.getanyText().strip() text += "\n" text += '#include "iec_types_all.h"\n\n' @@ -76,25 +73,25 @@ # Adding user global variables and routines text += "/* User internal user variables and routines */\n" - text += self.CodeFile.globals.gettext().strip() + text += self.CodeFile.globals.getanyText().strip() text += "\n" # Adding Beremiz confnode functions text += "/* Beremiz confnode functions */\n" text += "int __init_%s(int argc,char **argv)\n{\n"%location_str - text += self.CodeFile.initFunction.gettext().strip() + text += self.CodeFile.initFunction.getanyText().strip() text += " return 0;\n}\n\n" text += "void __cleanup_%s(void)\n{\n"%location_str - text += self.CodeFile.cleanUpFunction.gettext().strip() + text += self.CodeFile.cleanUpFunction.getanyText().strip() text += "\n}\n\n" text += "void __retrieve_%s(void)\n{\n"%location_str - text += self.CodeFile.retrieveFunction.gettext().strip() + text += self.CodeFile.retrieveFunction.getanyText().strip() text += "\n}\n\n" text += "void __publish_%s(void)\n{\n"%location_str - text += self.CodeFile.publishFunction.gettext().strip() + text += self.CodeFile.publishFunction.getanyText().strip() text += "\n}\n\n" Gen_Cfile_path = os.path.join(buildpath, "CFile_%s.c"%location_str) diff -r 72a826dfcfbb -r 02fe382c4511 canfestival/SlaveEditor.py --- a/canfestival/SlaveEditor.py Wed Jul 31 10:45:07 2013 +0900 +++ b/canfestival/SlaveEditor.py Mon Nov 18 12:12:31 2013 +0900 @@ -75,8 +75,9 @@ self.ParentWindow.RefreshPageTitles() class MasterViewer(SlaveEditor): + SHOW_BASE_PARAMS = False SHOW_PARAMS = False - + def __init__(self, parent, controler, window, tagname): SlaveEditor.__init__(self, parent, controler, window, False) @@ -96,3 +97,7 @@ def IsViewing(self, tagname): return self.GetInstancePath() == tagname + + def RefreshView(self): + self.SlaveNodeEditor.RefreshIndexList() + diff -r 72a826dfcfbb -r 02fe382c4511 controls/CustomTable.py --- a/controls/CustomTable.py Wed Jul 31 10:45:07 2013 +0900 +++ b/controls/CustomTable.py Mon Nov 18 12:12:31 2013 +0900 @@ -18,6 +18,11 @@ import wx import wx.grid +if wx.Platform == '__WXMSW__': + ROW_HEIGHT = 20 +else: + ROW_HEIGHT = 28 + class CustomTable(wx.grid.PyGridTableBase): """ @@ -124,11 +129,9 @@ self.ResizeRow(grid, row) def ResizeRow(self, grid, row): - if wx.Platform == '__WXMSW__': - grid.SetRowMinimalHeight(row, 20) - else: - grid.SetRowMinimalHeight(row, 28) - grid.AutoSizeRow(row, False) + if grid.GetRowSize(row) < ROW_HEIGHT: + grid.SetRowMinimalHeight(row, ROW_HEIGHT) + grid.AutoSizeRow(row, False) def SetData(self, data): self.data = data diff -r 72a826dfcfbb -r 02fe382c4511 controls/DebugVariablePanel/DebugVariableGraphicPanel.py --- a/controls/DebugVariablePanel/DebugVariableGraphicPanel.py Wed Jul 31 10:45:07 2013 +0900 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,955 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- - -#This file is part of PLCOpenEditor, a library implementing an IEC 61131-3 editor -#based on the plcopen standard. -# -#Copyright (C) 2012: Edouard TISSERANT and Laurent BESSARD -# -#See COPYING file for copyrights details. -# -#This library is free software; you can redistribute it and/or -#modify it under the terms of the GNU General Public -#License as published by the Free Software Foundation; either -#version 2.1 of the License, or (at your option) any later version. -# -#This library is distributed in the hope that it will be useful, -#but WITHOUT ANY WARRANTY; without even the implied warranty of -#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -#General Public License for more details. -# -#You should have received a copy of the GNU General Public -#License along with this library; if not, write to the Free Software -#Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - -from types import TupleType -import math -import numpy - -import wx -import wx.lib.buttons - -import matplotlib -matplotlib.use('WX') -import matplotlib.pyplot -from matplotlib.backends.backend_wxagg import _convert_agg_to_wx_bitmap - -from editors.DebugViewer import DebugViewer -from util.BitmapLibrary import GetBitmap - -from DebugVariableItem import DebugVariableItem -from DebugVariableTextViewer import DebugVariableTextViewer -from DebugVariableGraphicViewer import * - -MILLISECOND = 1000000 # Number of nanosecond in a millisecond -SECOND = 1000 * MILLISECOND # Number of nanosecond in a second -MINUTE = 60 * SECOND # Number of nanosecond in a minute -HOUR = 60 * MINUTE # Number of nanosecond in a hour -DAY = 24 * HOUR # Number of nanosecond in a day - -# List of values possible for graph range -# Format is [(time_in_plain_text, value_in_nanosecond),...] -RANGE_VALUES = \ - [("%dms" % i, i * MILLISECOND) for i in (10, 20, 50, 100, 200, 500)] + \ - [("%ds" % i, i * SECOND) for i in (1, 2, 5, 10, 20, 30)] + \ - [("%dm" % i, i * MINUTE) for i in (1, 2, 5, 10, 20, 30)] + \ - [("%dh" % i, i * HOUR) for i in (1, 2, 3, 6, 12, 24)] - -# Scrollbar increment in pixel -SCROLLBAR_UNIT = 10 - -def compute_mask(x, y): - return [(xp if xp == yp else "*") - for xp, yp in zip(x, y)] - -def NextTick(variables): - next_tick = None - for item, data in variables: - if len(data) == 0: - continue - - next_tick = (data[0][0] - if next_tick is None - else min(next_tick, data[0][0])) - - return next_tick - -#------------------------------------------------------------------------------- -# Debug Variable Graphic Panel Drop Target -#------------------------------------------------------------------------------- - -""" -Class that implements a custom drop target class for Debug Variable Graphic -Panel -""" - -class DebugVariableDropTarget(wx.TextDropTarget): - - def __init__(self, window): - """ - Constructor - @param window: Reference to the Debug Variable Panel - """ - wx.TextDropTarget.__init__(self) - self.ParentWindow = window - - def __del__(self): - """ - Destructor - """ - # Remove reference to Debug Variable Panel - self.ParentWindow = None - - def OnDragOver(self, x, y, d): - """ - Function called when mouse is dragged over Drop Target - @param x: X coordinate of mouse pointer - @param y: Y coordinate of mouse pointer - @param d: Suggested default for return value - """ - # Signal Debug Variable Panel to refresh highlight giving mouse position - self.ParentWindow.RefreshHighlight(x, y) - return wx.TextDropTarget.OnDragOver(self, x, y, d) - - def OnDropText(self, x, y, data): - """ - Function called when mouse is released in Drop Target - @param x: X coordinate of mouse pointer - @param y: Y coordinate of mouse pointer - @param data: Text associated to drag'n drop - """ - # Signal Debug Variable Panel to reset highlight - self.ParentWindow.ResetHighlight() - - message = None - - # Check that data is valid regarding DebugVariablePanel - try: - values = eval(data) - if not isinstance(values, TupleType): - raise ValueError - except: - message = _("Invalid value \"%s\" for debug variable")%data - values = None - - # Display message if data is invalid - if message is not None: - wx.CallAfter(self.ShowMessage, message) - - # Data contain a reference to a variable to debug - elif values[1] == "debug": - - # Drag'n Drop is an internal is an internal move inside Debug - # Variable Panel - if len(values) > 2 and values[2] == "move": - self.ParentWindow.MoveValue(values[0]) - - # Drag'n Drop was initiated by another control of Beremiz - else: - self.ParentWindow.InsertValue(values[0], force=True) - - def OnLeave(self): - """ - Function called when mouse is leave Drop Target - """ - # Signal Debug Variable Panel to reset highlight - self.ParentWindow.ResetHighlight() - return wx.TextDropTarget.OnLeave(self) - - def ShowMessage(self, message): - """ - Show error message in Error Dialog - @param message: Error message to display - """ - dialog = wx.MessageDialog(self.ParentWindow, - message, - _("Error"), - wx.OK|wx.ICON_ERROR) - dialog.ShowModal() - dialog.Destroy() - - -#------------------------------------------------------------------------------- -# Debug Variable Graphic Panel Class -#------------------------------------------------------------------------------- - -""" -Class that implements a Viewer that display variable values as a graphs -""" - -class DebugVariableGraphicPanel(wx.Panel, DebugViewer): - - def __init__(self, parent, producer, window): - """ - Constructor - @param parent: Reference to the parent wx.Window - @param producer: Object receiving debug value and dispatching them to - consumers - @param window: Reference to Beremiz frame - """ - wx.Panel.__init__(self, parent, style=wx.SP_3D|wx.TAB_TRAVERSAL) - - # Save Reference to Beremiz frame - self.ParentWindow = window - - # Variable storing flag indicating that variable displayed in table - # received new value and then table need to be refreshed - self.HasNewData = False - - # Variable storing flag indicating that refresh has been forced, and - # that next time refresh is possible, it will be done even if no new - # data is available - self.Force = False - - self.SetBackgroundColour(wx.WHITE) - - main_sizer = wx.BoxSizer(wx.VERTICAL) - - self.Ticks = numpy.array([]) # List of tick received - self.StartTick = 0 # Tick starting range of data displayed - self.Fixed = False # Flag that range of data is fixed - self.CursorTick = None # Tick of cursor for displaying values - - self.DraggingAxesPanel = None - self.DraggingAxesBoundingBox = None - self.DraggingAxesMousePos = None - self.VetoScrollEvent = False - - self.VariableNameMask = [] - - self.GraphicPanels = [] - - graphics_button_sizer = wx.BoxSizer(wx.HORIZONTAL) - main_sizer.AddSizer(graphics_button_sizer, border=5, flag=wx.GROW|wx.ALL) - - range_label = wx.StaticText(self, label=_('Range:')) - graphics_button_sizer.AddWindow(range_label, flag=wx.ALIGN_CENTER_VERTICAL) - - self.CanvasRange = wx.ComboBox(self, style=wx.CB_READONLY) - self.Bind(wx.EVT_COMBOBOX, self.OnRangeChanged, self.CanvasRange) - graphics_button_sizer.AddWindow(self.CanvasRange, 1, - border=5, flag=wx.LEFT|wx.ALIGN_CENTER_VERTICAL) - - self.CanvasRange.Clear() - default_range_idx = 0 - for idx, (text, value) in enumerate(RANGE_VALUES): - self.CanvasRange.Append(text) - if text == "1s": - default_range_idx = idx - self.CanvasRange.SetSelection(default_range_idx) - - for name, bitmap, help in [ - ("CurrentButton", "current", _("Go to current value")), - ("ExportGraphButton", "export_graph", _("Export graph values to clipboard"))]: - button = wx.lib.buttons.GenBitmapButton(self, - bitmap=GetBitmap(bitmap), - size=wx.Size(28, 28), style=wx.NO_BORDER) - button.SetToolTipString(help) - setattr(self, name, button) - self.Bind(wx.EVT_BUTTON, getattr(self, "On" + name), button) - graphics_button_sizer.AddWindow(button, border=5, flag=wx.LEFT) - - self.CanvasPosition = wx.ScrollBar(self, - size=wx.Size(0, 16), style=wx.SB_HORIZONTAL) - self.CanvasPosition.Bind(wx.EVT_SCROLL_THUMBTRACK, - self.OnPositionChanging, self.CanvasPosition) - self.CanvasPosition.Bind(wx.EVT_SCROLL_LINEUP, - self.OnPositionChanging, self.CanvasPosition) - self.CanvasPosition.Bind(wx.EVT_SCROLL_LINEDOWN, - self.OnPositionChanging, self.CanvasPosition) - self.CanvasPosition.Bind(wx.EVT_SCROLL_PAGEUP, - self.OnPositionChanging, self.CanvasPosition) - self.CanvasPosition.Bind(wx.EVT_SCROLL_PAGEDOWN, - self.OnPositionChanging, self.CanvasPosition) - main_sizer.AddWindow(self.CanvasPosition, border=5, flag=wx.GROW|wx.LEFT|wx.RIGHT|wx.BOTTOM) - - self.TickSizer = wx.BoxSizer(wx.HORIZONTAL) - main_sizer.AddSizer(self.TickSizer, border=5, flag=wx.ALL|wx.GROW) - - self.TickLabel = wx.StaticText(self) - self.TickSizer.AddWindow(self.TickLabel, border=5, flag=wx.RIGHT) - - self.MaskLabel = wx.TextCtrl(self, style=wx.TE_READONLY|wx.TE_CENTER|wx.NO_BORDER) - self.TickSizer.AddWindow(self.MaskLabel, 1, border=5, flag=wx.RIGHT|wx.GROW) - - self.TickTimeLabel = wx.StaticText(self) - self.TickSizer.AddWindow(self.TickTimeLabel) - - self.GraphicsWindow = wx.ScrolledWindow(self, style=wx.HSCROLL|wx.VSCROLL) - self.GraphicsWindow.SetBackgroundColour(wx.WHITE) - self.GraphicsWindow.SetDropTarget(DebugVariableDropTarget(self)) - self.GraphicsWindow.Bind(wx.EVT_ERASE_BACKGROUND, self.OnGraphicsWindowEraseBackground) - self.GraphicsWindow.Bind(wx.EVT_PAINT, self.OnGraphicsWindowPaint) - self.GraphicsWindow.Bind(wx.EVT_SIZE, self.OnGraphicsWindowResize) - self.GraphicsWindow.Bind(wx.EVT_MOUSEWHEEL, self.OnGraphicsWindowMouseWheel) - - main_sizer.AddWindow(self.GraphicsWindow, 1, flag=wx.GROW) - - self.GraphicsSizer = wx.BoxSizer(wx.VERTICAL) - self.GraphicsWindow.SetSizer(self.GraphicsSizer) - - DebugViewer.__init__(self, producer, True) - - self.SetSizer(main_sizer) - - def SetTickTime(self, ticktime=0): - """ - Set Ticktime for calculate data range according to time range selected - @param ticktime: Ticktime to apply to range (default: 0) - """ - # Save ticktime - self.Ticktime = ticktime - - # Set ticktime to millisecond if undefined - if self.Ticktime == 0: - self.Ticktime = MILLISECOND - - # Calculate range to apply to data - self.CurrentRange = RANGE_VALUES[ - self.CanvasRange.GetSelection()][1] / self.Ticktime - - def SetDataProducer(self, producer): - """ - Set Data Producer - @param producer: Data Producer - """ - DebugViewer.SetDataProducer(self, producer) - - # Set ticktime if data producer is available - if self.DataProducer is not None: - self.SetTickTime(self.DataProducer.GetTicktime()) - - def RefreshNewData(self, *args, **kwargs): - """ - Called to refresh Panel according to values received by variables - Can receive any parameters (not used here) - """ - # Refresh graphs if new data is available or refresh is forced - if self.HasNewData or self.Force: - self.HasNewData = False - self.RefreshView() - - DebugViewer.RefreshNewData(self, *args, **kwargs) - - def NewDataAvailable(self, tick, *args, **kwargs): - """ - Called by DataProducer for each tick captured or by panel to refresh - graphs - @param tick: PLC tick captured - All other parameters are passed to refresh function - """ - # If tick given - if tick is not None: - self.HasNewData = True - - # Save tick as start tick for range if data is still empty - if len(self.Ticks) == 0: - self.StartTick = tick - - # Add tick to list of ticks received - self.Ticks = numpy.append(self.Ticks, [tick]) - - # Update start tick for range if range follow ticks received - if not self.Fixed or tick < self.StartTick + self.CurrentRange: - self.StartTick = max(self.StartTick, tick - self.CurrentRange) - - # Force refresh if graph is fixed because range of data received - # is too small to fill data range selected - if self.Fixed and \ - self.Ticks[-1] - self.Ticks[0] < self.CurrentRange: - self.Force = True - - DebugViewer.NewDataAvailable(self, tick, *args, **kwargs) - - def ForceRefresh(self): - """ - Called to force refresh of graphs - """ - self.Force = True - wx.CallAfter(self.NewDataAvailable, None, True) - - def SetCursorTick(self, cursor_tick): - """ - Set Cursor for displaying values of items at a tick given - @param cursor_tick: Tick of cursor - """ - # Save cursor tick - self.CursorTick = cursor_tick - self.Fixed = cursor_tick is not None - self.UpdateCursorTick() - - def MoveCursorTick(self, move): - if self.CursorTick is not None: - cursor_tick = max(self.Ticks[0], - min(self.CursorTick + move, - self.Ticks[-1])) - cursor_tick_idx = numpy.argmin(numpy.abs(self.Ticks - cursor_tick)) - if self.Ticks[cursor_tick_idx] == self.CursorTick: - cursor_tick_idx = max(0, - min(cursor_tick_idx + abs(move) / move, - len(self.Ticks) - 1)) - self.CursorTick = self.Ticks[cursor_tick_idx] - self.StartTick = max(self.Ticks[ - numpy.argmin(numpy.abs(self.Ticks - - self.CursorTick + self.CurrentRange))], - min(self.StartTick, self.CursorTick)) - self.RefreshCanvasPosition() - self.UpdateCursorTick() - - def ResetCursorTick(self): - self.CursorTick = None - self.Fixed = False - self.UpdateCursorTick() - - def UpdateCursorTick(self): - for panel in self.GraphicPanels: - if isinstance(panel, DebugVariableGraphicViewer): - panel.SetCursorTick(self.CursorTick) - self.ForceRefresh() - - def StartDragNDrop(self, panel, item, x_mouse, y_mouse, x_mouse_start, y_mouse_start): - if len(panel.GetItems()) > 1: - self.DraggingAxesPanel = DebugVariableGraphicViewer(self.GraphicsWindow, self, [item], GRAPH_PARALLEL) - self.DraggingAxesPanel.SetCursorTick(self.CursorTick) - width, height = panel.GetSize() - self.DraggingAxesPanel.SetSize(wx.Size(width, height)) - self.DraggingAxesPanel.ResetGraphics() - self.DraggingAxesPanel.SetPosition(wx.Point(0, -height)) - else: - self.DraggingAxesPanel = panel - self.DraggingAxesBoundingBox = panel.GetAxesBoundingBox(parent_coordinate=True) - self.DraggingAxesMousePos = wx.Point( - x_mouse_start - self.DraggingAxesBoundingBox.x, - y_mouse_start - self.DraggingAxesBoundingBox.y) - self.MoveDragNDrop(x_mouse, y_mouse) - - def MoveDragNDrop(self, x_mouse, y_mouse): - self.DraggingAxesBoundingBox.x = x_mouse - self.DraggingAxesMousePos.x - self.DraggingAxesBoundingBox.y = y_mouse - self.DraggingAxesMousePos.y - self.RefreshHighlight(x_mouse, y_mouse) - - def RefreshHighlight(self, x_mouse, y_mouse): - for idx, panel in enumerate(self.GraphicPanels): - x, y = panel.GetPosition() - width, height = panel.GetSize() - rect = wx.Rect(x, y, width, height) - if (rect.InsideXY(x_mouse, y_mouse) or - idx == 0 and y_mouse < 0 or - idx == len(self.GraphicPanels) - 1 and y_mouse > panel.GetPosition()[1]): - panel.RefreshHighlight(x_mouse - x, y_mouse - y) - else: - panel.SetHighlight(HIGHLIGHT_NONE) - if wx.Platform == "__WXMSW__": - self.RefreshView() - else: - self.ForceRefresh() - - def ResetHighlight(self): - for panel in self.GraphicPanels: - panel.SetHighlight(HIGHLIGHT_NONE) - if wx.Platform == "__WXMSW__": - self.RefreshView() - else: - self.ForceRefresh() - - def IsDragging(self): - return self.DraggingAxesPanel is not None - - def GetDraggingAxesClippingRegion(self, panel): - x, y = panel.GetPosition() - width, height = panel.GetSize() - bbox = wx.Rect(x, y, width, height) - bbox = bbox.Intersect(self.DraggingAxesBoundingBox) - bbox.x -= x - bbox.y -= y - return bbox - - def GetDraggingAxesPosition(self, panel): - x, y = panel.GetPosition() - return wx.Point(self.DraggingAxesBoundingBox.x - x, - self.DraggingAxesBoundingBox.y - y) - - def StopDragNDrop(self, variable, x_mouse, y_mouse): - if self.DraggingAxesPanel not in self.GraphicPanels: - self.DraggingAxesPanel.Destroy() - self.DraggingAxesPanel = None - self.DraggingAxesBoundingBox = None - self.DraggingAxesMousePos = None - for idx, panel in enumerate(self.GraphicPanels): - panel.SetHighlight(HIGHLIGHT_NONE) - xw, yw = panel.GetPosition() - width, height = panel.GetSize() - bbox = wx.Rect(xw, yw, width, height) - if bbox.InsideXY(x_mouse, y_mouse): - panel.ShowButtons(True) - merge_type = GRAPH_PARALLEL - if isinstance(panel, DebugVariableTextViewer) or panel.Is3DCanvas(): - if y_mouse > yw + height / 2: - idx += 1 - wx.CallAfter(self.MoveValue, variable, idx, True) - else: - rect = panel.GetAxesBoundingBox(True) - if rect.InsideXY(x_mouse, y_mouse): - merge_rect = wx.Rect(rect.x, rect.y, rect.width / 2., rect.height) - if merge_rect.InsideXY(x_mouse, y_mouse): - merge_type = GRAPH_ORTHOGONAL - wx.CallAfter(self.MergeGraphs, variable, idx, merge_type, force=True) - else: - if y_mouse > yw + height / 2: - idx += 1 - wx.CallAfter(self.MoveValue, variable, idx, True) - self.ForceRefresh() - return - width, height = self.GraphicsWindow.GetVirtualSize() - rect = wx.Rect(0, 0, width, height) - if rect.InsideXY(x_mouse, y_mouse): - wx.CallAfter(self.MoveValue, variable, len(self.GraphicPanels), True) - self.ForceRefresh() - - def RefreshGraphicsSizer(self): - self.GraphicsSizer.Clear() - - for panel in self.GraphicPanels: - self.GraphicsSizer.AddWindow(panel, flag=wx.GROW) - - self.GraphicsSizer.Layout() - self.RefreshGraphicsWindowScrollbars() - - def RefreshView(self): - self.RefreshCanvasPosition() - - width, height = self.GraphicsWindow.GetVirtualSize() - bitmap = wx.EmptyBitmap(width, height) - dc = wx.BufferedDC(wx.ClientDC(self.GraphicsWindow), bitmap) - dc.Clear() - dc.BeginDrawing() - if self.DraggingAxesPanel is not None: - destBBox = self.DraggingAxesBoundingBox - srcBBox = self.DraggingAxesPanel.GetAxesBoundingBox() - - srcBmp = _convert_agg_to_wx_bitmap(self.DraggingAxesPanel.get_renderer(), None) - srcDC = wx.MemoryDC() - srcDC.SelectObject(srcBmp) - - dc.Blit(destBBox.x, destBBox.y, - int(destBBox.width), int(destBBox.height), - srcDC, srcBBox.x, srcBBox.y) - dc.EndDrawing() - - if not self.Fixed or self.Force: - self.Force = False - refresh_graphics = True - else: - refresh_graphics = False - - if self.DraggingAxesPanel is not None and self.DraggingAxesPanel not in self.GraphicPanels: - self.DraggingAxesPanel.RefreshViewer(refresh_graphics) - for panel in self.GraphicPanels: - if isinstance(panel, DebugVariableGraphicViewer): - panel.RefreshViewer(refresh_graphics) - else: - panel.RefreshViewer() - - if self.CursorTick is not None: - tick = self.CursorTick - elif len(self.Ticks) > 0: - tick = self.Ticks[-1] - else: - tick = None - if tick is not None: - self.TickLabel.SetLabel("Tick: %d" % tick) - tick_duration = int(tick * self.Ticktime) - not_null = False - duration = "" - for value, format in [(tick_duration / DAY, "%dd"), - ((tick_duration % DAY) / HOUR, "%dh"), - ((tick_duration % HOUR) / MINUTE, "%dm"), - ((tick_duration % MINUTE) / SECOND, "%ds")]: - - if value > 0 or not_null: - duration += format % value - not_null = True - - duration += "%gms" % (float(tick_duration % SECOND) / MILLISECOND) - self.TickTimeLabel.SetLabel("t: %s" % duration) - else: - self.TickLabel.SetLabel("") - self.TickTimeLabel.SetLabel("") - self.TickSizer.Layout() - - def SubscribeAllDataConsumers(self): - DebugViewer.SubscribeAllDataConsumers(self) - - if self.DataProducer is not None: - if self.DataProducer is not None: - self.SetTickTime(self.DataProducer.GetTicktime()) - - self.ResetCursorTick() - - for panel in self.GraphicPanels[:]: - panel.SubscribeAllDataConsumers() - if panel.ItemsIsEmpty(): - if panel.HasCapture(): - panel.ReleaseMouse() - self.GraphicPanels.remove(panel) - panel.Destroy() - - self.ResetVariableNameMask() - self.RefreshGraphicsSizer() - self.ForceRefresh() - - def ResetView(self): - self.UnsubscribeAllDataConsumers() - - self.Fixed = False - for panel in self.GraphicPanels: - panel.Destroy() - self.GraphicPanels = [] - self.ResetVariableNameMask() - self.RefreshGraphicsSizer() - - def SetCanvasPosition(self, tick): - tick = max(self.Ticks[0], min(tick, self.Ticks[-1] - self.CurrentRange)) - self.StartTick = self.Ticks[numpy.argmin(numpy.abs(self.Ticks - tick))] - self.Fixed = True - self.RefreshCanvasPosition() - self.ForceRefresh() - - def RefreshCanvasPosition(self): - if len(self.Ticks) > 0: - pos = int(self.StartTick - self.Ticks[0]) - range = int(self.Ticks[-1] - self.Ticks[0]) - else: - pos = 0 - range = 0 - self.CanvasPosition.SetScrollbar(pos, self.CurrentRange, range, self.CurrentRange) - - def ChangeRange(self, dir, tick=None): - current_range = self.CurrentRange - current_range_idx = self.CanvasRange.GetSelection() - new_range_idx = max(0, min(current_range_idx + dir, len(RANGE_VALUES) - 1)) - if new_range_idx != current_range_idx: - self.CanvasRange.SetSelection(new_range_idx) - self.CurrentRange = RANGE_VALUES[new_range_idx][1] / self.Ticktime - if len(self.Ticks) > 0: - if tick is None: - tick = self.StartTick + self.CurrentRange / 2. - new_start_tick = min(tick - (tick - self.StartTick) * self.CurrentRange / current_range, - self.Ticks[-1] - self.CurrentRange) - self.StartTick = self.Ticks[numpy.argmin(numpy.abs(self.Ticks - new_start_tick))] - self.Fixed = new_start_tick < self.Ticks[-1] - self.CurrentRange - self.ForceRefresh() - - def RefreshRange(self): - if len(self.Ticks) > 0: - if self.Fixed and self.Ticks[-1] - self.Ticks[0] < self.CurrentRange: - self.Fixed = False - if self.Fixed: - self.StartTick = min(self.StartTick, self.Ticks[-1] - self.CurrentRange) - else: - self.StartTick = max(self.Ticks[0], self.Ticks[-1] - self.CurrentRange) - self.ForceRefresh() - - def OnRangeChanged(self, event): - try: - self.CurrentRange = RANGE_VALUES[self.CanvasRange.GetSelection()][1] / self.Ticktime - except ValueError, e: - self.CanvasRange.SetValue(str(self.CurrentRange)) - wx.CallAfter(self.RefreshRange) - event.Skip() - - def OnCurrentButton(self, event): - if len(self.Ticks) > 0: - self.StartTick = max(self.Ticks[0], self.Ticks[-1] - self.CurrentRange) - self.ResetCursorTick() - event.Skip() - - def CopyDataToClipboard(self, variables): - text = "tick;%s;\n" % ";".join([item.GetVariable() for item, data in variables]) - next_tick = NextTick(variables) - while next_tick is not None: - values = [] - for item, data in variables: - if len(data) > 0: - if next_tick == data[0][0]: - var_type = item.GetVariableType() - if var_type in ["STRING", "WSTRING"]: - value = item.GetRawValue(int(data.pop(0)[2])) - if var_type == "STRING": - values.append("'%s'" % value) - else: - values.append('"%s"' % value) - else: - values.append("%.3f" % data.pop(0)[1]) - else: - values.append("") - else: - values.append("") - text += "%d;%s;\n" % (next_tick, ";".join(values)) - next_tick = NextTick(variables) - self.ParentWindow.SetCopyBuffer(text) - - def OnExportGraphButton(self, event): - items = reduce(lambda x, y: x + y, - [panel.GetItems() for panel in self.GraphicPanels], - []) - variables = [(item, [entry for entry in item.GetData()]) - for item in items - if item.IsNumVariable()] - wx.CallAfter(self.CopyDataToClipboard, variables) - event.Skip() - - def OnPositionChanging(self, event): - if len(self.Ticks) > 0: - self.StartTick = self.Ticks[0] + event.GetPosition() - self.Fixed = True - self.ForceRefresh() - event.Skip() - - def GetRange(self): - return self.StartTick, self.StartTick + self.CurrentRange - - def GetViewerIndex(self, viewer): - if viewer in self.GraphicPanels: - return self.GraphicPanels.index(viewer) - return None - - def IsViewerFirst(self, viewer): - return viewer == self.GraphicPanels[0] - - def HighlightPreviousViewer(self, viewer): - if self.IsViewerFirst(viewer): - return - idx = self.GetViewerIndex(viewer) - if idx is None: - return - self.GraphicPanels[idx-1].SetHighlight(HIGHLIGHT_AFTER) - - def ResetVariableNameMask(self): - items = [] - for panel in self.GraphicPanels: - items.extend(panel.GetItems()) - if len(items) > 1: - self.VariableNameMask = reduce(compute_mask, - [item.GetVariable().split('.') for item in items]) - elif len(items) > 0: - self.VariableNameMask = items[0].GetVariable().split('.')[:-1] + ['*'] - else: - self.VariableNameMask = [] - self.MaskLabel.ChangeValue(".".join(self.VariableNameMask)) - self.MaskLabel.SetInsertionPoint(self.MaskLabel.GetLastPosition()) - - def GetVariableNameMask(self): - return self.VariableNameMask - - def InsertValue(self, iec_path, idx = None, force=False, graph=False): - for panel in self.GraphicPanels: - if panel.GetItem(iec_path) is not None: - if graph and isinstance(panel, DebugVariableTextViewer): - self.ToggleViewerType(panel) - return - if idx is None: - idx = len(self.GraphicPanels) - item = DebugVariableItem(self, iec_path, True) - result = self.AddDataConsumer(iec_path.upper(), item) - if result is not None or force: - - self.Freeze() - if item.IsNumVariable() and graph: - panel = DebugVariableGraphicViewer(self.GraphicsWindow, self, [item], GRAPH_PARALLEL) - if self.CursorTick is not None: - panel.SetCursorTick(self.CursorTick) - else: - panel = DebugVariableTextViewer(self.GraphicsWindow, self, [item]) - if idx is not None: - self.GraphicPanels.insert(idx, panel) - else: - self.GraphicPanels.append(panel) - self.ResetVariableNameMask() - self.RefreshGraphicsSizer() - self.Thaw() - self.ForceRefresh() - - def MoveValue(self, iec_path, idx = None, graph=False): - if idx is None: - idx = len(self.GraphicPanels) - source_panel = None - item = None - for panel in self.GraphicPanels: - item = panel.GetItem(iec_path) - if item is not None: - source_panel = panel - break - if source_panel is not None: - source_panel_idx = self.GraphicPanels.index(source_panel) - - if (len(source_panel.GetItems()) == 1): - - if source_panel_idx < idx: - self.GraphicPanels.insert(idx, source_panel) - self.GraphicPanels.pop(source_panel_idx) - elif source_panel_idx > idx: - self.GraphicPanels.pop(source_panel_idx) - self.GraphicPanels.insert(idx, source_panel) - else: - return - - else: - source_panel.RemoveItem(item) - source_size = source_panel.GetSize() - if item.IsNumVariable() and graph: - panel = DebugVariableGraphicViewer(self.GraphicsWindow, self, [item], GRAPH_PARALLEL) - panel.SetCanvasHeight(source_size.height) - if self.CursorTick is not None: - panel.SetCursorTick(self.CursorTick) - - else: - panel = DebugVariableTextViewer(self.GraphicsWindow, self, [item]) - - self.GraphicPanels.insert(idx, panel) - - if source_panel.ItemsIsEmpty(): - if source_panel.HasCapture(): - source_panel.ReleaseMouse() - source_panel.Destroy() - self.GraphicPanels.remove(source_panel) - - self.ResetVariableNameMask() - self.RefreshGraphicsSizer() - self.ForceRefresh() - - def MergeGraphs(self, source, target_idx, merge_type, force=False): - source_item = None - source_panel = None - for panel in self.GraphicPanels: - source_item = panel.GetItem(source) - if source_item is not None: - source_panel = panel - break - if source_item is None: - item = DebugVariableItem(self, source, True) - if item.IsNumVariable(): - result = self.AddDataConsumer(source.upper(), item) - if result is not None or force: - source_item = item - if source_item is not None and source_item.IsNumVariable(): - if source_panel is not None: - source_size = source_panel.GetSize() - else: - source_size = None - target_panel = self.GraphicPanels[target_idx] - graph_type = target_panel.GraphType - if target_panel != source_panel: - if (merge_type == GRAPH_PARALLEL and graph_type != merge_type or - merge_type == GRAPH_ORTHOGONAL and - (graph_type == GRAPH_PARALLEL and len(target_panel.Items) > 1 or - graph_type == GRAPH_ORTHOGONAL and len(target_panel.Items) >= 3)): - return - - if source_panel is not None: - source_panel.RemoveItem(source_item) - if source_panel.ItemsIsEmpty(): - if source_panel.HasCapture(): - source_panel.ReleaseMouse() - source_panel.Destroy() - self.GraphicPanels.remove(source_panel) - elif (merge_type != graph_type and len(target_panel.Items) == 2): - target_panel.RemoveItem(source_item) - else: - target_panel = None - - if target_panel is not None: - target_panel.AddItem(source_item) - target_panel.GraphType = merge_type - size = target_panel.GetSize() - if merge_type == GRAPH_ORTHOGONAL: - target_panel.SetCanvasHeight(size.width) - elif source_size is not None and source_panel != target_panel: - target_panel.SetCanvasHeight(size.height + source_size.height) - else: - target_panel.SetCanvasHeight(size.height) - target_panel.ResetGraphics() - - self.ResetVariableNameMask() - self.RefreshGraphicsSizer() - self.ForceRefresh() - - def DeleteValue(self, source_panel, item=None): - source_idx = self.GetViewerIndex(source_panel) - if source_idx is not None: - - if item is None: - source_panel.ClearItems() - source_panel.Destroy() - self.GraphicPanels.remove(source_panel) - self.ResetVariableNameMask() - self.RefreshGraphicsSizer() - else: - source_panel.RemoveItem(item) - if source_panel.ItemsIsEmpty(): - source_panel.Destroy() - self.GraphicPanels.remove(source_panel) - self.ResetVariableNameMask() - self.RefreshGraphicsSizer() - if len(self.GraphicPanels) == 0: - self.Fixed = False - self.ResetCursorTick() - self.ForceRefresh() - - def ToggleViewerType(self, panel): - panel_idx = self.GetViewerIndex(panel) - if panel_idx is not None: - self.GraphicPanels.remove(panel) - items = panel.GetItems() - if isinstance(panel, DebugVariableGraphicViewer): - for idx, item in enumerate(items): - new_panel = DebugVariableTextViewer(self.GraphicsWindow, self, [item]) - self.GraphicPanels.insert(panel_idx + idx, new_panel) - else: - new_panel = DebugVariableGraphicViewer(self.GraphicsWindow, self, items, GRAPH_PARALLEL) - self.GraphicPanels.insert(panel_idx, new_panel) - panel.Destroy() - self.RefreshGraphicsSizer() - self.ForceRefresh() - - def ResetGraphicsValues(self): - self.Ticks = numpy.array([]) - self.StartTick = 0 - for panel in self.GraphicPanels: - panel.ResetItemsData() - self.ResetCursorTick() - - def RefreshGraphicsWindowScrollbars(self): - xstart, ystart = self.GraphicsWindow.GetViewStart() - window_size = self.GraphicsWindow.GetClientSize() - vwidth, vheight = self.GraphicsSizer.GetMinSize() - posx = max(0, min(xstart, (vwidth - window_size[0]) / SCROLLBAR_UNIT)) - posy = max(0, min(ystart, (vheight - window_size[1]) / SCROLLBAR_UNIT)) - self.GraphicsWindow.Scroll(posx, posy) - self.GraphicsWindow.SetScrollbars(SCROLLBAR_UNIT, SCROLLBAR_UNIT, - vwidth / SCROLLBAR_UNIT, vheight / SCROLLBAR_UNIT, posx, posy) - - def OnGraphicsWindowEraseBackground(self, event): - pass - - def OnGraphicsWindowPaint(self, event): - self.RefreshView() - event.Skip() - - def OnGraphicsWindowResize(self, event): - size = self.GetSize() - for panel in self.GraphicPanels: - panel_size = panel.GetSize() - if (isinstance(panel, DebugVariableGraphicViewer) and - panel.GraphType == GRAPH_ORTHOGONAL and - panel_size.width == panel_size.height): - panel.SetCanvasHeight(size.width) - self.RefreshGraphicsWindowScrollbars() - self.GraphicsSizer.Layout() - event.Skip() - - def OnGraphicsWindowMouseWheel(self, event): - if self.VetoScrollEvent: - self.VetoScrollEvent = False - else: - event.Skip() diff -r 72a826dfcfbb -r 02fe382c4511 controls/DebugVariablePanel/DebugVariableGraphicViewer.py --- a/controls/DebugVariablePanel/DebugVariableGraphicViewer.py Wed Jul 31 10:45:07 2013 +0900 +++ b/controls/DebugVariablePanel/DebugVariableGraphicViewer.py Mon Nov 18 12:12:31 2013 +0900 @@ -29,7 +29,6 @@ import wx import matplotlib -matplotlib.use('WX') import matplotlib.pyplot from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg as FigureCanvas from matplotlib.backends.backend_wxagg import _convert_agg_to_wx_bitmap diff -r 72a826dfcfbb -r 02fe382c4511 controls/DebugVariablePanel/DebugVariableItem.py --- a/controls/DebugVariablePanel/DebugVariableItem.py Wed Jul 31 10:45:07 2013 +0900 +++ b/controls/DebugVariablePanel/DebugVariableItem.py Mon Nov 18 12:12:31 2013 +0900 @@ -232,52 +232,62 @@ return (self.Parent.IsNumType(self.VariableType) or self.VariableType in ["STRING", "WSTRING"]) - def NewValue(self, tick, value, forced=False): + def NewValues(self, ticks, values): """ Function called by debug thread when a new debug value is available @param tick: PLC tick when value was captured @param value: Value captured @param forced: Forced flag, True if value is forced (default: False) """ - DebugDataConsumer.NewValue(self, tick, value, forced, raw=None) + DebugDataConsumer.NewValues(self, ticks[-1], values[-1], raw=None) if self.Data is not None: - # String data value is CRC - num_value = (binascii.crc32(value) & STRING_CRC_MASK - if self.VariableType in ["STRING", "WSTRING"] - else float(value)) - - # Update variable range values - self.MinValue = (min(self.MinValue, num_value) - if self.MinValue is not None - else num_value) - self.MaxValue = (max(self.MaxValue, num_value) - if self.MaxValue is not None - else num_value) - - # Translate forced flag to float for storing in Data table - forced_value = float(forced) - - # In the case of string variables, we store raw string value and - # forced flag in raw data table. Only changes in this two values - # are stored. Index to the corresponding raw value is stored in - # data third column + if self.VariableType in ["STRING", "WSTRING"]: - raw_data = (value, forced_value) - if len(self.RawData) == 0 or self.RawData[-1] != raw_data: - extra_value = len(self.RawData) - self.RawData.append(raw_data) + last_raw_data = (self.RawData[-1] + if len(self.RawData) > 0 else None) + last_raw_data_idx = len(self.RawData) - 1 + + data_values = [] + for tick, (value, forced) in zip(ticks, values): + # Translate forced flag to float for storing in Data table + forced_value = float(forced) + + # String data value is CRC + num_value = (binascii.crc32(value) & STRING_CRC_MASK + if self.VariableType in ["STRING", "WSTRING"] + else float(value)) + + # Update variable range values + self.MinValue = (min(self.MinValue, num_value) + if self.MinValue is not None + else num_value) + self.MaxValue = (max(self.MaxValue, num_value) + if self.MaxValue is not None + else num_value) + + # In the case of string variables, we store raw string value and + # forced flag in raw data table. Only changes in this two values + # are stored. Index to the corresponding raw value is stored in + # data third column + if self.VariableType in ["STRING", "WSTRING"]: + raw_data = (value, forced_value) + if len(self.RawData) == 0 or last_raw_data != raw_data: + last_raw_data_idx += 1 + last_raw_data = raw_data + self.RawData.append(raw_data) + extra_value = last_raw_data_idx + + # In other case, data third column is forced flag else: - extra_value = len(self.RawData) - 1 - - # In other case, data third column is forced flag - else: - extra_value = forced_value + extra_value = forced_value + + data_values.append( + [float(tick), num_value, extra_value]) # Add New data to stored data table - self.Data = numpy.append(self.Data, - [[float(tick), num_value, extra_value]], axis=0) - + self.Data = numpy.append(self.Data, data_values, axis=0) + # Signal to debug variable panel to refresh self.Parent.HasNewData = True diff -r 72a826dfcfbb -r 02fe382c4511 controls/DebugVariablePanel/DebugVariablePanel.py --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/controls/DebugVariablePanel/DebugVariablePanel.py Mon Nov 18 12:12:31 2013 +0900 @@ -0,0 +1,958 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +#This file is part of PLCOpenEditor, a library implementing an IEC 61131-3 editor +#based on the plcopen standard. +# +#Copyright (C) 2012: Edouard TISSERANT and Laurent BESSARD +# +#See COPYING file for copyrights details. +# +#This library is free software; you can redistribute it and/or +#modify it under the terms of the GNU General Public +#License as published by the Free Software Foundation; either +#version 2.1 of the License, or (at your option) any later version. +# +#This library is distributed in the hope that it will be useful, +#but WITHOUT ANY WARRANTY; without even the implied warranty of +#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +#General Public License for more details. +# +#You should have received a copy of the GNU General Public +#License along with this library; if not, write to the Free Software +#Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + +from types import TupleType +import math +import numpy + +import wx +import wx.lib.buttons + +import matplotlib +import matplotlib.pyplot +from matplotlib.backends.backend_wxagg import _convert_agg_to_wx_bitmap + +from editors.DebugViewer import DebugViewer +from util.BitmapLibrary import GetBitmap + +from DebugVariableItem import DebugVariableItem +from DebugVariableTextViewer import DebugVariableTextViewer +from DebugVariableGraphicViewer import * + +MILLISECOND = 1000000 # Number of nanosecond in a millisecond +SECOND = 1000 * MILLISECOND # Number of nanosecond in a second +MINUTE = 60 * SECOND # Number of nanosecond in a minute +HOUR = 60 * MINUTE # Number of nanosecond in a hour +DAY = 24 * HOUR # Number of nanosecond in a day + +# List of values possible for graph range +# Format is [(time_in_plain_text, value_in_nanosecond),...] +RANGE_VALUES = \ + [("%dms" % i, i * MILLISECOND) for i in (10, 20, 50, 100, 200, 500)] + \ + [("%ds" % i, i * SECOND) for i in (1, 2, 5, 10, 20, 30)] + \ + [("%dm" % i, i * MINUTE) for i in (1, 2, 5, 10, 20, 30)] + \ + [("%dh" % i, i * HOUR) for i in (1, 2, 3, 6, 12, 24)] + +# Scrollbar increment in pixel +SCROLLBAR_UNIT = 10 + +def compute_mask(x, y): + return [(xp if xp == yp else "*") + for xp, yp in zip(x, y)] + +def NextTick(variables): + next_tick = None + for item, data in variables: + if len(data) == 0: + continue + + next_tick = (data[0][0] + if next_tick is None + else min(next_tick, data[0][0])) + + return next_tick + +#------------------------------------------------------------------------------- +# Debug Variable Graphic Panel Drop Target +#------------------------------------------------------------------------------- + +""" +Class that implements a custom drop target class for Debug Variable Graphic +Panel +""" + +class DebugVariableDropTarget(wx.TextDropTarget): + + def __init__(self, window): + """ + Constructor + @param window: Reference to the Debug Variable Panel + """ + wx.TextDropTarget.__init__(self) + self.ParentWindow = window + + def __del__(self): + """ + Destructor + """ + # Remove reference to Debug Variable Panel + self.ParentWindow = None + + def OnDragOver(self, x, y, d): + """ + Function called when mouse is dragged over Drop Target + @param x: X coordinate of mouse pointer + @param y: Y coordinate of mouse pointer + @param d: Suggested default for return value + """ + # Signal Debug Variable Panel to refresh highlight giving mouse position + self.ParentWindow.RefreshHighlight(x, y) + return wx.TextDropTarget.OnDragOver(self, x, y, d) + + def OnDropText(self, x, y, data): + """ + Function called when mouse is released in Drop Target + @param x: X coordinate of mouse pointer + @param y: Y coordinate of mouse pointer + @param data: Text associated to drag'n drop + """ + # Signal Debug Variable Panel to reset highlight + self.ParentWindow.ResetHighlight() + + message = None + + # Check that data is valid regarding DebugVariablePanel + try: + values = eval(data) + if not isinstance(values, TupleType): + raise ValueError + except: + message = _("Invalid value \"%s\" for debug variable")%data + values = None + + # Display message if data is invalid + if message is not None: + wx.CallAfter(self.ShowMessage, message) + + # Data contain a reference to a variable to debug + elif values[1] == "debug": + + # Drag'n Drop is an internal is an internal move inside Debug + # Variable Panel + if len(values) > 2 and values[2] == "move": + self.ParentWindow.MoveValue(values[0]) + + # Drag'n Drop was initiated by another control of Beremiz + else: + self.ParentWindow.InsertValue(values[0], force=True) + + def OnLeave(self): + """ + Function called when mouse is leave Drop Target + """ + # Signal Debug Variable Panel to reset highlight + self.ParentWindow.ResetHighlight() + return wx.TextDropTarget.OnLeave(self) + + def ShowMessage(self, message): + """ + Show error message in Error Dialog + @param message: Error message to display + """ + dialog = wx.MessageDialog(self.ParentWindow, + message, + _("Error"), + wx.OK|wx.ICON_ERROR) + dialog.ShowModal() + dialog.Destroy() + + +#------------------------------------------------------------------------------- +# Debug Variable Graphic Panel Class +#------------------------------------------------------------------------------- + +""" +Class that implements a Viewer that display variable values as a graphs +""" + +class DebugVariablePanel(wx.Panel, DebugViewer): + + def __init__(self, parent, producer, window): + """ + Constructor + @param parent: Reference to the parent wx.Window + @param producer: Object receiving debug value and dispatching them to + consumers + @param window: Reference to Beremiz frame + """ + wx.Panel.__init__(self, parent, style=wx.SP_3D|wx.TAB_TRAVERSAL) + + # Save Reference to Beremiz frame + self.ParentWindow = window + + # Variable storing flag indicating that variable displayed in table + # received new value and then table need to be refreshed + self.HasNewData = False + + # Variable storing flag indicating that refresh has been forced, and + # that next time refresh is possible, it will be done even if no new + # data is available + self.Force = False + + self.SetBackgroundColour(wx.WHITE) + + main_sizer = wx.BoxSizer(wx.VERTICAL) + + self.Ticks = numpy.array([]) # List of tick received + self.StartTick = 0 # Tick starting range of data displayed + self.Fixed = False # Flag that range of data is fixed + self.CursorTick = None # Tick of cursor for displaying values + + self.DraggingAxesPanel = None + self.DraggingAxesBoundingBox = None + self.DraggingAxesMousePos = None + self.VetoScrollEvent = False + + self.VariableNameMask = [] + + self.GraphicPanels = [] + + graphics_button_sizer = wx.BoxSizer(wx.HORIZONTAL) + main_sizer.AddSizer(graphics_button_sizer, border=5, flag=wx.GROW|wx.ALL) + + range_label = wx.StaticText(self, label=_('Range:')) + graphics_button_sizer.AddWindow(range_label, flag=wx.ALIGN_CENTER_VERTICAL) + + self.CanvasRange = wx.ComboBox(self, style=wx.CB_READONLY) + self.Bind(wx.EVT_COMBOBOX, self.OnRangeChanged, self.CanvasRange) + graphics_button_sizer.AddWindow(self.CanvasRange, 1, + border=5, flag=wx.LEFT|wx.ALIGN_CENTER_VERTICAL) + + self.CanvasRange.Clear() + default_range_idx = 0 + for idx, (text, value) in enumerate(RANGE_VALUES): + self.CanvasRange.Append(text) + if text == "1s": + default_range_idx = idx + self.CanvasRange.SetSelection(default_range_idx) + + for name, bitmap, help in [ + ("CurrentButton", "current", _("Go to current value")), + ("ExportGraphButton", "export_graph", _("Export graph values to clipboard"))]: + button = wx.lib.buttons.GenBitmapButton(self, + bitmap=GetBitmap(bitmap), + size=wx.Size(28, 28), style=wx.NO_BORDER) + button.SetToolTipString(help) + setattr(self, name, button) + self.Bind(wx.EVT_BUTTON, getattr(self, "On" + name), button) + graphics_button_sizer.AddWindow(button, border=5, flag=wx.LEFT) + + self.CanvasPosition = wx.ScrollBar(self, + size=wx.Size(0, 16), style=wx.SB_HORIZONTAL) + self.CanvasPosition.Bind(wx.EVT_SCROLL_THUMBTRACK, + self.OnPositionChanging, self.CanvasPosition) + self.CanvasPosition.Bind(wx.EVT_SCROLL_LINEUP, + self.OnPositionChanging, self.CanvasPosition) + self.CanvasPosition.Bind(wx.EVT_SCROLL_LINEDOWN, + self.OnPositionChanging, self.CanvasPosition) + self.CanvasPosition.Bind(wx.EVT_SCROLL_PAGEUP, + self.OnPositionChanging, self.CanvasPosition) + self.CanvasPosition.Bind(wx.EVT_SCROLL_PAGEDOWN, + self.OnPositionChanging, self.CanvasPosition) + main_sizer.AddWindow(self.CanvasPosition, border=5, flag=wx.GROW|wx.LEFT|wx.RIGHT|wx.BOTTOM) + + self.TickSizer = wx.BoxSizer(wx.HORIZONTAL) + main_sizer.AddSizer(self.TickSizer, border=5, flag=wx.ALL|wx.GROW) + + self.TickLabel = wx.StaticText(self) + self.TickSizer.AddWindow(self.TickLabel, border=5, flag=wx.RIGHT) + + self.MaskLabel = wx.TextCtrl(self, style=wx.TE_READONLY|wx.TE_CENTER|wx.NO_BORDER) + self.TickSizer.AddWindow(self.MaskLabel, 1, border=5, flag=wx.RIGHT|wx.GROW) + + self.TickTimeLabel = wx.StaticText(self) + self.TickSizer.AddWindow(self.TickTimeLabel) + + self.GraphicsWindow = wx.ScrolledWindow(self, style=wx.HSCROLL|wx.VSCROLL) + self.GraphicsWindow.SetBackgroundColour(wx.WHITE) + self.GraphicsWindow.SetDropTarget(DebugVariableDropTarget(self)) + self.GraphicsWindow.Bind(wx.EVT_ERASE_BACKGROUND, self.OnGraphicsWindowEraseBackground) + self.GraphicsWindow.Bind(wx.EVT_PAINT, self.OnGraphicsWindowPaint) + self.GraphicsWindow.Bind(wx.EVT_SIZE, self.OnGraphicsWindowResize) + self.GraphicsWindow.Bind(wx.EVT_MOUSEWHEEL, self.OnGraphicsWindowMouseWheel) + + main_sizer.AddWindow(self.GraphicsWindow, 1, flag=wx.GROW) + + self.GraphicsSizer = wx.BoxSizer(wx.VERTICAL) + self.GraphicsWindow.SetSizer(self.GraphicsSizer) + + DebugViewer.__init__(self, producer, True) + + self.SetSizer(main_sizer) + + def SetTickTime(self, ticktime=0): + """ + Set Ticktime for calculate data range according to time range selected + @param ticktime: Ticktime to apply to range (default: 0) + """ + # Save ticktime + self.Ticktime = ticktime + + # Set ticktime to millisecond if undefined + if self.Ticktime == 0: + self.Ticktime = MILLISECOND + + # Calculate range to apply to data + self.CurrentRange = RANGE_VALUES[ + self.CanvasRange.GetSelection()][1] / self.Ticktime + + def SetDataProducer(self, producer): + """ + Set Data Producer + @param producer: Data Producer + """ + DebugViewer.SetDataProducer(self, producer) + + # Set ticktime if data producer is available + if self.DataProducer is not None: + self.SetTickTime(self.DataProducer.GetTicktime()) + + def RefreshNewData(self, *args, **kwargs): + """ + Called to refresh Panel according to values received by variables + Can receive any parameters (not used here) + """ + # Refresh graphs if new data is available or refresh is forced + if self.HasNewData or self.Force: + self.HasNewData = False + self.RefreshView() + + DebugViewer.RefreshNewData(self, *args, **kwargs) + + def NewDataAvailable(self, ticks, *args, **kwargs): + """ + Called by DataProducer for each tick captured or by panel to refresh + graphs + @param tick: PLC tick captured + All other parameters are passed to refresh function + """ + # If tick given + if ticks is not None: + tick = ticks[-1] + + # Save tick as start tick for range if data is still empty + if len(self.Ticks) == 0: + self.StartTick = ticks[0] + + # Add tick to list of ticks received + self.Ticks = numpy.append(self.Ticks, ticks) + + # Update start tick for range if range follow ticks received + if not self.Fixed or tick < self.StartTick + self.CurrentRange: + self.StartTick = max(self.StartTick, tick - self.CurrentRange) + + # Force refresh if graph is fixed because range of data received + # is too small to fill data range selected + if self.Fixed and \ + self.Ticks[-1] - self.Ticks[0] < self.CurrentRange: + self.Force = True + + self.HasNewData = False + self.RefreshView() + + else: + DebugViewer.NewDataAvailable(self, ticks, *args, **kwargs) + + def ForceRefresh(self): + """ + Called to force refresh of graphs + """ + self.Force = True + wx.CallAfter(self.NewDataAvailable, None, True) + + def SetCursorTick(self, cursor_tick): + """ + Set Cursor for displaying values of items at a tick given + @param cursor_tick: Tick of cursor + """ + # Save cursor tick + self.CursorTick = cursor_tick + self.Fixed = cursor_tick is not None + self.UpdateCursorTick() + + def MoveCursorTick(self, move): + if self.CursorTick is not None: + cursor_tick = max(self.Ticks[0], + min(self.CursorTick + move, + self.Ticks[-1])) + cursor_tick_idx = numpy.argmin(numpy.abs(self.Ticks - cursor_tick)) + if self.Ticks[cursor_tick_idx] == self.CursorTick: + cursor_tick_idx = max(0, + min(cursor_tick_idx + abs(move) / move, + len(self.Ticks) - 1)) + self.CursorTick = self.Ticks[cursor_tick_idx] + self.StartTick = max(self.Ticks[ + numpy.argmin(numpy.abs(self.Ticks - + self.CursorTick + self.CurrentRange))], + min(self.StartTick, self.CursorTick)) + self.RefreshCanvasPosition() + self.UpdateCursorTick() + + def ResetCursorTick(self): + self.CursorTick = None + self.Fixed = False + self.UpdateCursorTick() + + def UpdateCursorTick(self): + for panel in self.GraphicPanels: + if isinstance(panel, DebugVariableGraphicViewer): + panel.SetCursorTick(self.CursorTick) + self.ForceRefresh() + + def StartDragNDrop(self, panel, item, x_mouse, y_mouse, x_mouse_start, y_mouse_start): + if len(panel.GetItems()) > 1: + self.DraggingAxesPanel = DebugVariableGraphicViewer(self.GraphicsWindow, self, [item], GRAPH_PARALLEL) + self.DraggingAxesPanel.SetCursorTick(self.CursorTick) + width, height = panel.GetSize() + self.DraggingAxesPanel.SetSize(wx.Size(width, height)) + self.DraggingAxesPanel.ResetGraphics() + self.DraggingAxesPanel.SetPosition(wx.Point(0, -height)) + else: + self.DraggingAxesPanel = panel + self.DraggingAxesBoundingBox = panel.GetAxesBoundingBox(parent_coordinate=True) + self.DraggingAxesMousePos = wx.Point( + x_mouse_start - self.DraggingAxesBoundingBox.x, + y_mouse_start - self.DraggingAxesBoundingBox.y) + self.MoveDragNDrop(x_mouse, y_mouse) + + def MoveDragNDrop(self, x_mouse, y_mouse): + self.DraggingAxesBoundingBox.x = x_mouse - self.DraggingAxesMousePos.x + self.DraggingAxesBoundingBox.y = y_mouse - self.DraggingAxesMousePos.y + self.RefreshHighlight(x_mouse, y_mouse) + + def RefreshHighlight(self, x_mouse, y_mouse): + for idx, panel in enumerate(self.GraphicPanels): + x, y = panel.GetPosition() + width, height = panel.GetSize() + rect = wx.Rect(x, y, width, height) + if (rect.InsideXY(x_mouse, y_mouse) or + idx == 0 and y_mouse < 0 or + idx == len(self.GraphicPanels) - 1 and y_mouse > panel.GetPosition()[1]): + panel.RefreshHighlight(x_mouse - x, y_mouse - y) + else: + panel.SetHighlight(HIGHLIGHT_NONE) + if wx.Platform == "__WXMSW__": + self.RefreshView() + else: + self.ForceRefresh() + + def ResetHighlight(self): + for panel in self.GraphicPanels: + panel.SetHighlight(HIGHLIGHT_NONE) + if wx.Platform == "__WXMSW__": + self.RefreshView() + else: + self.ForceRefresh() + + def IsDragging(self): + return self.DraggingAxesPanel is not None + + def GetDraggingAxesClippingRegion(self, panel): + x, y = panel.GetPosition() + width, height = panel.GetSize() + bbox = wx.Rect(x, y, width, height) + bbox = bbox.Intersect(self.DraggingAxesBoundingBox) + bbox.x -= x + bbox.y -= y + return bbox + + def GetDraggingAxesPosition(self, panel): + x, y = panel.GetPosition() + return wx.Point(self.DraggingAxesBoundingBox.x - x, + self.DraggingAxesBoundingBox.y - y) + + def StopDragNDrop(self, variable, x_mouse, y_mouse): + if self.DraggingAxesPanel not in self.GraphicPanels: + self.DraggingAxesPanel.Destroy() + self.DraggingAxesPanel = None + self.DraggingAxesBoundingBox = None + self.DraggingAxesMousePos = None + for idx, panel in enumerate(self.GraphicPanels): + panel.SetHighlight(HIGHLIGHT_NONE) + xw, yw = panel.GetPosition() + width, height = panel.GetSize() + bbox = wx.Rect(xw, yw, width, height) + if bbox.InsideXY(x_mouse, y_mouse): + panel.ShowButtons(True) + merge_type = GRAPH_PARALLEL + if isinstance(panel, DebugVariableTextViewer) or panel.Is3DCanvas(): + if y_mouse > yw + height / 2: + idx += 1 + wx.CallAfter(self.MoveValue, variable, idx, True) + else: + rect = panel.GetAxesBoundingBox(True) + if rect.InsideXY(x_mouse, y_mouse): + merge_rect = wx.Rect(rect.x, rect.y, rect.width / 2., rect.height) + if merge_rect.InsideXY(x_mouse, y_mouse): + merge_type = GRAPH_ORTHOGONAL + wx.CallAfter(self.MergeGraphs, variable, idx, merge_type, force=True) + else: + if y_mouse > yw + height / 2: + idx += 1 + wx.CallAfter(self.MoveValue, variable, idx, True) + self.ForceRefresh() + return + width, height = self.GraphicsWindow.GetVirtualSize() + rect = wx.Rect(0, 0, width, height) + if rect.InsideXY(x_mouse, y_mouse): + wx.CallAfter(self.MoveValue, variable, len(self.GraphicPanels), True) + self.ForceRefresh() + + def RefreshGraphicsSizer(self): + self.GraphicsSizer.Clear() + + for panel in self.GraphicPanels: + self.GraphicsSizer.AddWindow(panel, flag=wx.GROW) + + self.GraphicsSizer.Layout() + self.RefreshGraphicsWindowScrollbars() + + def RefreshView(self): + self.RefreshCanvasPosition() + + width, height = self.GraphicsWindow.GetVirtualSize() + bitmap = wx.EmptyBitmap(width, height) + dc = wx.BufferedDC(wx.ClientDC(self.GraphicsWindow), bitmap) + dc.Clear() + dc.BeginDrawing() + if self.DraggingAxesPanel is not None: + destBBox = self.DraggingAxesBoundingBox + srcBBox = self.DraggingAxesPanel.GetAxesBoundingBox() + + srcBmp = _convert_agg_to_wx_bitmap(self.DraggingAxesPanel.get_renderer(), None) + srcDC = wx.MemoryDC() + srcDC.SelectObject(srcBmp) + + dc.Blit(destBBox.x, destBBox.y, + int(destBBox.width), int(destBBox.height), + srcDC, srcBBox.x, srcBBox.y) + dc.EndDrawing() + + if not self.Fixed or self.Force: + self.Force = False + refresh_graphics = True + else: + refresh_graphics = False + + if self.DraggingAxesPanel is not None and self.DraggingAxesPanel not in self.GraphicPanels: + self.DraggingAxesPanel.RefreshViewer(refresh_graphics) + for panel in self.GraphicPanels: + if isinstance(panel, DebugVariableGraphicViewer): + panel.RefreshViewer(refresh_graphics) + else: + panel.RefreshViewer() + + if self.CursorTick is not None: + tick = self.CursorTick + elif len(self.Ticks) > 0: + tick = self.Ticks[-1] + else: + tick = None + if tick is not None: + self.TickLabel.SetLabel("Tick: %d" % tick) + tick_duration = int(tick * self.Ticktime) + not_null = False + duration = "" + for value, format in [(tick_duration / DAY, "%dd"), + ((tick_duration % DAY) / HOUR, "%dh"), + ((tick_duration % HOUR) / MINUTE, "%dm"), + ((tick_duration % MINUTE) / SECOND, "%ds")]: + + if value > 0 or not_null: + duration += format % value + not_null = True + + duration += "%gms" % (float(tick_duration % SECOND) / MILLISECOND) + self.TickTimeLabel.SetLabel("t: %s" % duration) + else: + self.TickLabel.SetLabel("") + self.TickTimeLabel.SetLabel("") + self.TickSizer.Layout() + + def SubscribeAllDataConsumers(self): + DebugViewer.SubscribeAllDataConsumers(self) + + if self.DataProducer is not None: + if self.DataProducer is not None: + self.SetTickTime(self.DataProducer.GetTicktime()) + + self.ResetCursorTick() + + for panel in self.GraphicPanels[:]: + panel.SubscribeAllDataConsumers() + if panel.ItemsIsEmpty(): + if panel.HasCapture(): + panel.ReleaseMouse() + self.GraphicPanels.remove(panel) + panel.Destroy() + + self.ResetVariableNameMask() + self.RefreshGraphicsSizer() + self.ForceRefresh() + + def ResetView(self): + self.UnsubscribeAllDataConsumers() + + self.Fixed = False + for panel in self.GraphicPanels: + panel.Destroy() + self.GraphicPanels = [] + self.ResetVariableNameMask() + self.RefreshGraphicsSizer() + + def SetCanvasPosition(self, tick): + tick = max(self.Ticks[0], min(tick, self.Ticks[-1] - self.CurrentRange)) + self.StartTick = self.Ticks[numpy.argmin(numpy.abs(self.Ticks - tick))] + self.Fixed = True + self.RefreshCanvasPosition() + self.ForceRefresh() + + def RefreshCanvasPosition(self): + if len(self.Ticks) > 0: + pos = int(self.StartTick - self.Ticks[0]) + range = int(self.Ticks[-1] - self.Ticks[0]) + else: + pos = 0 + range = 0 + self.CanvasPosition.SetScrollbar(pos, self.CurrentRange, range, self.CurrentRange) + + def ChangeRange(self, dir, tick=None): + current_range = self.CurrentRange + current_range_idx = self.CanvasRange.GetSelection() + new_range_idx = max(0, min(current_range_idx + dir, len(RANGE_VALUES) - 1)) + if new_range_idx != current_range_idx: + self.CanvasRange.SetSelection(new_range_idx) + self.CurrentRange = RANGE_VALUES[new_range_idx][1] / self.Ticktime + if len(self.Ticks) > 0: + if tick is None: + tick = self.StartTick + self.CurrentRange / 2. + new_start_tick = min(tick - (tick - self.StartTick) * self.CurrentRange / current_range, + self.Ticks[-1] - self.CurrentRange) + self.StartTick = self.Ticks[numpy.argmin(numpy.abs(self.Ticks - new_start_tick))] + self.Fixed = new_start_tick < self.Ticks[-1] - self.CurrentRange + self.ForceRefresh() + + def RefreshRange(self): + if len(self.Ticks) > 0: + if self.Fixed and self.Ticks[-1] - self.Ticks[0] < self.CurrentRange: + self.Fixed = False + if self.Fixed: + self.StartTick = min(self.StartTick, self.Ticks[-1] - self.CurrentRange) + else: + self.StartTick = max(self.Ticks[0], self.Ticks[-1] - self.CurrentRange) + self.ForceRefresh() + + def OnRangeChanged(self, event): + try: + self.CurrentRange = RANGE_VALUES[self.CanvasRange.GetSelection()][1] / self.Ticktime + except ValueError, e: + self.CanvasRange.SetValue(str(self.CurrentRange)) + wx.CallAfter(self.RefreshRange) + event.Skip() + + def OnCurrentButton(self, event): + if len(self.Ticks) > 0: + self.StartTick = max(self.Ticks[0], self.Ticks[-1] - self.CurrentRange) + self.ResetCursorTick() + event.Skip() + + def CopyDataToClipboard(self, variables): + text = "tick;%s;\n" % ";".join([item.GetVariable() for item, data in variables]) + next_tick = NextTick(variables) + while next_tick is not None: + values = [] + for item, data in variables: + if len(data) > 0: + if next_tick == data[0][0]: + var_type = item.GetVariableType() + if var_type in ["STRING", "WSTRING"]: + value = item.GetRawValue(int(data.pop(0)[2])) + if var_type == "STRING": + values.append("'%s'" % value) + else: + values.append('"%s"' % value) + else: + values.append("%.3f" % data.pop(0)[1]) + else: + values.append("") + else: + values.append("") + text += "%d;%s;\n" % (next_tick, ";".join(values)) + next_tick = NextTick(variables) + self.ParentWindow.SetCopyBuffer(text) + + def OnExportGraphButton(self, event): + items = reduce(lambda x, y: x + y, + [panel.GetItems() for panel in self.GraphicPanels], + []) + variables = [(item, [entry for entry in item.GetData()]) + for item in items + if item.IsNumVariable()] + wx.CallAfter(self.CopyDataToClipboard, variables) + event.Skip() + + def OnPositionChanging(self, event): + if len(self.Ticks) > 0: + self.StartTick = self.Ticks[0] + event.GetPosition() + self.Fixed = True + self.ForceRefresh() + event.Skip() + + def GetRange(self): + return self.StartTick, self.StartTick + self.CurrentRange + + def GetViewerIndex(self, viewer): + if viewer in self.GraphicPanels: + return self.GraphicPanels.index(viewer) + return None + + def IsViewerFirst(self, viewer): + return viewer == self.GraphicPanels[0] + + def HighlightPreviousViewer(self, viewer): + if self.IsViewerFirst(viewer): + return + idx = self.GetViewerIndex(viewer) + if idx is None: + return + self.GraphicPanels[idx-1].SetHighlight(HIGHLIGHT_AFTER) + + def ResetVariableNameMask(self): + items = [] + for panel in self.GraphicPanels: + items.extend(panel.GetItems()) + if len(items) > 1: + self.VariableNameMask = reduce(compute_mask, + [item.GetVariable().split('.') for item in items]) + elif len(items) > 0: + self.VariableNameMask = items[0].GetVariable().split('.')[:-1] + ['*'] + else: + self.VariableNameMask = [] + self.MaskLabel.ChangeValue(".".join(self.VariableNameMask)) + self.MaskLabel.SetInsertionPoint(self.MaskLabel.GetLastPosition()) + + def GetVariableNameMask(self): + return self.VariableNameMask + + def InsertValue(self, iec_path, idx = None, force=False, graph=False): + for panel in self.GraphicPanels: + if panel.GetItem(iec_path) is not None: + if graph and isinstance(panel, DebugVariableTextViewer): + self.ToggleViewerType(panel) + return + if idx is None: + idx = len(self.GraphicPanels) + item = DebugVariableItem(self, iec_path, True) + result = self.AddDataConsumer(iec_path.upper(), item, True) + if result is not None or force: + + self.Freeze() + if item.IsNumVariable() and graph: + panel = DebugVariableGraphicViewer(self.GraphicsWindow, self, [item], GRAPH_PARALLEL) + if self.CursorTick is not None: + panel.SetCursorTick(self.CursorTick) + else: + panel = DebugVariableTextViewer(self.GraphicsWindow, self, [item]) + if idx is not None: + self.GraphicPanels.insert(idx, panel) + else: + self.GraphicPanels.append(panel) + self.ResetVariableNameMask() + self.RefreshGraphicsSizer() + self.Thaw() + self.ForceRefresh() + + def MoveValue(self, iec_path, idx = None, graph=False): + if idx is None: + idx = len(self.GraphicPanels) + source_panel = None + item = None + for panel in self.GraphicPanels: + item = panel.GetItem(iec_path) + if item is not None: + source_panel = panel + break + if source_panel is not None: + source_panel_idx = self.GraphicPanels.index(source_panel) + + if (len(source_panel.GetItems()) == 1): + + if source_panel_idx < idx: + self.GraphicPanels.insert(idx, source_panel) + self.GraphicPanels.pop(source_panel_idx) + elif source_panel_idx > idx: + self.GraphicPanels.pop(source_panel_idx) + self.GraphicPanels.insert(idx, source_panel) + else: + return + + else: + source_panel.RemoveItem(item) + source_size = source_panel.GetSize() + if item.IsNumVariable() and graph: + panel = DebugVariableGraphicViewer(self.GraphicsWindow, self, [item], GRAPH_PARALLEL) + panel.SetCanvasHeight(source_size.height) + if self.CursorTick is not None: + panel.SetCursorTick(self.CursorTick) + + else: + panel = DebugVariableTextViewer(self.GraphicsWindow, self, [item]) + + self.GraphicPanels.insert(idx, panel) + + if source_panel.ItemsIsEmpty(): + if source_panel.HasCapture(): + source_panel.ReleaseMouse() + source_panel.Destroy() + self.GraphicPanels.remove(source_panel) + + self.ResetVariableNameMask() + self.RefreshGraphicsSizer() + self.ForceRefresh() + + def MergeGraphs(self, source, target_idx, merge_type, force=False): + source_item = None + source_panel = None + for panel in self.GraphicPanels: + source_item = panel.GetItem(source) + if source_item is not None: + source_panel = panel + break + if source_item is None: + item = DebugVariableItem(self, source, True) + if item.IsNumVariable(): + result = self.AddDataConsumer(source.upper(), item, True) + if result is not None or force: + source_item = item + if source_item is not None and source_item.IsNumVariable(): + if source_panel is not None: + source_size = source_panel.GetSize() + else: + source_size = None + target_panel = self.GraphicPanels[target_idx] + graph_type = target_panel.GraphType + if target_panel != source_panel: + if (merge_type == GRAPH_PARALLEL and graph_type != merge_type or + merge_type == GRAPH_ORTHOGONAL and + (graph_type == GRAPH_PARALLEL and len(target_panel.Items) > 1 or + graph_type == GRAPH_ORTHOGONAL and len(target_panel.Items) >= 3)): + return + + if source_panel is not None: + source_panel.RemoveItem(source_item) + if source_panel.ItemsIsEmpty(): + if source_panel.HasCapture(): + source_panel.ReleaseMouse() + source_panel.Destroy() + self.GraphicPanels.remove(source_panel) + elif (merge_type != graph_type and len(target_panel.Items) == 2): + target_panel.RemoveItem(source_item) + else: + target_panel = None + + if target_panel is not None: + target_panel.AddItem(source_item) + target_panel.GraphType = merge_type + size = target_panel.GetSize() + if merge_type == GRAPH_ORTHOGONAL: + target_panel.SetCanvasHeight(size.width) + elif source_size is not None and source_panel != target_panel: + target_panel.SetCanvasHeight(size.height + source_size.height) + else: + target_panel.SetCanvasHeight(size.height) + target_panel.ResetGraphics() + + self.ResetVariableNameMask() + self.RefreshGraphicsSizer() + self.ForceRefresh() + + def DeleteValue(self, source_panel, item=None): + source_idx = self.GetViewerIndex(source_panel) + if source_idx is not None: + + if item is None: + source_panel.ClearItems() + source_panel.Destroy() + self.GraphicPanels.remove(source_panel) + self.ResetVariableNameMask() + self.RefreshGraphicsSizer() + else: + source_panel.RemoveItem(item) + if source_panel.ItemsIsEmpty(): + source_panel.Destroy() + self.GraphicPanels.remove(source_panel) + self.ResetVariableNameMask() + self.RefreshGraphicsSizer() + if len(self.GraphicPanels) == 0: + self.Fixed = False + self.ResetCursorTick() + self.ForceRefresh() + + def ToggleViewerType(self, panel): + panel_idx = self.GetViewerIndex(panel) + if panel_idx is not None: + self.GraphicPanels.remove(panel) + items = panel.GetItems() + if isinstance(panel, DebugVariableGraphicViewer): + for idx, item in enumerate(items): + new_panel = DebugVariableTextViewer(self.GraphicsWindow, self, [item]) + self.GraphicPanels.insert(panel_idx + idx, new_panel) + else: + new_panel = DebugVariableGraphicViewer(self.GraphicsWindow, self, items, GRAPH_PARALLEL) + self.GraphicPanels.insert(panel_idx, new_panel) + panel.Destroy() + self.RefreshGraphicsSizer() + self.ForceRefresh() + + def ResetGraphicsValues(self): + self.Ticks = numpy.array([]) + self.StartTick = 0 + for panel in self.GraphicPanels: + panel.ResetItemsData() + self.ResetCursorTick() + + def RefreshGraphicsWindowScrollbars(self): + xstart, ystart = self.GraphicsWindow.GetViewStart() + window_size = self.GraphicsWindow.GetClientSize() + vwidth, vheight = self.GraphicsSizer.GetMinSize() + posx = max(0, min(xstart, (vwidth - window_size[0]) / SCROLLBAR_UNIT)) + posy = max(0, min(ystart, (vheight - window_size[1]) / SCROLLBAR_UNIT)) + self.GraphicsWindow.Scroll(posx, posy) + self.GraphicsWindow.SetScrollbars(SCROLLBAR_UNIT, SCROLLBAR_UNIT, + vwidth / SCROLLBAR_UNIT, vheight / SCROLLBAR_UNIT, posx, posy) + + def OnGraphicsWindowEraseBackground(self, event): + pass + + def OnGraphicsWindowPaint(self, event): + self.RefreshView() + event.Skip() + + def OnGraphicsWindowResize(self, event): + size = self.GetSize() + for panel in self.GraphicPanels: + panel_size = panel.GetSize() + if (isinstance(panel, DebugVariableGraphicViewer) and + panel.GraphType == GRAPH_ORTHOGONAL and + panel_size.width == panel_size.height): + panel.SetCanvasHeight(size.width) + self.RefreshGraphicsWindowScrollbars() + self.GraphicsSizer.Layout() + event.Skip() + + def OnGraphicsWindowMouseWheel(self, event): + if self.VetoScrollEvent: + self.VetoScrollEvent = False + else: + event.Skip() diff -r 72a826dfcfbb -r 02fe382c4511 controls/DebugVariablePanel/DebugVariableTablePanel.py --- a/controls/DebugVariablePanel/DebugVariableTablePanel.py Wed Jul 31 10:45:07 2013 +0900 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,509 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- - -#This file is part of PLCOpenEditor, a library implementing an IEC 61131-3 editor -#based on the plcopen standard. -# -#Copyright (C) 2012: Edouard TISSERANT and Laurent BESSARD -# -#See COPYING file for copyrights details. -# -#This library is free software; you can redistribute it and/or -#modify it under the terms of the GNU General Public -#License as published by the Free Software Foundation; either -#version 2.1 of the License, or (at your option) any later version. -# -#This library is distributed in the hope that it will be useful, -#but WITHOUT ANY WARRANTY; without even the implied warranty of -#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -#General Public License for more details. -# -#You should have received a copy of the GNU General Public -#License along with this library; if not, write to the Free Software -#Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - -from types import TupleType - -import wx -import wx.lib.buttons - -from editors.DebugViewer import DebugViewer -from controls import CustomGrid, CustomTable -from dialogs.ForceVariableDialog import ForceVariableDialog -from util.BitmapLibrary import GetBitmap - -from DebugVariableItem import DebugVariableItem - -def GetDebugVariablesTableColnames(): - """ - Function returning table column header labels - @return: List of labels [col_label,...] - """ - _ = lambda x : x - return [_("Variable"), _("Value")] - -#------------------------------------------------------------------------------- -# Debug Variable Table Panel -#------------------------------------------------------------------------------- - -""" -Class that implements a custom table storing value to display in Debug Variable -Table Panel grid -""" - -class DebugVariableTable(CustomTable): - - def GetValue(self, row, col): - if row < self.GetNumberRows(): - return self.GetValueByName(row, self.GetColLabelValue(col, False)) - return "" - - def SetValue(self, row, col, value): - if col < len(self.colnames): - self.SetValueByName(row, self.GetColLabelValue(col, False), value) - - def GetValueByName(self, row, colname): - if row < self.GetNumberRows(): - if colname == "Variable": - return self.data[row].GetVariable() - elif colname == "Value": - return self.data[row].GetValue() - return "" - - def SetValueByName(self, row, colname, value): - if row < self.GetNumberRows(): - if colname == "Variable": - self.data[row].SetVariable(value) - elif colname == "Value": - self.data[row].SetValue(value) - - def IsForced(self, row): - if row < self.GetNumberRows(): - return self.data[row].IsForced() - return False - - def _updateColAttrs(self, grid): - """ - wx.grid.Grid -> update the column attributes to add the - appropriate renderer given the column name. - - Otherwise default to the default renderer. - """ - - for row in range(self.GetNumberRows()): - for col in range(self.GetNumberCols()): - colname = self.GetColLabelValue(col, False) - if colname == "Value": - if self.IsForced(row): - grid.SetCellTextColour(row, col, wx.BLUE) - else: - grid.SetCellTextColour(row, col, wx.BLACK) - grid.SetReadOnly(row, col, True) - self.ResizeRow(grid, row) - - def RefreshValues(self, grid): - for col in xrange(self.GetNumberCols()): - colname = self.GetColLabelValue(col, False) - if colname == "Value": - for row in xrange(self.GetNumberRows()): - grid.SetCellValue(row, col, str(self.data[row].GetValue())) - if self.IsForced(row): - grid.SetCellTextColour(row, col, wx.BLUE) - else: - grid.SetCellTextColour(row, col, wx.BLACK) - - def AppendItem(self, item): - self.data.append(item) - - def InsertItem(self, idx, item): - self.data.insert(idx, item) - - def RemoveItem(self, item): - self.data.remove(item) - - def MoveItem(self, idx, new_idx): - self.data.insert(new_idx, self.data.pop(idx)) - - def GetItem(self, idx): - return self.data[idx] - - -#------------------------------------------------------------------------------- -# Debug Variable Table Panel Drop Target -#------------------------------------------------------------------------------- - -""" -Class that implements a custom drop target class for Debug Variable Table Panel -""" - -class DebugVariableTableDropTarget(wx.TextDropTarget): - - def __init__(self, parent): - """ - Constructor - @param window: Reference to the Debug Variable Panel - """ - wx.TextDropTarget.__init__(self) - self.ParentWindow = parent - - def __del__(self): - """ - Destructor - """ - # Remove reference to Debug Variable Panel - self.ParentWindow = None - - def OnDropText(self, x, y, data): - """ - Function called when mouse is dragged over Drop Target - @param x: X coordinate of mouse pointer - @param y: Y coordinate of mouse pointer - @param data: Text associated to drag'n drop - """ - message = None - - # Check that data is valid regarding DebugVariablePanel - try: - values = eval(data) - if not isinstance(values, TupleType): - raise ValueError - except: - message = _("Invalid value \"%s\" for debug variable") % data - values = None - - # Display message if data is invalid - if message is not None: - wx.CallAfter(self.ShowMessage, message) - - # Data contain a reference to a variable to debug - elif values[1] == "debug": - grid = self.ParentWindow.VariablesGrid - - # Get row where variable was dropped - x, y = grid.CalcUnscrolledPosition(x, y) - row = grid.YToRow(y - grid.GetColLabelSize()) - - # If no row found add variable at table end - if row == wx.NOT_FOUND: - row = self.ParentWindow.Table.GetNumberRows() - - # Add variable to table - self.ParentWindow.InsertValue(values[0], row, force=True) - - def ShowMessage(self, message): - """ - Show error message in Error Dialog - @param message: Error message to display - """ - dialog = wx.MessageDialog(self.ParentWindow, - message, - _("Error"), - wx.OK|wx.ICON_ERROR) - dialog.ShowModal() - dialog.Destroy() - - -#------------------------------------------------------------------------------- -# Debug Variable Table Panel -#------------------------------------------------------------------------------- - -""" -Class that implements a panel displaying debug variable values in a table -""" - -class DebugVariableTablePanel(wx.Panel, DebugViewer): - - def __init__(self, parent, producer, window): - """ - Constructor - @param parent: Reference to the parent wx.Window - @param producer: Object receiving debug value and dispatching them to - consumers - @param window: Reference to Beremiz frame - """ - wx.Panel.__init__(self, parent, style=wx.SP_3D|wx.TAB_TRAVERSAL) - - # Save Reference to Beremiz frame - self.ParentWindow = window - - # Variable storing flag indicating that variable displayed in table - # received new value and then table need to be refreshed - self.HasNewData = False - - DebugViewer.__init__(self, producer, True) - - # Construction of window layout by creating controls and sizers - - main_sizer = wx.FlexGridSizer(cols=1, hgap=0, rows=2, vgap=0) - main_sizer.AddGrowableCol(0) - main_sizer.AddGrowableRow(1) - - button_sizer = wx.BoxSizer(wx.HORIZONTAL) - main_sizer.AddSizer(button_sizer, border=5, - flag=wx.ALIGN_RIGHT|wx.ALL) - - # Creation of buttons for navigating in table - - for name, bitmap, help in [ - ("DeleteButton", "remove_element", _("Remove debug variable")), - ("UpButton", "up", _("Move debug variable up")), - ("DownButton", "down", _("Move debug variable down"))]: - button = wx.lib.buttons.GenBitmapButton(self, - bitmap=GetBitmap(bitmap), - size=wx.Size(28, 28), style=wx.NO_BORDER) - button.SetToolTipString(help) - setattr(self, name, button) - button_sizer.AddWindow(button, border=5, flag=wx.LEFT) - - # Creation of grid and associated table - - self.VariablesGrid = CustomGrid(self, - size=wx.Size(-1, 150), style=wx.VSCROLL) - # Define grid drop target - self.VariablesGrid.SetDropTarget(DebugVariableTableDropTarget(self)) - self.VariablesGrid.Bind(wx.grid.EVT_GRID_CELL_RIGHT_CLICK, - self.OnVariablesGridCellRightClick) - self.VariablesGrid.Bind(wx.grid.EVT_GRID_CELL_LEFT_CLICK, - self.OnVariablesGridCellLeftClick) - main_sizer.AddWindow(self.VariablesGrid, flag=wx.GROW) - - self.Table = DebugVariableTable(self, [], - GetDebugVariablesTableColnames()) - self.VariablesGrid.SetTable(self.Table) - self.VariablesGrid.SetButtons({"Delete": self.DeleteButton, - "Up": self.UpButton, - "Down": self.DownButton}) - - # Definition of function associated to navigation buttons - - def _AddVariable(new_row): - return self.VariablesGrid.GetGridCursorRow() - setattr(self.VariablesGrid, "_AddRow", _AddVariable) - - def _DeleteVariable(row): - item = self.Table.GetItem(row) - self.RemoveDataConsumer(item) - self.Table.RemoveItem(item) - self.RefreshView() - setattr(self.VariablesGrid, "_DeleteRow", _DeleteVariable) - - def _MoveVariable(row, move): - new_row = max(0, min(row + move, self.Table.GetNumberRows() - 1)) - if new_row != row: - self.Table.MoveItem(row, new_row) - self.RefreshView() - return new_row - setattr(self.VariablesGrid, "_MoveRow", _MoveVariable) - - # Initialization of grid layout - - self.VariablesGrid.SetRowLabelSize(0) - - self.GridColSizes = [200, 100] - - for col in range(self.Table.GetNumberCols()): - attr = wx.grid.GridCellAttr() - attr.SetAlignment(wx.ALIGN_RIGHT, wx.ALIGN_CENTER) - self.VariablesGrid.SetColAttr(col, attr) - self.VariablesGrid.SetColSize(col, self.GridColSizes[col]) - - self.Table.ResetView(self.VariablesGrid) - self.VariablesGrid.RefreshButtons() - - self.SetSizer(main_sizer) - - def RefreshNewData(self, *args, **kwargs): - """ - Called to refresh Table according to values received by variables - Can receive any parameters (not used here) - """ - # Refresh 'Value' column of table if new data have been received since - # last refresh - if self.HasNewData: - self.HasNewData = False - self.RefreshView(only_values=True) - DebugViewer.RefreshNewData(self, *args, **kwargs) - - def RefreshView(self, only_values=False): - """ - Function refreshing table layout and values - @param only_values: True if only 'Value' column need to be updated - """ - # Block refresh until table layout and values are completely updated - self.Freeze() - - # Update only 'value' column from table - if only_values: - self.Table.RefreshValues(self.VariablesGrid) - - # Update complete table layout refreshing table navigation buttons - # state according to - else: - self.Table.ResetView(self.VariablesGrid) - self.VariablesGrid.RefreshButtons() - - self.Thaw() - - def ResetView(self): - """ - Function removing all variables denugged from table - @param only_values: True if only 'Value' column need to be updated - """ - # Unsubscribe all variables debugged - self.UnsubscribeAllDataConsumers() - - # Clear table content - self.Table.Empty() - - # Update table layout - self.Freeze() - self.Table.ResetView(self.VariablesGrid) - self.VariablesGrid.RefreshButtons() - self.Thaw() - - def SubscribeAllDataConsumers(self): - """ - Function refreshing table layout and values - @param only_values: True if only 'Value' column need to be updated - """ - DebugViewer.SubscribeAllDataConsumers(self) - - # Navigate through variable displayed in table, removing those that - # doesn't exist anymore in PLC - for item in self.Table.GetData()[:]: - iec_path = item.GetVariable() - if self.GetDataType(iec_path) is None: - self.RemoveDataConsumer(item) - self.Table.RemoveItem(idx) - else: - self.AddDataConsumer(iec_path.upper(), item) - item.RefreshVariableType() - - # Update table layout - self.Freeze() - self.Table.ResetView(self.VariablesGrid) - self.VariablesGrid.RefreshButtons() - self.Thaw() - - def GetForceVariableMenuFunction(self, item): - """ - Function returning callback function for contextual menu 'Force' item - @param item: Debug Variable item where contextual menu was opened - @return: Callback function - """ - def ForceVariableFunction(event): - # Get variable path and data type - iec_path = item.GetVariable() - iec_type = self.GetDataType(iec_path) - - # Return immediately if not data type found - if iec_type is None: - return - - # Open dialog for entering value to force variable - dialog = ForceVariableDialog(self, iec_type, str(item.GetValue())) - - # If valid value entered, force variable - if dialog.ShowModal() == wx.ID_OK: - self.ForceDataValue(iec_path.upper(), dialog.GetValue()) - - return ForceVariableFunction - - def GetReleaseVariableMenuFunction(self, iec_path): - """ - Function returning callback function for contextual menu 'Release' item - @param iec_path: Debug Variable path where contextual menu was opened - @return: Callback function - """ - def ReleaseVariableFunction(event): - # Release variable - self.ReleaseDataValue(iec_path) - return ReleaseVariableFunction - - def OnVariablesGridCellLeftClick(self, event): - """ - Called when left mouse button is pressed on a table cell - @param event: wx.grid.GridEvent - """ - # Initiate a drag and drop if the cell clicked was in 'Variable' column - if self.Table.GetColLabelValue(event.GetCol(), False) == "Variable": - item = self.Table.GetItem(event.GetRow()) - data = wx.TextDataObject(str((item.GetVariable(), "debug"))) - dragSource = wx.DropSource(self.VariablesGrid) - dragSource.SetData(data) - dragSource.DoDragDrop() - - event.Skip() - - def OnVariablesGridCellRightClick(self, event): - """ - Called when right mouse button is pressed on a table cell - @param event: wx.grid.GridEvent - """ - # Open a contextual menu if the cell clicked was in 'Value' column - if self.Table.GetColLabelValue(event.GetCol(), False) == "Value": - row = event.GetRow() - - # Get variable path - item = self.Table.GetItem(row) - iec_path = item.GetVariable().upper() - - # Create contextual menu - menu = wx.Menu(title='') - - # Add menu items - for text, enable, callback in [ - (_("Force value"), True, - self.GetForceVariableMenuFunction(item)), - # Release menu item is enabled only if variable is forced - (_("Release value"), self.Table.IsForced(row), - self.GetReleaseVariableMenuFunction(iec_path))]: - - new_id = wx.NewId() - menu.Append(help='', id=new_id, kind=wx.ITEM_NORMAL, text=text) - menu.Enable(new_id, enable) - self.Bind(wx.EVT_MENU, callback, id=new_id) - - # Popup contextual menu - self.PopupMenu(menu) - - menu.Destroy() - event.Skip() - - def InsertValue(self, iec_path, index=None, force=False, graph=False): - """ - Insert a new variable to debug in table - @param iec_path: Variable path to debug - @param index: Row where insert the variable in table (default None, - insert at last position) - @param force: Force insertion of variable even if not defined in - producer side - @param graph: Values must be displayed in graph canvas (Do nothing, - here for compatibility with Debug Variable Graphic Panel) - """ - # Return immediately if variable is already debugged - for item in self.Table.GetData(): - if iec_path == item.GetVariable(): - return - - # Insert at last position if index not defined - if index is None: - index = self.Table.GetNumberRows() - - # Subscribe variable to producer - item = DebugVariableItem(self, iec_path) - result = self.AddDataConsumer(iec_path.upper(), item) - - # Insert variable in table if subscription done or insertion forced - if result is not None or force: - self.Table.InsertItem(index, item) - self.RefreshView() - - def ResetGraphicsValues(self): - """ - Called to reset graphics values when PLC is started - (Nothing to do because no graphic values here. Defined for - compatibility with Debug Variable Graphic Panel) - """ - pass - \ No newline at end of file diff -r 72a826dfcfbb -r 02fe382c4511 controls/DebugVariablePanel/DebugVariableViewer.py --- a/controls/DebugVariablePanel/DebugVariableViewer.py Wed Jul 31 10:45:07 2013 +0900 +++ b/controls/DebugVariablePanel/DebugVariableViewer.py Mon Nov 18 12:12:31 2013 +0900 @@ -27,7 +27,6 @@ import wx import matplotlib -matplotlib.use('WX') import matplotlib.pyplot from matplotlib.backends.backend_wxagg import _convert_agg_to_wx_bitmap @@ -150,7 +149,7 @@ self.RemoveItem(item) else: # If it exist, resubscribe and refresh data type - self.ParentWindow.AddDataConsumer(iec_path.upper(), item) + self.ParentWindow.AddDataConsumer(iec_path.upper(), item, True) item.RefreshVariableType() def ResetItemsData(self): diff -r 72a826dfcfbb -r 02fe382c4511 controls/DebugVariablePanel/__init__.py --- a/controls/DebugVariablePanel/__init__.py Wed Jul 31 10:45:07 2013 +0900 +++ b/controls/DebugVariablePanel/__init__.py Mon Nov 18 12:12:31 2013 +0900 @@ -1,4 +1,1 @@ -try: - from DebugVariableGraphicPanel import DebugVariableGraphicPanel as DebugVariablePanel -except: - from DebugVariableTablePanel import DebugVariableTablePanel as DebugVariablePanel \ No newline at end of file +from DebugVariablePanel import DebugVariablePanel \ No newline at end of file diff -r 72a826dfcfbb -r 02fe382c4511 controls/PouInstanceVariablesPanel.py --- a/controls/PouInstanceVariablesPanel.py Wed Jul 31 10:45:07 2013 +0900 +++ b/controls/PouInstanceVariablesPanel.py Mon Nov 18 12:12:31 2013 +0900 @@ -22,22 +22,98 @@ #License along with this library; if not, write to the Free Software #Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +from collections import namedtuple + import wx +import wx.lib.agw.customtreectrl as CT import wx.lib.buttons -import wx.lib.agw.customtreectrl as CT - -try: - import matplotlib - matplotlib.use('WX') - USE_MPL = True -except: - USE_MPL = False + +# Customize CustomTreeItem for adding icon on item right +CT.GenericTreeItem._rightimages = [] + +def SetRightImages(self, images): + self._rightimages = images +CT.GenericTreeItem.SetRightImages = SetRightImages + +def GetRightImages(self): + return self._rightimages +CT.GenericTreeItem.GetRightImages = GetRightImages + + +class CustomTreeCtrlWithRightImage(CT.CustomTreeCtrl): + + def SetRightImageList(self, imageList): + self._imageListRight = imageList + + def GetLineHeight(self, item): + height = CT.CustomTreeCtrl.GetLineHeight(self, item) + rightimages = item.GetRightImages() + if len(rightimages) > 0: + r_image_w, r_image_h = self._imageListRight.GetSize(rightimages[0]) + return max(height, r_image_h + 8) + return height + + def GetItemRightImagesBBox(self, item): + rightimages = item.GetRightImages() + if len(rightimages) > 0: + w, h = self.GetClientSize() + total_h = self.GetLineHeight(item) + r_image_w, r_image_h = self._imageListRight.GetSize(rightimages[0]) + + bbox_width = (r_image_w + 4) * len(rightimages) + 4 + bbox_height = r_image_h + 8 + bbox_x = w - bbox_width + bbox_y = item.GetY() + ((total_h > r_image_h) and [(total_h-r_image_h)/2] or [0])[0] + + return wx.Rect(bbox_x, bbox_y, bbox_width, bbox_height) + + return None + + def IsOverItemRightImage(self, item, point): + rightimages = item.GetRightImages() + if len(rightimages) > 0: + point = self.CalcUnscrolledPosition(point) + r_image_w, r_image_h = self._imageListRight.GetSize(rightimages[0]) + images_bbx = self.GetItemRightImagesBBox(item) + + rect = wx.Rect(images_bbx.x + 4, images_bbx.y + 4, + r_image_w, r_image_h) + for r_image in rightimages: + if rect.Inside(point): + return r_image + rect.x += r_image_w + 4 + + return None + + def PaintItem(self, item, dc, level, align): + CT.CustomTreeCtrl.PaintItem(self, item, dc, level, align) + + rightimages = item.GetRightImages() + if len(rightimages) > 0: + images_bbx = self.GetItemRightImagesBBox(item) + r_image_w, r_image_h = self._imageListRight.GetSize(rightimages[0]) + + dc.SetBrush(wx.WHITE_BRUSH) + dc.SetPen(wx.TRANSPARENT_PEN) + + bg_width = (r_image_w + 4) * len(rightimages) + 4 + bg_height = r_image_h + 8 + dc.DrawRectangle(images_bbx.x, images_bbx.y, + images_bbx.width, images_bbx.height) + x_pos = images_bbx.x + 4 + for r_image in rightimages: + self._imageListRight.Draw( + r_image, dc, x_pos, images_bbx.y + 4, + wx.IMAGELIST_DRAW_TRANSPARENT) + x_pos += r_image_w + 4 + +_ButtonCallbacks = namedtuple("ButtonCallbacks", ["leftdown", "dclick"]) from PLCControler import ITEMS_VARIABLE, ITEM_CONFIGURATION, ITEM_RESOURCE, ITEM_POU, ITEM_TRANSITION, ITEM_ACTION from util.BitmapLibrary import GetBitmap class PouInstanceVariablesPanel(wx.Panel): - + def __init__(self, parent, window, controller, debug): wx.Panel.__init__(self, name='PouInstanceTreePanel', parent=parent, pos=wx.Point(0, 0), @@ -59,7 +135,7 @@ self.Bind(wx.EVT_BUTTON, self.OnDebugButtonClick, self.DebugButton) - self.VariablesList = CT.CustomTreeCtrl(self, + self.VariablesList = CustomTreeCtrlWithRightImage(self, style=wx.SUNKEN_BORDER, agwStyle=CT.TR_NO_BUTTONS| CT.TR_SINGLE| @@ -75,6 +151,17 @@ self.VariablesList.Bind(wx.EVT_LEFT_DOWN, self.OnVariablesListLeftDown) self.VariablesList.Bind(wx.EVT_KEY_DOWN, self.OnVariablesListKeyDown) + self.TreeRightImageList = wx.ImageList(24, 24) + self.EditImage = self.TreeRightImageList.Add(GetBitmap("edit")) + self.DebugInstanceImage = self.TreeRightImageList.Add(GetBitmap("debug_instance")) + self.VariablesList.SetRightImageList(self.TreeRightImageList) + + self.ButtonCallBacks = { + self.EditImage: _ButtonCallbacks( + self.EditButtonCallback, None), + self.DebugInstanceImage: _ButtonCallbacks( + self.DebugButtonCallback, self.DebugButtonDClickCallback)} + buttons_sizer = wx.FlexGridSizer(cols=3, hgap=0, rows=1, vgap=0) buttons_sizer.AddWindow(self.ParentButton) buttons_sizer.AddWindow(self.InstanceChoice, flag=wx.GROW) @@ -147,56 +234,22 @@ self.PouInfos = None if self.PouInfos is not None: root = self.VariablesList.AddRoot("") - for var_infos in self.PouInfos["variables"]: - if var_infos.get("type", None) is not None: - text = "%(name)s (%(type)s)" % var_infos + for var_infos in self.PouInfos.variables: + if var_infos.type is not None: + text = "%s (%s)" % (var_infos.name, var_infos.type) else: - text = var_infos["name"] - - panel = wx.Panel(self.VariablesList) - - buttons = [] - if var_infos["class"] in ITEMS_VARIABLE: - if (not USE_MPL and var_infos["debug"] and self.Debug and - (self.Controller.IsOfType(var_infos["type"], "ANY_NUM", True) or - self.Controller.IsOfType(var_infos["type"], "ANY_BIT", True))): - graph_button = wx.lib.buttons.GenBitmapButton(panel, - bitmap=GetBitmap("instance_graph"), - size=wx.Size(28, 28), style=wx.NO_BORDER) - self.Bind(wx.EVT_BUTTON, self.GenGraphButtonCallback(var_infos), graph_button) - buttons.append(graph_button) - elif var_infos["edit"]: - edit_button = wx.lib.buttons.GenBitmapButton(panel, - bitmap=GetBitmap("edit"), - size=wx.Size(28, 28), style=wx.NO_BORDER) - self.Bind(wx.EVT_BUTTON, self.GenEditButtonCallback(var_infos), edit_button) - buttons.append(edit_button) - - if var_infos["debug"] and self.Debug: - debug_button = wx.lib.buttons.GenBitmapButton(panel, - bitmap=GetBitmap("debug_instance"), - size=wx.Size(28, 28), style=wx.NO_BORDER) - self.Bind(wx.EVT_BUTTON, self.GenDebugButtonCallback(var_infos), debug_button) - debug_button.Bind(wx.EVT_LEFT_DCLICK, self.GenDebugButtonDClickCallback(var_infos)) - buttons.append(debug_button) - - button_num = len(buttons) - if button_num > 0: - panel.SetSize(wx.Size(button_num * 32, 28)) - panel.SetBackgroundColour(self.VariablesList.GetBackgroundColour()) - panel_sizer = wx.BoxSizer(wx.HORIZONTAL) - panel.SetSizer(panel_sizer) - - for button in buttons: - panel_sizer.AddWindow(button, 0, border=4, flag=wx.LEFT) - panel_sizer.Layout() - - else: - panel.Destroy() - panel = None - - item = self.VariablesList.AppendItem(root, text, wnd=panel) - self.VariablesList.SetItemImage(item, self.ParentWindow.GetTreeImage(var_infos["class"])) + text = var_infos.name + + right_images = [] + if var_infos.edit: + right_images.append(self.EditImage) + + if var_infos.debug and self.Debug: + right_images.append(self.DebugInstanceImage) + + item = self.VariablesList.AppendItem(root, text) + item.SetRightImages(right_images) + self.VariablesList.SetItemImage(item, self.ParentWindow.GetTreeImage(var_infos.var_class)) self.VariablesList.SetPyData(item, var_infos) self.RefreshInstanceChoice() @@ -213,7 +266,7 @@ self.InstanceChoice.Append(instance) if len(instances) == 1: self.PouInstance = instances[0] - if self.PouInfos["class"] in [ITEM_CONFIGURATION, ITEM_RESOURCE]: + if self.PouInfos.var_class in [ITEM_CONFIGURATION, ITEM_RESOURCE]: self.PouInstance = None self.InstanceChoice.SetSelection(0) elif self.PouInstance in instances: @@ -224,8 +277,8 @@ def RefreshButtons(self): enabled = self.InstanceChoice.GetSelection() != -1 - self.ParentButton.Enable(enabled and self.PouInfos["class"] != ITEM_CONFIGURATION) - self.DebugButton.Enable(enabled and self.PouInfos["debug"] and self.Debug) + self.ParentButton.Enable(enabled and self.PouInfos.var_class != ITEM_CONFIGURATION) + self.DebugButton.Enable(enabled and self.PouInfos.debug and self.Debug) root = self.VariablesList.GetRootItem() if root is not None and root.IsOk(): @@ -238,79 +291,60 @@ child.Enable(enabled) item, item_cookie = self.VariablesList.GetNextChild(root, item_cookie) - def GenEditButtonCallback(self, infos): - def EditButtonCallback(event): - var_class = infos["class"] - if var_class == ITEM_RESOURCE: - tagname = self.Controller.ComputeConfigurationResourceName( - self.InstanceChoice.GetStringSelection(), - infos["name"]) + def EditButtonCallback(self, infos): + var_class = infos.var_class + if var_class == ITEM_RESOURCE: + tagname = self.Controller.ComputeConfigurationResourceName( + self.InstanceChoice.GetStringSelection(), + infos.name) + elif var_class == ITEM_TRANSITION: + tagname = self.Controller.ComputePouTransitionName( + self.PouTagName.split("::")[1], + infos.name) + elif var_class == ITEM_ACTION: + tagname = self.Controller.ComputePouActionName( + self.PouTagName.split("::")[1], + infos.name) + else: + var_class = ITEM_POU + tagname = self.Controller.ComputePouName(infos.type) + self.ParentWindow.EditProjectElement(var_class, tagname) + + def DebugButtonCallback(self, infos): + if self.InstanceChoice.GetSelection() != -1: + var_class = infos.var_class + var_path = "%s.%s" % (self.InstanceChoice.GetStringSelection(), + infos.name) + if var_class in ITEMS_VARIABLE: + self.ParentWindow.AddDebugVariable(var_path, force=True) elif var_class == ITEM_TRANSITION: - tagname = self.Controller.ComputePouTransitionName( - self.PouTagName.split("::")[1], - infos["name"]) + self.ParentWindow.OpenDebugViewer( + var_class, + var_path, + self.Controller.ComputePouTransitionName( + self.PouTagName.split("::")[1], + infos.name)) elif var_class == ITEM_ACTION: - tagname = self.Controller.ComputePouActionName( - self.PouTagName.split("::")[1], - infos["name"]) + self.ParentWindow.OpenDebugViewer( + var_class, + var_path, + self.Controller.ComputePouActionName( + self.PouTagName.split("::")[1], + infos.name)) else: - var_class = ITEM_POU - tagname = self.Controller.ComputePouName(infos["type"]) - self.ParentWindow.EditProjectElement(var_class, tagname) - event.Skip() - return EditButtonCallback - - def GenDebugButtonCallback(self, infos): - def DebugButtonCallback(event): - if self.InstanceChoice.GetSelection() != -1: - var_class = infos["class"] - var_path = "%s.%s" % (self.InstanceChoice.GetStringSelection(), - infos["name"]) - if var_class in ITEMS_VARIABLE: - self.ParentWindow.AddDebugVariable(var_path, force=True) - elif var_class == ITEM_TRANSITION: - self.ParentWindow.OpenDebugViewer( - var_class, - var_path, - self.Controller.ComputePouTransitionName( - self.PouTagName.split("::")[1], - infos["name"])) - elif var_class == ITEM_ACTION: - self.ParentWindow.OpenDebugViewer( - var_class, - var_path, - self.Controller.ComputePouActionName( - self.PouTagName.split("::")[1], - infos["name"])) - else: - self.ParentWindow.OpenDebugViewer( - var_class, - var_path, - self.Controller.ComputePouName(infos["type"])) - event.Skip() - return DebugButtonCallback - - def GenDebugButtonDClickCallback(self, infos): - def DebugButtonDClickCallback(event): - if self.InstanceChoice.GetSelection() != -1: - if infos["class"] in ITEMS_VARIABLE: - self.ParentWindow.AddDebugVariable( - "%s.%s" % (self.InstanceChoice.GetStringSelection(), - infos["name"]), - force=True, - graph=True) - event.Skip() - return DebugButtonDClickCallback - - def GenGraphButtonCallback(self, infos): - def GraphButtonCallback(event): - if self.InstanceChoice.GetSelection() != -1: - if infos["class"] in ITEMS_VARIABLE: - var_path = "%s.%s" % (self.InstanceChoice.GetStringSelection(), - infos["name"]) - self.ParentWindow.OpenDebugViewer(infos["class"], var_path, infos["type"]) - event.Skip() - return GraphButtonCallback + self.ParentWindow.OpenDebugViewer( + var_class, + var_path, + self.Controller.ComputePouName(infos.type)) + + def DebugButtonDClickCallback(self, infos): + if self.InstanceChoice.GetSelection() != -1: + if infos.var_class in ITEMS_VARIABLE: + self.ParentWindow.AddDebugVariable( + "%s.%s" % (self.InstanceChoice.GetStringSelection(), + infos.name), + force=True, + graph=True) def ShowInstanceChoicePopup(self): self.InstanceChoice.SetFocusFromKbd() @@ -339,33 +373,42 @@ def OnDebugButtonClick(self, event): if self.InstanceChoice.GetSelection() != -1: self.ParentWindow.OpenDebugViewer( - self.PouInfos["class"], + self.PouInfos.var_class, self.InstanceChoice.GetStringSelection(), self.PouTagName) event.Skip() - + def OnVariablesListItemActivated(self, event): selected_item = event.GetItem() if selected_item is not None and selected_item.IsOk(): item_infos = self.VariablesList.GetPyData(selected_item) - if item_infos is not None and item_infos["class"] not in ITEMS_VARIABLE: - instance_path = self.InstanceChoice.GetStringSelection() - if item_infos["class"] == ITEM_RESOURCE: - if instance_path != "": - tagname = self.Controller.ComputeConfigurationResourceName( - instance_path, - item_infos["name"]) + if item_infos is not None: + + item_button = self.VariablesList.IsOverItemRightImage( + selected_item, event.GetPoint()) + if item_button is not None: + callback = self.ButtonCallBacks[item_button].dclick + if callback is not None: + callback(item_infos) + + elif item_infos.var_class not in ITEMS_VARIABLE: + instance_path = self.InstanceChoice.GetStringSelection() + if item_infos.var_class == ITEM_RESOURCE: + if instance_path != "": + tagname = self.Controller.ComputeConfigurationResourceName( + instance_path, + item_infos.name) + else: + tagname = None else: - tagname = None - else: - tagname = self.Controller.ComputePouName(item_infos["type"]) - if tagname is not None: - if instance_path != "": - item_path = "%s.%s" % (instance_path, item_infos["name"]) - else: - item_path = None - self.SetPouType(tagname, item_path) - self.ParentWindow.SelectProjectTreeItem(tagname) + tagname = self.Controller.ComputePouName(item_infos.type) + if tagname is not None: + if instance_path != "": + item_path = "%s.%s" % (instance_path, item_infos.name) + else: + item_path = None + self.SetPouType(tagname, item_path) + self.ParentWindow.SelectProjectTreeItem(tagname) event.Skip() def OnVariablesListLeftDown(self, event): @@ -374,16 +417,26 @@ else: instance_path = self.InstanceChoice.GetStringSelection() item, flags = self.VariablesList.HitTest(event.GetPosition()) - if item is not None and flags & CT.TREE_HITTEST_ONITEMLABEL: + if item is not None: item_infos = self.VariablesList.GetPyData(item) - if item_infos is not None and item_infos["class"] in ITEMS_VARIABLE: - self.ParentWindow.EnsureTabVisible( - self.ParentWindow.DebugVariablePanel) - item_path = "%s.%s" % (instance_path, item_infos["name"]) - data = wx.TextDataObject(str((item_path, "debug"))) - dragSource = wx.DropSource(self.VariablesList) - dragSource.SetData(data) - dragSource.DoDragDrop() + if item_infos is not None: + + item_button = self.VariablesList.IsOverItemRightImage( + item, event.GetPosition()) + if item_button is not None: + callback = self.ButtonCallBacks[item_button].leftdown + if callback is not None: + callback(item_infos) + + elif (flags & CT.TREE_HITTEST_ONITEMLABEL and + item_infos.var_class in ITEMS_VARIABLE): + self.ParentWindow.EnsureTabVisible( + self.ParentWindow.DebugVariablePanel) + item_path = "%s.%s" % (instance_path, item_infos.name) + data = wx.TextDataObject(str((item_path, "debug"))) + dragSource = wx.DropSource(self.VariablesList) + dragSource.SetData(data) + dragSource.DoDragDrop() event.Skip() def OnVariablesListKeyDown(self, event): diff -r 72a826dfcfbb -r 02fe382c4511 controls/VariablePanel.py --- a/controls/VariablePanel.py Wed Jul 31 10:45:07 2013 +0900 +++ b/controls/VariablePanel.py Mon Nov 18 12:12:31 2013 +0900 @@ -37,6 +37,7 @@ from CustomTable import CustomTable from LocationCellEditor import LocationCellEditor from util.BitmapLibrary import GetBitmap +from PLCControler import _VariableInfos #------------------------------------------------------------------------------- # Helpers @@ -105,12 +106,22 @@ CustomTable.__init__(self, parent, data, colnames) self.old_value = None + def GetValueByName(self, row, colname): + if row < self.GetNumberRows(): + return getattr(self.data[row], colname) + + def SetValueByName(self, row, colname, value): + if row < self.GetNumberRows(): + setattr(self.data[row], colname, value) + def GetValue(self, row, col): if row < self.GetNumberRows(): if col == 0: - return self.data[row]["Number"] + return self.data[row].Number colname = self.GetColLabelValue(col, False) - value = self.data[row].get(colname, "") + if colname == "Initial Value": + colname = "InitialValue" + value = getattr(self.data[row], colname, "") if colname == "Type" and isinstance(value, TupleType): if value[0] == "array": return "ARRAY [%s] OF %s" % (",".join(map(lambda x : "..".join(x), value[2])), value[1]) @@ -124,15 +135,17 @@ if col < len(self.colnames): colname = self.GetColLabelValue(col, False) if colname == "Name": - self.old_value = self.data[row][colname] + self.old_value = getattr(self.data[row], colname) elif colname == "Class": value = VARIABLE_CLASSES_DICT[value] self.SetValueByName(row, "Option", CheckOptionForClass[value](self.GetValueByName(row, "Option"))) if value == "External": - self.SetValueByName(row, "Initial Value", "") + self.SetValueByName(row, "InitialValue", "") elif colname == "Option": value = OPTIONS_DICT[value] - self.data[row][colname] = value + elif colname == "Initial Value": + colname = "InitialValue" + setattr(self.data[row], colname, value) def GetOldValue(self): return self.old_value @@ -173,7 +186,7 @@ if var_class not in ["External", "InOut"]: if self.Parent.Controler.IsEnumeratedType(var_type): editor = wx.grid.GridCellChoiceEditor() - editor.SetParameters(",".join(self.Parent.Controler.GetEnumeratedDataValues(var_type))) + editor.SetParameters(",".join([""] + self.Parent.Controler.GetEnumeratedDataValues(var_type))) else: editor = wx.grid.GridCellTextEditor() renderer = wx.grid.GridCellStringRenderer() @@ -314,8 +327,8 @@ for name in self.ParentWindow.Controler.\ GetEditedElementVariables(tagname, self.ParentWindow.Debug)]: var_infos = self.ParentWindow.DefaultValue.copy() - var_infos["Name"] = var_name - var_infos["Type"] = values[2] + var_infos.Name = var_name + var_infos.Type = values[2] if values[1] == "location": location = values[0] if not location.startswith("%"): @@ -346,16 +359,16 @@ GetConfigurationVariableNames(configs[0])]: self.ParentWindow.Controler.AddConfigurationGlobalVar( configs[0], values[2], var_name, location, "") - var_infos["Class"] = "External" + var_infos.Class = "External" else: if element_type == "program": - var_infos["Class"] = "Local" + var_infos.Class = "Local" else: - var_infos["Class"] = "Global" - var_infos["Location"] = location + var_infos.Class = "Global" + var_infos.Location = location else: - var_infos["Class"] = "External" - var_infos["Number"] = len(self.ParentWindow.Values) + var_infos.Class = "External" + var_infos.Number = len(self.ParentWindow.Values) self.ParentWindow.Values.append(var_infos) self.ParentWindow.SaveValues() self.ParentWindow.RefreshValues() @@ -447,17 +460,8 @@ self.FilterChoices = [] self.FilterChoiceTransfer = GetFilterChoiceTransfer() - self.DefaultValue = { - "Name" : "", - "Class" : "", - "Type" : "INT", - "Location" : "", - "Initial Value" : "", - "Option" : "", - "Documentation" : "", - "Edit" : True - } - + self.DefaultValue = _VariableInfos("", "", "", "", "", True, "", "INT", ([], []), 0) + if element_type in ["config", "resource"]: self.DefaultTypes = {"All" : "Global"} else: @@ -503,7 +507,10 @@ # Num Name Class Type Init Option Doc self.ColSizes = [40, 80, 70, 80, 80, 100, 160] self.ColAlignements = [c, l, l, l, l, l, l] - + + self.ElementType = element_type + self.BodyType = None + for choice in self.FilterChoices: self.ClassFilter.Append(_(choice)) @@ -524,32 +531,32 @@ if new_row > 0: row_content = self.Values[new_row - 1].copy() - result = VARIABLE_NAME_SUFFIX_MODEL.search(row_content["Name"]) + result = VARIABLE_NAME_SUFFIX_MODEL.search(row_content.Name) if result is not None: - name = row_content["Name"][:result.start(1)] + name = row_content.Name[:result.start(1)] suffix = result.group(1) if suffix != "": start_idx = int(suffix) else: start_idx = 0 else: - name = row_content["Name"] + name = row_content.Name start_idx = 0 else: row_content = None start_idx = 0 name = "LocalVar" - if row_content is not None and row_content["Edit"]: + if row_content is not None and row_content.Edit: row_content = self.Values[new_row - 1].copy() else: row_content = self.DefaultValue.copy() if self.Filter in self.DefaultTypes: - row_content["Class"] = self.DefaultTypes[self.Filter] + row_content.Class = self.DefaultTypes[self.Filter] else: - row_content["Class"] = self.Filter + row_content.Class = self.Filter - row_content["Name"] = self.Controler.GenerateNewName( + row_content.Name = self.Controler.GenerateNewName( self.TagName, None, name + "%d", start_idx) if self.Filter == "All" and len(self.Values) > 0: @@ -566,6 +573,8 @@ if self.Table.GetValueByName(row, "Edit"): self.Values.remove(self.Table.GetRow(row)) self.SaveValues() + if self.ElementType == "resource": + self.ParentWindow.RefreshView(variablepanel = False) self.RefreshValues() setattr(self.VariablesGrid, "_DeleteRow", _DeleteVariable) @@ -608,17 +617,16 @@ def SetTagName(self, tagname): self.TagName = tagname + self.BodyType = self.Controler.GetEditedElementBodyType(self.TagName) def GetTagName(self): return self.TagName def IsFunctionBlockType(self, name): - bodytype = self.Controler.GetEditedElementBodyType(self.TagName) - pouname, poutype = self.Controler.GetEditedElementType(self.TagName) - if poutype != "function" and bodytype in ["ST", "IL"]: + if self.ElementType != "function" and self.BodyType in ["ST", "IL"]: return False else: - return name in self.Controler.GetFunctionBlockTypes(self.TagName) + return self.Controler.GetBlockType(name, debug=self.Debug) is not None def RefreshView(self): self.PouNames = self.Controler.GetProjectPouNames(self.Debug) @@ -635,9 +643,9 @@ self.ReturnType.Clear() for data_type in self.Controler.GetDataTypes(self.TagName, debug=self.Debug): self.ReturnType.Append(data_type) - returnType = self.Controler.GetEditedElementInterfaceReturnType(self.TagName) + returnType = self.Controler.GetEditedElementInterfaceReturnType(self.TagName, debug=self.Debug) description = self.Controler.GetPouDescription(words[1]) - self.Values = self.Controler.GetEditedElementInterfaceVars(self.TagName, self.Debug) + self.Values = self.Controler.GetEditedElementInterfaceVars(self.TagName, debug=self.Debug) if returnType is not None: self.ReturnType.SetStringSelection(returnType) @@ -710,7 +718,7 @@ message = _("\"%s\" is a keyword. It can't be used!") % value elif value.upper() in self.PouNames: message = _("A POU named \"%s\" already exists!") % value - elif value.upper() in [var["Name"].upper() for var in self.Values if var != self.Table.data[row]]: + elif value.upper() in [var.Name.upper() for var in self.Values if var != self.Table.data[row]]: message = _("A variable with \"%s\" as name already exists in this pou!") % value else: self.SaveValues(False) @@ -844,8 +852,8 @@ def RefreshValues(self): data = [] for num, variable in enumerate(self.Values): - if variable["Class"] in self.ClassList: - variable["Number"] = num + 1 + if variable.Class in self.ClassList: + variable.Number = num + 1 data.append(variable) self.Table.SetData(data) self.Table.ResetView(self.VariablesGrid) diff -r 72a826dfcfbb -r 02fe382c4511 dialogs/ActionBlockDialog.py --- a/dialogs/ActionBlockDialog.py Wed Jul 31 10:45:07 2013 +0900 +++ b/dialogs/ActionBlockDialog.py Mon Nov 18 12:12:31 2013 +0900 @@ -27,6 +27,7 @@ from controls import CustomGrid, CustomTable from util.BitmapLibrary import GetBitmap +from PLCControler import _ActionInfos #------------------------------------------------------------------------------- # Helpers @@ -49,17 +50,19 @@ def GetValue(self, row, col): if row < self.GetNumberRows(): colname = self.GetColLabelValue(col, False) - name = str(self.data[row].get(colname, "")) + value = getattr(self.data[row], colname.lower()) if colname == "Type": - return _(name) - return name + return _(value) + return value def SetValue(self, row, col, value): if col < len(self.colnames): colname = self.GetColLabelValue(col, False) if colname == "Type": value = self.Parent.TranslateType[value] - self.data[row][colname] = value + elif colname == "Qualifier" and not self.Parent.DurationList[value]: + self.data[row].duration = "" + setattr(self.data[row], colname.lower(), value) def _updateColAttrs(self, grid): """ @@ -81,23 +84,19 @@ if colname == "Duration": editor = wx.grid.GridCellTextEditor() renderer = wx.grid.GridCellStringRenderer() - if self.Parent.DurationList[self.data[row]["Qualifier"]]: - readonly = False - else: - readonly = True - self.data[row]["Duration"] = "" + readonly = not self.Parent.DurationList[self.data[row].qualifier] elif colname == "Type": editor = wx.grid.GridCellChoiceEditor() editor.SetParameters(self.Parent.TypeList) elif colname == "Value": - type = self.data[row]["Type"] - if type == "Action": + value_type = self.data[row].type + if value_type == "Action": editor = wx.grid.GridCellChoiceEditor() editor.SetParameters(self.Parent.ActionList) - elif type == "Variable": + elif value_type == "Variable": editor = wx.grid.GridCellChoiceEditor() editor.SetParameters(self.Parent.VariableList) - elif type == "Inline": + elif value_type == "Inline": editor = wx.grid.GridCellTextEditor() renderer = wx.grid.GridCellStringRenderer() elif colname == "Indicator": @@ -168,11 +167,7 @@ self.ColAlignements = [wx.ALIGN_LEFT, wx.ALIGN_LEFT, wx.ALIGN_LEFT, wx.ALIGN_LEFT, wx.ALIGN_LEFT] self.ActionsGrid.SetTable(self.Table) - self.ActionsGrid.SetDefaultValue({"Qualifier" : "N", - "Duration" : "", - "Type" : "Action", - "Value" : "", - "Indicator" : ""}) + self.ActionsGrid.SetDefaultValue(_ActionInfos("N", "Action", "", "", "")) self.ActionsGrid.SetButtons({"Add": self.AddButton, "Delete": self.DeleteButton, "Up": self.UpButton, @@ -199,35 +194,24 @@ event.Skip() def SetQualifierList(self, list): - self.QualifierList = "," + ",".join(list) + self.QualifierList = ",".join(list) self.DurationList = list def SetVariableList(self, list): - self.VariableList = "," + ",".join([variable["Name"] for variable in list]) + self.VariableList = "," + ",".join([variable.Name for variable in list]) def SetActionList(self, list): self.ActionList = "," + ",".join(list) def SetValues(self, actions): for action in actions: - row = {"Qualifier" : action["qualifier"], "Value" : action["value"]} - if action["type"] == "reference": - if action["value"] in self.ActionList: - row["Type"] = "Action" - elif action["value"] in self.VariableList: - row["Type"] = "Variable" - else: - row["Type"] = "Inline" + row = action.copy() + if row.type == "reference" and row.value in self.ActionList: + row.type = "Action" + elif row.type == "reference" and row.value in self.VariableList: + row.type = "Variable" else: - row["Type"] = "Inline" - if "duration" in action: - row["Duration"] = action["duration"] - else: - row["Duration"] = "" - if "indicator" in action: - row["Indicator"] = action["indicator"] - else: - row["Indicator"] = "" + row.type = "Inline" self.Table.AppendRow(row) self.Table.ResetView(self.ActionsGrid) if len(actions) > 0: @@ -235,16 +219,10 @@ self.ActionsGrid.RefreshButtons() def GetValues(self): - values = [] - for data in self.Table.GetData(): - action = {"qualifier" : data["Qualifier"], "value" : data["Value"]} - if data["Type"] in ["Action", "Variable"]: - action["type"] = "reference" + actions = self.Table.GetData() + for action in actions: + if action.type in ["Action", "Variable"]: + action.type = "reference" else: - action["type"] = "inline" - if data["Duration"] != "": - action["duration"] = data["Duration"] - if data["Indicator"] != "": - action["indicator"] = data["Indicator"] - values.append(action) - return values + action.type = "inline" + return actions diff -r 72a826dfcfbb -r 02fe382c4511 dialogs/BlockPreviewDialog.py --- a/dialogs/BlockPreviewDialog.py Wed Jul 31 10:45:07 2013 +0900 +++ b/dialogs/BlockPreviewDialog.py Mon Nov 18 12:12:31 2013 +0900 @@ -170,10 +170,10 @@ """ # Get list of variables defined in POU self.VariableList = { - var["Name"]: (var["Class"], var["Type"]) + var.Name: (var.Class, var.Type) for var in self.Controller.GetEditedElementInterfaceVars( self.TagName) - if var["Edit"]} + if var.Edit} # Add POU name to variable list if POU is a function returntype = self.Controller.GetEditedElementInterfaceReturnType( diff -r 72a826dfcfbb -r 02fe382c4511 dialogs/FBDBlockDialog.py --- a/dialogs/FBDBlockDialog.py Wed Jul 31 10:45:07 2013 +0900 +++ b/dialogs/FBDBlockDialog.py Mon Nov 18 12:12:31 2013 +0900 @@ -160,6 +160,11 @@ # Extract block type defined in parameters blocktype = values.get("type", None) + # Select block type in library panel + if blocktype is not None: + self.LibraryPanel.SelectTreeItem(blocktype, + values.get("inputs", None)) + # Define regular expression for determine if block name is block # default name default_name_model = GetBlockTypeDefaultNameModel(blocktype) @@ -186,11 +191,6 @@ if control is not None: control.SetValue(value) - # Select block type in library panel - if blocktype is not None: - self.LibraryPanel.SelectTreeItem(blocktype, - values.get("inputs", None)) - # Refresh preview panel self.RefreshPreview() diff -r 72a826dfcfbb -r 02fe382c4511 dialogs/LDElementDialog.py --- a/dialogs/LDElementDialog.py Wed Jul 31 10:45:07 2013 +0900 +++ b/dialogs/LDElementDialog.py Mon Nov 18 12:12:31 2013 +0900 @@ -91,7 +91,7 @@ flag=wx.GROW|wx.TOP) # Create a combo box for defining LD element variable - self.ElementVariable = wx.ComboBox(self, style=wx.CB_READONLY|wx.CB_SORT) + self.ElementVariable = wx.ComboBox(self, style=wx.CB_SORT) self.Bind(wx.EVT_COMBOBOX, self.OnVariableChanged, self.ElementVariable) self.LeftGridSizer.AddWindow(self.ElementVariable, border=5, @@ -117,7 +117,6 @@ if (type == "contact" or var_type != "Input") and \ value_type == "BOOL": self.ElementVariable.Append(name) - self.ElementVariable.Enable(self.ElementVariable.GetCount() > 0) # Normal radio button is default control having keyboard focus self.ModifierRadioButtons[element_modifiers[0]].SetFocus() @@ -144,7 +143,7 @@ # Parameter is LD element variable if name == "variable": - self.ElementVariable.SetStringSelection(value) + self.ElementVariable.SetValue(value) # Set value of other controls elif name == "modifier": @@ -189,7 +188,7 @@ self.Element = self.ElementClass( self.Preview, self.GetElementModifier(), - self.ElementVariable.GetStringSelection()) + self.ElementVariable.GetValue()) # Call BlockPreviewDialog function BlockPreviewDialog.RefreshPreview(self) diff -r 72a826dfcfbb -r 02fe382c4511 dialogs/LDPowerRailDialog.py --- a/dialogs/LDPowerRailDialog.py Wed Jul 31 10:45:07 2013 +0900 +++ b/dialogs/LDPowerRailDialog.py Mon Nov 18 12:12:31 2013 +0900 @@ -75,6 +75,7 @@ # Create spin control for defining power rail pin number self.PinNumber = wx.SpinCtrl(self, min=1, max=50, style=wx.SP_ARROW_KEYS) + self.PinNumber.SetValue(1) self.Bind(wx.EVT_SPINCTRL, self.OnPinNumberChanged, self.PinNumber) self.LeftGridSizer.AddWindow(self.PinNumber, flag=wx.GROW) diff -r 72a826dfcfbb -r 02fe382c4511 dialogs/SFCStepNameDialog.py --- a/dialogs/SFCStepNameDialog.py Wed Jul 31 10:45:07 2013 +0900 +++ b/dialogs/SFCStepNameDialog.py Mon Nov 18 12:12:31 2013 +0900 @@ -67,7 +67,7 @@ self.PouNames = [pou_name.upper() for pou_name in pou_names] def SetVariables(self, variables): - self.Variables = [var["Name"].upper() for var in variables] + self.Variables = [var.Name.upper() for var in variables] def SetStepNames(self, step_names): self.StepNames = [step_name.upper() for step_name in step_names] diff -r 72a826dfcfbb -r 02fe382c4511 editors/ConfTreeNodeEditor.py --- a/editors/ConfTreeNodeEditor.py Wed Jul 31 10:45:07 2013 +0900 +++ b/editors/ConfTreeNodeEditor.py Mon Nov 18 12:12:31 2013 +0900 @@ -3,7 +3,6 @@ import types import wx -import wx.lib.buttons from EditorPanel import EditorPanel @@ -35,22 +34,6 @@ def Bpath(*args): return os.path.join(CWD,*args) -# Patch wx.lib.imageutils so that gray is supported on alpha images -import wx.lib.imageutils -from wx.lib.imageutils import grayOut as old_grayOut -def grayOut(anImage): - if anImage.HasAlpha(): - AlphaData = anImage.GetAlphaData() - else : - AlphaData = None - - old_grayOut(anImage) - - if AlphaData is not None: - anImage.SetAlphaData(AlphaData) - -wx.lib.imageutils.grayOut = grayOut - class GenBitmapTextButton(wx.lib.buttons.GenBitmapTextButton): def _GetLabelSize(self): """ used internally """ @@ -333,7 +316,11 @@ else: element_path = element_infos["name"] if element_infos["type"] == "element": - label = element_infos["name"] + name = element_infos["name"] + value = element_infos["value"] + label = _(name) + if value is not None: + label += " - %s" % _(value) staticbox = wx.StaticBox(self.ParamsEditor, label=_(label), size=wx.Size(10, 0)) staticboxsizer = wx.StaticBoxSizer(staticbox, wx.VERTICAL) @@ -509,6 +496,8 @@ def GetChoiceCallBackFunction(self, choicectrl, path): def OnChoiceChanged(event): res = self.SetConfNodeParamsAttribute(path, choicectrl.GetStringSelection()) + if res is None: + res = "" choicectrl.SetStringSelection(res) event.Skip() return OnChoiceChanged diff -r 72a826dfcfbb -r 02fe382c4511 editors/DebugViewer.py --- a/editors/DebugViewer.py Wed Jul 31 10:45:07 2013 +0900 +++ b/editors/DebugViewer.py Mon Nov 18 12:12:31 2013 +0900 @@ -106,7 +106,7 @@ # Subscribe tick to new data producer if producer is not None: - producer.SubscribeDebugIECVariable("__tick__", self) + producer.SubscribeDebugIECVariable("__tick__", self, True) # Unsubscribe tick from old data producer if getattr(self, "DataProducer", None) is not None: @@ -134,7 +134,7 @@ # Save inhibit flag self.Inhibited = inhibit - def AddDataConsumer(self, iec_path, consumer): + def AddDataConsumer(self, iec_path, consumer, buffer_list=False): """ Subscribe data consumer to DataProducer @param iec_path: Path in PLC of variable needed by data consumer @@ -148,7 +148,7 @@ # Subscribe data consumer to DataProducer result = self.DataProducer.SubscribeDebugIECVariable( - iec_path, consumer) + iec_path, consumer, buffer_list) if result is not None and consumer != self: # Store data consumer if successfully subscribed and inform @@ -178,7 +178,7 @@ """ # Subscribe tick if needed if self.SubscribeTick and self.Debug and self.DataProducer is not None: - self.DataProducer.SubscribeDebugIECVariable("__tick__", self) + self.DataProducer.SubscribeDebugIECVariable("__tick__", self, True) def UnsubscribeAllDataConsumers(self, tick=True): """ @@ -214,7 +214,7 @@ # Search for variable informations in project data infos = self.DataProducer.GetInstanceInfos(iec_path) if infos is not None: - return infos["type"] + return infos.type return None @@ -246,7 +246,7 @@ if self.DataProducer is not None: self.DataProducer.ReleaseDebugIECVariable(iec_path) - def NewDataAvailable(self, tick, *args, **kwargs): + def NewDataAvailable(self, ticks, *args, **kwargs): """ Called by DataProducer for each tick captured @param tick: PLC tick captured diff -r 72a826dfcfbb -r 02fe382c4511 editors/GraphicViewer.py --- a/editors/GraphicViewer.py Wed Jul 31 10:45:07 2013 +0900 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,543 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- - -#This file is part of PLCOpenEditor, a library implementing an IEC 61131-3 editor -#based on the plcopen standard. -# -#Copyright (C) 2007: Edouard TISSERANT and Laurent BESSARD -# -#See COPYING file for copyrights details. -# -#This library is free software; you can redistribute it and/or -#modify it under the terms of the GNU General Public -#License as published by the Free Software Foundation; either -#version 2.1 of the License, or (at your option) any later version. -# -#This library is distributed in the hope that it will be useful, -#but WITHOUT ANY WARRANTY; without even the implied warranty of -#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -#General Public License for more details. -# -#You should have received a copy of the GNU General Public -#License along with this library; if not, write to the Free Software -#Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - -import numpy -import math - -import wx -import wx.lib.plot as plot -import wx.lib.buttons - -from graphics.GraphicCommons import MODE_SELECTION, MODE_MOTION -from editors.DebugViewer import DebugViewer -from editors.EditorPanel import EditorPanel -from util.BitmapLibrary import GetBitmap - -colours = ['blue', 'red', 'green', 'yellow', 'orange', 'purple', 'brown', 'cyan', - 'pink', 'grey'] -markers = ['circle', 'dot', 'square', 'triangle', 'triangle_down', 'cross', 'plus', 'circle'] - - -#------------------------------------------------------------------------------- -# Debug Variable Graphic Viewer class -#------------------------------------------------------------------------------- - -SECOND = 1000000000 -MINUTE = 60 * SECOND -HOUR = 60 * MINUTE - -ZOOM_VALUES = map(lambda x:("x %.1f" % x, x), [math.sqrt(2) ** i for i in xrange(8)]) -RANGE_VALUES = map(lambda x: (str(x), x), [25 * 2 ** i for i in xrange(6)]) -TIME_RANGE_VALUES = [("%ds" % i, i * SECOND) for i in (1, 2, 5, 10, 20, 30)] + \ - [("%dm" % i, i * MINUTE) for i in (1, 2, 5, 10, 20, 30)] + \ - [("%dh" % i, i * HOUR) for i in (1, 2, 3, 6, 12, 24)] - -class GraphicViewer(EditorPanel, DebugViewer): - - def _init_Editor(self, prnt): - self.Editor = wx.Panel(prnt) - - main_sizer = wx.FlexGridSizer(cols=1, hgap=0, rows=2, vgap=0) - main_sizer.AddGrowableCol(0) - main_sizer.AddGrowableRow(0) - - self.Canvas = plot.PlotCanvas(self.Editor, name='Canvas') - def _axisInterval(spec, lower, upper): - if spec == 'border': - if lower == upper: - return lower - 0.5, upper + 0.5 - else: - border = (upper - lower) * 0.05 - return lower - border, upper + border - else: - return plot.PlotCanvas._axisInterval(self.Canvas, spec, lower, upper) - self.Canvas._axisInterval = _axisInterval - self.Canvas.SetYSpec('border') - self.Canvas.canvas.Bind(wx.EVT_LEFT_DOWN, self.OnCanvasLeftDown) - self.Canvas.canvas.Bind(wx.EVT_LEFT_UP, self.OnCanvasLeftUp) - self.Canvas.canvas.Bind(wx.EVT_MIDDLE_DOWN, self.OnCanvasMiddleDown) - self.Canvas.canvas.Bind(wx.EVT_MIDDLE_UP, self.OnCanvasMiddleUp) - self.Canvas.canvas.Bind(wx.EVT_MOTION, self.OnCanvasMotion) - self.Canvas.canvas.Bind(wx.EVT_SIZE, self.OnCanvasResize) - main_sizer.AddWindow(self.Canvas, 0, border=0, flag=wx.GROW) - - range_sizer = wx.FlexGridSizer(cols=10, hgap=5, rows=1, vgap=0) - range_sizer.AddGrowableCol(5) - range_sizer.AddGrowableRow(0) - main_sizer.AddSizer(range_sizer, 0, border=5, flag=wx.GROW|wx.ALL) - - range_label = wx.StaticText(self.Editor, label=_('Range:')) - range_sizer.AddWindow(range_label, 0, border=0, flag=wx.ALIGN_CENTER_VERTICAL) - - self.CanvasRange = wx.ComboBox(self.Editor, - size=wx.Size(100, 28), style=wx.CB_READONLY) - self.Bind(wx.EVT_COMBOBOX, self.OnRangeChanged, self.CanvasRange) - range_sizer.AddWindow(self.CanvasRange, 0, border=0, flag=wx.ALIGN_CENTER_VERTICAL) - - zoom_label = wx.StaticText(self.Editor, label=_('Zoom:')) - range_sizer.AddWindow(zoom_label, 0, border=0, flag=wx.ALIGN_CENTER_VERTICAL) - - self.CanvasZoom = wx.ComboBox(self.Editor, - size=wx.Size(70, 28), style=wx.CB_READONLY) - self.Bind(wx.EVT_COMBOBOX, self.OnZoomChanged, self.CanvasZoom) - range_sizer.AddWindow(self.CanvasZoom, 0, border=0, flag=wx.ALIGN_CENTER_VERTICAL) - - position_label = wx.StaticText(self.Editor, label=_('Position:')) - range_sizer.AddWindow(position_label, 0, border=0, flag=wx.ALIGN_CENTER_VERTICAL) - - self.CanvasPosition = wx.ScrollBar(self.Editor, - size=wx.Size(0, 16), style=wx.SB_HORIZONTAL) - self.CanvasPosition.SetScrollbar(0, 10, 100, 10) - self.CanvasPosition.Bind(wx.EVT_SCROLL_THUMBTRACK, - self.OnPositionChanging, self.CanvasPosition) - self.CanvasPosition.Bind(wx.EVT_SCROLL_LINEUP, - self.OnPositionChanging, self.CanvasPosition) - self.CanvasPosition.Bind(wx.EVT_SCROLL_LINEDOWN, - self.OnPositionChanging, self.CanvasPosition) - self.CanvasPosition.Bind(wx.EVT_SCROLL_PAGEUP, - self.OnPositionChanging, self.CanvasPosition) - self.CanvasPosition.Bind(wx.EVT_SCROLL_PAGEDOWN, - self.OnPositionChanging, self.CanvasPosition) - range_sizer.AddWindow(self.CanvasPosition, 0, border=5, flag=wx.GROW|wx.ALL) - - self.ResetButton = wx.lib.buttons.GenBitmapButton(self.Editor, - bitmap=GetBitmap("reset"), size=wx.Size(28, 28), style=wx.NO_BORDER) - self.ResetButton.SetToolTipString(_("Clear the graph values")) - self.Bind(wx.EVT_BUTTON, self.OnResetButton, self.ResetButton) - range_sizer.AddWindow(self.ResetButton, 0, border=0, flag=0) - - self.CurrentButton = wx.lib.buttons.GenBitmapButton(self.Editor, - bitmap=GetBitmap("current"), size=wx.Size(28, 28), style=wx.NO_BORDER) - self.CurrentButton.SetToolTipString(_("Go to current value")) - self.Bind(wx.EVT_BUTTON, self.OnCurrentButton, self.CurrentButton) - range_sizer.AddWindow(self.CurrentButton, 0, border=0, flag=0) - - self.ResetZoomOffsetButton = wx.lib.buttons.GenBitmapButton(self.Editor, - bitmap=GetBitmap("fit"), size=wx.Size(28, 28), style=wx.NO_BORDER) - self.ResetZoomOffsetButton.SetToolTipString(_("Reset zoom and offset")) - self.Bind(wx.EVT_BUTTON, self.OnResetZoomOffsetButton, - self.ResetZoomOffsetButton) - range_sizer.AddWindow(self.ResetZoomOffsetButton, 0, border=0, flag=0) - - self.ExportGraphButton = wx.lib.buttons.GenBitmapButton(self.Editor, - bitmap=GetBitmap("export_graph"), size=wx.Size(28, 28), style=wx.NO_BORDER) - self.ExportGraphButton.SetToolTipString(_("Export graph values to clipboard")) - self.Bind(wx.EVT_BUTTON, self.OnExportGraphButtonClick, - self.ExportGraphButton) - range_sizer.AddWindow(self.ExportGraphButton, 0, border=0, flag=0) - - self.Editor.SetSizer(main_sizer) - - self.Editor.Bind(wx.EVT_MOUSEWHEEL, self.OnCanvasMouseWheel) - - def __init__(self, parent, window, producer, instancepath = ""): - EditorPanel.__init__(self, parent, "", window, None) - DebugViewer.__init__(self, producer, True, False) - - self.InstancePath = instancepath - self.RangeValues = None - self.CursorIdx = None - self.LastCursor = None - self.CurrentMousePos = None - self.CurrentMotionValue = None - self.Dragging = False - - # Initialize Viewer mode to Selection mode - self.Mode = MODE_SELECTION - - self.Data = numpy.array([]).reshape(0, 2) - self.StartTick = 0 - self.StartIdx = 0 - self.EndIdx = 0 - self.MinValue = None - self.MaxValue = None - self.YCenter = 0 - self.CurrentZoom = 1.0 - self.Fixed = False - self.Ticktime = self.DataProducer.GetTicktime() - self.RefreshCanvasRange() - - for zoom_txt, zoom in ZOOM_VALUES: - self.CanvasZoom.Append(zoom_txt) - self.CanvasZoom.SetSelection(0) - - self.AddDataConsumer(self.InstancePath.upper(), self) - - def __del__(self): - DebugViewer.__del__(self) - self.RemoveDataConsumer(self) - - def GetTitle(self): - if len(self.InstancePath) > 15: - return "..." + self.InstancePath[-12:] - return self.InstancePath - - # Changes Viewer mode - def SetMode(self, mode): - if self.Mode != mode or mode == MODE_SELECTION: - if self.Mode == MODE_MOTION: - wx.CallAfter(self.Canvas.canvas.SetCursor, wx.NullCursor) - self.Mode = mode - if self.Mode == MODE_MOTION: - wx.CallAfter(self.Canvas.canvas.SetCursor, wx.StockCursor(wx.CURSOR_HAND)) - - def ResetView(self, register=False): - self.Data = numpy.array([]).reshape(0, 2) - self.StartTick = 0 - self.StartIdx = 0 - self.EndIdx = 0 - self.MinValue = None - self.MaxValue = None - self.CursorIdx = None - self.Fixed = False - self.Ticktime = self.DataProducer.GetTicktime() - if register: - self.AddDataConsumer(self.InstancePath.upper(), self) - self.ResetLastCursor() - self.RefreshCanvasRange() - self.RefreshView() - - def RefreshNewData(self, *args, **kwargs): - self.RefreshView(*args, **kwargs) - DebugViewer.RefreshNewData(self) - - def GetNearestData(self, tick, adjust): - ticks = self.Data[:, 0] - new_cursor = numpy.argmin(abs(ticks - tick)) - if adjust == -1 and ticks[new_cursor] > tick and new_cursor > 0: - new_cursor -= 1 - elif adjust == 1 and ticks[new_cursor] < tick and new_cursor < len(ticks): - new_cursor += 1 - return new_cursor - - def GetBounds(self): - if self.StartIdx is None or self.EndIdx is None: - self.StartIdx = self.GetNearestData(self.StartTick, -1) - self.EndIdx = self.GetNearestData(self.StartTick + self.CurrentRange, 1) - - def ResetBounds(self): - self.StartIdx = None - self.EndIdx = None - - def RefreshCanvasRange(self): - if self.Ticktime == 0 and self.RangeValues != RANGE_VALUES: - self.RangeValues = RANGE_VALUES - self.CanvasRange.Clear() - for text, value in RANGE_VALUES: - self.CanvasRange.Append(text) - self.CanvasRange.SetStringSelection(RANGE_VALUES[0][0]) - self.CurrentRange = RANGE_VALUES[0][1] - elif self.RangeValues != TIME_RANGE_VALUES: - self.RangeValues = TIME_RANGE_VALUES - self.CanvasRange.Clear() - for text, value in TIME_RANGE_VALUES: - self.CanvasRange.Append(text) - self.CanvasRange.SetStringSelection(TIME_RANGE_VALUES[0][0]) - self.CurrentRange = TIME_RANGE_VALUES[0][1] / self.Ticktime - - def RefreshView(self, force=False): - self.Freeze() - if force or not self.Fixed or (len(self.Data) > 0 and self.StartTick + self.CurrentRange > self.Data[-1, 0]): - if (self.MinValue is not None and - self.MaxValue is not None and - self.MinValue != self.MaxValue): - Yrange = float(self.MaxValue - self.MinValue) / self.CurrentZoom - else: - Yrange = 2. / self.CurrentZoom - - if not force and not self.Fixed and len(self.Data) > 0: - self.YCenter = max(self.Data[-1, 1] - Yrange / 2, - min(self.YCenter, - self.Data[-1, 1] + Yrange / 2)) - - var_name = self.InstancePath.split(".")[-1] - - self.GetBounds() - self.VariableGraphic = plot.PolyLine(self.Data[self.StartIdx:self.EndIdx + 1], - legend=var_name, colour=colours[0]) - self.GraphicsObject = plot.PlotGraphics([self.VariableGraphic], _("%s Graphics") % var_name, _("Tick"), _("Values")) - self.Canvas.Draw(self.GraphicsObject, - xAxis=(self.StartTick, self.StartTick + self.CurrentRange), - yAxis=(self.YCenter - Yrange * 1.1 / 2., self.YCenter + Yrange * 1.1 / 2.)) - - # Reset and draw cursor - self.ResetLastCursor() - self.RefreshCursor() - - self.RefreshScrollBar() - - self.Thaw() - - def GetInstancePath(self): - return self.InstancePath - - def IsViewing(self, tagname): - return self.InstancePath == tagname - - def NewValue(self, tick, value, forced=False): - value = {True:1., False:0.}.get(value, float(value)) - self.Data = numpy.append(self.Data, [[float(tick), value]], axis=0) - if self.MinValue is None: - self.MinValue = value - else: - self.MinValue = min(self.MinValue, value) - if self.MaxValue is None: - self.MaxValue = value - else: - self.MaxValue = max(self.MaxValue, value) - if not self.Fixed or tick < self.StartTick + self.CurrentRange: - self.GetBounds() - while int(self.Data[self.StartIdx, 0]) < tick - self.CurrentRange: - self.StartIdx += 1 - self.EndIdx += 1 - self.StartTick = self.Data[self.StartIdx, 0] - self.NewDataAvailable(None) - - def RefreshScrollBar(self): - if len(self.Data) > 0: - self.GetBounds() - pos = int(self.Data[self.StartIdx, 0] - self.Data[0, 0]) - range = int(self.Data[-1, 0] - self.Data[0, 0]) - else: - pos = 0 - range = 0 - self.CanvasPosition.SetScrollbar(pos, self.CurrentRange, range, self.CurrentRange) - - def RefreshRange(self): - if len(self.Data) > 0: - if self.Fixed and self.Data[-1, 0] - self.Data[0, 0] < self.CurrentRange: - self.Fixed = False - self.ResetBounds() - if self.Fixed: - self.StartTick = min(self.StartTick, self.Data[-1, 0] - self.CurrentRange) - else: - self.StartTick = max(self.Data[0, 0], self.Data[-1, 0] - self.CurrentRange) - self.RefreshView(True) - - def OnRangeChanged(self, event): - try: - if self.Ticktime == 0: - self.CurrentRange = self.RangeValues[self.CanvasRange.GetSelection()][1] - else: - self.CurrentRange = self.RangeValues[self.CanvasRange.GetSelection()][1] / self.Ticktime - except ValueError, e: - self.CanvasRange.SetValue(str(self.CurrentRange)) - wx.CallAfter(self.RefreshRange) - event.Skip() - - def OnZoomChanged(self, event): - self.CurrentZoom = ZOOM_VALUES[self.CanvasZoom.GetSelection()][1] - wx.CallAfter(self.RefreshView, True) - event.Skip() - - def OnPositionChanging(self, event): - if len(self.Data) > 0: - self.ResetBounds() - self.StartTick = self.Data[0, 0] + event.GetPosition() - self.Fixed = True - self.NewDataAvailable(None, True) - event.Skip() - - def OnResetButton(self, event): - self.Fixed = False - self.ResetView() - event.Skip() - - def OnCurrentButton(self, event): - if len(self.Data) > 0: - self.ResetBounds() - self.StartTick = max(self.Data[0, 0], self.Data[-1, 0] - self.CurrentRange) - self.Fixed = False - self.NewDataAvailable(None, True) - event.Skip() - - def OnResetZoomOffsetButton(self, event): - if len(self.Data) > 0: - self.YCenter = (self.MaxValue + self.MinValue) / 2 - else: - self.YCenter = 0.0 - self.CurrentZoom = 1.0 - self.CanvasZoom.SetSelection(0) - wx.CallAfter(self.RefreshView, True) - event.Skip() - - def OnExportGraphButtonClick(self, event): - data_copy = self.Data[:] - text = "tick;%s;\n" % self.InstancePath - for tick, value in data_copy: - text += "%d;%.3f;\n" % (tick, value) - self.ParentWindow.SetCopyBuffer(text) - event.Skip() - - def OnCanvasLeftDown(self, event): - self.Fixed = True - self.Canvas.canvas.CaptureMouse() - if len(self.Data) > 0: - if self.Mode == MODE_SELECTION: - self.Dragging = True - pos = self.Canvas.PositionScreenToUser(event.GetPosition()) - self.CursorIdx = self.GetNearestData(pos[0], -1) - self.RefreshCursor() - elif self.Mode == MODE_MOTION: - self.GetBounds() - self.CurrentMousePos = event.GetPosition() - self.CurrentMotionValue = self.Data[self.StartIdx, 0] - event.Skip() - - def OnCanvasLeftUp(self, event): - self.Dragging = False - if self.Mode == MODE_MOTION: - self.CurrentMousePos = None - self.CurrentMotionValue = None - if self.Canvas.canvas.HasCapture(): - self.Canvas.canvas.ReleaseMouse() - event.Skip() - - def OnCanvasMiddleDown(self, event): - self.Fixed = True - self.Canvas.canvas.CaptureMouse() - if len(self.Data) > 0: - self.GetBounds() - self.CurrentMousePos = event.GetPosition() - self.CurrentMotionValue = self.Data[self.StartIdx, 0] - event.Skip() - - def OnCanvasMiddleUp(self, event): - self.CurrentMousePos = None - self.CurrentMotionValue = None - if self.Canvas.canvas.HasCapture(): - self.Canvas.canvas.ReleaseMouse() - event.Skip() - - def OnCanvasMotion(self, event): - if self.Mode == MODE_SELECTION and self.Dragging: - pos = self.Canvas.PositionScreenToUser(event.GetPosition()) - graphics, xAxis, yAxis = self.Canvas.last_draw - self.CursorIdx = self.GetNearestData(max(xAxis[0], min(pos[0], xAxis[1])), -1) - self.RefreshCursor() - elif self.CurrentMousePos is not None and len(self.Data) > 0: - oldpos = self.Canvas.PositionScreenToUser(self.CurrentMousePos) - newpos = self.Canvas.PositionScreenToUser(event.GetPosition()) - self.CurrentMotionValue += oldpos[0] - newpos[0] - self.YCenter += oldpos[1] - newpos[1] - self.ResetBounds() - self.StartTick = max(self.Data[0, 0], min(self.CurrentMotionValue, self.Data[-1, 0] - self.CurrentRange)) - self.CurrentMousePos = event.GetPosition() - self.NewDataAvailable(None, True) - event.Skip() - - def OnCanvasMouseWheel(self, event): - if self.CurrentMousePos is None: - rotation = event.GetWheelRotation() / event.GetWheelDelta() - if event.ShiftDown(): - current = self.CanvasRange.GetSelection() - new = max(0, min(current - rotation, len(self.RangeValues) - 1)) - if new != current: - if self.Ticktime == 0: - self.CurrentRange = self.RangeValues[new][1] - else: - self.CurrentRange = self.RangeValues[new][1] / self.Ticktime - self.CanvasRange.SetStringSelection(self.RangeValues[new][0]) - wx.CallAfter(self.RefreshRange) - else: - current = self.CanvasZoom.GetSelection() - new = max(0, min(current + rotation, len(ZOOM_VALUES) - 1)) - if new != current: - self.CurrentZoom = ZOOM_VALUES[new][1] - self.CanvasZoom.SetStringSelection(ZOOM_VALUES[new][0]) - wx.CallAfter(self.RefreshView, True) - event.Skip() - - def OnCanvasResize(self, event): - self.ResetLastCursor() - wx.CallAfter(self.RefreshCursor) - event.Skip() - - ## Reset the last cursor - def ResetLastCursor(self): - self.LastCursor = None - - ## Draw the cursor on graphic - # @param dc The draw canvas - # @param cursor The cursor parameters - def DrawCursor(self, dc, cursor, value): - if self.StartTick <= cursor <= self.StartTick + self.CurrentRange: - # Prepare temporary dc for drawing - width = self.Canvas._Buffer.GetWidth() - height = self.Canvas._Buffer.GetHeight() - tmp_Buffer = wx.EmptyBitmap(width, height) - dcs = wx.MemoryDC() - dcs.SelectObject(tmp_Buffer) - dcs.Clear() - dcs.BeginDrawing() - - dcs.SetPen(wx.Pen(wx.RED)) - dcs.SetBrush(wx.Brush(wx.RED, wx.SOLID)) - dcs.SetFont(self.Canvas._getFont(self.Canvas._fontSizeAxis)) - - # Calculate clipping region - graphics, xAxis, yAxis = self.Canvas.last_draw - p1 = numpy.array([xAxis[0], yAxis[0]]) - p2 = numpy.array([xAxis[1], yAxis[1]]) - cx, cy, cwidth, cheight = self.Canvas._point2ClientCoord(p1, p2) - - px, py = self.Canvas.PositionUserToScreen((float(cursor), 0.)) - - # Draw line cross drawing for diaplaying time cursor - dcs.DrawLine(px, cy + 1, px, cy + cheight - 1) - - lines = ("X:%d\nY:%f" % (cursor, value)).splitlines() - - wtext = 0 - for line in lines: - w, h = dcs.GetTextExtent(line) - wtext = max(wtext, w) - - offset = 0 - for line in lines: - # Draw time cursor date - dcs.DrawText(line, min(px + 3, cx + cwidth - wtext), cy + 3 + offset) - w, h = dcs.GetTextExtent(line) - offset += h - - dcs.EndDrawing() - - #this will erase if called twice - dc.Blit(0, 0, width, height, dcs, 0, 0, wx.EQUIV) #(NOT src) XOR dst - - ## Refresh the variable cursor. - # @param dc The draw canvas - def RefreshCursor(self, dc=None): - if self: - if dc is None: - dc = wx.BufferedDC(wx.ClientDC(self.Canvas.canvas), self.Canvas._Buffer) - - # Erase previous time cursor if drawn - if self.LastCursor is not None: - self.DrawCursor(dc, *self.LastCursor) - - # Draw new time cursor - if self.CursorIdx is not None: - self.LastCursor = self.Data[self.CursorIdx] - self.DrawCursor(dc, *self.LastCursor) diff -r 72a826dfcfbb -r 02fe382c4511 editors/LDViewer.py --- a/editors/LDViewer.py Wed Jul 31 10:45:07 2013 +0900 +++ b/editors/LDViewer.py Mon Nov 18 12:12:31 2013 +0900 @@ -482,12 +482,12 @@ dialog = LDElementDialog(self.ParentWindow, self.Controler, "coil") dialog.SetPreviewFont(self.GetFont()) varlist = [] - vars = self.Controler.GetEditedElementInterfaceVars(self.TagName, self.Debug) + vars = self.Controler.GetEditedElementInterfaceVars(self.TagName, debug=self.Debug) if vars: for var in vars: - if var["Class"] != "Input" and var["Type"] == "BOOL": - varlist.append(var["Name"]) - returntype = self.Controler.GetEditedElementInterfaceReturnType(self.TagName, self.Debug) + if var.Class != "Input" and var.Type == "BOOL": + varlist.append(var.Name) + returntype = self.Controler.GetEditedElementInterfaceReturnType(self.TagName, debug=self.Debug) if returntype == "BOOL": varlist.append(self.Controler.GetEditedElementName(self.TagName)) dialog.SetVariables(varlist) @@ -582,11 +582,11 @@ dialog = LDElementDialog(self.ParentWindow, self.Controler, "contact") dialog.SetPreviewFont(self.GetFont()) varlist = [] - vars = self.Controler.GetEditedElementInterfaceVars(self.TagName, self.Debug) + vars = self.Controler.GetEditedElementInterfaceVars(self.TagName, debug=self.Debug) if vars: for var in vars: - if var["Class"] != "Output" and var["Type"] == "BOOL": - varlist.append(var["Name"]) + if var.Class != "Output" and var.Type == "BOOL": + varlist.append(var.Name) dialog.SetVariables(varlist) dialog.SetValues({"name":"","type":CONTACT_NORMAL}) if dialog.ShowModal() == wx.ID_OK: @@ -796,12 +796,12 @@ dialog = LDElementDialog(self.ParentWindow, self.Controleur, "coil") dialog.SetPreviewFont(self.GetFont()) varlist = [] - vars = self.Controler.GetEditedElementInterfaceVars(self.TagName, self.Debug) + vars = self.Controler.GetEditedElementInterfaceVars(self.TagName, debug=self.Debug) if vars: for var in vars: - if var["Class"] != "Input" and var["Type"] == "BOOL": - varlist.append(var["Name"]) - returntype = self.Controler.GetEditedElementInterfaceReturnType(self.TagName, self.Debug) + if var.Class != "Input" and var.Type == "BOOL": + varlist.append(var.Name) + returntype = self.Controler.GetEditedElementInterfaceReturnType(self.TagName, debug=self.Debug) if returntype == "BOOL": varlist.append(self.Controler.GetEditedElementName(self.TagName)) dialog.SetVariables(varlist) diff -r 72a826dfcfbb -r 02fe382c4511 editors/SFCViewer.py --- a/editors/SFCViewer.py Wed Jul 31 10:45:07 2013 +0900 +++ b/editors/SFCViewer.py Mon Nov 18 12:12:31 2013 +0900 @@ -358,7 +358,7 @@ def AddInitialStep(self, pos): dialog = SFCStepNameDialog(self.ParentWindow, _("Please enter step name"), _("Add a new initial step"), "", wx.OK|wx.CANCEL) dialog.SetPouNames(self.Controler.GetProjectPouNames(self.Debug)) - dialog.SetVariables(self.Controler.GetEditedElementInterfaceVars(self.TagName, self.Debug)) + dialog.SetVariables(self.Controler.GetEditedElementInterfaceVars(self.TagName, debug=self.Debug)) dialog.SetStepNames([block.GetName() for block in self.Blocks if isinstance(block, SFC_Step)]) if dialog.ShowModal() == wx.ID_OK: id = self.GetNewId() @@ -380,7 +380,7 @@ if self.SelectedElement in self.Wires or isinstance(self.SelectedElement, SFC_Step): dialog = SFCStepNameDialog(self.ParentWindow, _("Add a new step"), _("Please enter step name"), "", wx.OK|wx.CANCEL) dialog.SetPouNames(self.Controler.GetProjectPouNames(self.Debug)) - dialog.SetVariables(self.Controler.GetEditedElementInterfaceVars(self.TagName, self.Debug)) + dialog.SetVariables(self.Controler.GetEditedElementInterfaceVars(self.TagName, debug=self.Debug)) dialog.SetStepNames([block.GetName() for block in self.Blocks if isinstance(block, SFC_Step)]) if dialog.ShowModal() == wx.ID_OK: name = dialog.GetValue() @@ -437,7 +437,7 @@ dialog = ActionBlockDialog(self.ParentWindow) dialog.SetQualifierList(self.Controler.GetQualifierTypes()) dialog.SetActionList(self.Controler.GetEditedElementActions(self.TagName, self.Debug)) - dialog.SetVariableList(self.Controler.GetEditedElementInterfaceVars(self.TagName, self.Debug)) + dialog.SetVariableList(self.Controler.GetEditedElementInterfaceVars(self.TagName, debug=self.Debug)) if dialog.ShowModal() == wx.ID_OK: actions = dialog.GetValues() self.SelectedElement.AddAction() @@ -724,7 +724,7 @@ else: dialog = SFCStepNameDialog(self.ParentWindow, _("Edit step name"), _("Please enter step name"), step.GetName(), wx.OK|wx.CANCEL) dialog.SetPouNames(self.Controler.GetProjectPouNames(self.Debug)) - dialog.SetVariables(self.Controler.GetEditedElementInterfaceVars(self.TagName, self.Debug)) + dialog.SetVariables(self.Controler.GetEditedElementInterfaceVars(self.TagName, debug=self.Debug)) dialog.SetStepNames([block.GetName() for block in self.Blocks if isinstance(block, SFC_Step) and block.GetName() != step.GetName()]) if dialog.ShowModal() == wx.ID_OK: value = dialog.GetValue() diff -r 72a826dfcfbb -r 02fe382c4511 editors/TextViewer.py --- a/editors/TextViewer.py Wed Jul 31 10:45:07 2013 +0900 +++ b/editors/TextViewer.py Mon Nov 18 12:12:31 2013 +0900 @@ -458,11 +458,13 @@ def RefreshVariableTree(self): words = self.TagName.split("::") - self.Variables = self.GenerateVariableTree([(variable["Name"], variable["Type"], variable["Tree"]) for variable in self.Controler.GetEditedElementInterfaceVars(self.TagName, self.Debug)]) + self.Variables = self.GenerateVariableTree( + [(variable.Name, variable.Type, variable.Tree) + for variable in self.Controler.GetEditedElementInterfaceVars( + self.TagName, True, self.Debug)]) if self.Controler.GetEditedElementType(self.TagName, self.Debug)[1] == "function" or words[0] == "T" and self.TextSyntax == "IL": - return_type = self.Controler.GetEditedElementInterfaceReturnType(self.TagName, self.Debug) + return_type, (var_tree, var_dimension) = self.Controler.GetEditedElementInterfaceReturnType(self.TagName, True, self.Debug) if return_type is not None: - var_tree, var_dimension = self.Controler.GenerateVarTree(return_type, self.Debug) self.Variables[words[-1].upper()] = self.GenerateVariableTree(var_tree) else: self.Variables[words[-1].upper()] = {} diff -r 72a826dfcfbb -r 02fe382c4511 editors/Viewer.py --- a/editors/Viewer.py Wed Jul 31 10:45:07 2013 +0900 +++ b/editors/Viewer.py Mon Nov 18 12:12:31 2013 +0900 @@ -84,36 +84,38 @@ def GetVariableCreationFunction(variable_type): def variableCreationFunction(viewer, id, specific_values): return FBD_Variable(viewer, variable_type, - specific_values["name"], - specific_values["value_type"], + specific_values.name, + specific_values.value_type, id, - specific_values["executionOrder"]) + specific_values.execution_order) return variableCreationFunction def GetConnectorCreationFunction(connector_type): def connectorCreationFunction(viewer, id, specific_values): return FBD_Connector(viewer, connector_type, - specific_values["name"], id) + specific_values.name, id) return connectorCreationFunction def commentCreationFunction(viewer, id, specific_values): - return Comment(viewer, specific_values["content"], id) + return Comment(viewer, specific_values.content, id) def GetPowerRailCreationFunction(powerrail_type): def powerRailCreationFunction(viewer, id, specific_values): return LD_PowerRail(viewer, powerrail_type, id, - specific_values["connectors"]) + specific_values.connectors) return powerRailCreationFunction +MODIFIER_VALUE = lambda x: x if x is not None else 'none' + CONTACT_TYPES = {(True, "none"): CONTACT_REVERSE, (False, "rising"): CONTACT_RISING, (False, "falling"): CONTACT_FALLING} def contactCreationFunction(viewer, id, specific_values): - contact_type = CONTACT_TYPES.get((specific_values.get("negated", False), - specific_values.get("edge", "none")), + contact_type = CONTACT_TYPES.get((specific_values.negated, + MODIFIER_VALUE(specific_values.edge)), CONTACT_NORMAL) - return LD_Contact(viewer, contact_type, specific_values["name"], id) + return LD_Contact(viewer, contact_type, specific_values.name, id) COIL_TYPES = {(True, "none", "none"): COIL_REVERSE, (False, "none", "set"): COIL_SET, @@ -122,38 +124,38 @@ (False, "falling", "none"): COIL_FALLING} def coilCreationFunction(viewer, id, specific_values): - coil_type = COIL_TYPES.get((specific_values.get("negated", False), - specific_values.get("edge", "none"), - specific_values.get("storage", "none")), + coil_type = COIL_TYPES.get((specific_values.negated, + MODIFIER_VALUE(specific_values.edge), + MODIFIER_VALUE(specific_values.storage)), COIL_NORMAL) - return LD_Coil(viewer, coil_type, specific_values["name"], id) + return LD_Coil(viewer, coil_type, specific_values.name, id) def stepCreationFunction(viewer, id, specific_values): - step = SFC_Step(viewer, specific_values["name"], - specific_values.get("initial", False), id) - if specific_values.get("action", None): + step = SFC_Step(viewer, specific_values.name, + specific_values.initial, id) + if specific_values.action is not None: step.AddAction() connector = step.GetActionConnector() - connector.SetPosition(wx.Point(*specific_values["action"]["position"])) + connector.SetPosition(wx.Point(*specific_values.action.position)) return step def transitionCreationFunction(viewer, id, specific_values): - transition = SFC_Transition(viewer, specific_values["condition_type"], - specific_values.get("condition", None), - specific_values["priority"], id) + transition = SFC_Transition(viewer, specific_values.condition_type, + specific_values.condition, + specific_values.priority, id) return transition def GetDivergenceCreationFunction(divergence_type): def divergenceCreationFunction(viewer, id, specific_values): return SFC_Divergence(viewer, divergence_type, - specific_values["connectors"], id) + specific_values.connectors, id) return divergenceCreationFunction def jumpCreationFunction(viewer, id, specific_values): - return SFC_Jump(viewer, specific_values["target"], id) + return SFC_Jump(viewer, specific_values.target, id) def actionBlockCreationFunction(viewer, id, specific_values): - return SFC_ActionBlock(viewer, specific_values["actions"], id) + return SFC_ActionBlock(viewer, specific_values.actions, id) ElementCreationFunctions = { "input": GetVariableCreationFunction(INPUT), @@ -330,7 +332,7 @@ var_class = INPUT else: var_class = INPUT - tree = dict([(var["Name"], var["Tree"]) for var in self.ParentWindow.Controler.GetEditedElementInterfaceVars(tagname, self.ParentWindow.Debug)]).get(values[0], None) + tree = dict([(var.Name, var.Tree) for var in self.ParentWindow.Controler.GetEditedElementInterfaceVars(tagname, True, self.ParentWindow.Debug)]).get(values[0], None) if tree is not None: if len(tree[0]) > 0: menu = wx.Menu(title='') @@ -568,6 +570,7 @@ self.Editor.SetBackgroundColour(wx.Colour(255,255,255)) self.Editor.SetBackgroundStyle(wx.BG_STYLE_CUSTOM) self.ResetView() + self.LastClientSize = None self.Scaling = None self.DrawGrid = True self.GridBrush = wx.TRANSPARENT_BRUSH @@ -1050,22 +1053,21 @@ self.ElementRefreshList.append(element) self.ElementRefreshList_lock.release() - def RefreshNewData(self): - refresh_rect = None - self.ElementRefreshList_lock.acquire() - for element in self.ElementRefreshList: - if refresh_rect is None: - refresh_rect = element.GetRedrawRect() - else: - refresh_rect.Union(element.GetRedrawRect()) - self.ElementRefreshList = [] - self.ElementRefreshList_lock.release() - - if refresh_rect is not None: - self.RefreshRect(self.GetScrolledRect(refresh_rect), False) - else: - DebugViewer.RefreshNewData(self) - + def NewDataAvailable(self, ticks, *args, **kwargs): + if self.IsShown(): + refresh_rect = None + self.ElementRefreshList_lock.acquire() + for element in self.ElementRefreshList: + if refresh_rect is None: + refresh_rect = element.GetRedrawRect() + else: + refresh_rect.Union(element.GetRedrawRect()) + self.ElementRefreshList = [] + self.ElementRefreshList_lock.release() + + if refresh_rect is not None: + self.RefreshRect(self.GetScrolledRect(refresh_rect), False) + def SubscribeAllDataConsumers(self): self.RefreshView() DebugViewer.SubscribeAllDataConsumers(self) @@ -1074,7 +1076,7 @@ def RefreshView(self, variablepanel=True, selection=None): EditorPanel.RefreshView(self, variablepanel) - if self.TagName.split("::")[0] == "A": + if self.TagName.split("::")[0] == "A" and self.Debug: self.AddDataConsumer("%s.Q" % self.InstancePath.upper(), self) if self.ToolTipElement is not None: @@ -1089,12 +1091,10 @@ self.ResetBuffer() instance = {} # List of ids of already loaded blocks - ids = [] + instances = self.Controler.GetEditedElementInstancesInfos(self.TagName, debug = self.Debug) # Load Blocks until they are all loaded - while instance is not None: - instance = self.Controler.GetEditedElementInstanceInfos(self.TagName, exclude = ids, debug = self.Debug) - if instance is not None: - self.loadInstance(instance, ids, selection) + while len(instances) > 0: + self.loadInstance(instances.popitem(0)[1], instances, selection) if (selection is not None and isinstance(self.SelectedElement, Graphic_Group)): @@ -1220,124 +1220,133 @@ self.SelectedElement = group # Load instance from given informations - def loadInstance(self, instance, ids, selection): - ids.append(instance["id"]) - self.current_id = max(self.current_id, instance["id"]) - creation_function = ElementCreationFunctions.get(instance["type"], None) + def loadInstance(self, instance, remaining_instances, selection): + self.current_id = max(self.current_id, instance.id) + creation_function = ElementCreationFunctions.get(instance.type, None) connectors = {"inputs" : [], "outputs" : []} - specific_values = instance["specific_values"] + specific_values = instance.specific_values if creation_function is not None: - element = creation_function(self, instance["id"], specific_values) + element = creation_function(self, instance.id, specific_values) if isinstance(element, SFC_Step): - if len(instance["inputs"]) > 0: + if len(instance.inputs) > 0: element.AddInput() else: element.RemoveInput() - if len(instance["outputs"]) > 0: + if len(instance.outputs) > 0: element.AddOutput() - if isinstance(element, SFC_Transition) and specific_values["condition_type"] == "connection": + if isinstance(element, SFC_Transition) and specific_values.condition_type == "connection": connector = element.GetConditionConnector() - self.CreateWires(connector, instance["id"], specific_values["connection"]["links"], ids, selection) + self.CreateWires(connector, instance.id, specific_values.connection.links, remaining_instances, selection) else: executionControl = False - for input in instance["inputs"]: - if input["negated"]: - connectors["inputs"].append((input["name"], None, "negated")) - elif input["edge"]: - connectors["inputs"].append((input["name"], None, input["edge"])) + for input in instance.inputs: + input_edge = MODIFIER_VALUE(input.edge) + if input.negated: + connectors["inputs"].append((input.name, None, "negated")) + elif input_edge: + connectors["inputs"].append((input.name, None, input_edge)) else: - connectors["inputs"].append((input["name"], None, "none")) - for output in instance["outputs"]: - if output["negated"]: - connectors["outputs"].append((output["name"], None, "negated")) - elif output["edge"]: - connectors["outputs"].append((output["name"], None, output["edge"])) + connectors["inputs"].append((input.name, None, "none")) + for output in instance.outputs: + output_edge = MODIFIER_VALUE(output.edge) + if output.negated: + connectors["outputs"].append((output.name, None, "negated")) + elif output_edge: + connectors["outputs"].append((output.name, None, output_edge)) else: - connectors["outputs"].append((output["name"], None, "none")) + connectors["outputs"].append((output.name, None, "none")) if len(connectors["inputs"]) > 0 and connectors["inputs"][0][0] == "EN": connectors["inputs"].pop(0) executionControl = True if len(connectors["outputs"]) > 0 and connectors["outputs"][0][0] == "ENO": connectors["outputs"].pop(0) executionControl = True - if specific_values["name"] is None: - specific_values["name"] = "" - element = FBD_Block(self, instance["type"], specific_values["name"], - instance["id"], len(connectors["inputs"]), + block_name = specific_values.name if specific_values.name is not None else "" + element = FBD_Block(self, instance.type, block_name, + instance.id, len(connectors["inputs"]), connectors=connectors, executionControl=executionControl, - executionOrder=specific_values["executionOrder"]) + executionOrder=specific_values.execution_order) if isinstance(element, Comment): self.AddComment(element) else: self.AddBlock(element) connectors = element.GetConnectors() - element.SetPosition(instance["x"], instance["y"]) - element.SetSize(instance["width"], instance["height"]) - for i, output_connector in enumerate(instance["outputs"]): + element.SetPosition(instance.x, instance.y) + element.SetSize(instance.width, instance.height) + for i, output_connector in enumerate(instance.outputs): + connector_pos = wx.Point(*output_connector.position) if isinstance(element, FBD_Block): - connector = element.GetConnector( - wx.Point(*output_connector["position"]), - output_name = output_connector["name"]) + connector = element.GetConnector(connector_pos, + output_name = output_connector.name) elif i < len(connectors["outputs"]): connector = connectors["outputs"][i] else: connector = None if connector is not None: - if output_connector.get("negated", False): + if output_connector.negated: connector.SetNegated(True) - if output_connector.get("edge", "none") != "none": - connector.SetEdge(output_connector["edge"]) + if output_connector.edge is not None: + connector.SetEdge(output_connector.edge) if connectors["outputs"].index(connector) == i: - connector.SetPosition(wx.Point(*output_connector["position"])) - for i, input_connector in enumerate(instance["inputs"]): + connector.SetPosition(connector_pos) + for i, input_connector in enumerate(instance.inputs): + connector_pos = wx.Point(*input_connector.position) if isinstance(element, FBD_Block): - connector = element.GetConnector( - wx.Point(*input_connector["position"]), - input_name = input_connector["name"]) + connector = element.GetConnector(connector_pos, + input_name = input_connector.name) elif i < len(connectors["inputs"]): connector = connectors["inputs"][i] else: connector = None if connector is not None: if connectors["inputs"].index(connector) == i: - connector.SetPosition(wx.Point(*input_connector["position"])) - if input_connector.get("negated", False): + connector.SetPosition(connector_pos) + if input_connector.negated: connector.SetNegated(True) - if input_connector.get("edge", "none") != "none": - connector.SetEdge(input_connector["edge"]) - if not self.CreateWires(connector, instance["id"], input_connector["links"], ids, selection): + if input_connector.edge is not None: + connector.SetEdge(input_connector.edge) + if not self.CreateWires(connector, instance.id, input_connector.links, remaining_instances, selection): element.RefreshModel() element.RefreshConnectors() - if selection is not None and selection[0].get(instance["id"], False): + if selection is not None and selection[0].get(instance.id, False): self.SelectInGroup(element) - def CreateWires(self, start_connector, id, links, ids, selection=None): + def CreateWires(self, start_connector, id, links, remaining_instances, selection=None): links_connected = True for link in links: - refLocalId = link["refLocalId"] + refLocalId = link.refLocalId if refLocalId is None: links_connected = False continue - if refLocalId not in ids: - new_instance = self.Controler.GetEditedElementInstanceInfos(self.TagName, refLocalId, debug = self.Debug) - if new_instance is not None: - self.loadInstance(new_instance, ids, selection) + new_instance = remaining_instances.pop(refLocalId, None) + if new_instance is not None: + self.loadInstance(new_instance, remaining_instances, selection) connected = self.FindElementById(refLocalId) if connected is None: links_connected = False continue - points = link["points"] - end_connector = connected.GetConnector(wx.Point(points[-1][0], points[-1][1]), link["formalParameter"]) + points = link.points + end_connector = connected.GetConnector( + wx.Point(points[-1].x, points[-1].y) + if len(points) > 0 else wx.Point(0, 0), + link.formalParameter) if end_connector is not None: - wire = Wire(self) - wire.SetPoints(points) - start_connector.Connect((wire, 0), False) - end_connector.Connect((wire, -1), False) - wire.ConnectStartPoint(None, start_connector) - wire.ConnectEndPoint(None, end_connector) + if len(points) > 0: + wire = Wire(self) + wire.SetPoints(points) + else: + wire = Wire(self, + [wx.Point(*start_connector.GetPosition()), + start_connector.GetDirection()], + [wx.Point(*end_connector.GetPosition()), + end_connector.GetDirection()]) + start_connector.Wires.append((wire, 0)) + end_connector.Wires.append((wire, -1)) + wire.StartConnected = start_connector + wire.EndConnected = end_connector connected.RefreshConnectors() self.AddWire(wire) if selection is not None and (\ @@ -2214,7 +2223,6 @@ movex, movey = self.SelectedElement.OnMotion(event, dc, self.Scaling) if movex != 0 or movey != 0: self.RefreshRect(self.GetScrolledRect(self.SelectedElement.GetRedrawRect(movex, movey)), False) - self.RefreshVisibleElements() elif self.Debug and self.StartMousePos is not None and event.Dragging(): pos = event.GetPosition() if abs(self.StartMousePos.x - pos.x) > 5 or abs(self.StartMousePos.y - pos.y) > 5: @@ -2423,11 +2431,12 @@ executionOrder = values["executionOrder"]) self.Controler.AddEditedElementBlock(self.TagName, id, values["type"], values.get("name", None)) connector = None - for input_connector in block.GetConnectors()["inputs"]: - if input_connector.IsCompatible( - wire.GetStartConnectedType()): - connector = input_connector - break + if wire is not None: + for input_connector in block.GetConnectors()["inputs"]: + if input_connector.IsCompatible( + wire.GetStartConnectedType()): + connector = input_connector + break self.AddNewElement(block, bbox, wire, connector) dialog.Destroy() @@ -2610,7 +2619,7 @@ dialog = ActionBlockDialog(self.ParentWindow) dialog.SetQualifierList(self.Controler.GetQualifierTypes()) dialog.SetActionList(self.Controler.GetEditedElementActions(self.TagName, self.Debug)) - dialog.SetVariableList(self.Controler.GetEditedElementInterfaceVars(self.TagName, self.Debug)) + dialog.SetVariableList(self.Controler.GetEditedElementInterfaceVars(self.TagName, debug=self.Debug)) if dialog.ShowModal() == wx.ID_OK: id = self.GetNewId() actionblock = SFC_ActionBlock(self, dialog.GetValues(), id) @@ -2860,7 +2869,7 @@ dialog = ActionBlockDialog(self.ParentWindow) dialog.SetQualifierList(self.Controler.GetQualifierTypes()) dialog.SetActionList(self.Controler.GetEditedElementActions(self.TagName, self.Debug)) - dialog.SetVariableList(self.Controler.GetEditedElementInterfaceVars(self.TagName, self.Debug)) + dialog.SetVariableList(self.Controler.GetEditedElementInterfaceVars(self.TagName, debug=self.Debug)) dialog.SetValues(actionblock.GetActions()) if dialog.ShowModal() == wx.ID_OK: actions = dialog.GetValues() @@ -3458,8 +3467,11 @@ self.Scroll(x, yp) def OnMoveWindow(self, event): - self.RefreshScrollBars() - self.RefreshVisibleElements() + client_size = self.GetClientSize() + if self.LastClientSize != client_size: + self.LastClientSize = client_size + self.RefreshScrollBars() + self.RefreshVisibleElements() event.Skip() def DoDrawing(self, dc, printing = False): diff -r 72a826dfcfbb -r 02fe382c4511 graphics/DebugDataConsumer.py --- a/graphics/DebugDataConsumer.py Wed Jul 31 10:45:07 2013 +0900 +++ b/graphics/DebugDataConsumer.py Mon Nov 18 12:12:31 2013 +0900 @@ -197,7 +197,7 @@ """ self.DataType = data_type - def NewValue(self, tick, value, forced=False, raw="BOOL"): + def NewValues(self, tick, values, raw="BOOL"): """ Function called by debug thread when a new debug value is available @param tick: PLC tick when value was captured @@ -205,6 +205,8 @@ @param forced: Forced flag, True if value is forced (default: False) @param raw: Data type of values not translated (default: 'BOOL') """ + value, forced = values + # Translate value to IEC literal if self.DataType != raw: value = TYPE_TRANSLATOR.get(self.DataType, str)(value) diff -r 72a826dfcfbb -r 02fe382c4511 graphics/LD_Objects.py --- a/graphics/LD_Objects.py Wed Jul 31 10:45:07 2013 +0900 +++ b/graphics/LD_Objects.py Mon Nov 18 12:12:31 2013 +0900 @@ -774,8 +774,8 @@ # Unconnect input and output def Clean(self): - self.Input.UnConnect() - self.Output.UnConnect() + self.Input.UnConnect(delete = self.Parent.GetDrawingMode() == FREEDRAWING_MODE) + self.Output.UnConnect(delete = self.Parent.GetDrawingMode() == FREEDRAWING_MODE) # Refresh the size of text for name def RefreshNameSize(self): diff -r 72a826dfcfbb -r 02fe382c4511 graphics/SFC_Objects.py --- a/graphics/SFC_Objects.py Wed Jul 31 10:45:07 2013 +0900 +++ b/graphics/SFC_Objects.py Mon Nov 18 12:12:31 2013 +0900 @@ -1894,18 +1894,19 @@ self.ColSize = [0, 0, 0] min_height = 0 for action in self.Actions: - width, height = self.Parent.GetTextExtent(action["qualifier"]) + width, height = self.Parent.GetTextExtent( + action.qualifier if action.qualifier != "" else "N") self.ColSize[0] = max(self.ColSize[0], width + 10) row_height = height - if action.has_key("duration"): - width, height = self.Parent.GetTextExtent(action["duration"]) + if action.duration != "": + width, height = self.Parent.GetTextExtent(action.duration) row_height = max(row_height, height) self.ColSize[0] = max(self.ColSize[0], width + 10) - width, height = self.Parent.GetTextExtent(action["value"]) + width, height = self.Parent.GetTextExtent(action.value) row_height = max(row_height, height) self.ColSize[1] = max(self.ColSize[1], width + 10) - if action.get("indicator", "") != "": - width, height = self.Parent.GetTextExtent(action["indicator"]) + if action.indicator != "": + width, height = self.Parent.GetTextExtent(action.indicator) row_height = max(row_height, height) self.ColSize[2] = max(self.ColSize[2], width + 10) min_height += row_height + 5 @@ -1920,7 +1921,7 @@ self.MinSize = max(self.ColSize[0] + self.ColSize[1] + self.ColSize[2], SFC_ACTION_MIN_SIZE[0]), len(self.Actions) * SFC_ACTION_MIN_SIZE[1] self.RefreshBoundingBox() - if self.Input: + if self.Input is not None: wires = self.Input.GetWires() if len(wires) == 1: input_block = wires[0][0].GetOtherConnected(self.Input).GetParentBlock() @@ -2022,39 +2023,39 @@ if i != 0: dc.DrawLine(self.Pos.x, self.Pos.y + i * line_size, self.Pos.x + self.Size[0], self.Pos.y + i * line_size) - qualifier_size = dc.GetTextExtent(action["qualifier"]) - if action.has_key("duration"): + qualifier_size = dc.GetTextExtent(action.qualifier) + if action.duration != "": qualifier_pos = (self.Pos.x + (colsize[0] - qualifier_size[0]) / 2, self.Pos.y + i * line_size + line_size / 2 - qualifier_size[1]) - duration_size = dc.GetTextExtent(action["duration"]) + duration_size = dc.GetTextExtent(action.duration) duration_pos = (self.Pos.x + (colsize[0] - duration_size[0]) / 2, self.Pos.y + i * line_size + line_size / 2) - dc.DrawText(action["duration"], duration_pos[0], duration_pos[1]) + dc.DrawText(action.duration, duration_pos[0], duration_pos[1]) else: qualifier_pos = (self.Pos.x + (colsize[0] - qualifier_size[0]) / 2, self.Pos.y + i * line_size + (line_size - qualifier_size[1]) / 2) - dc.DrawText(action["qualifier"], qualifier_pos[0], qualifier_pos[1]) - content_size = dc.GetTextExtent(action["value"]) + dc.DrawText(action.qualifier, qualifier_pos[0], qualifier_pos[1]) + content_size = dc.GetTextExtent(action.value) content_pos = (self.Pos.x + colsize[0] + (colsize[1] - content_size[0]) / 2, self.Pos.y + i * line_size + (line_size - content_size[1]) / 2) - dc.DrawText(action["value"], content_pos[0], content_pos[1]) - if action.has_key("indicator"): - indicator_size = dc.GetTextExtent(action["indicator"]) + dc.DrawText(action.value, content_pos[0], content_pos[1]) + if action.indicator != "": + indicator_size = dc.GetTextExtent(action.indicator) indicator_pos = (self.Pos.x + colsize[0] + colsize[1] + (colsize[2] - indicator_size[0]) / 2, self.Pos.y + i * line_size + (line_size - indicator_size[1]) / 2) - dc.DrawText(action["indicator"], indicator_pos[0], indicator_pos[1]) + dc.DrawText(action.indicator, indicator_pos[0], indicator_pos[1]) if not getattr(dc, "printing", False): action_highlights = self.Highlights.get(i, {}) for name, attribute_highlights in action_highlights.iteritems(): if name == "qualifier": - DrawHighlightedText(dc, action["qualifier"], attribute_highlights, qualifier_pos[0], qualifier_pos[1]) + DrawHighlightedText(dc, action.qualifier, attribute_highlights, qualifier_pos[0], qualifier_pos[1]) elif name == "duration": - DrawHighlightedText(dc, action["duration"], attribute_highlights, duration_pos[0], duration_pos[1]) + DrawHighlightedText(dc, action.duration, attribute_highlights, duration_pos[0], duration_pos[1]) elif name in ["reference", "inline"]: - DrawHighlightedText(dc, action["value"], attribute_highlights, content_pos[0], content_pos[1]) + DrawHighlightedText(dc, action.value, attribute_highlights, content_pos[0], content_pos[1]) elif name == "indicator": - DrawHighlightedText(dc, action["indicator"], attribute_highlights, indicator_pos[0], indicator_pos[1]) + DrawHighlightedText(dc, action.indicator, attribute_highlights, indicator_pos[0], indicator_pos[1]) # Draw input connector self.Input.Draw(dc) diff -r 72a826dfcfbb -r 02fe382c4511 plcopen/Additional_Function_Blocks.xml --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/plcopen/Additional_Function_Blocks.xml Mon Nov 18 12:12:31 2013 +0900 @@ -0,0 +1,522 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + + + + + + + + + + + + + + + + + +
+ + + + + + + + + + + + + + + + + + + + + +
+ + + + + + + ,CURRENT_TIME,__CURRENT_TIME)} + + IF IN + THEN + IF NOT PREV_IN + THEN + OFFSET := PDT - CURRENT_TIME; + END_IF; + + (* PDT + time since PDT was loaded *) + CDT := CURRENT_TIME + OFFSET; + ELSE + CDT := CURRENT_TIME; + END_IF; + + Q := IN; + PREV_IN := IN; +]]> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + = TR THEN + BUSY := 0; + XOUT := X1; + ELSE XOUT := XI + (X1-XI) * TIME_TO_REAL(T) + / TIME_TO_REAL(TR); + T := T + CYCLE; + END_IF; +ELSE + XOUT := X0; + XI := X0; + T := T#0s; +END_IF;]]> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + (XIN2 + EPS) THEN + Q := 1; +END_IF;]]> + + + + + + + + + + + + diff -r 72a826dfcfbb -r 02fe382c4511 plcopen/Makefile --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/plcopen/Makefile Mon Nov 18 12:12:31 2013 +0900 @@ -0,0 +1,15 @@ +#! gmake + +yml := ../../yml2 +ysl2files := $(wildcard *.ysl2) +xsltfiles := $(patsubst %.ysl2, %.xslt, $(ysl2files)) + +all:$(xsltfiles) + +%.xslt: %.ysl2 + $(yml)/yml2c -I $(yml) $< -o $@.tmp + xmlstarlet fo $@.tmp > $@ + rm $@.tmp + +clean: + rm -f $(xsltfiles) \ No newline at end of file diff -r 72a826dfcfbb -r 02fe382c4511 plcopen/Standard_Function_Blocks.xml --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/plcopen/Standard_Function_Blocks.xml Mon Nov 18 12:12:31 2013 +0900 @@ -0,0 +1,1469 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + = PV);]]> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + = PV);]]> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + = PV);]]> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + = PV);]]> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + = PV);]]> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 0) + THEN CV := CV-1; +END_IF; +Q := (CV <= 0);]]> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 0) + THEN CV := CV-1; +END_IF; +Q := (CV <= 0);]]> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 0) + THEN CV := CV-1; +END_IF; +Q := (CV <= 0);]]> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 0) + THEN CV := CV-1; +END_IF; +Q := (CV <= 0);]]> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 0) + THEN CV := CV-1; +END_IF; +Q := (CV <= 0);]]> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 0) + THEN CV := CV-1; + END_IF; + END_IF; +END_IF; +QU := (CV >= PV); +QD := (CV <= 0);]]> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 0) + THEN CV := CV-1; + END_IF; + END_IF; +END_IF; +QU := (CV >= PV); +QD := (CV <= 0);]]> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 0) + THEN CV := CV-1; + END_IF; + END_IF; +END_IF; +QU := (CV >= PV); +QD := (CV <= 0);]]> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 0) + THEN CV := CV-1; + END_IF; + END_IF; +END_IF; +QU := (CV >= PV); +QD := (CV <= 0);]]> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 0) + THEN CV := CV-1; + END_IF; + END_IF; +END_IF; +QU := (CV >= PV); +QD := (CV <= 0);]]> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + ,CURRENT_TIME,__CURRENT_TIME)} + +IF ((STATE = 0) AND NOT(PREV_IN) AND IN) (* found rising edge on IN *) +THEN + (* start timer... *) + STATE := 1; + Q := TRUE; + START_TIME := CURRENT_TIME; + +ELSIF (STATE = 1) +THEN + IF ((START_TIME + PT) <= CURRENT_TIME) + THEN + STATE := 2; + Q := FALSE; + ET := PT; + ELSE + ET := CURRENT_TIME - START_TIME; + END_IF; +END_IF; + +IF ((STATE = 2) AND NOT(IN)) +THEN + ET := T#0s; + STATE := 0; +END_IF; + +PREV_IN := IN; +]]> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + ,CURRENT_TIME,__CURRENT_TIME)} + +IF ((STATE = 0) AND NOT(PREV_IN) AND IN) (* found rising edge on IN *) +THEN + (* start timer... *) + STATE := 1; + Q := FALSE; + START_TIME := CURRENT_TIME; + +ELSE + (* STATE is 1 or 2 !! *) + IF (NOT(IN)) + THEN + ET := T#0s; + Q := FALSE; + STATE := 0; + + ELSIF (STATE = 1) + THEN + IF ((START_TIME + PT) <= CURRENT_TIME) + THEN + STATE := 2; + Q := TRUE; + ET := PT; + ELSE + ET := CURRENT_TIME - START_TIME; + END_IF; + END_IF; + +END_IF; + +PREV_IN := IN; +]]> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + ,CURRENT_TIME,__CURRENT_TIME)} + +IF ((STATE = 0) AND PREV_IN AND NOT(IN)) (* found falling edge on IN *) +THEN + (* start timer... *) + STATE := 1; + START_TIME := CURRENT_TIME; + +ELSE + (* STATE is 1 or 2 !! *) + IF (IN) + THEN + ET := T#0s; + STATE := 0; + + ELSIF (STATE = 1) + THEN + IF ((START_TIME + PT) <= CURRENT_TIME) + THEN + STATE := 2; + ET := PT; + ELSE + ET := CURRENT_TIME - START_TIME; + END_IF; + END_IF; + +END_IF; + +Q := IN OR (STATE = 1); +PREV_IN := IN; +]]> + + + + + + + + + + + + diff -r 72a826dfcfbb -r 02fe382c4511 plcopen/__init__.py --- a/plcopen/__init__.py Wed Jul 31 10:45:07 2013 +0900 +++ b/plcopen/__init__.py Mon Nov 18 12:12:31 2013 +0900 @@ -25,9 +25,7 @@ # Package initialisation # plcopen module dynamically creates its classes -import plcopen -for classname, cls in plcopen.PLCOpenClasses.items(): - plcopen.__dict__[classname] = cls -from plcopen import VarOrder, ElementNameToClass, rect +from plcopen import PLCOpenParser, LoadProject, SaveProject, LoadPou, \ + LoadPouInstances, VarOrder, QualifierList, rect from structures import * diff -r 72a826dfcfbb -r 02fe382c4511 plcopen/instance_tagname.xslt --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/plcopen/instance_tagname.xslt Mon Nov 18 12:12:31 2013 +0900 @@ -0,0 +1,196 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff -r 72a826dfcfbb -r 02fe382c4511 plcopen/instance_tagname.ysl2 --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/plcopen/instance_tagname.ysl2 Mon Nov 18 12:12:31 2013 +0900 @@ -0,0 +1,186 @@ +include yslt.yml2 +estylesheet xmlns:ppx="http://www.plcopen.org/xml/tc6_0201" + xmlns:xhtml="http://www.w3.org/1999/xhtml" + xmlns:ns="instance_tagname_ns" + extension-element-prefixes="ns" + exclude-result-prefixes="ns" { + + param "instance_path"; + + variable "project" { + copy "document('project')/project/*"; + } + + variable "stdlib" { + copy "document('stdlib')/stdlib/*"; + } + variable "extensions" { + copy "document('extensions')/extensions/*"; + } + + function "element_name" { + param "path"; + choose { + when "contains($path,'.')" > «substring-before($path,'.')» + otherwise > «$path» + } + } + + function "next_path" { + param "path"; + choose { + when "contains($path,'.')" > «substring-after($path,'.')» + } + } + + template "ppx:project" { + variable "config_name" { + call "element_name" { + with "path", "$instance_path"; + } + } + apply "ppx:instances/ppx:configurations/ppx:configuration[@name=$config_name]" { + with "element_path" { + call "next_path" { + with "path", "$instance_path"; + } + } + } + } + + template "ppx:configuration" { + param "element_path"; + choose { + when "$element_path!=''" { + variable "child_name" { + call "element_name" { + with "path", "$element_path"; + } + } + apply "ppx:resource[@name=$child_name] | ppx:globalVars/ppx:variable[@name=$child_name]/ppx:type/*[self::ppx:derived or self::ppx:struct or self::ppx:array]" { + with "element_path" { + call "next_path" { + with "path", "$element_path"; + } + } + } + } + otherwise { + value "ns:ConfigTagName(@name)"; + } + } + } + + template "ppx:resource" { + param "element_path"; + choose { + when "$element_path!=''" { + variable "child_name" { + call "element_name" { + with "path" > «$element_path» + } + } + apply "ppx:pouInstance[@name=$child_name] | ppx:task/ppx:pouInstance[@name=$child_name] | ppx:globalVars/ppx:variable[@name=$child_name]/ppx:type/*[self::ppx:derived or self::ppx:struct or self::ppx:array]" { + with "element_path" { + call "next_path" { + with "path", "$element_path"; + } + } + } + } + otherwise { + value "ns:ResourceTagName(ancestor::ppx:configuration/@name, @name)"; + } + } + } + + template "ppx:pouInstance" { + param "element_path"; + variable "type_name" > «@typeName» + apply """exsl:node-set($project)/ppx:project/ppx:types/ppx:pous/ppx:pou[@name=$type_name] | + exsl:node-set($project)/ppx:project/ppx:types/ppx:dataTypes/ppx:dataType[@name=$type_name] | + exsl:node-set($stdlib)/ppx:project/ppx:types/ppx:pous/ppx:pou[@name=$type_name] | + exsl:node-set($stdlib)/ppx:project/ppx:types/ppx:dataTypes/ppx:dataType[@name=$type_name] | + exsl:node-set($extensions)/ppx:project/ppx:types/ppx:pous/ppx:pou[@name=$type_name] | + exsl:node-set($extensions)/ppx:project/ppx:types/ppx:dataTypes/ppx:dataType[@name=$type_name]""" { + with "element_path", "$element_path"; + } + } + + template "ppx:pou" { + param "element_path"; + choose { + when "$element_path!=''" { + variable "child_name" { + call "element_name" { + with "path", "$element_path"; + } + } + apply "ppx:interface/*/ppx:variable[@name=$child_name]/ppx:type/*[self::ppx:derived or self::ppx:struct or self::ppx:array]" { + with "element_path" { + call "next_path" { + with "path", "$element_path"; + } + } + } + apply "ppx:actions/ppx:action[@name=$child_name] | ppx:transitions/ppx:transition[@name=$child_name]"; + } + otherwise { + variable "name" > «@name» + value "ns:PouTagName($name)"; + } + } + } + + template "ppx:action" { + value "ns:ActionTagName(ancestor::ppx:pou/@name, @name)"; + } + + template "ppx:transition" { + value "ns:TransitionTagName(ancestor::ppx:pou/@name, @name)"; + } + + template "ppx:dataType" { + param "element_path"; + apply "ppx:baseType/*[self::ppx:derived or self::ppx:struct or self::ppx:array]" { + with "element_path", "$element_path"; + } + } + + template "ppx:derived" { + param "element_path"; + variable "type_name" > «@name» + apply """exsl:node-set($project)/ppx:project/ppx:types/ppx:pous/ppx:pou[@name=$type_name] | + exsl:node-set($project)/ppx:project/ppx:types/ppx:dataTypes/ppx:dataType[@name=$type_name] | + exsl:node-set($stdlib)/ppx:project/ppx:types/ppx:pous/ppx:pou[@name=$type_name] | + exsl:node-set($stdlib)/ppx:project/ppx:types/ppx:dataTypes/ppx:dataType[@name=$type_name] | + exsl:node-set($extensions)/ppx:project/ppx:types/ppx:pous/ppx:pou[@name=$type_name] | + exsl:node-set($extensions)/ppx:project/ppx:types/ppx:dataTypes/ppx:dataType[@name=$type_name]""" { + with "element_path", "$element_path"; + } + } + + template "ppx:array" { + param "element_path"; + apply "ppx:baseType/*[self::ppx:derived or self::ppx:struct or self::ppx:array]" { + with "element_path", "$element_path"; + } + } + + template "ppx:struct" { + param "element_path"; + variable "child_name" { + call "element_name" { + with "path", "$element_path"; + } + } + apply "ppx:variable[@name=$child_name]/ppx:type/*[self::ppx:derived or self::ppx:struct or self::ppx:array]" { + with "element_path" { + call "next_path" { + with "path", "$element_path"; + } + } + } + } + +} diff -r 72a826dfcfbb -r 02fe382c4511 plcopen/instances_path.xslt --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/plcopen/instances_path.xslt Mon Nov 18 12:12:31 2013 +0900 @@ -0,0 +1,158 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + . + + + + + + + + + + + + + + + . + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + . + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + . + + + + + + + + + + + + + + + + + + + + + diff -r 72a826dfcfbb -r 02fe382c4511 plcopen/instances_path.ysl2 --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/plcopen/instances_path.ysl2 Mon Nov 18 12:12:31 2013 +0900 @@ -0,0 +1,123 @@ +include yslt.yml2 +estylesheet xmlns:ppx="http://www.plcopen.org/xml/tc6_0201" + xmlns:xhtml="http://www.w3.org/1999/xhtml" + xmlns:ns="instances_ns" + extension-element-prefixes="ns" + exclude-result-prefixes="ns" { + + param "instance_type"; + + template "text()"; + + variable "project" { + copy "document('project')/project/*"; + } + + variable "stdlib" { + copy "document('stdlib')/stdlib/*"; + } + variable "extensions" { + copy "document('extensions')/extensions/*"; + } + + template "ppx:project" { + instances { + apply "ppx:instances/ppx:configurations/ppx:configuration"; + } + } + + template "ppx:configuration" { + apply "ppx:globalVars/ppx:variable[ppx:type/ppx:derived] | ppx:resource" { + with "parent_path" > «@name» + } + } + + template "ppx:resource" { + param "parent_path"; + variable "resource_path" > «$parent_path».«@name» + apply "ppx:globalVars/ppx:variable[ppx:type/ppx:derived] | ppx:pouInstance | ppx:task/ppx:pouInstance" { + with "parent_path" > «$resource_path» + } + } + + template "ppx:pouInstance" { + param "parent_path"; + variable "pou_instance_path" > «$parent_path».«@name» + choose { + when "@typeName=$instance_type" { + value "ns:AddInstance($pou_instance_path)"; + } + otherwise { + variable "type_name" > «@typeName» + apply """exsl:node-set($project)/ppx:project/ppx:types/ppx:pous/ppx:pou[@name=$type_name] | + exsl:node-set($project)/ppx:project/ppx:types/ppx:dataTypes/ppx:dataType[@name=$type_name] | + exsl:node-set($stdlib)/ppx:project/ppx:types/ppx:pous/ppx:pou[@name=$type_name] | + exsl:node-set($stdlib)/ppx:project/ppx:types/ppx:dataTypes/ppx:dataType[@name=$type_name] | + exsl:node-set($extensions)/ppx:project/ppx:types/ppx:pous/ppx:pou[@name=$type_name] | + exsl:node-set($extensions)/ppx:project/ppx:types/ppx:dataTypes/ppx:dataType[@name=$type_name]""" { + with "instance_path" > «$pou_instance_path» + } + } + } + } + + template "ppx:pou" { + param "instance_path"; + apply "ppx:interface/*/ppx:variable[ppx:type/ppx:derived]" { + with "parent_path" > «$instance_path» + } + } + + template "ppx:dataType" { + param "instance_path"; + apply "ppx:baseType/*[self::ppx:derived or self::ppx:struct or self::ppx:array]" { + with "parent_path" > «$instance_path» + } + } + + template "ppx:variable" { + param "parent_path"; + variable "variable_path" > «$parent_path».«@name» + apply "ppx:type/ppx:derived" { + with "variable_path" > «$variable_path» + } + } + + template "ppx:derived" { + param "variable_path"; + choose { + when "@name=$instance_type" { + value "ns:AddInstance($variable_path)"; + } + otherwise { + variable "type_name" > «@name» + apply """exsl:node-set($project)/ppx:project/ppx:types/ppx:pous/ppx:pou[@name=$type_name] | + exsl:node-set($project)/ppx:project/ppx:types/ppx:dataTypes/ppx:dataType[@name=$type_name] | + exsl:node-set($stdlib)/ppx:project/ppx:types/ppx:pous/ppx:pou[@name=$type_name] | + exsl:node-set($stdlib)/ppx:project/ppx:types/ppx:dataTypes/ppx:dataType[@name=$type_name] | + exsl:node-set($extensions)/ppx:project/ppx:types/ppx:pous/ppx:pou[@name=$type_name] | + exsl:node-set($extensions)/ppx:project/ppx:types/ppx:dataTypes/ppx:dataType[@name=$type_name]""" { + with "instance_path" > «$variable_path» + } + } + } + } + + template "ppx:struct" { + param "variable_path"; + foreach "ppx:variable[ppx:type/ppx:derived or ppx:type/ppx:struct or ppx:type/ppx:array]" { + variable "element_path" > «$variable_path».«@name» + } + apply "ppx:type/*[self::ppx:derived or self::ppx:struct or self::ppx:array]" { + with "variable_path" > «$element_path» + } + } + + template "ppx:array" { + param "variable_path"; + apply "ppx:baseType/*[self::ppx:derived or self::ppx:struct or self::ppx:array]" { + with "variable_path" > «$variable_path» + } + } + +} diff -r 72a826dfcfbb -r 02fe382c4511 plcopen/plcopen.py --- a/plcopen/plcopen.py Wed Jul 31 10:45:07 2013 +0900 +++ b/plcopen/plcopen.py Mon Nov 18 12:12:31 2013 +0900 @@ -23,9 +23,10 @@ #Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA from xmlclass import * -from structures import * from types import * import os, re +from lxml import etree +from collections import OrderedDict """ Dictionary that makes the relation between var names in plcopen and displayed values @@ -48,8 +49,9 @@ """ Define which action qualifier must be associated with a duration """ -QualifierList = {"N" : False, "R" : False, "S" : False, "L" : True, "D" : True, - "P" : False, "P0" : False, "P1" : False, "SD" : True, "DS" : True, "SL" : True} +QualifierList = OrderedDict([("N", False), ("R", False), ("S", False), + ("L", True), ("D", True), ("P", False), ("P0", False), + ("P1", False), ("SD", True), ("DS", True), ("SL", True)]) FILTER_ADDRESS_MODEL = "(%%[IQM](?:[XBWDL])?)(%s)((?:\.[0-9]+)*)" @@ -122,14 +124,167 @@ result = criteria["pattern"].search(text, result.end()) return test_result -PLCOpenClasses = GenerateClassesFromXSD(os.path.join(os.path.split(__file__)[0], "tc6_xml_v201.xsd")) - -ElementNameToClass = {} - -cls = PLCOpenClasses.get("formattedText", None) +PLCOpenParser = GenerateParserFromXSD(os.path.join(os.path.split(__file__)[0], "tc6_xml_v201.xsd")) +PLCOpen_XPath = lambda xpath: etree.XPath(xpath, namespaces=PLCOpenParser.NSMAP) + +LOAD_POU_PROJECT_TEMPLATE = """ + + + + + + + + + + + + %s + + + + + +""" + +def LOAD_POU_INSTANCES_PROJECT_TEMPLATE(body_type): + return LOAD_POU_PROJECT_TEMPLATE % """ + + + <%(body_type)s>%%s + +""" % locals() + +PLCOpen_v1_file = open(os.path.join(os.path.split(__file__)[0], "TC6_XML_V10_B.xsd")) +PLCOpen_v1_xml = PLCOpen_v1_file.read() +PLCOpen_v1_file.close() +PLCOpen_v1_xml = PLCOpen_v1_xml.replace( + "http://www.plcopen.org/xml/tc6.xsd", + "http://www.plcopen.org/xml/tc6_0201") +PLCOpen_v1_xsd = etree.XMLSchema(etree.fromstring(PLCOpen_v1_xml)) + +# XPath for file compatibility process +ProjectResourcesXPath = PLCOpen_XPath("ppx:instances/ppx:configurations/ppx:configuration/ppx:resource") +ResourceInstancesXpath = PLCOpen_XPath("ppx:pouInstance | ppx:task/ppx:pouInstance") +TransitionsConditionXPath = PLCOpen_XPath("ppx:types/ppx:pous/ppx:pou/ppx:body/*/ppx:transition/ppx:condition") +ConditionConnectionsXPath = PLCOpen_XPath("ppx:connection") +ActionBlocksXPath = PLCOpen_XPath("ppx:types/ppx:pous/ppx:pou/ppx:body/*/ppx:actionBlock") +ActionBlocksConnectionPointOutXPath = PLCOpen_XPath("ppx:connectionPointOut") + +def LoadProjectXML(project_xml): + project_xml = project_xml.replace( + "http://www.plcopen.org/xml/tc6.xsd", + "http://www.plcopen.org/xml/tc6_0201") + for cre, repl in [ + (re.compile("(?)(?:)(?!)"), "]]>")]: + project_xml = cre.sub(repl, project_xml) + + try: + tree, error = PLCOpenParser.LoadXMLString(project_xml) + if error is None: + return tree, None + + if PLCOpen_v1_xsd.validate(tree): + # Make file compatible with PLCOpen v2 + + # Update resource interval value + for resource in ProjectResourcesXPath(tree): + for task in resource.gettask(): + interval = task.get("interval") + if interval is not None: + result = time_model.match(interval) + if result is not None: + values = result.groups() + time_values = [int(v) for v in values[:2]] + seconds = float(values[2]) + time_values.extend([int(seconds), int((seconds % 1) * 1000000)]) + text = "T#" + if time_values[0] != 0: + text += "%dh"%time_values[0] + if time_values[1] != 0: + text += "%dm"%time_values[1] + if time_values[2] != 0: + text += "%ds"%time_values[2] + if time_values[3] != 0: + if time_values[3] % 1000 != 0: + text += "%.3fms"%(float(time_values[3]) / 1000) + else: + text += "%dms"%(time_values[3] / 1000) + task.set("interval", text) + + # Update resources pou instance attributes + for pouInstance in ResourceInstancesXpath(resource): + type_name = pouInstance.attrib.pop("type") + if type_name is not None: + pouInstance.set("typeName", type_name) + + # Update transitions condition + for transition_condition in TransitionsConditionXPath(tree): + connections = ConditionConnectionsXPath(transition_condition) + if len(connections) > 0: + connectionPointIn = PLCOpenParser.CreateElement("connectionPointIn", "condition") + transition_condition.setcontent(connectionPointIn) + connectionPointIn.setrelPositionXY(0, 0) + for connection in connections: + connectionPointIn.append(connection) + + # Update actionBlocks + for actionBlock in ActionBlocksXPath(tree): + for connectionPointOut in ActionBlocksConnectionPointOutXPath(actionBlock): + actionBlock.remove(connectionPointOut) + + for action in actionBlock.getaction(): + action.set("localId", "0") + relPosition = PLCOpenParser.CreateElement("relPosition", "action") + relPosition.set("x", "0") + relPosition.set("y", "0") + action.setrelPosition(relPosition) + + return tree, None + + return tree, error + + except Exception, e: + return None, e.message + +def LoadProject(filepath): + project_file = open(filepath) + project_xml = project_file.read() + project_file.close() + return LoadProjectXML(project_xml) + +project_pou_xpath = PLCOpen_XPath("/ppx:project/ppx:types/ppx:pous/ppx:pou") +def LoadPou(xml_string): + root, error = LoadProjectXML(LOAD_POU_PROJECT_TEMPLATE % xml_string) + return project_pou_xpath(root)[0], error + +project_pou_instances_xpath = { + body_type: PLCOpen_XPath( + "/ppx:project/ppx:types/ppx:pous/ppx:pou[@name='paste_pou']/ppx:body/ppx:%s/*" % body_type) + for body_type in ["FBD", "LD", "SFC"]} +def LoadPouInstances(xml_string, body_type): + root, error = LoadProjectXML( + LOAD_POU_INSTANCES_PROJECT_TEMPLATE(body_type) % xml_string) + return project_pou_instances_xpath[body_type](root), error + +def SaveProject(project, filepath): + project_file = open(filepath, 'w') + project_file.write(etree.tostring( + project, + pretty_print=True, + xml_declaration=True, + encoding='utf-8')) + project_file.close() + +cls = PLCOpenParser.GetElementClass("formattedText") if cls: def updateElementName(self, old_name, new_name): - text = self.text + text = self.getanyText() index = text.find(old_name) while index != -1: if index > 0 and (text[index - 1].isalnum() or text[index - 1] == "_"): @@ -139,11 +294,11 @@ else: text = text[:index] + new_name + text[index + len(old_name):] index = text.find(old_name, index + len(new_name)) - self.text = text + self.setanyText(text) setattr(cls, "updateElementName", updateElementName) def updateElementAddress(self, address_model, new_leading): - text = self.text + text = self.getanyText() startpos = 0 result = address_model.search(text, startpos) while result is not None: @@ -151,12 +306,12 @@ new_address = groups[0] + new_leading + groups[2] text = text[:result.start()] + new_address + text[result.end():] startpos = result.start() + len(new_address) - result = address_model.search(self.text, startpos) - self.text = text + result = address_model.search(text, startpos) + self.setanyText(text) setattr(cls, "updateElementAddress", updateElementAddress) def hasblock(self, block_type): - text = self.text.upper() + text = self.getanyText().upper() index = text.find(block_type.upper()) while index != -1: if (not (index > 0 and (text[index - 1].isalnum() or text[index - 1] == "_")) and @@ -167,17 +322,11 @@ setattr(cls, "hasblock", hasblock) def Search(self, criteria, parent_infos): - return [(tuple(parent_infos),) + result for result in TestTextElement(self.gettext(), criteria)] + return [(tuple(parent_infos),) + result for result in TestTextElement(self.getanyText(), criteria)] setattr(cls, "Search", Search) -cls = PLCOpenClasses.get("project", None) -if cls: - cls.singleLineAttributes = False - cls.EnumeratedDataTypeValues = {} - cls.CustomDataTypeRange = {} - cls.CustomTypeHierarchy = {} - cls.ElementUsingTree = {} - cls.CustomBlockTypes = [] +cls = PLCOpenParser.GetElementClass("project") +if cls: def setname(self, name): self.contentHeader.setname(name) @@ -188,532 +337,219 @@ setattr(cls, "getname", getname) def getfileHeader(self): - fileheader = {} - for name, value in [("companyName", self.fileHeader.getcompanyName()), - ("companyURL", self.fileHeader.getcompanyURL()), - ("productName", self.fileHeader.getproductName()), - ("productVersion", self.fileHeader.getproductVersion()), - ("productRelease", self.fileHeader.getproductRelease()), - ("creationDateTime", self.fileHeader.getcreationDateTime()), - ("contentDescription", self.fileHeader.getcontentDescription())]: + fileheader_obj = self.fileHeader + return { + attr: value if value is not None else "" + for attr, value in [ + ("companyName", fileheader_obj.getcompanyName()), + ("companyURL", fileheader_obj.getcompanyURL()), + ("productName", fileheader_obj.getproductName()), + ("productVersion", fileheader_obj.getproductVersion()), + ("productRelease", fileheader_obj.getproductRelease()), + ("creationDateTime", fileheader_obj.getcreationDateTime()), + ("contentDescription", fileheader_obj.getcontentDescription())] + } + setattr(cls, "getfileHeader", getfileHeader) + + def setfileHeader(self, fileheader): + fileheader_obj = self.fileHeader + for attr in ["companyName", "companyURL", "productName", + "productVersion", "productRelease", "creationDateTime", + "contentDescription"]: + value = fileheader.get(attr) if value is not None: - fileheader[name] = value - else: - fileheader[name] = "" - return fileheader - setattr(cls, "getfileHeader", getfileHeader) - - def setfileHeader(self, fileheader): - if fileheader.has_key("companyName"): - self.fileHeader.setcompanyName(fileheader["companyName"]) - if fileheader.has_key("companyURL"): - self.fileHeader.setcompanyURL(fileheader["companyURL"]) - if fileheader.has_key("productName"): - self.fileHeader.setproductName(fileheader["productName"]) - if fileheader.has_key("productVersion"): - self.fileHeader.setproductVersion(fileheader["productVersion"]) - if fileheader.has_key("productRelease"): - self.fileHeader.setproductRelease(fileheader["productRelease"]) - if fileheader.has_key("creationDateTime"): - self.fileHeader.setcreationDateTime(fileheader["creationDateTime"]) - if fileheader.has_key("contentDescription"): - self.fileHeader.setcontentDescription(fileheader["contentDescription"]) + setattr(fileheader_obj, attr, value) setattr(cls, "setfileHeader", setfileHeader) def getcontentHeader(self): - contentheader = {} - for name, value in [("projectName", self.contentHeader.getname()), - ("projectVersion", self.contentHeader.getversion()), - ("modificationDateTime", self.contentHeader.getmodificationDateTime()), - ("organization", self.contentHeader.getorganization()), - ("authorName", self.contentHeader.getauthor()), - ("language", self.contentHeader.getlanguage())]: - if value is not None: - contentheader[name] = value - else: - contentheader[name] = "" + contentheader_obj = self.contentHeader + contentheader = { + attr: value if value is not None else "" + for attr, value in [ + ("projectName", contentheader_obj.getname()), + ("projectVersion", contentheader_obj.getversion()), + ("modificationDateTime", contentheader_obj.getmodificationDateTime()), + ("organization", contentheader_obj.getorganization()), + ("authorName", contentheader_obj.getauthor()), + ("language", contentheader_obj.getlanguage())] + } contentheader["pageSize"] = self.contentHeader.getpageSize() contentheader["scaling"] = self.contentHeader.getscaling() return contentheader setattr(cls, "getcontentHeader", getcontentHeader) def setcontentHeader(self, contentheader): - if contentheader.has_key("projectName"): - self.contentHeader.setname(contentheader["projectName"]) - if contentheader.has_key("projectVersion"): - self.contentHeader.setversion(contentheader["projectVersion"]) - if contentheader.has_key("modificationDateTime"): - self.contentHeader.setmodificationDateTime(contentheader["modificationDateTime"]) - if contentheader.has_key("organization"): - self.contentHeader.setorganization(contentheader["organization"]) - if contentheader.has_key("authorName"): - self.contentHeader.setauthor(contentheader["authorName"]) - if contentheader.has_key("language"): - self.contentHeader.setlanguage(contentheader["language"]) - if contentheader.has_key("pageSize"): - self.contentHeader.setpageSize(*contentheader["pageSize"]) - if contentheader.has_key("scaling"): - self.contentHeader.setscaling(contentheader["scaling"]) + contentheader_obj = self.contentHeader + for attr, value in contentheader.iteritems(): + func = {"projectName": contentheader_obj.setname, + "projectVersion": contentheader_obj.setversion, + "authorName": contentheader_obj.setauthor, + "pageSize": lambda v: contentheader_obj.setpageSize(*v), + "scaling": contentheader_obj.setscaling}.get(attr) + if func is not None: + func(value) + elif attr in ["modificationDateTime", "organization", "language"]: + setattr(contentheader_obj, attr, value) setattr(cls, "setcontentHeader", setcontentHeader) - def getdataTypes(self): - return self.types.getdataTypeElements() + def gettypeElementFunc(element_type): + elements_xpath = PLCOpen_XPath( + "ppx:types/ppx:%(element_type)ss/ppx:%(element_type)s[@name=$name]" % locals()) + def gettypeElement(self, name): + elements = elements_xpath(self, name=name) + if len(elements) == 1: + return elements[0] + return None + return gettypeElement + + datatypes_xpath = PLCOpen_XPath("ppx:types/ppx:dataTypes/ppx:dataType") + filtered_datatypes_xpath = PLCOpen_XPath( + "ppx:types/ppx:dataTypes/ppx:dataType[@name!=$exclude]") + def getdataTypes(self, exclude=None): + if exclude is not None: + return filtered_datatypes_xpath(self, exclude=exclude) + return datatypes_xpath(self) setattr(cls, "getdataTypes", getdataTypes) - def getdataType(self, name): - return self.types.getdataTypeElement(name) - setattr(cls, "getdataType", getdataType) + setattr(cls, "getdataType", gettypeElementFunc("dataType")) def appenddataType(self, name): - if self.CustomTypeHierarchy.has_key(name): + if self.getdataType(name) is not None: raise ValueError, "\"%s\" Data Type already exists !!!"%name self.types.appenddataTypeElement(name) - self.AddCustomDataType(self.getdataType(name)) setattr(cls, "appenddataType", appenddataType) def insertdataType(self, index, datatype): self.types.insertdataTypeElement(index, datatype) - self.AddCustomDataType(datatype) setattr(cls, "insertdataType", insertdataType) def removedataType(self, name): self.types.removedataTypeElement(name) - self.RefreshDataTypeHierarchy() - self.RefreshElementUsingTree() setattr(cls, "removedataType", removedataType) - def getpous(self): - return self.types.getpouElements() + def getpous(self, exclude=None, filter=[]): + return self.xpath( + "ppx:types/ppx:pous/ppx:pou%s%s" % + (("[@name!='%s']" % exclude) if exclude is not None else '', + ("[%s]" % " or ".join( + map(lambda x: "@pouType='%s'" % x, filter))) + if len(filter) > 0 else ""), + namespaces=PLCOpenParser.NSMAP) setattr(cls, "getpous", getpous) - def getpou(self, name): - return self.types.getpouElement(name) - setattr(cls, "getpou", getpou) + setattr(cls, "getpou", gettypeElementFunc("pou")) def appendpou(self, name, pou_type, body_type): self.types.appendpouElement(name, pou_type, body_type) - self.AddCustomBlockType(self.getpou(name)) setattr(cls, "appendpou", appendpou) def insertpou(self, index, pou): self.types.insertpouElement(index, pou) - self.AddCustomBlockType(pou) setattr(cls, "insertpou", insertpou) def removepou(self, name): self.types.removepouElement(name) - self.RefreshCustomBlockTypes() - self.RefreshElementUsingTree() setattr(cls, "removepou", removepou) + configurations_xpath = PLCOpen_XPath( + "ppx:instances/ppx:configurations/ppx:configuration") def getconfigurations(self): - configurations = self.instances.configurations.getconfiguration() - if configurations: - return configurations - return [] + return configurations_xpath(self) setattr(cls, "getconfigurations", getconfigurations) + configuration_xpath = PLCOpen_XPath( + "ppx:instances/ppx:configurations/ppx:configuration[@name=$name]") def getconfiguration(self, name): - for configuration in self.instances.configurations.getconfiguration(): - if configuration.getname() == name: - return configuration + configurations = configuration_xpath(self, name=name) + if len(configurations) == 1: + return configurations[0] return None setattr(cls, "getconfiguration", getconfiguration) def addconfiguration(self, name): - for configuration in self.instances.configurations.getconfiguration(): - if configuration.getname() == name: - raise ValueError, _("\"%s\" configuration already exists !!!")%name - new_configuration = PLCOpenClasses["configurations_configuration"]() + if self.getconfiguration(name) is not None: + raise ValueError, _("\"%s\" configuration already exists !!!") % name + new_configuration = PLCOpenParser.CreateElement("configuration", "configurations") new_configuration.setname(name) self.instances.configurations.appendconfiguration(new_configuration) setattr(cls, "addconfiguration", addconfiguration) def removeconfiguration(self, name): - found = False - for idx, configuration in enumerate(self.instances.configurations.getconfiguration()): - if configuration.getname() == name: - self.instances.configurations.removeconfiguration(idx) - found = True - break - if not found: - raise ValueError, ("\"%s\" configuration doesn't exist !!!")%name + configuration = self.getconfiguration(name) + if configuration is None: + raise ValueError, ("\"%s\" configuration doesn't exist !!!") % name + self.instances.configurations.remove(configuration) setattr(cls, "removeconfiguration", removeconfiguration) - + + resources_xpath = PLCOpen_XPath( + "ppx:instances/ppx:configurations/ppx:configuration[@name=$configname]/ppx:resource[@name=$name]") def getconfigurationResource(self, config_name, name): - configuration = self.getconfiguration(config_name) - if configuration: - for resource in configuration.getresource(): - if resource.getname() == name: - return resource + resources = resources_xpath(self, configname=config_name, name=name) + if len(resources) == 1: + return resources[0] return None setattr(cls, "getconfigurationResource", getconfigurationResource) def addconfigurationResource(self, config_name, name): + if self.getconfigurationResource(config_name, name) is not None: + raise ValueError, _("\"%s\" resource already exists in \"%s\" configuration !!!") % (name, config_name) configuration = self.getconfiguration(config_name) - if configuration: - for resource in configuration.getresource(): - if resource.getname() == name: - raise ValueError, _("\"%s\" resource already exists in \"%s\" configuration !!!")%(name, config_name) - new_resource = PLCOpenClasses["configuration_resource"]() + if configuration is not None: + new_resource = PLCOpenParser.CreateElement("resource", "configuration") new_resource.setname(name) configuration.appendresource(new_resource) setattr(cls, "addconfigurationResource", addconfigurationResource) def removeconfigurationResource(self, config_name, name): configuration = self.getconfiguration(config_name) - if configuration: - found = False - for idx, resource in enumerate(configuration.getresource()): - if resource.getname() == name: - configuration.removeresource(idx) - found = True - break - if not found: - raise ValueError, _("\"%s\" resource doesn't exist in \"%s\" configuration !!!")%(name, config_name) + found = False + if configuration is not None: + resource = self.getconfigurationResource(config_name, name) + if resource is not None: + configuration.remove(resource) + found = True + if not found: + raise ValueError, _("\"%s\" resource doesn't exist in \"%s\" configuration !!!")%(name, config_name) setattr(cls, "removeconfigurationResource", removeconfigurationResource) def updateElementName(self, old_name, new_name): - for datatype in self.types.getdataTypeElements(): + for datatype in self.getdataTypes(): datatype.updateElementName(old_name, new_name) - for pou in self.types.getpouElements(): + for pou in self.getpous(): pou.updateElementName(old_name, new_name) - for configuration in self.instances.configurations.getconfiguration(): + for configuration in self.getconfigurations(): configuration.updateElementName(old_name, new_name) setattr(cls, "updateElementName", updateElementName) def updateElementAddress(self, old_leading, new_leading): address_model = re.compile(FILTER_ADDRESS_MODEL % old_leading) - for pou in self.types.getpouElements(): + for pou in self.getpous(): pou.updateElementAddress(address_model, new_leading) - for configuration in self.instances.configurations.getconfiguration(): + for configuration in self.getconfigurations(): configuration.updateElementAddress(address_model, new_leading) setattr(cls, "updateElementAddress", updateElementAddress) def removeVariableByAddress(self, address): - for pou in self.types.getpouElements(): + for pou in self.getpous(): pou.removeVariableByAddress(address) - for configuration in self.instances.configurations.getconfiguration(): + for configuration in self.getconfigurations(): configuration.removeVariableByAddress(address) setattr(cls, "removeVariableByAddress", removeVariableByAddress) def removeVariableByFilter(self, leading): address_model = re.compile(FILTER_ADDRESS_MODEL % leading) - for pou in self.types.getpouElements(): + for pou in self.getpous(): pou.removeVariableByFilter(address_model) - for configuration in self.instances.configurations.getconfiguration(): + for configuration in self.getconfigurations(): configuration.removeVariableByFilter(address_model) setattr(cls, "removeVariableByFilter", removeVariableByFilter) - def RefreshDataTypeHierarchy(self): - self.EnumeratedDataTypeValues = {} - self.CustomDataTypeRange = {} - self.CustomTypeHierarchy = {} - for datatype in self.getdataTypes(): - self.AddCustomDataType(datatype) - setattr(cls, "RefreshDataTypeHierarchy", RefreshDataTypeHierarchy) - - def AddCustomDataType(self, datatype): - name = datatype.getname() - basetype_content = datatype.getbaseType().getcontent() - if basetype_content["value"] is None: - self.CustomTypeHierarchy[name] = basetype_content["name"] - elif basetype_content["name"] in ["string", "wstring"]: - self.CustomTypeHierarchy[name] = basetype_content["name"].upper() - elif basetype_content["name"] == "derived": - self.CustomTypeHierarchy[name] = basetype_content["value"].getname() - elif basetype_content["name"] in ["subrangeSigned", "subrangeUnsigned"]: - range = (basetype_content["value"].range.getlower(), - basetype_content["value"].range.getupper()) - self.CustomDataTypeRange[name] = range - base_type = basetype_content["value"].baseType.getcontent() - if base_type["value"] is None: - self.CustomTypeHierarchy[name] = base_type["name"] - else: - self.CustomTypeHierarchy[name] = base_type["value"].getname() - else: - if basetype_content["name"] == "enum": - values = [] - for value in basetype_content["value"].values.getvalue(): - values.append(value.getname()) - self.EnumeratedDataTypeValues[name] = values - self.CustomTypeHierarchy[name] = "ANY_DERIVED" - setattr(cls, "AddCustomDataType", AddCustomDataType) - - # Update Block types with user-defined pou added - def RefreshCustomBlockTypes(self): - # Reset the tree of user-defined pou cross-use - self.CustomBlockTypes = [] - for pou in self.getpous(): - self.AddCustomBlockType(pou) - setattr(cls, "RefreshCustomBlockTypes", RefreshCustomBlockTypes) - - def AddCustomBlockType(self, pou): - pou_name = pou.getname() - pou_type = pou.getpouType() - block_infos = {"name" : pou_name, "type" : pou_type, "extensible" : False, - "inputs" : [], "outputs" : [], "comment" : pou.getdescription(), - "generate" : generate_block, "initialise" : initialise_block} - if pou.getinterface(): - return_type = pou.interface.getreturnType() - if return_type: - var_type = return_type.getcontent() - if var_type["name"] == "derived": - block_infos["outputs"].append(("OUT", var_type["value"].getname(), "none")) - elif var_type["name"] in ["string", "wstring"]: - block_infos["outputs"].append(("OUT", var_type["name"].upper(), "none")) - else: - block_infos["outputs"].append(("OUT", var_type["name"], "none")) - for type, varlist in pou.getvars(): - if type == "InOut": - for var in varlist.getvariable(): - var_type = var.type.getcontent() - if var_type["name"] == "derived": - block_infos["inputs"].append((var.getname(), var_type["value"].getname(), "none")) - block_infos["outputs"].append((var.getname(), var_type["value"].getname(), "none")) - elif var_type["name"] in ["string", "wstring"]: - block_infos["inputs"].append((var.getname(), var_type["name"].upper(), "none")) - block_infos["outputs"].append((var.getname(), var_type["name"].upper(), "none")) - else: - block_infos["inputs"].append((var.getname(), var_type["name"], "none")) - block_infos["outputs"].append((var.getname(), var_type["name"], "none")) - elif type == "Input": - for var in varlist.getvariable(): - var_type = var.type.getcontent() - if var_type["name"] == "derived": - block_infos["inputs"].append((var.getname(), var_type["value"].getname(), "none")) - elif var_type["name"] in ["string", "wstring"]: - block_infos["inputs"].append((var.getname(), var_type["name"].upper(), "none")) - else: - block_infos["inputs"].append((var.getname(), var_type["name"], "none")) - elif type == "Output": - for var in varlist.getvariable(): - var_type = var.type.getcontent() - if var_type["name"] == "derived": - block_infos["outputs"].append((var.getname(), var_type["value"].getname(), "none")) - elif var_type["name"] in ["string", "wstring"]: - block_infos["outputs"].append((var.getname(), var_type["name"].upper(), "none")) - else: - block_infos["outputs"].append((var.getname(), var_type["name"], "none")) - block_infos["usage"] = "\n (%s) => (%s)" % (", ".join(["%s:%s" % (input[1], input[0]) for input in block_infos["inputs"]]), - ", ".join(["%s:%s" % (output[1], output[0]) for output in block_infos["outputs"]])) - self.CustomBlockTypes.append(block_infos) - setattr(cls, "AddCustomBlockType", AddCustomBlockType) - - def AddElementUsingTreeInstance(self, name, type_infos): - typename = type_infos.getname() - if not self.ElementUsingTree.has_key(typename): - self.ElementUsingTree[typename] = [name] - elif name not in self.ElementUsingTree[typename]: - self.ElementUsingTree[typename].append(name) - setattr(cls, "AddElementUsingTreeInstance", AddElementUsingTreeInstance) - - def RefreshElementUsingTree(self): - # Reset the tree of user-defined element cross-use - self.ElementUsingTree = {} - pous = self.getpous() - datatypes = self.getdataTypes() - # Analyze each datatype - for datatype in datatypes: - name = datatype.getname() - basetype_content = datatype.baseType.getcontent() - if basetype_content["name"] == "derived": - typename = basetype_content["value"].getname() - if name in self.ElementUsingTree[typename]: - self.ElementUsingTree[typename].append(name) - elif basetype_content["name"] in ["subrangeSigned", "subrangeUnsigned", "array"]: - base_type = basetype_content["value"].baseType.getcontent() - if base_type["name"] == "derived": - self.AddElementUsingTreeInstance(name, base_type["value"]) - elif basetype_content["name"] == "struct": - for element in basetype_content["value"].getvariable(): - type_content = element.type.getcontent() - if type_content["name"] == "derived": - self.AddElementUsingTreeInstance(name, type_content["value"]) - # Analyze each pou - for pou in pous: - name = pou.getname() - if pou.interface: - # Extract variables from every varLists - for type, varlist in pou.getvars(): - for var in varlist.getvariable(): - vartype_content = var.gettype().getcontent() - if vartype_content["name"] == "derived": - self.AddElementUsingTreeInstance(name, vartype_content["value"]) - for typename in self.ElementUsingTree.iterkeys(): - if typename != name and pou.hasblock(block_type=typename) and name not in self.ElementUsingTree[typename]: - self.ElementUsingTree[typename].append(name) - - setattr(cls, "RefreshElementUsingTree", RefreshElementUsingTree) - - def GetParentType(self, type): - if self.CustomTypeHierarchy.has_key(type): - return self.CustomTypeHierarchy[type] - elif TypeHierarchy.has_key(type): - return TypeHierarchy[type] - return None - setattr(cls, "GetParentType", GetParentType) - - def GetBaseType(self, type): - parent_type = self.GetParentType(type) - if parent_type is not None: - if parent_type.startswith("ANY"): - return type - else: - return self.GetBaseType(parent_type) - return None - setattr(cls, "GetBaseType", GetBaseType) - - def GetSubrangeBaseTypes(self, exclude): - derived = [] - for type in self.CustomTypeHierarchy.keys(): - for base_type in DataTypeRange.keys(): - if self.IsOfType(type, base_type) and not self.IsOfType(type, exclude): - derived.append(type) - break - return derived - setattr(cls, "GetSubrangeBaseTypes", GetSubrangeBaseTypes) - - """ - returns true if the given data type is the same that "reference" meta-type or one of its types. - """ - def IsOfType(self, type, reference): - if reference is None: - return True - elif type == reference: - return True - else: - parent_type = self.GetParentType(type) - if parent_type is not None: - return self.IsOfType(parent_type, reference) - return False - setattr(cls, "IsOfType", IsOfType) - - # Return if pou given by name is used by another pou - def ElementIsUsed(self, name): - if self.ElementUsingTree.has_key(name): - return len(self.ElementUsingTree[name]) > 0 - return False - setattr(cls, "ElementIsUsed", ElementIsUsed) - - def DataTypeIsDerived(self, name): - return name in self.CustomTypeHierarchy.values() - setattr(cls, "DataTypeIsDerived", DataTypeIsDerived) - - # Return if pou given by name is directly or undirectly used by the reference pou - def ElementIsUsedBy(self, name, reference): - if self.ElementUsingTree.has_key(name): - list = self.ElementUsingTree[name] - # Test if pou is directly used by reference - if reference in list: - return True - else: - # Test if pou is undirectly used by reference, by testing if pous - # that directly use pou is directly or undirectly used by reference - used = False - for element in list: - used |= self.ElementIsUsedBy(element, reference) - return used - return False - setattr(cls, "ElementIsUsedBy", ElementIsUsedBy) - - def GetDataTypeRange(self, type): - if self.CustomDataTypeRange.has_key(type): - return self.CustomDataTypeRange[type] - elif DataTypeRange.has_key(type): - return DataTypeRange[type] - else: - parent_type = self.GetParentType(type) - if parent_type is not None: - return self.GetDataTypeRange(parent_type) - return None - setattr(cls, "GetDataTypeRange", GetDataTypeRange) - - def GetEnumeratedDataTypeValues(self, type = None): - if type is None: - all_values = [] - for values in self.EnumeratedDataTypeValues.values(): - all_values.extend(values) - return all_values - elif self.EnumeratedDataTypeValues.has_key(type): - return self.EnumeratedDataTypeValues[type] - return [] + enumerated_values_xpath = PLCOpen_XPath( + "ppx:types/ppx:dataTypes/ppx:dataType/ppx:baseType/ppx:enum/ppx:values/ppx:value") + def GetEnumeratedDataTypeValues(self): + return [value.getname() for value in enumerated_values_xpath(self)] setattr(cls, "GetEnumeratedDataTypeValues", GetEnumeratedDataTypeValues) - # Function that returns the block definition associated to the block type given - def GetCustomBlockType(self, type, inputs = None): - for customblocktype in self.CustomBlockTypes: - if inputs is not None and inputs != "undefined": - customblock_inputs = tuple([var_type for name, var_type, modifier in customblocktype["inputs"]]) - same_inputs = inputs == customblock_inputs - else: - same_inputs = True - if customblocktype["name"] == type and same_inputs: - return customblocktype - return None - setattr(cls, "GetCustomBlockType", GetCustomBlockType) - - # Return Block types checking for recursion - def GetCustomBlockTypes(self, exclude = "", onlyfunctions = False): - type = None - if exclude != "": - pou = self.getpou(exclude) - if pou is not None: - type = pou.getpouType() - customblocktypes = [] - for customblocktype in self.CustomBlockTypes: - if customblocktype["type"] != "program" and customblocktype["name"] != exclude and not self.ElementIsUsedBy(exclude, customblocktype["name"]) and not (onlyfunctions and customblocktype["type"] != "function"): - customblocktypes.append(customblocktype) - return customblocktypes - setattr(cls, "GetCustomBlockTypes", GetCustomBlockTypes) - - # Return Function Block types checking for recursion - def GetCustomFunctionBlockTypes(self, exclude = ""): - customblocktypes = [] - for customblocktype in self.CustomBlockTypes: - if customblocktype["type"] == "functionBlock" and customblocktype["name"] != exclude and not self.ElementIsUsedBy(exclude, customblocktype["name"]): - customblocktypes.append(customblocktype["name"]) - return customblocktypes - setattr(cls, "GetCustomFunctionBlockTypes", GetCustomFunctionBlockTypes) - - # Return Block types checking for recursion - def GetCustomBlockResource(self): - customblocktypes = [] - for customblocktype in self.CustomBlockTypes: - if customblocktype["type"] == "program": - customblocktypes.append(customblocktype["name"]) - return customblocktypes - setattr(cls, "GetCustomBlockResource", GetCustomBlockResource) - - # Return Data Types checking for recursion - def GetCustomDataTypes(self, exclude = "", only_locatable = False): - customdatatypes = [] - for customdatatype in self.getdataTypes(): - if not only_locatable or self.IsLocatableType(customdatatype): - customdatatype_name = customdatatype.getname() - if customdatatype_name != exclude and not self.ElementIsUsedBy(exclude, customdatatype_name): - customdatatypes.append({"name": customdatatype_name, "infos": customdatatype}) - return customdatatypes - setattr(cls, "GetCustomDataTypes", GetCustomDataTypes) - - # Return if Data Type can be used for located variables - def IsLocatableType(self, datatype): - basetype_content = datatype.baseType.getcontent() - if basetype_content["name"] in ["enum", "struct"]: - return False - elif basetype_content["name"] == "derived": - base_type = self.getdataType(basetype_content["value"].getname()) - if base_type is not None: - return self.IsLocatableType(base_type) - elif basetype_content["name"] == "array": - array_base_type = basetype_content["value"].baseType.getcontent() - if array_base_type["value"] is not None and array_base_type["name"] not in ["string", "wstring"]: - base_type = self.getdataType(array_base_type["value"].getname()) - if base_type is not None: - return self.IsLocatableType(base_type) - return True - setattr(cls, "IsLocatableType", IsLocatableType) - def Search(self, criteria, parent_infos=[]): result = self.types.Search(criteria, parent_infos) for configuration in self.instances.configurations.getconfiguration(): @@ -721,13 +557,8 @@ return result setattr(cls, "Search", Search) -cls = PLCOpenClasses.get("project_fileHeader", None) -if cls: - cls.singleLineAttributes = False - -cls = PLCOpenClasses.get("project_contentHeader", None) -if cls: - cls.singleLineAttributes = False +cls = PLCOpenParser.GetElementClass("contentHeader", "project") +if cls: def setpageSize(self, width, height): self.coordinateInfo.setpageSize(width, height) @@ -750,7 +581,7 @@ return scaling setattr(cls, "getscaling", getscaling) -cls = PLCOpenClasses.get("contentHeader_coordinateInfo", None) +cls = PLCOpenParser.GetElementClass("coordinateInfo", "contentHeader") if cls: def setpageSize(self, width, height): if width == 0 and height == 0: @@ -819,7 +650,7 @@ variables = varlist.getvariable() for i in xrange(len(variables)-1, -1, -1): if variables[i].getaddress() == address: - variables.pop(i) + variables.remove(variables[i]) def _removeConfigurationResourceVariableByFilter(self, address_model): for varlist in self.getglobalVars(): @@ -829,7 +660,7 @@ if var_address is not None: result = address_model.match(var_address) if result is not None: - variables.pop(i) + variables.remove(variables[i]) def _SearchInConfigurationResource(self, criteria, parent_infos=[]): search_result = _Search([("name", self.getname())], criteria, parent_infos) @@ -849,33 +680,21 @@ var_number += 1 return search_result -cls = PLCOpenClasses.get("configurations_configuration", None) -if cls: - - def addglobalVar(self, type, name, location="", description=""): +cls = PLCOpenParser.GetElementClass("configuration", "configurations") +if cls: + + def addglobalVar(self, var_type, name, location="", description=""): globalvars = self.getglobalVars() if len(globalvars) == 0: - globalvars.append(PLCOpenClasses["varList"]()) - var = PLCOpenClasses["varListPlain_variable"]() + globalvars.append(PLCOpenParser.CreateElement("varList")) + var = PLCOpenParser.CreateElement("variable", "varListPlain") var.setname(name) - var_type = PLCOpenClasses["dataType"]() - if type in [x for x,y in TypeHierarchy_list if not x.startswith("ANY")]: - if type == "STRING": - var_type.setcontent({"name" : "string", "value" : PLCOpenClasses["elementaryTypes_string"]()}) - elif type == "WSTRING": - var_type.setcontent({"name" : "wstring", "value" : PLCOpenClasses["elementaryTypes_wstring"]()}) - else: - var_type.setcontent({"name" : type, "value" : None}) - else: - derived_type = PLCOpenClasses["derivedTypes_derived"]() - derived_type.setname(type) - var_type.setcontent({"name" : "derived", "value" : derived_type}) var.settype(var_type) if location != "": var.setaddress(location) if description != "": - ft = PLCOpenClasses["formattedText"]() - ft.settext(description) + ft = PLCOpenParser.CreateElement("documentation", "variable") + ft.setanyText(description) var.setdocumentation(ft) globalvars[-1].appendvariable(var) setattr(cls, "addglobalVar", addglobalVar) @@ -906,7 +725,7 @@ return search_result setattr(cls, "Search", Search) -cls = PLCOpenClasses.get("configuration_resource", None) +cls = PLCOpenParser.GetElementClass("resource", "configuration") if cls: def updateElementName(self, old_name, new_name): _updateConfigurationResourceElementName(self, old_name, new_name) @@ -947,32 +766,8 @@ return search_result setattr(cls, "Search", Search) -cls = PLCOpenClasses.get("resource_task", None) -if cls: - def compatibility(self, tree): - if tree.hasAttribute("interval"): - interval = GetAttributeValue(tree._attrs["interval"]) - result = time_model.match(interval) - if result is not None: - values = result.groups() - time_values = [int(v) for v in values[:2]] - seconds = float(values[2]) - time_values.extend([int(seconds), int((seconds % 1) * 1000000)]) - text = "t#" - if time_values[0] != 0: - text += "%dh"%time_values[0] - if time_values[1] != 0: - text += "%dm"%time_values[1] - if time_values[2] != 0: - text += "%ds"%time_values[2] - if time_values[3] != 0: - if time_values[3] % 1000 != 0: - text += "%.3fms"%(float(time_values[3]) / 1000) - else: - text += "%dms"%(time_values[3] / 1000) - NodeSetAttr(tree, "interval", text) - setattr(cls, "compatibility", compatibility) - +cls = PLCOpenParser.GetElementClass("task", "resource") +if cls: def updateElementName(self, old_name, new_name): if self.single == old_name: self.single = new_name @@ -996,13 +791,8 @@ criteria, parent_infos) setattr(cls, "Search", Search) -cls = PLCOpenClasses.get("pouInstance", None) -if cls: - def compatibility(self, tree): - if tree.hasAttribute("type"): - NodeRenameAttr(tree, "type", "typeName") - setattr(cls, "compatibility", compatibility) - +cls = PLCOpenParser.GetElementClass("pouInstance") +if cls: def updateElementName(self, old_name, new_name): if self.typeName == old_name: self.typeName = new_name @@ -1014,31 +804,33 @@ criteria, parent_infos) setattr(cls, "Search", Search) -cls = PLCOpenClasses.get("varListPlain_variable", None) +cls = PLCOpenParser.GetElementClass("variable", "varListPlain") if cls: def gettypeAsText(self): vartype_content = self.gettype().getcontent() + vartype_content_name = vartype_content.getLocalTag() # Variable type is a user data type - if vartype_content["name"] == "derived": - return vartype_content["value"].getname() + if vartype_content_name == "derived": + return vartype_content.getname() # Variable type is a string type - elif vartype_content["name"] in ["string", "wstring"]: - return vartype_content["name"].upper() + elif vartype_content_name in ["string", "wstring"]: + return vartype_content_name.upper() # Variable type is an array - elif vartype_content["name"] == "array": - base_type = vartype_content["value"].baseType.getcontent() + elif vartype_content_name == "array": + base_type = vartype_content.baseType.getcontent() + base_type_name = base_type.getLocalTag() # Array derived directly from a user defined type - if base_type["name"] == "derived": - basetype_name = base_type["value"].getname() + if base_type_name == "derived": + basetype_name = base_type.getname() # Array derived directly from a string type - elif base_type["name"] in ["string", "wstring"]: - basetype_name = base_type["name"].upper() + elif base_type_name in ["string", "wstring"]: + basetype_name = base_type_name.upper() # Array derived directly from an elementary type else: - basetype_name = base_type["name"] - return "ARRAY [%s] OF %s" % (",".join(map(lambda x : "%s..%s" % (x.getlower(), x.getupper()), vartype_content["value"].getdimension())), basetype_name) + basetype_name = base_type_name + return "ARRAY [%s] OF %s" % (",".join(map(lambda x : "%s..%s" % (x.getlower(), x.getupper()), vartype_content.getdimension())), basetype_name) # Variable type is an elementary type - return vartype_content["name"] + return vartype_content_name setattr(cls, "gettypeAsText", gettypeAsText) def Search(self, criteria, parent_infos=[]): @@ -1055,7 +847,7 @@ return search_result setattr(cls, "Search", Search) -cls = PLCOpenClasses.get("project_types", None) +cls = PLCOpenParser.GetElementClass("types", "project") if cls: def getdataTypeElements(self): return self.dataTypes.getdataType() @@ -1070,10 +862,10 @@ setattr(cls, "getdataTypeElement", getdataTypeElement) def appenddataTypeElement(self, name): - new_datatype = PLCOpenClasses["dataTypes_dataType"]() + new_datatype = PLCOpenParser.CreateElement("dataType", "dataTypes") + self.dataTypes.appenddataType(new_datatype) new_datatype.setname(name) - new_datatype.baseType.setcontent({"name" : "BOOL", "value" : None}) - self.dataTypes.appenddataType(new_datatype) + new_datatype.baseType.setcontent(PLCOpenParser.CreateElement("BOOL", "dataType")) setattr(cls, "appenddataTypeElement", appenddataTypeElement) def insertdataTypeElement(self, index, dataType): @@ -1082,9 +874,9 @@ def removedataTypeElement(self, name): found = False - for idx, element in enumerate(self.dataTypes.getdataType()): + for element in self.dataTypes.getdataType(): if element.getname() == name: - self.dataTypes.removedataType(idx) + self.dataTypes.remove(element) found = True break if not found: @@ -1107,12 +899,12 @@ for element in self.pous.getpou(): if element.getname() == name: raise ValueError, _("\"%s\" POU already exists !!!")%name - new_pou = PLCOpenClasses["pous_pou"]() + new_pou = PLCOpenParser.CreateElement("pou", "pous") + self.pous.appendpou(new_pou) new_pou.setname(name) new_pou.setpouType(pou_type) - new_pou.appendbody(PLCOpenClasses["body"]()) + new_pou.appendbody(PLCOpenParser.CreateElement("body", "pou")) new_pou.setbodyType(body_type) - self.pous.appendpou(new_pou) setattr(cls, "appendpouElement", appendpouElement) def insertpouElement(self, index, pou): @@ -1121,9 +913,9 @@ def removepouElement(self, name): found = False - for idx, element in enumerate(self.pous.getpou()): + for element in self.pous.getpou(): if element.getname() == name: - self.pous.removepou(idx) + self.pous.remove(element) found = True break if not found: @@ -1143,7 +935,7 @@ def _updateBaseTypeElementName(self, old_name, new_name): self.baseType.updateElementName(old_name, new_name) -cls = PLCOpenClasses.get("dataTypes_dataType", None) +cls = PLCOpenParser.GetElementClass("dataType", "dataTypes") if cls: setattr(cls, "updateElementName", _updateBaseTypeElementName) @@ -1159,33 +951,45 @@ return search_result setattr(cls, "Search", Search) -cls = PLCOpenClasses.get("dataType", None) +cls = PLCOpenParser.GetElementClass("dataType") if cls: def updateElementName(self, old_name, new_name): - if self.content["name"] in ["derived", "array", "subrangeSigned", "subrangeUnsigned"]: - self.content["value"].updateElementName(old_name, new_name) - elif self.content["name"] == "struct": - for element in self.content["value"].getvariable(): + content_name = self.content.getLocalTag() + if content_name in ["derived", "array", "subrangeSigned", "subrangeUnsigned"]: + self.content.updateElementName(old_name, new_name) + elif content_name == "struct": + for element in self.content.getvariable(): element_type = element.type.updateElementName(old_name, new_name) setattr(cls, "updateElementName", updateElementName) def Search(self, criteria, parent_infos=[]): search_result = [] - if self.content["name"] in ["derived", "array", "enum", "subrangeSigned", "subrangeUnsigned"]: - search_result.extend(self.content["value"].Search(criteria, parent_infos)) - elif self.content["name"] == "struct": - for i, element in enumerate(self.content["value"].getvariable()): + content_name = self.content.getLocalTag() + if content_name in ["derived", "array", "enum", "subrangeSigned", "subrangeUnsigned"]: + search_result.extend(self.content.Search(criteria, parent_infos + ["base"])) + elif content_name == "struct": + for i, element in enumerate(self.content.getvariable()): search_result.extend(element.Search(criteria, parent_infos + ["struct", i])) else: - basetype = self.content["name"] - if basetype in ["string", "wstring"]: - basetype = basetype.upper() - search_result.extend(_Search([("base", basetype)], criteria, parent_infos)) + if content_name in ["string", "wstring"]: + content_name = content_name.upper() + search_result.extend(_Search([("base", content_name)], criteria, parent_infos)) return search_result setattr(cls, "Search", Search) -cls = PLCOpenClasses.get("derivedTypes_array", None) +cls = PLCOpenParser.GetElementClass("derived", "dataType") +if cls: + def updateElementName(self, old_name, new_name): + if self.name == old_name: + self.name = new_name + setattr(cls, "updateElementName", updateElementName) + + def Search(self, criteria, parent_infos=[]): + return [(tuple(parent_infos),) + result for result in TestTextElement(self.name, criteria)] + setattr(cls, "Search", Search) + +cls = PLCOpenParser.GetElementClass("array", "dataType") if cls: setattr(cls, "updateElementName", _updateBaseTypeElementName) @@ -1205,68 +1009,100 @@ criteria, parent_infos)) return search_result -cls = PLCOpenClasses.get("derivedTypes_subrangeSigned", None) +cls = PLCOpenParser.GetElementClass("subrangeSigned", "dataType") if cls: setattr(cls, "updateElementName", _updateBaseTypeElementName) setattr(cls, "Search", _SearchInSubrange) -cls = PLCOpenClasses.get("derivedTypes_subrangeUnsigned", None) +cls = PLCOpenParser.GetElementClass("subrangeUnsigned", "dataType") if cls: setattr(cls, "updateElementName", _updateBaseTypeElementName) setattr(cls, "Search", _SearchInSubrange) -cls = PLCOpenClasses.get("derivedTypes_enum", None) +cls = PLCOpenParser.GetElementClass("enum", "dataType") if cls: def updateElementName(self, old_name, new_name): pass setattr(cls, "updateElementName", updateElementName) + enumerated_datatype_values_xpath = PLCOpen_XPath("ppx:values/ppx:value") def Search(self, criteria, parent_infos=[]): search_result = [] - for i, value in enumerate(self.values.getvalue()): + for i, value in enumerate(enumerated_datatype_values_xpath(self)): for result in TestTextElement(value.getname(), criteria): search_result.append((tuple(parent_infos + ["value", i]),) + result) return search_result setattr(cls, "Search", Search) -cls = PLCOpenClasses.get("pous_pou", None) -if cls: +def _getvariableTypeinfos(variable_type): + type_content = variable_type.getcontent() + type_content_type = type_content.getLocalTag() + if type_content_type == "derived": + return type_content.getname() + return type_content_type.upper() + +cls = PLCOpenParser.GetElementClass("pou", "pous") +if cls: + + block_inputs_xpath = PLCOpen_XPath( + "ppx:interface/*[self::ppx:inputVars or self::ppx:inOutVars]/ppx:variable") + block_outputs_xpath = PLCOpen_XPath( + "ppx:interface/*[self::ppx:outputVars or self::ppx:inOutVars]/ppx:variable") + def getblockInfos(self): + block_infos = { + "name" : self.getname(), + "type" : self.getpouType(), + "extensible" : False, + "inputs" : [], + "outputs" : [], + "comment" : self.getdescription()} + if self.interface is not None: + return_type = self.interface.getreturnType() + if return_type is not None: + block_infos["outputs"].append( + ("OUT", _getvariableTypeinfos(return_type), "none")) + block_infos["inputs"].extend( + [(var.getname(), _getvariableTypeinfos(var.type), "none") + for var in block_inputs_xpath(self)]) + block_infos["outputs"].extend( + [(var.getname(), _getvariableTypeinfos(var.type), "none") + for var in block_outputs_xpath(self)]) + + block_infos["usage"] = ("\n (%s) => (%s)" % + (", ".join(["%s:%s" % (input[1], input[0]) + for input in block_infos["inputs"]]), + ", ".join(["%s:%s" % (output[1], output[0]) + for output in block_infos["outputs"]]))) + return block_infos + setattr(cls, "getblockInfos", getblockInfos) def setdescription(self, description): doc = self.getdocumentation() if doc is None: - doc = PLCOpenClasses["formattedText"]() + doc = PLCOpenParser.CreateElement("documentation", "pou") self.setdocumentation(doc) - doc.settext(description) + doc.setanyText(description) setattr(cls, "setdescription", setdescription) def getdescription(self): doc = self.getdocumentation() if doc is not None: - return doc.gettext() + return doc.getanyText() return "" setattr(cls, "getdescription", getdescription) - def setbodyType(self, type): + def setbodyType(self, body_type): if len(self.body) > 0: - if type == "IL": - self.body[0].setcontent({"name" : "IL", "value" : PLCOpenClasses["formattedText"]()}) - elif type == "ST": - self.body[0].setcontent({"name" : "ST", "value" : PLCOpenClasses["formattedText"]()}) - elif type == "LD": - self.body[0].setcontent({"name" : "LD", "value" : PLCOpenClasses["body_LD"]()}) - elif type == "FBD": - self.body[0].setcontent({"name" : "FBD", "value" : PLCOpenClasses["body_FBD"]()}) - elif type == "SFC": - self.body[0].setcontent({"name" : "SFC", "value" : PLCOpenClasses["body_SFC"]()}) + if body_type in ["IL", "ST", "LD", "FBD", "SFC"]: + self.body[0].setcontent(PLCOpenParser.CreateElement(body_type, "body")) else: raise ValueError, "%s isn't a valid body type!"%type setattr(cls, "setbodyType", setbodyType) def getbodyType(self): if len(self.body) > 0: - return self.body[0].getcontent()["name"] + return self.body[0].getcontent().getLocalTag() setattr(cls, "getbodyType", getbodyType) def resetexecutionOrder(self): @@ -1284,9 +1120,9 @@ self.body[0].setelementExecutionOrder(instance, new_executionOrder) setattr(cls, "setelementExecutionOrder", setelementExecutionOrder) - def addinstance(self, name, instance): + def addinstance(self, instance): if len(self.body) > 0: - self.body[0].appendcontentInstance(name, instance) + self.body[0].appendcontentInstance(instance) setattr(cls, "addinstance", addinstance) def getinstances(self): @@ -1301,11 +1137,11 @@ return None setattr(cls, "getinstance", getinstance) - def getrandomInstance(self, exclude): + def getinstancesIds(self): if len(self.body) > 0: - return self.body[0].getcontentRandomInstance(exclude) - return None - setattr(cls, "getrandomInstance", getrandomInstance) + return self.body[0].getcontentInstancesIds() + return [] + setattr(cls, "getinstancesIds", getinstancesIds) def getinstanceByName(self, name): if len(self.body) > 0: @@ -1336,96 +1172,85 @@ for name, value in VarTypes.items(): reverse_types[value] = name for varlist in self.interface.getcontent(): - vars.append((reverse_types[varlist["name"]], varlist["value"])) + vars.append((reverse_types[varlist.getLocalTag()], varlist)) return vars setattr(cls, "getvars", getvars) def setvars(self, vars): if self.interface is None: - self.interface = PLCOpenClasses["pou_interface"]() - self.interface.setcontent([]) - for vartype, varlist in vars: - self.interface.appendcontent({"name" : VarTypes[vartype], "value" : varlist}) + self.interface = PLCOpenParser.CreateElement("interface", "pou") + self.interface.setcontent(vars) setattr(cls, "setvars", setvars) - def addpouLocalVar(self, type, name, location="", description=""): - self.addpouVar(type, name, location=location, description=description) + def addpouLocalVar(self, var_type, name, location="", description=""): + self.addpouVar(var_type, name, location=location, description=description) setattr(cls, "addpouLocalVar", addpouLocalVar) - def addpouExternalVar(self, type, name): + def addpouExternalVar(self, var_type, name): self.addpouVar(type, name, "externalVars") setattr(cls, "addpouExternalVar", addpouExternalVar) - def addpouVar(self, type, name, var_class="localVars", location="", description=""): + def addpouVar(self, var_type, name, var_class="localVars", location="", description=""): if self.interface is None: - self.interface = PLCOpenClasses["pou_interface"]() + self.interface = PLCOpenParser.CreateElement("interface", "pou") content = self.interface.getcontent() - if len(content) == 0 or content[-1]["name"] != var_class: - content.append({"name" : var_class, "value" : PLCOpenClasses["interface_%s" % var_class]()}) + if len(content) == 0: + varlist = PLCOpenParser.CreateElement(var_class, "interface") + self.interface.setcontent([varlist]) + elif content[-1].getLocalTag() != var_class: + varlist = PLCOpenParser.CreateElement(var_class, "interface") + content[-1].addnext(varlist) else: - varlist = content[-1]["value"] + varlist = content[-1] variables = varlist.getvariable() if varlist.getconstant() or varlist.getretain() or len(variables) > 0 and variables[0].getaddress(): - content.append({"name" : var_class, "value" : PLCOpenClasses["interface_%s" % var_class]()}) - var = PLCOpenClasses["varListPlain_variable"]() + varlist = PLCOpenParser.CreateElement(var_class, "interface") + content[-1].addnext(varlist) + var = PLCOpenParser.CreateElement("variable", "varListPlain") var.setname(name) - var_type = PLCOpenClasses["dataType"]() - if type in [x for x,y in TypeHierarchy_list if not x.startswith("ANY")]: - if type == "STRING": - var_type.setcontent({"name" : "string", "value" : PLCOpenClasses["elementaryTypes_string"]()}) - elif type == "WSTRING": - var_type.setcontent({"name" : "wstring", "value" : PLCOpenClasses["elementaryTypes_wstring"]()}) - else: - var_type.setcontent({"name" : type, "value" : None}) - else: - derived_type = PLCOpenClasses["derivedTypes_derived"]() - derived_type.setname(type) - var_type.setcontent({"name" : "derived", "value" : derived_type}) var.settype(var_type) if location != "": var.setaddress(location) if description != "": - ft = PLCOpenClasses["formattedText"]() - ft.settext(description) + ft = PLCOpenParser.CreateElement("documentation", "variable") + ft.setanyText(description) var.setdocumentation(ft) - content[-1]["value"].appendvariable(var) + varlist.appendvariable(var) setattr(cls, "addpouVar", addpouVar) def changepouVar(self, old_type, old_name, new_type, new_name): if self.interface is not None: content = self.interface.getcontent() for varlist in content: - variables = varlist["value"].getvariable() + variables = varlist.getvariable() for var in variables: if var.getname() == old_name: vartype_content = var.gettype().getcontent() - if vartype_content["name"] == "derived" and vartype_content["value"].getname() == old_type: + if vartype_content.getLocalTag() == "derived" and vartype_content.getname() == old_type: var.setname(new_name) - vartype_content["value"].setname(new_type) + vartype_content.setname(new_type) return setattr(cls, "changepouVar", changepouVar) - def removepouVar(self, type, name): + def removepouVar(self, var_type, name): if self.interface is not None: content = self.interface.getcontent() for varlist in content: - variables = varlist["value"].getvariable() - for var in variables: + for var in varlist.getvariable(): if var.getname() == name: vartype_content = var.gettype().getcontent() - if vartype_content["name"] == "derived" and vartype_content["value"].getname() == type: - variables.remove(var) + if vartype_content.getLocalTag() == "derived" and vartype_content.getname() == var_type: + varlist.remove(var) + if len(varlist.getvariable()) == 0: + self.interface.remove(varlist) break - if len(varlist["value"].getvariable()) == 0: - content.remove(varlist) - break setattr(cls, "removepouVar", removepouVar) def hasblock(self, name=None, block_type=None): if self.getbodyType() in ["FBD", "LD", "SFC"]: for instance in self.getinstances(): - if (isinstance(instance, PLCOpenClasses["fbdObjects_block"]) and + if (isinstance(instance, PLCOpenParser.GetElementClass("block", "fbdObjects")) and (name and instance.getinstanceName() == name or block_type and instance.gettypeName() == block_type)): return True @@ -1444,22 +1269,22 @@ return False setattr(cls, "hasblock", hasblock) - def addtransition(self, name, type): - if not self.transitions: + def addtransition(self, name, body_type): + if self.transitions is None: self.addtransitions() self.transitions.settransition([]) - transition = PLCOpenClasses["transitions_transition"]() + transition = PLCOpenParser.CreateElement("transition", "transitions") + self.transitions.appendtransition(transition) transition.setname(name) - transition.setbodyType(type) - if type == "ST": - transition.settext(":= ;") - elif type == "IL": - transition.settext("\tST\t%s"%name) - self.transitions.appendtransition(transition) + transition.setbodyType(body_type) + if body_type == "ST": + transition.setanyText(":= ;") + elif body_type == "IL": + transition.setanyText("\tST\t%s"%name) setattr(cls, "addtransition", addtransition) def gettransition(self, name): - if self.transitions: + if self.transitions is not None: for transition in self.transitions.gettransition(): if transition.getname() == name: return transition @@ -1467,42 +1292,40 @@ setattr(cls, "gettransition", gettransition) def gettransitionList(self): - if self.transitions: + if self.transitions is not None: return self.transitions.gettransition() return [] setattr(cls, "gettransitionList", gettransitionList) def removetransition(self, name): - if self.transitions: - transitions = self.transitions.gettransition() - i = 0 + if self.transitions is not None: removed = False - while i < len(transitions) and not removed: - if transitions[i].getname() == name: - if transitions[i].getbodyType() in ["FBD", "LD", "SFC"]: - for instance in transitions[i].getinstances(): - if isinstance(instance, PLCOpenClasses["fbdObjects_block"]): + for transition in self.transitions.gettransition(): + if transition.getname() == name: + if transition.getbodyType() in ["FBD", "LD", "SFC"]: + for instance in transition.getinstances(): + if isinstance(instance, PLCOpenParser.GetElementClass("block", "fbdObjects")): self.removepouVar(instance.gettypeName(), instance.getinstanceName()) - transitions.pop(i) + self.transitions.remove(transition) removed = True - i += 1 + break if not removed: raise ValueError, _("Transition with name %s doesn't exist!")%name setattr(cls, "removetransition", removetransition) - def addaction(self, name, type): - if not self.actions: + def addaction(self, name, body_type): + if self.actions is None: self.addactions() self.actions.setaction([]) - action = PLCOpenClasses["actions_action"]() + action = PLCOpenParser.CreateElement("action", "actions") + self.actions.appendaction(action) action.setname(name) - action.setbodyType(type) - self.actions.appendaction(action) + action.setbodyType(body_type) setattr(cls, "addaction", addaction) def getaction(self, name): - if self.actions: + if self.actions is not None: for action in self.actions.getaction(): if action.getname() == name: return action @@ -1516,28 +1339,26 @@ setattr(cls, "getactionList", getactionList) def removeaction(self, name): - if self.actions: - actions = self.actions.getaction() - i = 0 + if self.actions is not None: removed = False - while i < len(actions) and not removed: - if actions[i].getname() == name: - if actions[i].getbodyType() in ["FBD", "LD", "SFC"]: - for instance in actions[i].getinstances(): - if isinstance(instance, PLCOpenClasses["fbdObjects_block"]): + for action in self.actions.getaction(): + if action.getname() == name: + if action.getbodyType() in ["FBD", "LD", "SFC"]: + for instance in action.getinstances(): + if isinstance(instance, PLCOpenParser.GetElementClass("block", "fbdObjects")): self.removepouVar(instance.gettypeName(), instance.getinstanceName()) - actions.pop(i) + self.actions.remove(action) removed = True - i += 1 + break if not removed: raise ValueError, _("Action with name %s doesn't exist!")%name setattr(cls, "removeaction", removeaction) def updateElementName(self, old_name, new_name): - if self.interface: + if self.interface is not None: for content in self.interface.getcontent(): - for var in content["value"].getvariable(): + for var in content.getvariable(): var_address = var.getaddress() if var_address is not None: if var_address == old_name: @@ -1545,9 +1366,9 @@ if var.getname() == old_name: var.setname(new_name) var_type_content = var.gettype().getcontent() - if var_type_content["name"] == "derived": - if var_type_content["value"].getname() == old_name: - var_type_content["value"].setname(new_name) + if var_type_content.getLocalTag() == "derived": + if var_type_content.getname() == old_name: + var_type_content.setname(new_name) self.body[0].updateElementName(old_name, new_name) for action in self.getactionList(): action.updateElementName(old_name, new_name) @@ -1556,9 +1377,9 @@ setattr(cls, "updateElementName", updateElementName) def updateElementAddress(self, address_model, new_leading): - if self.interface: + if self.interface is not None: for content in self.interface.getcontent(): - for var in content["value"].getvariable(): + for var in content.getvariable(): var_address = var.getaddress() if var_address is not None: var.setaddress(update_address(var_address, address_model, new_leading)) @@ -1570,24 +1391,22 @@ setattr(cls, "updateElementAddress", updateElementAddress) def removeVariableByAddress(self, address): - if self.interface: + if self.interface is not None: for content in self.interface.getcontent(): - variables = content["value"].getvariable() - for i in xrange(len(variables)-1, -1, -1): - if variables[i].getaddress() == address: - variables.pop(i) + for variable in content.getvariable(): + if variable.getaddress() == address: + content.remove(variable) setattr(cls, "removeVariableByAddress", removeVariableByAddress) def removeVariableByFilter(self, address_model): - if self.interface: + if self.interface is not None: for content in self.interface.getcontent(): - variables = content["value"].getvariable() - for i in xrange(len(variables)-1, -1, -1): - var_address = variables[i].getaddress() + for variable in content.getvariable(): + var_address = variable.getaddress() if var_address is not None: result = address_model.match(var_address) if result is not None: - variables.pop(i) + content.remove(variable) setattr(cls, "removeVariableByFilter", removeVariableByFilter) def Search(self, criteria, parent_infos=[]): @@ -1599,11 +1418,11 @@ if self.interface is not None: var_number = 0 for content in self.interface.getcontent(): - variable_type = searchResultVarTypes.get(content["value"], "var_local") - variables = content["value"].getvariable() - for modifier, has_modifier in [("constant", content["value"].getconstant()), - ("retain", content["value"].getretain()), - ("non_retain", content["value"].getnonretain())]: + variable_type = searchResultVarTypes.get(content, "var_local") + variables = content.getvariable() + for modifier, has_modifier in [("constant", content.getconstant()), + ("retain", content.getretain()), + ("non_retain", content.getnonretain())]: if has_modifier: for result in TestTextElement(modifier, criteria): search_result.append((tuple(parent_infos + [variable_type, (var_number, var_number + len(variables)), modifier]),) + result) @@ -1620,22 +1439,14 @@ return search_result setattr(cls, "Search", Search) -def setbodyType(self, type): - if type == "IL": - self.body.setcontent({"name" : "IL", "value" : PLCOpenClasses["formattedText"]()}) - elif type == "ST": - self.body.setcontent({"name" : "ST", "value" : PLCOpenClasses["formattedText"]()}) - elif type == "LD": - self.body.setcontent({"name" : "LD", "value" : PLCOpenClasses["body_LD"]()}) - elif type == "FBD": - self.body.setcontent({"name" : "FBD", "value" : PLCOpenClasses["body_FBD"]()}) - elif type == "SFC": - self.body.setcontent({"name" : "SFC", "value" : PLCOpenClasses["body_SFC"]()}) +def setbodyType(self, body_type): + if body_type in ["IL", "ST", "LD", "FBD", "SFC"]: + self.body.setcontent(PLCOpenParser.CreateElement(body_type, "body")) else: raise ValueError, "%s isn't a valid body type!"%type def getbodyType(self): - return self.body.getcontent()["name"] + return self.body.getcontent().getLocalTag() def resetexecutionOrder(self): self.body.resetexecutionOrder() @@ -1646,8 +1457,8 @@ def setelementExecutionOrder(self, instance, new_executionOrder): self.body.setelementExecutionOrder(instance, new_executionOrder) -def addinstance(self, name, instance): - self.body.appendcontentInstance(name, instance) +def addinstance(self, instance): + self.body.appendcontentInstance(instance) def getinstances(self): return self.body.getcontentInstances() @@ -1673,7 +1484,7 @@ def hasblock(self, name=None, block_type=None): if self.getbodyType() in ["FBD", "LD", "SFC"]: for instance in self.getinstances(): - if (isinstance(instance, PLCOpenClasses["fbdObjects_block"]) and + if (isinstance(instance, PLCOpenParser.GetElementClass("block", "fbdObjects")) and (name and instance.getinstanceName() == name or block_type and instance.gettypeName() == block_type)): return True @@ -1688,7 +1499,7 @@ self.body.updateElementAddress(address_model, new_leading) -cls = PLCOpenClasses.get("transitions_transition", None) +cls = PLCOpenParser.GetElementClass("transition", "transitions") if cls: setattr(cls, "setbodyType", setbodyType) setattr(cls, "getbodyType", getbodyType) @@ -1716,7 +1527,7 @@ return search_result setattr(cls, "Search", Search) -cls = PLCOpenClasses.get("actions_action", None) +cls = PLCOpenParser.GetElementClass("action", "actions") if cls: setattr(cls, "setbodyType", setbodyType) setattr(cls, "getbodyType", getbodyType) @@ -1744,27 +1555,9 @@ return search_result setattr(cls, "Search", Search) -cls = PLCOpenClasses.get("body", None) +cls = PLCOpenParser.GetElementClass("body") if cls: cls.currentExecutionOrderId = 0 - cls.instances_dict = {} - - setattr(cls, "_init_", getattr(cls, "__init__")) - - def __init__(self, *args, **kwargs): - self._init_(*args, **kwargs) - self.instances_dict = {} - setattr(cls, "__init__", __init__) - - setattr(cls, "_loadXMLTree", getattr(cls, "loadXMLTree")) - - def loadXMLTree(self, *args, **kwargs): - self._loadXMLTree(*args, **kwargs) - if self.content["name"] in ["LD","FBD","SFC"]: - self.instances_dict = dict( - [(element["value"].getlocalId(), element) - for element in self.content["value"].getcontent()]) - setattr(cls, "loadXMLTree", loadXMLTree) def resetcurrentExecutionOrderId(self): object.__setattr__(self, "currentExecutionOrderId", 0) @@ -1776,44 +1569,44 @@ setattr(cls, "getnewExecutionOrderId", getnewExecutionOrderId) def resetexecutionOrder(self): - if self.content["name"] == "FBD": - for element in self.content["value"].getcontent(): - if not isinstance(element["value"], (PLCOpenClasses.get("commonObjects_comment", None), - PLCOpenClasses.get("commonObjects_connector", None), - PLCOpenClasses.get("commonObjects_continuation", None))): - element["value"].setexecutionOrderId(0) + if self.content.getLocalTag() == "FBD": + for element in self.content.getcontent(): + if not isinstance(element, (PLCOpenParser.GetElementClass("comment", "commonObjects"), + PLCOpenParser.GetElementClass("connector", "commonObjects"), + PLCOpenParser.GetElementClass("continuation", "commonObjects"))): + element.setexecutionOrderId(0) else: raise TypeError, _("Can only generate execution order on FBD networks!") setattr(cls, "resetexecutionOrder", resetexecutionOrder) def compileexecutionOrder(self): - if self.content["name"] == "FBD": + if self.content.getLocalTag() == "FBD": self.resetexecutionOrder() self.resetcurrentExecutionOrderId() - for element in self.content["value"].getcontent(): - if isinstance(element["value"], PLCOpenClasses.get("fbdObjects_outVariable", None)) and element["value"].getexecutionOrderId() == 0: - connections = element["value"].connectionPointIn.getconnections() + for element in self.content.getcontent(): + if isinstance(element, PLCOpenParser.GetElementClass("outVariable", "fbdObjects")) and element.getexecutionOrderId() == 0: + connections = element.connectionPointIn.getconnections() if connections and len(connections) == 1: self.compileelementExecutionOrder(connections[0]) - element["value"].setexecutionOrderId(self.getnewExecutionOrderId()) + element.setexecutionOrderId(self.getnewExecutionOrderId()) else: raise TypeError, _("Can only generate execution order on FBD networks!") setattr(cls, "compileexecutionOrder", compileexecutionOrder) def compileelementExecutionOrder(self, link): - if self.content["name"] == "FBD": + if self.content.getLocalTag() == "FBD": localid = link.getrefLocalId() instance = self.getcontentInstance(localid) - if isinstance(instance, PLCOpenClasses.get("fbdObjects_block", None)) and instance.getexecutionOrderId() == 0: + if isinstance(instance, PLCOpenParser.GetElementClass("block", "fbdObjects")) and instance.getexecutionOrderId() == 0: for variable in instance.inputVariables.getvariable(): connections = variable.connectionPointIn.getconnections() if connections and len(connections) == 1: self.compileelementExecutionOrder(connections[0]) instance.setexecutionOrderId(self.getnewExecutionOrderId()) - elif isinstance(instance, PLCOpenClasses.get("commonObjects_continuation", None)) and instance.getexecutionOrderId() == 0: + elif isinstance(instance, PLCOpenParser.GetElementClass("continuation", "commonObjects")) and instance.getexecutionOrderId() == 0: name = instance.getname() for tmp_instance in self.getcontentInstances(): - if isinstance(tmp_instance, PLCOpenClasses.get("commonObjects_connector", None)) and tmp_instance.getname() == name and tmp_instance.getexecutionOrderId() == 0: + if isinstance(tmp_instance, PLCOpenParser.GetElementClass("connector", "commonObjects")) and tmp_instance.getname() == name and tmp_instance.getexecutionOrderId() == 0: connections = tmp_instance.connectionPointIn.getconnections() if connections and len(connections) == 1: self.compileelementExecutionOrder(connections[0]) @@ -1822,124 +1615,120 @@ setattr(cls, "compileelementExecutionOrder", compileelementExecutionOrder) def setelementExecutionOrder(self, instance, new_executionOrder): - if self.content["name"] == "FBD": + if self.content.getLocalTag() == "FBD": old_executionOrder = instance.getexecutionOrderId() if old_executionOrder is not None and old_executionOrder != 0 and new_executionOrder != 0: - for element in self.content["value"].getcontent(): - if element["value"] != instance and not isinstance(element["value"], PLCOpenClasses.get("commonObjects_comment", None)): - element_executionOrder = element["value"].getexecutionOrderId() + for element in self.content.getcontent(): + if element != instance and not isinstance(element, PLCOpenParser.GetElementClass("comment", "commonObjects")): + element_executionOrder = element.getexecutionOrderId() if old_executionOrder <= element_executionOrder <= new_executionOrder: - element["value"].setexecutionOrderId(element_executionOrder - 1) + element.setexecutionOrderId(element_executionOrder - 1) if new_executionOrder <= element_executionOrder <= old_executionOrder: - element["value"].setexecutionOrderId(element_executionOrder + 1) + element.setexecutionOrderId(element_executionOrder + 1) instance.setexecutionOrderId(new_executionOrder) else: raise TypeError, _("Can only generate execution order on FBD networks!") setattr(cls, "setelementExecutionOrder", setelementExecutionOrder) - def appendcontentInstance(self, name, instance): - if self.content["name"] in ["LD","FBD","SFC"]: - element = {"name" : name, "value" : instance} - self.content["value"].appendcontent(element) - self.instances_dict[instance.getlocalId()] = element + def appendcontentInstance(self, instance): + if self.content.getLocalTag() in ["LD","FBD","SFC"]: + self.content.appendcontent(instance) else: - raise TypeError, _("%s body don't have instances!")%self.content["name"] + raise TypeError, _("%s body don't have instances!")%self.content.getLocalTag() setattr(cls, "appendcontentInstance", appendcontentInstance) def getcontentInstances(self): - if self.content["name"] in ["LD","FBD","SFC"]: - instances = [] - for element in self.content["value"].getcontent(): - instances.append(element["value"]) - return instances + if self.content.getLocalTag() in ["LD","FBD","SFC"]: + return self.content.getcontent() else: - raise TypeError, _("%s body don't have instances!")%self.content["name"] + raise TypeError, _("%s body don't have instances!")%self.content.getLocalTag() setattr(cls, "getcontentInstances", getcontentInstances) - - def getcontentInstance(self, id): - if self.content["name"] in ["LD","FBD","SFC"]: - instance = self.instances_dict.get(id, None) - if instance is not None: - return instance["value"] + + instance_by_id_xpath = PLCOpen_XPath("*[@localId=$localId]") + instance_by_name_xpath = PLCOpen_XPath("ppx:block[@instanceName=$name]") + def getcontentInstance(self, local_id): + if self.content.getLocalTag() in ["LD","FBD","SFC"]: + instance = instance_by_id_xpath(self.content, localId=local_id) + if len(instance) > 0: + return instance[0] return None else: - raise TypeError, _("%s body don't have instances!")%self.content["name"] + raise TypeError, _("%s body don't have instances!")%self.content.getLocalTag() setattr(cls, "getcontentInstance", getcontentInstance) - def getcontentRandomInstance(self, exclude): - if self.content["name"] in ["LD","FBD","SFC"]: - ids = self.instances_dict.viewkeys() - exclude - if len(ids) > 0: - return self.instances_dict[ids.pop()]["value"] + def getcontentInstancesIds(self): + if self.content.getLocalTag() in ["LD","FBD","SFC"]: + return OrderedDict([(instance.getlocalId(), True) + for instance in self.content]) + else: + raise TypeError, _("%s body don't have instances!")%self.content.getLocalTag() + setattr(cls, "getcontentInstancesIds", getcontentInstancesIds) + + def getcontentInstanceByName(self, name): + if self.content.getLocalTag() in ["LD","FBD","SFC"]: + instance = instance_by_name_xpath(self.content) + if len(instance) > 0: + return instance[0] return None else: - raise TypeError, _("%s body don't have instances!")%self.content["name"] - setattr(cls, "getcontentRandomInstance", getcontentRandomInstance) - - def getcontentInstanceByName(self, name): - if self.content["name"] in ["LD","FBD","SFC"]: - for element in self.content["value"].getcontent(): - if isinstance(element["value"], PLCOpenClasses.get("fbdObjects_block", None)) and element["value"].getinstanceName() == name: - return element["value"] - else: - raise TypeError, _("%s body don't have instances!")%self.content["name"] + raise TypeError, _("%s body don't have instances!")%self.content.getLocalTag() setattr(cls, "getcontentInstanceByName", getcontentInstanceByName) - def removecontentInstance(self, id): - if self.content["name"] in ["LD","FBD","SFC"]: - element = self.instances_dict.pop(id, None) - if element is not None: - self.content["value"].getcontent().remove(element) + def removecontentInstance(self, local_id): + if self.content.getLocalTag() in ["LD","FBD","SFC"]: + instance = instance_by_id_xpath(self.content, localId=local_id) + if len(instance) > 0: + self.content.remove(instance[0]) else: raise ValueError, _("Instance with id %d doesn't exist!")%id else: - raise TypeError, "%s body don't have instances!"%self.content["name"] + raise TypeError, "%s body don't have instances!"%self.content.getLocalTag() setattr(cls, "removecontentInstance", removecontentInstance) def settext(self, text): - if self.content["name"] in ["IL","ST"]: - self.content["value"].settext(text) + if self.content.getLocalTag() in ["IL","ST"]: + self.content.setanyText(text) else: - raise TypeError, _("%s body don't have text!")%self.content["name"] + raise TypeError, _("%s body don't have text!")%self.content.getLocalTag() setattr(cls, "settext", settext) def gettext(self): - if self.content["name"] in ["IL","ST"]: - return self.content["value"].gettext() + if self.content.getLocalTag() in ["IL","ST"]: + return self.content.getanyText() else: - raise TypeError, _("%s body don't have text!")%self.content["name"] + raise TypeError, _("%s body don't have text!")%self.content.getLocalTag() setattr(cls, "gettext", gettext) def hasblock(self, block_type): - if self.content["name"] in ["IL","ST"]: - return self.content["value"].hasblock(block_type) + if self.content.getLocalTag() in ["IL","ST"]: + return self.content.hasblock(block_type) else: - raise TypeError, _("%s body don't have text!")%self.content["name"] + raise TypeError, _("%s body don't have text!")%self.content.getLocalTag() setattr(cls, "hasblock", hasblock) def updateElementName(self, old_name, new_name): - if self.content["name"] in ["IL", "ST"]: - self.content["value"].updateElementName(old_name, new_name) + if self.content.getLocalTag() in ["IL", "ST"]: + self.content.updateElementName(old_name, new_name) else: - for element in self.content["value"].getcontent(): - element["value"].updateElementName(old_name, new_name) + for element in self.content.getcontent(): + element.updateElementName(old_name, new_name) setattr(cls, "updateElementName", updateElementName) def updateElementAddress(self, address_model, new_leading): - if self.content["name"] in ["IL", "ST"]: - self.content["value"].updateElementAddress(address_model, new_leading) + if self.content.getLocalTag() in ["IL", "ST"]: + self.content.updateElementAddress(address_model, new_leading) else: - for element in self.content["value"].getcontent(): - element["value"].updateElementAddress(address_model, new_leading) + for element in self.content.getcontent(): + element.updateElementAddress(address_model, new_leading) setattr(cls, "updateElementAddress", updateElementAddress) def Search(self, criteria, parent_infos=[]): - if self.content["name"] in ["IL", "ST"]: - search_result = self.content["value"].Search(criteria, parent_infos + ["body", 0]) + if self.content.getLocalTag() in ["IL", "ST"]: + search_result = self.content.Search(criteria, parent_infos + ["body", 0]) else: search_result = [] - for element in self.content["value"].getcontent(): - search_result.extend(element["value"].Search(criteria, parent_infos)) + for element in self.content.getcontent(): + search_result.extend(element.Search(criteria, parent_infos)) return search_result setattr(cls, "Search", Search) @@ -1982,15 +1771,11 @@ def _filterConnections(connectionPointIn, localId, connections): in_connections = connectionPointIn.getconnections() if in_connections is not None: - to_delete = [] - for i, connection in enumerate(in_connections): + for connection in in_connections: connected = connection.getrefLocalId() if not connections.has_key((localId, connected)) and \ not connections.has_key((connected, localId)): - to_delete.append(i) - to_delete.reverse() - for i in to_delete: - connectionPointIn.removeconnection(i) + connectionPointIn.remove(connection) def _filterConnectionsSingle(self, connections): if self.connectionPointIn is not None: @@ -2001,8 +1786,8 @@ _filterConnections(connectionPointIn, self.localId, connections) def _getconnectionsdefinition(instance, connections_end): - id = instance.getlocalId() - return dict([((id, end), True) for end in connections_end]) + local_id = instance.getlocalId() + return dict([((local_id, end), True) for end in connections_end]) def _updateConnectionsId(connectionPointIn, translation): connections_end = [] @@ -2073,9 +1858,8 @@ "multiple": _updateConnectionsIdMultiple}, } -def _initElementClass(name, classname, connectionPointInType="none"): - ElementNameToClass[name] = classname - cls = PLCOpenClasses.get(classname, None) +def _initElementClass(name, parent, connectionPointInType="none"): + cls = PLCOpenParser.GetElementClass(name, parent) if cls: setattr(cls, "getx", getx) setattr(cls, "gety", gety) @@ -2090,151 +1874,14 @@ setattr(cls, "Search", _SearchInElement) return cls -def _getexecutionOrder(instance, specific_values): - executionOrder = instance.getexecutionOrderId() - if executionOrder is None: - executionOrder = 0 - specific_values["executionOrder"] = executionOrder - -def _getdefaultmodifiers(instance, infos): - infos["negated"] = instance.getnegated() - infos["edge"] = instance.getedge() - -def _getinputmodifiers(instance, infos): - infos["negated"] = instance.getnegatedIn() - infos["edge"] = instance.getedgeIn() - -def _getoutputmodifiers(instance, infos): - infos["negated"] = instance.getnegatedOut() - infos["edge"] = instance.getedgeOut() - -MODIFIERS_FUNCTIONS = {"default": _getdefaultmodifiers, - "input": _getinputmodifiers, - "output": _getoutputmodifiers} - -def _getconnectioninfos(instance, connection, links=False, modifiers=None, parameter=False): - infos = {"position": connection.getrelPositionXY()} - if parameter: - infos["name"] = instance.getformalParameter() - MODIFIERS_FUNCTIONS.get(modifiers, lambda x, y: None)(instance, infos) - if links: - infos["links"] = [] - connections = connection.getconnections() - if connections is not None: - for link in connections: - dic = {"refLocalId": link.getrefLocalId(), - "points": link.getpoints(), - "formalParameter": link.getformalParameter()} - infos["links"].append(dic) - return infos - -def _getelementinfos(instance): - return {"id": instance.getlocalId(), - "x": instance.getx(), - "y": instance.gety(), - "height": instance.getheight(), - "width": instance.getwidth(), - "specific_values": {}, - "inputs": [], - "outputs": []} - -def _getvariableinfosFunction(type, input, output): - def getvariableinfos(self): - infos = _getelementinfos(self) - infos["type"] = type - specific_values = infos["specific_values"] - specific_values["name"] = self.getexpression() - _getexecutionOrder(self, specific_values) - if input and output: - infos["inputs"].append(_getconnectioninfos(self, self.connectionPointIn, True, "input")) - infos["outputs"].append(_getconnectioninfos(self, self.connectionPointOut, False, "output")) - elif input: - infos["inputs"].append(_getconnectioninfos(self, self.connectionPointIn, True, "default")) - elif output: - infos["outputs"].append(_getconnectioninfos(self, self.connectionPointOut, False, "default")) - return infos - return getvariableinfos - -def _getconnectorinfosFunction(type): - def getvariableinfos(self): - infos = _getelementinfos(self) - infos["type"] = type - infos["specific_values"]["name"] = self.getname() - if type == "connector": - infos["inputs"].append(_getconnectioninfos(self, self.connectionPointIn, True)) - elif type == "continuation": - infos["outputs"].append(_getconnectioninfos(self, self.connectionPointOut)) - return infos - return getvariableinfos - -def _getpowerrailinfosFunction(type): - def getpowerrailinfos(self): - infos = _getelementinfos(self) - infos["type"] = type - if type == "rightPowerRail": - for connectionPointIn in self.getconnectionPointIn(): - infos["inputs"].append(_getconnectioninfos(self, connectionPointIn, True)) - infos["specific_values"]["connectors"] = len(infos["inputs"]) - elif type == "leftPowerRail": - for connectionPointOut in self.getconnectionPointOut(): - infos["outputs"].append(_getconnectioninfos(self, connectionPointOut)) - infos["specific_values"]["connectors"] = len(infos["outputs"]) - return infos - return getpowerrailinfos - -def _getldelementinfosFunction(type): - def getldelementinfos(self): - infos = _getelementinfos(self) - infos["type"] = type - specific_values = infos["specific_values"] - specific_values["name"] = self.getvariable() - _getexecutionOrder(self, specific_values) - specific_values["negated"] = self.getnegated() - specific_values["edge"] = self.getedge() - if type == "coil": - specific_values["storage"] = self.getstorage() - infos["inputs"].append(_getconnectioninfos(self, self.connectionPointIn, True)) - infos["outputs"].append(_getconnectioninfos(self, self.connectionPointOut)) - return infos - return getldelementinfos - -DIVERGENCE_TYPES = {(True, True): "simultaneousDivergence", - (True, False): "selectionDivergence", - (False, True): "simultaneousConvergence", - (False, False): "selectionConvergence"} - -def _getdivergenceinfosFunction(divergence, simultaneous): - def getdivergenceinfos(self): - infos = _getelementinfos(self) - infos["type"] = DIVERGENCE_TYPES[(divergence, simultaneous)] - if divergence: - infos["inputs"].append(_getconnectioninfos(self, self.connectionPointIn, True)) - for connectionPointOut in self.getconnectionPointOut(): - infos["outputs"].append(_getconnectioninfos(self, connectionPointOut)) - infos["specific_values"]["connectors"] = len(infos["outputs"]) - else: - for connectionPointIn in self.getconnectionPointIn(): - infos["inputs"].append(_getconnectioninfos(self, connectionPointIn, True)) - infos["outputs"].append(_getconnectioninfos(self, self.connectionPointOut)) - infos["specific_values"]["connectors"] = len(infos["inputs"]) - return infos - return getdivergenceinfos - -cls = _initElementClass("comment", "commonObjects_comment") -if cls: - def getinfos(self): - infos = _getelementinfos(self) - infos["type"] = "comment" - infos["specific_values"]["content"] = self.getcontentText() - return infos - setattr(cls, "getinfos", getinfos) - +cls = _initElementClass("comment", "commonObjects") +if cls: def setcontentText(self, text): - self.content.settext(text) + self.content.setanyText(text) setattr(cls, "setcontentText", setcontentText) def getcontentText(self): - return self.content.gettext() + return self.content.getanyText() setattr(cls, "getcontentText", getcontentText) def updateElementName(self, old_name, new_name): @@ -2249,7 +1896,7 @@ return self.content.Search(criteria, parent_infos + ["comment", self.getlocalId(), "content"]) setattr(cls, "Search", Search) -cls = _initElementClass("block", "fbdObjects_block") +cls = _initElementClass("block", "fbdObjects") if cls: def getBoundingBox(self): bbox = _getBoundingBox(self) @@ -2258,19 +1905,6 @@ return bbox setattr(cls, "getBoundingBox", getBoundingBox) - def getinfos(self): - infos = _getelementinfos(self) - infos["type"] = self.gettypeName() - specific_values = infos["specific_values"] - specific_values["name"] = self.getinstanceName() - _getexecutionOrder(self, specific_values) - for variable in self.inputVariables.getvariable(): - infos["inputs"].append(_getconnectioninfos(variable, variable.connectionPointIn, True, "default", True)) - for variable in self.outputVariables.getvariable(): - infos["outputs"].append(_getconnectioninfos(variable, variable.connectionPointOut, False, "default", True)) - return infos - setattr(cls, "getinfos", getinfos) - def updateElementName(self, old_name, new_name): if self.typeName == old_name: self.typeName = new_name @@ -2308,150 +1942,83 @@ return search_result setattr(cls, "Search", Search) -cls = _initElementClass("leftPowerRail", "ldObjects_leftPowerRail") -if cls: - setattr(cls, "getinfos", _getpowerrailinfosFunction("leftPowerRail")) - -cls = _initElementClass("rightPowerRail", "ldObjects_rightPowerRail", "multiple") -if cls: - setattr(cls, "getinfos", _getpowerrailinfosFunction("rightPowerRail")) - -cls = _initElementClass("contact", "ldObjects_contact", "single") -if cls: - setattr(cls, "getinfos", _getldelementinfosFunction("contact")) - - def updateElementName(self, old_name, new_name): - if self.variable == old_name: - self.variable = new_name - setattr(cls, "updateElementName", updateElementName) - - def updateElementAddress(self, address_model, new_leading): - self.variable = update_address(self.variable, address_model, new_leading) - setattr(cls, "updateElementAddress", updateElementAddress) - - def Search(self, criteria, parent_infos=[]): - return _Search([("reference", self.getvariable())], criteria, parent_infos + ["contact", self.getlocalId()]) - setattr(cls, "Search", Search) - -cls = _initElementClass("coil", "ldObjects_coil", "single") -if cls: - setattr(cls, "getinfos", _getldelementinfosFunction("coil")) - - def updateElementName(self, old_name, new_name): - if self.variable == old_name: - self.variable = new_name - setattr(cls, "updateElementName", updateElementName) - - def updateElementAddress(self, address_model, new_leading): - self.variable = update_address(self.variable, address_model, new_leading) - setattr(cls, "updateElementAddress", updateElementAddress) - - def Search(self, criteria, parent_infos=[]): - return _Search([("reference", self.getvariable())], criteria, parent_infos + ["coil", self.getlocalId()]) - setattr(cls, "Search", Search) - -cls = _initElementClass("step", "sfcObjects_step", "single") -if cls: - def getinfos(self): - infos = _getelementinfos(self) - infos["type"] = "step" - specific_values = infos["specific_values"] - specific_values["name"] = self.getname() - specific_values["initial"] = self.getinitialStep() - if self.connectionPointIn: - infos["inputs"].append(_getconnectioninfos(self, self.connectionPointIn, True)) - if self.connectionPointOut: - infos["outputs"].append(_getconnectioninfos(self, self.connectionPointOut)) - if self.connectionPointOutAction: - specific_values["action"] = _getconnectioninfos(self, self.connectionPointOutAction) - return infos - setattr(cls, "getinfos", getinfos) - +_initElementClass("leftPowerRail", "ldObjects") +_initElementClass("rightPowerRail", "ldObjects", "multiple") + +def _UpdateLDElementName(self, old_name, new_name): + if self.variable == old_name: + self.variable = new_name + +def _UpdateLDElementAddress(self, address_model, new_leading): + self.variable = update_address(self.variable, address_model, new_leading) + +def _getSearchInLDElement(ld_element_type): + def SearchInLDElement(self, criteria, parent_infos=[]): + return _Search([("reference", self.variable)], criteria, parent_infos + [ld_element_type, self.getlocalId()]) + return SearchInLDElement + +cls = _initElementClass("contact", "ldObjects", "single") +if cls: + setattr(cls, "updateElementName", _UpdateLDElementName) + setattr(cls, "updateElementAddress", _UpdateLDElementAddress) + setattr(cls, "Search", _getSearchInLDElement("contact")) + +cls = _initElementClass("coil", "ldObjects", "single") +if cls: + setattr(cls, "updateElementName", _UpdateLDElementName) + setattr(cls, "updateElementAddress", _UpdateLDElementAddress) + setattr(cls, "Search", _getSearchInLDElement("coil")) + +cls = _initElementClass("step", "sfcObjects", "single") +if cls: def Search(self, criteria, parent_infos=[]): return _Search([("name", self.getname())], criteria, parent_infos + ["step", self.getlocalId()]) setattr(cls, "Search", Search) -cls = PLCOpenClasses.get("transition_condition", None) -if cls: - def compatibility(self, tree): - connections = [] - for child in tree.childNodes: - if child.nodeName == "connection": - connections.append(child) - if len(connections) > 0: - node = CreateNode("connectionPointIn") - relPosition = CreateNode("relPosition") - NodeSetAttr(relPosition, "x", "0") - NodeSetAttr(relPosition, "y", "0") - node.childNodes.append(relPosition) - node.childNodes.extend(connections) - tree.childNodes = [node] - setattr(cls, "compatibility", compatibility) - -cls = _initElementClass("transition", "sfcObjects_transition") -if cls: - def getinfos(self): - infos = _getelementinfos(self) - infos["type"] = "transition" - specific_values = infos["specific_values"] - priority = self.getpriority() - if priority is None: - priority = 0 - specific_values["priority"] = priority - condition = self.getconditionContent() - specific_values["condition_type"] = condition["type"] - if specific_values["condition_type"] == "connection": - specific_values["connection"] = _getconnectioninfos(self, condition["value"], True) +cls = _initElementClass("transition", "sfcObjects") +if cls: + def setconditionContent(self, condition_type, value): + if self.condition is None: + self.addcondition() + if condition_type == "connection": + condition = PLCOpenParser.CreateElement("connectionPointIn", "condition") else: - specific_values["condition"] = condition["value"] - infos["inputs"].append(_getconnectioninfos(self, self.connectionPointIn, True)) - infos["outputs"].append(_getconnectioninfos(self, self.connectionPointOut)) - return infos - setattr(cls, "getinfos", getinfos) - - def setconditionContent(self, type, value): - if not self.condition: - self.addcondition() - if type == "reference": - condition = PLCOpenClasses["condition_reference"]() + condition = PLCOpenParser.CreateElement(condition_type, "condition") + self.condition.setcontent(condition) + if condition_type == "reference": condition.setname(value) - elif type == "inline": - condition = PLCOpenClasses["condition_inline"]() - condition.setcontent({"name" : "ST", "value" : PLCOpenClasses["formattedText"]()}) + elif condition_type == "inline": + condition.setcontent(PLCOpenParser.CreateElement("ST", "inline")) condition.settext(value) - elif type == "connection": - type = "connectionPointIn" - condition = PLCOpenClasses["connectionPointIn"]() - self.condition.setcontent({"name" : type, "value" : condition}) setattr(cls, "setconditionContent", setconditionContent) def getconditionContent(self): - if self.condition: + if self.condition is not None: content = self.condition.getcontent() - values = {"type" : content["name"]} + values = {"type" : content.getLocalTag()} if values["type"] == "reference": - values["value"] = content["value"].getname() + values["value"] = content.getname() elif values["type"] == "inline": - values["value"] = content["value"].gettext() + values["value"] = content.gettext() elif values["type"] == "connectionPointIn": values["type"] = "connection" - values["value"] = content["value"] + values["value"] = content return values return "" setattr(cls, "getconditionContent", getconditionContent) def getconditionConnection(self): - if self.condition: + if self.condition is not None: content = self.condition.getcontent() - if content["name"] == "connectionPointIn": - return content["value"] + if content.getLocalTag() == "connectionPointIn": + return content return None setattr(cls, "getconditionConnection", getconditionConnection) def getBoundingBox(self): bbox = _getBoundingBoxSingle(self) condition_connection = self.getconditionConnection() - if condition_connection: + if condition_connection is not None: bbox.union(_getConnectionsBoundingBox(condition_connection)) return bbox setattr(cls, "getBoundingBox", getBoundingBox) @@ -2459,14 +2026,14 @@ def translate(self, dx, dy): _translateSingle(self, dx, dy) condition_connection = self.getconditionConnection() - if condition_connection: + if condition_connection is not None: _translateConnections(condition_connection, dx, dy) setattr(cls, "translate", translate) def filterConnections(self, connections): _filterConnectionsSingle(self, connections) condition_connection = self.getconditionConnection() - if condition_connection: + if condition_connection is not None: _filterConnections(condition_connection, self.localId, connections) setattr(cls, "filterConnections", filterConnections) @@ -2475,33 +2042,35 @@ if self.connectionPointIn is not None: connections_end = _updateConnectionsId(self.connectionPointIn, translation) condition_connection = self.getconditionConnection() - if condition_connection: + if condition_connection is not None: connections_end.extend(_updateConnectionsId(condition_connection, translation)) return _getconnectionsdefinition(self, connections_end) setattr(cls, "updateConnectionsId", updateConnectionsId) def updateElementName(self, old_name, new_name): - if self.condition: + if self.condition is not None: content = self.condition.getcontent() - if content["name"] == "reference": - if content["value"].getname() == old_name: - content["value"].setname(new_name) - elif content["name"] == "inline": - content["value"].updateElementName(old_name, new_name) + content_name = content.getLocalTag() + if content_name == "reference": + if content.getname() == old_name: + content.setname(new_name) + elif content_name == "inline": + content.updateElementName(old_name, new_name) setattr(cls, "updateElementName", updateElementName) def updateElementAddress(self, address_model, new_leading): - if self.condition: + if self.condition is not None: content = self.condition.getcontent() - if content["name"] == "reference": - content["value"].setname(update_address(content["value"].getname(), address_model, new_leading)) - elif content["name"] == "inline": - content["value"].updateElementAddress(address_model, new_leading) + content_name = content.getLocalTag() + if content_name == "reference": + content.setname(update_address(content.getname(), address_model, new_leading)) + elif content_name == "inline": + content.updateElementAddress(address_model, new_leading) setattr(cls, "updateElementAddress", updateElementAddress) def getconnections(self): condition_connection = self.getconditionConnection() - if condition_connection: + if condition_connection is not None: return condition_connection.getconnections() return None setattr(cls, "getconnections", getconnections) @@ -2510,90 +2079,61 @@ parent_infos = parent_infos + ["transition", self.getlocalId()] search_result = [] content = self.condition.getcontent() - if content["name"] == "reference": - search_result.extend(_Search([("reference", content["value"].getname())], criteria, parent_infos)) - elif content["name"] == "inline": - search_result.extend(content["value"].Search(criteria, parent_infos + ["inline"])) + content_name = content.getLocalTag() + if content_name == "reference": + search_result.extend(_Search([("reference", content.getname())], criteria, parent_infos)) + elif content_name == "inline": + search_result.extend(content.Search(criteria, parent_infos + ["inline"])) return search_result setattr(cls, "Search", Search) - -cls = _initElementClass("selectionDivergence", "sfcObjects_selectionDivergence", "single") -if cls: - setattr(cls, "getinfos", _getdivergenceinfosFunction(True, False)) - -cls = _initElementClass("selectionConvergence", "sfcObjects_selectionConvergence", "multiple") -if cls: - setattr(cls, "getinfos", _getdivergenceinfosFunction(False, False)) - -cls = _initElementClass("simultaneousDivergence", "sfcObjects_simultaneousDivergence", "single") -if cls: - setattr(cls, "getinfos", _getdivergenceinfosFunction(True, True)) - -cls = _initElementClass("simultaneousConvergence", "sfcObjects_simultaneousConvergence", "multiple") -if cls: - setattr(cls, "getinfos", _getdivergenceinfosFunction(False, True)) - -cls = _initElementClass("jumpStep", "sfcObjects_jumpStep", "single") -if cls: - def getinfos(self): - infos = _getelementinfos(self) - infos["type"] = "jump" - infos["specific_values"]["target"] = self.gettargetName() - infos["inputs"].append(_getconnectioninfos(self, self.connectionPointIn, True)) - return infos - setattr(cls, "getinfos", getinfos) - + +_initElementClass("selectionDivergence", "sfcObjects", "single") +_initElementClass("selectionConvergence", "sfcObjects", "multiple") +_initElementClass("simultaneousDivergence", "sfcObjects", "single") +_initElementClass("simultaneousConvergence", "sfcObjects", "multiple") + +cls = _initElementClass("jumpStep", "sfcObjects", "single") +if cls: def Search(self, criteria, parent_infos): return _Search([("target", self.gettargetName())], criteria, parent_infos + ["jump", self.getlocalId()]) setattr(cls, "Search", Search) -cls = PLCOpenClasses.get("actionBlock_action", None) -if cls: - def compatibility(self, tree): - relPosition = reduce(lambda x, y: x | (y.nodeName == "relPosition"), tree.childNodes, False) - if not tree.hasAttribute("localId"): - NodeSetAttr(tree, "localId", "0") - if not relPosition: - node = CreateNode("relPosition") - NodeSetAttr(node, "x", "0") - NodeSetAttr(node, "y", "0") - tree.childNodes.insert(0, node) - setattr(cls, "compatibility", compatibility) - +cls = PLCOpenParser.GetElementClass("action", "actionBlock") +if cls: def setreferenceName(self, name): - if self.reference: + if self.reference is not None: self.reference.setname(name) setattr(cls, "setreferenceName", setreferenceName) def getreferenceName(self): - if self.reference: + if self.reference is not None: return self.reference.getname() return None setattr(cls, "getreferenceName", getreferenceName) def setinlineContent(self, content): - if self.inline: - self.inline.setcontent({"name" : "ST", "value" : PLCOpenClasses["formattedText"]()}) + if self.inline is not None: + self.inline.setcontent(PLCOpenParser.CreateElement("ST", "inline")) self.inline.settext(content) setattr(cls, "setinlineContent", setinlineContent) def getinlineContent(self): - if self.inline: + if self.inline is not None: return self.inline.gettext() return None setattr(cls, "getinlineContent", getinlineContent) def updateElementName(self, old_name, new_name): - if self.reference and self.reference.getname() == old_name: + if self.reference is not None and self.reference.getname() == old_name: self.reference.setname(new_name) - if self.inline: + if self.inline is not None: self.inline.updateElementName(old_name, new_name) setattr(cls, "updateElementName", updateElementName) def updateElementAddress(self, address_model, new_leading): - if self.reference: + if self.reference is not None: self.reference.setname(update_address(self.reference.getname(), address_model, new_leading)) - if self.inline: + if self.inline is not None: self.inline.updateElementAddress(address_model, new_leading) setattr(cls, "updateElementAddress", updateElementAddress) @@ -2609,38 +2149,24 @@ criteria, parent_infos) setattr(cls, "Search", Search) -cls = _initElementClass("actionBlock", "commonObjects_actionBlock", "single") -if cls: - def compatibility(self, tree): - for child in tree.childNodes[:]: - if child.nodeName == "connectionPointOut": - tree.childNodes.remove(child) - setattr(cls, "compatibility", compatibility) - - def getinfos(self): - infos = _getelementinfos(self) - infos["type"] = "actionBlock" - infos["specific_values"]["actions"] = self.getactions() - infos["inputs"].append(_getconnectioninfos(self, self.connectionPointIn, True)) - return infos - setattr(cls, "getinfos", getinfos) - +cls = _initElementClass("actionBlock", "commonObjects", "single") +if cls: def setactions(self, actions): self.action = [] for params in actions: - action = PLCOpenClasses["actionBlock_action"]() - action.setqualifier(params["qualifier"]) - if params["type"] == "reference": + action = PLCOpenParser.CreateElement("action", "actionBlock") + self.appendaction(action) + action.setqualifier(params.qualifier) + if params.type == "reference": action.addreference() - action.setreferenceName(params["value"]) + action.setreferenceName(params.value) else: action.addinline() - action.setinlineContent(params["value"]) - if params.has_key("duration"): - action.setduration(params["duration"]) - if params.has_key("indicator"): - action.setindicator(params["indicator"]) - self.action.append(action) + action.setinlineContent(params.value) + if params.duration != "": + action.setduration(params.duration) + if params.indicator != "": + action.setindicator(params.indicator) setattr(cls, "setactions", setactions) def getactions(self): @@ -2650,17 +2176,17 @@ params["qualifier"] = action.getqualifier() if params["qualifier"] is None: params["qualifier"] = "N" - if action.getreference(): + if action.getreference() is not None: params["type"] = "reference" params["value"] = action.getreferenceName() - elif action.getinline(): + elif action.getinline() is not None: params["type"] = "inline" params["value"] = action.getinlineContent() duration = action.getduration() if duration: params["duration"] = duration indicator = action.getindicator() - if indicator: + if indicator is not None: params["indicator"] = indicator actions.append(params) return actions @@ -2685,60 +2211,39 @@ setattr(cls, "Search", Search) def _SearchInIOVariable(self, criteria, parent_infos=[]): - return _Search([("expression", self.getexpression())], criteria, parent_infos + ["io_variable", self.getlocalId()]) - -cls = _initElementClass("inVariable", "fbdObjects_inVariable") -if cls: - setattr(cls, "getinfos", _getvariableinfosFunction("input", False, True)) - - def updateElementName(self, old_name, new_name): - if self.expression == old_name: - self.expression = new_name - setattr(cls, "updateElementName", updateElementName) - - def updateElementAddress(self, address_model, new_leading): - self.expression = update_address(self.expression, address_model, new_leading) - setattr(cls, "updateElementAddress", updateElementAddress) - + return _Search([("expression", self.expression)], criteria, parent_infos + ["io_variable", self.getlocalId()]) + +def _UpdateIOElementName(self, old_name, new_name): + if self.expression == old_name: + self.expression = new_name + +def _UpdateIOElementAddress(self, old_name, new_name): + self.expression = update_address(self.expression, address_model, new_leading) + +cls = _initElementClass("inVariable", "fbdObjects") +if cls: + setattr(cls, "updateElementName", _UpdateIOElementName) + setattr(cls, "updateElementAddress", _UpdateIOElementAddress) setattr(cls, "Search", _SearchInIOVariable) -cls = _initElementClass("outVariable", "fbdObjects_outVariable", "single") -if cls: - setattr(cls, "getinfos", _getvariableinfosFunction("output", True, False)) - - def updateElementName(self, old_name, new_name): - if self.expression == old_name: - self.expression = new_name - setattr(cls, "updateElementName", updateElementName) - - def updateElementAddress(self, address_model, new_leading): - self.expression = update_address(self.expression, address_model, new_leading) - setattr(cls, "updateElementAddress", updateElementAddress) - +cls = _initElementClass("outVariable", "fbdObjects", "single") +if cls: + setattr(cls, "updateElementName", _UpdateIOElementName) + setattr(cls, "updateElementAddress", _UpdateIOElementAddress) setattr(cls, "Search", _SearchInIOVariable) -cls = _initElementClass("inOutVariable", "fbdObjects_inOutVariable", "single") -if cls: - setattr(cls, "getinfos", _getvariableinfosFunction("inout", True, True)) - - def updateElementName(self, old_name, new_name): - if self.expression == old_name: - self.expression = new_name - setattr(cls, "updateElementName", updateElementName) - - def updateElementAddress(self, address_model, new_leading): - self.expression = update_address(self.expression, address_model, new_leading) - setattr(cls, "updateElementAddress", updateElementAddress) - +cls = _initElementClass("inOutVariable", "fbdObjects", "single") +if cls: + setattr(cls, "updateElementName", _UpdateIOElementName) + setattr(cls, "updateElementAddress", _UpdateIOElementAddress) setattr(cls, "Search", _SearchInIOVariable) def _SearchInConnector(self, criteria, parent_infos=[]): return _Search([("name", self.getname())], criteria, parent_infos + ["connector", self.getlocalId()]) -cls = _initElementClass("continuation", "commonObjects_continuation") -if cls: - setattr(cls, "getinfos", _getconnectorinfosFunction("continuation")) +cls = _initElementClass("continuation", "commonObjects") +if cls: setattr(cls, "Search", _SearchInConnector) def updateElementName(self, old_name, new_name): @@ -2746,9 +2251,8 @@ self.name = new_name setattr(cls, "updateElementName", updateElementName) -cls = _initElementClass("connector", "commonObjects_connector", "single") -if cls: - setattr(cls, "getinfos", _getconnectorinfosFunction("connector")) +cls = _initElementClass("connector", "commonObjects", "single") +if cls: setattr(cls, "Search", _SearchInConnector) def updateElementName(self, old_name, new_name): @@ -2756,15 +2260,16 @@ self.name = new_name setattr(cls, "updateElementName", updateElementName) -cls = PLCOpenClasses.get("connection", None) +cls = PLCOpenParser.GetElementClass("connection") if cls: def setpoints(self, points): - self.position = [] + positions = [] for point in points: - position = PLCOpenClasses["position"]() + position = PLCOpenParser.CreateElement("position", "connection") position.setx(point.x) position.sety(point.y) - self.position.append(position) + positions.append(position) + self.position = positions setattr(cls, "setpoints", setpoints) def getpoints(self): @@ -2774,110 +2279,115 @@ return points setattr(cls, "getpoints", getpoints) -cls = PLCOpenClasses.get("connectionPointIn", None) +cls = PLCOpenParser.GetElementClass("connectionPointIn") if cls: def setrelPositionXY(self, x, y): - self.relPosition = PLCOpenClasses["position"]() + self.relPosition = PLCOpenParser.CreateElement("relPosition", "connectionPointIn") self.relPosition.setx(x) self.relPosition.sety(y) setattr(cls, "setrelPositionXY", setrelPositionXY) def getrelPositionXY(self): - if self.relPosition: + if self.relPosition is not None: return self.relPosition.getx(), self.relPosition.gety() - else: - return self.relPosition + return self.relPosition setattr(cls, "getrelPositionXY", getrelPositionXY) def addconnection(self): - if not self.content: - self.content = {"name" : "connection", "value" : [PLCOpenClasses["connection"]()]} - else: - self.content["value"].append(PLCOpenClasses["connection"]()) + self.append(PLCOpenParser.CreateElement("connection", "connectionPointIn")) setattr(cls, "addconnection", addconnection) def removeconnection(self, idx): - if self.content: - self.content["value"].pop(idx) - if len(self.content["value"]) == 0: - self.content = None + if len(self.content) > idx: + self.remove(self.content[idx]) setattr(cls, "removeconnection", removeconnection) def removeconnections(self): - if self.content: - self.content = None + self.content = None setattr(cls, "removeconnections", removeconnections) + connection_xpath = PLCOpen_XPath("ppx:connection") + connection_by_position_xpath = PLCOpen_XPath("ppx:connection[position()=$pos]") def getconnections(self): - if self.content: - return self.content["value"] + return connection_xpath(self) setattr(cls, "getconnections", getconnections) - def setconnectionId(self, idx, id): - if self.content: - self.content["value"][idx].setrefLocalId(id) + def getconnection(self, idx): + connection = connection_by_position_xpath(self, pos=idx+1) + if len(connection) > 0: + return connection[0] + return None + setattr(cls, "getconnection", getconnection) + + def setconnectionId(self, idx, local_id): + connection = self.getconnection(idx) + if connection is not None: + connection.setrefLocalId(local_id) setattr(cls, "setconnectionId", setconnectionId) def getconnectionId(self, idx): - if self.content: - return self.content["value"][idx].getrefLocalId() + connection = self.getconnection(idx) + if connection is not None: + return connection.getrefLocalId() return None setattr(cls, "getconnectionId", getconnectionId) def setconnectionPoints(self, idx, points): - if self.content: - self.content["value"][idx].setpoints(points) + connection = self.getconnection(idx) + if connection is not None: + connection.setpoints(points) setattr(cls, "setconnectionPoints", setconnectionPoints) def getconnectionPoints(self, idx): - if self.content: - return self.content["value"][idx].getpoints() - return None + connection = self.getconnection(idx) + if connection is not None: + return connection.getpoints() + return [] setattr(cls, "getconnectionPoints", getconnectionPoints) def setconnectionParameter(self, idx, parameter): - if self.content: - self.content["value"][idx].setformalParameter(parameter) + connection = self.getconnection(idx) + if connection is not None: + connection.setformalParameter(parameter) setattr(cls, "setconnectionParameter", setconnectionParameter) def getconnectionParameter(self, idx): - if self.content: - return self.content["value"][idx].getformalParameter() + connection = self.getconnection(idx) + if connection is not None: + return connection.getformalParameter() return None setattr(cls, "getconnectionParameter", getconnectionParameter) -cls = PLCOpenClasses.get("connectionPointOut", None) +cls = PLCOpenParser.GetElementClass("connectionPointOut") if cls: def setrelPositionXY(self, x, y): - self.relPosition = PLCOpenClasses["position"]() + self.relPosition = PLCOpenParser.CreateElement("relPosition", "connectionPointOut") self.relPosition.setx(x) self.relPosition.sety(y) setattr(cls, "setrelPositionXY", setrelPositionXY) def getrelPositionXY(self): - if self.relPosition: + if self.relPosition is not None: return self.relPosition.getx(), self.relPosition.gety() return self.relPosition setattr(cls, "getrelPositionXY", getrelPositionXY) -cls = PLCOpenClasses.get("value", None) +cls = PLCOpenParser.GetElementClass("value") if cls: def setvalue(self, value): value = value.strip() if value.startswith("[") and value.endswith("]"): - arrayValue = PLCOpenClasses["value_arrayValue"]() - self.content = {"name" : "arrayValue", "value" : arrayValue} + content = PLCOpenParser.CreateElement("arrayValue", "value") elif value.startswith("(") and value.endswith(")"): - structValue = PLCOpenClasses["value_structValue"]() - self.content = {"name" : "structValue", "value" : structValue} + content = PLCOpenParser.CreateElement("structValue", "value") else: - simpleValue = PLCOpenClasses["value_simpleValue"]() - self.content = {"name" : "simpleValue", "value": simpleValue} - self.content["value"].setvalue(value) + content = PLCOpenParser.CreateElement("simpleValue", "value") + content.setvalue(value) + self.setcontent(content) setattr(cls, "setvalue", setvalue) def getvalue(self): - return self.content["value"].getvalue() + return self.content.getvalue() setattr(cls, "getvalue", getvalue) def extractValues(values): @@ -2894,15 +2404,15 @@ raise ValueError, _("\"%s\" is an invalid value!")%value return items -cls = PLCOpenClasses.get("value_arrayValue", None) +cls = PLCOpenParser.GetElementClass("arrayValue", "value") if cls: arrayValue_model = re.compile("([0-9]*)\((.*)\)$") def setvalue(self, value): - self.value = [] + elements = [] for item in extractValues(value[1:-1]): item = item.strip() - element = PLCOpenClasses["arrayValue_value"]() + element = PLCOpenParser.CreateElement("value", "arrayValue") result = arrayValue_model.match(item) if result is not None: groups = result.groups() @@ -2910,14 +2420,18 @@ element.setvalue(groups[1].strip()) else: element.setvalue(item) - self.value.append(element) + elements.append(element) + self.value = elements setattr(cls, "setvalue", setvalue) def getvalue(self): values = [] for element in self.value: - repetition = element.getrepetitionValue() - if repetition is not None and int(repetition) > 1: + try: + repetition = int(element.getrepetitionValue()) + except: + repetition = 1 + if repetition > 1: value = element.getvalue() if value is None: value = "" @@ -2927,20 +2441,21 @@ return "[%s]"%", ".join(values) setattr(cls, "getvalue", getvalue) -cls = PLCOpenClasses.get("value_structValue", None) +cls = PLCOpenParser.GetElementClass("structValue", "value") if cls: structValue_model = re.compile("(.*):=(.*)") def setvalue(self, value): - self.value = [] + elements = [] for item in extractValues(value[1:-1]): result = structValue_model.match(item) if result is not None: groups = result.groups() - element = PLCOpenClasses["structValue_value"]() + element = PLCOpenParser.CreateElement("value", "structValue") element.setmember(groups[0].strip()) element.setvalue(groups[1].strip()) - self.value.append(element) + elements.append(element) + self.value = elements setattr(cls, "setvalue", setvalue) def getvalue(self): @@ -2949,3 +2464,4 @@ values.append("%s := %s"%(element.getmember(), element.getvalue())) return "(%s)"%", ".join(values) setattr(cls, "getvalue", getvalue) + diff -r 72a826dfcfbb -r 02fe382c4511 plcopen/pou_block_instances.xslt --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/plcopen/pou_block_instances.xslt Mon Nov 18 12:12:31 2013 +0900 @@ -0,0 +1,452 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + 0 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + input + + + + + + + + + + + + + + + + + + + + + + + output + + + + + + + + + + + + + + + + + output + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + STRING + + + + WSTRING + + + + + + + + + + + + + + + BOOL + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 0 + + + + + + + connection + + + reference + + + inline + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + jump + + + + + + + + + + + + + + + + + reference + + + inline + + + + + + + + + + + + + + + + + + + + N + + + + + + + + + + + + + + + + + + + + + + diff -r 72a826dfcfbb -r 02fe382c4511 plcopen/pou_block_instances.ysl2 --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/plcopen/pou_block_instances.ysl2 Mon Nov 18 12:12:31 2013 +0900 @@ -0,0 +1,315 @@ +include yslt.yml2 +estylesheet xmlns:ppx="http://www.plcopen.org/xml/tc6_0201" + xmlns:xhtml="http://www.w3.org/1999/xhtml" + xmlns:ns="pou_block_instances_ns" + extension-element-prefixes="ns" + exclude-result-prefixes="ns" { + + template "text()"; + + template "ppx:pou" { + apply "ppx:body/*[self::ppx:FBD or self::ppx:LD or self::ppx:SFC]/*"; + } + + function "add_instance" { + param "type"; + value "ns:AddBlockInstance($type, @localId, ppx:position/@x, ppx:position/@y, @width, @height)"; + } + + function "execution_order" { + choose { + when "@executionOrderId" > «@executionOrderId» + otherwise > 0 + } + } + + function "ConnectionInfos" { + param "type"; + param "negated"; + param "edge"; + param "formalParameter"; + value "ns:AddInstanceConnection($type, $formalParameter, $negated, $edge, ppx:relPosition/@x, ppx:relPosition/@y)"; + } + + template "ppx:position" { + value "ns:AddLinkPoint(@x, @y)"; + } + + template "ppx:connection" { + value "ns:AddConnectionLink(@refLocalId, @formalParameter)"; + apply "ppx:position"; + } + + template "ppx:connectionPointIn" { + param "negated"; + param "edge"; + param "formalParameter"; + call "ConnectionInfos" { + with "type" > input + with "negated" > «$negated» + with "edge" > «$edge» + with "formalParameter" > «$formalParameter» + } + apply "ppx:connection"; + } + + template "ppx:connectionPointOut" { + param "negated"; + param "edge"; + param "formalParameter"; + call "ConnectionInfos" { + with "type" > output + with "negated" > «$negated» + with "edge" > «$edge» + with "formalParameter" > «$formalParameter» + } + } + + template "ppx:connectionPointOutAction" { + call "ConnectionInfos" { + with "type" > output + } + } + + template "ppx:comment" { + value "ns:SetSpecificValues(ppx:content/xhtml:p/text())"; + call "add_instance" { + with "type" > «local-name()» + } + } + + template "ppx:block" { + variable "execution_order" { + call "execution_order"; + } + value "ns:SetSpecificValues(@instanceName, $execution_order)"; + call "add_instance" { + with "type" > «@typeName» + } + foreach "ppx:inputVariables/ppx:variable" { + apply "ppx:connectionPointIn" { + with "negated", "@negated"; + with "edge", "@edge"; + with "formalParameter", "@formalParameter"; + } + } + foreach "ppx:outputVariables/ppx:variable" { + apply "ppx:connectionPointOut" { + with "negated", "@negated"; + with "edge", "@edge"; + with "formalParameter", "@formalParameter"; + } + } + } + + template "*[self::ppx:type or self::ppx:baseType or self::ppx:returnType]/ppx:derived" { + > «@name» + } + + template "*[self::ppx:type or self::ppx:baseType or self::ppx:returnType]/ppx:string" { + > STRING + } + + template "*[self::ppx:type or self::ppx:baseType or self::ppx:returnType]/ppx:wstring" { + > WSTRING + } + + template "*[self::ppx:type or self::ppx:baseType or self::ppx:returnType]/*" { + > «local-name()» + } + + function "VariableBlockInfos" { + param "type"; + variable "expression" > «ppx:expression/text()» + variable "value_type" { + choose { + when "ancestor::ppx:transition[@name=$expression]" > BOOL + when "ancestor::ppx:pou[@name=$expression]" { + apply "ancestor::ppx:pou/child::ppx:interface/ppx:returnType" + } + otherwise { + apply "ancestor::ppx:pou/child::ppx:interface/*/ppx:variable[@name=$expression]/ppx:type" + } + } + } + variable "execution_order" { + call "execution_order"; + } + value "ns:SetSpecificValues($expression, $value_type, $execution_order)"; + call "add_instance" { + with "type" > «$type» + } + apply "ppx:connectionPointIn" { + with "negated", "@negatedIn"; + with "edge", "@edgeIn"; + } + apply "ppx:connectionPointOut" { + with "negated", "@negatedOut"; + with "edge", "@edgeOut"; + } + } + + template "ppx:inVariable" { + call "VariableBlockInfos" with "type", "'input'"; + } + + template "ppx:outVariable" { + call "VariableBlockInfos" with "type", "'output'"; + } + + template "ppx:inOutVariable" { + call "VariableBlockInfos" with "type", "'inout'"; + } + + template "ppx:connector|ppx:continuation" { + value "ns:SetSpecificValues(@name)"; + call "add_instance" { + with "type" > «local-name()» + } + apply "ppx:connectionPointIn"; + apply "ppx:connectionPointOut"; + } + + template "ppx:leftPowerRail|ppx:rightPowerRail" { + variable "type", "local-name()"; + variable "connectors" { + choose { + when "$type='leftPowerRail'" > «count(ppx:connectionPointOut)» + otherwise > «count(ppx:connectionPointIn)» + } + } + value "ns:SetSpecificValues($connectors)"; + call "add_instance" { + with "type" > «$type» + } + choose { + when "$type='leftPowerRail'" { + apply "ppx:connectionPointOut"; + } + otherwise { + apply "ppx:connectionPointIn"; + } + } + } + + template "ppx:contact|ppx:coil" { + variable "type", "local-name()"; + variable "storage" { + choose { + when "$type='coil'" > «@storage» + } + } + variable "execution_order" { + call "execution_order"; + } + value "ns:SetSpecificValues(ppx:variable/text(), @negated, @edge, $storage, $execution_order)"; + call "add_instance" { + with "type" > «$type» + } + apply "ppx:connectionPointIn"; + apply "ppx:connectionPointOut"; + } + + template "ppx:step" { + value "ns:SetSpecificValues(@name, @initialStep)"; + apply "ppx:connectionPointOutAction" { + with "negated", "@negated"; + } + call "add_instance" { + with "type" > «local-name()» + } + apply "ppx:connectionPointIn"; + apply "ppx:connectionPointOut"; + } + + template "ppx:transition" { + variable "priority" { + choose { + when "@priority" > «@priority» + otherwise > 0 + } + } + variable "condition_type" { + choose { + when "ppx:condition/ppx:connectionPointIn" > connection + when "ppx:condition/ppx:reference" > reference + when "ppx:condition/ppx:inline" > inline + } + } + variable "condition" { + choose { + when "ppx:reference" > «ppx:condition/ppx:reference/@name» + when "ppx:inline" > «ppx:condition/ppx:inline/ppx:body/ppx:ST/xhtml:p/text()» + } + } + value "ns:SetSpecificValues($priority, $condition_type, $condition)"; + apply "ppx:condition/ppx:connectionPointIn" { + with "negated", "ppx:condition/@negated"; + } + call "add_instance" { + with "type" > «local-name()» + } + apply "ppx:connectionPointIn"; + apply "ppx:connectionPointOut"; + } + + template "ppx:selectionDivergence|ppx:selectionConvergence|ppx:simultaneousDivergence|ppx:simultaneousConvergence" { + variable "type" > «local-name()» + variable "connectors" { + choose { + when "$type='selectionDivergence' or $type='simultaneousDivergence'" { + > «count(ppx:connectionPointOut)» + } + otherwise > «count(ppx:connectionPointIn)» + } + } + value "ns:SetSpecificValues($connectors)"; + call "add_instance" { + with "type" > «$type» + } + apply "ppx:connectionPointIn"; + apply "ppx:connectionPointOut"; + } + + template "ppx:jumpStep" { + variable "type" > jump + value "ns:SetSpecificValues(@targetName)"; + call "add_instance" { + with "type" > «$type» + } + apply "ppx:connectionPointIn"; + } + + template "ppx:action" { + variable "type" { + choose { + when "ppx:reference" > reference + when "ppx:inline" > inline + } + } + variable "value" { + choose { + when "ppx:reference" > «ppx:reference/@name» + when "ppx:inline" > «ppx:inline/ppx:ST/xhtml:p/text()» + } + } + variable "qualifier" { + choose { + when "@qualifier" > «@qualifier» + otherwise > N + } + } + value "ns:AddAction($qualifier, $type, $value, @duration, @indicator)"; + } + + template "ppx:actionBlock" { + value "ns:SetSpecificValues()"; + apply "ppx:action"; + call "add_instance" { + with "type" > «local-name()» + } + apply "ppx:connectionPointIn" { + with "negated", "@negated"; + } + } +} \ No newline at end of file diff -r 72a826dfcfbb -r 02fe382c4511 plcopen/pou_variables.xslt --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/plcopen/pou_variables.xslt Mon Nov 18 12:12:31 2013 +0900 @@ -0,0 +1,378 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + true + + + true + + + + + + + + + + + + + + + + + + + + + + + + + action + + + + + + + + + + + transition + + + + + + + + + + + configuration + + + false + + + + + + + + + + + + + + resource + + + false + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Local + + + + + + + + Global + + + + + + + + External + + + + + + + + Temp + + + + + + + + Input + + + + + + + + Output + + + + + + + + InOut + + + + + + + + + + true + + + true + + + + + + + + + + + action + + + + + + + + + + + transition + + + + + + + + + + + resource + + + false + + + + + + + + + + + program + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + ARRAY [ + + + .. + + + ] OF + + + + + + + STRING + + + + WSTRING + + + + + + + + + + + + + + true + + + false + + + + + + + + + + + + false + + + + + + + + + + + + + + + false + + + + + + true + + + + false + + + + false + + + + true + + diff -r 72a826dfcfbb -r 02fe382c4511 plcopen/pou_variables.ysl2 --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/plcopen/pou_variables.ysl2 Mon Nov 18 12:12:31 2013 +0900 @@ -0,0 +1,279 @@ +include yslt.yml2 +estylesheet xmlns:ppx="http://www.plcopen.org/xml/tc6_0201" + xmlns:xhtml="http://www.w3.org/1999/xhtml" + xmlns:ns="pou_vars_ns" + extension-element-prefixes="ns" + exclude-result-prefixes="ns" { + + template "text()"; + template "text()", mode="var_class"; + template "text()", mode="var_type"; + template "text()", mode="var_edit"; + template "text()", mode="var_debug"; + + variable "project" { + copy "document('project')/project/*"; + } + + variable "stdlib" { + copy "document('stdlib')/stdlib/*"; + } + variable "extensions" { + copy "document('extensions')/extensions/*"; + } + + function "add_root" { + param "class"; + param "type"; + param "edit" > true + param "debug" > true + value "ns:SetRoot($class, $type, $edit, $debug)"; + } + + template "ppx:pou" { + call "add_root" { + with "class" > «@pouType» + with "type" > «@name» + } + apply "ppx:interface"; + apply "ppx:actions/ppx:action | ppx:transitions/ppx:transition", mode="variable_list"; + } + + template "ppx:action" { + call "add_root" { + with "class" > action + } + apply "ancestor::ppx:pou/child::ppx:interface"; + } + + template "ppx:transition" { + call "add_root" { + with "class" > transition + } + apply "ancestor::ppx:pou/child::ppx:interface"; + } + + template "ppx:configuration" { + call "add_root" { + with "class" > configuration + with "debug" > false + } + apply "ppx:resource", mode="variable_list"; + apply "ppx:globalVars"; + } + + template "ppx:resource" { + call "add_root" { + with "class" > resource + with "debug" > false + } + apply "ppx:pouInstance | ppx:task/ppx:pouInstance", mode="variable_list"; + apply "ppx:globalVars"; + } + + function "variables_infos" { + param "var_class"; + foreach "ppx:variable" { + variable "class" { + apply "ppx:type", mode="var_class" { + with "default_class" > «$var_class» + } + } + variable "type" { + apply"ppx:type", mode="var_type"; + } + variable "edit" { + apply "ppx:type", mode="var_edit"; + } + variable "debug" { + apply "ppx:type", mode="var_debug"; + } + value "ns:AddVariable(@name, $class, $type, $edit, $debug)"; + } + } + + template "ppx:localVars" { + call "variables_infos" { + with "var_class" > Local + } + } + + template "ppx:globalVars" { + call "variables_infos" { + with "var_class" > Global + } + } + + template "ppx:externalVars" { + call "variables_infos" { + with "var_class" > External + } + } + + template "ppx:tempVars" { + call "variables_infos" { + with "var_class" > Temp + } + } + + template "ppx:inputVars" { + call "variables_infos" { + with "var_class" > Input + } + } + + template "ppx:outputVars" { + call "variables_infos" { + with "var_class" > Output + } + } + + template "ppx:inOutVars" { + call "variables_infos" { + with "var_class" > InOut + } + } + + function "add_variable" { + param "name"; + param "class"; + param "type"; + param "edit" > true + param "debug" > true + value "ns:AddVariable($name, $class, $type, $edit, $debug)"; + } + + template "ppx:action", mode="variable_list" { + call "add_variable" { + with "name" > «@name» + with "class" > action + } + } + + template "ppx:transition", mode="variable_list" { + call "add_variable" { + with "name" > «@name» + with "class" > transition + } + } + + template "ppx:resource", mode="variable_list" { + call "add_variable" { + with "name" > «@name» + with "class" > resource + with "debug" > false + } + } + + template "ppx:pouInstance", mode="variable_list" { + call "add_variable" { + with "name" > «@name» + with "class" > program + with "type" > «@typeName» + } + } + + template "*[self::ppx:type or self::ppx:baseType]/ppx:derived", mode="var_class" { + param "default_class"; + variable "type_name", "@name"; + variable "pou_infos" { + copy """exsl:node-set($project)/ppx:project/ppx:types/ppx:pous/ppx:pou[@name=$type_name] | + exsl:node-set($stdlib)/ppx:project/ppx:types/ppx:pous/ppx:pou[@name=$type_name] | + exsl:node-set($extensions)/ppx:project/ppx:types/ppx:pous/ppx:pou[@name=$type_name]"""; + } + choose { + when "$pou_infos != ''" { + apply "exsl:node-set($pou_infos)", mode="var_class"; + } + otherwise { + value "$default_class" + } + } + } + + template "ppx:pou", mode="var_class" { + value "@pouType"; + } + + template "*[self::ppx:type or self::ppx:baseType]/*" mode="var_class" { + param "default_class"; + value "$default_class"; + } + + template "*[self::ppx:type or self::ppx:baseType]/ppx:derived", mode="var_type" { + > «@name» + } + + template "*[self::ppx:type or self::ppx:baseType]/ppx:array", mode="var_type" { + > ARRAY [ + foreach "ppx:dimension" { + > «@lower»..«@upper» + } + > ] OF + apply "ppx:baseType", mode="var_type"; + } + + template "*[self::ppx:type or self::ppx:baseType]/ppx:string", mode="var_type" { + > STRING + } + + template "*[self::ppx:type or self::ppx:baseType]/ppx:wstring", mode="var_type" { + > WSTRING + } + + template "*[self::ppx:type or self::ppx:baseType]/*", mode="var_type" { + > «local-name()» + } + + template "*[self::ppx:type or self::ppx:baseType]/ppx:derived", mode="var_edit" { + variable "type_name", "@name"; + variable "pou_infos" { + copy "exsl:node-set($project)/ppx:project/ppx:types/ppx:pous/ppx:pou[@name=$type_name]"; + } + choose { + when "$pou_infos != ''" > true + otherwise > false + } + } + + template "*[self::ppx:type or self::ppx:baseType]/ppx:array", mode="var_edit" { + apply "ppx:baseType", mode="var_edit"; + } + + template "*[self::ppx:type or self::ppx:baseType]/*", mode="var_edit" { + > false + } + + template "*[self::ppx:type or self::ppx:baseType]/ppx:derived", mode="var_debug" { + variable "type_name", "@name"; + variable "datatype_infos" { + copy """exsl:node-set($project)/ppx:project/ppx:types/ppx:pous/ppx:pou[@name=$type_name] | + exsl:node-set($project)/ppx:project/ppx:types/ppx:dataTypes/ppx:dataType[@name=$type_name] | + exsl:node-set($stdlib)/ppx:project/ppx:types/ppx:dataTypes/ppx:dataType[@name=$type_name] | + exsl:node-set($extensions)/ppx:project/ppx:types/ppx:dataTypes/ppx:dataType[@name=$type_name]"""; + } + choose { + when "$datatype_infos != ''" { + apply "exsl:node-set($datatype_infos)", mode="var_debug"; + } + otherwise > false + } + } + + template "ppx:pou", mode="var_debug" { + > true + } + + template "*[self::ppx:type or self::ppx:baseType]/ppx:array", mode="var_debug" { + > false + } + + template "*[self::ppx:type or self::ppx:baseType]/ppx:struct", mode="var_debug" { + > false + } + + template "*[self::ppx:type or self::ppx:baseType]/*", mode="var_debug" { + > true + } + +} diff -r 72a826dfcfbb -r 02fe382c4511 plcopen/structures.py --- a/plcopen/structures.py Wed Jul 31 10:45:07 2013 +0900 +++ b/plcopen/structures.py Mon Nov 18 12:12:31 2013 +0900 @@ -23,6 +23,8 @@ #Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA import string, os, sys, re +from plcopen import LoadProject +from collections import OrderedDict LANGUAGES = ["IL","ST","FBD","LD","SFC"] @@ -34,205 +36,50 @@ _ = lambda x:x -# Helper for emulate join on element list -def JoinList(separator, mylist): - if len(mylist) > 0 : - return reduce(lambda x, y: x + separator + y, mylist) - else : - return mylist - -def generate_block(generator, block, block_infos, body, link, order=False, to_inout=False): - body_type = body.getcontent()["name"] - name = block.getinstanceName() - type = block.gettypeName() - executionOrderId = block.getexecutionOrderId() - input_variables = block.inputVariables.getvariable() - output_variables = block.outputVariables.getvariable() - inout_variables = {} - for input_variable in input_variables: - for output_variable in output_variables: - if input_variable.getformalParameter() == output_variable.getformalParameter(): - inout_variables[input_variable.getformalParameter()] = "" - input_names = [input[0] for input in block_infos["inputs"]] - output_names = [output[0] for output in block_infos["outputs"]] - if block_infos["type"] == "function": - if not generator.ComputedBlocks.get(block, False) and not order: - generator.ComputedBlocks[block] = True - connected_vars = [] - if not block_infos["extensible"]: - input_connected = dict([("EN", None)] + - [(input_name, None) for input_name in input_names]) - for variable in input_variables: - parameter = variable.getformalParameter() - if input_connected.has_key(parameter): - input_connected[parameter] = variable - if input_connected["EN"] is None: - input_connected.pop("EN") - input_parameters = input_names - else: - input_parameters = ["EN"] + input_names - else: - input_connected = dict([(variable.getformalParameter(), variable) - for variable in input_variables]) - input_parameters = [variable.getformalParameter() - for variable in input_variables] - one_input_connected = False - all_input_connected = True - for i, parameter in enumerate(input_parameters): - variable = input_connected.get(parameter) - if variable is not None: - input_info = (generator.TagName, "block", block.getlocalId(), "input", i) - connections = variable.connectionPointIn.getconnections() - if connections is not None: - if parameter != "EN": - one_input_connected = True - if inout_variables.has_key(parameter): - expression = generator.ComputeExpression(body, connections, executionOrderId > 0, True) - if expression is not None: - inout_variables[parameter] = value - else: - expression = generator.ComputeExpression(body, connections, executionOrderId > 0) - if expression is not None: - connected_vars.append(([(parameter, input_info), (" := ", ())], - generator.ExtractModifier(variable, expression, input_info))) - else: - all_input_connected = False - else: - all_input_connected = False - if len(output_variables) > 1 or not all_input_connected: - vars = [name + value for name, value in connected_vars] - else: - vars = [value for name, value in connected_vars] - if one_input_connected: - for i, variable in enumerate(output_variables): - parameter = variable.getformalParameter() - if not inout_variables.has_key(parameter) and parameter in output_names + ["", "ENO"]: - if variable.getformalParameter() == "": - variable_name = "%s%d"%(type, block.getlocalId()) - else: - variable_name = "%s%d_%s"%(type, block.getlocalId(), parameter) - if generator.Interface[-1][0] != "VAR" or generator.Interface[-1][1] is not None or generator.Interface[-1][2]: - generator.Interface.append(("VAR", None, False, [])) - if variable.connectionPointOut in generator.ConnectionTypes: - generator.Interface[-1][3].append((generator.ConnectionTypes[variable.connectionPointOut], variable_name, None, None)) - else: - generator.Interface[-1][3].append(("ANY", variable_name, None, None)) - if len(output_variables) > 1 and parameter not in ["", "OUT"]: - vars.append([(parameter, (generator.TagName, "block", block.getlocalId(), "output", i)), - (" => %s"%variable_name, ())]) - else: - output_info = (generator.TagName, "block", block.getlocalId(), "output", i) - output_name = variable_name - generator.Program += [(generator.CurrentIndent, ()), - (output_name, output_info), - (" := ", ()), - (type, (generator.TagName, "block", block.getlocalId(), "type")), - ("(", ())] - generator.Program += JoinList([(", ", ())], vars) - generator.Program += [(");\n", ())] - else: - generator.Warnings.append(_("\"%s\" function cancelled in \"%s\" POU: No input connected")%(type, generator.TagName.split("::")[-1])) - elif block_infos["type"] == "functionBlock": - if not generator.ComputedBlocks.get(block, False) and not order: - generator.ComputedBlocks[block] = True - vars = [] - offset_idx = 0 - for variable in input_variables: - parameter = variable.getformalParameter() - if parameter in input_names or parameter == "EN": - if parameter == "EN": - input_idx = 0 - offset_idx = 1 - else: - input_idx = offset_idx + input_names.index(parameter) - input_info = (generator.TagName, "block", block.getlocalId(), "input", input_idx) - connections = variable.connectionPointIn.getconnections() - if connections is not None: - expression = generator.ComputeExpression(body, connections, executionOrderId > 0, inout_variables.has_key(parameter)) - if expression is not None: - vars.append([(parameter, input_info), - (" := ", ())] + generator.ExtractModifier(variable, expression, input_info)) - generator.Program += [(generator.CurrentIndent, ()), - (name, (generator.TagName, "block", block.getlocalId(), "name")), - ("(", ())] - generator.Program += JoinList([(", ", ())], vars) - generator.Program += [(");\n", ())] - - if link: - connectionPoint = link.getposition()[-1] - output_parameter = link.getformalParameter() - else: - connectionPoint = None - output_parameter = None - - output_variable = None - output_idx = 0 - if output_parameter is not None: - if output_parameter in output_names or output_parameter == "ENO": - for variable in output_variables: - if variable.getformalParameter() == output_parameter: - output_variable = variable - if output_parameter != "ENO": - output_idx = output_names.index(output_parameter) - else: - for i, variable in enumerate(output_variables): - blockPointx, blockPointy = variable.connectionPointOut.getrelPositionXY() - if (not connectionPoint or - block.getx() + blockPointx == connectionPoint.getx() and - block.gety() + blockPointy == connectionPoint.gety()): - output_variable = variable - output_parameter = variable.getformalParameter() - output_idx = i - - if output_variable is not None: - if block_infos["type"] == "function": - output_info = (generator.TagName, "block", block.getlocalId(), "output", output_idx) - if inout_variables.has_key(output_parameter): - output_value = inout_variables[output_parameter] - else: - if output_parameter == "": - output_name = "%s%d"%(type, block.getlocalId()) - else: - output_name = "%s%d_%s"%(type, block.getlocalId(), output_parameter) - output_value = [(output_name, output_info)] - return generator.ExtractModifier(output_variable, output_value, output_info) - - if block_infos["type"] == "functionBlock": - output_info = (generator.TagName, "block", block.getlocalId(), "output", output_idx) - output_name = generator.ExtractModifier(output_variable, [("%s.%s"%(name, output_parameter), output_info)], output_info) - if to_inout: - variable_name = "%s_%s"%(name, output_parameter) - if not generator.IsAlreadyDefined(variable_name): - if generator.Interface[-1][0] != "VAR" or generator.Interface[-1][1] is not None or generator.Interface[-1][2]: - generator.Interface.append(("VAR", None, False, [])) - if variable.connectionPointOut in generator.ConnectionTypes: - generator.Interface[-1][3].append( - (generator.ConnectionTypes[output_variable.connectionPointOut], variable_name, None, None)) - else: - generator.Interface[-1][3].append(("ANY", variable_name, None, None)) - generator.Program += [(generator.CurrentIndent, ()), - ("%s := "%variable_name, ())] - generator.Program += output_name - generator.Program += [(";\n", ())] - return [(variable_name, ())] - return output_name - if link is not None: - if output_parameter is None: - output_parameter = "" - if name: - blockname = "%s(%s)" % (name, type) - else: - blockname = type - raise ValueError, _("No output %s variable found in block %s in POU %s. Connection must be broken") % \ - (output_parameter, blockname, generator.Name) - -def initialise_block(type, name, block = None): - return [(type, name, None, None)] - #------------------------------------------------------------------------------- # Function Block Types definitions #------------------------------------------------------------------------------- +ScriptDirectory = os.path.split(os.path.realpath(__file__))[0] + +StdBlockLibrary, error = LoadProject( + os.path.join(ScriptDirectory, "Standard_Function_Blocks.xml")) +AddnlBlockLibrary, error = LoadProject( + os.path.join(ScriptDirectory, "Additional_Function_Blocks.xml")) + +StdBlockComments = { + "SR": _("SR bistable\nThe SR bistable is a latch where the Set dominates."), + "RS": _("RS bistable\nThe RS bistable is a latch where the Reset dominates."), + "SEMA": _("Semaphore\nThe semaphore provides a mechanism to allow software elements mutually exclusive access to certain ressources."), + "R_TRIG": _("Rising edge detector\nThe output produces a single pulse when a rising edge is detected."), + "F_TRIG": _("Falling edge detector\nThe output produces a single pulse when a falling edge is detected."), + "CTU": _("Up-counter\nThe up-counter can be used to signal when a count has reached a maximum value."), + "CTD": _("Down-counter\nThe down-counter can be used to signal when a count has reached zero, on counting down from a preset value."), + "CTUD": _("Up-down counter\nThe up-down counter has two inputs CU and CD. It can be used to both count up on one input and down on the other."), + "TP": _("Pulse timer\nThe pulse timer can be used to generate output pulses of a given time duration."), + "TON": _("On-delay timer\nThe on-delay timer can be used to delay setting an output true, for fixed period after an input becomes true."), + "TOF": _("Off-delay timer\nThe off-delay timer can be used to delay setting an output false, for fixed period after input goes false."), + "RTC": _("Real time clock\nThe real time clock has many uses including time stamping, setting dates and times of day in batch reports, in alarm messages and so on."), + "INTEGRAL": _("Integral\nThe integral function block integrates the value of input XIN over time."), + "DERIVATIVE": _("Derivative\nThe derivative function block produces an output XOUT proportional to the rate of change of the input XIN."), + "PID": _("PID\nThe PID (proportional, Integral, Derivative) function block provides the classical three term controller for closed loop control."), + "RAMP": _("Ramp\nThe RAMP function block is modelled on example given in the standard."), + "HYSTERESIS": _("Hysteresis\nThe hysteresis function block provides a hysteresis boolean output driven by the difference of two floating point (REAL) inputs XIN1 and XIN2."), +} + +for block_type in ["CTU", "CTD", "CTUD"]: + for return_type in ["DINT", "LINT", "UDINT", "ULINT"]: + StdBlockComments["%s_%s" % (block_type, return_type)] = StdBlockComments[block_type] + +def GetBlockInfos(pou): + infos = pou.getblockInfos() + infos["comment"] = StdBlockComments[infos["name"]] + infos["inputs"] = [ + (var_name, var_type, "rising") + if var_name in ["CU", "CD"] + else (var_name, var_type, var_modifier) + for var_name, var_type, var_modifier in infos["inputs"]] + return infos """ Ordored list of common Function Blocks defined in the IEC 61131-3 @@ -250,100 +97,10 @@ - The default modifier which can be "none", "negated", "rising" or "falling" """ -BlockTypes = [{"name" : _("Standard function blocks"), "list": - [{"name" : "SR", "type" : "functionBlock", "extensible" : False, - "inputs" : [("S1","BOOL","none"),("R","BOOL","none")], - "outputs" : [("Q1","BOOL","none")], - "comment" : _("SR bistable\nThe SR bistable is a latch where the Set dominates."), - "generate" : generate_block, "initialise" : initialise_block}, - {"name" : "RS", "type" : "functionBlock", "extensible" : False, - "inputs" : [("S","BOOL","none"),("R1","BOOL","none")], - "outputs" : [("Q1","BOOL","none")], - "comment" : _("RS bistable\nThe RS bistable is a latch where the Reset dominates."), - "generate" : generate_block, "initialise" : initialise_block}, - {"name" : "SEMA", "type" : "functionBlock", "extensible" : False, - "inputs" : [("CLAIM","BOOL","none"),("RELEASE","BOOL","none")], - "outputs" : [("BUSY","BOOL","none")], - "comment" : _("Semaphore\nThe semaphore provides a mechanism to allow software elements mutually exclusive access to certain ressources."), - "generate" : generate_block, "initialise" : initialise_block}, - {"name" : "R_TRIG", "type" : "functionBlock", "extensible" : False, - "inputs" : [("CLK","BOOL","none")], - "outputs" : [("Q","BOOL","none")], - "comment" : _("Rising edge detector\nThe output produces a single pulse when a rising edge is detected."), - "generate" : generate_block, "initialise" : initialise_block}, - {"name" : "F_TRIG", "type" : "functionBlock", "extensible" : False, - "inputs" : [("CLK","BOOL","none")], - "outputs" : [("Q","BOOL","none")], - "comment" : _("Falling edge detector\nThe output produces a single pulse when a falling edge is detected."), - "generate" : generate_block, "initialise" : initialise_block}, - {"name" : "CTU", "type" : "functionBlock", "extensible" : False, - "inputs" : [("CU","BOOL","rising"),("R","BOOL","none"),("PV","INT","none")], - "outputs" : [("Q","BOOL","none"),("CV","INT","none")], - "comment" : _("Up-counter\nThe up-counter can be used to signal when a count has reached a maximum value."), - "generate" : generate_block, "initialise" : initialise_block}, - {"name" : "CTD", "type" : "functionBlock", "extensible" : False, - "inputs" : [("CD","BOOL","rising"),("LD","BOOL","none"),("PV","INT","none")], - "outputs" : [("Q","BOOL","none"),("CV","INT","none")], - "comment" : _("Down-counter\nThe down-counter can be used to signal when a count has reached zero, on counting down from a preset value."), - "generate" : generate_block, "initialise" : initialise_block}, - {"name" : "CTUD", "type" : "functionBlock", "extensible" : False, - "inputs" : [("CU","BOOL","rising"),("CD","BOOL","rising"),("R","BOOL","none"),("LD","BOOL","none"),("PV","INT","none")], - "outputs" : [("QU","BOOL","none"),("QD","BOOL","none"),("CV","INT","none")], - "comment" : _("Up-down counter\nThe up-down counter has two inputs CU and CD. It can be used to both count up on one input and down on the other."), - "generate" : generate_block, "initialise" : initialise_block}, - {"name" : "TP", "type" : "functionBlock", "extensible" : False, - "inputs" : [("IN","BOOL","none"),("PT","TIME","none")], - "outputs" : [("Q","BOOL","none"),("ET","TIME","none")], - "comment" : _("Pulse timer\nThe pulse timer can be used to generate output pulses of a given time duration."), - "generate" : generate_block, "initialise" : initialise_block}, - {"name" : "TON", "type" : "functionBlock", "extensible" : False, - "inputs" : [("IN","BOOL","none"),("PT","TIME","none")], - "outputs" : [("Q","BOOL","none"),("ET","TIME","none")], - "comment" : _("On-delay timer\nThe on-delay timer can be used to delay setting an output true, for fixed period after an input becomes true."), - "generate" : generate_block, "initialise" : initialise_block}, - {"name" : "TOF", "type" : "functionBlock", "extensible" : False, - "inputs" : [("IN","BOOL","none"),("PT","TIME","none")], - "outputs" : [("Q","BOOL","none"),("ET","TIME","none")], - "comment" : _("Off-delay timer\nThe off-delay timer can be used to delay setting an output false, for fixed period after input goes false."), - "generate" : generate_block, "initialise" : initialise_block}, - ]}, +StdBlckLst = [{"name" : _("Standard function blocks"), "list": + [GetBlockInfos(pou) for pou in StdBlockLibrary.getpous()]}, {"name" : _("Additional function blocks"), "list": - [{"name" : "RTC", "type" : "functionBlock", "extensible" : False, - "inputs" : [("IN","BOOL","none"),("PDT","DATE_AND_TIME","none")], - "outputs" : [("Q","BOOL","none"),("CDT","DATE_AND_TIME","none")], - "comment" : _("Real time clock\nThe real time clock has many uses including time stamping, setting dates and times of day in batch reports, in alarm messages and so on."), - "generate" : generate_block, "initialise" : initialise_block}, - {"name" : "INTEGRAL", "type" : "functionBlock", "extensible" : False, - "inputs" : [("RUN","BOOL","none"),("R1","BOOL","none"),("XIN","REAL","none"),("X0","REAL","none"),("CYCLE","TIME","none")], - "outputs" : [("Q","BOOL","none"),("XOUT","REAL","none")], - "comment" : _("Integral\nThe integral function block integrates the value of input XIN over time."), - "generate" : generate_block, "initialise" : initialise_block}, - {"name" : "DERIVATIVE", "type" : "functionBlock", "extensible" : False, - "inputs" : [("RUN","BOOL","none"),("XIN","REAL","none"),("CYCLE","TIME","none")], - "outputs" : [("XOUT","REAL","none")], - "comment" : _("Derivative\nThe derivative function block produces an output XOUT proportional to the rate of change of the input XIN."), - "generate" : generate_block, "initialise" : initialise_block}, - {"name" : "PID", "type" : "functionBlock", "extensible" : False, - "inputs" : [("AUTO","BOOL","none"),("PV","REAL","none"),("SP","REAL","none"),("X0","REAL","none"),("KP","REAL","none"),("TR","REAL","none"),("TD","REAL","none"),("CYCLE","TIME","none")], - "outputs" : [("XOUT","REAL","none")], - "comment" : _("PID\nThe PID (proportional, Integral, Derivative) function block provides the classical three term controller for closed loop control."), - "generate" : generate_block, "initialise" : initialise_block}, - {"name" : "RAMP", "type" : "functionBlock", "extensible" : False, - "inputs" : [("RUN","BOOL","none"),("X0","REAL","none"),("X1","REAL","none"),("TR","TIME","none"),("CYCLE","TIME","none")], - "outputs" : [("BUSY","BOOL","none"),("XOUT","REAL","none")], - "comment" : _("Ramp\nThe RAMP function block is modelled on example given in the standard."), - "generate" : generate_block, "initialise" : initialise_block}, - {"name" : "HYSTERESIS", "type" : "functionBlock", "extensible" : False, - "inputs" : [("XIN1","REAL","none"),("XIN2","REAL","none"),("EPS","REAL","none")], - "outputs" : [("Q","BOOL","none")], - "comment" : _("Hysteresis\nThe hysteresis function block provides a hysteresis boolean output driven by the difference of two floating point (REAL) inputs XIN1 and XIN2."), - "generate" : generate_block, "initialise" : initialise_block}, -## {"name" : "RATIO_MONITOR", "type" : "functionBlock", "extensible" : False, -## "inputs" : [("PV1","REAL","none"),("PV2","REAL","none"),("RATIO","REAL","none"),("TIMON","TIME","none"),("TIMOFF","TIME","none"),("TOLERANCE","BOOL","none"),("RESET","BOOL","none"),("CYCLE","TIME","none")], -## "outputs" : [("ALARM","BOOL","none"),("TOTAL_ERR","BOOL","none")], -## "comment" : _("Ratio monitor\nThe ratio_monitor function block checks that one process value PV1 is always a given ratio (defined by input RATIO) of a second process value PV2."), -## "generate" : generate_block, "initialise" : initialise_block} - ]}, + [GetBlockInfos(pou) for pou in AddnlBlockLibrary.getpous()]}, ] @@ -601,8 +358,6 @@ Function_decl_list = [] if Current_section: Function_decl = dict([(champ, val) for champ, val in zip(fonctions, fields[1:]) if champ]) - Function_decl["generate"] = generate_block - Function_decl["initialise"] = lambda x,y:[] baseinputnumber = int(Function_decl.get("baseinputnumber",1)) Function_decl["baseinputnumber"] = baseinputnumber for param, value in Function_decl.iteritems(): @@ -661,22 +416,25 @@ return Standard_Functions_Decl -std_decl = get_standard_funtions(csv_file_to_table(open(os.path.join(os.path.split(__file__)[0],"iec_std.csv"))))#, True) - -BlockTypes.extend(std_decl) - -for section in BlockTypes: +std_decl = get_standard_funtions(csv_file_to_table(open(os.path.join(ScriptDirectory,"iec_std.csv"))))#, True) + +StdBlckLst.extend(std_decl) + +# Dictionary to speedup block type fetching by name +StdBlckDct = OrderedDict() + +for section in StdBlckLst: for desc in section["list"]: words = desc["comment"].split('"') if len(words) > 1: desc["comment"] = words[1] - desc["usage"] = ( - "\n (" + - str([ " " + fctdecl[1]+":"+fctdecl[0] for fctdecl in desc["inputs"]]).strip("[]").replace("'",'') + - " ) => (" + - str([ " " + fctdecl[1]+":"+fctdecl[0] for fctdecl in desc["outputs"]]).strip("[]").replace("'",'') + - " )") - + desc["usage"] = ("\n (%s) => (%s)" % + (", ".join(["%s:%s" % (input[1], input[0]) + for input in desc["inputs"]]), + ", ".join(["%s:%s" % (output[1], output[0]) + for output in desc["outputs"]]))) + BlkLst = StdBlckDct.setdefault(desc["name"],[]) + BlkLst.append((section["name"], desc)) #------------------------------------------------------------------------------- # Languages Keywords @@ -687,7 +445,7 @@ POU_BLOCK_START_KEYWORDS = ["FUNCTION", "FUNCTION_BLOCK", "PROGRAM"] POU_BLOCK_END_KEYWORDS = ["END_FUNCTION", "END_FUNCTION_BLOCK", "END_PROGRAM"] POU_KEYWORDS = ["EN", "ENO", "F_EDGE", "R_EDGE"] + POU_BLOCK_START_KEYWORDS + POU_BLOCK_END_KEYWORDS -for category in BlockTypes: +for category in StdBlckLst: for block in category["list"]: if block["name"] not in POU_KEYWORDS: POU_KEYWORDS.append(block["name"]) diff -r 72a826dfcfbb -r 02fe382c4511 plcopen/variables_infos.xslt --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/plcopen/variables_infos.xslt Mon Nov 18 12:12:31 2013 +0900 @@ -0,0 +1,309 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Constant + + + Retain + + + Non-Retain + + + + + + + + + + + + + true + + + + + + + + + + + + + + + + + + + + Local + + + + + + + + Global + + + + + + + + External + + + + + + + + Temp + + + + + + + + Input + + + + + + + + Output + + + + + + + + InOut + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + STRING + + + + + + + WSTRING + + + + + + + + + + + + + + + + + + + + + false + + + true + + + + + + true + + + + + + + ( + + + + ) + + + + := + + + + + + + + + + + + + + + + + + + + + + + + + + + , + + + + + + + + + + [ + + + ] + + + + + + + + ( + + + ) + + + + diff -r 72a826dfcfbb -r 02fe382c4511 plcopen/variables_infos.ysl2 --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/plcopen/variables_infos.ysl2 Mon Nov 18 12:12:31 2013 +0900 @@ -0,0 +1,235 @@ +include yslt.yml2 +estylesheet xmlns:ppx="http://www.plcopen.org/xml/tc6_0201" + xmlns:xhtml="http://www.w3.org/1999/xhtml" + xmlns:ns="var_infos_ns" + extension-element-prefixes="ns" + exclude-result-prefixes="ns" { + + param "tree"; + + template "text()"; + + variable "project" { + copy "document('project')/project/*"; + } + + variable "stdlib" { + copy "document('stdlib')/stdlib/*"; + } + variable "extensions" { + copy "document('extensions')/extensions/*"; + } + + template "ppx:configuration" { + apply "ppx:globalVars"; + } + + template "ppx:resource" { + apply "ppx:globalVars"; + } + + template "ppx:pou" { + apply "ppx:interface/*"; + } + + template "ppx:returnType" { + value "ns:AddTree()"; + apply ".", mode="var_type"; + } + + function "variables_infos" { + param "var_class"; + variable "var_option" { + choose { + when "@constant='true' or @constant='1'" > Constant + when "@retain='true' or @retain='1'" > Retain + when "@nonretain='true' or @nonretain='1'" > Non-Retain + } + } + foreach "ppx:variable" { + variable "initial_value" { + apply "ppx:initialValue"; + } + variable "edit" { + choose { + when "$var_class='Global' or $var_class='External'" > true + otherwise { + apply "ppx:type", mode="var_edit"; + } + } + } + value "ns:AddTree()"; + apply "ppx:type", mode="var_type"; + value "ns:AddVariable(@name, $var_class, $var_option, @address, $initial_value, $edit, ppx:documentation/xhtml:p/text())"; + } + } + + template "ppx:localVars" { + call "variables_infos" { + with "var_class" > Local + } + } + + template "ppx:globalVars" { + call "variables_infos" { + with "var_class" > Global + } + } + + template "ppx:externalVars" { + call "variables_infos" { + with "var_class" > External + } + } + + template "ppx:tempVars" { + call "variables_infos" { + with "var_class" > Temp + } + } + + template "ppx:inputVars" { + call "variables_infos" { + with "var_class" > Input + } + } + + template "ppx:outputVars" { + call "variables_infos" { + with "var_class" > Output + } + } + + template "ppx:inOutVars" { + call "variables_infos" { + with "var_class" > InOut + } + } + + template "ppx:pou", mode="var_type" { + apply "ppx:interface/*[self::ppx:inputVars or self::ppx:inOutVars or self::ppx:outputVars]/ppx:variable", mode="var_type"; + } + + template "ppx:variable", mode="var_type" { + variable "name" > «@name» + value "ns:AddTree()"; + apply "ppx:type", mode="var_type"; + value "ns:AddVarToTree($name)"; + } + + template "ppx:dataType", mode="var_type" { + apply "ppx:baseType", mode="var_type"; + } + + template "*[self::ppx:type or self::ppx:baseType or self::ppx:returnType]/ppx:struct", mode="var_type" { + apply "ppx:variable", mode="var_type"; + } + + template "*[self::ppx:type or self::ppx:baseType or self::ppx:returnType]/ppx:derived", mode="var_type" { + variable "type_name" > «@name» + choose { + when "$tree='True'" { + apply """exsl:node-set($project)/ppx:project/ppx:types/ppx:pous/ppx:pou[@name=$type_name] | + exsl:node-set($project)/ppx:project/ppx:types/ppx:dataTypes/ppx:dataType[@name=$type_name] | + exsl:node-set($stdlib)/ppx:project/ppx:types/ppx:pous/ppx:pou[@name=$type_name] | + exsl:node-set($stdlib)/ppx:project/ppx:types/ppx:dataTypes/ppx:dataType[@name=$type_name] | + exsl:node-set($extensions)/ppx:project/ppx:types/ppx:pous/ppx:pou[@name=$type_name] | + exsl:node-set($extensions)/ppx:project/ppx:types/ppx:dataTypes/ppx:dataType[@name=$type_name]""", mode="var_type"; + } + } + value "ns:SetType($type_name)"; + } + + template "*[self::ppx:type or self::ppx:baseType or self::ppx:returnType]/ppx:array", mode="var_type" { + apply "ppx:baseType", mode="var_type"; + foreach "ppx:dimension" { + variable "lower" > «@lower» + variable "upper" > «@upper» + value "ns:AddDimension($lower, $upper)"; + } + } + + template "*[self::ppx:type or self::ppx:baseType or self::ppx:returnType]/ppx:string", mode="var_type" { + variable "name" > STRING + value "ns:SetType($name)"; + } + + template "*[self::ppx:type or self::ppx:baseType or self::ppx:returnType]/ppx:wstring", mode="var_type" { + variable "name" > WSTRING + value "ns:SetType($name)"; + } + + template "*[self::ppx:type or self::ppx:baseType or self::ppx:returnType]/*", mode="var_type" { + variable "name" > «local-name()» + value "ns:SetType($name)"; + } + + template "*[self::ppx:type or self::ppx:baseType or self::ppx:returnType]/ppx:derived", mode="var_edit" { + variable "type_name" > «@name» + variable "pou_infos" { + copy """exsl:node-set($project)/ppx:project/ppx:types/ppx:pous/ppx:pou[@name=$type_name] | + exsl:node-set($stdlib)/ppx:project/ppx:types/ppx:pous/ppx:pou[@name=$type_name] | + exsl:node-set($extensions)/ppx:project/ppx:types/ppx:pous/ppx:pou[@name=$type_name]"""; + } + choose { + when "$pou_infos != ''" > false + otherwise > true + } + } + + template "*[self::ppx:type or self::ppx:baseType or self::ppx:returnType]/*", mode="var_edit" { + > true + } + + template "ppx:value" { + choose { + when "@repetitionValue" { + > «@repetitionValue»( + apply; + > ) + } + when "@member" { + > «@member» := + apply; + } + otherwise { + apply; + } + } + } + + template "ppx:simpleValue" { + > «@value» + } + + function "complex_type_value" { + param "start_bracket"; + param "end_bracket"; + > «$start_bracket» + foreach "ppx:value" { + apply "."; + choose { + when "position()!=last()" > , + } + } + > «$end_bracket» + } + + template "ppx:arrayValue" { + call "complex_type_value" { + with "start_bracket" > [ + with "end_bracket" > ] + } + } + + template "ppx:structValue" { + call "complex_type_value" { + with "start_bracket" > ( + with "end_bracket" > ) + } + } + +} + + + \ No newline at end of file diff -r 72a826dfcfbb -r 02fe382c4511 py_ext/PythonFileCTNMixin.py --- a/py_ext/PythonFileCTNMixin.py Wed Jul 31 10:45:07 2013 +0900 +++ b/py_ext/PythonFileCTNMixin.py Mon Nov 18 12:12:31 2013 +0900 @@ -1,15 +1,11 @@ -import os -from PLCControler import UndoBuffer +import os, re +from lxml import etree + +from xmlclass import GenerateParserFromXSD + +from CodeFileTreeNode import CodeFile from PythonEditor import PythonEditor -from xml.dom import minidom -from xmlclass import GenerateClassesFromXSD -import cPickle - -from CodeFileTreeNode import CodeFile - -PythonClasses = GenerateClassesFromXSD(os.path.join(os.path.dirname(__file__), "py_ext_xsd.xsd")) - class PythonFileCTNMixin(CodeFile): CODEFILE_NAME = "PyFile" @@ -26,19 +22,35 @@ filepath = self.PythonFileName() - python_code = PythonClasses["Python"]() if os.path.isfile(filepath): + PythonParser = GenerateParserFromXSD( + os.path.join(os.path.dirname(__file__), "py_ext_xsd.xsd")) + xmlfile = open(filepath, 'r') - tree = minidom.parse(xmlfile) + pythonfile_xml = xmlfile.read() xmlfile.close() - for child in tree.childNodes: - if child.nodeType == tree.ELEMENT_NODE and child.nodeName == "Python": - python_code.loadXMLTree(child, ["xmlns", "xmlns:xsi", "xsi:schemaLocation"]) - self.CodeFile.globals.settext(python_code.gettext()) + pythonfile_xml = pythonfile_xml.replace( + 'xmlns="http://www.w3.org/2001/XMLSchema"', + 'xmlns:xhtml="http://www.w3.org/1999/xhtml"') + for cre, repl in [ + (re.compile("(?)(?:)(?!)"), "]]>")]: + pythonfile_xml = cre.sub(repl, pythonfile_xml) + + try: + python_code, error = PythonParser.LoadXMLString(pythonfile_xml) + if error is None: + self.CodeFile.globals.setanyText(python_code.getanyText()) os.remove(filepath) self.CreateCodeFileBuffer(False) self.OnCTNSave() + except Exception, exc: + error = unicode(exc) + + if error is not None: + self.GetCTRoot().logger.write_error( + _("Couldn't import old %s file.") % CTNName) def CodeFileName(self): return os.path.join(self.CTNPath(), "pyfile.xml") @@ -50,7 +62,7 @@ PostSectionsTexts = {} def GetSection(self,section): return self.PreSectionsTexts.get(section,"") + "\n" + \ - getattr(self.CodeFile, section).gettext() + "\n" + \ + getattr(self.CodeFile, section).getanyText() + "\n" + \ self.PostSectionsTexts.get(section,"") diff -r 72a826dfcfbb -r 02fe382c4511 py_ext/plc_python.c --- a/py_ext/plc_python.c Wed Jul 31 10:45:07 2013 +0900 +++ b/py_ext/plc_python.c Mon Nov 18 12:12:31 2013 +0900 @@ -163,7 +163,6 @@ LockPython(); /* Get current FB */ data__ = EvalFBs[Current_Python_EvalFB]; - *id=data__; if(data__ && /* may be null at first run */ __GET_VAR(data__->STATE) == PYTHON_FB_PROCESSING){ /* some answer awaited*/ /* If result not None */ @@ -209,6 +208,7 @@ __SET_VAR(data__->, BUFFER, 0, .body[__GET_VAR(data__->BUFFER, .len)]); /* next command is BUFFER */ next_command = (char*)__GET_VAR(data__->BUFFER, .body); + *id=data__; /* free python mutex */ UnLockPython(); /* return the next command to eval */ diff -r 72a826dfcfbb -r 02fe382c4511 py_ext/py_ext_xsd.xsd --- a/py_ext/py_ext_xsd.xsd Wed Jul 31 10:45:07 2013 +0900 +++ b/py_ext/py_ext_xsd.xsd Mon Nov 18 12:12:31 2013 +0900 @@ -1,18 +1,14 @@ - - + - - - Formatted text according to parts of XHTML 1.1 - - - - - - + + + Formatted text according to parts of XHTML 1.1 + + + + + + diff -r 72a826dfcfbb -r 02fe382c4511 runtime/PLCObject.py --- a/runtime/PLCObject.py Wed Jul 31 10:45:07 2013 +0900 +++ b/runtime/PLCObject.py Mon Nov 18 12:12:31 2013 +0900 @@ -329,7 +329,7 @@ if ccmd is None or ccmd!=cmd: AST = compile(cmd, '', 'eval') compile_cache[FBID]=(cmd,AST) - result,exp = self.evaluator(eval,cmd,self.python_runtime_vars) + result,exp = self.evaluator(eval,AST,self.python_runtime_vars) if exp is not None: res = "#EXCEPTION : "+str(exp[1]) self.LogMessage(1,('PyEval@0x%x(Code="%s") Exception "%s"')%(FBID,cmd, diff -r 72a826dfcfbb -r 02fe382c4511 targets/Xenomai/__init__.py --- a/targets/Xenomai/__init__.py Wed Jul 31 10:45:07 2013 +0900 +++ b/targets/Xenomai/__init__.py Mon Nov 18 12:12:31 2013 +0900 @@ -5,7 +5,7 @@ extension = ".so" def getXenoConfig(self, flagsname): """ Get xeno-config from target parameters """ - xeno_config=self.CTRInstance.GetTarget().getcontent()["value"].getXenoConfig() + xeno_config=self.CTRInstance.GetTarget().getcontent().getXenoConfig() if xeno_config: from util.ProcessLogger import ProcessLogger status, result, err_result = ProcessLogger(self.CTRInstance.logger, diff -r 72a826dfcfbb -r 02fe382c4511 targets/toolchain_gcc.py --- a/targets/toolchain_gcc.py Wed Jul 31 10:45:07 2013 +0900 +++ b/targets/toolchain_gcc.py Mon Nov 18 12:12:31 2013 +0900 @@ -19,14 +19,14 @@ """ Returns list of builder specific CFLAGS """ - return [self.CTRInstance.GetTarget().getcontent()["value"].getCFLAGS()] + return [self.CTRInstance.GetTarget().getcontent().getCFLAGS()] def getBuilderLDFLAGS(self): """ Returns list of builder specific LDFLAGS """ return self.CTRInstance.LDFLAGS + \ - [self.CTRInstance.GetTarget().getcontent()["value"].getLDFLAGS()] + [self.CTRInstance.GetTarget().getcontent().getLDFLAGS()] def GetBinaryCode(self): try: @@ -89,7 +89,7 @@ def build(self): # Retrieve toolchain user parameters - toolchain_params = self.CTRInstance.GetTarget().getcontent()["value"] + toolchain_params = self.CTRInstance.GetTarget().getcontent() self.compiler = toolchain_params.getCompiler() self.linker = toolchain_params.getLinker() diff -r 72a826dfcfbb -r 02fe382c4511 util/MiniTextControler.py --- a/util/MiniTextControler.py Wed Jul 31 10:45:07 2013 +0900 +++ b/util/MiniTextControler.py Mon Nov 18 12:12:31 2013 +0900 @@ -29,7 +29,7 @@ return text return "" - def GetEditedElementInterfaceVars(self, tagname, debug = False): + def GetEditedElementInterfaceVars(self, tagname, tree=False, debug = False): return [] def GetEditedElementType(self, tagname, debug = False): diff -r 72a826dfcfbb -r 02fe382c4511 xmlclass/__init__.py --- a/xmlclass/__init__.py Wed Jul 31 10:45:07 2013 +0900 +++ b/xmlclass/__init__.py Mon Nov 18 12:12:31 2013 +0900 @@ -24,5 +24,5 @@ # Package initialisation -from xmlclass import ClassFactory, GenerateClasses, GetAttributeValue, time_model, CreateNode, NodeSetAttr, NodeRenameAttr, UpdateXMLClassGlobals -from xsdschema import XSDClassFactory, GenerateClassesFromXSD, GenerateClassesFromXSDstring +from xmlclass import ClassFactory, GenerateParser, DefaultElementClass, GetAttributeValue, time_model, CreateNode, NodeSetAttr, NodeRenameAttr +from xsdschema import XSDClassFactory, GenerateParserFromXSD, GenerateParserFromXSDstring diff -r 72a826dfcfbb -r 02fe382c4511 xmlclass/xmlclass.py --- a/xmlclass/xmlclass.py Wed Jul 31 10:45:07 2013 +0900 +++ b/xmlclass/xmlclass.py Mon Nov 18 12:12:31 2013 +0900 @@ -28,7 +28,9 @@ from types import * from xml.dom import minidom from xml.sax.saxutils import escape, unescape, quoteattr +from lxml import etree from new import classobj +from collections import OrderedDict def CreateNode(name): node = minidom.Node() @@ -533,28 +535,33 @@ return GetModelNameList def GenerateAnyInfos(infos): + + def GetTextElement(tree): + if infos["namespace"][0] == "##any": + return tree.xpath("p")[0] + return tree.xpath("ns:p", namespaces={"ns": infos["namespace"][0]})[0] + def ExtractAny(tree): - if tree.nodeName in ["#text", "#cdata-section"]: - return unicode(unescape(tree.data)) - else: - return tree - - def GenerateAny(value, name=None, indent=0): - if isinstance(value, (StringType, UnicodeType)): - try: - value = value.decode("utf-8") - except: - pass - return u'\n' % value - else: - return value.toprettyxml(indent=" "*indent, encoding="utf-8") + return GetTextElement(tree).text + + def GenerateAny(tree, value): + GetTextElement(tree).text = etree.CDATA(value) + + def InitialAny(): + if infos["namespace"][0] == "##any": + element_name = "p" + else: + element_name = "{%s}p" % infos["namespace"][0] + p = etree.Element(element_name) + p.text = etree.CDATA("") + return p return { "type": COMPLEXTYPE, "extract": ExtractAny, "generate": GenerateAny, - "initial": lambda: "", - "check": lambda x: isinstance(x, (StringType, UnicodeType, minidom.Node)) + "initial": InitialAny, + "check": lambda x: isinstance(x, (StringType, UnicodeType, etree.ElementBase)) } def GenerateTagInfos(infos): @@ -591,38 +598,23 @@ def GetElementInitialValue(factory, infos): infos["elmt_type"] = FindTypeInfos(factory, infos["elmt_type"]) - if infos["minOccurs"] == 0 and infos["maxOccurs"] == 1: - if infos.has_key("default"): - return infos["elmt_type"]["extract"](infos["default"], False) - else: - return None - elif infos["minOccurs"] == 1 and infos["maxOccurs"] == 1: - return infos["elmt_type"]["initial"]() + if infos["minOccurs"] == 1: + element_name = factory.etreeNamespaceFormat % infos["name"] + if infos["elmt_type"]["type"] == SIMPLETYPE: + def initial_value(): + value = etree.Element(element_name) + value.text = (infos["elmt_type"]["generate"](infos["elmt_type"]["initial"]())) + return value + else: + def initial_value(): + value = infos["elmt_type"]["initial"]() + if infos["type"] != ANY: + DefaultElementClass.__setattr__(value, "tag", element_name) + value._init_() + return value + return [initial_value() for i in xrange(infos["minOccurs"])] else: - return [infos["elmt_type"]["initial"]() for i in xrange(infos["minOccurs"])] - -def HandleError(message, raise_exception): - if raise_exception: - raise ValueError(message) - return False - -def CheckElementValue(factory, name, infos, value, raise_exception=True): - infos["elmt_type"] = FindTypeInfos(factory, infos["elmt_type"]) - if value is None and raise_exception: - if not (infos["minOccurs"] == 0 and infos["maxOccurs"] == 1): - return HandleError("Attribute '%s' isn't optional." % name, raise_exception) - elif infos["maxOccurs"] == "unbounded" or infos["maxOccurs"] > 1: - if not isinstance(value, ListType): - return HandleError("Attribute '%s' must be a list." % name, raise_exception) - if len(value) < infos["minOccurs"] or infos["maxOccurs"] != "unbounded" and len(value) > infos["maxOccurs"]: - return HandleError("List out of bounds for attribute '%s'." % name, raise_exception) - if not reduce(lambda x, y: x and y, map(infos["elmt_type"]["check"], value), True): - return HandleError("Attribute '%s' must be a list of valid elements." % name, raise_exception) - elif infos.has_key("fixed") and value != infos["fixed"]: - return HandleError("Value of attribute '%s' can only be '%s'." % (name, str(infos["fixed"])), raise_exception) - else: - return infos["elmt_type"]["check"](value) - return True + return [] def GetContentInfos(name, choices): for choice_infos in choices: @@ -649,6 +641,7 @@ sequence_element["elmt_type"] = element_infos elif choice["elmt_type"] == "tag": choice["elmt_type"] = GenerateTagInfos(choice) + factory.AddToLookupClass(choice["name"], name, DefaultElementClass) else: choice_infos = factory.ExtractTypeInfos(choice["name"], name, choice["elmt_type"]) if choice_infos is not None: @@ -656,26 +649,6 @@ choices.append((choice["name"], choice)) return choices -def ExtractContentElement(factory, tree, infos, content): - infos["elmt_type"] = FindTypeInfos(factory, infos["elmt_type"]) - if infos["maxOccurs"] == "unbounded" or infos["maxOccurs"] > 1: - if isinstance(content, ListType) and len(content) > 0 and \ - content[-1]["name"] == tree.nodeName: - content_item = content.pop(-1) - content_item["value"].append(infos["elmt_type"]["extract"](tree)) - return content_item - elif not isinstance(content, ListType) and \ - content is not None and \ - content["name"] == tree.nodeName: - return {"name": tree.nodeName, - "value": content["value"] + [infos["elmt_type"]["extract"](tree)]} - else: - return {"name": tree.nodeName, - "value": [infos["elmt_type"]["extract"](tree)]} - else: - return {"name": tree.nodeName, - "value": infos["elmt_type"]["extract"](tree)} - def GenerateContentInfos(factory, name, choices): choices_dict = {} for choice_name, infos in choices: @@ -691,6 +664,9 @@ if choices_dict.has_key(choice_name): raise ValueError("'%s' element defined two times in choice" % choice_name) choices_dict[choice_name] = infos + prefix = ("%s:" % factory.TargetNamespace + if factory.TargetNamespace is not None else "") + choices_xpath = "|".join(map(lambda x: prefix + x, choices_dict.keys())) def GetContentInitial(): content_name, infos = choices[0] @@ -698,140 +674,15 @@ content_value = [] for i in xrange(infos["minOccurs"]): for element_infos in infos["elements"]: - value = GetElementInitialValue(factory, element_infos) - if value is not None: - if element_infos["type"] == CHOICE: - content_value.append(value) - else: - content_value.append({"name": element_infos["name"], "value": value}) + content_value.extend(GetElementInitialValue(factory, element_infos)) else: content_value = GetElementInitialValue(factory, infos) - return {"name": content_name, "value": content_value} - - def CheckContent(value): - if value["name"] != "sequence": - infos = choices_dict.get(value["name"], None) - if infos is not None: - return CheckElementValue(factory, value["name"], infos, value["value"], False) - elif len(value["value"]) > 0: - infos = choices_dict.get(value["value"][0]["name"], None) - if infos is None: - for choice_name, infos in choices: - if infos["type"] == "sequence": - for element_infos in infos["elements"]: - if element_infos["type"] == CHOICE: - infos = GetContentInfos(value["value"][0]["name"], element_infos["choices"]) - if infos is not None: - sequence_number = 0 - element_idx = 0 - while element_idx < len(value["value"]): - for element_infos in infos["elements"]: - element_value = None - if element_infos["type"] == CHOICE: - choice_infos = None - if element_idx < len(value["value"]): - for choice in element_infos["choices"]: - if choice["name"] == value["value"][element_idx]["name"]: - choice_infos = choice - element_value = value["value"][element_idx]["value"] - element_idx += 1 - break - if ((choice_infos is not None and - not CheckElementValue(factory, choice_infos["name"], choice_infos, element_value, False)) or - (choice_infos is None and element_infos["minOccurs"] > 0)): - raise ValueError("Invalid sequence value in attribute 'content'") - else: - if element_idx < len(value["value"]) and element_infos["name"] == value["value"][element_idx]["name"]: - element_value = value["value"][element_idx]["value"] - element_idx += 1 - if not CheckElementValue(factory, element_infos["name"], element_infos, element_value, False): - raise ValueError("Invalid sequence value in attribute 'content'") - sequence_number += 1 - if sequence_number < infos["minOccurs"] or infos["maxOccurs"] != "unbounded" and sequence_number > infos["maxOccurs"]: - raise ValueError("Invalid sequence value in attribute 'content'") - return True - else: - for element_name, infos in choices: - if element_name == "sequence": - required = 0 - for element in infos["elements"]: - if element["minOccurs"] > 0: - required += 1 - if required == 0: - return True - return False - - def ExtractContent(tree, content): - infos = choices_dict.get(tree.nodeName, None) - if infos is not None: - if infos["name"] == "sequence": - sequence_dict = dict([(element_infos["name"], element_infos) for element_infos in infos["elements"] if element_infos["type"] != CHOICE]) - element_infos = sequence_dict.get(tree.nodeName) - if content is not None and \ - content["name"] == "sequence" and \ - len(content["value"]) > 0 and \ - choices_dict.get(content["value"][-1]["name"]) == infos: - return {"name": "sequence", - "value": content["value"] + [ExtractContentElement(factory, tree, element_infos, content["value"][-1])]} - else: - return {"name": "sequence", - "value": [ExtractContentElement(factory, tree, element_infos, None)]} - else: - return ExtractContentElement(factory, tree, infos, content) - else: - for choice_name, infos in choices: - if infos["type"] == "sequence": - for element_infos in infos["elements"]: - if element_infos["type"] == CHOICE: - try: - if content is not None and \ - content["name"] == "sequence" and \ - len(content["value"]) > 0: - return {"name": "sequence", - "value": content["value"] + [element_infos["elmt_type"]["extract"](tree, content["value"][-1])]} - else: - return {"name": "sequence", - "value": [element_infos["elmt_type"]["extract"](tree, None)]} - except: - pass - raise ValueError("Invalid element \"%s\" for content!" % tree.nodeName) - - def GenerateContent(value, name=None, indent=0): - text = "" - if value["name"] != "sequence": - infos = choices_dict.get(value["name"], None) - if infos is not None: - infos["elmt_type"] = FindTypeInfos(factory, infos["elmt_type"]) - if infos["maxOccurs"] == "unbounded" or infos["maxOccurs"] > 1: - for item in value["value"]: - text += infos["elmt_type"]["generate"](item, value["name"], indent) - else: - text += infos["elmt_type"]["generate"](value["value"], value["name"], indent) - elif len(value["value"]) > 0: - infos = choices_dict.get(value["value"][0]["name"], None) - if infos is None: - for choice_name, infos in choices: - if infos["type"] == "sequence": - for element_infos in infos["elements"]: - if element_infos["type"] == CHOICE: - infos = GetContentInfos(value["value"][0]["name"], element_infos["choices"]) - if infos is not None: - sequence_dict = dict([(element_infos["name"], element_infos) for element_infos in infos["elements"]]) - for element_value in value["value"]: - element_infos = sequence_dict.get(element_value["name"]) - if element_infos["maxOccurs"] == "unbounded" or element_infos["maxOccurs"] > 1: - for item in element_value["value"]: - text += element_infos["elmt_type"]["generate"](item, element_value["name"], indent) - else: - text += element_infos["elmt_type"]["generate"](element_value["value"], element_infos["name"], indent) - return text + return content_value return { "type": COMPLEXTYPE, + "choices_xpath": etree.XPath(choices_xpath, namespaces=factory.NSMAP), "initial": GetContentInitial, - "check": CheckContent, - "extract": ExtractContent, - "generate": GenerateContent } #------------------------------------------------------------------------------- @@ -901,9 +752,11 @@ self.XMLClassDefinitions = {} self.DefinedNamespaces = {} + self.NSMAP = {} self.Namespaces = {} self.SchemaNamespace = None self.TargetNamespace = None + self.etreeNamespaceFormat = "%s" self.CurrentCompilations = [] @@ -914,6 +767,8 @@ else: self.ComputedClasses = {} self.ComputedClassesInfos = {} + self.ComputedClassesLookUp = {} + self.EquivalentClassesParent = {} self.AlreadyComputed = {} def GetQualifiedNameInfos(self, name, namespace=None, canbenone=False): @@ -1016,7 +871,9 @@ attrs[name] = infos["extract"]["default"](attr) elif namespace == "xmlns": infos = self.GetQualifiedNameInfos("anyURI", self.SchemaNamespace) - self.DefinedNamespaces[infos["extract"](attr)] = name + value = infos["extract"](attr) + self.DefinedNamespaces[value] = name + self.NSMAP[name] = value else: raise ValueError("Invalid attribute \"%s\" for member \"%s\"!" % (qualified_name, node.nodeName)) for attr in valid_attrs: @@ -1063,20 +920,63 @@ def ParseSchema(self): pass - + + def AddEquivalentClass(self, name, base): + if name != base: + equivalences = self.EquivalentClassesParent.setdefault(self.etreeNamespaceFormat % base, {}) + equivalences[self.etreeNamespaceFormat % name] = True + + def AddDistinctionBetweenParentsInLookupClass( + self, lookup_classes, parent, typeinfos): + parent = (self.etreeNamespaceFormat % parent + if parent is not None else None) + parent_class = lookup_classes.get(parent) + if parent_class is not None: + if isinstance(parent_class, ListType): + if typeinfos not in parent_class: + lookup_classes[parent].append(typeinfos) + elif parent_class != typeinfos: + lookup_classes[parent] = [parent_class, typeinfos] + else: + lookup_classes[parent] = typeinfos + + def AddToLookupClass(self, name, parent, typeinfos): + lookup_name = self.etreeNamespaceFormat % name + if isinstance(typeinfos, (StringType, UnicodeType)): + self.AddEquivalentClass(name, typeinfos) + typeinfos = self.etreeNamespaceFormat % typeinfos + lookup_classes = self.ComputedClassesLookUp.get(lookup_name) + if lookup_classes is None: + self.ComputedClassesLookUp[lookup_name] = (typeinfos, parent) + elif isinstance(lookup_classes, DictType): + self.AddDistinctionBetweenParentsInLookupClass( + lookup_classes, parent, typeinfos) + else: + lookup_classes = { + self.etreeNamespaceFormat % lookup_classes[1] + if lookup_classes[1] is not None else None: lookup_classes[0]} + self.AddDistinctionBetweenParentsInLookupClass( + lookup_classes, parent, typeinfos) + self.ComputedClassesLookUp[lookup_name] = lookup_classes + def ExtractTypeInfos(self, name, parent, typeinfos): if isinstance(typeinfos, (StringType, UnicodeType)): - namespace, name = DecomposeQualifiedName(typeinfos) - infos = self.GetQualifiedNameInfos(name, namespace) + namespace, type_name = DecomposeQualifiedName(typeinfos) + infos = self.GetQualifiedNameInfos(type_name, namespace) + if name != "base": + if infos["type"] == SIMPLETYPE: + self.AddToLookupClass(name, parent, DefaultElementClass) + elif namespace == self.TargetNamespace: + self.AddToLookupClass(name, parent, type_name) if infos["type"] == COMPLEXTYPE: - name, parent = self.SplitQualifiedName(name, namespace) - result = self.CreateClass(name, parent, infos) + type_name, parent = self.SplitQualifiedName(type_name, namespace) + result = self.CreateClass(type_name, parent, infos) if result is not None and not isinstance(result, (UnicodeType, StringType)): self.Namespaces[self.TargetNamespace][result["name"]] = result return result elif infos["type"] == ELEMENT and infos["elmt_type"]["type"] == COMPLEXTYPE: - name, parent = self.SplitQualifiedName(name, namespace) - result = self.CreateClass(name, parent, infos["elmt_type"]) + type_name, parent = self.SplitQualifiedName(type_name, namespace) + result = self.CreateClass(type_name, parent, infos["elmt_type"]) if result is not None and not isinstance(result, (UnicodeType, StringType)): self.Namespaces[self.TargetNamespace][result["name"]] = result return result @@ -1086,7 +986,12 @@ return self.CreateClass(name, parent, typeinfos) elif typeinfos["type"] == SIMPLETYPE: return typeinfos - + + def GetEquivalentParents(self, parent): + return reduce(lambda x, y: x + y, + [[p] + self.GetEquivalentParents(p) + for p in self.EquivalentClassesParent.get(parent, {}).keys()], []) + """ Methods that generates the classes """ @@ -1123,6 +1028,21 @@ if result is not None and \ not isinstance(result, (UnicodeType, StringType)): self.Namespaces[self.TargetNamespace][result["name"]] = result + + for name, parents in self.ComputedClassesLookUp.iteritems(): + if isinstance(parents, DictType): + computed_classes = parents.items() + elif parents[1] is not None: + computed_classes = [(self.etreeNamespaceFormat % parents[1], parents[0])] + else: + computed_classes = [] + for parent, computed_class in computed_classes: + for equivalent_parent in self.GetEquivalentParents(parent): + if not isinstance(parents, DictType): + parents = dict(computed_classes) + self.ComputedClassesLookUp[name] = parents + parents[equivalent_parent] = computed_class + return self.ComputedClasses def CreateClass(self, name, parent, classinfos, baseclass = False): @@ -1141,9 +1061,12 @@ bases = [] base_infos = classinfos.get("base", None) if base_infos is not None: + namespace, base_name = DecomposeQualifiedName(base_infos) + if namespace == self.TargetNamespace: + self.AddEquivalentClass(name, base_name) result = self.ExtractTypeInfos("base", name, base_infos) if result is None: - namespace, base_name = DecomposeQualifiedName(base_infos) + namespace, base_name = DecomposeQualifiedName(base_infos) if self.AlreadyComputed.get(base_name, False): self.ComputeAfter.append((name, parent, classinfos)) if self.TargetNamespace is not None: @@ -1164,7 +1087,7 @@ if classinfos["base"] is None: raise ValueError("No class found for base type") bases.append(classinfos["base"]) - bases.append(object) + bases.append(DefaultElementClass) bases = tuple(bases) classmembers = {"__doc__": classinfos.get("doc", ""), "IsBaseClass": baseclass} @@ -1177,11 +1100,8 @@ raise ValueError("\"%s\" type is not a simple type!" % attribute["attr_type"]) attrname = attribute["name"] if attribute["use"] == "optional": - classmembers[attrname] = None classmembers["add%s"%attrname] = generateAddMethod(attrname, self, attribute) classmembers["delete%s"%attrname] = generateDeleteMethod(attrname) - else: - classmembers[attrname] = infos["initial"]() classmembers["set%s"%attrname] = generateSetMethod(attrname) classmembers["get%s"%attrname] = generateGetMethod(attrname) else: @@ -1200,54 +1120,43 @@ classmembers["set%sbytype" % elmtname] = generateSetChoiceByTypeMethod(self, element["choices"]) infos = GenerateContentInfos(self, name, choices) elif element["type"] == ANY: - elmtname = element["name"] = "text" + elmtname = element["name"] = "anyText" element["minOccurs"] = element["maxOccurs"] = 1 infos = GenerateAnyInfos(element) else: elmtname = element["name"] if element["elmt_type"] == "tag": infos = GenerateTagInfos(element) + self.AddToLookupClass(element["name"], name, DefaultElementClass) else: infos = self.ExtractTypeInfos(element["name"], name, element["elmt_type"]) if infos is not None: element["elmt_type"] = infos if element["maxOccurs"] == "unbounded" or element["maxOccurs"] > 1: - classmembers[elmtname] = [] classmembers["append%s" % elmtname] = generateAppendMethod(elmtname, element["maxOccurs"], self, element) classmembers["insert%s" % elmtname] = generateInsertMethod(elmtname, element["maxOccurs"], self, element) classmembers["remove%s" % elmtname] = generateRemoveMethod(elmtname, element["minOccurs"]) classmembers["count%s" % elmtname] = generateCountMethod(elmtname) else: if element["minOccurs"] == 0: - classmembers[elmtname] = None classmembers["add%s" % elmtname] = generateAddMethod(elmtname, self, element) classmembers["delete%s" % elmtname] = generateDeleteMethod(elmtname) - elif not isinstance(element["elmt_type"], (UnicodeType, StringType)): - classmembers[elmtname] = element["elmt_type"]["initial"]() - else: - classmembers[elmtname] = None classmembers["set%s" % elmtname] = generateSetMethod(elmtname) classmembers["get%s" % elmtname] = generateGetMethod(elmtname) - classmembers["__init__"] = generateInitMethod(self, classinfos) - classmembers["getStructure"] = generateStructureMethod(classinfos) - classmembers["loadXMLTree"] = generateLoadXMLTree(self, classinfos) - classmembers["generateXMLText"] = generateGenerateXMLText(self, classinfos) + classmembers["_init_"] = generateInitMethod(self, classinfos) + classmembers["StructurePattern"] = GetStructurePattern(classinfos) classmembers["getElementAttributes"] = generateGetElementAttributes(self, classinfos) classmembers["getElementInfos"] = generateGetElementInfos(self, classinfos) classmembers["setElementValue"] = generateSetElementValue(self, classinfos) - classmembers["singleLineAttributes"] = True - classmembers["compatibility"] = lambda x, y: None - classmembers["extraAttrs"] = {} class_definition = classobj(str(classname), bases, classmembers) + setattr(class_definition, "__getattr__", generateGetattrMethod(self, class_definition, classinfos)) setattr(class_definition, "__setattr__", generateSetattrMethod(self, class_definition, classinfos)) class_infos = {"type": COMPILEDCOMPLEXTYPE, "name": classname, - "check": generateClassCheckFunction(class_definition), "initial": generateClassCreateFunction(class_definition), - "extract": generateClassExtractFunction(class_definition), - "generate": class_definition.generateXMLText} + } if self.FileName is not None: self.ComputedClasses[self.FileName][classname] = class_definition @@ -1255,6 +1164,9 @@ self.ComputedClasses[classname] = class_definition self.ComputedClassesInfos[classname] = class_infos + self.AddToLookupClass(name, parent, class_definition) + self.AddToLookupClass(classname, None, class_definition) + return class_infos """ @@ -1281,69 +1193,6 @@ print classname """ -Method that generate the method for checking a class instance -""" -def generateClassCheckFunction(class_definition): - def classCheckfunction(instance): - return isinstance(instance, class_definition) - return classCheckfunction - -""" -Method that generate the method for creating a class instance -""" -def generateClassCreateFunction(class_definition): - def classCreatefunction(): - return class_definition() - return classCreatefunction - -""" -Method that generate the method for extracting a class instance -""" -def generateClassExtractFunction(class_definition): - def classExtractfunction(node): - instance = class_definition() - instance.loadXMLTree(node) - return instance - return classExtractfunction - -""" -Method that generate the method for loading an xml tree by following the -attributes list defined -""" -def generateSetattrMethod(factory, class_definition, classinfos): - attributes = dict([(attr["name"], attr) for attr in classinfos["attributes"] if attr["use"] != "prohibited"]) - optional_attributes = dict([(attr["name"], True) for attr in classinfos["attributes"] if attr["use"] == "optional"]) - elements = dict([(element["name"], element) for element in classinfos["elements"]]) - - def setattrMethod(self, name, value): - if attributes.has_key(name): - attributes[name]["attr_type"] = FindTypeInfos(factory, attributes[name]["attr_type"]) - if value is None: - if optional_attributes.get(name, False): - return object.__setattr__(self, name, None) - else: - raise ValueError("Attribute '%s' isn't optional." % name) - elif attributes[name].has_key("fixed") and value != attributes[name]["fixed"]: - raise ValueError, "Value of attribute '%s' can only be '%s'."%(name, str(attributes[name]["fixed"])) - elif attributes[name]["attr_type"]["check"](value): - return object.__setattr__(self, name, value) - else: - raise ValueError("Invalid value for attribute '%s'." % (name)) - elif elements.has_key(name): - if CheckElementValue(factory, name, elements[name], value): - return object.__setattr__(self, name, value) - else: - raise ValueError("Invalid value for attribute '%s'." % (name)) - elif classinfos.has_key("base"): - return classinfos["base"].__setattr__(self, name, value) - elif class_definition.__dict__.has_key(name): - return object.__setattr__(self, name, value) - else: - raise AttributeError("'%s' can't have an attribute '%s'." % (self.__class__.__name__, name)) - - return setattrMethod - -""" Method that generate the method for generating the xml tree structure model by following the attributes list defined """ @@ -1369,7 +1218,10 @@ return "(?:%s){%d,%d}" % (name, infos["minOccurs"], infos["maxOccurs"]) -def GetStructure(classinfos): +def GetStructurePattern(classinfos): + base_structure_pattern = ( + classinfos["base"].StructurePattern.pattern[:-1] + if classinfos.has_key("base") else "") elements = [] for element in classinfos["elements"]: if element["type"] == ANY: @@ -1380,7 +1232,7 @@ choices = [] for infos in element["choices"]: if infos["type"] == "sequence": - structure = "(?:%s)" % GetStructure(infos) + structure = "(?:%s)" % GetStructurePattern(infos) else: structure = "%s " % infos["name"] choices.append(ComputeMultiplicity(structure, infos)) @@ -1390,170 +1242,139 @@ else: elements.append(ComputeMultiplicity("%s " % element["name"], element)) if classinfos.get("order", True) or len(elements) == 0: - return "".join(elements) + return re.compile(base_structure_pattern + "".join(elements) + "$") else: raise ValueError("XSD structure not yet supported!") -def generateStructureMethod(classinfos): - def getStructureMethod(self): - structure = GetStructure(classinfos) - if classinfos.has_key("base"): - return classinfos["base"].getStructure(self) + structure - return structure - return getStructureMethod - """ -Method that generate the method for loading an xml tree by following the -attributes list defined +Method that generate the method for creating a class instance """ -def generateLoadXMLTree(factory, classinfos): +def generateClassCreateFunction(class_definition): + def classCreatefunction(): + return class_definition() + return classCreatefunction + +def generateGetattrMethod(factory, class_definition, classinfos): attributes = dict([(attr["name"], attr) for attr in classinfos["attributes"] if attr["use"] != "prohibited"]) + optional_attributes = dict([(attr["name"], True) for attr in classinfos["attributes"] if attr["use"] == "optional"]) elements = dict([(element["name"], element) for element in classinfos["elements"]]) - def loadXMLTreeMethod(self, tree, extras=[], derived=False): - self.extraAttrs = {} - self.compatibility(tree) - if not derived: - children_structure = "" - for node in tree.childNodes: - if not (node.nodeName == "#text" and node.data.strip() == "") and node.nodeName != "#comment": - children_structure += "%s " % node.nodeName - structure_pattern = self.getStructure() - if structure_pattern != "": - structure_model = re.compile("(%s)$" % structure_pattern) - result = structure_model.match(children_structure) - if not result: - raise ValueError("Invalid structure for \"%s\" children!." % tree.nodeName) - required_attributes = dict([(attr["name"], True) for attr in classinfos["attributes"] if attr["use"] == "required"]) - if classinfos.has_key("base"): - extras.extend([attr["name"] for attr in classinfos["attributes"] if attr["use"] != "prohibited"]) - classinfos["base"].loadXMLTree(self, tree, extras, True) - for attrname, attr in tree._attrs.iteritems(): - if attributes.has_key(attrname): - attributes[attrname]["attr_type"] = FindTypeInfos(factory, attributes[attrname]["attr_type"]) - object.__setattr__(self, attrname, attributes[attrname]["attr_type"]["extract"](attr)) - elif not classinfos.has_key("base") and not attrname in extras and not self.extraAttrs.has_key(attrname): - self.extraAttrs[attrname] = GetAttributeValue(attr) - required_attributes.pop(attrname, None) - if len(required_attributes) > 0: - raise ValueError("Required attributes %s missing for \"%s\" element!" % (", ".join(["\"%s\""%name for name in required_attributes]), tree.nodeName)) - first = {} - for node in tree.childNodes: - name = node.nodeName - if name == "#text" and node.data.strip() == "" or name == "#comment": - continue - elif elements.has_key(name): - elements[name]["elmt_type"] = FindTypeInfos(factory, elements[name]["elmt_type"]) - if elements[name]["maxOccurs"] == "unbounded" or elements[name]["maxOccurs"] > 1: - if first.get(name, True): - object.__setattr__(self, name, [elements[name]["elmt_type"]["extract"](node)]) - first[name] = False + def getattrMethod(self, name): + if attributes.has_key(name): + attribute_infos = attributes[name] + attribute_infos["attr_type"] = FindTypeInfos(factory, attribute_infos["attr_type"]) + value = self.get(name) + if value is not None: + return attribute_infos["attr_type"]["extract"](value, extract=False) + elif attribute_infos.has_key("fixed"): + return attribute_infos["attr_type"]["extract"](attribute_infos["fixed"], extract=False) + elif attribute_infos.has_key("default"): + return attribute_infos["attr_type"]["extract"](attribute_infos["default"], extract=False) + return None + + elif elements.has_key(name): + element_infos = elements[name] + element_infos["elmt_type"] = FindTypeInfos(factory, element_infos["elmt_type"]) + if element_infos["type"] == CHOICE: + content = element_infos["elmt_type"]["choices_xpath"](self) + if element_infos["maxOccurs"] == "unbounded" or element_infos["maxOccurs"] > 1: + return content + elif len(content) > 0: + return content[0] + return None + elif element_infos["type"] == ANY: + return element_infos["elmt_type"]["extract"](self) + elif name == "content" and element_infos["elmt_type"]["type"] == SIMPLETYPE: + return element_infos["elmt_type"]["extract"](self.text, extract=False) + else: + element_name = factory.etreeNamespaceFormat % name + if element_infos["maxOccurs"] == "unbounded" or element_infos["maxOccurs"] > 1: + values = self.findall(element_name) + if element_infos["elmt_type"]["type"] == SIMPLETYPE: + return map(lambda value: + element_infos["elmt_type"]["extract"](value.text, extract=False), + values) + return values + else: + value = self.find(element_name) + if element_infos["elmt_type"]["type"] == SIMPLETYPE: + return element_infos["elmt_type"]["extract"](value.text, extract=False) + return value + + elif classinfos.has_key("base"): + return classinfos["base"].__getattr__(self, name) + + return DefaultElementClass.__getattribute__(self, name) + + return getattrMethod + +def generateSetattrMethod(factory, class_definition, classinfos): + attributes = dict([(attr["name"], attr) for attr in classinfos["attributes"] if attr["use"] != "prohibited"]) + optional_attributes = dict([(attr["name"], True) for attr in classinfos["attributes"] if attr["use"] == "optional"]) + elements = OrderedDict([(element["name"], element) for element in classinfos["elements"]]) + + def setattrMethod(self, name, value): + if attributes.has_key(name): + attribute_infos = attributes[name] + attribute_infos["attr_type"] = FindTypeInfos(factory, attribute_infos["attr_type"]) + if optional_attributes.get(name, False): + default = attribute_infos.get("default", None) + if value is None or value == default: + self.attrib.pop(name, None) + return + elif attribute_infos.has_key("fixed"): + return + return self.set(name, attribute_infos["attr_type"]["generate"](value)) + + elif elements.has_key(name): + element_infos = elements[name] + element_infos["elmt_type"] = FindTypeInfos(factory, element_infos["elmt_type"]) + if element_infos["type"] == ANY: + element_infos["elmt_type"]["generate"](self, value) + + elif name == "content" and element_infos["elmt_type"]["type"] == SIMPLETYPE: + self.text = element_infos["elmt_type"]["generate"](value) + + else: + prefix = ("%s:" % factory.TargetNamespace + if factory.TargetNamespace is not None else "") + element_xpath = (prefix + name + if name != "content" + else elements["content"]["elmt_type"]["choices_xpath"].path) + + for element in self.xpath(element_xpath, namespaces=factory.NSMAP): + self.remove(element) + + if value is not None: + element_idx = elements.keys().index(name) + if element_idx > 0: + previous_elements_xpath = "|".join(map( + lambda x: prefix + x + if x != "content" + else elements["content"]["elmt_type"]["choices_xpath"].path, + elements.keys()[:element_idx])) + + insertion_point = len(self.xpath(previous_elements_xpath, namespaces=factory.NSMAP)) else: - getattr(self, name).append(elements[name]["elmt_type"]["extract"](node)) - else: - object.__setattr__(self, name, elements[name]["elmt_type"]["extract"](node)) - elif elements.has_key("text"): - if elements["text"]["maxOccurs"] == "unbounded" or elements["text"]["maxOccurs"] > 1: - if first.get("text", True): - object.__setattr__(self, "text", [elements["text"]["elmt_type"]["extract"](node)]) - first["text"] = False - else: - getattr(self, "text").append(elements["text"]["elmt_type"]["extract"](node)) - else: - object.__setattr__(self, "text", elements["text"]["elmt_type"]["extract"](node)) - elif elements.has_key("content"): - if name in ["#cdata-section", "#text"]: - if elements["content"]["elmt_type"]["type"] == SIMPLETYPE: - object.__setattr__(self, "content", elements["content"]["elmt_type"]["extract"](node.data, False)) - else: - content = getattr(self, "content") - if elements["content"]["maxOccurs"] == "unbounded" or elements["content"]["maxOccurs"] > 1: - if first.get("content", True): - object.__setattr__(self, "content", [elements["content"]["elmt_type"]["extract"](node, None)]) - first["content"] = False - else: - content.append(elements["content"]["elmt_type"]["extract"](node, content)) - else: - object.__setattr__(self, "content", elements["content"]["elmt_type"]["extract"](node, content)) - return loadXMLTreeMethod - - -""" -Method that generates the method for generating an xml text by following the -attributes list defined -""" -def generateGenerateXMLText(factory, classinfos): - def generateXMLTextMethod(self, name, indent=0, extras={}, derived=False): - ind1, ind2 = getIndent(indent, name) - if not derived: - text = ind1 + u'<%s' % name - else: - text = u'' - - first = True - - if not classinfos.has_key("base"): - extras.update(self.extraAttrs) - for attr, value in extras.iteritems(): - if not first and not self.singleLineAttributes: - text += u'\n%s' % (ind2) - text += u' %s=%s' % (attr, quoteattr(value)) - first = False - extras.clear() - for attr in classinfos["attributes"]: - if attr["use"] != "prohibited": - attr["attr_type"] = FindTypeInfos(factory, attr["attr_type"]) - value = getattr(self, attr["name"], None) - if value != None: - computed_value = attr["attr_type"]["generate"](value) - else: - computed_value = None - if attr["use"] != "optional" or (value != None and \ - computed_value != attr.get("default", attr["attr_type"]["generate"](attr["attr_type"]["initial"]()))): - if classinfos.has_key("base"): - extras[attr["name"]] = computed_value - else: - if not first and not self.singleLineAttributes: - text += u'\n%s' % (ind2) - text += ' %s=%s' % (attr["name"], quoteattr(computed_value)) - first = False - if classinfos.has_key("base"): - first, new_text = classinfos["base"].generateXMLText(self, name, indent, extras, True) - text += new_text - else: - first = True - for element in classinfos["elements"]: - element["elmt_type"] = FindTypeInfos(factory, element["elmt_type"]) - value = getattr(self, element["name"], None) - if element["minOccurs"] == 0 and element["maxOccurs"] == 1: - if value is not None: - if first: - text += u'>\n' - first = False - text += element["elmt_type"]["generate"](value, element["name"], indent + 1) - elif element["minOccurs"] == 1 and element["maxOccurs"] == 1: - if first: - text += u'>\n' - first = False - if element["name"] == "content" and element["elmt_type"]["type"] == SIMPLETYPE: - text += element["elmt_type"]["generate"](value) - else: - text += element["elmt_type"]["generate"](value, element["name"], indent + 1) - else: - if first and len(value) > 0: - text += u'>\n' - first = False - for item in value: - text += element["elmt_type"]["generate"](item, element["name"], indent + 1) - if not derived: - if first: - text += u'/>\n' - else: - text += ind1 + u'\n' % (name) - return text - else: - return first, text - return generateXMLTextMethod + insertion_point = 0 + + if not isinstance(value, ListType): + value = [value] + + for element in reversed(value): + if element_infos["elmt_type"]["type"] == SIMPLETYPE: + tmp_element = etree.Element(factory.etreeNamespaceFormat % name) + tmp_element.text = element_infos["elmt_type"]["generate"](element) + element = tmp_element + self.insert(insertion_point, element) + + elif classinfos.has_key("base"): + return classinfos["base"].__setattr__(self, name, value) + + else: + raise AttributeError("'%s' can't have an attribute '%s'." % (self.__class__.__name__, name)) + + return setattrMethod def gettypeinfos(name, facets): if facets.has_key("enumeration") and facets["enumeration"][0] is not None: @@ -1611,7 +1432,7 @@ elements[parts[0]]["elmt_type"]["facets"]) value = getattr(self, parts[0], "") elif parts[0] == "content": - return self.content["value"].getElementInfos(self.content["name"], path) + return self.content.getElementInfos(self.content.getLocalTag(), path) else: attr = getattr(self, parts[0], None) if attr is None: @@ -1622,7 +1443,7 @@ return attr.getElementInfos(parts[0], parts[1]) elif elements.has_key("content"): if len(parts) > 0: - return self.content["value"].getElementInfos(name, path) + return self.content.getElementInfos(name, path) elif classinfos.has_key("base"): classinfos["base"].getElementInfos(name, path) else: @@ -1640,15 +1461,9 @@ if self.content is None: value = "" else: - value = self.content["name"] - if self.content["value"] is not None: - if self.content["name"] == "sequence": - choices_dict = dict([(choice["name"], choice) for choice in element["choices"]]) - sequence_infos = choices_dict.get("sequence", None) - if sequence_infos is not None: - children.extend([item.getElementInfos(infos["name"]) for item, infos in zip(self.content["value"], sequence_infos["elements"])]) - else: - children.extend(self.content["value"].getElementInfos(self.content["name"])["children"]) + value = self.content.getLocalTag() + if self.content is not None: + children.extend(self.content.getElementInfos(value)["children"]) elif element["elmt_type"]["type"] == SIMPLETYPE: children.append({"name": element_name, "require": element["minOccurs"] != 0, "type": gettypeinfos(element["elmt_type"]["basename"], @@ -1705,13 +1520,13 @@ instance.setElementValue(None, value) elif elements.has_key("content"): if len(parts) > 0: - self.content["value"].setElementValue(path, value) + self.content.setElementValue(path, value) elif classinfos.has_key("base"): classinfos["base"].setElementValue(self, path, value) elif elements.has_key("content"): if value == "": if elements["content"]["minOccurs"] == 0: - self.setcontent(None) + self.setcontent([]) else: raise ValueError("\"content\" element is required!") else: @@ -1723,20 +1538,21 @@ """ def generateInitMethod(factory, classinfos): def initMethod(self): - self.extraAttrs = {} if classinfos.has_key("base"): - classinfos["base"].__init__(self) + classinfos["base"]._init_(self) for attribute in classinfos["attributes"]: attribute["attr_type"] = FindTypeInfos(factory, attribute["attr_type"]) if attribute["use"] == "required": - setattr(self, attribute["name"], attribute["attr_type"]["initial"]()) - elif attribute["use"] == "optional": - if attribute.has_key("default"): - setattr(self, attribute["name"], attribute["attr_type"]["extract"](attribute["default"], False)) - else: - setattr(self, attribute["name"], None) + self.set(attribute["name"], attribute["attr_type"]["generate"](attribute["attr_type"]["initial"]())) for element in classinfos["elements"]: - setattr(self, element["name"], GetElementInitialValue(factory, element)) + if element["type"] != CHOICE: + element_name = ( + etree.QName(factory.NSMAP["xhtml"], "p") + if element["type"] == ANY + else factory.etreeNamespaceFormat % element["name"]) + initial = GetElementInitialValue(factory, element) + if initial is not None: + map(self.append, initial) return initMethod def generateSetMethod(attr): @@ -1753,18 +1569,16 @@ def addMethod(self): if infos["type"] == ATTRIBUTE: infos["attr_type"] = FindTypeInfos(factory, infos["attr_type"]) - initial = infos["attr_type"]["initial"] - extract = infos["attr_type"]["extract"] + if not infos.has_key("default"): + setattr(self, attr, infos["attr_type"]["initial"]()) elif infos["type"] == ELEMENT: infos["elmt_type"] = FindTypeInfos(factory, infos["elmt_type"]) - initial = infos["elmt_type"]["initial"] - extract = infos["elmt_type"]["extract"] + value = infos["elmt_type"]["initial"]() + DefaultElementClass.__setattr__(value, "tag", factory.etreeNamespaceFormat % attr) + setattr(self, attr, value) + value._init_() else: raise ValueError("Invalid class attribute!") - if infos.has_key("default"): - setattr(self, attr, extract(infos["default"], False)) - else: - setattr(self, attr, initial()) return addMethod def generateDeleteMethod(attr): @@ -1777,10 +1591,10 @@ infos["elmt_type"] = FindTypeInfos(factory, infos["elmt_type"]) attr_list = getattr(self, attr) if maxOccurs == "unbounded" or len(attr_list) < maxOccurs: - if infos["elmt_type"]["check"](value): - attr_list.append(value) + if len(attr_list) == 0: + setattr(self, attr, [value]) else: - raise ValueError("\"%s\" value isn't valid!" % attr) + attr_list[-1].addnext(value) else: raise ValueError("There can't be more than %d values in \"%s\"!" % (maxOccurs, attr)) return appendMethod @@ -1790,10 +1604,12 @@ infos["elmt_type"] = FindTypeInfos(factory, infos["elmt_type"]) attr_list = getattr(self, attr) if maxOccurs == "unbounded" or len(attr_list) < maxOccurs: - if infos["elmt_type"]["check"](value): - attr_list.insert(index, value) + if len(attr_list) == 0: + setattr(self, attr, [value]) + elif index == 0: + attr_list[0].addprevious(value) else: - raise ValueError("\"%s\" value isn't valid!" % attr) + attr_list[min(index - 1, len(attr_list) - 1)].addnext(value) else: raise ValueError("There can't be more than %d values in \"%s\"!" % (maxOccurs, attr)) return insertMethod @@ -1805,24 +1621,26 @@ def generateSetChoiceByTypeMethod(factory, choice_types): choices = dict([(choice["name"], choice) for choice in choice_types]) - def setChoiceMethod(self, type): - if not choices.has_key(type): - raise ValueError("Unknown \"%s\" choice type for \"content\"!" % type) - choices[type]["elmt_type"] = FindTypeInfos(factory, choices[type]["elmt_type"]) - new_element = choices[type]["elmt_type"]["initial"]() - self.content = {"name": type, "value": new_element} - return new_element + def setChoiceMethod(self, content_type): + if not choices.has_key(content_type): + raise ValueError("Unknown \"%s\" choice type for \"content\"!" % content_type) + choices[content_type]["elmt_type"] = FindTypeInfos(factory, choices[content_type]["elmt_type"]) + new_content = choices[content_type]["elmt_type"]["initial"]() + DefaultElementClass.__setattr__(new_content, "tag", factory.etreeNamespaceFormat % content_type) + self.content = new_content + return new_content return setChoiceMethod def generateAppendChoiceByTypeMethod(maxOccurs, factory, choice_types): choices = dict([(choice["name"], choice) for choice in choice_types]) - def appendChoiceMethod(self, type): - if not choices.has_key(type): - raise ValueError("Unknown \"%s\" choice type for \"content\"!" % type) - choices[type]["elmt_type"] = FindTypeInfos(factory, choices[type]["elmt_type"]) + def appendChoiceMethod(self, content_type): + if not choices.has_key(content_type): + raise ValueError("Unknown \"%s\" choice type for \"content\"!" % content_type) + choices[content_type]["elmt_type"] = FindTypeInfos(factory, choices[content_type]["elmt_type"]) if maxOccurs == "unbounded" or len(self.content) < maxOccurs: - new_element = choices[type]["elmt_type"]["initial"]() - self.content.append({"name": type, "value": new_element}) + new_element = choices[content_type]["elmt_type"]["initial"]() + DefaultElementClass.__setattr__(new_element, "tag", factory.etreeNamespaceFormat % content_type) + self.appendcontent(new_element) return new_element else: raise ValueError("There can't be more than %d values in \"content\"!" % maxOccurs) @@ -1830,13 +1648,14 @@ def generateInsertChoiceByTypeMethod(maxOccurs, factory, choice_types): choices = dict([(choice["name"], choice) for choice in choice_types]) - def insertChoiceMethod(self, index, type): - if not choices.has_key(type): - raise ValueError("Unknown \"%s\" choice type for \"content\"!" % type) - choices[type]["elmt_type"] = FindTypeInfos(factory, choices[type]["elmt_type"]) + def insertChoiceMethod(self, index, content_type): + if not choices.has_key(content_type): + raise ValueError("Unknown \"%s\" choice type for \"content\"!" % content_type) + choices[type]["elmt_type"] = FindTypeInfos(factory, choices[content_type]["elmt_type"]) if maxOccurs == "unbounded" or len(self.content) < maxOccurs: - new_element = choices[type]["elmt_type"]["initial"]() - self.content.insert(index, {"name" : type, "value" : new_element}) + new_element = choices[content_type]["elmt_type"]["initial"]() + DefaultElementClass.__setattr__(new_element, "tag", factory.etreeNamespaceFormat % content_type) + self.insertcontent(index, new_element) return new_element else: raise ValueError("There can't be more than %d values in \"content\"!" % maxOccurs) @@ -1846,7 +1665,7 @@ def removeMethod(self, index): attr_list = getattr(self, attr) if len(attr_list) > minOccurs: - getattr(self, attr).pop(index) + self.remove(attr_list[index]) else: raise ValueError("There can't be less than %d values in \"%s\"!" % (minOccurs, attr)) return removeMethod @@ -1857,16 +1676,135 @@ return countMethod """ -This function generate the classes from a class factory +This function generate a xml parser from a class factory """ -def GenerateClasses(factory): + +NAMESPACE_PATTERN = re.compile("xmlns(?:\:[^\=]*)?=\"[^\"]*\" ") + +class DefaultElementClass(etree.ElementBase): + + StructurePattern = re.compile("$") + + def _init_(self): + pass + + def getLocalTag(self): + return etree.QName(self.tag).localname + + def tostring(self): + return NAMESPACE_PATTERN.sub("", etree.tostring(self, pretty_print=True)) + +class XMLElementClassLookUp(etree.PythonElementClassLookup): + + def __init__(self, classes, *args, **kwargs): + etree.PythonElementClassLookup.__init__(self, *args, **kwargs) + self.LookUpClasses = classes + + def GetElementClass(self, element_tag, parent_tag=None, default=DefaultElementClass): + element_class = self.LookUpClasses.get(element_tag, (default, None)) + if not isinstance(element_class, DictType): + if isinstance(element_class[0], (StringType, UnicodeType)): + return self.GetElementClass(element_class[0], default=default) + return element_class[0] + + element_with_parent_class = element_class.get(parent_tag, default) + if isinstance(element_with_parent_class, (StringType, UnicodeType)): + return self.GetElementClass(element_with_parent_class, default=default) + return element_with_parent_class + + def lookup(self, document, element): + parent = element.getparent() + element_class = self.GetElementClass(element.tag, + parent.tag if parent is not None else None) + if isinstance(element_class, ListType): + children = "".join([ + "%s " % etree.QName(child.tag).localname + for child in element]) + for possible_class in element_class: + if isinstance(possible_class, (StringType, UnicodeType)): + possible_class = self.GetElementClass(possible_class) + if possible_class.StructurePattern.match(children) is not None: + return possible_class + return element_class[0] + return element_class + +class XMLClassParser(etree.XMLParser): + + def __init__(self, namespaces, default_namespace_format, base_class, xsd_schema, *args, **kwargs): + etree.XMLParser.__init__(self, *args, **kwargs) + self.DefaultNamespaceFormat = default_namespace_format + self.NSMAP = namespaces + targetNamespace = etree.QName(default_namespace_format % "d").namespace + if targetNamespace is not None: + self.RootNSMAP = { + name if targetNamespace != uri else None: uri + for name, uri in namespaces.iteritems()} + else: + self.RootNSMAP = namespaces + self.BaseClass = base_class + self.XSDSchema = xsd_schema + + def set_element_class_lookup(self, class_lookup): + etree.XMLParser.set_element_class_lookup(self, class_lookup) + self.ClassLookup = class_lookup + + def LoadXMLString(self, xml_string): + tree = etree.fromstring(xml_string, self) + if not self.XSDSchema.validate(tree): + error = self.XSDSchema.error_log.last_error + return tree, (error.line, error.message) + return tree, None + + def Dumps(self, xml_obj): + return etree.tostring(xml_obj) + + def Loads(self, xml_string): + return etree.fromstring(xml_string, self) + + def CreateRoot(self): + if self.BaseClass is not None: + root = self.makeelement( + self.DefaultNamespaceFormat % self.BaseClass[0], + nsmap=self.RootNSMAP) + root._init_() + return root + return None + + def GetElementClass(self, element_tag, parent_tag=None): + return self.ClassLookup.GetElementClass( + self.DefaultNamespaceFormat % element_tag, + self.DefaultNamespaceFormat % parent_tag + if parent_tag is not None else parent_tag, + None) + + def CreateElement(self, element_tag, parent_tag=None, class_idx=None): + element_class = self.GetElementClass(element_tag, parent_tag) + if isinstance(element_class, ListType): + if class_idx is not None and class_idx < len(element_class): + new_element = element_class[class_idx]() + else: + raise ValueError, "No corresponding class found!" + else: + new_element = element_class() + DefaultElementClass.__setattr__(new_element, "tag", self.DefaultNamespaceFormat % element_tag) + new_element._init_() + return new_element + +def GenerateParser(factory, xsdstring): ComputedClasses = factory.CreateClasses() - if factory.FileName is not None and len(ComputedClasses) == 1: - UpdateXMLClassGlobals(ComputedClasses[factory.FileName]) - return ComputedClasses[factory.FileName] - else: - UpdateXMLClassGlobals(ComputedClasses) - return ComputedClasses - -def UpdateXMLClassGlobals(classes): - globals().update(classes) + + if factory.FileName is not None: + ComputedClasses = ComputedClasses[factory.FileName] + BaseClass = [(name, XSDclass) for name, XSDclass in ComputedClasses.items() if XSDclass.IsBaseClass] + + parser = XMLClassParser( + factory.NSMAP, + factory.etreeNamespaceFormat, + BaseClass[0] if len(BaseClass) == 1 else None, + etree.XMLSchema(etree.fromstring(xsdstring)), + strip_cdata = False, remove_blank_text=True) + class_lookup = XMLElementClassLookUp(factory.ComputedClassesLookUp) + parser.set_element_class_lookup(class_lookup) + + return parser + diff -r 72a826dfcfbb -r 02fe382c4511 xmlclass/xsdschema.py --- a/xmlclass/xsdschema.py Wed Jul 31 10:45:07 2013 +0900 +++ b/xmlclass/xsdschema.py Mon Nov 18 12:12:31 2013 +0900 @@ -44,16 +44,20 @@ return text return generateXMLTextMethod -def GenerateFloatXMLText(extra_values=[]): +def GenerateFloatXMLText(extra_values=[], decimal=None): + float_format = (lambda x: "{:.{width}f}".format(x, width=decimal).rstrip('0') + if decimal is not None else str) def generateXMLTextMethod(value, name=None, indent=0): text = "" if name is not None: ind1, ind2 = getIndent(indent, name) text += ind1 + "<%s>" % name - if value in extra_values or value % 1 != 0 or isinstance(value, IntType): + if isinstance(value, IntType): text += str(value) + elif value in extra_values or value % 1 != 0: + text += float_format(value) else: - text += "%.0f" % value + text += "{:.0f}".format(value) if name is not None: text += "\n" % name return text @@ -924,6 +928,8 @@ else: factory.Namespaces[include_factory.TargetNamespace] = include_factory.Namespaces[include_factory.TargetNamespace] factory.ComputedClasses.update(include_factory.ComputedClasses) + factory.ComputedClassesLookUp.update(include_factory.ComputedClassesLookUp) + factory.EquivalentClassesParent.update(include_factory.EquivalentClassesParent) return None def ReduceRedefine(factory, attributes, elements): @@ -939,8 +945,10 @@ factory.BlockDefault = attributes["blockDefault"] factory.FinalDefault = attributes["finalDefault"] - if attributes.has_key("targetNamespace"): - factory.TargetNamespace = factory.DefinedNamespaces.get(attributes["targetNamespace"], None) + targetNamespace = attributes.get("targetNamespace", None) + factory.TargetNamespace = factory.DefinedNamespaces.get(targetNamespace, None) + if factory.TargetNamespace is not None: + factory.etreeNamespaceFormat = "{%s}%%s" % targetNamespace factory.Namespaces[factory.TargetNamespace] = {} annotations, children = factory.ReduceElements(elements, True) @@ -1030,15 +1038,14 @@ schema = child break for qualified_name, attr in schema._attrs.items(): - value = GetAttributeValue(attr) - if value == "http://www.w3.org/2001/XMLSchema": - namespace, name = DecomposeQualifiedName(qualified_name) - if namespace == "xmlns": - self.DefinedNamespaces["http://www.w3.org/2001/XMLSchema"] = name + namespace, name = DecomposeQualifiedName(qualified_name) + if namespace == "xmlns": + value = GetAttributeValue(attr) + self.DefinedNamespaces[value] = name + self.NSMAP[name] = value + if value == "http://www.w3.org/2001/XMLSchema": self.SchemaNamespace = name - else: - self.DefinedNamespaces["http://www.w3.org/2001/XMLSchema"] = self.SchemaNamespace - self.Namespaces[self.SchemaNamespace] = XSD_NAMESPACE + self.Namespaces[self.SchemaNamespace] = XSD_NAMESPACE self.Schema = XSD_NAMESPACE["schema"]["extract"]["default"](self, schema) ReduceSchema(self, self.Schema[1], self.Schema[2]) @@ -1084,19 +1091,24 @@ return None """ -This function opens the xsd file and generate the classes from the xml tree +This function opens the xsd file and generate a xml parser with class lookup from +the xml tree """ -def GenerateClassesFromXSD(filepath): +def GenerateParserFromXSD(filepath): xsdfile = open(filepath, 'r') - factory = XSDClassFactory(minidom.parse(xsdfile), filepath) + xsdstring = xsdfile.read() xsdfile.close() - return GenerateClasses(factory) + cwd = os.getcwd() + os.chdir(os.path.dirname(filepath)) + parser = GenerateParser(XSDClassFactory(minidom.parseString(xsdstring), filepath), xsdstring) + os.chdir(cwd) + return parser """ -This function generate the classes from the xsd given as a string +This function generate a xml from the xsd given as a string """ -def GenerateClassesFromXSDstring(xsdstring): - return GenerateClasses(XSDClassFactory(minidom.parseString(xsdstring))) +def GenerateParserFromXSDstring(xsdstring): + return GenerateParser(XSDClassFactory(minidom.parseString(xsdstring)), xsdstring) #------------------------------------------------------------------------------- @@ -2261,7 +2273,7 @@ "basename": "decimal", "extract": GenerateFloatExtraction("decimal"), "facets": DECIMAL_FACETS, - "generate": GenerateFloatXMLText(), + "generate": GenerateFloatXMLText(decimal=3), "initial": lambda: 0., "check": lambda x: isinstance(x, (IntType, FloatType)) }, @@ -2520,19 +2532,3 @@ "anyType": {"type": COMPLEXTYPE, "extract": lambda x:None}, } -if __name__ == '__main__': - classes = GenerateClassesFromXSD("test.xsd") - - # Code for test of test.xsd - xmlfile = open("po.xml", 'r') - tree = minidom.parse(xmlfile) - xmlfile.close() - test = classes["PurchaseOrderType"]() - for child in tree.childNodes: - if child.nodeType == tree.ELEMENT_NODE and child.nodeName == "purchaseOrder": - test.loadXMLTree(child) - test.items.item[0].setquantity(2) - testfile = open("test.xml", 'w') - testfile.write(u'\n') - testfile.write(test.generateXMLText("purchaseOrder").encode("utf-8")) - testfile.close()