--- 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
+from copy import deepcopy from time import localtime
+from collections import OrderedDict, namedtuple -from plcopen import plcopen
-from plcopen.structures import *
from graphics.GraphicCommons import *
from PLCGenerator import *
@@ -66,14 +67,14 @@
-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)
+ "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 + 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)) + 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 + 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 "") + return _VariableInfos(*[getattr(self, attr) for attr in self.__slots__]) +class VariablesInfosFactory: + def __init__(self, variables): + self.Variables = variables + def SetType(self, context, *args): + if len(self.Dimensions) > 0: + return ("array", self.Type, self.Dimensions) + 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([]) + 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): + "configuration": ITEM_CONFIGURATION, + "resource": ITEM_RESOURCE, + "transition": ITEM_TRANSITION, + "program": ITEM_PROGRAM}.get(value) + if class_type is not None: + pou_type = POU_TYPES.get(value) + if pou_type is not None: + var_type = VAR_CLASS_INFOS.get(value) + if var_type is not 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 "") + return _VariableTreeItem(*[getattr(self, attr) for attr in self.__slots__]) +class VariablesTreeInfosFactory: + def SetRoot(self, context, *args): + self.Root = _VariablesTreeItemInfos( + *([''] + _translate_args( + [class_extraction, str] + [_BoolValue] * 2, + def AddVariable(self, context, *args): + if self.Root is not None: + self.Root.variables.append(_VariablesTreeItemInfos( + [str, class_extraction, str] + [_BoolValue] * 2, +#------------------------------------------------------------------------------- +# 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 +#------------------------------------------------------------------------------- + def __init__(self, controller): + self.Controller = controller + 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"]), +_VariableSpecificValues = ( + namedtuple("VariableSpecificValues", + ["name", "value_type", "execution_order"]), +_ConnectionSpecificValues = ( + namedtuple("ConnectionSpecificValues", ["name"]), +_PowerRailSpecificValues = ( + namedtuple("PowerRailSpecificValues", ["connectors"]), +_LDElementSpecificValues = ( + namedtuple("LDElementSpecificValues", + ["name", "negated", "edge", "storage", "execution_order"]), + [str, _BoolValue, str, str, int]) +_DivergenceSpecificValues = ( + namedtuple("DivergenceSpecificValues", ["connectors"]), +_SpecificValuesTuples = { + namedtuple("CommentSpecificValues", ["content"]), + "input": _VariableSpecificValues, + "output": _VariableSpecificValues, + "inout": _VariableSpecificValues, + "connector": _ConnectionSpecificValues, + "continuation": _ConnectionSpecificValues, + "leftPowerRail": _PowerRailSpecificValues, + "rightPowerRail": _PowerRailSpecificValues, + "contact": _LDElementSpecificValues, + "coil": _LDElementSpecificValues, + namedtuple("StepSpecificValues", ["name", "initial", "action"]), + [str, _BoolValue, lambda x: x]), + namedtuple("TransitionSpecificValues", + ["priority", "condition_type", "condition", "connection"]), + [int, str, str, lambda x: x]), + "selectionDivergence": _DivergenceSpecificValues, + "selectionConvergence": _DivergenceSpecificValues, + "simultaneousDivergence": _DivergenceSpecificValues, + "simultaneousConvergence": _DivergenceSpecificValues, + namedtuple("JumpSpecificValues", ["target"]), + namedtuple("ActionBlockSpecificValues", ["actions"]), +_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 "") + 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) + self.CurrentInstance.outputs.append(self.CurrentConnection) + 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.TotalTypesDict = StdBlckDct.copy() + self.TotalTypes = StdBlckLst[:] self.ProgramFilePath = ""
def GetQualifierTypes(self):
- return plcopen.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):
- self.Project = plcopen.project()
+ self.Project = PLCOpenParser.CreateRoot() properties["creationDateTime"] = datetime.datetime(*localtime()[:6])
self.Project.setfileHeader(properties)
self.Project.setcontentHeader(properties)
# Initialize the project buffer
self.CreateProjectBuffer(False)
@@ -273,7 +603,7 @@
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 @@
- 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 = project.getpou(var_type)
- pou_type = pou.getpouType()
- edit = debug = pou_type is not 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:
- 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(),
- elif var_type in self.GetDataTypes(debug = debug):
- return {"name": variable.getname(),
- elif vartype_content["name"] in ["string", "wstring"]:
- return {"name": variable.getname(),
- "type": vartype_content["name"].upper(),
- return {"name": variable.getname(),
- "type": vartype_content["name"],
def GetPouVariables(self, tagname, debug = False):
project = self.GetProject(debug)
+ factory = VariablesTreeInfosFactory() + parser = etree.XMLParser() + parser.resolvers.add(LibraryResolver(self, debug)) + pou_variable_xslt_tree = etree.XSLT( + os.path.join(ScriptDirectory, "plcopen", "pou_variables.xslt"), + extensions = {("pou_vars_ns", name): getattr(factory, name) + for name in ["SetRoot", "AddVariable"]}) words = tagname.split("::")
- pou = project.getpou(words[1])
- 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]
- 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:
- if pou.getbodyType() == "SFC":
- for transition in pou.gettransitionList():
- "name": transition.getname(),
- "class": ITEM_TRANSITION,
- for action in pou.getactionList():
- "name": action.getname(),
- return {"class": POU_TYPES[pou_type],
- 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,
- "class" : ITEM_VAR_INPUT,
- for varname, vartype, varmodifier in block_infos["outputs"]:
- vars.append({"name" : varname,
- "class" : ITEM_VAR_OUTPUT,
- return {"class": POU_TYPES[block_infos["type"]],
- elif words[0] in ['A', 'T']:
- pou_vars = self.GetPouVariables(self.ComputePouName(words[1]), debug)
- if pou_vars is not None:
- element_type = ITEM_ACTION
- element_type = ITEM_TRANSITION
- return {"class": element_type,
- "variables": [var for var in pou_vars["variables"]
- if var["class"] not in [ITEM_ACTION, ITEM_TRANSITION]],
- elif words[0] in ['C', 'R']:
- element_type = ITEM_CONFIGURATION
- element = project.getconfiguration(words[1])
- if element is not None:
- for resource in element.getresource():
- vars.append({"name": resource.getname(),
- "class": ITEM_RESOURCE,
- 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(),
- for pou in element.getpouInstance():
- vars.append({"name": pou.getname(),
- "type": pou.gettypeName(),
- 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:
- return {"class": element_type,
+ obj = self.GetPou(words[1], debug) + obj = self.GetEditedElement(tagname, debug) + pou_variable_xslt_tree(obj) + return factory.GetRoot() - def RecursiveSearchPouInstances(self, project, pou_type, parent_path, varlists, debug = False):
+ def GetInstanceList(self, root, name, debug = False): - 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)
- pou = project.getpou(var_type)
- if pou is not None and project.ElementIsUsedBy(pou_type, var_type):
- self.RecursiveSearchPouInstances(
- project, pou_type, var_path,
- [varlist for type, varlist in pou.getvars()],
+ 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( + os.path.join(ScriptDirectory, "plcopen", "instances_path.xslt"), + ("instances_ns", "AddInstance"): factory.AddInstance}) + instances_path_xslt_tree(root, + instance_type=etree.XSLT.strparam(name))
def SearchPouInstances(self, tagname, debug = False):
project = self.GetProject(debug)
words = tagname.split("::")
- for config in project.getconfigurations():
- config_name = config.getname()
- self.RecursiveSearchPouInstances(
- project, words[1], config_name,
- config.getglobalVars(), debug))
- for resource in config.getresource():
- res_path = "%s.%s" % (config_name, resource.getname())
- 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):
- self.RecursiveSearchPouInstances(
- project, words[1], pou_path,
- [varlist for type, varlist in pou.getvars()],
+ return self.GetInstanceList(project, words[1]) @@ -613,114 +781,40 @@
self.ComputePouName(words[1]), debug)]
- def RecursiveGetPouInstanceTagName(self, project, pou_type, parts, debug = False):
- pou = project.getpou(pou_type)
- 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(
- vartype_content["value"].getname(),
- 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])
- block_infos = self.GetBlockType(pou_type, debug=debug)
- if (block_infos is not None and
- block_infos["type"] in ["program", "functionBlock"]):
- 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)
- 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":
- return self.ComputePouName(
- vartype_content["value"].getname())
- return self.RecursiveGetPouInstanceTagName(
- vartype_content["value"].getname(),
def GetPouInstanceTagName(self, instance_path, debug = False):
project = self.GetProject(debug)
- parts = instance_path.split(".")
- return self.ComputeConfigurationName(parts[0])
- for config in project.getconfigurations():
- if config.getname() == parts[0]:
- result = self.GetGlobalInstanceTagName(project,
- return self.ComputeConfigurationResourceName(parts[0], parts[1])
- 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]:
- return self.ComputePouName(
- pou_instance.gettypeName())
- return self.RecursiveGetPouInstanceTagName(
- pou_instance.gettypeName(),
- return self.GetGlobalInstanceTagName(project,
- return self.GetGlobalInstanceTagName(project,
+ factory = InstanceTagName(self) + parser = etree.XMLParser() + parser.resolvers.add(LibraryResolver(self, debug)) + instance_tagname_xslt_tree = etree.XSLT( + os.path.join(ScriptDirectory, "plcopen", "instance_tagname.xslt"), + extensions = {("instance_tagname_ns", name): getattr(factory, name) + for name in ["ConfigTagName", "ResourceTagName", + "PouTagName", "ActionTagName", + 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)
infos = self.GetPouVariables(tagname, debug)
- infos["type"] = tagname
pou_path, var_name = instance_path.rsplit(".", 1)
tagname = self.GetPouInstanceTagName(pou_path)
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: @@ -728,21 +822,21 @@
def DataTypeIsUsed(self, name, debug = False):
project = self.GetProject(debug)
- return project.ElementIsUsed(name) or project.DataTypeIsDerived(name)
+ return len(self.GetInstanceList(project, name, debug)) > 0 # Return if pou given by name is used by another pou
def PouIsUsed(self, name, debug = False):
project = self.GetProject(debug)
- return project.ElementIsUsed(name)
+ return len(self.GetInstanceList(project, name, debug)) > 0 # 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 def GenerateProgram(self, filepath=None):
@@ -830,14 +924,13 @@
pou = self.Project.getpou(name)
- self.Project.RefreshCustomBlockTypes()
def GetPouXml(self, pou_name):
if self.Project is not None:
pou = self.Project.getpou(pou_name)
- return pou.generateXMLText('pou', 0)
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'
- tree = minidom.parseString(pou_xml.encode("utf-8"))
- root = tree.childNodes[0]
+ new_pou, error = LoadPou(pou_xml) 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() + 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. + new_name = "%s%d" % (name, idx)
- 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.
- 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)
+ new_pou.setpouType(pou_type) - self.Project.insertpou(-1, new_pou)
- return self.ComputePouName(new_name),
- return _("Couldn't paste non-POU object.")
+ self.Project.insertpou(-1, new_pou) + return self.ComputePouName(new_name), # Remove a Pou from project
def ProjectRemovePou(self, pou_name):
@@ -980,8 +1068,6 @@
datatype.setname(new_name)
self.Project.updateElementName(old_name, new_name)
- self.Project.RefreshElementUsingTree()
- self.Project.RefreshDataTypeHierarchy()
# Change the name of a pou
@@ -992,8 +1078,6 @@
self.Project.updateElementName(old_name, new_name)
- self.Project.RefreshElementUsingTree()
- self.Project.RefreshCustomBlockTypes()
# Change the name of a pou transition
@@ -1030,7 +1114,6 @@
for var in varlist.getvariable():
if var.getname() == old_name:
- self.Project.RefreshCustomBlockTypes()
# Change the name of a configuration
@@ -1069,7 +1152,6 @@
pou = project.getpou(name)
pou.setdescription(description)
- project.RefreshCustomBlockTypes()
# Return the type of the pou given by its name
@@ -1157,152 +1239,114 @@
- next_type = (var["Class"],
- var["Location"] in ["", None] or
+ next_type = (var.Class, + var.Location in ["", None] or # When declaring globals, located
# and not located variables are
# in the same declaration block
- var["Class"] == "Global")
if current_type != next_type:
- infos = VAR_CLASS_INFOS.get(var["Class"], None)
+ infos = VAR_CLASS_INFOS.get(var.Class, None) - current_varlist = infos[0]()
+ current_varlist = PLCOpenParser.CreateElement(infos[0], "interface") - 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") array.setdimension([dimension_range])
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()})
- array.baseType.setcontent({"name" : base_type_name, "value" : None})
+ baseType.setcontent(PLCOpenParser.CreateElement( + if base_type_name in ["STRING", "WSTRING"] + else base_type_name, "dataType")) - 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()})
- 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( + if var.Type in ["STRING", "WSTRING"] + else var.Type, "dataType")) - 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"])
+ tempvar.setaddress(var.Location) - 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)
- def GetVariableDictionary(self, varlist, var):
- convert a PLC variable to the dictionary representation
- 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":
- 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()
- 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()
- tempvar["Type"] = vartype_content["name"]
- initial = var.getinitialValue()
- tempvar["Initial Value"] = initial.getvalue()
- tempvar["Initial Value"] = ""
- address = var.getaddress()
- tempvar["Location"] = address
- tempvar["Location"] = ""
- if varlist.getconstant():
- tempvar["Option"] = "Constant"
- elif varlist.getretain():
- tempvar["Option"] = "Retain"
- elif varlist.getnonretain():
- tempvar["Option"] = "Non-Retain"
- doc = var.getdocumentation()
- tempvar["Documentation"] = doc.gettext()
- tempvar["Documentation"] = ""
+ def GetVariableDictionary(self, object_with_vars, tree=False, debug=False): + factory = VariablesInfosFactory(variables) + parser = etree.XMLParser() + parser.resolvers.add(LibraryResolver(self, debug)) + variables_infos_xslt_tree = etree.XSLT( + os.path.join(ScriptDirectory, "plcopen", "variables_infos.xslt"), + 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))) # 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):
project = self.GetProject(debug)
# 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"
+ # Extract variables defined in configuration + return self.GetVariableDictionary(configuration, debug) # 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
- 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):
project = self.GetProject(debug)
# Found the resource corresponding to name
resource = project.getconfigurationResource(config_name, name)
- # Extract variables from every varLists
- for varlist in resource.getglobalVars():
- for var in varlist.getvariable():
- tempvar = self.GetVariableDictionary(varlist, var)
- tempvar["Class"] = "Global"
+ if resource is not None: + # Extract variables defined in configuration + return self.GetVariableDictionary(resource, debug) # Return resource variable names
def GetConfigurationResourceVariableNames(self,
@@ -1388,73 +1424,15 @@
for varlist in resource.globalVars],
- # 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:
- 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)))
- tree.insert(0, ("ENO", "BOOL", ([], [])))
- tree.insert(0, ("EN", "BOOL", ([], [])))
- datatype = project.getdataType(typename)
- datatype = self.GetConfNodeDataType(typename)
- if datatype is not None:
- basetype_content = datatype.baseType.getcontent()
- if basetype_content["name"] == "derived":
- return self.GenerateVarTree(basetype_content["value"].getname())
- elif basetype_content["name"] == "array":
- base_type = basetype_content["value"].baseType.getcontent()
- if base_type["name"] == "derived":
- tree = self.GenerateVarTree(base_type["value"].getname())
- 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())))
- tree.append((element.getname(), element_type["name"], ([], [])))
# Return the interface for the given pou
- def GetPouInterfaceVars(self, pou, debug = False):
+ 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)
+ if interface is not None: + # Extract variables defined in interface + return self.GetVariableDictionary(interface, tree, debug) # Replace the Pou interface by the one given
def SetPouInterfaceVars(self, name, vars):
@@ -1463,100 +1441,99 @@
pou = self.Project.getpou(name)
if pou.interface is None:
- pou.interface = plcopen.pou_interface()
+ pou.interface = PLCOpenParser.CreateElement("interface", "pou") - 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.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()
- 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) - if type in self.GetBaseTypes():
- return_type.setcontent({"name" : "string", "value" : plcopen.elementaryTypes_string()})
- elif type == "WSTRING":
- return_type.setcontent({"name" : "wstring", "value" : plcopen.elementaryTypes_wstring()})
- return_type.setcontent({"name" : type, "value" : None})
+ if return_type in self.GetBaseTypes(): + return_type_obj.setcontent(PLCOpenParser.CreateElement( + if return_type in ["STRING", "WSTRING"] + else return_type, "dataType")) - 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 is not None: self.Project.updateElementName(old_name, new_name)
def UpdateEditedElementUsedVariable(self, tagname, old_name, new_name):
pou = self.GetEditedElement(tagname)
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)
- return self.GetPouInterfaceReturnType(pou)
# 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()
- 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()
- return returntype_content["name"]
+ if return_type is not None: + factory = VariablesInfosFactory([]) + parser = etree.XMLParser() + parser.resolvers.add(LibraryResolver(self)) + return_type_infos_xslt_tree = etree.XSLT( + os.path.join(ScriptDirectory, "plcopen", "variables_infos.xslt"), + 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))) + return [factory.GetType(), factory.GetTree()] + return factory.GetType() + 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 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)
+ self.ConfNodeTypes = [] + self.TotalTypesDict = StdBlckDct.copy() + self.TotalTypes = StdBlckLst[:] - def GetConfNodeBlockTypes(self):
- return [{"name": _("%s POUs") % confnodetypes["name"],
- "list": confnodetypes["types"].GetCustomBlockTypes()}
- for confnodetypes in self.ConfNodeTypes]
- def GetConfNodeDataTypes(self, exclude = "", only_locatables = False):
+ def GetConfNodeDataTypes(self, exclude = None, only_locatables = False): return [{"name": _("%s Data Types") % confnodetypes["name"],
- "list": [datatype["name"] for datatype in confnodetypes["types"].GetCustomDataTypes(exclude, only_locatables)]}
+ for datatype in confnodetypes["types"].getdataTypes() + if not only_locatables or self.IsLocatableDataType(datatype, debug)]} for confnodetypes in self.ConfNodeTypes]
- def GetConfNodeDataType(self, type):
- for confnodetype in self.ConfNodeTypes:
- datatype = confnodetype["types"].getdataType(type)
- if datatype is not None:
def GetVariableLocationTree(self):
@@ -1566,25 +1543,23 @@
def GetConfigurationExtraVariables(self):
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()})
- tempvartype.setcontent({"name" : var_type, "value" : None})
+ tempvartype.setcontent(PLCOpenParser.CreateElement( + if var_type in ["STRING", "WSTRING"] + else var_type, "dataType")) - 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)
- value = plcopen.value()
+ value = PLCOpenParser.CreateElement("initialValue", "variable") value.setvalue(var_initial)
tempvar.setinitialValue(value)
@@ -1592,82 +1567,96 @@
# 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): - 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):
+ 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): + if result_blocktype is not None: + if inputs == "undefined": - if result_blocktype is not None:
- if inputs == "undefined":
- 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:
project = self.GetProject(debug)
- return project.GetCustomBlockType(type, inputs)
+ blocktype = project.getpou(typename) + if blocktype is not None: + blocktype_infos = blocktype.getblockInfos() + if inputs in [None, "undefined"]: + if inputs == tuple([var_type + for name, var_type, modifier in blocktype_infos["inputs"]]): # Return Block types checking for recursion
def GetBlockTypes(self, tagname = "", debug = False):
words = tagname.split("::")
+ project = self.GetProject(debug) + if project is not None: if words[0] in ["P","T","A"]:
- type = self.GetPouType(name, debug)
- 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 = [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")})
+ pou_type = self.GetPouType(name, debug) + if pou_type == "function" or words[0] == "T" + else ["functionBlock", "function"]) + {"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) + len(self.GetInstanceList(pou, name, debug)) == 0)]}) # Return Function Block types checking for recursion
def GetFunctionBlockTypes(self, tagname = "", debug = False):
+ project = self.GetProject(debug) + words = tagname.split("::") + if project is not None and words[0] in ["P","T","A"]: - 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)
- words = tagname.split("::")
- if words[0] in ["P","T","A"]:
- blocktypes.extend(project.GetCustomFunctionBlockTypes(name))
+ blocktypes.extend([pou.getname() + for pou in project.getpous(name, ["functionBlock"]) + len(self.GetInstanceList(pou, name, debug)) == 0)]) # Return Block types checking for recursion
def GetBlockResource(self, debug = False):
- 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)
- blocktypes.extend(project.GetCustomBlockResource())
+ for pou in project.getpous(filter=["program"])]) # Return Data Types checking for recursion
@@ -1677,30 +1666,80 @@
project = self.GetProject(debug)
words = tagname.split("::")
- datatypes.extend([datatype["name"] for datatype in project.GetCustomDataTypes(name, only_locatables)])
+ for datatype in project.getdataTypes(name) + if (not only_locatables or self.IsLocatableDataType(datatype, debug)) + len(self.GetInstanceList(datatype, name, debug)) == 0)]) for category in self.GetConfNodeDataTypes(name, only_locatables):
datatypes.extend(category["list"])
- # Return Base Type of given possible derived type
- def GetBaseType(self, type, debug = False):
+ # Return Data Type Object + def GetPou(self, typename, debug = False): project = self.GetProject(debug)
- result = project.GetBaseType(type)
+ result = project.getpou(typename) + for standardlibrary in [StdBlockLibrary, AddnlBlockLibrary]: + result = standardlibrary.getpou(typename) + for confnodetype in self.ConfNodeTypes: + result = confnodetype["types"].getpou(typename) + # Return Data Type Object + def GetDataType(self, typename, debug = False): + project = self.GetProject(debug) + if project is not None: + result = project.getdataType(typename) for confnodetype in self.ConfNodeTypes:
- result = confnodetype["types"].GetBaseType(type)
+ result = confnodetype["types"].getdataType(typename) + # 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 Base Type of given possible derived type + def GetBaseType(self, typename, debug = False): + if TypeHierarchy.has_key(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 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):
- elif type == reference:
+ def IsOfType(self, typename, reference, debug = False): + if reference is None or typename == reference: - elif type in TypeHierarchy:
- return self.IsOfType(TypeHierarchy[type], reference)
- project = self.GetProject(debug)
- if project is not None and project.IsOfType(type, reference):
- for confnodetype in self.ConfNodeTypes:
- if confnodetype["types"].IsOfType(type, reference):
+ 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) - def IsEndType(self, type):
- return not type.startswith("ANY")
+ def IsEndType(self, typename): + if typename is not None: + return not typename.startswith("ANY") - def IsLocatableType(self, type, debug = False):
- if isinstance(type, TupleType):
- 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"]: - project = self.GetProject(debug)
- if project is not None:
- datatype = project.getdataType(type)
- 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) + def IsLocatableType(self, typename, debug = False): + if isinstance(typename, TupleType) or self.GetBlockType(typename) is not None: + datatype = self.GetDataType(typename, debug) + if datatype is not None: + return self.IsLocatableDataType(datatype) - def IsEnumeratedType(self, type, debug = False):
- project = self.GetProject(debug)
- if project is not None:
- datatype = project.getdataType(type)
- datatype = self.GetConfNodeDataType(type)
- if datatype is not None:
- basetype_content = datatype.baseType.getcontent()
- return basetype_content["name"] == "enum"
+ def IsEnumeratedType(self, typename, debug = False): + if isinstance(typename, TupleType): + 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" - 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: + if isinstance(typename, TupleType): + 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) + 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]
- project = self.GetProject(debug)
- if project is not None:
- result = project.GetDataTypeRange(type)
- for confnodetype in self.ConfNodeTypes:
- result = confnodetype["types"].GetDataTypeRange(type)
+ def GetDataTypeRange(self, typename, debug = False): + range = DataTypeRange.get(typename) + 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) def GetSubrangeBaseTypes(self, exclude, debug = False):
- subrange_basetypes = []
+ subrange_basetypes = DataTypeRange.keys() project = self.GetProject(debug)
- subrange_basetypes.extend(project.GetSubrangeBaseTypes(exclude))
+ 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(confnodetype["types"].GetSubrangeBaseTypes(exclude))
- return DataTypeRange.keys() + subrange_basetypes
+ 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, type = None, debug = False):
+ def GetEnumeratedDataValues(self, typename = None, debug = False): - project = self.GetProject(debug)
- if project is not None:
- values.extend(project.GetEnumeratedDataTypeValues(type))
- if type is None and len(values) > 0:
- for confnodetype in self.ConfNodeTypes:
- values.extend(confnodetype["types"].GetEnumeratedDataTypeValues(type))
- if type is None and len(values) > 0:
+ 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) + project = self.GetProject(debug) + if project is not None: + values.extend(project.GetEnumeratedDataTypeValues()) + for confnodetype in self.ConfNodeTypes: + values.extend(confnodetype["types"].GetEnumeratedDataTypeValues()) #-------------------------------------------------------------------------------
@@ -1847,62 +1924,64 @@
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"]
- 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" + elif basetype_content_type == "enum": infos["type"] = "Enumerated"
- 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": - 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()
- 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"
- for element in basetype_content["value"].getvariable():
+ for element in basetype_content.getvariable(): 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": - 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()
- 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", + if base_type_type == "derived" + else base_type_type.upper(), dimensions) + elif element_type_type == "derived": + element_infos["Type"] = element_type.getname() - 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())
element_infos["Initial Value"] = ""
infos["elements"].append(element_infos)
+ 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())
@@ -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()})
- 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")) - 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})
- subrange = plcopen.derivedTypes_subrangeSigned()
- datatype.baseType.setcontent({"name" : "subrangeSigned", "value" : subrange})
+ subrange = PLCOpenParser.CreateElement( + 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")) - 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)
- enumerated.values.setvalue([value])
+ values.setvalue([value]) - 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])
@@ -1963,28 +2043,28 @@
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()})
- 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")) - 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])
@@ -1992,45 +2072,39 @@
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()})
- array.baseType.setcontent({"name" : base_type_name, "value" : None})
+ array.baseType.setcontent(PLCOpenParser.CreateElement( + if base_type_name in ["STRING", "WSTRING"] + else base_type_name, "dataType")) - 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()})
- 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")) - 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)
struct.setvariable([element])
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"])
datatype.initialValue = None
- self.Project.RefreshDataTypeHierarchy()
- self.Project.RefreshElementUsingTree()
#-------------------------------------------------------------------------------
@@ -2087,25 +2161,25 @@
# 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)
pou = project.getpou(words[1])
- return self.GetPouInterfaceVars(pou, debug)
+ return self.GetPouInterfaceVars(pou, tree, debug) # Return the edited element return type
- def GetEditedElementInterfaceReturnType(self, tagname, debug = False):
+ def GetEditedElementInterfaceReturnType(self, tagname, tree=False, debug = False): words = tagname.split("::")
project = self.GetProject(debug)
pou = self.Project.getpou(words[1])
- return self.GetPouInterfaceReturnType(pou)
+ return self.GetPouInterfaceReturnType(pou, tree, debug) @@ -2116,7 +2190,6 @@
element = self.GetEditedElement(tagname)
- 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)
- name = element.__class__.__name__
- return element.generateXMLText(name.split("_")[-1], 0)
+ return element.tostring() def GetEditedElementInstancesCopy(self, tagname, blocks_id = None, wires = None, debug = False):
element = self.GetEditedElement(tagname, debug)
- wires = dict([(wire, True) for wire in wires if wire[0] in blocks_id and wire[1] in blocks_id])
+ wires = dict([(wire, True) + if wire[0] in blocks_id and wire[1] in blocks_id]) + copy_body = PLCOpenParser.CreateElement("body", "pou") + element.append(copy_body) + PLCOpenParser.CreateElement(element.getbodyType(), "body")) instance = element.getinstance(id)
- 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) 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
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 @@
- 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()])
- text = "<paste>%s</paste>"%text
+ instances, error = LoadPouInstances(text.encode("utf-8"), bodytype) + instances, error = [], "" + if error is not None or len(instances) == 0: + return _("Invalid plcopen element(s)!!!")
- tree = minidom.parseString(text.encode("utf-8"))
- return _("Invalid plcopen element(s)!!!")
- 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.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,
- exclude[blockname] = True
- instance.setinstanceName(blockname)
- self.AddEditedElementPouVar(tagname, blocktype, blockname)
- elif child.nodeName == "step":
- stepname = self.GenerateNewName(tagname,
- exclude[stepname] = True
- instance.setname(stepname)
- localid = instance.getlocalId()
- if not used_id.has_key(localid):
- 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, + exclude[blockname] = True + instance.setinstanceName(blockname) + self.AddEditedElementPouVar(tagname, blocktype, blockname) + elif instance_type == "step": + stepname = self.GenerateNewName(tagname, + exclude[stepname] = True + instance.setname(stepname) + localid = instance.getlocalId() + if not used_id.has_key(localid):
- for name, instance in instances:
+ 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]))
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)) - 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):
+ def GetEditedElementInstancesInfos(self, tagname, debug = False): + element_instances = OrderedDict() element = self.GetEditedElement(tagname, debug)
- instance = element.getinstance(id)
- 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
+ factory = BlockInstanceFactory(element_instances) + pou_block_instances_xslt_tree = etree.XSLT( + pou_block_instances_xslt, + ("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 @@
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 words[0] == "T" and varname == words[2]:
- 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()
- return vartype_content["name"]
def SetConnectionWires(self, connection, connector):
wires = connector.GetWires()
@@ -2410,21 +2444,36 @@
connection.setconnectionParameter(idx, None)
- 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")) + derived_type = PLCOpenParser.CreateElement("derived", "dataType") + derived_type.setname(var_type) + var_type_obj.setcontent(derived_type) + 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])
- pou.addpouLocalVar(type, name, location, description)
+ self.GetVarTypeObject(var_type), + name, location, description) - def AddEditedElementPouExternalVar(self, tagname, type, name):
+ 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])
- pou.addpouExternalVar(type, name)
+ 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)
- block = plcopen.fbdObjects_block()
+ block = PLCOpenParser.CreateElement("block", "fbdObjects") 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():
- block.setinstanceName(value)
+ block.setinstanceName(value) + block.attrib.pop("instanceName", None) 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):
+ def AddEditedElementVariable(self, tagname, id, var_type): element = self.GetEditedElement(tagname)
- if element is not None:
- variable = plcopen.fbdObjects_inVariable()
- variable = plcopen.fbdObjects_outVariable()
- variable = plcopen.fbdObjects_inOutVariable()
+ if element is not None: + variable = PLCOpenParser.CreateElement( + INOUT: "inOutVariable"}[var_type], "fbdObjects") - element.addinstance(name, variable)
+ element.addinstance(variable) def SetEditedElementVariableInfos(self, tagname, id, infos):
element = self.GetEditedElement(tagname)
@@ -2544,7 +2590,7 @@
for param, value in infos.items():
- variable.setexpression(value)
+ variable.setexpression(value) elif param == "executionOrder" and variable.getexecutionOrderId() != value:
element.setelementExecutionOrder(variable, value)
@@ -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)
- connection = plcopen.commonObjects_connector()
- elif type == 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 @@
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)
- comment = plcopen.commonObjects_comment()
+ comment = PLCOpenParser.CreateElement("comment", "commonObjects") - element.addinstance("comment", comment)
+ element.addinstance(comment) def SetEditedElementCommentInfos(self, tagname, id, infos):
element = self.GetEditedElement(tagname)
@@ -2642,17 +2685,14 @@
- def AddEditedElementPowerRail(self, tagname, id, type):
+ def AddEditedElementPowerRail(self, tagname, id, powerrail_type): element = self.GetEditedElement(tagname)
- powerrail = plcopen.ldObjects_leftPowerRail()
- elif type == RIGHTRAIL:
- name = "rightPowerRail"
- powerrail = plcopen.ldObjects_rightPowerRail()
+ powerrail = PLCOpenParser.CreateElement( + {LEFTRAIL: "leftPowerRail", + RIGHTRAIL: "rightPowerRail"}[powerrail_type], "ldObjects") - element.addinstance(name, powerrail)
+ element.addinstance(powerrail) def SetEditedElementPowerRailInfos(self, tagname, id, infos):
element = self.GetEditedElement(tagname)
@@ -2670,28 +2710,28 @@
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)
- contact = plcopen.ldObjects_contact()
+ contact = PLCOpenParser.CreateElement("contact", "ldObjects") - element.addinstance("contact", contact)
+ element.addinstance(contact) def SetEditedElementContactInfos(self, tagname, id, infos):
element = self.GetEditedElement(tagname)
@@ -2703,18 +2743,13 @@
contact.setvariable(value)
- 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")
+ CONTACT_NORMAL: (False, "none"), + CONTACT_REVERSE: (True, "none"), + CONTACT_RISING: (False, "rising"), + CONTACT_FALLING: (False, "falling")}[value] + contact.setnegated(negated) @@ -2737,9 +2772,9 @@
def AddEditedElementCoil(self, tagname, id):
element = self.GetEditedElement(tagname)
- coil = plcopen.ldObjects_coil()
+ coil = PLCOpenParser.CreateElement("coil", "ldObjects") - element.addinstance("coil", coil)
+ element.addinstance(coil) def SetEditedElementCoilInfos(self, tagname, id, infos):
element = self.GetEditedElement(tagname)
@@ -2751,30 +2786,16 @@
- if value == COIL_NORMAL:
- coil.setstorage("none")
- elif value == COIL_REVERSE:
- coil.setstorage("none")
- elif value == COIL_SET:
- elif value == COIL_RESET:
- coil.setstorage("reset")
- elif value == COIL_RISING:
- coil.setstorage("none")
- elif value == COIL_FALLING:
- 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) @@ -2797,9 +2818,9 @@
def AddEditedElementStep(self, tagname, id):
element = self.GetEditedElement(tagname)
- step = plcopen.sfcObjects_step()
+ step = PLCOpenParser.CreateElement("step", "sfcObjects") - 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)
- 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)
+ self.SetConnectionWires(transition.condition.content, value) - def AddEditedElementDivergence(self, tagname, id, type):
+ def AddEditedElementDivergence(self, tagname, id, divergence_type): element = self.GetEditedElement(tagname)
- 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) + 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): def SetEditedElementDivergenceInfos(self, tagname, id, infos):
element = self.GetEditedElement(tagname)
@@ -2922,7 +2949,8 @@
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()
- 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()
- 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)
- jump = plcopen.sfcObjects_jumpStep()
+ jump = PLCOpenParser.CreateElement("jumpStep", "sfcObjects") - 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)
- 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)
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):
words = tagname.split("::")
for var in self.GetConfigurationGlobalVars(words[1], debug):
- if var["Type"] == "BOOL":
- varlist.append(var["Name"])
+ varlist.append(var.Name) for var in self.GetConfigurationResourceGlobalVars(words[1], words[2], debug):
- if var["Type"] == "BOOL":
- varlist.append(var["Name"])
+ varlist.append(var.Name) def SetEditedResourceInfos(self, tagname, tasks, instances):
@@ -3041,7 +3062,8 @@
resource.setpouInstance([])
- 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"]))
task_list[task["Name"]] = new_task
- resource.appendtask(new_task)
for instance in instances:
- new_instance = plcopen.pouInstance()
+ task = task_list.get(instance["Task"]) + new_instance = PLCOpenParser.CreateElement("pouInstance", "task") + task.appendpouInstance(new_instance) + 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)
+ 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.NextCompiledProject = self.Copy(self.Project) + self.CurrentCompiledProject = None + self.CurrentElementEditing = None - self.Project = plcopen.project()
- for child in tree.childNodes:
- if child.nodeType == tree.ELEMENT_NODE and child.nodeName == "project":
- result = self.Project.loadXMLTree(child)
- 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.NextCompiledProject = self.Copy(self.Project)
- self.CurrentCompiledProject = None
- self.CurrentElementEditing = None
- return _("No PLC project found")
def SaveXMLFile(self, filepath = None):
if not filepath and self.FilePath == "":
@@ -3156,19 +3170,11 @@
contentheader = {"modificationDateTime": datetime.datetime(*localtime()[:6])}
self.Project.setcontentHeader(contentheader)
- text = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\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)
+ SaveProject(self.Project, filepath) + SaveProject(self.Project, self.FilePath)
- xmlfile = open(filepath,"w")
- xmlfile = open(self.FilePath,"w")
- xmlfile.write(text.encode("utf-8"))
self.MarkProjectAsSaved()
self.SetFilePath(filepath)
@@ -3195,11 +3201,11 @@
Return a copy of the project
- return cPickle.loads(cPickle.dumps(model))
def CreateProjectBuffer(self, saved):
if self.ProjectBufferEnabled:
- self.ProjectBuffer = UndoBuffer(cPickle.dumps(self.Project), saved)
+ self.ProjectBuffer = UndoBuffer(PLCOpenParser.Dumps(self.Project), saved) self.ProjectBuffer = None
self.ProjectSaved = saved
@@ -3218,7 +3224,7 @@
if self.ProjectBuffer is not None:
- self.ProjectBuffer.Buffering(cPickle.dumps(self.Project))
+ self.ProjectBuffer.Buffering(PLCOpenParser.Dumps(self.Project)) self.ProjectSaved = False
@@ -3230,7 +3236,7 @@
if self.ProjectBuffer is not None and self.Buffering:
- self.ProjectBuffer.Buffering(cPickle.dumps(self.Project))
+ self.ProjectBuffer.Buffering(PLCOpenParser.Dumps(self.Project)) def MarkProjectAsSaved(self):
@@ -3250,11 +3256,11 @@
if self.ProjectBuffer is not None:
- self.Project = cPickle.loads(self.ProjectBuffer.Previous())
+ self.Project = PLCOpenParser.Loads(self.ProjectBuffer.Previous()) 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:
--- 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 *
@@ -75,6 +75,13 @@
+# Helper for emulate join on element list +def JoinList(separator, mylist): + return reduce(lambda x, y: x + separator + y, 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
- 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 += [(")", ())]
- 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
- 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": - 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
- 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
- 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
- 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:
- 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)
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 is not None: (self.ComputeValue(initial.getvalue(), var_type), (tagname, variable_type, var_number, "initial value"))]
config += [(" END_VAR\n", ())]
+ if extra_global_vars is not None: + configuration.remove(extra_global_vars) + 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)
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 is not None: (self.ComputeValue(initial.getvalue(), var_type), (tagname, variable_type, var_number, "initial value"))]
@@ -378,13 +392,13 @@
single = task.getsingle()
# Single argument if exists
resrce += [("SINGLE := ", ()),
(single, (tagname, "task", task_number, "single")),
# Interval argument if exists
interval = task.getinterval()
+ 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)
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_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()
+ returntype_content_type = returntype_content.getLocalTag() + if returntype_content_type == "derived": + self.ReturnType = returntype_content.getname() - self.ReturnType = returntype_content["name"]
+ self.ReturnType = returntype_content_type.upper() for varlist in interface.getcontent():
- 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())
- for variable in blocktype["initialise"](var_type, var.getname(), block):
- if variable[2] is not None:
- located.append(variable)
- variables.append(variable)
+ variables.append((var_type, var.getname(), None, None)) self.ParentGenerator.GenerateDataType(var_type)
initial = var.getinitialValue()
+ if initial is not None: initial_value = initial.getvalue()
address = var.getaddress()
- located.append((vartype_content["value"].getname(), var.getname(), address, initial_value))
+ located.append((vartype_content.getname(), var.getname(), address, initial_value)) - variables.append((vartype_content["value"].getname(), var.getname(), None, initial_value))
+ variables.append((vartype_content.getname(), var.getname(), None, initial_value)) var_type = var.gettypeAsText()
initial = var.getinitialValue()
+ if initial is not None: initial_value = initial.getvalue()
@@ -642,18 +668,18 @@
located.append((var_type, var.getname(), address, initial_value))
variables.append((var_type, var.getname(), None, initial_value))
- if varlist["value"].getconstant():
+ if varlist.getconstant(): - elif varlist["value"].getretain():
+ elif varlist.getretain(): - elif varlist["value"].getnonretain():
+ elif varlist.getnonretain(): - self.Interface.append((varTypeNames[varlist["name"]], option, False, variables))
+ self.Interface.append((varTypeNames[varlist_type], option, False, variables)) - self.Interface.append((varTypeNames[varlist["name"]], option, True, located))
+ self.Interface.append((varTypeNames[varlist_type], option, True, located)) @@ -669,24 +695,25 @@
if isinstance(body, ListType):
body_content = body.getcontent()
- body_type = body_content["name"]
+ body_type = body_content.getLocalTag() if body_type in ["FBD", "LD", "SFC"]:
for instance in body.getcontentInstances():
- if isinstance(instance, (plcopen.fbdObjects_inVariable, plcopen.fbdObjects_outVariable, plcopen.fbdObjects_inOutVariable)):
+ if isinstance(instance, (InVariableClass, OutVariableClass, 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()): - 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() - var_type = returntype_content["name"]
+ var_type = returntype_content_type.upper() parts = expression.split("#")
@@ -698,54 +725,58 @@
elif expression.startswith('"'):
- 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()
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)
if connector is not None:
undefined = [instance.connectionPointOut, connector.connectionPointIn]
connected = self.GetConnectedConnector(connector.connectionPointIn, body)
+ if connected is not None: undefined.append(connected)
for connection in undefined:
@@ -760,7 +791,7 @@
self.ConnectionTypes[connection] = var_type
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].append(variable.connectionPointIn)
+ if connected is not None: undefined[itype].append(connected)
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_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)))]
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" : []}
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()
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)
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 @@
raise PLCGenException, _("Undefined block type \"%s\" in \"%s\" POU")%(block_type, self.Name)
- block_infos["generate"](self, instance, block_infos, body, None)
+ self.GenerateBlock(instance, block_infos, body, None) raise PLCGenException, e.message
- elif isinstance(instance, plcopen.commonObjects_connector):
+ elif isinstance(instance, ConnectorClass): connector = instance.getname()
if self.ComputedConnectors.get(connector, None):
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 @@
+ 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() + 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 + 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 + input_parameters = ["EN"] + input_names + 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: + 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 + expression = self.ComputeExpression(body, connections, executionOrderId > 0) + if expression is not None: + connected_vars.append(([(parameter, input_info), (" := ", ())], + self.ExtractModifier(variable, expression, input_info))) + all_input_connected = False + all_input_connected = False + if len(output_variables) > 1 or not all_input_connected: + vars = [name + value for name, value in connected_vars] + 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()) + 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)) + 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, ())]) + 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", ())] + 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 + for variable in input_variables: + parameter = variable.getformalParameter() + if parameter in input_names or parameter == "EN": + 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", ())] + connectionPoint = link.getposition()[-1] + output_parameter = link.getformalParameter() + output_parameter = None + 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) + 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() + 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] + if output_parameter == "": + output_name = "%s%d"%(type, block.getlocalId()) + 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) + 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)) + 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, ())] + if output_parameter is None: + blockname = "%s(%s)" % (name, 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):
for connection in connections:
localId = connection.getrefLocalId()
next = body.getcontentInstance(localId)
- if isinstance(next, plcopen.ldObjects_leftPowerRail):
+ if isinstance(next, LeftPowerRailClass): - 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 @@
raise PLCGenException, _("Undefined block type \"%s\" in \"%s\" POU")%(block_type, self.Name)
- 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))) raise PLCGenException, e.message
- elif isinstance(next, plcopen.commonObjects_continuation):
+ elif isinstance(next, ContinuationClass): computed_value = self.ComputedConnectors.get(name, None)
if computed_value != None:
@@ -992,7 +1208,7 @@
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)
@@ -1005,7 +1221,7 @@
paths.append(str(expression))
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]])
- elif isinstance(next, plcopen.ldObjects_coil):
+ elif isinstance(next, CoilClass): paths.append(str(self.GeneratePaths(next.connectionPointIn.getconnections(), body, order)))
@@ -1092,7 +1308,7 @@
def ExtractDivergenceInput(self, divergence, pou):
connectionPointIn = divergence.getconnectionPointIn()
+ 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 @@
self.SFCNetworks["Steps"][step_name] = step_infos
- if step.connectionPointIn:
+ if step.connectionPointIn is not None: connections = step.connectionPointIn.getconnections()
if connections is not None and len(connections) == 1:
@@ -1133,16 +1349,16 @@
if isinstance(body, ListType):
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 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: connections = jump.connectionPointIn.getconnections()
if connections is not None and len(connections) == 1:
@@ -1161,16 +1377,16 @@
if isinstance(body, ListType):
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 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 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):
instance = body.getcontentInstance(instanceLocalId)
- if isinstance(instance, plcopen.sfcObjects_step):
+ if isinstance(instance, StepClass): - elif isinstance(instance, plcopen.sfcObjects_selectionDivergence):
+ elif isinstance(instance, SelectionDivergenceClass): step = self.ExtractDivergenceInput(instance, pou)
- if isinstance(step, plcopen.sfcObjects_step):
+ if isinstance(step, StepClass): - 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(),
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)))] 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 @@
if isinstance(body, ListType):
- 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),
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 is not None: (self.ReturnType, (self.TagName, "return"))]
--- 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 structures import *
+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())
-PLCOpenClasses = GenerateClassesFromXSD(os.path.join(os.path.split(__file__)[0], "tc6_xml_v201.xsd"))
+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 = """ +<project xmlns:ns1="http://www.plcopen.org/xml/tc6_0201" + xmlns:xhtml="http://www.w3.org/1999/xhtml" + xmlns:xsd="http://www.w3.org/2001/XMLSchema" + xmlns="http://www.plcopen.org/xml/tc6_0201"> + <fileHeader companyName="" productName="" productVersion="" + creationDateTime="1970-01-01T00:00:00"/> + <contentHeader name="paste_project"> + <fbd><scaling x="0" y="0"/></fbd> + <ld><scaling x="0" y="0"/></ld> + <sfc><scaling x="0" y="0"/></sfc> +def LOAD_POU_INSTANCES_PROJECT_TEMPLATE(body_type): + return LOAD_POU_PROJECT_TEMPLATE % """ +<pou name="paste_pou" pouType="program"> + <%(body_type)s>%%s</%(body_type)s> +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_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") + (re.compile("(?<!<xhtml:p>)(?:<!\[CDATA\[)"), "<xhtml:p><![CDATA["), + (re.compile("(?:]]>)(?!</xhtml:p>)"), "]]></xhtml:p>")]: + project_xml = cre.sub(repl, project_xml) + tree, error = PLCOpenParser.LoadXMLString(project_xml) + 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) + 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)]) + 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) + 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) + 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) -cls = PLCOpenClasses.get("formattedText", None)
+def LoadProject(filepath): + project_file = open(filepath) + project_xml = project_file.read() + 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( +cls = PLCOpenParser.GetElementClass("formattedText") def updateElementName(self, old_name, new_name):
+ text = self.getanyText() index = text.find(old_name)
if index > 0 and (text[index - 1].isalnum() or text[index - 1] == "_"):
@@ -139,11 +294,11 @@
text = text[:index] + new_name + text[index + len(old_name):]
index = text.find(old_name, index + len(new_name))
setattr(cls, "updateElementName", updateElementName)
def updateElementAddress(self, address_model, new_leading):
+ text = self.getanyText() 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)
+ result = address_model.search(text, startpos) setattr(cls, "updateElementAddress", updateElementAddress)
def hasblock(self, block_type):
- text = self.text.upper()
+ text = self.getanyText().upper() index = text.find(block_type.upper())
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)
+cls = PLCOpenParser.GetElementClass("project") - cls.singleLineAttributes = False
- cls.EnumeratedDataTypeValues = {}
- cls.CustomDataTypeRange = {}
- cls.CustomTypeHierarchy = {}
- cls.ElementUsingTree = {}
- cls.CustomBlockTypes = []
self.contentHeader.setname(name)
@@ -188,532 +337,219 @@
setattr(cls, "getname", getname)
- 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[name] = value
+ fileheader_obj = self.fileHeader + attr: value if value is not None else "" + ("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):
- 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"])
+ fileheader_obj = self.fileHeader + for attr in ["companyName", "companyURL", "productName", + "productVersion", "productRelease", "creationDateTime", + value = fileheader.get(attr) + setattr(fileheader_obj, attr, value) setattr(cls, "setfileHeader", setfileHeader)
def getcontentHeader(self):
- 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())]:
- contentheader[name] = value
- contentheader[name] = ""
+ contentheader_obj = self.contentHeader + attr: value if value is not None else "" + ("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()
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) + 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) + 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)
- return self.types.getpouElements()
+ def getpous(self, exclude=None, filter=[]): + "ppx:types/ppx:pous/ppx:pou%s%s" % + (("[@name!='%s']" % exclude) if exclude is not None else '', + 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()
+ 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:
+ configurations = configuration_xpath(self, name=name) + if len(configurations) == 1: + return configurations[0] 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):
- for idx, configuration in enumerate(self.instances.configurations.getconfiguration()):
- if configuration.getname() == name:
- self.instances.configurations.removeconfiguration(idx)
- 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)
- for resource in configuration.getresource():
- if resource.getname() == name:
+ resources = resources_xpath(self, configname=config_name, name=name) + if len(resources) == 1: 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)
- 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)
- for idx, resource in enumerate(configuration.getresource()):
- if resource.getname() == name:
- configuration.removeresource(idx)
- raise ValueError, _("\"%s\" resource doesn't exist in \"%s\" configuration !!!")%(name, config_name)
+ if configuration is not None: + resource = self.getconfigurationResource(config_name, name) + if resource is not None: + configuration.remove(resource) + 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"]
- self.CustomTypeHierarchy[name] = base_type["value"].getname()
- if basetype_content["name"] == "enum":
- 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}
- return_type = pou.interface.getreturnType()
- 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"))
- block_infos["outputs"].append(("OUT", var_type["name"], "none"))
- for type, varlist in pou.getvars():
- 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"))
- block_infos["inputs"].append((var.getname(), var_type["name"], "none"))
- block_infos["outputs"].append((var.getname(), var_type["name"], "none"))
- 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"))
- block_infos["inputs"].append((var.getname(), var_type["name"], "none"))
- 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"))
- 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 = {}
- 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"])
- # 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]
- 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 self.GetBaseType(parent_type)
- setattr(cls, "GetBaseType", GetBaseType)
- def GetSubrangeBaseTypes(self, exclude):
- for type in self.CustomTypeHierarchy.keys():
- for base_type in DataTypeRange.keys():
- if self.IsOfType(type, base_type) and not self.IsOfType(type, exclude):
- 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):
- elif type == reference:
- parent_type = self.GetParentType(type)
- if parent_type is not None:
- return self.IsOfType(parent_type, reference)
- 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
- 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
- # Test if pou is undirectly used by reference, by testing if pous
- # that directly use pou is directly or undirectly used by reference
- used |= self.ElementIsUsedBy(element, reference)
- 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]
- parent_type = self.GetParentType(type)
- if parent_type is not None:
- return self.GetDataTypeRange(parent_type)
- setattr(cls, "GetDataTypeRange", GetDataTypeRange)
- def GetEnumeratedDataTypeValues(self, type = None):
- for values in self.EnumeratedDataTypeValues.values():
- all_values.extend(values)
- elif self.EnumeratedDataTypeValues.has_key(type):
- return self.EnumeratedDataTypeValues[type]
+ 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
- if customblocktype["name"] == type and same_inputs:
- setattr(cls, "GetCustomBlockType", GetCustomBlockType)
- # Return Block types checking for recursion
- def GetCustomBlockTypes(self, exclude = "", onlyfunctions = False):
- pou = self.getpou(exclude)
- type = pou.getpouType()
- 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 = ""):
- 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):
- 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):
- 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})
- 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"]:
- 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)
- 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 @@
setattr(cls, "Search", Search)
-cls = PLCOpenClasses.get("project_fileHeader", None)
+cls = PLCOpenParser.GetElementClass("contentHeader", "project") - cls.singleLineAttributes = False
-cls = PLCOpenClasses.get("project_contentHeader", None)
- cls.singleLineAttributes = False
def setpageSize(self, width, height):
self.coordinateInfo.setpageSize(width, height)
@@ -750,7 +581,7 @@
setattr(cls, "getscaling", getscaling)
-cls = PLCOpenClasses.get("contentHeader_coordinateInfo", None)
+cls = PLCOpenParser.GetElementClass("coordinateInfo", "contentHeader") 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.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)
+ variables.remove(variables[i]) def _SearchInConfigurationResource(self, criteria, parent_infos=[]):
search_result = _Search([("name", self.getname())], criteria, parent_infos)
@@ -849,33 +680,21 @@
-cls = PLCOpenClasses.get("configurations_configuration", None)
+cls = PLCOpenParser.GetElementClass("configuration", "configurations") - def addglobalVar(self, type, name, location="", description=""):
+ def addglobalVar(self, var_type, name, location="", description=""): globalvars = self.getglobalVars()
- globalvars.append(PLCOpenClasses["varList"]())
- var = PLCOpenClasses["varListPlain_variable"]()
+ globalvars.append(PLCOpenParser.CreateElement("varList")) + var = PLCOpenParser.CreateElement("variable", "varListPlain") - var_type = PLCOpenClasses["dataType"]()
- if type in [x for x,y in TypeHierarchy_list if not x.startswith("ANY")]:
- var_type.setcontent({"name" : "string", "value" : PLCOpenClasses["elementaryTypes_string"]()})
- elif type == "WSTRING":
- var_type.setcontent({"name" : "wstring", "value" : PLCOpenClasses["elementaryTypes_wstring"]()})
- var_type.setcontent({"name" : type, "value" : None})
- derived_type = PLCOpenClasses["derivedTypes_derived"]()
- derived_type.setname(type)
- var_type.setcontent({"name" : "derived", "value" : derived_type})
- ft = PLCOpenClasses["formattedText"]()
- ft.settext(description)
+ ft = PLCOpenParser.CreateElement("documentation", "variable") + ft.setanyText(description) globalvars[-1].appendvariable(var)
setattr(cls, "addglobalVar", addglobalVar)
@@ -906,7 +725,7 @@
setattr(cls, "Search", Search)
-cls = PLCOpenClasses.get("configuration_resource", None)
+cls = PLCOpenParser.GetElementClass("resource", "configuration") def updateElementName(self, old_name, new_name):
_updateConfigurationResourceElementName(self, old_name, new_name)
@@ -947,32 +766,8 @@
setattr(cls, "Search", Search)
-cls = PLCOpenClasses.get("resource_task", None)
+cls = PLCOpenParser.GetElementClass("task", "resource") - def compatibility(self, tree):
- if tree.hasAttribute("interval"):
- interval = GetAttributeValue(tree._attrs["interval"])
- result = time_model.match(interval)
- 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)])
- 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)
- text += "%dms"%(time_values[3] / 1000)
- NodeSetAttr(tree, "interval", text)
- setattr(cls, "compatibility", compatibility)
def updateElementName(self, old_name, new_name):
if self.single == old_name:
@@ -996,13 +791,8 @@
setattr(cls, "Search", Search)
-cls = PLCOpenClasses.get("pouInstance", None)
+cls = PLCOpenParser.GetElementClass("pouInstance") - def compatibility(self, tree):
- if tree.hasAttribute("type"):
- NodeRenameAttr(tree, "type", "typeName")
- setattr(cls, "compatibility", compatibility)
def updateElementName(self, old_name, new_name):
if self.typeName == old_name:
@@ -1014,31 +804,33 @@
setattr(cls, "Search", Search)
-cls = PLCOpenClasses.get("varListPlain_variable", None)
+cls = PLCOpenParser.GetElementClass("variable", "varListPlain") 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
- 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 @@
setattr(cls, "Search", Search)
-cls = PLCOpenClasses.get("project_types", None)
+cls = PLCOpenParser.GetElementClass("types", "project") 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):
- 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) @@ -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.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):
- 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) @@ -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") setattr(cls, "updateElementName", _updateBaseTypeElementName)
@@ -1159,33 +951,45 @@
setattr(cls, "Search", Search)
-cls = PLCOpenClasses.get("dataType", None)
+cls = PLCOpenParser.GetElementClass("dataType") 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=[]):
- 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]))
- 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)) setattr(cls, "Search", Search)
-cls = PLCOpenClasses.get("derivedTypes_array", None)
+cls = PLCOpenParser.GetElementClass("derived", "dataType") + def updateElementName(self, old_name, new_name): + if self.name == old_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") setattr(cls, "updateElementName", _updateBaseTypeElementName)
@@ -1205,68 +1009,100 @@
-cls = PLCOpenClasses.get("derivedTypes_subrangeSigned", None)
+cls = PLCOpenParser.GetElementClass("subrangeSigned", "dataType") setattr(cls, "updateElementName", _updateBaseTypeElementName)
setattr(cls, "Search", _SearchInSubrange)
-cls = PLCOpenClasses.get("derivedTypes_subrangeUnsigned", None)
+cls = PLCOpenParser.GetElementClass("subrangeUnsigned", "dataType") setattr(cls, "updateElementName", _updateBaseTypeElementName)
setattr(cls, "Search", _SearchInSubrange)
-cls = PLCOpenClasses.get("derivedTypes_enum", None)
+cls = PLCOpenParser.GetElementClass("enum", "dataType") def updateElementName(self, old_name, new_name):
setattr(cls, "updateElementName", updateElementName)
+ enumerated_datatype_values_xpath = PLCOpen_XPath("ppx:values/ppx:value") def Search(self, criteria, parent_infos=[]):
- 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)
setattr(cls, "Search", Search)
-cls = PLCOpenClasses.get("pous_pou", None)
+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") + 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): + "name" : self.getname(), + "type" : self.getpouType(), + "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"]]))) + setattr(cls, "getblockInfos", getblockInfos) def setdescription(self, description):
doc = self.getdocumentation()
- 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()
+ return doc.getanyText() setattr(cls, "getdescription", getdescription)
- def setbodyType(self, type):
+ def setbodyType(self, body_type):
- self.body[0].setcontent({"name" : "IL", "value" : PLCOpenClasses["formattedText"]()})
- self.body[0].setcontent({"name" : "ST", "value" : PLCOpenClasses["formattedText"]()})
- self.body[0].setcontent({"name" : "LD", "value" : PLCOpenClasses["body_LD"]()})
- self.body[0].setcontent({"name" : "FBD", "value" : PLCOpenClasses["body_FBD"]()})
- 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")) raise ValueError, "%s isn't a valid body type!"%type
setattr(cls, "setbodyType", setbodyType)
- 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): - self.body[0].appendcontentInstance(name, instance)
+ self.body[0].appendcontentInstance(instance) setattr(cls, "addinstance", addinstance)
@@ -1301,11 +1137,11 @@
setattr(cls, "getinstance", getinstance)
- def getrandomInstance(self, exclude):
+ def getinstancesIds(self): - return self.body[0].getcontentRandomInstance(exclude)
- setattr(cls, "getrandomInstance", getrandomInstance)
+ return self.body[0].getcontentInstancesIds() + setattr(cls, "getinstancesIds", getinstancesIds) def getinstanceByName(self, name):
@@ -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)) setattr(cls, "getvars", getvars)
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]()})
+ 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) - varlist = content[-1]["value"]
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_type = PLCOpenClasses["dataType"]()
- if type in [x for x,y in TypeHierarchy_list if not x.startswith("ANY")]:
- var_type.setcontent({"name" : "string", "value" : PLCOpenClasses["elementaryTypes_string"]()})
- elif type == "WSTRING":
- var_type.setcontent({"name" : "wstring", "value" : PLCOpenClasses["elementaryTypes_wstring"]()})
- var_type.setcontent({"name" : type, "value" : None})
- derived_type = PLCOpenClasses["derivedTypes_derived"]()
- derived_type.setname(type)
- var_type.setcontent({"name" : "derived", "value" : derived_type})
- ft = PLCOpenClasses["formattedText"]()
- ft.settext(description)
+ ft = PLCOpenParser.CreateElement("documentation", "variable") + ft.setanyText(description) - 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()
- variables = varlist["value"].getvariable()
+ variables = varlist.getvariable() 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: - vartype_content["value"].setname(new_type)
+ vartype_content.setname(new_type) 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()
- variables = varlist["value"].getvariable()
+ 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:
+ if vartype_content.getLocalTag() == "derived" and vartype_content.getname() == var_type: + if len(varlist.getvariable()) == 0: + self.interface.remove(varlist) - if len(varlist["value"].getvariable()) == 0:
- content.remove(varlist)
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)):
@@ -1444,22 +1269,22 @@
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.transitions.settransition([])
- transition = PLCOpenClasses["transitions_transition"]()
+ transition = PLCOpenParser.CreateElement("transition", "transitions") + self.transitions.appendtransition(transition) - transition.setbodyType(type)
- transition.settext(":= ;")
- transition.settext("\tST\t%s"%name)
- self.transitions.appendtransition(transition)
+ transition.setbodyType(body_type) + transition.setanyText(":= ;") + elif body_type == "IL": + transition.setanyText("\tST\t%s"%name) setattr(cls, "addtransition", addtransition)
def gettransition(self, name):
+ if self.transitions is not None: for transition in self.transitions.gettransition():
if transition.getname() == name:
@@ -1467,42 +1292,40 @@
setattr(cls, "gettransition", gettransition)
def gettransitionList(self):
+ if self.transitions is not None: return self.transitions.gettransition()
setattr(cls, "gettransitionList", gettransitionList)
def removetransition(self, name):
- transitions = self.transitions.gettransition()
+ if self.transitions is not None: - 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())
+ self.transitions.remove(transition)
raise ValueError, _("Transition with name %s doesn't exist!")%name
setattr(cls, "removetransition", removetransition)
- def addaction(self, name, type):
+ def addaction(self, name, body_type): + if self.actions is None: self.actions.setaction([])
- action = PLCOpenClasses["actions_action"]()
+ action = PLCOpenParser.CreateElement("action", "actions") + self.actions.appendaction(action) - action.setbodyType(type)
- self.actions.appendaction(action)
+ action.setbodyType(body_type) setattr(cls, "addaction", addaction)
def getaction(self, name):
+ if self.actions is not None: for action in self.actions.getaction():
if action.getname() == name:
@@ -1516,28 +1339,26 @@
setattr(cls, "getactionList", getactionList)
def removeaction(self, name):
- actions = self.actions.getaction()
+ if self.actions is not None: - 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())
+ self.actions.remove(action)
raise ValueError, _("Action with name %s doesn't exist!")%name
setattr(cls, "removeaction", removeaction)
def updateElementName(self, old_name, new_name):
+ 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_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 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 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:
+ for variable in content.getvariable(): + if variable.getaddress() == address: + content.remove(variable) setattr(cls, "removeVariableByAddress", removeVariableByAddress)
def removeVariableByFilter(self, address_model):
+ 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)
+ content.remove(variable) setattr(cls, "removeVariableByFilter", removeVariableByFilter)
def Search(self, criteria, parent_infos=[]):
@@ -1599,11 +1418,11 @@
if self.interface is not None:
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())]: 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 @@
setattr(cls, "Search", Search)
-def setbodyType(self, type):
- self.body.setcontent({"name" : "IL", "value" : PLCOpenClasses["formattedText"]()})
- self.body.setcontent({"name" : "ST", "value" : PLCOpenClasses["formattedText"]()})
- self.body.setcontent({"name" : "LD", "value" : PLCOpenClasses["body_LD"]()})
- self.body.setcontent({"name" : "FBD", "value" : PLCOpenClasses["body_FBD"]()})
- 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")) raise ValueError, "%s isn't a valid body type!"%type
- 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) 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)):
@@ -1688,7 +1499,7 @@
self.body.updateElementAddress(address_model, new_leading)
-cls = PLCOpenClasses.get("transitions_transition", None)
+cls = PLCOpenParser.GetElementClass("transition", "transitions") setattr(cls, "setbodyType", setbodyType)
setattr(cls, "getbodyType", getbodyType)
@@ -1716,7 +1527,7 @@
setattr(cls, "Search", Search)
-cls = PLCOpenClasses.get("actions_action", None)
+cls = PLCOpenParser.GetElementClass("action", "actions") setattr(cls, "setbodyType", setbodyType)
setattr(cls, "getbodyType", getbodyType)
@@ -1744,27 +1555,9 @@
setattr(cls, "Search", Search)
-cls = PLCOpenClasses.get("body", None)
+cls = PLCOpenParser.GetElementClass("body") 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) 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()) 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)
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) - 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"]:
- for element in self.content["value"].getcontent():
- instances.append(element["value"])
+ if self.content.getLocalTag() in ["LD","FBD","SFC"]: + return self.content.getcontent() - 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) - 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
- 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]) - raise TypeError, _("%s body don't have instances!")%self.content["name"]
- setattr(cls, "getcontentRandomInstance", getcontentRandomInstance)
+ raise TypeError, _("%s body don't have instances!")%self.content.getLocalTag() + setattr(cls, "getcontentInstancesIds", getcontentInstancesIds) 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"]
+ if self.content.getLocalTag() in ["LD","FBD","SFC"]: + instance = instance_by_name_xpath(self.content) - 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) + self.content.remove(instance[0]) raise ValueError, _("Instance with id %d doesn't exist!")%id
- 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)
- if self.content["name"] in ["IL","ST"]:
- self.content["value"].settext(text)
+ if self.content.getLocalTag() in ["IL","ST"]: + self.content.setanyText(text) - 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)
- if self.content["name"] in ["IL","ST"]:
- return self.content["value"].gettext()
+ if self.content.getLocalTag() in ["IL","ST"]: + return self.content.getanyText() - 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) - 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) - 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) - 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]) - 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)) setattr(cls, "Search", Search)
@@ -1982,15 +1771,11 @@
def _filterConnections(connectionPointIn, localId, connections):
in_connections = connectionPointIn.getconnections()
if in_connections is not None:
- 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)):
- 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):
@@ -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) setattr(cls, "getx", getx)
setattr(cls, "gety", gety)
@@ -2090,151 +1874,14 @@
setattr(cls, "Search", _SearchInElement)
-def _getexecutionOrder(instance, specific_values):
- executionOrder = instance.getexecutionOrderId()
- if executionOrder is None:
- 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()}
- infos["name"] = instance.getformalParameter()
- MODIFIERS_FUNCTIONS.get(modifiers, lambda x, y: None)(instance, infos)
- 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)
-def _getelementinfos(instance):
- return {"id": instance.getlocalId(),
- "height": instance.getheight(),
- "width": instance.getwidth(),
-def _getvariableinfosFunction(type, input, output):
- def getvariableinfos(self):
- infos = _getelementinfos(self)
- specific_values = infos["specific_values"]
- specific_values["name"] = self.getexpression()
- _getexecutionOrder(self, specific_values)
- infos["inputs"].append(_getconnectioninfos(self, self.connectionPointIn, True, "input"))
- infos["outputs"].append(_getconnectioninfos(self, self.connectionPointOut, False, "output"))
- infos["inputs"].append(_getconnectioninfos(self, self.connectionPointIn, True, "default"))
- infos["outputs"].append(_getconnectioninfos(self, self.connectionPointOut, False, "default"))
- return getvariableinfos
-def _getconnectorinfosFunction(type):
- def getvariableinfos(self):
- infos = _getelementinfos(self)
- 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 getvariableinfos
-def _getpowerrailinfosFunction(type):
- def getpowerrailinfos(self):
- infos = _getelementinfos(self)
- 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 getpowerrailinfos
-def _getldelementinfosFunction(type):
- def getldelementinfos(self):
- infos = _getelementinfos(self)
- specific_values = infos["specific_values"]
- specific_values["name"] = self.getvariable()
- _getexecutionOrder(self, specific_values)
- specific_values["negated"] = self.getnegated()
- specific_values["edge"] = self.getedge()
- specific_values["storage"] = self.getstorage()
- infos["inputs"].append(_getconnectioninfos(self, self.connectionPointIn, True))
- infos["outputs"].append(_getconnectioninfos(self, self.connectionPointOut))
- 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)]
- 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"])
- 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 getdivergenceinfos
-cls = _initElementClass("comment", "commonObjects_comment")
+cls = _initElementClass("comment", "commonObjects")
- infos = _getelementinfos(self)
- infos["type"] = "comment"
- infos["specific_values"]["content"] = self.getcontentText()
- setattr(cls, "getinfos", getinfos)
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") def getBoundingBox(self):
bbox = _getBoundingBox(self)
@@ -2258,19 +1905,6 @@
setattr(cls, "getBoundingBox", getBoundingBox)
- 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))
- setattr(cls, "getinfos", getinfos)
def updateElementName(self, old_name, new_name):
if self.typeName == old_name:
@@ -2308,150 +1942,83 @@
setattr(cls, "Search", Search)
-cls = _initElementClass("leftPowerRail", "ldObjects_leftPowerRail")
- setattr(cls, "getinfos", _getpowerrailinfosFunction("leftPowerRail"))
+_initElementClass("leftPowerRail", "ldObjects") +_initElementClass("rightPowerRail", "ldObjects", "multiple") -cls = _initElementClass("rightPowerRail", "ldObjects_rightPowerRail", "multiple")
- setattr(cls, "getinfos", _getpowerrailinfosFunction("rightPowerRail"))
+def _UpdateLDElementName(self, old_name, new_name): + if self.variable == old_name: + self.variable = new_name -cls = _initElementClass("contact", "ldObjects_contact", "single")
- 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)
+def _UpdateLDElementAddress(self, address_model, new_leading): + self.variable = update_address(self.variable, address_model, new_leading) -cls = _initElementClass("coil", "ldObjects_coil", "single")
+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") - 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)
+ setattr(cls, "updateElementName", _UpdateLDElementName) + setattr(cls, "updateElementAddress", _UpdateLDElementAddress) + setattr(cls, "Search", _getSearchInLDElement("contact")) -cls = _initElementClass("step", "sfcObjects_step", "single")
+cls = _initElementClass("coil", "ldObjects", "single")
- infos = _getelementinfos(self)
- 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)
- setattr(cls, "getinfos", getinfos)
+ setattr(cls, "updateElementName", _UpdateLDElementName) + setattr(cls, "updateElementAddress", _UpdateLDElementAddress) + setattr(cls, "Search", _getSearchInLDElement("coil")) +cls = _initElementClass("step", "sfcObjects", "single") 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)
- def compatibility(self, tree):
- 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")
+cls = _initElementClass("transition", "sfcObjects")
- infos = _getelementinfos(self)
- infos["type"] = "transition"
- specific_values = infos["specific_values"]
- priority = self.getpriority()
- 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)
+ def setconditionContent(self, condition_type, value): + if self.condition is None: + if condition_type == "connection": + condition = PLCOpenParser.CreateElement("connectionPointIn", "condition") - specific_values["condition"] = condition["value"]
- infos["inputs"].append(_getconnectioninfos(self, self.connectionPointIn, True))
- infos["outputs"].append(_getconnectioninfos(self, self.connectionPointOut))
- setattr(cls, "getinfos", getinfos)
- def setconditionContent(self, type, value):
- if type == "reference":
- condition = PLCOpenClasses["condition_reference"]()
+ condition = PLCOpenParser.CreateElement(condition_type, "condition") + self.condition.setcontent(condition) + if condition_type == "reference":
- condition = PLCOpenClasses["condition_inline"]()
- condition.setcontent({"name" : "ST", "value" : PLCOpenClasses["formattedText"]()})
+ elif condition_type == "inline": + condition.setcontent(PLCOpenParser.CreateElement("ST", "inline")) - 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 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 setattr(cls, "getconditionContent", getconditionContent)
def getconditionConnection(self):
+ if self.condition is not None: content = self.condition.getcontent()
- if content["name"] == "connectionPointIn":
- return content["value"]
+ if content.getLocalTag() == "connectionPointIn": 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))
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 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 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()
setattr(cls, "getconnections", getconnections)
@@ -2510,90 +2079,61 @@
parent_infos = parent_infos + ["transition", self.getlocalId()]
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"])) setattr(cls, "Search", Search)
+_initElementClass("selectionDivergence", "sfcObjects", "single") +_initElementClass("selectionConvergence", "sfcObjects", "multiple") +_initElementClass("simultaneousDivergence", "sfcObjects", "single") +_initElementClass("simultaneousConvergence", "sfcObjects", "multiple") -cls = _initElementClass("selectionDivergence", "sfcObjects_selectionDivergence", "single")
- setattr(cls, "getinfos", _getdivergenceinfosFunction(True, False))
-cls = _initElementClass("selectionConvergence", "sfcObjects_selectionConvergence", "multiple")
- setattr(cls, "getinfos", _getdivergenceinfosFunction(False, False))
-cls = _initElementClass("simultaneousDivergence", "sfcObjects_simultaneousDivergence", "single")
+cls = _initElementClass("jumpStep", "sfcObjects", "single") - setattr(cls, "getinfos", _getdivergenceinfosFunction(True, True))
-cls = _initElementClass("simultaneousConvergence", "sfcObjects_simultaneousConvergence", "multiple")
- setattr(cls, "getinfos", _getdivergenceinfosFunction(False, True))
-cls = _initElementClass("jumpStep", "sfcObjects_jumpStep", "single")
- infos = _getelementinfos(self)
- infos["specific_values"]["target"] = self.gettargetName()
- infos["inputs"].append(_getconnectioninfos(self, self.connectionPointIn, True))
- setattr(cls, "getinfos", getinfos)
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)
+cls = PLCOpenParser.GetElementClass("action", "actionBlock") - 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")
- node = CreateNode("relPosition")
- NodeSetAttr(node, "x", "0")
- NodeSetAttr(node, "y", "0")
- tree.childNodes.insert(0, node)
- setattr(cls, "compatibility", compatibility)
def setreferenceName(self, name):
+ if self.reference is not None: self.reference.setname(name)
setattr(cls, "setreferenceName", setreferenceName)
def getreferenceName(self):
+ if self.reference is not None: return self.reference.getname()
setattr(cls, "getreferenceName", getreferenceName)
def setinlineContent(self, content):
- 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 is not None: return self.inline.gettext()
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 is not None: self.inline.updateElementName(old_name, new_name)
setattr(cls, "updateElementName", updateElementName)
def updateElementAddress(self, address_model, new_leading):
+ if self.reference is not None: self.reference.setname(update_address(self.reference.getname(), address_model, new_leading))
+ if self.inline is not None: self.inline.updateElementAddress(address_model, new_leading)
setattr(cls, "updateElementAddress", updateElementAddress)
@@ -2609,38 +2149,24 @@
setattr(cls, "Search", Search)
-cls = _initElementClass("actionBlock", "commonObjects_actionBlock", "single")
+cls = _initElementClass("actionBlock", "commonObjects", "single") - def compatibility(self, tree):
- for child in tree.childNodes[:]:
- if child.nodeName == "connectionPointOut":
- tree.childNodes.remove(child)
- setattr(cls, "compatibility", compatibility)
- infos = _getelementinfos(self)
- infos["type"] = "actionBlock"
- infos["specific_values"]["actions"] = self.getactions()
- infos["inputs"].append(_getconnectioninfos(self, self.connectionPointIn, True))
- setattr(cls, "getinfos", getinfos)
def setactions(self, 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.setreferenceName(params["value"])
+ action.setreferenceName(params.value) - 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)
@@ -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()
params["duration"] = duration
indicator = action.getindicator()
+ if indicator is not None: params["indicator"] = indicator
@@ -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()])
+ return _Search([("expression", self.expression)], criteria, parent_infos + ["io_variable", self.getlocalId()]) -cls = _initElementClass("inVariable", "fbdObjects_inVariable")
+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") - 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)
+ setattr(cls, "updateElementName", _UpdateIOElementName) + setattr(cls, "updateElementAddress", _UpdateIOElementAddress) setattr(cls, "Search", _SearchInIOVariable)
-cls = _initElementClass("outVariable", "fbdObjects_outVariable", "single")
+cls = _initElementClass("outVariable", "fbdObjects", "single") - 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)
+ setattr(cls, "updateElementName", _UpdateIOElementName) + setattr(cls, "updateElementAddress", _UpdateIOElementAddress) setattr(cls, "Search", _SearchInIOVariable)
-cls = _initElementClass("inOutVariable", "fbdObjects_inOutVariable", "single")
+cls = _initElementClass("inOutVariable", "fbdObjects", "single") - 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)
+ 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")
+cls = _initElementClass("continuation", "commonObjects") - setattr(cls, "getinfos", _getconnectorinfosFunction("continuation"))
setattr(cls, "Search", _SearchInConnector)
def updateElementName(self, old_name, new_name):
@@ -2746,9 +2251,8 @@
setattr(cls, "updateElementName", updateElementName)
-cls = _initElementClass("connector", "commonObjects_connector", "single")
+cls = _initElementClass("connector", "commonObjects", "single") - setattr(cls, "getinfos", _getconnectorinfosFunction("connector"))
setattr(cls, "Search", _SearchInConnector)
def updateElementName(self, old_name, new_name):
@@ -2756,15 +2260,16 @@
setattr(cls, "updateElementName", updateElementName)
-cls = PLCOpenClasses.get("connection", None)
+cls = PLCOpenParser.GetElementClass("connection") def setpoints(self, points):
- position = PLCOpenClasses["position"]()
+ position = PLCOpenParser.CreateElement("position", "connection") - self.position.append(position)
+ positions.append(position) + self.position = positions setattr(cls, "setpoints", setpoints)
@@ -2774,110 +2279,115 @@
setattr(cls, "getpoints", getpoints)
-cls = PLCOpenClasses.get("connectionPointIn", None)
+cls = PLCOpenParser.GetElementClass("connectionPointIn") def setrelPositionXY(self, x, y):
- self.relPosition = PLCOpenClasses["position"]()
+ self.relPosition = PLCOpenParser.CreateElement("relPosition", "connectionPointIn") setattr(cls, "setrelPositionXY", setrelPositionXY)
def getrelPositionXY(self):
+ if self.relPosition is not None: return self.relPosition.getx(), self.relPosition.gety()
- return self.relPosition
+ return self.relPosition setattr(cls, "getrelPositionXY", getrelPositionXY)
- self.content = {"name" : "connection", "value" : [PLCOpenClasses["connection"]()]}
- self.content["value"].append(PLCOpenClasses["connection"]())
+ self.append(PLCOpenParser.CreateElement("connection", "connectionPointIn")) setattr(cls, "addconnection", addconnection)
def removeconnection(self, idx):
- self.content["value"].pop(idx)
- if len(self.content["value"]) == 0:
+ if len(self.content) > idx: + self.remove(self.content[idx]) setattr(cls, "removeconnection", removeconnection)
def removeconnections(self):
setattr(cls, "removeconnections", removeconnections)
+ connection_xpath = PLCOpen_XPath("ppx:connection") + connection_by_position_xpath = PLCOpen_XPath("ppx:connection[position()=$pos]") def getconnections(self):
- return self.content["value"]
+ return connection_xpath(self) setattr(cls, "getconnections", getconnections)
- def setconnectionId(self, idx, id):
- self.content["value"][idx].setrefLocalId(id)
+ def getconnection(self, idx): + connection = connection_by_position_xpath(self, pos=idx+1) + if len(connection) > 0: + 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):
- return self.content["value"][idx].getrefLocalId()
+ connection = self.getconnection(idx) + if connection is not None: + return connection.getrefLocalId() setattr(cls, "getconnectionId", getconnectionId)
def setconnectionPoints(self, idx, points):
- 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):
- return self.content["value"][idx].getpoints()
+ connection = self.getconnection(idx) + if connection is not None: + return connection.getpoints() setattr(cls, "getconnectionPoints", getconnectionPoints)
def setconnectionParameter(self, idx, parameter):
- 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):
- return self.content["value"][idx].getformalParameter()
+ connection = self.getconnection(idx) + if connection is not None: + return connection.getformalParameter() setattr(cls, "getconnectionParameter", getconnectionParameter)
-cls = PLCOpenClasses.get("connectionPointOut", None)
+cls = PLCOpenParser.GetElementClass("connectionPointOut") def setrelPositionXY(self, x, y):
- self.relPosition = PLCOpenClasses["position"]()
+ self.relPosition = PLCOpenParser.CreateElement("relPosition", "connectionPointOut") setattr(cls, "setrelPositionXY", setrelPositionXY)
def getrelPositionXY(self):
+ if self.relPosition is not None: return self.relPosition.getx(), self.relPosition.gety()
setattr(cls, "getrelPositionXY", getrelPositionXY)
-cls = PLCOpenClasses.get("value", None)
+cls = PLCOpenParser.GetElementClass("value") def setvalue(self, value):
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") - 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)
- 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
-cls = PLCOpenClasses.get("value_arrayValue", None)
+cls = PLCOpenParser.GetElementClass("arrayValue", "value") arrayValue_model = re.compile("([0-9]*)\((.*)\)$")
def setvalue(self, value):
for item in extractValues(value[1:-1]):
- element = PLCOpenClasses["arrayValue_value"]()
+ element = PLCOpenParser.CreateElement("value", "arrayValue") result = arrayValue_model.match(item)
@@ -2910,14 +2420,18 @@
element.setvalue(groups[1].strip())
- self.value.append(element)
+ elements.append(element) setattr(cls, "setvalue", setvalue)
for element in self.value:
- repetition = element.getrepetitionValue()
- if repetition is not None and int(repetition) > 1:
+ repetition = int(element.getrepetitionValue()) value = element.getvalue()
@@ -2927,20 +2441,21 @@
return "[%s]"%", ".join(values)
setattr(cls, "getvalue", getvalue)
-cls = PLCOpenClasses.get("value_structValue", None)
+cls = PLCOpenParser.GetElementClass("structValue", "value") structValue_model = re.compile("(.*):=(.*)")
def setvalue(self, value):
for item in extractValues(value[1:-1]):
result = structValue_model.match(item)
- 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) setattr(cls, "setvalue", setvalue)
@@ -2949,3 +2464,4 @@
values.append("%s := %s"%(element.getmember(), element.getvalue()))
return "(%s)"%", ".join(values)
setattr(cls, "getvalue", getvalue)
--- 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 xml.dom import minidom
from xml.sax.saxutils import escape, unescape, quoteattr
+from collections import OrderedDict @@ -533,28 +535,33 @@
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] - if tree.nodeName in ["#text", "#cdata-section"]:
- return unicode(unescape(tree.data))
+ return GetTextElement(tree).text - def GenerateAny(value, name=None, indent=0):
- if isinstance(value, (StringType, UnicodeType)):
- value = value.decode("utf-8")
- return u'<![CDATA[%s]]>\n' % value
+ def GenerateAny(tree, value): + GetTextElement(tree).text = etree.CDATA(value) + if infos["namespace"][0] == "##any": - return value.toprettyxml(indent=" "*indent, encoding="utf-8")
+ element_name = "{%s}p" % infos["namespace"][0] + p = etree.Element(element_name) + p.text = etree.CDATA("")
- "check": lambda x: isinstance(x, (StringType, UnicodeType, minidom.Node))
+ "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)
+ if infos["minOccurs"] == 1: + element_name = factory.etreeNamespaceFormat % infos["name"] + if infos["elmt_type"]["type"] == SIMPLETYPE: + value = etree.Element(element_name) + value.text = (infos["elmt_type"]["generate"](infos["elmt_type"]["initial"]()))
- elif infos["minOccurs"] == 1 and infos["maxOccurs"] == 1:
- return infos["elmt_type"]["initial"]()
+ value = infos["elmt_type"]["initial"]() + if infos["type"] != ANY: + DefaultElementClass.__setattr__(value, "tag", element_name) + return [initial_value() for i in xrange(infos["minOccurs"])] - return [infos["elmt_type"]["initial"]() for i in xrange(infos["minOccurs"])]
-def HandleError(message, raise_exception):
- raise ValueError(message)
-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)
- return infos["elmt_type"]["check"](value)
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) 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))
-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))
- 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)]}
- return {"name": tree.nodeName,
- "value": [infos["elmt_type"]["extract"](tree)]}
- return {"name": tree.nodeName,
- "value": infos["elmt_type"]["extract"](tree)}
def GenerateContentInfos(factory, name, choices):
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())) content_name, infos = choices[0]
@@ -698,140 +674,15 @@
for i in xrange(infos["minOccurs"]):
for element_infos in infos["elements"]:
- value = GetElementInitialValue(factory, element_infos)
- if element_infos["type"] == CHOICE:
- content_value.append(value)
- content_value.append({"name": element_infos["name"], "value": value})
+ content_value.extend(GetElementInitialValue(factory, element_infos)) 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)
- return CheckElementValue(factory, value["name"], infos, value["value"], False)
- elif len(value["value"]) > 0:
- infos = choices_dict.get(value["value"][0]["name"], 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"])
- while element_idx < len(value["value"]):
- for element_infos in infos["elements"]:
- if element_infos["type"] == CHOICE:
- if element_idx < len(value["value"]):
- for choice in element_infos["choices"]:
- if choice["name"] == value["value"][element_idx]["name"]:
- element_value = value["value"][element_idx]["value"]
- 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'")
- if element_idx < len(value["value"]) and element_infos["name"] == value["value"][element_idx]["name"]:
- element_value = value["value"][element_idx]["value"]
- if not CheckElementValue(factory, element_infos["name"], element_infos, element_value, False):
- raise ValueError("Invalid sequence value in attribute 'content'")
- if sequence_number < infos["minOccurs"] or infos["maxOccurs"] != "unbounded" and sequence_number > infos["maxOccurs"]:
- raise ValueError("Invalid sequence value in attribute 'content'")
- for element_name, infos in choices:
- if element_name == "sequence":
- for element in infos["elements"]:
- if element["minOccurs"] > 0:
- def ExtractContent(tree, content):
- infos = choices_dict.get(tree.nodeName, 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])]}
- return {"name": "sequence",
- "value": [ExtractContentElement(factory, tree, element_infos, None)]}
- return ExtractContentElement(factory, tree, infos, content)
- for choice_name, infos in choices:
- if infos["type"] == "sequence":
- for element_infos in infos["elements"]:
- if element_infos["type"] == CHOICE:
- 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])]}
- return {"name": "sequence",
- "value": [element_infos["elmt_type"]["extract"](tree, None)]}
- raise ValueError("Invalid element \"%s\" for content!" % tree.nodeName)
- def GenerateContent(value, name=None, indent=0):
- if value["name"] != "sequence":
- infos = choices_dict.get(value["name"], 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)
- text += infos["elmt_type"]["generate"](value["value"], value["name"], indent)
- elif len(value["value"]) > 0:
- infos = choices_dict.get(value["value"][0]["name"], 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"])
- 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)
- text += element_infos["elmt_type"]["generate"](element_value["value"], element_infos["name"], indent)
+ "choices_xpath": etree.XPath(choices_xpath, namespaces=factory.NSMAP), "initial": GetContentInitial,
- "extract": ExtractContent,
- "generate": GenerateContent
#-------------------------------------------------------------------------------
@@ -901,9 +752,11 @@
self.XMLClassDefinitions = {}
self.DefinedNamespaces = {}
self.SchemaNamespace = None
self.TargetNamespace = None
+ self.etreeNamespaceFormat = "%s" self.CurrentCompilations = []
@@ -914,6 +767,8 @@
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 raise ValueError("Invalid attribute \"%s\" for member \"%s\"!" % (qualified_name, node.nodeName))
@@ -1063,20 +920,63 @@
+ def AddEquivalentClass(self, 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] + 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) + 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 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
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
@@ -1086,7 +986,12 @@
return self.CreateClass(name, parent, typeinfos)
elif typeinfos["type"] == SIMPLETYPE:
+ 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])] + 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 @@
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)
- 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(DefaultElementClass) 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)
- classmembers[attrname] = infos["initial"]()
classmembers["set%s"%attrname] = generateSetMethod(attrname)
classmembers["get%s"%attrname] = generateGetMethod(attrname)
@@ -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)
elmtname = element["name"]
if element["elmt_type"] == "tag":
infos = GenerateTagInfos(element)
+ self.AddToLookupClass(element["name"], name, DefaultElementClass) infos = self.ExtractTypeInfos(element["name"], name, element["elmt_type"])
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)
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"]()
- 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,
- "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) @@ -1281,69 +1193,6 @@
-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 classExtractfunction
-Method that generate the method for loading an xml tree by following the
-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 optional_attributes.get(name, False):
- return object.__setattr__(self, name, None)
- 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)
- 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)
- 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)
- raise AttributeError("'%s' can't have an attribute '%s'." % (self.__class__.__name__, name))
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"],
-def GetStructure(classinfos):
+def GetStructurePattern(classinfos): + base_structure_pattern = ( + classinfos["base"].StructurePattern.pattern[:-1] + if classinfos.has_key("base") else "") for element in classinfos["elements"]:
if element["type"] == ANY:
@@ -1380,7 +1232,7 @@
for infos in element["choices"]:
if infos["type"] == "sequence":
- structure = "(?:%s)" % GetStructure(infos)
+ structure = "(?:%s)" % GetStructurePattern(infos) structure = "%s " % infos["name"]
choices.append(ComputeMultiplicity(structure, infos))
@@ -1390,170 +1242,139 @@
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) + "$") 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 getStructureMethod
+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 loading an xml tree by following the
-def generateLoadXMLTree(factory, classinfos):
+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.compatibility(tree)
- 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)
- 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))
- for node in tree.childNodes:
- if name == "#text" and node.data.strip() == "" or name == "#comment":
- 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)])
- getattr(self, name).append(elements[name]["elmt_type"]["extract"](node))
+ def getattrMethod(self, name): + if attributes.has_key(name): + attribute_infos = attributes[name] + attribute_infos["attr_type"] = FindTypeInfos(factory, attribute_infos["attr_type"]) + 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) + 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: + 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) + 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), - 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)])
- getattr(self, "text").append(elements["text"]["elmt_type"]["extract"](node))
- 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))
- 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
- content.append(elements["content"]["elmt_type"]["extract"](node, content))
- object.__setattr__(self, "content", elements["content"]["elmt_type"]["extract"](node, content))
- return loadXMLTreeMethod
+ value = self.find(element_name) + if element_infos["elmt_type"]["type"] == SIMPLETYPE: + return element_infos["elmt_type"]["extract"](value.text, extract=False) + elif classinfos.has_key("base"): + return classinfos["base"].__getattr__(self, name) + return DefaultElementClass.__getattribute__(self, name)
-Method that generates the method for generating an xml text by following the
-def generateGenerateXMLText(factory, classinfos):
- def generateXMLTextMethod(self, name, indent=0, extras={}, derived=False):
- ind1, ind2 = getIndent(indent, name)
- text = ind1 + u'<%s' % name
+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) + elif attribute_infos.has_key("fixed"): + return self.set(name, attribute_infos["attr_type"]["generate"](value)) - 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))
- for attr in classinfos["attributes"]:
- if attr["use"] != "prohibited":
- attr["attr_type"] = FindTypeInfos(factory, attr["attr_type"])
- value = getattr(self, attr["name"], None)
- computed_value = attr["attr_type"]["generate"](value)
- 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
+ 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) + prefix = ("%s:" % factory.TargetNamespace + if factory.TargetNamespace is not None else "") + element_xpath = (prefix + name + else elements["content"]["elmt_type"]["choices_xpath"].path) + for element in self.xpath(element_xpath, namespaces=factory.NSMAP): + element_idx = elements.keys().index(name) + previous_elements_xpath = "|".join(map( + else elements["content"]["elmt_type"]["choices_xpath"].path, + elements.keys()[:element_idx])) + insertion_point = len(self.xpath(previous_elements_xpath, namespaces=factory.NSMAP)) - if not first and not self.singleLineAttributes:
- text += u'\n%s' % (ind2)
- text += ' %s=%s' % (attr["name"], quoteattr(computed_value))
- if classinfos.has_key("base"):
- first, new_text = classinfos["base"].generateXMLText(self, name, indent, extras, True)
+ if not isinstance(value, ListType): + 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) + self.insert(insertion_point, element) + elif classinfos.has_key("base"): + return classinfos["base"].__setattr__(self, name, value)
- 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:
- text += element["elmt_type"]["generate"](value, element["name"], indent + 1)
- elif element["minOccurs"] == 1 and element["maxOccurs"] == 1:
- if element["name"] == "content" and element["elmt_type"]["type"] == SIMPLETYPE:
- text += element["elmt_type"]["generate"](value)
- text += element["elmt_type"]["generate"](value, element["name"], indent + 1)
- if first and len(value) > 0:
- text += element["elmt_type"]["generate"](item, element["name"], indent + 1)
- text += ind1 + u'</%s>\n' % (name)
- return generateXMLTextMethod
+ raise AttributeError("'%s' can't have an attribute '%s'." % (self.__class__.__name__, name)) 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) attr = getattr(self, parts[0], None)
@@ -1622,7 +1443,7 @@
return attr.getElementInfos(parts[0], parts[1])
elif elements.has_key("content"):
- return self.content["value"].getElementInfos(name, path)
+ return self.content.getElementInfos(name, path) elif classinfos.has_key("base"):
classinfos["base"].getElementInfos(name, path)
@@ -1640,15 +1461,9 @@
- 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"])])
- 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"):
- 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 elements["content"]["minOccurs"] == 0:
raise ValueError("\"content\" element is required!")
@@ -1723,20 +1538,21 @@
def generateInitMethod(factory, classinfos):
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))
- 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: + 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) def generateSetMethod(attr):
@@ -1753,18 +1569,16 @@
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) raise ValueError("Invalid class attribute!")
- if infos.has_key("default"):
- setattr(self, attr, extract(infos["default"], False))
- setattr(self, attr, initial())
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]) - raise ValueError("\"%s\" value isn't valid!" % attr)
+ attr_list[-1].addnext(value) raise ValueError("There can't be more than %d values in \"%s\"!" % (maxOccurs, attr))
@@ -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]) + attr_list[0].addprevious(value) - raise ValueError("\"%s\" value isn't valid!" % attr)
+ attr_list[min(index - 1, len(attr_list) - 1)].addnext(value) raise ValueError("There can't be more than %d values in \"%s\"!" % (maxOccurs, attr))
@@ -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}
+ 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 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) 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) 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]) raise ValueError("There can't be less than %d values in \"%s\"!" % (minOccurs, attr))
@@ -1857,16 +1676,135 @@
-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("$") + return etree.QName(self.tag).localname + 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): + "%s " % etree.QName(child.tag).localname + 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 element_class[0] +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: + name if targetNamespace != uri else None: uri + for name, uri in namespaces.iteritems()} + 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) + def Dumps(self, xml_obj): + return etree.tostring(xml_obj) + def Loads(self, xml_string): + return etree.fromstring(xml_string, self) + if self.BaseClass is not None: + root = self.makeelement( + self.DefaultNamespaceFormat % self.BaseClass[0], + 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, + 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]() + raise ValueError, "No corresponding class found!" + new_element = element_class() + DefaultElementClass.__setattr__(new_element, "tag", self.DefaultNamespaceFormat % element_tag) +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]
- UpdateXMLClassGlobals(ComputedClasses)
+ 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.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) -def UpdateXMLClassGlobals(classes):
- globals().update(classes)