--- a/PLCControler.py Tue Jan 22 10:53:34 2008 +0100
+++ b/PLCControler.py Tue Jan 22 10:57:41 2008 +0100
@@ -22,7 +22,6 @@
#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 minixsv import pyxsval
from xml.dom import minidom
from types import StringType, UnicodeType
import cPickle
@@ -43,28 +42,6 @@
ScriptDirectory = os.path.split(os.path.realpath(__file__))[0]
-"""
-pyxsval is not complete and the parts that are not supported print some error
-reports. This class is used for not displaying them
-"""
-class HolePseudoFile:
- """ Base class for file like objects to facilitate StdOut for the Shell."""
- def __init__(self, output = None):
- if output is None: output = []
- self.output = output
-
- def writelines(self, l):
- map(self.write, l)
-
- def write(self, s):
- pass
-
- def flush(self):
- pass
-
- def isatty(self):
- return false
-
#-------------------------------------------------------------------------------
# Undo Buffer for PLCOpenEditor
#-------------------------------------------------------------------------------
@@ -164,7 +141,6 @@
# Reset PLCControler internal variables
def Reset(self):
- self.VerifyXML = False
self.Project = None
self.ProjectBuffer = None
self.Buffering = False
@@ -193,8 +169,8 @@
# Create the project
self.Project = plcopen.project()
properties["creationDateTime"] = datetime(*localtime()[:6])
- self.Project.setFileHeader(properties)
- self.Project.setContentHeader(properties)
+ self.Project.setfileHeader(properties)
+ self.Project.setcontentHeader(properties)
self.SetFilePath("")
# Initialize the project buffer
self.ProjectBuffer = UndoBuffer(self.Copy(self.Project), False)
@@ -203,31 +179,31 @@
# Return project data type names
def GetProjectDataTypeNames(self):
if self.Project:
- return [datatype.getName() for datatype in self.Project.getDataTypes()]
+ return [datatype.getname() for datatype in self.Project.getdataTypes()]
return []
# Return project pou names
def GetProjectPouNames(self):
if self.Project:
- return [pou.getName() for pou in self.Project.getPous()]
+ return [pou.getname() for pou in self.Project.getpous()]
return []
# Return project pou names
def GetProjectConfigNames(self):
if self.Project:
- return [config.getName() for config in self.Project.getConfigurations()]
+ return [config.getName() for config in self.Project.getconfigurations()]
return []
# Return project pou variables
def GetProjectPouVariables(self, pou_name=None):
variables = []
- for pou in self.Project.getPous():
- if not pou_name or pou_name == pou.getName():
+ for pou in self.Project.getpous():
+ if not pou_name or pou_name == pou.getname():
variables.extend([var["Name"] for var in self.GetPouInterfaceVars(pou)])
- for transition in pou.getTransitionList():
- variables.append(transition.getName())
- for action in pou.getActionList():
- variables.append(action.getName())
+ for transition in pou.gettransitionList():
+ variables.append(transition.getname())
+ for action in pou.getactionList():
+ variables.append(action.getname())
return variables
# Return if project is saved
@@ -261,52 +237,52 @@
# Change project properties
def SetProjectProperties(self, name = None, properties = None):
if name != None:
- self.Project.setName(name)
+ self.Project.setname(name)
if properties != None:
- self.Project.setFileHeader(properties)
- self.Project.setContentHeader(properties)
+ self.Project.setfileHeader(properties)
+ self.Project.setcontentHeader(properties)
if name != None or properties != None:
self.BufferProject()
# Return project properties
def GetProjectProperties(self):
- properties = self.Project.getFileHeader()
- properties.update(self.Project.getContentHeader())
+ properties = self.Project.getfileHeader()
+ properties.update(self.Project.getcontentHeader())
return properties
# Return project informations
def GetProjectInfos(self):
if self.Project:
- infos = {"name": self.Project.getName(), "type": ITEM_PROJECT}
+ infos = {"name": self.Project.getname(), "type": ITEM_PROJECT}
datatypes = {"name": "Data Types", "type": ITEM_UNEDITABLE, "values":[]}
- for datatype in self.Project.getDataTypes():
- datatypes["values"].append({"name": datatype.getName(), "type": ITEM_DATATYPE, "values": []})
+ for datatype in self.Project.getdataTypes():
+ datatypes["values"].append({"name": datatype.getname(), "type": ITEM_DATATYPE, "values": []})
pou_types = {"function": {"name": "Functions", "type": ITEM_UNEDITABLE, "values":[]},
"functionBlock": {"name": "Function Blocks", "type": ITEM_UNEDITABLE, "values":[]},
"program": {"name": "Programs", "type": ITEM_UNEDITABLE, "values":[]}}
- for pou in self.Project.getPous():
- pou_type = pou.getPouType().getValue()
- pou_infos = {"name": pou.getName(), "type": ITEM_POU}
+ for pou in self.Project.getpous():
+ pou_type = pou.getpouType()
+ pou_infos = {"name": pou.getname(), "type": ITEM_POU}
pou_values = []
- if pou.getBodyType() == "SFC":
+ if pou.getbodyType() == "SFC":
transitions = []
- for transition in pou.getTransitionList():
- transitions.append({"name": transition.getName(), "type": ITEM_TRANSITION, "values": []})
+ for transition in pou.gettransitionList():
+ transitions.append({"name": transition.getname(), "type": ITEM_TRANSITION, "values": []})
pou_values.append({"name": "Transitions", "type": ITEM_UNEDITABLE, "values": transitions})
actions = []
- for action in pou.getActionList():
- actions.append({"name": action.getName(), "type": ITEM_ACTION, "values": []})
+ for action in pou.getactionList():
+ actions.append({"name": action.getname(), "type": ITEM_ACTION, "values": []})
pou_values.append({"name": "Actions", "type": ITEM_UNEDITABLE, "values": actions})
if pou_type in pou_types:
pou_infos["values"] = pou_values
pou_types[pou_type]["values"].append(pou_infos)
configurations = {"name": "Configurations", "type": ITEM_UNEDITABLE, "values": []}
- for config in self.Project.getConfigurations():
- config_name = config.getName()
+ for config in self.Project.getconfigurations():
+ config_name = config.getname()
config_infos = {"name": config_name, "type": ITEM_CONFIGURATION, "values": []}
resources = {"name": "Resources", "type": ITEM_UNEDITABLE, "values": []}
- for resource in config.getResource():
- resource_name = resource.getName()
+ for resource in config.getresource():
+ resource_name = resource.getname()
resource_infos = {"name": resource_name, "type": ITEM_RESOURCE, "values": []}
resources["values"].append(resource_infos)
config_infos["values"] = [resources]
@@ -322,24 +298,24 @@
# Reset the tree of user-defined pou cross-use
self.DataTypeUsingTree = {}
if self.Project:
- datatypes = self.Project.getDataTypes()
+ datatypes = self.Project.getdataTypes()
# Reference all the user-defined data type names and initialize the tree of
# user-defined data type cross-use
- datatypenames = [datatype.getName() for datatype in datatypes]
+ datatypenames = [datatype.getname() for datatype in datatypes]
for name in datatypenames:
self.DataTypeUsingTree[name] = []
# Analyze each data type
for datatype in datatypes:
- name = datatype.getName()
- basetype_content = datatype.getBaseType().getContent()
+ name = datatype.getname()
+ basetype_content = datatype.getbaseType().getcontent()
if basetype_content["name"] == "derived":
- basetype_name = basetype_content["value"].getName()
+ basetype_name = basetype_content["value"].getname()
if basetype_name in datatypenames and name not in self.DataTypeUsingTree[basetype_name]:
self.DataTypeUsingTree[basetype_name].append(name)
elif basetype_content["name"] in ["subrangeSigned", "subrangeUnsigned", "array"]:
- base_type = basetype_content["value"].baseType.getContent()
+ base_type = basetype_content["value"].baseType.getcontent()
if base_type["value"] is not None:
- basetype_name = base_type["value"].getName()
+ basetype_name = base_type["value"].getname()
if basetype_name in datatypenames and name not in self.DataTypeUsingTree[basetype_name]:
self.DataTypeUsingTree[basetype_name].append(name)
@@ -348,37 +324,37 @@
# Reset the tree of user-defined pou cross-use
self.PouUsingTree = {}
if self.Project:
- pous = self.Project.getPous()
+ pous = self.Project.getpous()
# Reference all the user-defined pou names and initialize the tree of
# user-defined pou cross-use
- pounames = [pou.getName() for pou in pous]
+ pounames = [pou.getname() for pou in pous]
for name in pounames:
self.PouUsingTree[name] = []
# Analyze each pou
for pou in pous:
- name = pou.getName()
+ name = pou.getname()
if pou.interface:
# Extract variables from every varLists
- for type, varlist in pou.getVars():
- for var in varlist.getVariable():
- vartype_content = var.getType().getContent()
+ for type, varlist in pou.getvars():
+ for var in varlist.getvariable():
+ vartype_content = var.gettype().getcontent()
if vartype_content["name"] == "derived":
- typename = vartype_content["value"].getName()
+ typename = vartype_content["value"].getname()
if typename in pounames and name not in self.PouUsingTree[typename]:
self.PouUsingTree[typename].append(name)
- bodytype = pou.getBodyType()
+ bodytype = pou.getbodyType()
# If pou is written in a graphical language
if bodytype in ["FBD","LD","SFC"]:
# Analyze each instance of the pou
- for instance in pou.getInstances():
- if isinstance(instance, plcopen.block):
- typename = instance.getTypeName()
+ for instance in pou.getinstances():
+ if isinstance(instance, plcopen.fbdObjects_block):
+ typename = instance.gettypeName()
# Update tree if there is a cross-use
if typename in pounames and name not in self.PouUsingTree[typename]:
self.PouUsingTree[typename].append(name)
# If pou is written in a textual language
elif bodytype in ["IL", "ST"]:
- text = pou.getText()
+ text = pou.gettext()
# Search if each pou is mentioned in the pou text
for typename in pounames:
typename_model = re.compile("[ \t\n]%s[ \t\n]"%typename)
@@ -450,14 +426,14 @@
# Add a Data Type to Project
def ProjectAddDataType(self, datatype_name):
# Add the pou to project
- self.Project.appendDataType(datatype_name)
+ self.Project.appenddataType(datatype_name)
self.RefreshDataTypeUsingTree()
self.RefreshDataTypes()
self.BufferProject()
# Remove a Data Type from project
def ProjectRemoveDataType(self, datatype_name):
- self.Project.removeDataType(datatype_name)
+ self.Project.removedataType(datatype_name)
self.RefreshDataTypeUsingTree()
self.RefreshDataTypes()
self.BufferProject()
@@ -465,7 +441,7 @@
# Add a Pou to Project
def ProjectAddPou(self, pou_name, pou_type, body_type):
# Add the pou to project
- self.Project.appendPou(pou_name, pou_type, body_type)
+ self.Project.appendpou(pou_name, pou_type, body_type)
if pou_type == "function":
self.SetPouInterfaceReturnType(pou_name, "BOOL")
self.RefreshPouUsingTree()
@@ -474,47 +450,47 @@
# Remove a Pou from project
def ProjectRemovePou(self, pou_name):
- self.Project.removePou(pou_name)
+ self.Project.removepou(pou_name)
self.RefreshPouUsingTree()
self.RefreshBlockTypes()
self.BufferProject()
# Add a configuration to Project
def ProjectAddConfiguration(self, config_name):
- self.Project.addConfiguration(config_name)
+ self.Project.addconfiguration(config_name)
self.BufferProject()
# Remove a configuration from project
def ProjectRemoveConfiguration(self, config_name):
- self.Project.removeConfiguration(config_name)
+ self.Project.removeconfiguration(config_name)
self.BufferProject()
# Add a resource to a configuration of the Project
def ProjectAddConfigurationResource(self, config_name, resource_name):
- self.Project.addConfigurationResource(config_name, resource_name)
+ self.Project.addconfigurationResource(config_name, resource_name)
self.BufferProject()
# Remove a resource from a configuration of the project
def ProjectRemoveConfigurationResource(self, config_name, resource_name):
- self.Project.removeConfigurationResource(config_name, resource_name)
+ self.Project.removeconfigurationResource(config_name, resource_name)
self.BufferProject()
# Add a Transition to a Project Pou
def ProjectAddPouTransition(self, pou_name, transition_name, transition_type):
- pou = self.Project.getPou(pou_name)
- pou.addTransition(transition_name, transition_type)
+ pou = self.Project.getpou(pou_name)
+ pou.addtransition(transition_name, transition_type)
self.BufferProject()
# Remove a Transition from a Project Pou
def ProjectRemovePouTransition(self, pou_name, transition_name):
- pou = self.Project.getPou(pou_name)
- pou.removeTransition(transition_name)
+ pou = self.Project.getpou(pou_name)
+ pou.removetransition(transition_name)
self.BufferProject()
# Add an Action to a Project Pou
def ProjectAddPouAction(self, pou_name, action_name, action_type):
- pou = self.Project.getPou(pou_name)
- pou.addAction(action_name, action_type)
+ pou = self.Project.getpou(pou_name)
+ pou.addaction(action_name, action_type)
self.BufferProject()
# Remove an Action from a Project Pou
@@ -524,23 +500,23 @@
words = element.split("::")
if words[0] == "A" and words[1] == pou_name and words[2] == action_name:
self.RemoveElementEditing(i)
- pou = self.Project.getPou(pou_name)
- pou.removeAction(action_name)
+ pou = self.Project.getpou(pou_name)
+ pou.removeaction(action_name)
self.BufferProject()
# Change the name of a pou
def ChangeDataTypeName(self, old_name, new_name):
# Found the pou corresponding to old name and change its name to new name
- datatype = self.Project.getDataType(old_name)
- datatype.setName(new_name)
+ datatype = self.Project.getdataType(old_name)
+ datatype.setname(new_name)
self.Project.updateElementName(old_name, new_name)
self.BufferProject()
# Change the name of a pou
def ChangePouName(self, old_name, new_name):
# Found the pou corresponding to old name and change its name to new name
- pou = self.Project.getPou(old_name)
- pou.setName(new_name)
+ pou = self.Project.getpou(old_name)
+ pou.setname(new_name)
self.Project.updateElementName(old_name, new_name)
self.RefreshPouUsingTree()
self.RefreshBlockTypes()
@@ -549,98 +525,98 @@
# Change the name of a pou transition
def ChangePouTransitionName(self, pou_name, old_name, new_name):
# Found the pou transition corresponding to old name and change its name to new name
- pou = self.Project.getPou(pou_name)
- transition = pou.getTransition(old_name)
- transition.setName(new_name)
+ pou = self.Project.getpou(pou_name)
+ transition = pou.gettransition(old_name)
+ transition.setname(new_name)
pou.updateElementName(old_name, new_name)
self.BufferProject()
# Change the name of a pou action
def ChangePouActionName(self, pou_name, old_name, new_name):
# Found the pou action corresponding to old name and change its name to new name
- pou = self.Project.getPou(pou_name)
- action = pou.getAction(old_name)
- action.setName(new_name)
+ pou = self.Project.getpou(pou_name)
+ action = pou.getaction(old_name)
+ action.setname(new_name)
pou.updateElementName(old_name, new_name)
self.BufferProject()
# Change the name of a pou variable
def ChangePouVariableName(self, pou_name, old_name, new_name):
# Found the pou action corresponding to old name and change its name to new name
- pou = self.Project.getPou(pou_name)
- for type, varlist in pou.getVars():
- for var in varlist.getVariable():
- if var.getName() == old_name:
- var.setName(new_name)
+ pou = self.Project.getpou(pou_name)
+ for type, varlist in pou.getvars():
+ for var in varlist.getvariable():
+ if var.getname() == old_name:
+ var.setname(new_name)
self.RefreshBlockTypes()
self.BufferProject()
# Change the name of a configuration
def ChangeConfigurationName(self, old_name, new_name):
# Found the configuration corresponding to old name and change its name to new name
- configuration = self.Project.getConfiguration(old_name)
- configuration.setName(new_name)
+ configuration = self.Project.getconfiguration(old_name)
+ configuration.setname(new_name)
self.BufferProject()
# Change the name of a configuration resource
def ChangeConfigurationResourceName(self, config_name, old_name, new_name):
# Found the resource corresponding to old name and change its name to new name
- resource = self.Project.getConfigurationResource(config_name)
+ resource = self.Project.getconfigurationResource(config_name)
resource.setName(new_name)
self.BufferProject()
# Return the type of the pou given by its name
def GetPouType(self, name):
# Found the pou correponding to name and return its type
- pou = self.Project.getPou(name)
- return pou.pouType.getValue()
+ pou = self.Project.getpou(name)
+ return pou.getpouType()
# Return pous with SFC language
def GetSFCPous(self):
list = []
if self.Project:
- for pou in self.Project.getPous():
+ for pou in self.Project.getpous():
if pou.getBodyType() == "SFC":
- list.append(pou.getName())
+ list.append(pou.getname())
return list
# Return the body language of the pou given by its name
def GetPouBodyType(self, name):
# Found the pou correponding to name and return its body language
- pou = self.Project.getPou(name)
- return pou.getBodyType()
+ pou = self.Project.getpou(name)
+ return pou.getbodyType()
# Return the actions of a pou
def GetPouTransitions(self, pou_name):
transitions = []
- pou = self.Project.getPou(pou_name)
- if pou.getBodyType() == "SFC":
- for transition in pou.getTransitionList():
- transitions.append(transition.getName())
+ pou = self.Project.getpou(pou_name)
+ if pou.getbodyType() == "SFC":
+ for transition in pou.gettransitionList():
+ transitions.append(transition.getname())
return transitions
# Return the body language of the transition given by its name
def GetTransitionBodyType(self, pou_name, pou_transition):
# Found the pou correponding to name and return its body language
- pou = self.Project.getPou(pou_name)
- transition = pou.getTransition(pou_transition)
- return transition.getBodyType()
+ pou = self.Project.getpou(pou_name)
+ transition = pou.gettransition(pou_transition)
+ return transition.getbodyType()
# Return the actions of a pou
def GetPouActions(self, pou_name):
actions = []
- pou = self.Project.getPou(pou_name)
- if pou.getBodyType() == "SFC":
- for action in pou.getActionList():
- actions.append(action.getName())
+ pou = self.Project.getpou(pou_name)
+ if pou.getbodyType() == "SFC":
+ for action in pou.getactionList():
+ actions.append(action.getname())
return actions
# Return the body language of the pou given by its name
def GetActionBodyType(self, pou_name, pou_action):
# Found the pou correponding to name and return its body language
- pou = self.Project.getPou(pou_name)
- action = pou.getAction(pou_action)
- return action.getBodyType()
+ pou = self.Project.getpou(pou_name)
+ action = pou.getaction(pou_action)
+ return action.getbodyType()
# Extract varlists from a list of vars
def ExtractVarLists(self, vars):
@@ -650,47 +626,62 @@
for var in vars:
if current_type != (var["Class"], var["Retain"], var["Constant"], var["Location"] in ["", None]):
current_type = (var["Class"], var["Retain"], var["Constant"], var["Location"] in ["", None])
- current_varlist = plcopen.varList()
+ if var["Class"] == "Local":
+ current_varlist = plcopen.interface_localVars()
+ elif var["Class"] == "Global":
+ current_varlist = plcopen.interface_globalVars()
+ elif var["Class"] == "External":
+ current_varlist = plcopen.interface_externalVars()
+ elif var["Class"] == "Temp":
+ current_varlist = plcopen.interface_tempVars()
+ elif var["Class"] == "Input":
+ current_varlist = plcopen.interface_inputVars()
+ elif var["Class"] == "Output":
+ current_varlist = plcopen.interface_outputVars()
+ elif var["Class"] == "InOut":
+ current_varlist = plcopen.interface_inOutVars()
+ else:
+ current_varlist = plcopen.varList()
varlist_list.append((var["Class"], current_varlist))
if var["Retain"] == "Yes":
- varlist.setRetain(True)
+ current_varlist.setretain(True)
if var["Constant"] == "Yes":
- varlist.setConstant(True)
+ current_varlist.setconstant(True)
# Create variable and change its properties
tempvar = plcopen.varListPlain_variable()
- tempvar.setName(var["Name"])
+ tempvar.setname(var["Name"])
var_type = plcopen.dataType()
- if var["Type"] not in var_type.getChoices():
+ if var["Type"] in self.GetBaseTypes():
if var["Type"] == "STRING":
- var_type.setContent("string", plcopen.string())
+ var_type.setcontent({"name" : "string", "value" : plcopen.elementaryTypes_string()})
elif var["Type"] == "WSTRING":
- var_type.setContent("wstring", plcopen.wstring())
+ var_type.setcontent({"name" : "wstring", "value" : plcopen.elementaryTypes_wstring()})
else:
- derived_type = plcopen.derived()
- derived_type.setName(var["Type"])
- var_type.setContent("derived", derived_type)
+ var_type.setcontent({"name" : var["Type"], "value" : None})
else:
- var_type.setContent(var["Type"], None)
- tempvar.setType(var_type)
+ derived_type = plcopen.derivedTypes_derived()
+ derived_type.setname(var["Type"])
+ var_type.setcontent({"name" : "derived", "value" : derived_type})
+ tempvar.settype(var_type)
if var["Initial Value"] != "":
value = plcopen.value()
- value.setValue(var["Initial Value"])
- tempvar.setInitialValue(value)
+ value.setvalue(var["Initial Value"])
+ tempvar.setinitialValue(value)
if var["Location"] != "":
- tempvar.setAddress(var["Location"])
+ tempvar.setaddress(var["Location"])
else:
- tempvar.setAddress(None)
+ tempvar.setaddress(None)
# Add variable to varList
- current_varlist.appendVariable(tempvar)
+ current_varlist.appendvariable(tempvar)
return varlist_list
# Replace the configuration globalvars by those given
def SetConfigurationGlobalVars(self, name, vars):
# Found the configuration corresponding to name
- configuration = self.Project.getConfiguration(name)
+ configuration = self.Project.getconfiguration(name)
if configuration:
# Set configuration global vars
- configuration.setGlobalVars([])
+ configuration.setglobalVars([])
for vartype, varlist in self.ExtractVarLists(vars):
configuration.globalVars.append(varlist)
self.RefreshBlockTypes()
@@ -699,35 +690,35 @@
def GetConfigurationGlobalVars(self, name):
vars = []
# Found the configuration corresponding to name
- configuration = self.Project.getConfiguration(name)
+ configuration = self.Project.getconfiguration(name)
if configuration:
# Extract variables from every varLists
- for varlist in configuration.getGlobalVars():
- for var in varlist.getVariable():
- tempvar = {"Name":var.getName(),"Class":"Global"}
- vartype_content = var.getType().getContent()
+ for varlist in configuration.getglobalVars():
+ for var in varlist.getvariable():
+ tempvar = {"Name" : var.getname(), "Class" : "Global"}
+ vartype_content = var.gettype().getcontent()
if vartype_content["name"] == "derived":
- tempvar["Type"] = vartype_content["value"].getName()
+ tempvar["Type"] = vartype_content["value"].getname()
elif vartype_content["name"] in ["string", "wstring"]:
tempvar["Type"] = vartype_content["name"].upper()
else:
tempvar["Type"] = vartype_content["name"]
tempvar["Edit"] = True
- initial = var.getInitialValue()
+ initial = var.getinitialValue()
if initial:
- tempvar["Initial Value"] = initial.getValue()
+ tempvar["Initial Value"] = initial.getvalue()
else:
tempvar["Initial Value"] = ""
- address = var.getAddress()
+ address = var.getaddress()
if address:
tempvar["Location"] = address
else:
tempvar["Location"] = ""
- if varlist.getRetain():
+ if varlist.getretain():
tempvar["Retain"] = "Yes"
else:
tempvar["Retain"] = "No"
- if varlist.getConstant():
+ if varlist.getconstant():
tempvar["Constant"] = "Yes"
else:
tempvar["Constant"] = "No"
@@ -737,10 +728,10 @@
# Replace the resource globalvars by those given
def SetConfigurationResourceGlobalVars(self, config_name, name, vars):
# Found the resource corresponding to name
- resource = self.Project.getConfigurationResource(config_name, name)
+ resource = self.Project.getconfigurationResource(config_name, name)
# Set resource global vars
if resource:
- resource.setGlobalVars([])
+ resource.setglobalVars([])
for vartype, varlist in self.ExtractVarLists(vars):
resource.globalVars.append(varlist)
self.RefreshBlockTypes()
@@ -749,35 +740,35 @@
def GetConfigurationResourceGlobalVars(self, config_name, name):
vars = []
# Found the resource corresponding to name
- resource = self.Project.getConfigurationResource(config_name, name)
+ resource = self.Project.getconfigurationResource(config_name, name)
if resource:
# Extract variables from every varLists
- for varlist in resource.getGlobalVars():
- for var in varlist.getVariable():
- tempvar = {"Name":var.getName(),"Class":"Global"}
- vartype_content = var.getType().getContent()
+ for varlist in resource.getglobalVars():
+ for var in varlist.getvariable():
+ tempvar = {"Name" : var.getname(), "Class" : "Global"}
+ vartype_content = var.gettype().getcontent()
if vartype_content["name"] == "derived":
- tempvar["Type"] = vartype_content["value"].getName()
+ tempvar["Type"] = vartype_content["value"].getname()
elif vartype_content["name"] in ["string", "wstring"]:
tempvar["Type"] = vartype_content["name"].upper()
else:
tempvar["Type"] = vartype_content["name"]
tempvar["Edit"] = True
- initial = var.getInitialValue()
+ initial = var.getinitialValue()
if initial:
- tempvar["Initial Value"] = initial.getValue()
+ tempvar["Initial Value"] = initial.getvalue()
else:
tempvar["Initial Value"] = ""
- address = var.getAddress()
+ address = var.getaddress()
if address:
tempvar["Location"] = address
else:
tempvar["Location"] = ""
- if varlist.getRetain():
+ if varlist.getretain():
tempvar["Retain"] = "Yes"
else:
tempvar["Retain"] = "No"
- if varlist.getConstant():
+ if varlist.getconstant():
tempvar["Constant"] = "Yes"
else:
tempvar["Constant"] = "No"
@@ -787,7 +778,7 @@
# Return the interface of the pou given by its name
def GetPouInterfaceVarsByName(self, name):
# Found the pou correponding to name and return the interface
- return self.GetPouInterfaceVars(self.Project.getPou(name))
+ return self.GetPouInterfaceVars(self.Project.getpou(name))
# Return the interface for the given pou
def GetPouInterfaceVars(self, pou):
@@ -795,34 +786,34 @@
# Verify that the pou has an interface
if pou.interface:
# Extract variables from every varLists
- for type, varlist in pou.getVars():
- for var in varlist.getVariable():
- tempvar = {"Name":var.getName(),"Class":type}
- vartype_content = var.getType().getContent()
+ for type, varlist in pou.getvars():
+ for var in varlist.getvariable():
+ tempvar = {"Name" : var.getname(), "Class" : type}
+ vartype_content = var.gettype().getcontent()
if vartype_content["name"] == "derived":
- tempvar["Type"] = vartype_content["value"].getName()
- tempvar["Edit"] = not pou.hasBlock(tempvar["Name"])
+ tempvar["Type"] = vartype_content["value"].getname()
+ tempvar["Edit"] = not pou.hasblock(tempvar["Name"])
else:
if vartype_content["name"] in ["string", "wstring"]:
tempvar["Type"] = vartype_content["name"].upper()
else:
tempvar["Type"] = vartype_content["name"]
tempvar["Edit"] = True
- initial = var.getInitialValue()
+ initial = var.getinitialValue()
if initial:
- tempvar["Initial Value"] = initial.getValue()
+ tempvar["Initial Value"] = initial.getvalue()
else:
tempvar["Initial Value"] = ""
- address = var.getAddress()
+ address = var.getaddress()
if address:
tempvar["Location"] = address
else:
tempvar["Location"] = ""
- if varlist.getRetain():
+ if varlist.getretain():
tempvar["Retain"] = "Yes"
else:
tempvar["Retain"] = "No"
- if varlist.getConstant():
+ if varlist.getconstant():
tempvar["Constant"] = "Yes"
else:
tempvar["Constant"] = "No"
@@ -832,31 +823,36 @@
# Replace the Pou interface by the one given
def SetPouInterfaceVars(self, name, vars):
# Found the pou corresponding to name and add interface if there isn't one yet
- pou = self.Project.getPou(name)
+ pou = self.Project.getpou(name)
if not pou.interface:
pou.interface = plcopen.pou_interface()
# Set Pou interface
- pou.setVars(self.ExtractVarLists(vars))
+ pou.setvars(self.ExtractVarLists(vars))
self.RefreshPouUsingTree()
self.RefreshBlockTypes()
# Replace the return type of the pou given by its name (only for functions)
def SetPouInterfaceReturnType(self, name, type):
- pou = self.Project.getPou(name)
+ pou = self.Project.getpou(name)
if not pou.interface:
pou.interface = plcopen.pou_interface()
# If there isn't any return type yet, add it
- return_type = pou.interface.getReturnType()
+ return_type = pou.interface.getreturnType()
if not return_type:
return_type = plcopen.dataType()
- pou.interface.setReturnType(return_type)
+ pou.interface.setreturnType(return_type)
# Change return type
if type in self.GetBaseTypes():
- return_type.setContent(type, None)
+ if type == "STRING":
+ return_type.setcontent({"name" : "string", "value" : plcopen.elementaryTypes_string()})
+ elif type == "WSTRING":
+ return_type.setcontent({"name" : "wstring", "value" : plcopen.elementaryTypes_wstring()})
+ else:
+ return_type.setcontent({"name" : type, "value" : None})
else:
- derived_type = plcopen.derived()
- derived_type.setName(type)
- return_type.setContent("derived", derived_type)
+ derived_type = plcopen.derivedTypes_derived()
+ derived_type.setname(type)
+ return_type.setcontent({"name" : "derived", "value" : derived_type})
self.RefreshBlockTypes()
def UpdateProjectUsedPous(self, old_name, new_name):
@@ -871,18 +867,18 @@
# Return the return type of the pou given by its name
def GetPouInterfaceReturnTypeByName(self, name):
# Found the pou correponding to name and return the return type
- return self.GetPouInterfaceReturnType(self.Project.getPou(name))
+ return self.GetPouInterfaceReturnType(self.Project.getpou(name))
# Return the return type of the given pou
def GetPouInterfaceReturnType(self, pou):
# Verify that the pou has an interface
if pou.interface:
# Return the return type if there is one
- return_type = pou.interface.getReturnType()
+ return_type = pou.interface.getreturnType()
if return_type:
- returntype_content = return_type.getContent()
+ returntype_content = return_type.getcontent()
if returntype_content["name"] == "derived":
- return returntype_content["value"].getName()
+ return returntype_content["value"].getname()
elif returntype_content["name"] in ["string", "wstring"]:
return returntype_content["name"].upper()
else:
@@ -894,26 +890,26 @@
ResetTypeHierarchy()
ResetEnumeratedDataValues()
if self.Project:
- for datatype in self.Project.getDataTypes():
- name = datatype.getName()
- basetype_content = datatype.getBaseType().getContent()
+ for datatype in self.Project.getdataTypes():
+ name = datatype.getname()
+ basetype_content = datatype.getbaseType().getcontent()
if basetype_content["value"] is None:
AddDataTypeHierarchy(name, basetype_content["name"])
elif basetype_content["name"] in ["string", "wstring"]:
AddDataTypeHierarchy(name, basetype_content["name"].upper())
elif basetype_content["name"] == "derived":
- AddDataTypeHierarchy(name, basetype_content["value"].getName())
+ AddDataTypeHierarchy(name, basetype_content["value"].getname())
elif basetype_content["name"] in ["subrangeSigned", "subrangeUnsigned"]:
- base_type = basetype_content["value"].baseType.getContent()
+ base_type = basetype_content["value"].baseType.getcontent()
if base_type["value"] is None:
AddDataTypeHierarchy(name, base_type["name"])
else:
- AddDataTypeHierarchy(name, base_type["value"].getName())
+ AddDataTypeHierarchy(name, base_type["value"].getname())
else:
if basetype_content["name"] == "enum":
values = []
- for value in basetype_content["value"].values.getValue():
- values.append(value.getName())
+ for value in basetype_content["value"].values.getvalue():
+ values.append(value.getname())
AddEnumeratedDataValues(values)
AddDataTypeHierarchy(name, "ANY_DERIVED")
@@ -924,58 +920,58 @@
else:
BlockTypes.append({"name" : "User-defined POUs", "list": []})
if self.Project:
- for pou in self.Project.getPous():
- pou_name = pou.getName()
- pou_type = pou.pouType.getValue()
+ for pou in self.Project.getpous():
+ pou_name = pou.getname()
+ pou_type = pou.getpouType()
if pou_type != "program":
block_infos = {"name" : pou_name, "type" : pou_type, "extensible" : False,
"inputs" : [], "outputs" : [], "comment" : "",
"generate" : generate_block, "initialise" : initialise_block }
- if pou.getInterface():
- for type, varlist in pou.getVars():
+ if pou.getinterface():
+ for type, varlist in pou.getvars():
if type == "InOut":
- for var in varlist.getVariable():
- var_type = var.type.getContent()
+ 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"))
+ 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"].upper(), "none"))
+ block_infos["outputs"].append((var.getname(), var_type["name"].upper(), "none"))
else:
- block_infos["inputs"].append((var.getName(),var_type["name"],"none"))
- block_infos["outputs"].append((var.getName(),var_type["name"],"none"))
+ block_infos["inputs"].append((var.getname(), var_type["name"], "none"))
+ block_infos["outputs"].append((var.getname(), var_type["name"], "none"))
elif type == "Input":
- for var in varlist.getVariable():
- var_type = var.type.getContent()
+ 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["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"].upper(), "none"))
else:
- block_infos["inputs"].append((var.getName(),var_type["name"],"none"))
+ block_infos["inputs"].append((var.getname(), var_type["name"], "none"))
elif type == "Output":
- for var in varlist.getVariable():
- var_type = var.type.getContent()
+ 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"))
+ 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"].upper(), "none"))
else:
- block_infos["outputs"].append((var.getName(),var_type["name"],"none"))
- return_type = pou.interface.getReturnType()
+ block_infos["outputs"].append((var.getname(), var_type["name"], "none"))
+ return_type = pou.interface.getreturnType()
if return_type:
- var_type = return_type.getContent()
+ var_type = return_type.getcontent()
if var_type["name"] == "derived":
- block_infos["outputs"].append(("",var_type["value"].getName(),"none"))
+ block_infos["outputs"].append(("", var_type["value"].getname(), "none"))
elif var_type["name"] in ["string", "wstring"]:
- block_infos["outputs"].append(("",var_type["name"].upper(),"none"))
+ block_infos["outputs"].append(("", var_type["name"].upper(), "none"))
else:
- block_infos["outputs"].append(("",var_type["name"],"none"))
- if pou.getBodyType() in ["FBD","LD","SFC"]:
- for instance in pou.getInstances():
- if isinstance(instance, plcopen.comment):
- block_infos["comment"] = instance.getContentText()
+ block_infos["outputs"].append(("", var_type["name"], "none"))
+ if pou.getbodyType() in ["FBD","LD","SFC"]:
+ for instance in pou.getinstances():
+ if isinstance(instance, plcopen.commonObjects_comment):
+ block_infos["comment"] = instance.getcontentText()
BlockTypes[-1]["list"].append(block_infos)
# Return Block types checking for recursion
@@ -1033,9 +1029,9 @@
if blocktype["type"] == "program":
blocktypes.append(blocktype["name"])
if self.Project:
- for pou in self.Project.getPous():
- if pou.pouType.getValue() == "program":
- blocktypes.append(pou.getName())
+ for pou in self.Project.getpous():
+ if pou.getpouType() == "program":
+ blocktypes.append(pou.getname())
return blocktypes
# Return Data Types checking for recursion
@@ -1050,8 +1046,8 @@
name = words[1]
else:
name = ""
- for datatype in self.Project.getDataTypes():
- datatype_name = datatype.getName()
+ for datatype in self.Project.getdataTypes():
+ datatype_name = datatype.getname()
if datatype_name != name and not self.DataTypeIsUsedBy(name, datatype_name):
datatypes.append(datatype_name)
return datatypes
@@ -1105,40 +1101,40 @@
words = tagname.split("::")
if words[0] == "D":
infos = {}
- datatype = self.Project.getDataType(words[1])
- basetype_content = datatype.baseType.getContent()
+ datatype = self.Project.getdataType(words[1])
+ basetype_content = datatype.baseType.getcontent()
if basetype_content["value"] is None:
infos["type"] = "Directly"
infos["base_type"] = basetype_content["name"]
elif basetype_content["name"] == "derived":
infos["type"] = "Directly"
- infos["base_type"] = basetype_content["value"].getName()
+ infos["base_type"] = basetype_content["value"].getname()
elif basetype_content["name"] 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()
+ infos["min"] = basetype_content["value"].range.getlower()
+ infos["max"] = basetype_content["value"].range.getupper()
+ base_type = basetype_content["value"].baseType.getcontent()
if base_type["value"] is None:
infos["base_type"] = base_type["name"]
else:
- infos["base_type"] = base_type["value"].getName()
+ infos["base_type"] = base_type["value"].getname()
elif basetype_content["name"] == "enum":
infos["type"] = "Enumerated"
infos["values"] = []
- for value in basetype_content["value"].values.getValue():
- infos["values"].append(value.getName())
+ for value in basetype_content["value"].values.getvalue():
+ infos["values"].append(value.getname())
elif basetype_content["name"] == "array":
infos["type"] = "Array"
infos["dimensions"] = []
- for dimension in basetype_content["value"].getDimension():
- infos["dimensions"].append(str(dimension.getUpper()))
- base_type = basetype_content["value"].baseType.getContent()
+ for dimension in basetype_content["value"].getdimension():
+ infos["dimensions"].append(str(dimension.getupper()))
+ base_type = basetype_content["value"].baseType.getcontent()
if base_type["value"] is None:
infos["base_type"] = base_type["name"]
else:
- infos["base_type"] = base_type["value"].getName()
+ infos["base_type"] = base_type["value"].getname()
if datatype.initialValue is not None:
- infos["initial"] = str(datatype.initialValue.getValue())
+ infos["initial"] = str(datatype.initialValue.getvalue())
else:
infos["initial"] = ""
return infos
@@ -1148,64 +1144,67 @@
def SetDataTypeInfos(self, tagname, infos):
words = tagname.split("::")
if words[0] == "D":
- datatype = self.Project.getDataType(words[1])
+ 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("string", plcopen.string())
+ datatype.baseType.setcontent({"name" : "string", "value" : plcopen.elementaryTypes_string()})
elif infos["base_type"] == "WSTRING":
- datatype.baseType.setContent("wstring", plcopen.wstring())
- else:
- datatype.baseType.setContent(infos["base_type"], None)
+ datatype.baseType.setcontent({"name" : "wstring", "value" : plcopen.elementaryTypes_wstring()})
+ else:
+ datatype.baseType.setcontent({"name" : infos["base_type"], "value" : None})
else:
- derived_datatype = plcopen.derived()
- derived_datatype.setName(infos["base_type"])
- datatype.baseType.setContent("derived", derived_datatype)
+ derived_datatype = plcopen.derivedTypes_derived()
+ derived_datatype.setname(infos["base_type"])
+ datatype.baseType.setcontent({"name" : "derived", "value" : derived_datatype})
elif infos["type"] == "Subrange":
if infos["base_type"] in GetSubTypes("ANY_UINT"):
- subrange = plcopen.subrangeUnsigned()
- datatype.baseType.setContent("subrangeUnsigned", subrange)
+ subrange = plcopen.derivedTypes_subrangeUnsigned()
+ datatype.baseType.setcontent({"name" : "subrangeUnsigned", "value" : subrange})
else:
- subrange = plcopen.subrangeSigned()
- datatype.baseType.setContent("subrangeSigned", subrange)
- subrange.range.setLower(infos["min"])
- subrange.range.setUpper(infos["max"])
+ subrange = plcopen.derivedTypes_subrangeSigned()
+ datatype.baseType.setcontent({"name" : "subrangeSigned", "value" : subrange})
+ subrange.range.setlower(infos["min"])
+ subrange.range.setupper(infos["max"])
if infos["base_type"] in self.GetBaseTypes():
- subrange.baseType.setContent(infos["base_type"], None)
+ subrange.baseType.setcontent({"name" : infos["base_type"], "value" : None})
else:
- derived_datatype = plcopen.derived()
- derived_datatype.setName(infos["base_type"])
- subrange.baseType.setContent("derived", derived_datatype)
+ derived_datatype = plcopen.derivedTypes_derived()
+ derived_datatype.setname(infos["base_type"])
+ subrange.baseType.setcontent({"name" : "derived", "value" : derived_datatype})
elif infos["type"] == "Enumerated":
- enumerated = plcopen.enum()
- for enum_value in infos["values"]:
+ enumerated = plcopen.derivedTypes_enum()
+ for i, enum_value in enumerate(infos["values"]):
value = plcopen.values_value()
- value.setName(enum_value)
- enumerated.values.appendValue(value)
- datatype.baseType.setContent("enum", enumerated)
+ value.setname(enum_value)
+ if i == 0:
+ enumerated.values.setvalue([value])
+ else:
+ enumerated.values.appendvalue(value)
+ datatype.baseType.setcontent({"name" : "enum", "value" : enumerated})
elif infos["type"] == "Array":
- array = plcopen.array()
+ array = plcopen.derivedTypes_array()
for dimension in infos["dimensions"]:
dimension_range = plcopen.rangeSigned()
- dimension_range.setLower(1)
- dimension_range.setUpper(int(dimension))
- array.appendDimension(dimension_range)
+ dimension_range.setlower(1)
+ dimension_range.setupper(int(dimension))
+ array.appenddimension(dimension_range)
if infos["base_type"] in self.GetBaseTypes():
if infos["base_type"] == "STRING":
- array.baseType.setContent("string", plcopen.string())
+ array.baseType.setcontent({"name" : "string", "value" : plcopen.elementaryTypes_string()})
elif infos["base_type"] == "WSTRING":
- array.baseType.setContent("wstring", plcopen.wstring())
- else:
- array.baseType.setContent(infos["base_type"], None)
+ array.baseType.setcontent({"name" : "wstring", "value" : plcopen.wstring()})
+ else:
+ array.baseType.setcontent({"name" : infos["base_type"], "value" : None})
else:
- derived_datatype = plcopen.derived()
- derived_datatype.setName(infos["base_type"])
- array.baseType.setContent("derived", derived_datatype)
- datatype.baseType.setContent("array", array)
+ derived_datatype = plcopen.derivedTypes_derived()
+ derived_datatype.setname(infos["base_type"])
+ array.baseType.setcontent({"name" : "derived", "value" : derived_datatype})
+ datatype.baseType.setcontent({"name" : "array", "value" : array})
if infos["initial"] != "":
if datatype.initialValue is None:
datatype.initialValue = plcopen.value()
- datatype.initialValue.setValue(infos["initial"])
+ datatype.initialValue.setvalue(infos["initial"])
else:
datatype.initialValue = None
self.RefreshDataTypeUsingTree()
@@ -1220,17 +1219,17 @@
def GetEditedElement(self, tagname):
words = tagname.split("::")
if words[0] == "P":
- return self.Project.getPou(words[1])
+ return self.Project.getpou(words[1])
if words[0] in ['T', 'A']:
- pou = self.Project.getPou(words[1])
+ pou = self.Project.getpou(words[1])
if words[0] == 'T':
- return pou.getTransition(words[2])
+ return pou.gettransition(words[2])
elif words[0] == 'A':
- return pou.getAction(words[2])
+ return pou.getaction(words[2])
elif words[0] == 'C':
- return self.Project.getConfiguration(words[1])
+ return self.Project.getconfiguration(words[1])
elif words[0] == 'R':
- return self.Project.getConfigurationResource(words[1], words[2])
+ return self.Project.getconfigurationResource(words[1], words[2])
return None
# Return edited element name
@@ -1264,7 +1263,7 @@
def GetEditedElementInterfaceVars(self, tagname):
words = tagname.split("::")
if words[0] in ["P","T","A"]:
- pou = self.Project.getPou(words[1])
+ pou = self.Project.getpou(words[1])
return self.GetPouInterfaceVars(pou)
return []
@@ -1272,7 +1271,7 @@
def GetEditedElementInterfaceReturnType(self, tagname):
words = tagname.split("::")
if words[0] == "P":
- pou = self.Project.getPou(words[1])
+ pou = self.Project.getpou(words[1])
return self.GetPouInterfaceReturnType(pou)
elif words[0] == 'T':
return "BOOL"
@@ -1282,33 +1281,33 @@
def SetEditedElementText(self, tagname, text):
element = self.GetEditedElement(tagname)
if element != None:
- element.setText(text)
+ element.settext(text)
self.RefreshPouUsingTree()
# Return the edited element text
def GetEditedElementText(self, tagname):
element = self.GetEditedElement(tagname)
if element != None:
- return element.getText()
+ return element.gettext()
return ""
# Return the edited element transitions
def GetEditedElementTransitions(self, tagname):
pou = self.GetEditedElement(tagname)
- if pou != None and pou.getBodyType() == "SFC":
+ if pou != None and pou.getbodyType() == "SFC":
transitions = []
- for transition in pou.getTransitionList():
- transitions.append(transition.getName())
+ for transition in pou.gettransitionList():
+ transitions.append(transition.getname())
return transitions
return []
# Return edited element transitions
def GetEditedElementActions(self, tagname):
pou = self.GetEditedElement(tagname)
- if pou != None and pou.getBodyType() == "SFC":
+ if pou != None and pou.getbodyType() == "SFC":
actions = []
- for action in pou.getActionList():
- actions.append(action.getName())
+ for action in pou.getactionList():
+ actions.append(action.getname())
return actions
return []
@@ -1327,284 +1326,284 @@
if element is not None:
# if id is defined
if id is not None:
- instance = element.getInstance(id)
+ instance = element.getinstance(id)
else:
- instance = element.getRandomInstance(exclude)
+ instance = element.getrandomInstance(exclude)
if instance is not None:
if id is not None:
infos["id"] = id
else:
- infos["id"] = instance.getLocalId()
- infos["x"] = instance.getX()
- infos["y"] = instance.getY()
- infos["height"] = instance.getHeight()
- infos["width"] = instance.getWidth()
- if isinstance(instance, plcopen.block):
- infos["name"] = instance.getInstanceName()
- infos["type"] = instance.getTypeName()
- executionOrder = instance.getExecutionOrderId()
+ infos["id"] = instance.getlocalId()
+ infos["x"] = instance.getx()
+ infos["y"] = instance.gety()
+ infos["height"] = instance.getheight()
+ infos["width"] = instance.getwidth()
+ if isinstance(instance, plcopen.fbdObjects_block):
+ infos["name"] = instance.getinstanceName()
+ infos["type"] = instance.gettypeName()
+ executionOrder = instance.getexecutionOrderId()
if executionOrder is not None:
infos["executionOrder"] = executionOrder
else:
infos["executionOrder"] = 0
infos["connectors"] = {"inputs":[],"outputs":[]}
- for variable in instance.inputVariables.getVariable():
+ for variable in instance.inputVariables.getvariable():
connector = {}
- connector["name"] = variable.getFormalParameter()
- connector["position"] = variable.connectionPointIn.getRelPosition()
- connector["negated"] = variable.getNegated()
- connector["edge"] = variable.getConnectorEdge()
+ connector["name"] = variable.getformalParameter()
+ connector["position"] = variable.connectionPointIn.getrelPositionXY()
+ connector["negated"] = variable.getnegated()
+ connector["edge"] = variable.getedge()
connector["links"] = []
- connections = variable.connectionPointIn.getConnections()
+ connections = variable.connectionPointIn.getconnections()
if connections:
for link in connections:
- dic = {"refLocalId":link.getRefLocalId(),"points":link.getPoints(),"formalParameter":link.getFormalParameter()}
+ dic = {"refLocalId":link.getrefLocalId(),"points":link.getpoints(),"formalParameter":link.getformalParameter()}
connector["links"].append(dic)
infos["connectors"]["inputs"].append(connector)
- for variable in instance.outputVariables.getVariable():
+ for variable in instance.outputVariables.getvariable():
connector = {}
- connector["name"] = variable.getFormalParameter()
- connector["position"] = variable.connectionPointOut.getRelPosition()
- connector["negated"] = variable.getNegated()
- connector["edge"] = variable.getConnectorEdge()
+ connector["name"] = variable.getformalParameter()
+ connector["position"] = variable.connectionPointOut.getrelPositionXY()
+ connector["negated"] = variable.getnegated()
+ connector["edge"] = variable.getedge()
infos["connectors"]["outputs"].append(connector)
- elif isinstance(instance, plcopen.inVariable):
- infos["name"] = instance.getExpression()
+ elif isinstance(instance, plcopen.fbdObjects_inVariable):
+ infos["name"] = instance.getexpression()
infos["value_type"] = self.GetEditedElementVarValueType(tagname, infos["name"])
infos["type"] = "input"
- executionOrder = instance.getExecutionOrderId()
+ executionOrder = instance.getexecutionOrderId()
if executionOrder is not None:
infos["executionOrder"] = executionOrder
else:
infos["executionOrder"] = 0
infos["connector"] = {}
- infos["connector"]["position"] = instance.connectionPointOut.getRelPosition()
- infos["connector"]["negated"] = instance.getNegated()
- infos["connector"]["edge"] = instance.getConnectorEdge()
- elif isinstance(instance, plcopen.outVariable):
- infos["name"] = instance.getExpression()
+ infos["connector"]["position"] = instance.connectionPointOut.getrelPositionXY()
+ infos["connector"]["negated"] = instance.getnegated()
+ infos["connector"]["edge"] = instance.getedge()
+ elif isinstance(instance, plcopen.fbdObjects_outVariable):
+ infos["name"] = instance.getexpression()
infos["value_type"] = self.GetEditedElementVarValueType(tagname, infos["name"])
infos["type"] = "output"
- executionOrder = instance.getExecutionOrderId()
+ executionOrder = instance.getexecutionOrderId()
if executionOrder is not None:
infos["executionOrder"] = executionOrder
else:
infos["executionOrder"] = 0
infos["connector"] = {}
- infos["connector"]["position"] = instance.connectionPointIn.getRelPosition()
- infos["connector"]["negated"] = instance.getNegated()
- infos["connector"]["edge"] = instance.getConnectorEdge()
+ infos["connector"]["position"] = instance.connectionPointIn.getrelPositionXY()
+ infos["connector"]["negated"] = instance.getnegated()
+ infos["connector"]["edge"] = instance.getedge()
infos["connector"]["links"] = []
- connections = instance.connectionPointIn.getConnections()
+ connections = instance.connectionPointIn.getconnections()
if connections:
for link in connections:
- dic = {"refLocalId":link.getRefLocalId(),"points":link.getPoints(),"formalParameter":link.getFormalParameter()}
+ dic = {"refLocalId":link.getrefLocalId(),"points":link.getpoints(),"formalParameter":link.getformalParameter()}
infos["connector"]["links"].append(dic)
- elif isinstance(instance, plcopen.inOutVariable):
- infos["name"] = instance.getExpression()
+ elif isinstance(instance, plcopen.fbdObjects_inOutVariable):
+ infos["name"] = instance.getexpression()
infos["value_type"] = self.GetEditedElementVarValueType(tagname, infos["name"])
infos["type"] = "inout"
- executionOrder = instance.getExecutionOrderId()
+ executionOrder = instance.getexecutionOrderId()
if executionOrder is not None:
infos["executionOrder"] = executionOrder
else:
infos["executionOrder"] = 0
infos["connectors"] = {"input":{},"output":{}}
- infos["connectors"]["output"]["position"] = instance.connectionPointOut.getRelPosition()
- infos["connectors"]["output"]["negated"] = instance.getNegatedOut()
- infos["connectors"]["output"]["edge"] = instance.getOutputEdge()
- infos["connectors"]["input"]["position"] = instance.connectionPointIn.getRelPosition()
- infos["connectors"]["input"]["negated"] = instance.getNegatedIn()
- infos["connectors"]["input"]["edge"] = instance.getInputEdge()
+ infos["connectors"]["output"]["position"] = instance.connectionPointOut.getrelPositionXY()
+ infos["connectors"]["output"]["negated"] = instance.getnegatedOut()
+ infos["connectors"]["output"]["edge"] = instance.getedgeOut()
+ infos["connectors"]["input"]["position"] = instance.connectionPointIn.getrelPositionXY()
+ infos["connectors"]["input"]["negated"] = instance.getnegatedIn()
+ infos["connectors"]["input"]["edge"] = instance.getedgeIn()
infos["connectors"]["input"]["links"] = []
- connections = instance.connectionPointIn.getConnections()
+ connections = instance.connectionPointIn.getconnections()
if connections:
for link in connections:
- dic = {"refLocalId":link.getRefLocalId(),"points":link.getPoints(),"formalParameter":link.getFormalParameter()}
+ dic = {"refLocalId":link.getrefLocalId(),"points":link.getpoints(),"formalParameter":link.getformalParameter()}
infos["connectors"]["input"]["links"].append(dic)
- elif isinstance(instance, plcopen.continuation):
- infos["name"] = instance.getName()
+ elif isinstance(instance, plcopen.commonObjects_continuation):
+ infos["name"] = instance.getname()
infos["type"] = "continuation"
infos["connector"] = {}
- infos["connector"]["position"] = instance.connectionPointOut.getRelPosition()
- elif isinstance(instance, plcopen.connector):
+ infos["connector"]["position"] = instance.connectionPointOut.getrelPositionXY()
+ elif isinstance(instance, plcopen.commonObjects_connector):
infos["name"] = instance.getName()
infos["type"] = "connection"
infos["connector"] = {}
- infos["connector"]["position"] = instance.connectionPointIn.getRelPosition()
+ infos["connector"]["position"] = instance.connectionPointIn.getrelPositionXY()
infos["connector"]["links"] = []
- connections = instance.connectionPointIn.getConnections()
+ connections = instance.connectionPointIn.getconnections()
if connections:
for link in connections:
- dic = {"refLocalId":link.getRefLocalId(),"points":link.getPoints(),"formalParameter":link.getFormalParameter()}
+ dic = {"refLocalId":link.getrefLocalId(),"points":link.getpoints(),"formalParameter":link.getformalParameter()}
infos["connector"]["links"].append(dic)
- elif isinstance(instance, plcopen.comment):
+ elif isinstance(instance, plcopen.commonObjects_comment):
infos["type"] = "comment"
- infos["content"] = instance.getContentText()
- elif isinstance(instance, plcopen.leftPowerRail):
+ infos["content"] = instance.getcontentText()
+ elif isinstance(instance, plcopen.ldObjects_leftPowerRail):
infos["type"] = "leftPowerRail"
infos["connectors"] = []
- for connection in instance.getConnectionPointOut():
+ for connection in instance.getconnectionPointOut():
connector = {}
- connector["position"] = connection.getRelPosition()
+ connector["position"] = connection.getrelPositionXY()
infos["connectors"].append(connector)
- elif isinstance(instance, plcopen.rightPowerRail):
+ elif isinstance(instance, plcopen.ldObjects_rightPowerRail):
infos["type"] = "rightPowerRail"
infos["connectors"] = []
- for connection in instance.getConnectionPointIn():
+ for connection in instance.getconnectionPointIn():
connector = {}
- connector["position"] = connection.getRelPosition()
+ connector["position"] = connection.getrelPositionXY()
connector["links"] = []
- connections = connection.getConnections()
+ connections = connection.getconnections()
if connections:
- for link in connection.getConnections():
- dic = {"refLocalId":link.getRefLocalId(),"points":link.getPoints(),"formalParameter":link.getFormalParameter()}
+ for link in connection.getconnections():
+ dic = {"refLocalId":link.getrefLocalId(),"points":link.getpoints(),"formalParameter":link.getformalParameter()}
connector["links"].append(dic)
infos["connectors"].append(connector)
- elif isinstance(instance, plcopen.contact):
- infos["name"] = instance.getVariable()
+ elif isinstance(instance, plcopen.ldObjects_contact):
+ infos["name"] = instance.getvariable()
infos["type"] = "contact"
- executionOrder = instance.getExecutionOrderId()
+ executionOrder = instance.getexecutionOrderId()
if executionOrder is not None:
infos["executionOrder"] = executionOrder
else:
infos["executionOrder"] = 0
- infos["negated"] = instance.getNegated()
- infos["edge"] = instance.getContactEdge()
+ infos["negated"] = instance.getnegated()
+ infos["edge"] = instance.getedge()
infos["connectors"] = {"input":{},"output":{}}
- infos["connectors"]["input"]["position"] = instance.connectionPointIn.getRelPosition()
+ infos["connectors"]["input"]["position"] = instance.connectionPointIn.getrelPositionXY()
infos["connectors"]["input"]["links"] = []
- connections = instance.connectionPointIn.getConnections()
+ connections = instance.connectionPointIn.getconnections()
if connections:
for link in connections:
- dic = {"refLocalId":link.getRefLocalId(),"points":link.getPoints(),"formalParameter":link.getFormalParameter()}
+ dic = {"refLocalId":link.getrefLocalId(),"points":link.getpoints(),"formalParameter":link.getformalParameter()}
infos["connectors"]["input"]["links"].append(dic)
- infos["connectors"]["output"]["position"] = instance.connectionPointOut.getRelPosition()
- elif isinstance(instance, plcopen.coil):
- infos["name"] = instance.getVariable()
+ infos["connectors"]["output"]["position"] = instance.connectionPointOut.getrelPositionXY()
+ elif isinstance(instance, plcopen.ldObjects_coil):
+ infos["name"] = instance.getvariable()
infos["type"] = "coil"
- executionOrder = instance.getExecutionOrderId()
+ executionOrder = instance.getexecutionOrderId()
if executionOrder is not None:
infos["executionOrder"] = executionOrder
else:
infos["executionOrder"] = 0
- infos["negated"] = instance.getNegated()
- infos["storage"] = instance.getCoilStorage()
+ infos["negated"] = instance.getnegated()
+ infos["storage"] = instance.getstorage()
infos["connectors"] = {"input":{},"output":{}}
- infos["connectors"]["input"]["position"] = instance.connectionPointIn.getRelPosition()
+ infos["connectors"]["input"]["position"] = instance.connectionPointIn.getrelPositionXY()
infos["connectors"]["input"]["links"] = []
- connections = instance.connectionPointIn.getConnections()
+ connections = instance.connectionPointIn.getconnections()
if connections:
for link in connections:
- dic = {"refLocalId":link.getRefLocalId(),"points":link.getPoints(),"formalParameter":link.getFormalParameter()}
+ dic = {"refLocalId":link.getrefLocalId(),"points":link.getpoints(),"formalParameter":link.getformalParameter()}
infos["connectors"]["input"]["links"].append(dic)
- infos["connectors"]["output"]["position"] = instance.connectionPointOut.getRelPosition()
- elif isinstance(instance, plcopen.step):
- infos["name"] = instance.getName()
+ infos["connectors"]["output"]["position"] = instance.connectionPointOut.getrelPositionXY()
+ elif isinstance(instance, plcopen.sfcObjects_step):
+ infos["name"] = instance.getname()
infos["type"] = "step"
- infos["initial"] = instance.getInitialStep()
+ infos["initial"] = instance.getinitialStep()
infos["connectors"] = {}
if instance.connectionPointIn:
infos["connectors"]["input"] = {}
- infos["connectors"]["input"]["position"] = instance.connectionPointIn.getRelPosition()
+ infos["connectors"]["input"]["position"] = instance.connectionPointIn.getrelPositionXY()
infos["connectors"]["input"]["links"] = []
- connections = instance.connectionPointIn.getConnections()
+ connections = instance.connectionPointIn.getconnections()
if connections:
for link in connections:
- dic = {"refLocalId":link.getRefLocalId(),"points":link.getPoints(),"formalParameter":link.getFormalParameter()}
+ dic = {"refLocalId":link.getrefLocalId(),"points":link.getpoints(),"formalParameter":link.getformalParameter()}
infos["connectors"]["input"]["links"].append(dic)
if instance.connectionPointOut:
- infos["connectors"]["output"] = {"position" : instance.connectionPointOut.getRelPosition()}
+ infos["connectors"]["output"] = {"position" : instance.connectionPointOut.getrelPositionXY()}
if instance.connectionPointOutAction:
- infos["connectors"]["action"] = {"position" : instance.connectionPointOutAction.getRelPosition()}
- elif isinstance(instance, plcopen.transition):
+ infos["connectors"]["action"] = {"position" : instance.connectionPointOutAction.getrelPositionXY()}
+ elif isinstance(instance, plcopen.sfcObjects_transition):
infos["type"] = "transition"
- condition = instance.getConditionContent()
- priority = instance.getPriority()
+ condition = instance.getconditionContent()
+ priority = instance.getpriority()
if priority == None:
infos["priority"] = 0
else:
infos["priority"] = priority
infos["condition_type"] = condition["type"]
infos["connectors"] = {"input":{},"output":{}}
- infos["connectors"]["input"]["position"] = instance.connectionPointIn.getRelPosition()
+ infos["connectors"]["input"]["position"] = instance.connectionPointIn.getrelPositionXY()
infos["connectors"]["input"]["links"] = []
- connections = instance.connectionPointIn.getConnections()
+ connections = instance.connectionPointIn.getconnections()
if connections:
for link in connections:
- dic = {"refLocalId":link.getRefLocalId(),"points":link.getPoints(),"formalParameter":link.getFormalParameter()}
+ dic = {"refLocalId":link.getrefLocalId(),"points":link.getpoints(),"formalParameter":link.getformalParameter()}
infos["connectors"]["input"]["links"].append(dic)
- infos["connectors"]["output"]["position"] = instance.connectionPointOut.getRelPosition()
+ infos["connectors"]["output"]["position"] = instance.connectionPointOut.getrelPositionXY()
if infos["condition_type"] == "connection":
infos["connectors"]["connection"] = {}
infos["connectors"]["connection"]["links"] = []
- connections = instance.getConnections()
+ connections = instance.getconnections()
if connections:
for link in connections:
- dic = {"refLocalId":link.getRefLocalId(),"points":link.getPoints(),"formalParameter":link.getFormalParameter()}
+ dic = {"refLocalId":link.getrefLocalId(),"points":link.getpoints(),"formalParameter":link.getformalParameter()}
infos["connectors"]["connection"]["links"].append(dic)
infos["condition"] = None
else:
infos["condition"] = condition["value"]
- elif isinstance(instance, (plcopen.selectionDivergence, plcopen.simultaneousDivergence)):
- if isinstance(instance, plcopen.selectionDivergence):
+ elif isinstance(instance, (plcopen.sfcObjects_selectionDivergence, plcopen.sfcObjects_simultaneousDivergence)):
+ if isinstance(instance, plcopen.sfcObjects_selectionDivergence):
infos["type"] = "selectionDivergence"
else:
infos["type"] = "simultaneousDivergence"
infos["connectors"] = {"inputs":[],"outputs":[]}
connector = {}
- connector["position"] = instance.connectionPointIn.getRelPosition()
+ connector["position"] = instance.connectionPointIn.getrelPositionXY()
connector["links"] = []
- connections = instance.connectionPointIn.getConnections()
+ connections = instance.connectionPointIn.getconnections()
if connections:
for link in connections:
- dic = {"refLocalId":link.getRefLocalId(),"points":link.getPoints(),"formalParameter":link.getFormalParameter()}
+ dic = {"refLocalId":link.getrefLocalId(),"points":link.getpoints(),"formalParameter":link.getformalParameter()}
connector["links"].append(dic)
infos["connectors"]["inputs"].append(connector)
- for sequence in instance.getConnectionPointOut():
+ for sequence in instance.getconnectionPointOut():
connector = {}
- connector["position"] = sequence.getRelPosition()
+ connector["position"] = sequence.getrelPositionXY()
infos["connectors"]["outputs"].append(connector)
- elif isinstance(instance, (plcopen.selectionConvergence, plcopen.simultaneousConvergence)):
- if isinstance(instance, plcopen.selectionConvergence):
+ elif isinstance(instance, (plcopen.sfcObjects_selectionConvergence, plcopen.sfcObjects_simultaneousConvergence)):
+ if isinstance(instance, plcopen.sfcObjects_selectionConvergence):
infos["type"] = "selectionConvergence"
else:
infos["type"] = "simultaneousConvergence"
infos["connectors"] = {"inputs":[],"outputs":[]}
- for sequence in instance.getConnectionPointIn():
+ for sequence in instance.getconnectionPointIn():
connector = {}
- connector["position"] = sequence.getRelPosition()
+ connector["position"] = sequence.getrelPositionXY()
connector["links"] = []
- connections = sequence.getConnections()
+ connections = sequence.getconnections()
if connections:
for link in connections:
- dic = {"refLocalId":link.getRefLocalId(),"points":link.getPoints(),"formalParameter":link.getFormalParameter()}
+ dic = {"refLocalId":link.getrefLocalId(),"points":link.getpoints(),"formalParameter":link.getformalParameter()}
connector["links"].append(dic)
infos["connectors"]["inputs"].append(connector)
connector = {}
- connector["position"] = instance.connectionPointOut.getRelPosition()
+ connector["position"] = instance.connectionPointOut.getrelPositionXY()
infos["connectors"]["outputs"].append(connector)
- elif isinstance(instance, plcopen.jumpStep):
+ elif isinstance(instance, plcopen.sfcObjects_jumpStep):
infos["type"] = "jump"
- infos["target"] = instance.getTargetName()
+ infos["target"] = instance.gettargetName()
infos["connector"] = {}
- infos["connector"]["position"] = instance.connectionPointIn.getRelPosition()
+ infos["connector"]["position"] = instance.connectionPointIn.getrelPositionXY()
infos["connector"]["links"] = []
- connections = instance.connectionPointIn.getConnections()
+ connections = instance.connectionPointIn.getconnections()
if connections:
for link in connections:
- dic = {"refLocalId":link.getRefLocalId(),"points":link.getPoints(),"formalParameter":link.getFormalParameter()}
+ dic = {"refLocalId":link.getrefLocalId(),"points":link.getpoints(),"formalParameter":link.getformalParameter()}
infos["connector"]["links"].append(dic)
- elif isinstance(instance, plcopen.actionBlock):
+ elif isinstance(instance, plcopen.commonObjects_actionBlock):
infos["type"] = "actionBlock"
- infos["actions"] = instance.getActions()
+ infos["actions"] = instance.getactions()
infos["connector"] = {}
- infos["connector"]["position"] = instance.connectionPointIn.getRelPosition()
+ infos["connector"]["position"] = instance.connectionPointIn.getrelPositionXY()
infos["connector"]["links"] = []
- connections = instance.connectionPointIn.getConnections()
+ connections = instance.connectionPointIn.getconnections()
if connections:
for link in connections:
- dic = {"refLocalId":link.getRefLocalId(),"points":link.getPoints(),"formalParameter":link.getFormalParameter()}
+ dic = {"refLocalId":link.getrefLocalId(),"points":link.getpoints(),"formalParameter":link.getformalParameter()}
infos["connector"]["links"].append(dic)
return infos
return False
@@ -1612,24 +1611,24 @@
def ClearEditedElementExecutionOrder(self, tagname):
element = self.GetEditedElement(tagname)
if element is not None:
- element.resetExecutionOrder()
+ element.resetexecutionOrder()
def ResetEditedElementExecutionOrder(self, tagname):
element = self.GetEditedElement(tagname)
if element is not None:
- element.compileExecutionOrder()
+ element.compileexecutionOrder()
# Return the variable type of the given pou
def GetEditedElementVarValueType(self, tagname, varname):
words = tagname.split("::")
if words[0] in ["P","T","A"]:
- pou = self.Project.getPou(words[1])
- for type, varlist in pou.getVars():
- for var in varlist.getVariable():
- if var.getName() == varname:
- vartype_content = var.getType().getContent()
+ pou = self.Project.getpou(words[1])
+ 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()
+ return vartype_content["value"].getname()
elif vartype_content["name"] in ["string", "wstring"]:
return vartype_content["name"].upper()
else:
@@ -1647,93 +1646,93 @@
result = wire.GetConnectedInfos(0)
if result != None:
refLocalId, formalParameter = result
- connection.addConnection()
- connection.setConnectionId(idx, refLocalId)
- connection.setConnectionPoints(idx, points)
+ connection.addconnection()
+ connection.setconnectionId(idx, refLocalId)
+ connection.setconnectionPoints(idx, points)
if formalParameter != "":
- connection.setConnectionParameter(idx, formalParameter)
+ connection.setconnectionParameter(idx, formalParameter)
else:
- connection.setConnectionParameter(idx, None)
+ connection.setconnectionParameter(idx, None)
idx += 1
def AddEditedElementPouVar(self, tagname, type, name):
words = tagname.split("::")
if words[0] in ['P', 'T', 'A']:
- pou = self.Project.getPou(words[1])
- pou.addPouVar(type, name)
+ pou = self.Project.getpou(words[1])
+ pou.addpouVar(type, name)
def ChangeEditedElementPouVar(self, tagname, old_type, old_name, new_type, new_name):
words = tagname.split("::")
if words[0] in ['P', 'T', 'A']:
- pou = self.Project.getPou(words[1])
- pou.changePouVar(old_type, old_name, new_type, new_name)
+ pou = self.Project.getpou(words[1])
+ pou.changepouVar(old_type, old_name, new_type, new_name)
def AddEditedElementBlock(self, tagname, id, blocktype, blockname = None):
element = self.GetEditedElement(tagname)
if element is not None:
- block = plcopen.block()
- block.setLocalId(id)
- block.setTypeName(blocktype)
+ block = plcopen.fbdObjects_block()
+ block.setlocalId(id)
+ block.settypeName(blocktype)
blocktype_infos = GetBlockType(blocktype)
if blocktype_infos["type"] != "function" and blockname is not None:
- block.setInstanceName(blockname)
+ block.setinstanceName(blockname)
self.AddEditedElementPouVar(tagname, blocktype, blockname)
- element.addInstance("block", block)
+ element.addinstance("block", block)
self.RefreshPouUsingTree()
def SetEditedElementBlockInfos(self, tagname, id, infos):
element = self.GetEditedElement(tagname)
if element is not None:
- block = element.getInstance(id)
- blocktype = infos.get("type", block.getTypeName())
+ block = element.getinstance(id)
+ blocktype = infos.get("type", block.gettypeName())
blocktype_infos = GetBlockType(blocktype)
if blocktype_infos["type"] != "function":
if "name" in infos or "type" in infos:
- old_name = block.getInstanceName()
- old_type = block.getTypeName()
+ old_name = block.getinstanceName()
+ old_type = block.gettypeName()
new_name = infos.get("name", old_name)
new_type = infos.get("type", old_type)
self.ChangeEditedElementPouVar(tagname, old_type, old_name, new_type, new_name)
for param, value in infos.items():
if param == "name":
- block.setInstanceName(value)
+ block.setinstanceName(value)
elif param == "type":
- block.setTypeName(value)
- elif param == "executionOrder" and block.getExecutionOrderId() != value:
- self.GetEditedElement(tagname).setElementExecutionOrder(block, value)
+ block.settypeName(value)
+ elif param == "executionOrder" and block.getexecutionOrderId() != value:
+ self.GetEditedElement(tagname).setelementExecutionOrder(block, value)
elif param == "height":
- block.setHeight(value)
+ block.setheight(value)
elif param == "width":
- block.setWidth(value)
+ block.setwidth(value)
elif param == "x":
- block.setX(value)
+ block.setx(value)
elif param == "y":
- block.setY(value)
+ block.sety(value)
elif param == "connectors":
- block.inputVariables.setVariable([])
- block.outputVariables.setVariable([])
+ block.inputVariables.setvariable([])
+ block.outputVariables.setvariable([])
for connector in value["inputs"]:
variable = plcopen.inputVariables_variable()
- variable.setFormalParameter(connector.GetName())
+ variable.setformalParameter(connector.GetName())
if connector.IsNegated():
- variable.setNegated(True)
+ variable.setnegated(True)
if connector.GetEdge() != "none":
- variable.setConnectorEdge(connector.GetEdge())
+ variable.setedge(connector.GetEdge())
position = connector.GetRelPosition()
- variable.connectionPointIn.setRelPosition(position.x, position.y)
+ variable.connectionPointIn.setrelPositionXY(position.x, position.y)
self.SetConnectionWires(variable.connectionPointIn, connector)
- block.inputVariables.appendVariable(variable)
+ block.inputVariables.appendvariable(variable)
for connector in value["outputs"]:
variable = plcopen.outputVariables_variable()
- variable.setFormalParameter(connector.GetName())
+ variable.setformalParameter(connector.GetName())
if connector.IsNegated():
- variable.setNegated(True)
+ variable.setnegated(True)
if connector.GetEdge() != "none":
- variable.setConnectorEdge(connector.GetEdge())
+ variable.setedge(connector.GetEdge())
position = connector.GetRelPosition()
- variable.addConnectionPointOut()
- variable.connectionPointOut.setRelPosition(position.x, position.y)
- block.outputVariables.appendVariable(variable)
+ variable.addconnectionPointOut()
+ variable.connectionPointOut.setrelPositionXY(position.x, position.y)
+ block.outputVariables.appendvariable(variable)
self.RefreshPouUsingTree()
def AddEditedElementVariable(self, tagname, id, type):
@@ -1741,66 +1740,66 @@
if element is not None:
if type == INPUT:
name = "inVariable"
- variable = plcopen.inVariable()
+ variable = plcopen.fbdObjects_inVariable()
elif type == OUTPUT:
name = "outVariable"
- variable = plcopen.outVariable()
+ variable = plcopen.fbdObjects_outVariable()
elif type == INOUT:
name = "inOutVariable"
- variable = plcopen.inOutVariable()
- variable.setLocalId(id)
- element.addInstance(name, variable)
+ variable = plcopen.fbdObjects_inOutVariable()
+ variable.setlocalId(id)
+ element.addinstance(name, variable)
def SetEditedElementVariableInfos(self, tagname, id, infos):
element = self.GetEditedElement(tagname)
if element is not None:
- variable = element.getInstance(id)
+ variable = element.getinstance(id)
for param, value in infos.items():
if param == "name":
- variable.setExpression(value)
- elif param == "executionOrder" and variable.getExecutionOrderId() != value:
- self.GetEditedElement(tagname).setElementExecutionOrder(variable, value)
+ variable.setexpression(value)
+ elif param == "executionOrder" and variable.getexecutionOrderId() != value:
+ self.GetEditedElement(tagname).setelementExecutionOrder(variable, value)
elif param == "height":
- variable.setHeight(value)
+ variable.setheight(value)
elif param == "width":
- variable.setWidth(value)
+ variable.setwidth(value)
elif param == "x":
- variable.setX(value)
+ variable.setx(value)
elif param == "y":
- variable.setY(value)
+ variable.sety(value)
elif param == "connectors":
- if isinstance(variable, plcopen.inVariable):
+ if isinstance(variable, plcopen.fbdObjects_inVariable):
if value["output"].IsNegated():
- variable.setNegated(True)
+ variable.setnegated(True)
if value["output"].GetEdge() != "none":
- variable.setConnectorEdge(value["output"].GetEdge())
+ variable.setedge(value["output"].GetEdge())
position = value["output"].GetRelPosition()
- variable.addConnectionPointOut()
- variable.connectionPointOut.setRelPosition(position.x, position.y)
- elif isinstance(variable, plcopen.outVariable):
+ variable.addconnectionPointOut()
+ variable.connectionPointOut.setrelPositionXY(position.x, position.y)
+ elif isinstance(variable, plcopen.fbdObjects_outVariable):
if value["input"].IsNegated():
- variable.setNegated(True)
+ variable.setnegated(True)
if value["input"].GetEdge() != "none":
- variable.setConnectorEdge(value["input"].GetEdge())
+ variable.setedge(value["input"].GetEdge())
position = value["input"].GetRelPosition()
- variable.addConnectionPointIn()
- variable.connectionPointIn.setRelPosition(position.x, position.y)
+ variable.addconnectionPointIn()
+ variable.connectionPointIn.setrelPositionXY(position.x, position.y)
self.SetConnectionWires(variable.connectionPointIn, value["input"])
- elif isinstance(variable, plcopen.inOutVariable):
+ elif isinstance(variable, plcopen.fbdObjects_inOutVariable):
if value["input"].IsNegated():
- variable.setNegatedIn(True)
+ variable.setnegatedIn(True)
if value["input"].GetEdge() != "none":
- variable.setInputEdge(value["input"].GetEdge())
+ variable.setedgeIn(value["input"].GetEdge())
if value["output"].IsNegated():
- variable.setNegatedOut(True)
+ variable.setnegatedOut(True)
if value["output"].GetEdge() != "none":
- variable.setOutputEdge(value["output"].GetEdge())
+ variable.setedgeOut(value["output"].GetEdge())
position = value["output"].GetRelPosition()
- variable.addConnectionPointOut()
- variable.connectionPointOut.setRelPosition(position.x, position.y)
+ variable.addconnectionPointOut()
+ variable.connectionPointOut.setrelPositionXY(position.x, position.y)
position = value["input"].GetRelPosition()
- variable.addConnectionPointIn()
- variable.connectionPointIn.setRelPosition(position.x, position.y)
+ variable.addconnectionPointIn()
+ variable.connectionPointIn.setrelPositionXY(position.x, position.y)
self.SetConnectionWires(variable.connectionPointIn, value["input"])
def AddEditedElementConnection(self, tagname, id, type):
@@ -1808,282 +1807,282 @@
if element is not None:
if type == CONNECTOR:
name = "connector"
- connection = plcopen.connector()
+ connection = plcopen.commonObjects_connector()
elif type == CONTINUATION:
name = "continuation"
- connection = plcopen.continuation()
- connection.setLocalId(id)
- element.addInstance(name, connection)
+ connection = plcopen.commonObjects_continuation()
+ connection.setlocalId(id)
+ element.addinstance(name, connection)
def SetEditedElementConnectionInfos(self, tagname, id, infos):
element = self.GetEditedElement(tagname)
if element is not None:
- connection = element.getInstance(id)
+ connection = element.getinstance(id)
for param, value in infos.items():
if param == "name":
- connection.setName(value)
+ connection.setname(value)
elif param == "height":
- connection.setHeight(value)
+ connection.setheight(value)
elif param == "width":
- connection.setWidth(value)
+ connection.setwidth(value)
elif param == "x":
- connection.setX(value)
+ connection.setx(value)
elif param == "y":
- connection.setY(value)
+ connection.sety(value)
elif param == "connector":
position = value.GetRelPosition()
- if isinstance(connection, plcopen.continuation):
- connection.addConnectionPointOut()
- connection.connectionPointOut.setRelPosition(position.x, position.y)
- elif isinstance(connection, plcopen.connector):
- connection.addConnectionPointIn()
- connection.connectionPointIn.setRelPosition(position.x, position.y)
+ if isinstance(connection, plcopen.commonObjects_continuation):
+ connection.addconnectionPointOut()
+ connection.connectionPointOut.setrelPositionXY(position.x, position.y)
+ elif isinstance(connection, plcopen.commonObjects_connector):
+ connection.addconnectionPointIn()
+ connection.connectionPointIn.setrelPositionXY(position.x, position.y)
self.SetConnectionWires(connection.connectionPointIn, value)
def AddEditedElementComment(self, tagname, id):
element = self.GetEditedElement(tagname)
if element is not None:
- comment = plcopen.comment()
- comment.setLocalId(id)
- element.addInstance("comment", comment)
+ comment = plcopen.commonObjects_comment()
+ comment.setlocalId(id)
+ element.addinstance("comment", comment)
def SetEditedElementCommentInfos(self, tagname, id, infos):
element = self.GetEditedElement(tagname)
if element is not None:
- comment = element.getInstance(id)
+ comment = element.getinstance(id)
for param, value in infos.items():
if param == "content":
- comment.setContentText(value)
+ comment.setcontentText(value)
elif param == "height":
- comment.setHeight(value)
+ comment.setheight(value)
elif param == "width":
- comment.setWidth(value)
+ comment.setwidth(value)
elif param == "x":
- comment.setX(value)
+ comment.setx(value)
elif param == "y":
- comment.setY(value)
+ comment.sety(value)
def AddEditedElementPowerRail(self, tagname, id, type):
element = self.GetEditedElement(tagname)
if element is not None:
if type == LEFTRAIL:
name = "leftPowerRail"
- powerrail = plcopen.leftPowerRail()
+ powerrail = plcopen.ldObjects_leftPowerRail()
elif type == RIGHTRAIL:
name = "rightPowerRail"
- powerrail = plcopen.rightPowerRail()
- powerrail.setLocalId(id)
- element.addInstance(name, powerrail)
+ powerrail = plcopen.ldObjects_rightPowerRail()
+ powerrail.setlocalId(id)
+ element.addinstance(name, powerrail)
def SetEditedElementPowerRailInfos(self, tagname, id, infos):
element = self.GetEditedElement(tagname)
if element is not None:
- powerrail = element.getInstance(id)
+ powerrail = element.getinstance(id)
for param, value in infos.items():
if param == "height":
- powerrail.setHeight(value)
+ powerrail.setheight(value)
elif param == "width":
- powerrail.setWidth(value)
+ powerrail.setwidth(value)
elif param == "x":
- powerrail.setX(value)
+ powerrail.setx(value)
elif param == "y":
- powerrail.setY(value)
+ powerrail.sety(value)
elif param == "connectors":
- if isinstance(powerrail, plcopen.leftPowerRail):
- powerrail.setConnectionPointOut([])
+ if isinstance(powerrail, plcopen.ldObjects_leftPowerRail):
+ powerrail.setconnectionPointOut([])
for connector in value:
position = connector.GetRelPosition()
connection = plcopen.leftPowerRail_connectionPointOut()
- connection.setRelPosition(position.x, position.y)
+ connection.setrelPositionXY(position.x, position.y)
powerrail.connectionPointOut.append(connection)
- elif isinstance(powerrail, plcopen.rightPowerRail):
- powerrail.setConnectionPointIn([])
+ elif isinstance(powerrail, plcopen.ldObjects_rightPowerRail):
+ powerrail.setconnectionPointIn([])
for connector in value:
position = connector.GetRelPosition()
connection = plcopen.connectionPointIn()
- connection.setRelPosition(position.x, position.y)
+ connection.setrelPositionXY(position.x, position.y)
self.SetConnectionWires(connection, connector)
powerrail.connectionPointIn.append(connection)
def AddEditedElementContact(self, tagname, id):
element = self.GetEditedElement(tagname)
if element is not None:
- contact = plcopen.contact()
- contact.setLocalId(id)
- element.addInstance("contact", contact)
+ contact = plcopen.ldObjects_contact()
+ contact.setlocalId(id)
+ element.addinstance("contact", contact)
def SetEditedElementContactInfos(self, tagname, id, infos):
element = self.GetEditedElement(tagname)
if element is not None:
- contact = element.getInstance(id)
+ contact = element.getinstance(id)
for param, value in infos.items():
if param == "name":
- contact.setVariable(value)
+ contact.setvariable(value)
elif param == "type":
if value == CONTACT_NORMAL:
- contact.setNegated(False)
- contact.setContactEdge("none")
+ contact.setnegated(False)
+ contact.setedge("none")
elif value == CONTACT_REVERSE:
- contact.setNegated(True)
- contact.setContactEdge("none")
+ contact.setnegated(True)
+ contact.setedge("none")
elif value == CONTACT_RISING:
- contact.setNegated(False)
- contact.setContactEdge("rising")
+ contact.setnegated(False)
+ contact.setedge("rising")
elif value == CONTACT_FALLING:
- contact.setNegated(False)
- contact.setContactEdge("falling")
+ contact.setnegated(False)
+ contact.setedge("falling")
elif param == "height":
- contact.setHeight(value)
+ contact.setheight(value)
elif param == "width":
- contact.setWidth(value)
+ contact.setwidth(value)
elif param == "x":
- contact.setX(value)
+ contact.setx(value)
elif param == "y":
- contact.setY(value)
+ contact.sety(value)
elif param == "connectors":
input_connector = value["input"]
position = input_connector.GetRelPosition()
- contact.addConnectionPointIn()
- contact.connectionPointIn.setRelPosition(position.x, position.y)
+ contact.addconnectionPointIn()
+ contact.connectionPointIn.setrelPositionXY(position.x, position.y)
self.SetConnectionWires(contact.connectionPointIn, input_connector)
output_connector = value["output"]
position = output_connector.GetRelPosition()
- contact.addConnectionPointOut()
- contact.connectionPointOut.setRelPosition(position.x, position.y)
+ contact.addconnectionPointOut()
+ contact.connectionPointOut.setrelPositionXY(position.x, position.y)
def AddEditedElementCoil(self, tagname, id):
element = self.GetEditedElement(tagname)
if element is not None:
- coil = plcopen.coil()
- coil.setLocalId(id)
- element.addInstance("coil", coil)
+ coil = plcopen.ldObjects_coil()
+ coil.setlocalId(id)
+ element.addinstance("coil", coil)
def SetEditedElementCoilInfos(self, tagname, id, infos):
element = self.GetEditedElement(tagname)
if element is not None:
- coil = element.getInstance(id)
+ coil = element.getinstance(id)
for param, value in infos.items():
if param == "name":
- coil.setVariable(value)
+ coil.setvariable(value)
elif param == "type":
if value == COIL_NORMAL:
- coil.setNegated(False)
- coil.setCoilStorage("none")
+ coil.setnegated(False)
+ coil.setstorage("none")
elif value == COIL_REVERSE:
- coil.setNegated(True)
- coil.setCoilStorage("none")
+ coil.setnegated(True)
+ coil.setstorage("none")
elif value == COIL_SET:
- coil.setNegated(False)
- coil.setCoilStorage("set")
+ coil.setnegated(False)
+ coil.setstorage("set")
elif value == COIL_RESET:
- coil.setNegated(False)
- coil.setCoilStorage("reset")
+ coil.setnegated(False)
+ coil.setstorage("reset")
elif param == "height":
- coil.setHeight(value)
+ coil.setheight(value)
elif param == "width":
- coil.setWidth(value)
+ coil.setwidth(value)
elif param == "x":
- coil.setX(value)
+ coil.setx(value)
elif param == "y":
- coil.setY(value)
+ coil.sety(value)
elif param == "connectors":
input_connector = value["input"]
position = input_connector.GetRelPosition()
- coil.addConnectionPointIn()
- coil.connectionPointIn.setRelPosition(position.x, position.y)
+ coil.addconnectionPointIn()
+ coil.connectionPointIn.setrelPositionXY(position.x, position.y)
self.SetConnectionWires(coil.connectionPointIn, input_connector)
output_connector = value["output"]
position = output_connector.GetRelPosition()
- coil.addConnectionPointOut()
- coil.connectionPointOut.setRelPosition(position.x, position.y)
+ coil.addconnectionPointOut()
+ coil.connectionPointOut.setrelPositionXY(position.x, position.y)
def AddEditedElementStep(self, tagname, id):
element = self.GetEditedElement(tagname)
if element is not None:
- step = plcopen.step()
- step.setLocalId(id)
- element.addInstance("step", step)
+ step = plcopen.sfcObjects_step()
+ step.setlocalId(id)
+ element.addinstance("step", step)
def SetEditedElementStepInfos(self, tagname, id, infos):
element = self.GetEditedElement(tagname)
if element is not None:
- step = element.getInstance(id)
+ step = element.getinstance(id)
for param, value in infos.items():
if param == "name":
- step.setName(value)
+ step.setname(value)
elif param == "initial":
- step.setInitialStep(value)
+ step.setinitialStep(value)
elif param == "height":
- step.setHeight(value)
+ step.setheight(value)
elif param == "width":
- step.setWidth(value)
+ step.setwidth(value)
elif param == "x":
- step.setX(value)
+ step.setx(value)
elif param == "y":
- step.setY(value)
+ step.sety(value)
elif param == "connectors":
input_connector = value["input"]
if input_connector:
position = input_connector.GetRelPosition()
- step.addConnectionPointIn()
- step.connectionPointIn.setRelPosition(position.x, position.y)
+ step.addconnectionPointIn()
+ step.connectionPointIn.setrelPositionXY(position.x, position.y)
self.SetConnectionWires(step.connectionPointIn, input_connector)
else:
- step.deleteConnectionPointIn()
+ step.deleteconnectionPointIn()
output_connector = value["output"]
if output_connector:
position = output_connector.GetRelPosition()
- step.addConnectionPointOut()
- step.connectionPointOut.setRelPosition(position.x, position.y)
- else:
- step.deleteConnectionPointOut()
+ step.addconnectionPointOut()
+ step.connectionPointOut.setrelPositionXY(position.x, position.y)
+ else:
+ step.deleteconnectionPointOut()
action_connector = value["action"]
if action_connector:
position = action_connector.GetRelPosition()
- step.addConnectionPointOutAction()
- step.connectionPointOutAction.setRelPosition(position.x, position.y)
- else:
- step.deleteConnectionPointOutAction()
+ step.addconnectionPointOutAction()
+ step.connectionPointOutAction.setrelPositionXY(position.x, position.y)
+ else:
+ step.deleteconnectionPointOutAction()
def AddEditedElementTransition(self, tagname, id):
element = self.GetEditedElement(tagname)
if element is not None:
- transition = plcopen.transition()
- transition.setLocalId(id)
- element.addInstance("transition", transition)
+ transition = plcopen.sfcObjects_transition()
+ transition.setlocalId(id)
+ element.addinstance("transition", transition)
def SetEditedElementTransitionInfos(self, tagname, id, infos):
element = self.GetEditedElement(tagname)
if element is not None:
- transition = element.getInstance(id)
+ transition = element.getinstance(id)
for param, value in infos.items():
if param == "type" and value != "connection":
- transition.setConditionContent(value, infos["condition"])
+ transition.setconditionContent(value, infos["condition"])
elif param == "height":
- transition.setHeight(value)
+ transition.setheight(value)
elif param == "width":
- transition.setWidth(value)
+ transition.setwidth(value)
elif param == "x":
- transition.setX(value)
+ transition.setx(value)
elif param == "y":
- transition.setY(value)
+ transition.sety(value)
elif param == "priority":
if value != 0:
- transition.setPriority(value)
- else:
- transition.setPriority(None)
+ transition.setpriority(value)
+ else:
+ transition.setpriority(None)
elif param == "connectors":
input_connector = value["input"]
position = input_connector.GetRelPosition()
- transition.addConnectionPointIn()
- transition.connectionPointIn.setRelPosition(position.x, position.y)
+ transition.addconnectionPointIn()
+ transition.connectionPointIn.setrelPositionXY(position.x, position.y)
self.SetConnectionWires(transition.connectionPointIn, input_connector)
output_connector = value["output"]
position = output_connector.GetRelPosition()
- transition.addConnectionPointOut()
- transition.connectionPointOut.setRelPosition(position.x, position.y)
+ transition.addconnectionPointOut()
+ transition.connectionPointOut.setrelPositionXY(position.x, position.y)
if infos.get("type", None) == "connection":
- transition.setConditionContent("connection", None)
+ transition.setconditionContent("connection", None)
connection_connector = value["connection"]
self.SetConnectionWires(transition, connection_connector)
@@ -2092,130 +2091,130 @@
if element is not None:
if type == SELECTION_DIVERGENCE:
name = "selectionDivergence"
- divergence = plcopen.selectionDivergence()
+ divergence = plcopen.sfcObjects_selectionDivergence()
elif type == SELECTION_CONVERGENCE:
name = "selectionConvergence"
- divergence = plcopen.selectionConvergence()
+ divergence = plcopen.sfcObjects_selectionConvergence()
elif type == SIMULTANEOUS_DIVERGENCE:
name = "simultaneousDivergence"
- divergence = plcopen.simultaneousDivergence()
+ divergence = plcopen.sfcObjects_simultaneousDivergence()
elif type == SIMULTANEOUS_CONVERGENCE:
name = "simultaneousConvergence"
- divergence = plcopen.simultaneousConvergence()
- divergence.setLocalId(id)
- element.addInstance(name, divergence)
+ divergence = plcopen.sfcObjects_simultaneousConvergence()
+ divergence.setlocalId(id)
+ element.addinstance(name, divergence)
def SetEditedElementDivergenceInfos(self, tagname, id, infos):
element = self.GetEditedElement(tagname)
if element is not None:
- divergence = element.getInstance(id)
+ divergence = element.getinstance(id)
for param, value in infos.items():
if param == "height":
- divergence.setHeight(value)
+ divergence.setheight(value)
elif param == "width":
- divergence.setWidth(value)
+ divergence.setwidth(value)
elif param == "x":
- divergence.setX(value)
+ divergence.setx(value)
elif param == "y":
- divergence.setY(value)
+ divergence.sety(value)
elif param == "connectors":
input_connectors = value["inputs"]
- if isinstance(divergence, (plcopen.selectionDivergence, plcopen.simultaneousDivergence)):
+ if isinstance(divergence, (plcopen.sfcObjects_selectionDivergence, plcopen.sfcObjects_simultaneousDivergence)):
position = input_connectors[0].GetRelPosition()
- divergence.addConnectionPointIn()
- divergence.connectionPointIn.setRelPosition(position.x, position.y)
+ divergence.addconnectionPointIn()
+ divergence.connectionPointIn.setrelPositionXY(position.x, position.y)
self.SetConnectionWires(divergence.connectionPointIn, input_connectors[0])
else:
- divergence.setConnectionPointIn([])
+ divergence.setconnectionPointIn([])
for input_connector in input_connectors:
position = input_connector.GetRelPosition()
- if isinstance(divergence, plcopen.selectionConvergence):
+ if isinstance(divergence, plcopen.sfcObjects_selectionConvergence):
connection = plcopen.selectionConvergence_connectionPointIn()
else:
connection = plcopen.connectionPointIn()
- connection.setRelPosition(position.x, position.y)
+ connection.setrelPositionXY(position.x, position.y)
self.SetConnectionWires(connection, input_connector)
- divergence.appendConnectionPointIn(connection)
+ divergence.appendconnectionPointIn(connection)
output_connectors = value["outputs"]
- if isinstance(divergence, (plcopen.selectionConvergence, plcopen.simultaneousConvergence)):
+ if isinstance(divergence, (plcopen.sfcObjects_selectionConvergence, plcopen.sfcObjects_simultaneousConvergence)):
position = output_connectors[0].GetRelPosition()
- divergence.addConnectionPointOut()
- divergence.connectionPointOut.setRelPosition(position.x, position.y)
- else:
- divergence.setConnectionPointOut([])
+ divergence.addconnectionPointOut()
+ divergence.connectionPointOut.setrelPositionXY(position.x, position.y)
+ else:
+ divergence.setconnectionPointOut([])
for output_connector in output_connectors:
position = output_connector.GetRelPosition()
- if isinstance(divergence, plcopen.selectionDivergence):
+ if isinstance(divergence, plcopen.sfcObjects_selectionDivergence):
connection = plcopen.selectionDivergence_connectionPointOut()
else:
connection = plcopen.simultaneousDivergence_connectionPointOut()
- connection.setRelPosition(position.x, position.y)
- divergence.appendConnectionPointOut(connection)
+ connection.setrelPositionXY(position.x, position.y)
+ divergence.appendconnectionPointOut(connection)
def AddEditedElementJump(self, tagname, id):
element = self.GetEditedElement(tagname)
if element is not None:
- jump = plcopen.jumpStep()
- jump.setLocalId(id)
- element.addInstance("jumpStep", jump)
+ jump = plcopen.sfcObjects_jumpStep()
+ jump.setlocalId(id)
+ element.addinstance("jumpStep", jump)
def SetEditedElementJumpInfos(self, tagname, id, infos):
element = self.GetEditedElement(tagname)
if element is not None:
- jump = element.getInstance(id)
+ jump = element.getinstance(id)
for param, value in infos.items():
if param == "target":
- jump.setTargetName(value)
+ jump.settargetName(value)
elif param == "height":
- jump.setHeight(value)
+ jump.setheight(value)
elif param == "width":
- jump.setWidth(value)
+ jump.setwidth(value)
elif param == "x":
- jump.setX(value)
+ jump.setx(value)
elif param == "y":
- jump.setY(value)
+ jump.sety(value)
elif param == "connector":
position = value.GetRelPosition()
- jump.addConnectionPointIn()
- jump.connectionPointIn.setRelPosition(position.x, position.y)
+ jump.addconnectionPointIn()
+ jump.connectionPointIn.setrelPositionXY(position.x, position.y)
self.SetConnectionWires(jump.connectionPointIn, value)
def AddEditedElementActionBlock(self, tagname, id):
element = self.GetEditedElement(tagname)
if element is not None:
- actionBlock = plcopen.actionBlock()
- actionBlock.setLocalId(id)
- element.addInstance("actionBlock", actionBlock)
+ actionBlock = plcopen.commonObjects_actionBlock()
+ actionBlock.setlocalId(id)
+ element.addinstance("actionBlock", actionBlock)
def SetEditedElementActionBlockInfos(self, tagname, id, infos):
element = self.GetEditedElement(tagname)
if element is not None:
- actionBlock = element.getInstance(id)
+ actionBlock = element.getinstance(id)
for param, value in infos.items():
if param == "actions":
- actionBlock.setActions(value)
+ actionBlock.setactions(value)
elif param == "height":
- actionBlock.setHeight(value)
+ actionBlock.setheight(value)
elif param == "width":
- actionBlock.setWidth(value)
+ actionBlock.setwidth(value)
elif param == "x":
- actionBlock.setX(value)
+ actionBlock.setx(value)
elif param == "y":
- actionBlock.setY(value)
+ actionBlock.sety(value)
elif param == "connector":
position = value.GetRelPosition()
- actionBlock.addConnectionPointIn()
- actionBlock.connectionPointIn.setRelPosition(position.x, position.y)
+ actionBlock.addconnectionPointIn()
+ actionBlock.connectionPointIn.setrelPositionXY(position.x, position.y)
self.SetConnectionWires(actionBlock.connectionPointIn, value)
def RemoveEditedElementInstance(self, tagname, id):
element = self.GetEditedElement(tagname)
if element is not None:
- instance = element.getInstance(id)
- if isinstance(instance, plcopen.block):
- blocktype = instance.getTypeName()
- element.removePouVar(blocktype, instance.getInstanceName())
- element.removeInstance(id)
+ instance = element.getinstance(id)
+ if isinstance(instance, plcopen.fbdObjects_block):
+ blocktype = instance.gettypeName()
+ element.removepouVar(blocktype, instance.getinstanceName())
+ element.removeinstance(id)
self.RefreshPouUsingTree()
def GetEditedResourceVariables(self, tagname):
@@ -2232,14 +2231,14 @@
def SetEditedResourceInfos(self, tagname, tasks, instances):
resource = self.GetEditedElement(tagname)
if resource is not None:
- resource.setTask([])
- resource.setPouInstance([])
+ resource.settask([])
+ resource.setpouInstance([])
task_list = {}
for task in tasks:
new_task = plcopen.resource_task()
- new_task.setName(task["Name"])
+ new_task.setname(task["Name"])
if task["Single"] != "":
- new_task.setSingle(task["Single"])
+ new_task.setsingle(task["Single"])
result = duration_model.match(task["Interval"]).groups()
if reduce(lambda x, y: x or y != None, result):
values = []
@@ -2249,36 +2248,36 @@
else:
values.append(0)
values.append(int(float(result[-1]) * 1000))
- new_task.setInterval(time(*values))
- new_task.priority.setValue(int(task["Priority"]))
+ new_task.setinterval(time(*values))
+ new_task.setpriority(int(task["Priority"]))
if task["Name"] != "":
task_list[task["Name"]] = new_task
- resource.appendTask(new_task)
+ resource.appendtask(new_task)
for instance in instances:
new_instance = plcopen.pouInstance()
- new_instance.setName(instance["Name"])
- new_instance.setType(instance["Type"])
+ new_instance.setname(instance["Name"])
+ new_instance.settype(instance["Type"])
if instance["Task"] != "":
- task_list[instance["Task"]].appendPouInstance(new_instance)
+ task_list[instance["Task"]].appendpouInstance(new_instance)
else:
- resource.appendPouInstance(new_instance)
+ resource.appendpouInstance(new_instance)
def GetEditedResourceInfos(self, tagname):
resource = self.GetEditedElement(tagname)
if resource is not None:
- tasks = resource.getTask()
- instances = resource.getPouInstance()
+ tasks = resource.gettask()
+ instances = resource.getpouInstance()
tasks_data = []
instances_data = []
for task in tasks:
new_task = {}
- new_task["Name"] = task.getName()
- single = task.getSingle()
+ new_task["Name"] = task.getname()
+ single = task.getsingle()
if single:
new_task["Single"] = single
else:
new_task["Single"] = ""
- interval = task.getInterval()
+ interval = task.getinterval()
if interval:
text = ""
if interval.hour != 0:
@@ -2295,39 +2294,31 @@
new_task["Interval"] = text
else:
new_task["Interval"] = ""
- new_task["Priority"] = str(task.priority.getValue())
+ new_task["Priority"] = str(task.getpriority())
tasks_data.append(new_task)
- for instance in task.getPouInstance():
+ for instance in task.getpouInstance():
new_instance = {}
- new_instance["Name"] = instance.getName()
- new_instance["Type"] = instance.getType()
- new_instance["Task"] = task.getName()
+ new_instance["Name"] = instance.getname()
+ new_instance["Type"] = instance.gettype()
+ new_instance["Task"] = task.getname()
instances_data.append(new_instance)
for instance in instances:
new_instance = {}
- new_instance["Name"] = instance.getName()
- new_instance["Type"] = instance.getType()
+ new_instance["Name"] = instance.getname()
+ new_instance["Type"] = instance.gettype()
new_instance["Task"] = ""
instances_data.append(new_instance)
return tasks_data, instances_data
def OpenXMLFile(self, filepath):
- if self.VerifyXML:
- if sys:
- sys.stdout = HolePseudoFile()
- result = pyxsval.parseAndValidate(filepath, os.path.join(ScriptDirectory, "plcopen", "TC6_XML_V10_B.xsd"))
- if sys:
- sys.stdout = sys.__stdout__
- tree = result.getTree()
- else:
- xmlfile = open(filepath, 'r')
- tree = minidom.parse(xmlfile)
- xmlfile.close()
+ xmlfile = open(filepath, 'r')
+ tree = minidom.parse(xmlfile)
+ xmlfile.close()
self.Project = plcopen.project()
for child in tree.childNodes:
if child.nodeType == tree.ELEMENT_NODE and child.nodeName == "project":
- self.Project.loadXMLTree(child)
+ self.Project.loadXMLTree(child, ["xmlns", "xmlns:xhtml", "xmlns:xsi", "xsi:schemaLocation"])
self.SetFilePath(filepath)
self.ProjectBuffer = UndoBuffer(self.Copy(self.Project), True)
self.Buffering = False
@@ -2344,9 +2335,9 @@
if not filepath and self.FilePath == "":
return False
else:
- contentheader = self.Project.getContentHeader()
+ contentheader = self.Project.getcontentHeader()
contentheader["modificationDateTime"] = datetime(*localtime()[:6])
- self.Project.setContentHeader(contentheader)
+ self.Project.setcontentHeader(contentheader)
text = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
extras = {"xmlns" : "http://www.plcopen.org/xml/tc6.xsd",
@@ -2355,13 +2346,6 @@
"xsi:schemaLocation" : "http://www.plcopen.org/xml/tc6.xsd http://www.plcopen.org/xml/tc6.xsd"}
text += self.Project.generateXMLText("project", 0, extras)
- if self.VerifyXML:
- if sys:
- sys.stdout = HolePseudoFile()
- pyxsval.parseAndValidateString(text, open(os.path.join(ScriptDirectory, "plcopen", "TC6_XML_V10_B.xsd"),"r").read())
- if sys:
- sys.stdout = sys.__stdout__
-
if filepath:
xmlfile = open(filepath,"w")
else:
--- a/PLCGenerator.py Tue Jan 22 10:53:34 2008 +0100
+++ b/PLCGenerator.py Tue Jan 22 10:57:41 2008 +0100
@@ -41,106 +41,110 @@
compute = ""
lines = text.splitlines()
if len(lines) > 0:
- spaces = 0
- while lines[0][spaces] == " ":
- spaces += 1
- indent = ""
- for i in xrange(spaces, nb_spaces):
- indent += " "
- for line in lines:
- if line != "":
- compute += "%s%s\n"%(indent, line)
- else:
- compute += "\n"
+ line_num = 0
+ while line_num < len(lines) and len(lines[line_num].strip()) == 0:
+ line_num += 1
+ if line_num < len(lines):
+ spaces = 0
+ while lines[line_num][spaces] == " ":
+ spaces += 1
+ indent = ""
+ for i in xrange(spaces, nb_spaces):
+ indent += " "
+ for line in lines:
+ if line != "":
+ compute += "%s%s\n"%(indent, line)
+ else:
+ compute += "\n"
return compute
def GenerateDataType(datatype_name):
if not datatypeComputed.get(datatype_name, True):
datatypeComputed[datatype_name] = True
global currentProject, currentProgram
- datatype = currentProject.getDataType(datatype_name)
- datatype_def = " %s :"%datatype.getName()
- basetype_content = datatype.baseType.getContent()
+ datatype = currentProject.getdataType(datatype_name)
+ datatype_def = " %s :"%datatype.getname()
+ basetype_content = datatype.baseType.getcontent()
if basetype_content["name"] in ["string", "wstring"]:
datatype_def += " %s"%basetype_content["name"].upper()
elif basetype_content["name"] == "derived":
- basetype_name = basetype_content["value"].getName()
+ basetype_name = basetype_content["value"].getname()
GenerateDataType(basetype_name)
datatype_def += " %s"%basetype_name
elif basetype_content["name"] in ["subrangeSigned", "subrangeUnsigned"]:
- base_type = basetype_content["value"].baseType.getContent()
+ base_type = basetype_content["value"].baseType.getcontent()
if base_type["name"] == "derived":
- basetype_name = base_type["value"].getName()
+ basetype_name = base_type["value"].getname()
else:
basetype_name = base_type["name"]
GenerateDataType(basetype_name)
- min_value = basetype_content["value"].range.getLower()
- max_value = basetype_content["value"].range.getUpper()
+ min_value = basetype_content["value"].range.getlower()
+ max_value = basetype_content["value"].range.getupper()
datatype_def += " %s (%d..%d)"%(basetype_name, min_value, max_value)
elif basetype_content["name"] == "enum":
values = []
- for value in basetype_content["value"].values.getValue():
- values.append(value.getName())
+ for value in basetype_content["value"].values.getvalue():
+ values.append(value.getname())
datatype_def += " (%s)"%", ".join(values)
elif basetype_content["name"] == "array":
- base_type = basetype_content["value"].baseType.getContent()
+ base_type = basetype_content["value"].baseType.getcontent()
if base_type["name"] == "derived":
- basetype_name = base_type["value"].getName()
+ basetype_name = base_type["value"].getname()
elif base_type["name"] in ["string", "wstring"]:
basetype_name = base_type["name"].upper()
else:
basetype_name = base_type["name"]
GenerateDataType(basetype_name)
dimensions = []
- for dimension in basetype_content["value"].getDimension():
- dimensions.append("0..%d"%(dimension.getUpper() - 1))
+ for dimension in basetype_content["value"].getdimension():
+ dimensions.append("0..%d"%(dimension.getupper() - 1))
datatype_def += " ARRAY [%s] OF %s"%(",".join(dimensions), basetype_name)
else:
datatype_def += " %s"%basetype_content["name"]
if datatype.initialValue is not None:
- datatype_def += " := %s"%str(datatype.initialValue.getValue())
+ datatype_def += " := %s"%str(datatype.initialValue.getvalue())
currentProgram += "%s;\n"%datatype_def
def GeneratePouProgram(pou_name):
if not pouComputed.get(pou_name, True):
pouComputed[pou_name] = True
global currentProject, currentProgram
- pou = currentProject.getPou(pou_name)
- pou_type = pou.getPouType().getValue()
+ pou = currentProject.getpou(pou_name)
+ pou_type = pou.getpouType()
if pou_type in pouTypeNames:
- pou_program = PouProgram(pou.getName(), pouTypeNames[pou_type])
+ pou_program = PouProgram(pou.getname(), pouTypeNames[pou_type])
else:
raise ValueError, "Undefined pou type"
- pou_program.GenerateInterface(pou.getInterface())
+ pou_program.GenerateInterface(pou.getinterface())
pou_program.GenerateConnectionTypes(pou)
pou_program.GenerateProgram(pou)
currentProgram += pou_program.GenerateSTProgram()
def GenerateConfiguration(configuration):
- config = "\nCONFIGURATION %s\n"%configuration.getName()
- for varlist in configuration.getGlobalVars():
+ config = "\nCONFIGURATION %s\n"%configuration.getname()
+ for varlist in configuration.getglobalVars():
config += " VAR_GLOBAL"
- if varlist.getRetain():
+ if varlist.getretain():
config += " RETAIN"
- if varlist.getConstant():
+ if varlist.getconstant():
config += " CONSTANT"
config += "\n"
- for var in varlist.getVariable():
- vartype_content = var.getType().getContent()
+ for var in varlist.getvariable():
+ vartype_content = var.gettype().getcontent()
if vartype_content["name"] == "derived":
- var_type = vartype_content["value"].getName()
+ var_type = vartype_content["value"].getname()
elif vartype_content["name"] in ["string", "wstring"]:
var_type = vartype_content["name"].upper()
else:
var_type = vartype_content["name"]
- config += " %s "%var.getName()
- address = var.getAddress()
+ config += " %s "%var.getname()
+ address = var.getaddress()
if address:
config += "AT %s "%address
config += ": %s"%var_type
- initial = var.getInitialValue()
+ initial = var.getinitialValue()
if initial:
- value = str(initial.getValue())
+ value = str(initial.getvalue())
value = {"TRUE":"0","FALSE":"1"}.get(value.upper(), value)
if var_type == "STRING":
config += " := '%s'"%value
@@ -150,36 +154,36 @@
config += " := %s"%value
config += ";\n"
config += " END_VAR\n"
- for resource in configuration.getResource():
+ for resource in configuration.getresource():
config += GenerateResource(resource)
config += "END_CONFIGURATION\n"
return config
def GenerateResource(resource):
- resrce = "\n RESOURCE %s ON BEREMIZ\n"%resource.getName()
- for varlist in resource.getGlobalVars():
+ resrce = "\n RESOURCE %s ON BEREMIZ\n"%resource.getname()
+ for varlist in resource.getglobalVars():
resrce += " VAR_GLOBAL"
- if varlist.getRetain():
+ if varlist.getretain():
resrce += " RETAIN"
- if varlist.getConstant():
+ if varlist.getconstant():
resrce += " CONSTANT"
resrce += "\n"
- for var in varlist.getVariable():
- vartype_content = var.getType().getContent()
+ for var in varlist.getvariable():
+ vartype_content = var.gettype().getcontent()
if vartype_content["name"] == "derived":
- var_type = vartype_content["value"].getName()
+ var_type = vartype_content["value"].getname()
elif vartype_content["name"] in ["string", "wstring"]:
var_type = vartype_content["name"].upper()
else:
var_type = vartype_content["name"]
- resrce += " %s "%var.getName()
- address = var.getAddress()
+ resrce += " %s "%var.getname()
+ address = var.getaddress()
if address:
resrce += "AT %s "%address
resrce += ": %s"%var_type
- initial = var.getInitialValue()
+ initial = var.getinitialValue()
if initial:
- value = str(initial.getValue())
+ value = str(initial.getvalue())
value = {"TRUE":"0","FALSE":"1"}.get(value.upper(), value)
if var_type == "STRING":
resrce += " := '%s'"%value
@@ -189,14 +193,14 @@
resrce += " := %s"%value
resrce += ";\n"
resrce += " END_VAR\n"
- tasks = resource.getTask()
+ tasks = resource.gettask()
for task in tasks:
- resrce += " TASK %s("%task.getName()
+ resrce += " TASK %s("%task.getname()
args = []
- single = task.getSingle()
+ single = task.getsingle()
if single:
args.append("SINGLE := %s"%single)
- interval = task.getInterval()
+ interval = task.getinterval()
if interval:
text = "t#"
if interval.hour != 0:
@@ -208,13 +212,13 @@
if interval.microsecond != 0:
text += "%dms"%(interval.microsecond / 1000)
args.append("INTERVAL := %s"%text)
- args.append("PRIORITY := %s"%str(task.priority.getValue()))
+ args.append("PRIORITY := %s"%str(task.getpriority()))
resrce += ",".join(args) + ");\n"
for task in tasks:
- for instance in task.getPouInstance():
- resrce += " PROGRAM %s WITH %s : %s;\n"%(instance.getName(), task.getName(), instance.getType())
- for instance in resource.getPouInstance():
- resrce += " PROGRAM %s : %s;\n"%(instance.getName(), instance.getType())
+ for instance in task.getpouInstance():
+ resrce += " PROGRAM %s WITH %s : %s;\n"%(instance.getname(), task.getname(), instance.gettype())
+ for instance in resource.getpouInstance():
+ resrce += " PROGRAM %s : %s;\n"%(instance.getname(), instance.gettype())
resrce += " END_RESOURCE\n"
return resrce
@@ -258,40 +262,40 @@
return None
def GetConnectedConnection(self, connection, body):
- links = connection.getConnections()
+ links = connection.getconnections()
if links and len(links) == 1:
return self.GetLinkedConnection(links[0], body)
return None
def GetLinkedConnection(self, link, body):
- parameter = link.getFormalParameter()
- instance = body.getContentInstance(link.getRefLocalId())
- if isinstance(instance, (plcopen.inVariable, plcopen.inOutVariable, plcopen.continuation, plcopen.contact, plcopen.coil)):
+ 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)):
return instance.connectionPointOut
- elif isinstance(instance, plcopen.block):
- outputvariables = instance.outputVariables.getVariable()
+ elif isinstance(instance, plcopen.fbdObjects_block):
+ outputvariables = instance.outputVariables.getvariable()
if len(outputvariables) == 1:
return outputvariables[0].connectionPointOut
elif parameter:
for variable in outputvariables:
- if variable.getFormalParameter() == parameter:
+ if variable.getformalParameter() == parameter:
return variable.connectionPointOut
else:
point = link.getPosition()[-1]
for variable in outputvariables:
- relposition = variable.connectionPointOut.getRelPosition()
- blockposition = instance.getPosition()
+ relposition = variable.connectionPointOut.getrelPositionXY()
+ blockposition = instance.getposition()
if point.x == blockposition.x + relposition[0] and point.y == blockposition.y + relposition[1]:
return variable.connectionPointOut
- elif isinstance(instance, plcopen.leftPowerRail):
- outputconnections = instance.getConnectionPointOut()
+ elif isinstance(instance, plcopen.ldObjects_leftPowerRail):
+ outputconnections = instance.getconnectionPointOut()
if len(outputconnections) == 1:
return outputconnections[0]
else:
- point = link.getPosition()[-1]
+ point = link.getposition()[-1]
for outputconnection in outputconnections:
- relposition = outputconnection.getRelPosition()
- powerrailposition = instance.getPosition()
+ relposition = outputconnection.getrelPositionXY()
+ powerrailposition = instance.getposition()
if point.x == powerrailposition.x + relposition[0] and point.y == powerrailposition.y + relposition[1]:
return outputconnection
return None
@@ -304,106 +308,106 @@
def GenerateInterface(self, interface):
if self.Type == "FUNCTION":
- returntype_content = interface.getReturnType().getContent()
+ returntype_content = interface.getreturnType().getcontent()
if returntype_content["value"] is None:
self.ReturnType = returntype_content["name"]
else:
- self.ReturnType = returntype_content["value"].getName()
- for varlist in interface.getContent():
+ self.ReturnType = returntype_content["value"].getname()
+ for varlist in interface.getcontent():
variables = []
located = False
- for var in varlist["value"].getVariable():
- vartype_content = var.getType().getContent()
+ for var in varlist["value"].getvariable():
+ vartype_content = var.gettype().getcontent()
if vartype_content["name"] == "derived":
- var_type = vartype_content["value"].getName()
+ var_type = vartype_content["value"].getname()
GeneratePouProgram(var_type)
blocktype = GetBlockType(var_type)
if blocktype is not None:
- variables.extend(blocktype["initialise"](var_type, var.getName()))
+ variables.extend(blocktype["initialise"](var_type, var.getname()))
located = False
else:
- initial = var.getInitialValue()
+ initial = var.getinitialValue()
if initial:
- initial_value = initial.getValue()
+ initial_value = initial.getvalue()
else:
initial_value = None
- address = var.getAddress()
+ address = var.getaddress()
if address:
located = True
- variables.append((vartype_content["value"].getName(), var.getName(), address, initial_value))
+ variables.append((vartype_content["value"].getname(), var.getname(), address, initial_value))
else:
- initial = var.getInitialValue()
+ initial = var.getinitialValue()
if initial:
- initial_value = initial.getValue()
+ initial_value = initial.getvalue()
else:
initial_value = None
- address = var.getAddress()
+ address = var.getaddress()
if address:
located = True
if vartype_content["name"] in ["string", "wstring"]:
- variables.append((vartype_content["name"].upper(), var.getName(), address, initial_value))
+ variables.append((vartype_content["name"].upper(), var.getname(), address, initial_value))
else:
- variables.append((vartype_content["name"], var.getName(), address, initial_value))
+ variables.append((vartype_content["name"], var.getname(), address, initial_value))
if len(variables) > 0:
- self.Interface.append((varTypeNames[varlist["name"]], varlist["value"].getRetain(),
- varlist["value"].getConstant(), located, variables))
+ self.Interface.append((varTypeNames[varlist["name"]], varlist["value"].getretain(),
+ varlist["value"].getconstant(), located, variables))
def GenerateConnectionTypes(self, pou):
- body = pou.getBody()
- body_content = body.getContent()
+ body = pou.getbody()
+ body_content = body.getcontent()
body_type = body_content["name"]
if body_type in ["FBD", "LD", "SFC"]:
- for instance in body.getContentInstances():
- if isinstance(instance, (plcopen.inVariable, plcopen.outVariable, plcopen.inOutVariable)):
- expression = instance.getExpression()
+ for instance in body.getcontentInstances():
+ if isinstance(instance, (plcopen.fbdObjects_inVariable, plcopen.fbdObjects_outVariable, plcopen.fbdObjects_inOutVariable)):
+ expression = instance.getexpression()
var_type = self.GetVariableType(expression)
- if expression == pou.getName():
- returntype_content = pou.interface.getReturnType().getContent()
+ if expression == pou.getname():
+ returntype_content = pou.interface.getreturnType().getcontent()
if returntype_content["name"] == "derived":
- var_type = returntype_content["value"].getName()
+ var_type = returntype_content["value"].getname()
elif returntype_content["name"] in ["string", "wstring"]:
var_type = returntype_content["name"].upper()
else:
var_type = returntype_content["name"]
elif var_type is None:
var_type = expression.split("#")[0]
- if isinstance(instance, (plcopen.inVariable, plcopen.inOutVariable)):
+ if isinstance(instance, (plcopen.fbdObjects_inVariable, plcopen.fbdObjects_inOutVariable)):
self.ConnectionTypes[instance.connectionPointOut] = var_type
- if isinstance(instance, (plcopen.outVariable, plcopen.inOutVariable)):
+ if isinstance(instance, (plcopen.fbdObjects_outVariable, plcopen.fbdObjects_inOutVariable)):
self.ConnectionTypes[instance.connectionPointIn] = var_type
connected = self.GetConnectedConnection(instance.connectionPointIn, body)
if connected and connected not in self.ConnectionTypes:
for connection in self.ExtractRelatedConnections(connected):
self.ConnectionTypes[connection] = var_type
- elif isinstance(instance, (plcopen.contact, plcopen.coil)):
+ elif isinstance(instance, (plcopen.ldObjects_contact, plcopen.ldObjects_coil)):
self.ConnectionTypes[instance.connectionPointOut] = "BOOL"
self.ConnectionTypes[instance.connectionPointIn] = "BOOL"
connected = self.GetConnectedConnection(instance.connectionPointIn, body)
if connected and connected not in self.ConnectionTypes:
for connection in self.ExtractRelatedConnections(connected):
self.ConnectionTypes[connection] = "BOOL"
- elif isinstance(instance, plcopen.leftPowerRail):
- for connection in instance.getConnectionPointOut():
+ elif isinstance(instance, plcopen.ldObjects_leftPowerRail):
+ for connection in instance.getconnectionPointOut():
self.ConnectionTypes[connection] = "BOOL"
- elif isinstance(instance, plcopen.rightPowerRail):
- for connection in instance.getConnectionPointIn():
+ elif isinstance(instance, plcopen.ldObjects_rightPowerRail):
+ for connection in instance.getconnectionPointIn():
self.ConnectionTypes[connection] = "BOOL"
connected = self.GetConnectedConnection(connection, body)
if connected and connected not in self.ConnectionTypes:
for connection in self.ExtractRelatedConnections(connected):
self.ConnectionTypes[connection] = "BOOL"
- elif isinstance(instance, plcopen.transition):
- content = instance.condition.getContent()
+ elif isinstance(instance, plcopen.sfcObjects_transition):
+ content = instance.condition.getcontent()
if content["name"] == "connection" and len(content["value"]) == 1:
connected = self.GetLinkedConnection(content["value"][0], body)
if connected and connected not in self.ConnectionTypes:
for connection in self.ExtractRelatedConnections(connected):
self.ConnectionTypes[connection] = "BOOL"
- elif isinstance(instance, plcopen.block):
- block_infos = GetBlockType(instance.getTypeName())
+ elif isinstance(instance, plcopen.fbdObjects_block):
+ block_infos = GetBlockType(instance.gettypeName())
undefined = {}
- for variable in instance.outputVariables.getVariable():
- output_name = variable.getFormalParameter()
+ for variable in instance.outputVariables.getvariable():
+ output_name = variable.getformalParameter()
for oname, otype, oqualifier in block_infos["outputs"]:
if output_name == oname and variable.connectionPointOut not in self.ConnectionTypes:
if otype.startswith("ANY"):
@@ -413,8 +417,8 @@
else:
for connection in self.ExtractRelatedConnections(variable.connectionPointOut):
self.ConnectionTypes[connection] = otype
- for variable in instance.inputVariables.getVariable():
- input_name = variable.getFormalParameter()
+ for variable in instance.inputVariables.getvariable():
+ input_name = variable.getformalParameter()
for iname, itype, iqualifier in block_infos["inputs"]:
if input_name == iname:
connected = self.GetConnectedConnection(variable.connectionPointIn, body)
@@ -443,64 +447,64 @@
self.ConnectionTypes[connection] = var_type
def GenerateProgram(self, pou):
- body = pou.getBody()
- body_content = body.getContent()
+ body = pou.getbody()
+ body_content = body.getcontent()
body_type = body_content["name"]
if body_type in ["IL","ST"]:
- self.Program = ReIndentText(body_content["value"].getText(), 2)
+ self.Program = ReIndentText(body_content["value"].gettext(), 2)
elif body_type == "FBD":
orderedInstances = []
otherInstances = []
- for instance in body.getContentInstances():
- if isinstance(instance, (plcopen.outVariable, plcopen.inOutVariable, plcopen.block)):
- executionOrderId = instance.getExecutionOrderId()
+ for instance in body.getcontentInstances():
+ if isinstance(instance, (plcopen.fbdObjects_outVariable, plcopen.fbdObjects_inOutVariable, plcopen.fbdObjects_block)):
+ executionOrderId = instance.getexecutionOrderId()
if executionOrderId > 0:
orderedInstances.append((executionOrderId, instance))
else:
otherInstances.append(instance)
- elif isinstance(instance, plcopen.connector):
+ elif isinstance(instance, plcopen.commonObjects_connector):
otherInstances.append(instance)
orderedInstances.sort()
instances = [instance for (executionOrderId, instance) in orderedInstances] + otherInstances
for instance in instances:
- if isinstance(instance, (plcopen.outVariable, plcopen.inOutVariable)):
- var = instance.getExpression()
- connections = instance.connectionPointIn.getConnections()
+ if isinstance(instance, (plcopen.fbdObjects_outVariable, plcopen.fbdObjects_inOutVariable)):
+ var = instance.getexpression()
+ connections = instance.connectionPointIn.getconnections()
if connections and len(connections) == 1:
expression = self.ComputeFBDExpression(body, connections[0])
self.Program += " %s := %s;\n"%(var, expression)
- elif isinstance(instance, plcopen.block):
- block_type = instance.getTypeName()
+ elif isinstance(instance, plcopen.fbdObjects_block):
+ block_type = instance.gettypeName()
self.GeneratePouProgram(block_type)
block_infos = GetBlockType(block_type)
block_infos["generate"](self, instance, body, None)
- elif isinstance(instance, plcopen.connector):
- connector = instance.getName()
+ elif isinstance(instance, plcopen.commonObjects_connector):
+ connector = instance.getname()
if self.ComputedConnectors.get(connector, None):
continue
- connections = instance.connectionPointIn.getConnections()
+ connections = instance.connectionPointIn.getconnections()
if connections and len(connections) == 1:
self.ComputedConnectors[connector] = self.ComputeFBDExpression(body, connections[0])
elif body_type == "LD":
- for instance in body.getContentInstances():
- if isinstance(instance, plcopen.coil):
- paths = self.GenerateLDPaths(instance.connectionPointIn.getConnections(), body)
+ for instance in body.getcontentInstances():
+ if isinstance(instance, plcopen.ldObjects_coil):
+ paths = self.GenerateLDPaths(instance.connectionPointIn.getconnections(), body)
if len(paths) > 0:
paths = tuple(paths)
else:
paths = paths[0]
- variable = self.ExtractModifier(instance, instance.getVariable())
+ variable = self.ExtractModifier(instance, instance.getvariable())
expression = self.ComputeLDExpression(paths, True)
self.Program += " %s := %s;\n"%(variable, expression)
elif body_type == "SFC":
- for instance in body.getContentInstances():
- if isinstance(instance, plcopen.step):
+ for instance in body.getcontentInstances():
+ if isinstance(instance, plcopen.sfcObjects_step):
self.GenerateSFCStep(instance, pou)
- elif isinstance(instance, plcopen.actionBlock):
+ elif isinstance(instance, plcopen.commonObjects_actionBlock):
self.GenerateSFCStepActions(instance, pou)
- elif isinstance(instance, plcopen.transition):
+ elif isinstance(instance, plcopen.sfcObjects_transition):
self.GenerateSFCTransition(instance, pou)
- elif isinstance(instance, plcopen.jumpStep):
+ elif isinstance(instance, plcopen.sfcObjects_jumpStep):
self.GenerateSFCJump(instance, pou)
if len(self.InitialSteps) > 0 and self.SFCComputedBlocks != "":
action_name = "COMPUTE_FUNCTION_BLOCKS"
@@ -512,24 +516,24 @@
self.ComputeSFCStep(initialstep)
def ComputeFBDExpression(self, body, link, order = False):
- localid = link.getRefLocalId()
- instance = body.getContentInstance(localid)
- if isinstance(instance, (plcopen.inVariable, plcopen.inOutVariable)):
- return instance.getExpression()
- elif isinstance(instance, plcopen.block):
- block_type = instance.getTypeName()
+ localid = link.getrefLocalId()
+ instance = body.getcontentInstance(localid)
+ if isinstance(instance, (plcopen.fbdObjects_inVariable, plcopen.fbdObjects_inOutVariable)):
+ return instance.getexpression()
+ elif isinstance(instance, plcopen.fbdObjects_block):
+ block_type = instance.gettypeName()
self.GeneratePouProgram(block_type)
block_infos = GetBlockType(block_type)
return block_infos["generate"](self, instance, body, link, order)
- elif isinstance(instance, plcopen.continuation):
- name = instance.getName()
+ elif isinstance(instance, plcopen.commonObjects_continuation):
+ name = instance.getname()
computed_value = self.ComputedConnectors.get(name, None)
if computed_value != None:
return computed_value
- for tmp_instance in body.getContentInstances():
- if isinstance(tmp_instance, plcopen.connector):
- if tmp_instance.getName() == name:
- connections = tmp_instance.connectionPointIn.getConnections()
+ for tmp_instance in body.getcontentInstances():
+ if isinstance(tmp_instance, plcopen.commonObjects_connector):
+ if tmp_instance.getname() == name:
+ connections = tmp_instance.connectionPointIn.getconnections()
if connections and len(connections) == 1:
expression = self.ComputeFBDExpression(body, connections[0], order)
self.ComputedConnectors[name] = expression
@@ -539,18 +543,18 @@
def GenerateLDPaths(self, connections, body):
paths = []
for connection in connections:
- localId = connection.getRefLocalId()
- next = body.getContentInstance(localId)
- if isinstance(next, plcopen.leftPowerRail):
+ localId = connection.getrefLocalId()
+ next = body.getcontentInstance(localId)
+ if isinstance(next, plcopen.ldObjects_leftPowerRail):
paths.append(None)
- elif isinstance(next, plcopen.block):
- block_type = next.getTypeName()
+ elif isinstance(next, plcopen.fbdObjects_block):
+ block_type = next.gettypeName()
self.GeneratePouProgram(block_type)
block_infos = GetBlockType(block_type)
paths.append(block_infos["generate"](self, next, body, connection))
else:
- variable = self.ExtractModifier(next, next.getVariable())
- result = self.GenerateLDPaths(next.connectionPointIn.getConnections(), body)
+ variable = self.ExtractModifier(next, next.getvariable())
+ result = self.GenerateLDPaths(next.connectionPointIn.getconnections(), body)
if len(result) > 1:
paths.append([variable, tuple(result)])
elif type(result[0]) == ListType:
@@ -564,63 +568,63 @@
def GetNetworkType(self, connections, body):
network_type = "FBD"
for connection in connections:
- localId = connection.getRefLocalId()
- next = body.getContentInstance(localId)
- if isinstance(next, plcopen.leftPowerRail) or isinstance(next, plcopen.contact):
+ localId = connection.getrefLocalId()
+ next = body.getcontentInstance(localId)
+ if isinstance(next, plcopen.ldObjects_leftPowerRail) or isinstance(next, plcopen.ldObjects_contact):
return "LD"
- elif isinstance(next, plcopen.block):
- for variable in next.inputVariables.getVariable():
- result = self.GetNetworkType(variable.connectionPointIn.getConnections(), body)
+ elif isinstance(next, plcopen.fbdObjects_block):
+ for variable in next.inputVariables.getvariable():
+ result = self.GetNetworkType(variable.connectionPointIn.getconnections(), body)
if result != "FBD":
return result
- elif isinstance(next, plcopen.inVariable):
+ elif isinstance(next, plcopen.fbdObjects_inVariable):
return "FBD"
- elif isinstance(next, plcopen.inOutVariable):
- return self.GetNetworkType(next.connectionPointIn.getConnections(), body)
+ elif isinstance(next, plcopen.fbdObjects_inOutVariable):
+ return self.GetNetworkType(next.connectionPointIn.getconnections(), body)
else:
return None
return "FBD"
def ExtractDivergenceInput(self, divergence, pou):
- connectionPointIn = divergence.getConnectionPointIn()
+ connectionPointIn = divergence.getconnectionPointIn()
if connectionPointIn:
- connections = connectionPointIn.getConnections()
+ connections = connectionPointIn.getconnections()
if len(connections) == 1:
- instanceLocalId = connections[0].getRefLocalId()
- return pou.body.getContentInstance(instanceLocalId)
+ instanceLocalId = connections[0].getrefLocalId()
+ return pou.body.getcontentInstance(instanceLocalId)
return None
def ExtractConvergenceInputs(self, convergence, pou):
instances = []
- for connectionPointIn in convergence.getConnectionPointIn():
- connections = connectionPointIn.getConnections()
+ for connectionPointIn in convergence.getconnectionPointIn():
+ connections = connectionPointIn.getconnections()
if len(connections) == 1:
- instanceLocalId = connections[0].getRefLocalId()
- instances.append(pou.body.getContentInstance(instanceLocalId))
+ instanceLocalId = connections[0].getrefLocalId()
+ instances.append(pou.body.getcontentInstance(instanceLocalId))
return instances
def GenerateSFCStep(self, step, pou):
- step_name = step.getName()
+ step_name = step.getname()
if step_name not in self.SFCNetworks["Steps"].keys():
- if step.getInitialStep():
+ if step.getinitialStep():
self.InitialSteps.append(step_name)
- step_infos = {"initial" : step.getInitialStep(), "transitions" : [], "actions" : []}
+ step_infos = {"initial" : step.getinitialStep(), "transitions" : [], "actions" : []}
if step.connectionPointIn:
instances = []
- connections = step.connectionPointIn.getConnections()
+ connections = step.connectionPointIn.getconnections()
if len(connections) == 1:
- instanceLocalId = connections[0].getRefLocalId()
- instance = pou.body.getContentInstance(instanceLocalId)
- if isinstance(instance, plcopen.transition):
+ instanceLocalId = connections[0].getrefLocalId()
+ instance = pou.body.getcontentInstance(instanceLocalId)
+ if isinstance(instance, plcopen.sfcObjects_transition):
instances.append(instance)
- elif isinstance(instance, plcopen.selectionConvergence):
+ elif isinstance(instance, plcopen.sfcObjects_selectionConvergence):
instances.extend(self.ExtractConvergenceInputs(instance, pou))
- elif isinstance(instance, plcopen.simultaneousDivergence):
+ elif isinstance(instance, plcopen.sfcObjects_simultaneousDivergence):
transition = self.ExtractDivergenceInput(instance, pou)
if transition:
- if isinstance(transition, plcopen.transition):
+ if isinstance(transition, plcopen.sfcObjects_transition):
instances.append(transition)
- elif isinstance(transition, plcopen.selectionConvergence):
+ elif isinstance(transition, plcopen.sfcObjects_selectionConvergence):
instances.extend(self.ExtractConvergenceInputs(transition, pou))
for instance in instances:
self.GenerateSFCTransition(instance, pou)
@@ -629,23 +633,23 @@
self.SFCNetworks["Steps"][step_name] = step_infos
def GenerateSFCJump(self, jump, pou):
- jump_target = jump.getTargetName()
+ jump_target = jump.gettargetName()
if jump.connectionPointIn:
instances = []
- connections = jump.connectionPointIn.getConnections()
+ connections = jump.connectionPointIn.getconnections()
if len(connections) == 1:
- instanceLocalId = connections[0].getRefLocalId()
- instance = pou.body.getContentInstance(instanceLocalId)
- if isinstance(instance, plcopen.transition):
+ instanceLocalId = connections[0].getrefLocalId()
+ instance = pou.body.getcontentInstance(instanceLocalId)
+ if isinstance(instance, plcopen.sfcObjects_transition):
instances.append(instance)
- elif isinstance(instance, plcopen.selectionConvergence):
+ elif isinstance(instance, plcopen.sfcObjects_selectionConvergence):
instances.extend(self.ExtractConvergenceInputs(instance, pou))
- elif isinstance(instance, plcopen.simultaneousDivergence):
+ elif isinstance(instance, plcopen.sfcObjects_simultaneousDivergence):
transition = self.ExtractDivergenceInput(instance, pou)
if transition:
- if isinstance(transition, plcopen.transition):
+ if isinstance(transition, plcopen.sfcObjects_transition):
instances.append(transition)
- elif isinstance(transition, plcopen.selectionConvergence):
+ elif isinstance(transition, plcopen.sfcObjects_selectionConvergence):
instances.extend(self.ExtractConvergenceInputs(transition, pou))
for instance in instances:
self.GenerateSFCTransition(instance, pou)
@@ -653,14 +657,14 @@
self.SFCNetworks["Transitions"][instance]["to"].append(jump_target)
def GenerateSFCStepActions(self, actionBlock, pou):
- connections = actionBlock.connectionPointIn.getConnections()
+ connections = actionBlock.connectionPointIn.getconnections()
if len(connections) == 1:
- stepLocalId = connections[0].getRefLocalId()
- step = pou.body.getContentInstance(stepLocalId)
+ stepLocalId = connections[0].getrefLocalId()
+ step = pou.body.getcontentInstance(stepLocalId)
self.GenerateSFCStep(step, pou)
- step_name = step.getName()
+ step_name = step.getname()
if step_name in self.SFCNetworks["Steps"].keys():
- actions = actionBlock.getActions()
+ actions = actionBlock.getactions()
for action in actions:
action_infos = {"qualifier" : action["qualifier"], "content" : action["value"]}
if "duration" in action:
@@ -677,27 +681,27 @@
def GenerateSFCAction(self, action_name, pou):
if action_name not in self.SFCNetworks["Actions"].keys():
- actionContent = pou.getAction(action_name)
+ actionContent = pou.getaction(action_name)
if actionContent:
- actionType = actionContent.getBodyType()
- actionBody = actionContent.getBody()
+ actionType = actionContent.getbodyType()
+ actionBody = actionContent.getbody()
if actionType in ["ST", "IL"]:
- self.SFCNetworks["Actions"][action_name] = ReIndentText(actionContent.getText(), 4)
+ self.SFCNetworks["Actions"][action_name] = ReIndentText(actionContent.gettext(), 4)
elif actionType == "FBD":
- for instance in actionBody.getContentInstances():
- if isinstance(instance, plcopen.outVariable):
- var = instance.getExpression()
- connections = instance.connectionPointIn.getConnections()
+ for instance in actionBody.getcontentInstances():
+ if isinstance(instance, plcopen.fbdObjects_outVariable):
+ var = instance.getexpression()
+ connections = instance.connectionPointIn.getconnections()
if connections and len(connections) == 1:
expression = self.ComputeFBDExpression(actionBody, connections[0])
action_content = self.Program + " %s := %s;\n"%(var, expression)
self.Program = ""
self.SFCNetworks["Actions"][action_name] = ReIndentText(action_content, 4)
elif actionType == "LD":
- for instance in actionbody.getContentInstances():
- if isinstance(instance, plcopen.coil):
- paths = self.GenerateLDPaths(instance.connectionPointIn.getConnections(), actionBody)
- variable = self.ExtractModifier(instance, instance.getVariable())
+ for instance in actionbody.getcontentInstances():
+ if isinstance(instance, plcopen.ldObjects_coil):
+ paths = self.GenerateLDPaths(instance.connectionPointIn.getconnections(), actionBody)
+ variable = self.ExtractModifier(instance, instance.getvariable())
expression = self.ComputeLDExpression(paths, True)
action_content = self.Program + " %s := %s;\n"%(variable, expression)
self.Program = ""
@@ -706,53 +710,53 @@
def GenerateSFCTransition(self, transition, pou):
if transition not in self.SFCNetworks["Transitions"].keys():
steps = []
- connections = transition.connectionPointIn.getConnections()
+ connections = transition.connectionPointIn.getconnections()
if len(connections) == 1:
- instanceLocalId = connections[0].getRefLocalId()
- instance = pou.body.getContentInstance(instanceLocalId)
- if isinstance(instance, plcopen.step):
+ instanceLocalId = connections[0].getrefLocalId()
+ instance = pou.body.getcontentInstance(instanceLocalId)
+ if isinstance(instance, plcopen.sfcObjects_step):
steps.append(instance)
- elif isinstance(instance, plcopen.selectionDivergence):
+ elif isinstance(instance, plcopen.sfcObjects_selectionDivergence):
step = self.ExtractDivergenceInput(instance, pou)
if step:
- if isinstance(step, plcopen.step):
+ if isinstance(step, plcopen.sfcObjects_step):
steps.append(step)
- elif isinstance(step, plcopen.simultaneousConvergence):
+ elif isinstance(step, plcopen.sfcObjects_simultaneousConvergence):
steps.extend(self.ExtractConvergenceInputs(step, pou))
- elif isinstance(instance, plcopen.simultaneousConvergence):
+ elif isinstance(instance, plcopen.sfcObjects_simultaneousConvergence):
steps.extend(self.ExtractConvergenceInputs(instance, pou))
- transition_infos = {"priority": transition.getPriority(), "from": [], "to" : []}
- transitionValues = transition.getConditionContent()
+ transition_infos = {"priority": transition.getpriority(), "from": [], "to" : []}
+ transitionValues = transition.getconditionContent()
if transitionValues["type"] == "inline":
transition_infos["content"] = "\n := %s;\n"%transitionValues["value"]
elif transitionValues["type"] == "reference":
- transitionContent = pou.getTransition(transitionValues["value"])
- transitionType = transitionContent.getBodyType()
- transitionBody = transitionContent.getBody()
+ transitionContent = pou.gettransition(transitionValues["value"])
+ transitionType = transitionContent.getbodyType()
+ transitionBody = transitionContent.getbody()
if transitionType == "IL":
- transition_infos["content"] = ":\n%s"%ReIndentText(transitionBody.getText(), 4)
+ transition_infos["content"] = ":\n%s"%ReIndentText(transitionBody.gettext(), 4)
elif transitionType == "ST":
- transition_infos["content"] = "\n%s"%ReIndentText(transitionBody.getText(), 4)
+ transition_infos["content"] = "\n%s"%ReIndentText(transitionBody.gettext(), 4)
elif transitionType == "FBD":
- for instance in transitionBody.getContentInstances():
- if isinstance(instance, plcopen.outVariable):
- connections = instance.connectionPointIn.getConnections()
+ for instance in transitionBody.getcontentInstances():
+ if isinstance(instance, plcopen.fbdObjects_outVariable):
+ connections = instance.connectionPointIn.getconnections()
if connections and len(connections) == 1:
expression = self.ComputeFBDExpression(transitionBody, connections[0])
transition_infos["content"] = "\n := %s;\n"%expression
self.SFCComputedBlocks += self.Program
self.Program = ""
elif transitionType == "LD":
- for instance in transitionBody.getContentInstances():
- if isinstance(instance, plcopen.coil):
- paths = self.GenerateLDPaths(instance.connectionPointIn.getConnections(), transitionBody)
+ for instance in transitionBody.getcontentInstances():
+ if isinstance(instance, plcopen.ldObjects_coil):
+ paths = self.GenerateLDPaths(instance.connectionPointIn.getconnections(), transitionBody)
expression = self.ComputeLDExpression(paths, True)
transition_infos["content"] = "\n := %s;\n"%expression
self.SFCComputedBlocks += self.Program
self.Program = ""
elif transitionValues["type"] == "connection":
- body = pou.getBody()
- connections = transition.getConnections()
+ body = pou.getbody()
+ connections = transition.getconnections()
network_type = self.GetNetworkType(connections, body)
if network_type == None:
raise Exception
@@ -769,7 +773,7 @@
self.Program = ""
for step in steps:
self.GenerateSFCStep(step, pou)
- step_name = step.getName()
+ step_name = step.getname()
if step_name in self.SFCNetworks["Steps"].keys():
transition_infos["from"].append(step_name)
self.SFCNetworks["Steps"][step_name]["transitions"].append(transition)
@@ -840,15 +844,14 @@
return paths
def ExtractModifier(self, variable, text):
- if variable.getNegated():
+ if variable.getnegated():
return "NOT(%s)"%text
else:
- edge = variable.getEdge()
- if edge:
- if edge.getValue() == "rising":
- return self.AddTrigger("R_TRIG", text)
- elif edge.getValue() == "falling":
- return self.AddTrigger("F_TRIG", text)
+ edge = variable.getedge()
+ if edge == "rising":
+ return self.AddTrigger("R_TRIG", text)
+ elif edge == "falling":
+ return self.AddTrigger("F_TRIG", text)
return text
def AddTrigger(self, edge, text):
@@ -904,10 +907,10 @@
global currentProject, currentProgram
currentProject = project
currentProgram = ""
- for datatype in project.getDataTypes():
- datatypeComputed[datatype.getName()] = False
- for pou in project.getPous():
- pouComputed[pou.getName()] = False
+ for datatype in project.getdataTypes():
+ datatypeComputed[datatype.getname()] = False
+ for pou in project.getpous():
+ pouComputed[pou.getname()] = False
if len(datatypeComputed) > 0:
currentProgram += "TYPE\n"
for datatype_name in datatypeComputed.keys():
@@ -915,7 +918,7 @@
currentProgram += "END_TYPE\n\n"
for pou_name in pouComputed.keys():
GeneratePouProgram(pou_name)
- for config in project.getConfigurations():
+ for config in project.getconfigurations():
currentProgram += GenerateConfiguration(config)
return currentProgram
--- a/examples/example.xml Tue Jan 22 10:53:34 2008 +0100
+++ b/examples/example.xml Tue Jan 22 10:57:41 2008 +0100
@@ -3,28 +3,28 @@
xmlns="http://www.plcopen.org/xml/tc6.xsd"
xmlns:xhtml="http://www.w3.org/1999/xhtml"
xsi:schemaLocation="http://www.plcopen.org/xml/tc6.xsd http://www.plcopen.org/xml/tc6.xsd">
- <fileHeader contentDescription="Example of PLCOpenEditor usage"
- companyName="Lolitech"
+ <fileHeader companyName="Lolitech"
companyURL="www.lolitech.net"
productName="PLCOpenEditorExample"
+ productVersion="1.0"
productRelease="rc1"
- productVersion="1.0"
- creationDateTime="2006-09-07 18:52:43"/>
+ creationDateTime="2006-09-07 18:52:43"
+ contentDescription="Example of PLCOpenEditor usage"/>
<contentHeader name="Test"
- language="en-US"
+ version="1"
+ modificationDateTime="2008-01-22 11:01:23"
author="Laurent Bessard"
- modificationDateTime="2008-01-10 17:33:58"
- version="1">
+ language="en-US">
<coordinateInfo>
- <pageSize y="2000" x="1000"/>
+ <pageSize x="1000" y="2000"/>
<fbd>
- <scaling y="8" x="8"/>
+ <scaling x="8" y="8"/>
</fbd>
<ld>
- <scaling y="0" x="0"/>
+ <scaling x="0" y="0"/>
</ld>
<sfc>
- <scaling y="0" x="0"/>
+ <scaling x="0" y="0"/>
</sfc>
</coordinateInfo>
</contentHeader>
@@ -33,8 +33,8 @@
<dataType name="MyType">
<baseType>
<array>
- <dimension upper="16" lower="1"/>
- <dimension upper="2" lower="1"/>
+ <dimension lower="1" upper="16"/>
+ <dimension lower="1" upper="2"/>
<baseType>
<INT/>
</baseType>
@@ -89,7 +89,7 @@
<dataType name="MyType4">
<baseType>
<subrangeSigned>
- <range upper="4500" lower="-4500"/>
+ <range lower="-4500" upper="4500"/>
<baseType>
<DINT/>
</baseType>
@@ -143,53 +143,53 @@
</interface>
<body>
<FBD>
- <inVariable localId="2" width="88" height="32" executionOrderId="0">
- <position y="80" x="64"/>
- <connectionPointOut>
- <relPosition y="16" x="88"/>
+ <inVariable localId="2" height="32" width="88">
+ <position x="64" y="80"/>
+ <connectionPointOut>
+ <relPosition x="88" y="16"/>
</connectionPointOut>
<expression>IN1</expression>
</inVariable>
- <inVariable localId="3" width="88" height="32" executionOrderId="0">
- <position y="200" x="64"/>
- <connectionPointOut>
- <relPosition y="16" x="88"/>
+ <inVariable localId="3" height="32" width="88">
+ <position x="64" y="200"/>
+ <connectionPointOut>
+ <relPosition x="88" y="16"/>
</connectionPointOut>
<expression>IN2</expression>
</inVariable>
- <outVariable localId="4" width="96" height="32" executionOrderId="2">
- <position y="176" x="584"/>
- <connectionPointIn>
- <relPosition y="16" x="0"/>
+ <outVariable localId="4" height="32" width="96" executionOrderId="2">
+ <position x="584" y="176"/>
+ <connectionPointIn>
+ <relPosition x="0" y="16"/>
<connection refLocalId="11" formalParameter="Q1">
- <position y="192" x="584"/>
- <position y="192" x="528"/>
+ <position x="584" y="192"/>
+ <position x="528" y="192"/>
</connection>
</connectionPointIn>
<expression>OUT</expression>
</outVariable>
- <block localId="6" height="88" width="104" executionOrderId="3" instanceName="" typeName="AND">
- <position y="104" x="232"/>
+ <block localId="6" width="104" height="88" typeName="AND" executionOrderId="3">
+ <position x="232" y="104"/>
<inputVariables>
<variable formalParameter="IN1" edge="rising">
<connectionPointIn>
- <relPosition y="40" x="0"/>
+ <relPosition x="0" y="40"/>
<connection refLocalId="2">
- <position y="144" x="232"/>
- <position y="144" x="192"/>
- <position y="96" x="192"/>
- <position y="96" x="152"/>
+ <position x="232" y="144"/>
+ <position x="192" y="144"/>
+ <position x="192" y="96"/>
+ <position x="152" y="96"/>
</connection>
</connectionPointIn>
</variable>
<variable formalParameter="IN2">
<connectionPointIn>
- <relPosition y="72" x="0"/>
+ <relPosition x="0" y="72"/>
<connection refLocalId="3">
- <position y="176" x="232"/>
- <position y="176" x="192"/>
- <position y="216" x="192"/>
- <position y="216" x="152"/>
+ <position x="232" y="176"/>
+ <position x="192" y="176"/>
+ <position x="192" y="216"/>
+ <position x="152" y="216"/>
</connection>
</connectionPointIn>
</variable>
@@ -198,40 +198,40 @@
<outputVariables>
<variable formalParameter="OUT">
<connectionPointOut>
- <relPosition y="40" x="104"/>
+ <relPosition x="104" y="40"/>
</connectionPointOut>
</variable>
</outputVariables>
</block>
- <inVariable localId="7" width="88" height="32" executionOrderId="0">
- <position y="336" x="64"/>
- <connectionPointOut>
- <relPosition y="16" x="88"/>
+ <inVariable localId="7" height="32" width="88">
+ <position x="64" y="336"/>
+ <connectionPointOut>
+ <relPosition x="88" y="16"/>
</connectionPointOut>
<expression>IN3</expression>
</inVariable>
- <block localId="8" height="88" width="104" executionOrderId="4" instanceName="" typeName="OR">
- <position y="240" x="232"/>
+ <block localId="8" width="104" height="88" typeName="OR" executionOrderId="4">
+ <position x="232" y="240"/>
<inputVariables>
<variable formalParameter="IN1" negated="true">
<connectionPointIn>
- <relPosition y="40" x="0"/>
+ <relPosition x="0" y="40"/>
<connection refLocalId="3">
- <position y="280" x="232"/>
- <position y="280" x="192"/>
- <position y="216" x="192"/>
- <position y="216" x="152"/>
+ <position x="232" y="280"/>
+ <position x="192" y="280"/>
+ <position x="192" y="216"/>
+ <position x="152" y="216"/>
</connection>
</connectionPointIn>
</variable>
<variable formalParameter="IN2">
<connectionPointIn>
- <relPosition y="72" x="0"/>
+ <relPosition x="0" y="72"/>
<connection refLocalId="7">
- <position y="312" x="232"/>
- <position y="312" x="192"/>
- <position y="352" x="192"/>
- <position y="352" x="152"/>
+ <position x="232" y="312"/>
+ <position x="192" y="312"/>
+ <position x="192" y="352"/>
+ <position x="152" y="352"/>
</connection>
</connectionPointIn>
</variable>
@@ -240,37 +240,39 @@
<outputVariables>
<variable formalParameter="OUT">
<connectionPointOut>
- <relPosition y="40" x="104"/>
+ <relPosition x="104" y="40"/>
</connectionPointOut>
</variable>
</outputVariables>
</block>
<comment localId="10" height="40" width="272">
- <position y="24" x="240"/>
- <content><![CDATA[POU used for testing PLCOpenEditor.]]></content>
+ <position x="240" y="24"/>
+ <content>
+<![CDATA[POU used for testing PLCOpenEditor.]]>
+ </content>
</comment>
- <block localId="11" height="96" width="104" executionOrderId="1" instanceName="SR1" typeName="SR">
- <position y="152" x="424"/>
+ <block localId="11" width="104" height="96" typeName="SR" instanceName="SR1" executionOrderId="1">
+ <position x="424" y="152"/>
<inputVariables>
<variable formalParameter="S1" negated="true">
<connectionPointIn>
- <relPosition y="40" x="0"/>
+ <relPosition x="0" y="40"/>
<connection refLocalId="6" formalParameter="OUT">
- <position y="192" x="424"/>
- <position y="192" x="376"/>
- <position y="144" x="376"/>
- <position y="144" x="336"/>
+ <position x="424" y="192"/>
+ <position x="376" y="192"/>
+ <position x="376" y="144"/>
+ <position x="336" y="144"/>
</connection>
</connectionPointIn>
</variable>
<variable formalParameter="R">
<connectionPointIn>
- <relPosition y="80" x="0"/>
+ <relPosition x="0" y="80"/>
<connection refLocalId="8" formalParameter="OUT">
- <position y="232" x="424"/>
- <position y="232" x="376"/>
- <position y="280" x="376"/>
- <position y="280" x="336"/>
+ <position x="424" y="232"/>
+ <position x="376" y="232"/>
+ <position x="376" y="280"/>
+ <position x="336" y="280"/>
</connection>
</connectionPointIn>
</variable>
@@ -279,7 +281,7 @@
<outputVariables>
<variable formalParameter="Q1">
<connectionPointOut>
- <relPosition y="40" x="104"/>
+ <relPosition x="104" y="40"/>
</connectionPointOut>
</variable>
</outputVariables>
@@ -318,101 +320,103 @@
<body>
<LD>
<comment localId="1" height="40" width="600">
- <position y="10" x="10"/>
- <content><![CDATA[Comment]]></content>
+ <position x="10" y="10"/>
+ <content>
+<![CDATA[Comment]]>
+ </content>
</comment>
<leftPowerRail localId="2" height="80" width="3">
- <position y="60" x="10"/>
+ <position x="10" y="60"/>
<connectionPointOut formalParameter="">
- <relPosition y="20" x="3"/>
+ <relPosition x="3" y="20"/>
</connectionPointOut>
<connectionPointOut formalParameter="">
- <relPosition y="60" x="3"/>
+ <relPosition x="3" y="60"/>
</connectionPointOut>
</leftPowerRail>
- <coil localId="3" width="21" height="15">
- <position y="72" x="265"/>
- <connectionPointIn>
- <relPosition y="8" x="0"/>
+ <coil localId="3" height="15" width="21">
+ <position x="265" y="72"/>
+ <connectionPointIn>
+ <relPosition x="0" y="8"/>
<connection refLocalId="7">
- <position y="80" x="265"/>
- <position y="80" x="195"/>
- </connection>
- </connectionPointIn>
- <connectionPointOut>
- <relPosition y="8" x="21"/>
+ <position x="265" y="80"/>
+ <position x="195" y="80"/>
+ </connection>
+ </connectionPointIn>
+ <connectionPointOut>
+ <relPosition x="21" y="8"/>
</connectionPointOut>
<variable>LDTest</variable>
</coil>
<rightPowerRail localId="4" height="40" width="3">
- <position y="60" x="323"/>
- <connectionPointIn>
- <relPosition y="20" x="0"/>
+ <position x="323" y="60"/>
+ <connectionPointIn>
+ <relPosition x="0" y="20"/>
<connection refLocalId="3">
- <position y="80" x="323"/>
- <position y="80" x="286"/>
+ <position x="323" y="80"/>
+ <position x="286" y="80"/>
</connection>
</connectionPointIn>
</rightPowerRail>
- <contact localId="5" width="21" height="15" negated="true">
- <position y="72" x="42"/>
- <connectionPointIn>
- <relPosition y="8" x="0"/>
+ <contact localId="5" height="15" width="21" negated="true">
+ <position x="42" y="72"/>
+ <connectionPointIn>
+ <relPosition x="0" y="8"/>
<connection refLocalId="2">
- <position y="80" x="42"/>
- <position y="80" x="13"/>
- </connection>
- </connectionPointIn>
- <connectionPointOut>
- <relPosition y="8" x="21"/>
+ <position x="42" y="80"/>
+ <position x="13" y="80"/>
+ </connection>
+ </connectionPointIn>
+ <connectionPointOut>
+ <relPosition x="21" y="8"/>
</connectionPointOut>
<variable>IN1</variable>
</contact>
- <contact localId="7" width="21" height="15">
- <position y="72" x="174"/>
- <connectionPointIn>
- <relPosition y="8" x="0"/>
+ <contact localId="7" height="15" width="21">
+ <position x="174" y="72"/>
+ <connectionPointIn>
+ <relPosition x="0" y="8"/>
<connection refLocalId="5">
- <position y="80" x="174"/>
- <position y="80" x="63"/>
+ <position x="174" y="80"/>
+ <position x="63" y="80"/>
</connection>
<connection refLocalId="9">
- <position y="80" x="174"/>
- <position y="80" x="144"/>
- <position y="120" x="144"/>
- <position y="120" x="114"/>
- </connection>
- </connectionPointIn>
- <connectionPointOut>
- <relPosition y="8" x="21"/>
+ <position x="174" y="80"/>
+ <position x="144" y="80"/>
+ <position x="144" y="120"/>
+ <position x="114" y="120"/>
+ </connection>
+ </connectionPointIn>
+ <connectionPointOut>
+ <relPosition x="21" y="8"/>
</connectionPointOut>
<variable>IN2</variable>
</contact>
- <contact localId="8" width="21" height="15">
- <position y="112" x="42"/>
- <connectionPointIn>
- <relPosition y="8" x="0"/>
+ <contact localId="8" height="15" width="21">
+ <position x="42" y="112"/>
+ <connectionPointIn>
+ <relPosition x="0" y="8"/>
<connection refLocalId="2">
- <position y="120" x="42"/>
- <position y="120" x="13"/>
- </connection>
- </connectionPointIn>
- <connectionPointOut>
- <relPosition y="8" x="21"/>
+ <position x="42" y="120"/>
+ <position x="13" y="120"/>
+ </connection>
+ </connectionPointIn>
+ <connectionPointOut>
+ <relPosition x="21" y="8"/>
</connectionPointOut>
<variable>IN3</variable>
</contact>
- <contact localId="9" width="21" height="15" negated="true">
- <position y="112" x="93"/>
- <connectionPointIn>
- <relPosition y="8" x="0"/>
+ <contact localId="9" height="15" width="21" negated="true">
+ <position x="93" y="112"/>
+ <connectionPointIn>
+ <relPosition x="0" y="8"/>
<connection refLocalId="8">
- <position y="120" x="93"/>
- <position y="120" x="63"/>
- </connection>
- </connectionPointIn>
- <connectionPointOut>
- <relPosition y="8" x="21"/>
+ <position x="93" y="120"/>
+ <position x="63" y="120"/>
+ </connection>
+ </connectionPointIn>
+ <connectionPointOut>
+ <relPosition x="21" y="8"/>
</connectionPointOut>
<variable>IN4</variable>
</contact>
@@ -546,59 +550,61 @@
<transitions>
<transition name="TR1">
<body>
- <ST><![CDATA[:= AND(IN1, IN2, IN3);]]></ST>
+ <ST>
+<![CDATA[:= AND(IN1, IN2, IN3);]]>
+ </ST>
</body>
</transition>
<transition name="TR2">
<body>
<FBD>
- <inVariable localId="2" width="54" height="27">
- <position y="59" x="27"/>
+ <inVariable localId="2" height="27" width="54">
+ <position x="27" y="59"/>
<connectionPointOut>
- <relPosition y="13" x="54"/>
+ <relPosition x="54" y="13"/>
</connectionPointOut>
<expression>IN1</expression>
</inVariable>
- <inVariable localId="3" width="53" height="27">
- <position y="140" x="28"/>
+ <inVariable localId="3" height="27" width="53">
+ <position x="28" y="140"/>
<connectionPointOut>
- <relPosition y="13" x="53"/>
+ <relPosition x="53" y="13"/>
</connectionPointOut>
<expression>IN2</expression>
</inVariable>
- <outVariable localId="4" width="57" height="27">
- <position y="82" x="340"/>
+ <outVariable localId="4" height="27" width="57">
+ <position x="340" y="82"/>
<connectionPointIn>
- <relPosition y="13" x="0"/>
+ <relPosition x="0" y="13"/>
<connection refLocalId="5" formalParameter="Q1">
- <position y="95" x="340"/>
- <position y="95" x="261"/>
+ <position x="340" y="95"/>
+ <position x="261" y="95"/>
</connection>
</connectionPointIn>
<expression>TR2</expression>
</outVariable>
- <block localId="5" height="70" width="100" instanceName="SR1" typeName="SR">
- <position y="63" x="161"/>
+ <block localId="5" width="100" height="70" typeName="SR" instanceName="SR1">
+ <position x="161" y="63"/>
<inputVariables>
<variable formalParameter="S1">
<connectionPointIn>
- <relPosition y="32" x="0"/>
+ <relPosition x="0" y="32"/>
<connection refLocalId="2">
- <position y="95" x="161"/>
- <position y="95" x="121"/>
- <position y="72" x="121"/>
- <position y="72" x="81"/>
+ <position x="161" y="95"/>
+ <position x="121" y="95"/>
+ <position x="121" y="72"/>
+ <position x="81" y="72"/>
</connection>
</connectionPointIn>
</variable>
<variable formalParameter="R">
<connectionPointIn>
- <relPosition y="57" x="0"/>
+ <relPosition x="0" y="57"/>
<connection refLocalId="3">
- <position y="120" x="161"/>
- <position y="120" x="121"/>
- <position y="153" x="121"/>
- <position y="153" x="81"/>
+ <position x="161" y="120"/>
+ <position x="121" y="120"/>
+ <position x="121" y="153"/>
+ <position x="81" y="153"/>
</connection>
</connectionPointIn>
</variable>
@@ -607,7 +613,7 @@
<outputVariables>
<variable formalParameter="Q1">
<connectionPointOut>
- <relPosition y="32" x="100"/>
+ <relPosition x="100" y="32"/>
</connectionPointOut>
</variable>
</outputVariables>
@@ -619,69 +625,69 @@
<body>
<LD>
<leftPowerRail localId="1" height="98" width="2">
- <position y="20" x="31"/>
+ <position x="31" y="20"/>
<connectionPointOut formalParameter="None">
- <relPosition y="20" x="2"/>
+ <relPosition x="2" y="20"/>
</connectionPointOut>
<connectionPointOut formalParameter="None">
- <relPosition y="64" x="2"/>
+ <relPosition x="2" y="64"/>
</connectionPointOut>
</leftPowerRail>
- <contact localId="2" width="21" height="15">
- <position y="32" x="72"/>
+ <contact localId="2" height="15" width="21">
+ <position x="72" y="32"/>
<connectionPointIn>
- <relPosition y="8" x="0"/>
+ <relPosition x="0" y="8"/>
<connection refLocalId="1">
- <position y="40" x="72"/>
- <position y="40" x="33"/>
+ <position x="72" y="40"/>
+ <position x="33" y="40"/>
</connection>
</connectionPointIn>
<connectionPointOut>
- <relPosition y="8" x="21"/>
+ <relPosition x="21" y="8"/>
</connectionPointOut>
<variable>IN2</variable>
</contact>
- <contact localId="3" width="21" height="15" edge="rising">
- <position y="76" x="72"/>
+ <contact localId="3" height="15" width="21" edge="rising">
+ <position x="72" y="76"/>
<connectionPointIn>
- <relPosition y="8" x="0"/>
+ <relPosition x="0" y="8"/>
<connection refLocalId="1">
- <position y="84" x="72"/>
- <position y="84" x="33"/>
+ <position x="72" y="84"/>
+ <position x="33" y="84"/>
</connection>
</connectionPointIn>
<connectionPointOut>
- <relPosition y="8" x="21"/>
+ <relPosition x="21" y="8"/>
</connectionPointOut>
<variable>IN5</variable>
</contact>
- <coil localId="4" width="21" height="15" negated="true">
- <position y="32" x="208"/>
+ <coil localId="4" height="15" width="21" negated="true">
+ <position x="208" y="32"/>
<connectionPointIn>
- <relPosition y="8" x="0"/>
+ <relPosition x="0" y="8"/>
<connection refLocalId="2">
- <position y="40" x="208"/>
- <position y="40" x="93"/>
+ <position x="208" y="40"/>
+ <position x="93" y="40"/>
</connection>
<connection refLocalId="3">
- <position y="40" x="208"/>
- <position y="40" x="131"/>
- <position y="84" x="131"/>
- <position y="84" x="93"/>
+ <position x="208" y="40"/>
+ <position x="131" y="40"/>
+ <position x="131" y="84"/>
+ <position x="93" y="84"/>
</connection>
</connectionPointIn>
<connectionPointOut>
- <relPosition y="8" x="21"/>
+ <relPosition x="21" y="8"/>
</connectionPointOut>
<variable>TR3</variable>
</coil>
<rightPowerRail localId="5" height="40" width="2">
- <position y="19" x="271"/>
+ <position x="271" y="19"/>
<connectionPointIn>
- <relPosition y="21" x="0"/>
+ <relPosition x="0" y="21"/>
<connection refLocalId="4">
- <position y="40" x="271"/>
- <position y="40" x="229"/>
+ <position x="271" y="40"/>
+ <position x="229" y="40"/>
</connection>
</connectionPointIn>
</rightPowerRail>
@@ -701,188 +707,190 @@
</transitions>
<body>
<SFC>
- <step localId="1" height="31" width="46" initialStep="true" name="Start">
- <position y="46" x="82"/>
+ <step localId="1" height="31" width="46" name="Start" initialStep="true">
+ <position x="82" y="46"/>
<connectionPointOut formalParameter="None">
- <relPosition y="31" x="23"/>
+ <relPosition x="23" y="31"/>
</connectionPointOut>
</step>
<transition localId="2" height="2" width="20">
- <position y="102" x="95"/>
- <connectionPointIn>
- <relPosition y="0" x="10"/>
+ <position x="95" y="102"/>
+ <connectionPointIn>
+ <relPosition x="10" y="0"/>
<connection refLocalId="1">
- <position y="102" x="105"/>
- <position y="77" x="105"/>
- </connection>
- </connectionPointIn>
- <connectionPointOut>
- <relPosition y="2" x="10"/>
+ <position x="105" y="102"/>
+ <position x="105" y="77"/>
+ </connection>
+ </connectionPointIn>
+ <connectionPointOut>
+ <relPosition x="10" y="2"/>
</connectionPointOut>
<condition>
<reference name="TR1"/>
</condition>
</transition>
<step localId="3" height="27" width="29" name="Init">
- <position y="129" x="91"/>
- <connectionPointIn>
- <relPosition y="0" x="14"/>
+ <position x="91" y="129"/>
+ <connectionPointIn>
+ <relPosition x="14" y="0"/>
<connection refLocalId="2">
- <position y="129" x="105"/>
- <position y="104" x="105"/>
+ <position x="105" y="129"/>
+ <position x="105" y="104"/>
</connection>
</connectionPointIn>
<connectionPointOut formalParameter="None">
- <relPosition y="27" x="14"/>
+ <relPosition x="14" y="27"/>
</connectionPointOut>
<connectionPointOutAction formalParameter="None">
- <relPosition y="13" x="29"/>
+ <relPosition x="29" y="13"/>
</connectionPointOutAction>
</step>
<selectionDivergence localId="4" height="1" width="391">
- <position y="181" x="105"/>
- <connectionPointIn>
- <relPosition y="0" x="0"/>
+ <position x="105" y="181"/>
+ <connectionPointIn>
+ <relPosition x="0" y="0"/>
<connection refLocalId="3">
- <position y="181" x="105"/>
- <position y="156" x="105"/>
+ <position x="105" y="181"/>
+ <position x="105" y="156"/>
</connection>
</connectionPointIn>
<connectionPointOut formalParameter="None">
- <relPosition y="1" x="0"/>
+ <relPosition x="0" y="1"/>
</connectionPointOut>
<connectionPointOut formalParameter="None">
- <relPosition y="1" x="228"/>
+ <relPosition x="228" y="1"/>
</connectionPointOut>
<connectionPointOut formalParameter="None">
- <relPosition y="1" x="391"/>
+ <relPosition x="391" y="1"/>
</connectionPointOut>
</selectionDivergence>
<transition localId="5" height="2" width="20">
- <position y="207" x="95"/>
- <connectionPointIn>
- <relPosition y="0" x="10"/>
+ <position x="95" y="207"/>
+ <connectionPointIn>
+ <relPosition x="10" y="0"/>
<connection refLocalId="4">
- <position y="207" x="105"/>
- <position y="182" x="105"/>
- </connection>
- </connectionPointIn>
- <connectionPointOut>
- <relPosition y="2" x="10"/>
+ <position x="105" y="207"/>
+ <position x="105" y="182"/>
+ </connection>
+ </connectionPointIn>
+ <connectionPointOut>
+ <relPosition x="10" y="2"/>
</connectionPointOut>
<condition>
<inline name="None">
- <ST><![CDATA[IN2 AND IN3]]></ST>
+ <ST>
+<![CDATA[IN2 AND IN3]]>
+ </ST>
</inline>
</condition>
</transition>
<step localId="6" height="27" width="48" name="Step1">
- <position y="262" x="81"/>
- <connectionPointIn>
- <relPosition y="0" x="24"/>
+ <position x="81" y="262"/>
+ <connectionPointIn>
+ <relPosition x="24" y="0"/>
<connection refLocalId="21">
- <position y="262" x="105"/>
- <position y="237" x="105"/>
+ <position x="105" y="262"/>
+ <position x="105" y="237"/>
</connection>
</connectionPointIn>
<connectionPointOut formalParameter="None">
- <relPosition y="27" x="24"/>
+ <relPosition x="24" y="27"/>
</connectionPointOut>
</step>
- <transition localId="7" height="2" priority="1" width="20">
- <position y="207" x="323"/>
- <connectionPointIn>
- <relPosition y="0" x="10"/>
+ <transition localId="7" height="2" width="20" priority="1">
+ <position x="323" y="207"/>
+ <connectionPointIn>
+ <relPosition x="10" y="0"/>
<connection refLocalId="4">
- <position y="207" x="333"/>
- <position y="182" x="333"/>
- </connection>
- </connectionPointIn>
- <connectionPointOut>
- <relPosition y="2" x="10"/>
+ <position x="333" y="207"/>
+ <position x="333" y="182"/>
+ </connection>
+ </connectionPointIn>
+ <connectionPointOut>
+ <relPosition x="10" y="2"/>
</connectionPointOut>
<condition>
<reference name="TR2"/>
</condition>
</transition>
<step localId="8" height="27" width="48" name="Step2">
- <position y="234" x="309"/>
- <connectionPointIn>
- <relPosition y="0" x="24"/>
+ <position x="309" y="234"/>
+ <connectionPointIn>
+ <relPosition x="24" y="0"/>
<connection refLocalId="7">
- <position y="234" x="333"/>
- <position y="209" x="333"/>
+ <position x="333" y="234"/>
+ <position x="333" y="209"/>
</connection>
</connectionPointIn>
<connectionPointOut formalParameter="None">
- <relPosition y="27" x="24"/>
+ <relPosition x="24" y="27"/>
</connectionPointOut>
</step>
<transition localId="9" height="2" width="20">
- <position y="207" x="486"/>
- <connectionPointIn>
- <relPosition y="0" x="10"/>
+ <position x="486" y="207"/>
+ <connectionPointIn>
+ <relPosition x="10" y="0"/>
<connection refLocalId="4">
- <position y="207" x="496"/>
- <position y="182" x="496"/>
- </connection>
- </connectionPointIn>
- <connectionPointOut>
- <relPosition y="2" x="10"/>
+ <position x="496" y="207"/>
+ <position x="496" y="182"/>
+ </connection>
+ </connectionPointIn>
+ <connectionPointOut>
+ <relPosition x="10" y="2"/>
</connectionPointOut>
<condition>
<reference name="TR4"/>
</condition>
</transition>
<step localId="10" height="27" width="48" name="Step3">
- <position y="234" x="472"/>
- <connectionPointIn>
- <relPosition y="0" x="24"/>
+ <position x="472" y="234"/>
+ <connectionPointIn>
+ <relPosition x="24" y="0"/>
<connection refLocalId="9">
- <position y="234" x="496"/>
- <position y="209" x="496"/>
+ <position x="496" y="234"/>
+ <position x="496" y="209"/>
</connection>
</connectionPointIn>
<connectionPointOut formalParameter="None">
- <relPosition y="27" x="24"/>
+ <relPosition x="24" y="27"/>
</connectionPointOut>
<connectionPointOutAction formalParameter="None">
- <relPosition y="13" x="48"/>
+ <relPosition x="48" y="13"/>
</connectionPointOutAction>
</step>
<transition localId="11" height="2" width="20">
- <position y="342" x="95"/>
- <connectionPointIn>
- <relPosition y="0" x="10"/>
+ <position x="95" y="342"/>
+ <connectionPointIn>
+ <relPosition x="10" y="0"/>
<connection refLocalId="23">
- <position y="342" x="105"/>
- <position y="317" x="105"/>
- </connection>
- </connectionPointIn>
- <connectionPointOut>
- <relPosition y="2" x="10"/>
+ <position x="105" y="342"/>
+ <position x="105" y="317"/>
+ </connection>
+ </connectionPointIn>
+ <connectionPointOut>
+ <relPosition x="10" y="2"/>
</connectionPointOut>
<condition>
<reference name="TR3"/>
</condition>
</transition>
<jumpStep localId="12" height="13" width="12" targetName="Start">
- <position y="369" x="99"/>
- <connectionPointIn>
- <relPosition y="0" x="6"/>
+ <position x="99" y="369"/>
+ <connectionPointIn>
+ <relPosition x="6" y="0"/>
<connection refLocalId="11">
- <position y="369" x="105"/>
- <position y="344" x="105"/>
+ <position x="105" y="369"/>
+ <position x="105" y="344"/>
</connection>
</connectionPointIn>
</jumpStep>
<actionBlock localId="13" height="30" width="100">
- <position y="127" x="145"/>
- <connectionPointIn>
- <relPosition y="15" x="0"/>
+ <position x="145" y="127"/>
+ <connectionPointIn>
+ <relPosition x="0" y="15"/>
<connection refLocalId="3">
- <position y="142" x="145"/>
- <position y="142" x="120"/>
+ <position x="145" y="142"/>
+ <position x="120" y="142"/>
</connection>
</connectionPointIn>
<action>
@@ -890,78 +898,82 @@
</action>
</actionBlock>
<transition localId="14" height="2" width="20">
- <position y="286" x="323"/>
- <connectionPointIn>
- <relPosition y="0" x="10"/>
+ <position x="323" y="286"/>
+ <connectionPointIn>
+ <relPosition x="10" y="0"/>
<connection refLocalId="8">
- <position y="286" x="333"/>
- <position y="261" x="333"/>
- </connection>
- </connectionPointIn>
- <connectionPointOut>
- <relPosition y="2" x="10"/>
+ <position x="333" y="286"/>
+ <position x="333" y="261"/>
+ </connection>
+ </connectionPointIn>
+ <connectionPointOut>
+ <relPosition x="10" y="2"/>
</connectionPointOut>
<condition>
<inline name="None">
- <ST><![CDATA[IN5]]></ST>
+ <ST>
+<![CDATA[IN5]]>
+ </ST>
</inline>
</condition>
</transition>
<transition localId="15" height="2" width="20">
- <position y="346" x="486"/>
- <connectionPointIn>
- <relPosition y="0" x="10"/>
+ <position x="486" y="346"/>
+ <connectionPointIn>
+ <relPosition x="10" y="0"/>
<connection refLocalId="10">
- <position y="346" x="496"/>
- <position y="261" x="496"/>
- </connection>
- </connectionPointIn>
- <connectionPointOut>
- <relPosition y="2" x="10"/>
+ <position x="496" y="346"/>
+ <position x="496" y="261"/>
+ </connection>
+ </connectionPointIn>
+ <connectionPointOut>
+ <relPosition x="10" y="2"/>
</connectionPointOut>
<condition>
<inline name="None">
- <ST><![CDATA[IN5]]></ST>
+ <ST>
+<![CDATA[IN5]]>
+ </ST>
</inline>
</condition>
</transition>
<selectionConvergence localId="16" height="1" width="163">
- <position y="373" x="333"/>
- <connectionPointIn>
- <relPosition y="0" x="0"/>
+ <position x="333" y="373"/>
+ <connectionPointIn>
+ <relPosition x="0" y="0"/>
<connection refLocalId="14">
- <position y="373" x="333"/>
- <position y="288" x="333"/>
- </connection>
- </connectionPointIn>
- <connectionPointIn>
- <relPosition y="0" x="163"/>
+ <position x="333" y="373"/>
+ <position x="333" y="288"/>
+ </connection>
+ </connectionPointIn>
+ <connectionPointIn>
+ <relPosition x="163" y="0"/>
<connection refLocalId="15">
- <position y="373" x="496"/>
- <position y="348" x="496"/>
- </connection>
- </connectionPointIn>
- <connectionPointOut>
- <relPosition y="1" x="80"/>
+ <position x="496" y="373"/>
+ <position x="496" y="348"/>
+ </connection>
+ </connectionPointIn>
+ <connectionPointOut>
+ <relPosition x="80" y="1"/>
</connectionPointOut>
</selectionConvergence>
<jumpStep localId="19" height="13" width="12" targetName="Init">
- <position y="399" x="407"/>
- <connectionPointIn>
- <relPosition y="0" x="6"/>
+ <position x="407" y="399"/>
+ <connectionPointIn>
+ <relPosition x="6" y="0"/>
<connection refLocalId="16">
- <position y="399" x="413"/>
- <position y="374" x="413"/>
+ <position x="413" y="399"/>
+ <position x="413" y="374"/>
</connection>
</connectionPointIn>
</jumpStep>
<actionBlock localId="20" height="90" width="173">
- <position y="232" x="545"/>
- <connectionPointIn>
- <relPosition y="15" x="0"/>
+ <position x="545" y="232"/>
+ <connectionPointIn>
+ <relPosition x="0" y="15"/>
<connection refLocalId="10">
- <position y="247" x="545"/>
- <position y="247" x="520"/>
+ <position x="545" y="247"/>
+ <position x="520" y="247"/>
</connection>
</connectionPointIn>
<action indicator="IN5">
@@ -972,57 +984,59 @@
</action>
<action qualifier="P">
<inline>
- <ST><![CDATA[IN2 := TRUE;]]></ST>
+ <ST>
+<![CDATA[IN2 := TRUE;]]>
+ </ST>
</inline>
</action>
</actionBlock>
<simultaneousDivergence localId="21" height="3" width="118">
- <position y="234" x="105"/>
- <connectionPointIn>
- <relPosition y="0" x="0"/>
+ <position x="105" y="234"/>
+ <connectionPointIn>
+ <relPosition x="0" y="0"/>
<connection refLocalId="5">
- <position y="234" x="105"/>
- <position y="209" x="105"/>
+ <position x="105" y="234"/>
+ <position x="105" y="209"/>
</connection>
</connectionPointIn>
<connectionPointOut formalParameter="None">
- <relPosition y="3" x="0"/>
+ <relPosition x="0" y="3"/>
</connectionPointOut>
<connectionPointOut formalParameter="None">
- <relPosition y="3" x="118"/>
+ <relPosition x="118" y="3"/>
</connectionPointOut>
</simultaneousDivergence>
<step localId="22" height="27" width="48" name="Step4">
- <position y="262" x="199"/>
- <connectionPointIn>
- <relPosition y="0" x="24"/>
+ <position x="199" y="262"/>
+ <connectionPointIn>
+ <relPosition x="24" y="0"/>
<connection refLocalId="21">
- <position y="262" x="223"/>
- <position y="237" x="223"/>
+ <position x="223" y="262"/>
+ <position x="223" y="237"/>
</connection>
</connectionPointIn>
<connectionPointOut formalParameter="None">
- <relPosition y="27" x="24"/>
+ <relPosition x="24" y="27"/>
</connectionPointOut>
</step>
<simultaneousConvergence localId="23" height="3" width="118">
- <position y="314" x="105"/>
- <connectionPointIn>
- <relPosition y="0" x="0"/>
+ <position x="105" y="314"/>
+ <connectionPointIn>
+ <relPosition x="0" y="0"/>
<connection refLocalId="6">
- <position y="314" x="105"/>
- <position y="289" x="105"/>
- </connection>
- </connectionPointIn>
- <connectionPointIn>
- <relPosition y="0" x="118"/>
+ <position x="105" y="314"/>
+ <position x="105" y="289"/>
+ </connection>
+ </connectionPointIn>
+ <connectionPointIn>
+ <relPosition x="118" y="0"/>
<connection refLocalId="22">
- <position y="314" x="223"/>
- <position y="289" x="223"/>
- </connection>
- </connectionPointIn>
- <connectionPointOut>
- <relPosition y="3" x="0"/>
+ <position x="223" y="314"/>
+ <position x="223" y="289"/>
+ </connection>
+ </connectionPointIn>
+ <connectionPointOut>
+ <relPosition x="0" y="3"/>
</connectionPointOut>
</simultaneousConvergence>
</SFC>
@@ -1101,8 +1115,8 @@
<configurations>
<configuration name="ConfigTest">
<resource name="ResourceTest">
- <task name="Toto" priority="6" single="Tutu">
- <pouInstance type="SFCTest" name="Program1"/>
+ <task name="Toto" single="Tutu" priority="6">
+ <pouInstance name="Program1" type="SFCTest"/>
</task>
<globalVars>
<variable name="Titi" address="%MW30">
--- a/plcopen/__init__.py Tue Jan 22 10:53:34 2008 +0100
+++ b/plcopen/__init__.py Tue Jan 22 10:57:41 2008 +0100
@@ -28,8 +28,6 @@
import plcopen
for classname, cls in plcopen.PLCOpenClasses.items():
plcopen.__dict__[classname] = cls
-for typename, typ in plcopen.PLCOpenTypes.items():
- plcopen.__dict__[typename] = typ
from plcopen import VarOrder
from structures import *
--- a/plcopen/plcopen.py Tue Jan 22 10:53:34 2008 +0100
+++ b/plcopen/plcopen.py Tue Jan 22 10:57:41 2008 +0100
@@ -44,37 +44,10 @@
QualifierList = {"N" : False, "R" : False, "S" : False, "L" : True, "D" : True,
"P" : False, "P0" : False, "P1" : False, "SD" : True, "DS" : True, "SL" : True}
-PLCOpenClasses, PLCOpenTypes = GenerateClassesFromXSD(os.path.join(os.path.split(__file__)[0], "TC6_XML_V10_B.xsd"))
+PLCOpenClasses = GenerateClassesFromXSD(os.path.join(os.path.split(__file__)[0], "TC6_XML_V10_B.xsd"))
cls = PLCOpenClasses.get("formattedText", None)
if cls:
- cls.text = ""
-
- def getText(self):
- return self.text
- setattr(cls, "getText", getText)
-
- def setText(self, text):
- self.text = text
- setattr(cls, "setText", setText)
-
- def loadXMLTree(self, tree):
- self.text = GetAttributeValue(tree)
- if len(self.text.splitlines()) > 1:
- self.text = self.text[1:].rstrip()
- setattr(cls, "loadXMLTree", loadXMLTree)
-
- def generateXMLText(self, name, indent, extras = {}):
- ind1, ind2 = getIndent(indent, name)
- if len(self.text.splitlines()) > 1:
- text = ind1 + "<%s>\n<![CDATA[\n"%name
- text += "%s\n"%self.text
- text += "]]>\n" + ind1 + "</%s>\n"%name
- return text
- else:
- return ind1 + "<%s><![CDATA[%s]]></%s>\n"%(name, self.text, name)
- setattr(cls, "generateXMLText", generateXMLText)
-
def updateElementName(self, old_name, new_name):
index = self.text.find(old_name)
while index != -1:
@@ -91,187 +64,187 @@
if cls:
cls.singleLineAttributes = False
- def setName(self, name):
- self.contentHeader.setName(name)
- setattr(cls, "setName", setName)
+ def setname(self, name):
+ self.contentHeader.setname(name)
+ setattr(cls, "setname", setname)
- def getName(self):
- return self.contentHeader.getName()
- setattr(cls, "getName", getName)
-
- def getFileHeader(self):
+ def getname(self):
+ return self.contentHeader.getname()
+ setattr(cls, "getname", getname)
+
+ def getfileHeader(self):
fileheader = {}
- fileheader["companyName"] = self.fileHeader.getCompanyName()
- if self.fileHeader.getCompanyURL():
- fileheader["companyURL"] = self.fileHeader.getCompanyURL()
- fileheader["productName"] = self.fileHeader.getProductName()
- fileheader["productVersion"] = self.fileHeader.getProductVersion()
- if self.fileHeader.getProductRelease():
- fileheader["productRelease"] = self.fileHeader.getProductRelease()
- fileheader["creationDateTime"] = self.fileHeader.getCreationDateTime()
- if self.fileHeader.getContentDescription():
- fileheader["contentDescription"] = self.fileHeader.getContentDescription()
+ fileheader["companyName"] = self.fileHeader.getcompanyName()
+ if self.fileHeader.getcompanyURL():
+ fileheader["companyURL"] = self.fileHeader.getcompanyURL()
+ fileheader["productName"] = self.fileHeader.getproductName()
+ fileheader["productVersion"] = self.fileHeader.getproductVersion()
+ if self.fileHeader.getproductRelease():
+ fileheader["productRelease"] = self.fileHeader.getproductRelease()
+ fileheader["creationDateTime"] = self.fileHeader.getcreationDateTime()
+ if self.fileHeader.getcontentDescription():
+ fileheader["contentDescription"] = self.fileHeader.getcontentDescription()
return fileheader
- setattr(cls, "getFileHeader", getFileHeader)
-
- def setFileHeader(self, fileheader):
- self.fileHeader.setCompanyName(fileheader["companyName"])
+ setattr(cls, "getfileHeader", getfileHeader)
+
+ def setfileHeader(self, fileheader):
+ self.fileHeader.setcompanyName(fileheader["companyName"])
if "companyURL" in fileheader:
- self.fileHeader.setCompanyURL(fileheader["companyURL"])
- self.fileHeader.setProductName(fileheader["productName"])
- self.fileHeader.setProductVersion(fileheader["productVersion"])
+ self.fileHeader.setcompanyURL(fileheader["companyURL"])
+ self.fileHeader.setproductName(fileheader["productName"])
+ self.fileHeader.setproductVersion(fileheader["productVersion"])
if "productRelease" in fileheader:
- self.fileHeader.setProductRelease(fileheader["productRelease"])
- self.fileHeader.setCreationDateTime(fileheader["creationDateTime"])
+ self.fileHeader.setproductRelease(fileheader["productRelease"])
+ self.fileHeader.setcreationDateTime(fileheader["creationDateTime"])
if "contentDescription" in fileheader:
- self.fileHeader.setContentDescription(fileheader["contentDescription"])
- setattr(cls, "setFileHeader", setFileHeader)
-
- def getContentHeader(self):
+ self.fileHeader.setcontentDescription(fileheader["contentDescription"])
+ setattr(cls, "setfileHeader", setfileHeader)
+
+ def getcontentHeader(self):
contentheader = {}
- contentheader["projectName"] = self.contentHeader.getName()
- if self.contentHeader.getVersion():
- contentheader["projectVersion"] = self.contentHeader.getVersion()
- if self.contentHeader.getModificationDateTime():
- contentheader["modificationDateTime"] = self.contentHeader.getModificationDateTime()
- if self.contentHeader.getOrganization():
- contentheader["organization"] = self.contentHeader.getOrganization()
- if self.contentHeader.getAuthor():
- contentheader["authorName"] = self.contentHeader.getAuthor()
- if self.contentHeader.getLanguage():
- contentheader["language"] = self.contentHeader.getLanguage()
- contentheader["pageSize"] = self.contentHeader.getPageSize()
- contentheader["scaling"] = self.contentHeader.getScaling()
+ contentheader["projectName"] = self.contentHeader.getname()
+ if self.contentHeader.getversion():
+ contentheader["projectVersion"] = self.contentHeader.getversion()
+ if self.contentHeader.getmodificationDateTime():
+ contentheader["modificationDateTime"] = self.contentHeader.getmodificationDateTime()
+ if self.contentHeader.getorganization():
+ contentheader["organization"] = self.contentHeader.getorganization()
+ if self.contentHeader.getauthor():
+ contentheader["authorName"] = self.contentHeader.getauthor()
+ if self.contentHeader.getlanguage():
+ contentheader["language"] = self.contentHeader.getlanguage()
+ contentheader["pageSize"] = self.contentHeader.getpageSize()
+ contentheader["scaling"] = self.contentHeader.getscaling()
return contentheader
- setattr(cls, "getContentHeader", getContentHeader)
-
- def setContentHeader(self, contentheader):
- self.contentHeader.setName(contentheader["projectName"])
+ setattr(cls, "getcontentHeader", getcontentHeader)
+
+ def setcontentHeader(self, contentheader):
+ self.contentHeader.setname(contentheader["projectName"])
if "projectVersion" in contentheader:
- self.contentHeader.setVersion(contentheader["projectVersion"])
+ self.contentHeader.setversion(contentheader["projectVersion"])
if "modificationDateTime" in contentheader:
- self.contentHeader.setModificationDateTime(contentheader["modificationDateTime"])
+ self.contentHeader.setmodificationDateTime(contentheader["modificationDateTime"])
if "organization" in contentheader:
- self.contentHeader.setOrganization(contentheader["organization"])
+ self.contentHeader.setorganization(contentheader["organization"])
if "authorName" in contentheader:
- self.contentHeader.setAuthor(contentheader["authorName"])
+ self.contentHeader.setauthor(contentheader["authorName"])
if "language" in contentheader:
- self.contentHeader.setLanguage(contentheader["language"])
- self.contentHeader.setPageSize(*contentheader["pageSize"])
- self.contentHeader.setScaling(contentheader["scaling"])
- setattr(cls, "setContentHeader", setContentHeader)
-
- def getDataTypes(self):
- return self.types.getDataTypeElements()
- setattr(cls, "getDataTypes", getDataTypes)
-
- def getDataType(self, name):
- return self.types.getDataTypeElement(name)
- setattr(cls, "getDataType", getDataType)
-
- def appendDataType(self, name):
- self.types.appendDataTypeElement(name)
- setattr(cls, "appendDataType", appendDataType)
+ self.contentHeader.setlanguage(contentheader["language"])
+ self.contentHeader.setpageSize(*contentheader["pageSize"])
+ self.contentHeader.setscaling(contentheader["scaling"])
+ setattr(cls, "setcontentHeader", setcontentHeader)
+
+ def getdataTypes(self):
+ return self.types.getdataTypeElements()
+ setattr(cls, "getdataTypes", getdataTypes)
+
+ def getdataType(self, name):
+ return self.types.getdataTypeElement(name)
+ setattr(cls, "getdataType", getdataType)
+
+ def appenddataType(self, name):
+ self.types.appenddataTypeElement(name)
+ setattr(cls, "appenddataType", appenddataType)
- def insertDataType(self, index, datatype):
- self.types.insertDataTypeElement(index, datatype)
- setattr(cls, "insertDataType", insertDataType)
-
- def removeDataType(self, name):
- self.types.removeDataTypeElement(name)
- setattr(cls, "removeDataType", removeDataType)
-
- def getPous(self):
- return self.types.getPouElements()
- setattr(cls, "getPous", getPous)
-
- def getPou(self, name):
- return self.types.getPouElement(name)
- setattr(cls, "getPou", getPou)
-
- def appendPou(self, name, pou_type, body_type):
- self.types.appendPouElement(name, pou_type, body_type)
- setattr(cls, "appendPou", appendPou)
+ def insertdataType(self, index, datatype):
+ self.types.insertdataTypeElement(index, datatype)
+ setattr(cls, "insertdataType", insertdataType)
+
+ def removedataType(self, name):
+ self.types.removedataTypeElement(name)
+ setattr(cls, "removedataType", removedataType)
+
+ def getpous(self):
+ return self.types.getpouElements()
+ setattr(cls, "getpous", getpous)
+
+ def getpou(self, name):
+ return self.types.getpouElement(name)
+ setattr(cls, "getpou", getpou)
+
+ def appendpou(self, name, pou_type, body_type):
+ self.types.appendpouElement(name, pou_type, body_type)
+ setattr(cls, "appendpou", appendpou)
- def insertPou(self, index, pou):
- self.types.insertPouElement(index, pou)
- setattr(cls, "insertPou", insertPou)
-
- def removePou(self, name):
- self.types.removePouElement(name)
- setattr(cls, "removePou", removePou)
-
- def getConfigurations(self):
- configurations = self.instances.configurations.getConfiguration()
+ def insertpou(self, index, pou):
+ self.types.insertpouElement(index, pou)
+ setattr(cls, "insertpou", insertpou)
+
+ def removepou(self, name):
+ self.types.removepouElement(name)
+ setattr(cls, "removepou", removepou)
+
+ def getconfigurations(self):
+ configurations = self.instances.configurations.getconfiguration()
if configurations:
return configurations
return []
- setattr(cls, "getConfigurations", getConfigurations)
-
- def getConfiguration(self, name):
- for configuration in self.instances.configurations.getConfiguration():
- if configuration.getName() == name:
+ setattr(cls, "getconfigurations", getconfigurations)
+
+ def getconfiguration(self, name):
+ for configuration in self.instances.configurations.getconfiguration():
+ if configuration.getname() == name:
return configuration
return None
- setattr(cls, "getConfiguration", getConfiguration)
-
- def addConfiguration(self, name):
- for configuration in self.instances.configurations.getConfiguration():
- if configuration.getName() == name:
+ 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"]()
- new_configuration.setName(name)
- self.instances.configurations.appendConfiguration(new_configuration)
- setattr(cls, "addConfiguration", addConfiguration)
-
- def removeConfiguration(self, name):
+ new_configuration.setname(name)
+ self.instances.configurations.appendconfiguration(new_configuration)
+ setattr(cls, "addconfiguration", addconfiguration)
+
+ def removeconfiguration(self, name):
found = False
- for idx, configuration in enumerate(self.instances.configurations.getConfiguration()):
- if configuration.getName() == name:
- self.instances.configurations.removeConfiguration(idx)
+ for idx, configuration in enumerate(self.instances.configurations.getconfiguration()):
+ if configuration.getname() == name:
+ self.instances.configurations.removeconfiguration(idx)
found = True
break
if not found:
raise ValueError, "\"%s\" configuration doesn't exist !!!"%name
- setattr(cls, "removeConfiguration", removeConfiguration)
-
- def getConfigurationResource(self, config_name, name):
- configuration = self.getConfiguration(config_name)
+ setattr(cls, "removeconfiguration", removeconfiguration)
+
+ def getconfigurationResource(self, config_name, name):
+ configuration = self.getconfiguration(config_name)
if configuration:
- for resource in configuration.getResource():
- if resource.getName() == name:
+ for resource in configuration.getresource():
+ if resource.getname() == name:
return resource
return None
- setattr(cls, "getConfigurationResource", getConfigurationResource)
-
- def addConfigurationResource(self, config_name, name):
- configuration = self.getConfiguration(config_name)
+ setattr(cls, "getconfigurationResource", getconfigurationResource)
+
+ def addconfigurationResource(self, config_name, name):
+ configuration = self.getconfiguration(config_name)
if configuration:
- for resource in configuration.getResource():
- if resource.getName() == 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"]()
- new_resource.setName(name)
- configuration.appendResource(new_resource)
- setattr(cls, "addConfigurationResource", addConfigurationResource)
-
- def removeConfigurationResource(self, config_name, name):
- configuration = self.getConfiguration(config_name)
+ new_resource.setname(name)
+ configuration.appendresource(new_resource)
+ setattr(cls, "addconfigurationResource", addconfigurationResource)
+
+ def removeconfigurationResource(self, config_name, name):
+ configuration = self.getconfiguration(config_name)
if configuration:
found = False
- for idx, resource in enumerate(configuration.getResource()):
- if resource.getName() == name:
- configuration.removeResource(idx)
+ for idx, resource in enumerate(configuration.getresource()):
+ if resource.getname() == name:
+ configuration.removeresource(idx)
found = True
break
if not found:
raise ValueError, "\"%s\" resource doesn't exist in \"%s\" configuration !!!"%(name, config_name)
- setattr(cls, "removeConfigurationResource", removeConfigurationResource)
-
- def updateElementName(self, old_name, new_name):
- for pou in self.types.getPouElements():
+ setattr(cls, "removeconfigurationResource", removeconfigurationResource)
+
+ def updateElementName(self, old_name, new_name):
+ for pou in self.types.getpouElements():
pou.updateElementName(old_name, new_name)
- for configuration in self.instances.configurations.getConfiguration():
+ for configuration in self.instances.configurations.getconfiguration():
configuration.updateElementName(old_name, new_name)
setattr(cls, "updateElementName", updateElementName)
@@ -283,71 +256,71 @@
if cls:
cls.singleLineAttributes = False
- def setPageSize(self, width, height):
- self.coordinateInfo.setPageSize(width, height)
- setattr(cls, "setPageSize", setPageSize)
-
- def getPageSize(self):
- return self.coordinateInfo.getPageSize()
- setattr(cls, "getPageSize", getPageSize)
-
- def setScaling(self, scaling):
+ def setpageSize(self, width, height):
+ self.coordinateInfo.setpageSize(width, height)
+ setattr(cls, "setpageSize", setpageSize)
+
+ def getpageSize(self):
+ return self.coordinateInfo.getpageSize()
+ setattr(cls, "getpageSize", getpageSize)
+
+ def setscaling(self, scaling):
for language, (x, y) in scaling.items():
- self.coordinateInfo.setScaling(language, x, y)
- setattr(cls, "setScaling", setScaling)
-
- def getScaling(self):
+ self.coordinateInfo.setscaling(language, x, y)
+ setattr(cls, "setscaling", setscaling)
+
+ def getscaling(self):
scaling = {}
- scaling["FBD"] = self.coordinateInfo.getScaling("FBD")
- scaling["LD"] = self.coordinateInfo.getScaling("LD")
- scaling["SFC"] = self.coordinateInfo.getScaling("SFC")
+ scaling["FBD"] = self.coordinateInfo.getscaling("FBD")
+ scaling["LD"] = self.coordinateInfo.getscaling("LD")
+ scaling["SFC"] = self.coordinateInfo.getscaling("SFC")
return scaling
- setattr(cls, "getScaling", getScaling)
+ setattr(cls, "getscaling", getscaling)
cls = PLCOpenClasses.get("contentHeader_coordinateInfo", None)
if cls:
- def setPageSize(self, width, height):
+ def setpageSize(self, width, height):
if width == 0 and height == 0:
- self.deletePageSize()
+ self.deletepageSize()
else:
if self.pageSize is None:
- self.addPageSize()
- self.pageSize.setX(width)
- self.pageSize.setY(height)
- setattr(cls, "setPageSize", setPageSize)
-
- def getPageSize(self):
+ self.addpageSize()
+ self.pageSize.setx(width)
+ self.pageSize.sety(height)
+ setattr(cls, "setpageSize", setpageSize)
+
+ def getpageSize(self):
if self.pageSize is not None:
- return self.pageSize.getX(), self.pageSize.getY()
+ return self.pageSize.getx(), self.pageSize.gety()
return 0, 0
- setattr(cls, "getPageSize", getPageSize)
-
- def setScaling(self, language, x, y):
+ setattr(cls, "getpageSize", getpageSize)
+
+ def setscaling(self, language, x, y):
if language == "FBD":
- self.fbd.scaling.setX(x)
- self.fbd.scaling.setY(y)
+ self.fbd.scaling.setx(x)
+ self.fbd.scaling.sety(y)
elif language == "LD":
- self.ld.scaling.setX(x)
- self.ld.scaling.setY(y)
+ self.ld.scaling.setx(x)
+ self.ld.scaling.sety(y)
elif language == "SFC":
- self.sfc.scaling.setX(x)
- self.sfc.scaling.setY(y)
- setattr(cls, "setScaling", setScaling)
-
- def getScaling(self, language):
+ self.sfc.scaling.setx(x)
+ self.sfc.scaling.sety(y)
+ setattr(cls, "setscaling", setscaling)
+
+ def getscaling(self, language):
if language == "FBD":
- return self.fbd.scaling.getX(), self.fbd.scaling.getY()
+ return self.fbd.scaling.getx(), self.fbd.scaling.gety()
elif language == "LD":
- return self.ld.scaling.getX(), self.ld.scaling.getY()
+ return self.ld.scaling.getx(), self.ld.scaling.gety()
elif language == "SFC":
- return self.sfc.scaling.getX(), self.sfc.scaling.getY()
+ return self.sfc.scaling.getx(), self.sfc.scaling.gety()
return 0, 0
- setattr(cls, "getScaling", getScaling)
+ setattr(cls, "getscaling", getscaling)
cls = PLCOpenClasses.get("configurations_configuration", None)
if cls:
def updateElementName(self, old_name, new_name):
- for resource in self.getResource():
+ for resource in self.getresource():
resource.updateElementName(old_name, new_name)
setattr(cls, "updateElementName", updateElementName)
@@ -379,850 +352,798 @@
cls = PLCOpenClasses.get("project_types", None)
if cls:
- def getDataTypeElements(self):
- return self.dataTypes.getDataType()
- setattr(cls, "getDataTypeElements", getDataTypeElements)
-
- def getDataTypeElement(self, name):
- elements = self.dataTypes.getDataType()
+ def getdataTypeElements(self):
+ return self.dataTypes.getdataType()
+ setattr(cls, "getdataTypeElements", getdataTypeElements)
+
+ def getdataTypeElement(self, name):
+ elements = self.dataTypes.getdataType()
for element in elements:
- if element.getName() == name:
+ if element.getname() == name:
return element
return None
- setattr(cls, "getDataTypeElement", getDataTypeElement)
-
- def appendDataTypeElement(self, name):
- for element in self.dataTypes.getDataType():
- if element.getName() == name:
+ setattr(cls, "getdataTypeElement", getdataTypeElement)
+
+ def appenddataTypeElement(self, name):
+ for element in self.dataTypes.getdataType():
+ if element.getname() == name:
raise ValueError, "\"%s\" Data Type already exists !!!"%name
new_datatype = PLCOpenClasses["dataTypes_dataType"]()
- new_datatype.setName(name)
- new_datatype.baseType.setContent("BOOL", None)
- self.dataTypes.appendDataType(new_datatype)
- setattr(cls, "appendDataTypeElement", appendDataTypeElement)
+ new_datatype.setname(name)
+ new_datatype.baseType.setcontent({"name" : "BOOL", "value" : None})
+ self.dataTypes.appenddataType(new_datatype)
+ setattr(cls, "appenddataTypeElement", appenddataTypeElement)
- def insertDataTypeElement(self, index, datatype):
- self.dataTypes.insertDataType(index, datatype)
- setattr(cls, "insertDataTypeElement", insertDataTypeElement)
-
- def removeDataTypeElement(self, name):
+ def insertdataTypeElement(self, index, dataType):
+ self.dataTypes.insertdataType(index, dataType)
+ setattr(cls, "insertdataTypeElement", insertdataTypeElement)
+
+ def removedataTypeElement(self, name):
found = False
- for idx, element in enumerate(self.dataTypes.getDataType()):
- if element.getName() == name:
- self.dataTypes.removeDataType(idx)
+ for idx, element in enumerate(self.dataTypes.getdataType()):
+ if element.getname() == name:
+ self.dataTypes.removedataType(idx)
found = True
break
if not found:
raise ValueError, "\"%s\" Data Type doesn't exist !!!"%name
- setattr(cls, "removeDataTypeElement", removeDataTypeElement)
-
- def getPouElements(self):
- return self.pous.getPou()
- setattr(cls, "getPouElements", getPouElements)
-
- def getPouElement(self, name):
- elements = self.pous.getPou()
+ setattr(cls, "removedataTypeElement", removedataTypeElement)
+
+ def getpouElements(self):
+ return self.pous.getpou()
+ setattr(cls, "getpouElements", getpouElements)
+
+ def getpouElement(self, name):
+ elements = self.pous.getpou()
for element in elements:
- if element.getName() == name:
+ if element.getname() == name:
return element
return None
- setattr(cls, "getPouElement", getPouElement)
-
- def appendPouElement(self, name, pou_type, body_type):
- for element in self.pous.getPou():
- if element.getName() == name:
+ setattr(cls, "getpouElement", getpouElement)
+
+ def appendpouElement(self, name, pou_type, body_type):
+ for element in self.pous.getpou():
+ if element.getname() == name:
raise ValueError, "\"%s\" POU already exists !!!"%name
new_pou = PLCOpenClasses["pous_pou"]()
- new_pou.setName(name)
- new_pou.pouType.setValue(pou_type)
- new_pou.setBody(PLCOpenClasses["body"]())
- new_pou.setBodyType(body_type)
- self.pous.appendPou(new_pou)
- setattr(cls, "appendPouElement", appendPouElement)
+ new_pou.setname(name)
+ new_pou.setpouType(pou_type)
+ new_pou.setbody(PLCOpenClasses["body"]())
+ new_pou.setbodyType(body_type)
+ self.pous.appendpou(new_pou)
+ setattr(cls, "appendpouElement", appendpouElement)
- def insertPouElement(self, index, pou):
- self.pous.insertPou(index, pou)
- setattr(cls, "insertPouElement", insertPouElement)
-
- def removePouElement(self, name):
+ def insertpouElement(self, index, pou):
+ self.pous.insertpou(index, pou)
+ setattr(cls, "insertpouElement", insertpouElement)
+
+ def removepouElement(self, name):
found = False
- for idx, element in enumerate(self.pous.getPou()):
- if element.getName() == name:
- self.pous.removePou(idx)
+ for idx, element in enumerate(self.pous.getpou()):
+ if element.getname() == name:
+ self.pous.removepou(idx)
found = True
break
if not found:
raise ValueError, "\"%s\" POU doesn't exist !!!"%name
- setattr(cls, "removePouElement", removePouElement)
-
-def setBodyType(self, type):
+ setattr(cls, "removepouElement", removepouElement)
+
+def setbodyType(self, type):
if type == "IL":
- self.body.setContent("IL", PLCOpenClasses["formattedText"]())
+ self.body.setcontent({"name" : "IL", "value" : PLCOpenClasses["formattedText"]()})
elif type == "ST":
- self.body.setContent("ST", PLCOpenClasses["formattedText"]())
+ self.body.setcontent({"name" : "ST", "value" : PLCOpenClasses["formattedText"]()})
elif type == "LD":
- self.body.setContent("LD", PLCOpenClasses["body_LD"]())
+ self.body.setcontent({"name" : "LD", "value" : PLCOpenClasses["body_LD"]()})
elif type == "FBD":
- self.body.setContent("FBD", PLCOpenClasses["body_FBD"]())
+ self.body.setcontent({"name" : "FBD", "value" : PLCOpenClasses["body_FBD"]()})
elif type == "SFC":
- self.body.setContent("SFC", PLCOpenClasses["body_SFC"]())
+ self.body.setcontent({"name" : "SFC", "value" : PLCOpenClasses["body_SFC"]()})
else:
raise ValueError, "%s isn't a valid body type!"%type
-def getBodyType(self):
- return self.body.getContent()["name"]
-
-def resetExecutionOrder(self):
- self.body.resetExecutionOrder()
-
-def compileExecutionOrder(self):
- self.body.compileExecutionOrder()
-
-def setElementExecutionOrder(self, instance, new_executionOrder):
- self.body.setElementExecutionOrder(instance, new_executionOrder)
-
-def addInstance(self, name, instance):
- self.body.appendContentInstance(name, instance)
-
-def getInstances(self):
- return self.body.getContentInstances()
-
-def getInstance(self, id):
- return self.body.getContentInstance(id)
-
-def getRandomInstance(self, exclude):
- return self.body.getContentRandomInstance(exclude)
-
-def getInstanceByName(self, name):
- return self.body.getContentInstanceByName(name)
-
-def removeInstance(self, id):
- self.body.removeContentInstance(id)
-
-def setText(self, text):
- self.body.setText(text)
-
-def getText(self):
- return self.body.getText()
-setattr(cls, "getText", getText)
+def getbodyType(self):
+ return self.body.getcontent()["name"]
+
+def resetexecutionOrder(self):
+ self.body.resetexecutionOrder()
+
+def compileexecutionOrder(self):
+ self.body.compileexecutionOrder()
+
+def setelementExecutionOrder(self, instance, new_executionOrder):
+ self.body.setelementExecutionOrder(instance, new_executionOrder)
+
+def addinstance(self, name, instance):
+ self.body.appendcontentInstance(name, instance)
+
+def getinstances(self):
+ return self.body.getcontentInstances()
+
+def getinstance(self, id):
+ return self.body.getcontentInstance(id)
+
+def getrandomInstance(self, exclude):
+ return self.body.getcontentRandomInstance(exclude)
+
+def getinstanceByName(self, name):
+ return self.body.getcontentInstanceByName(name)
+
+def removeinstance(self, id):
+ self.body.removecontentInstance(id)
+
+def settext(self, text):
+ self.body.settext(text)
+
+def gettext(self):
+ return self.body.gettext()
+setattr(cls, "gettext", gettext)
cls = PLCOpenClasses.get("pous_pou", None)
if cls:
- setattr(cls, "setBodyType", setBodyType)
- setattr(cls, "getBodyType", getBodyType)
- setattr(cls, "resetExecutionOrder", resetExecutionOrder)
- setattr(cls, "compileExecutionOrder", compileExecutionOrder)
- setattr(cls, "setElementExecutionOrder", setElementExecutionOrder)
- setattr(cls, "addInstance", addInstance)
- setattr(cls, "getInstances", getInstances)
- setattr(cls, "getInstance", getInstance)
- setattr(cls, "getRandomInstance", getRandomInstance)
- setattr(cls, "getInstanceByName", getInstanceByName)
- setattr(cls, "removeInstance", removeInstance)
- setattr(cls, "setText", setText)
- setattr(cls, "getText", getText)
-
- def getVars(self):
+ setattr(cls, "setbodyType", setbodyType)
+ setattr(cls, "getbodyType", getbodyType)
+ setattr(cls, "resetexecutionOrder", resetexecutionOrder)
+ setattr(cls, "compileexecutionOrder", compileexecutionOrder)
+ setattr(cls, "setelementExecutionOrder", setelementExecutionOrder)
+ setattr(cls, "addinstance", addinstance)
+ setattr(cls, "getinstances", getinstances)
+ setattr(cls, "getinstance", getinstance)
+ setattr(cls, "getrandomInstance", getrandomInstance)
+ setattr(cls, "getinstanceByName", getinstanceByName)
+ setattr(cls, "removeinstance", removeinstance)
+ setattr(cls, "settext", settext)
+ setattr(cls, "gettext", gettext)
+
+ def getvars(self):
vars = []
reverse_types = {}
for name, value in VarTypes.items():
reverse_types[value] = name
- for varlist in self.interface.getContent():
+ for varlist in self.interface.getcontent():
vars.append((reverse_types[varlist["name"]], varlist["value"]))
return vars
- setattr(cls, "getVars", getVars)
-
- def setVars(self, vars):
- self.interface.setContent([])
+ setattr(cls, "getvars", getvars)
+
+ def setvars(self, vars):
+ self.interface.setcontent([])
for vartype, varlist in vars:
- self.interface.appendContent(VarTypes[vartype], varlist)
- setattr(cls, "setVars", setVars)
-
- def addPouVar(self, type, name):
- content = self.interface.getContent()
+ self.interface.appendcontent({"name" : VarTypes[vartype], "value" : varlist})
+ setattr(cls, "setvars", setvars)
+
+ def addpouVar(self, type, name):
+ content = self.interface.getcontent()
if len(content) == 0 or content[-1]["name"] != "localVars":
- content.append({"name" : "localVars", "value" : PLCOpenClasses["varList"]()})
+ content.append({"name" : "localVars", "value" : PLCOpenClasses["interface_localVars"]()})
else:
varlist = content[-1]["value"]
- variables = varlist.getVariable()
- if varlist.getConstant() or varlist.getRetain() or len(variables) > 0 and variables[0].getAddress():
- content.append({"name" : "localVars", "value" : PLCOpenClasses["varList"]()})
+ variables = varlist.getvariable()
+ if varlist.getconstant() or varlist.getretain() or len(variables) > 0 and variables[0].getaddress():
+ content.append({"name" : "localVars", "value" : PLCOpenClasses["interface_localVars"]()})
var = PLCOpenClasses["varListPlain_variable"]()
- var.setName(name)
+ var.setname(name)
var_type = PLCOpenClasses["dataType"]()
- derived_type = PLCOpenClasses["derived"]()
- derived_type.setName(type)
- var_type.setContent("derived", derived_type)
- var.setType(var_type)
- content[-1]["value"].appendVariable(var)
- setattr(cls, "addPouVar", addPouVar)
-
- def changePouVar(self, old_type, old_name, new_type, new_name):
- content = self.interface.getContent()
+ derived_type = PLCOpenClasses["derivedTypes_derived"]()
+ derived_type.setname(type)
+ var_type.setcontent({"name" : "derived", "value" : derived_type})
+ var.settype(var_type)
+ content[-1]["value"].appendvariable(var)
+ setattr(cls, "addpouVar", addpouVar)
+
+ def changepouVar(self, old_type, old_name, new_type, new_name):
+ content = self.interface.getcontent()
for varlist in content:
- variables = varlist["value"].getVariable()
+ variables = varlist["value"].getvariable()
for var in variables:
- if var.getName() == old_name:
- vartype_content = var.getType().getContent()
- if vartype_content["name"] == "derived" and vartype_content["value"].getName() == old_type:
- var.setName(new_name)
- vartype_content["value"].setName(new_type)
+ if var.getname() == old_name:
+ vartype_content = var.gettype().getcontent()
+ if vartype_content["name"] == "derived" and vartype_content["value"].getname() == old_type:
+ var.setname(new_name)
+ vartype_content["value"].setname(new_type)
return
- setattr(cls, "changePouVar", changePouVar)
-
- def removePouVar(self, type, name):
- content = self.interface.getContent()
+ setattr(cls, "changepouVar", changepouVar)
+
+ def removepouVar(self, type, name):
+ content = self.interface.getcontent()
for varlist in content:
- variables = varlist["value"].getVariable()
+ variables = varlist["value"].getvariable()
for var in variables:
- if var.getName() == name:
- vartype_content = var.getType().getContent()
- if vartype_content["name"] == "derived" and vartype_content["value"].getName() == type:
+ if var.getname() == name:
+ vartype_content = var.gettype().getcontent()
+ if vartype_content["name"] == "derived" and vartype_content["value"].getname() == type:
variables.remove(var)
break
- if len(varlist["value"].getVariable()) == 0:
+ if len(varlist["value"].getvariable()) == 0:
content.remove(varlist)
break
- setattr(cls, "removePouVar", removePouVar)
-
- def hasBlock(self, name):
- if self.getBodyType() in ["FBD", "LD", "SFC"]:
- for instance in self.getInstances():
- if isinstance(instance, PLCOpenClasses["block"]) and instance.getInstanceName() == name:
+ setattr(cls, "removepouVar", removepouVar)
+
+ def hasblock(self, name):
+ if self.getbodyType() in ["FBD", "LD", "SFC"]:
+ for instance in self.getinstances():
+ if isinstance(instance, PLCOpenClasses["fbdObjects_block"]) and instance.getinstanceName() == name:
return True
if self.transitions:
- for transition in self.transitions.getTransition():
- result = transition.hasBlock(name)
+ for transition in self.transitions.gettransition():
+ result = transition.hasblock(name)
if result:
return result
if self.actions:
- for action in self.actions.getAction():
- result = action.hasBlock(name)
+ for action in self.actions.getaction():
+ result = action.hasblock(name)
if result:
return result
return False
- setattr(cls, "hasBlock", hasBlock)
-
- def addTransition(self, name, type):
+ setattr(cls, "hasblock", hasblock)
+
+ def addtransition(self, name, type):
if not self.transitions:
- self.addTransitions()
- self.transitions.setTransition([])
+ self.addtransitions()
+ self.transitions.settransition([])
transition = PLCOpenClasses["transitions_transition"]()
- transition.setName(name)
- transition.setBodyType(type)
- self.transitions.appendTransition(transition)
- setattr(cls, "addTransition", addTransition)
-
- def getTransition(self, name):
+ transition.setname(name)
+ transition.setbodyType(type)
+ self.transitions.appendtransition(transition)
+ setattr(cls, "addtransition", addtransition)
+
+ def gettransition(self, name):
if self.transitions:
- for transition in self.transitions.getTransition():
- if transition.getName() == name:
+ for transition in self.transitions.gettransition():
+ if transition.getname() == name:
return transition
return None
- setattr(cls, "getTransition", getTransition)
+ setattr(cls, "gettransition", gettransition)
- def getTransitionList(self):
+ def gettransitionList(self):
if self.transitions:
- return self.transitions.getTransition()
+ return self.transitions.gettransition()
return []
- setattr(cls, "getTransitionList", getTransitionList)
-
- def removeTransition(self, name):
+ setattr(cls, "gettransitionList", gettransitionList)
+
+ def removetransition(self, name):
if self.transitions:
- transitions = self.transitions.getTransition()
+ transitions = self.transitions.gettransition()
i = 0
removed = False
while i < len(transitions) and not removed:
- if transitions[i].getName() == name:
+ if transitions[i].getname() == name:
transitions.pop(i)
removed = True
i += 1
if not removed:
raise ValueError, "Transition with name %s doesn't exists!"%name
- setattr(cls, "removeTransition", removeTransition)
-
- def addAction(self, name, type):
+ setattr(cls, "removetransition", removetransition)
+
+ def addaction(self, name, type):
if not self.actions:
- self.addActions()
- self.actions.setAction([])
+ self.addactions()
+ self.actions.setaction([])
action = PLCOpenClasses["actions_action"]()
- action.setName(name)
- action.setBodyType(type)
- self.actions.appendAction(action)
- setattr(cls, "addAction", addAction)
-
- def getAction(self, name):
+ action.setname(name)
+ action.setbodyType(type)
+ self.actions.appendaction(action)
+ setattr(cls, "addaction", addaction)
+
+ def getaction(self, name):
if self.actions:
- for action in self.actions.getAction():
- if action.getName() == name:
+ for action in self.actions.getaction():
+ if action.getname() == name:
return action
return None
- setattr(cls, "getAction", getAction)
-
- def getActionList(self):
+ setattr(cls, "getaction", getaction)
+
+ def getactionList(self):
if self.actions:
- return self.actions.getAction()
+ return self.actions.getaction()
return []
- setattr(cls, "getActionList", getActionList)
+ setattr(cls, "getactionList", getactionList)
- def removeAction(self, name):
+ def removeaction(self, name):
if self.actions:
- actions = self.actions.getAction()
+ actions = self.actions.getaction()
i = 0
removed = False
while i < len(actions) and not removed:
- if actions[i].getName() == name:
+ if actions[i].getname() == name:
actions.pop(i)
removed = True
i += 1
if not removed:
raise ValueError, "Action with name %s doesn't exists!"%name
- setattr(cls, "removeAction", removeAction)
+ setattr(cls, "removeaction", removeaction)
def updateElementName(self, old_name, new_name):
self.body.updateElementName(old_name, new_name)
- for action in self.getActionList():
+ for action in self.getactionList():
action.updateElementName(old_name, new_name)
- for transition in self.getTransitionList():
+ for transition in self.gettransitionList():
transition.updateElementName(old_name, new_name)
setattr(cls, "updateElementName", updateElementName)
cls = PLCOpenClasses.get("transitions_transition", None)
if cls:
- setattr(cls, "setBodyType", setBodyType)
- setattr(cls, "getBodyType", getBodyType)
- setattr(cls, "resetExecutionOrder", resetExecutionOrder)
- setattr(cls, "compileExecutionOrder", compileExecutionOrder)
- setattr(cls, "setElementExecutionOrder", setElementExecutionOrder)
- setattr(cls, "addInstance", addInstance)
- setattr(cls, "getInstances", getInstances)
- setattr(cls, "getInstance", getInstance)
- setattr(cls, "getRandomInstance", getRandomInstance)
- setattr(cls, "getInstanceByName", getInstanceByName)
- setattr(cls, "removeInstance", removeInstance)
- setattr(cls, "setText", setText)
- setattr(cls, "getText", getText)
+ setattr(cls, "setbodyType", setbodyType)
+ setattr(cls, "getbodyType", getbodyType)
+ setattr(cls, "resetexecutionOrder", resetexecutionOrder)
+ setattr(cls, "compileexecutionOrder", compileexecutionOrder)
+ setattr(cls, "setelementExecutionOrder", setelementExecutionOrder)
+ setattr(cls, "addinstance", addinstance)
+ setattr(cls, "getinstances", getinstances)
+ setattr(cls, "getinstance", getinstance)
+ setattr(cls, "getrandomInstance", getrandomInstance)
+ setattr(cls, "getinstanceByName", getinstanceByName)
+ setattr(cls, "removeinstance", removeinstance)
+ setattr(cls, "settext", settext)
+ setattr(cls, "gettext", gettext)
def updateElementName(self, old_name, new_name):
self.body.updateElementName(old_name, new_name)
setattr(cls, "updateElementName", updateElementName)
- def hasBlock(self, name):
- if self.getBodyType() in ["FBD", "LD", "SFC"]:
- for instance in self.getInstances():
- if isinstance(instance, PLCOpenClasses["block"]) and instance.getInstanceName() == name:
+ def hasblock(self, name):
+ if self.getbodyType() in ["FBD", "LD", "SFC"]:
+ for instance in self.getinstances():
+ if isinstance(instance, PLCOpenClasses["fbdObjects_block"]) and instance.getinstanceName() == name:
return True
return False
- setattr(cls, "hasBlock", hasBlock)
+ setattr(cls, "hasblock", hasblock)
cls = PLCOpenClasses.get("actions_action", None)
if cls:
- setattr(cls, "setBodyType", setBodyType)
- setattr(cls, "getBodyType", getBodyType)
- setattr(cls, "resetExecutionOrder", resetExecutionOrder)
- setattr(cls, "compileExecutionOrder", compileExecutionOrder)
- setattr(cls, "setElementExecutionOrder", setElementExecutionOrder)
- setattr(cls, "addInstance", addInstance)
- setattr(cls, "getInstances", getInstances)
- setattr(cls, "getInstance", getInstance)
- setattr(cls, "getRandomInstance", getRandomInstance)
- setattr(cls, "getInstanceByName", getInstanceByName)
- setattr(cls, "removeInstance", removeInstance)
- setattr(cls, "setText", setText)
- setattr(cls, "getText", getText)
+ setattr(cls, "setbodyType", setbodyType)
+ setattr(cls, "getbodyType", getbodyType)
+ setattr(cls, "resetexecutionOrder", resetexecutionOrder)
+ setattr(cls, "compileexecutionOrder", compileexecutionOrder)
+ setattr(cls, "setelementExecutionOrder", setelementExecutionOrder)
+ setattr(cls, "addinstance", addinstance)
+ setattr(cls, "getinstances", getinstances)
+ setattr(cls, "getinstance", getinstance)
+ setattr(cls, "getrandomInstance", getrandomInstance)
+ setattr(cls, "getinstanceByName", getinstanceByName)
+ setattr(cls, "removeinstance", removeinstance)
+ setattr(cls, "settext", settext)
+ setattr(cls, "gettext", gettext)
def updateElementName(self, old_name, new_name):
self.body.updateElementName(old_name, new_name)
setattr(cls, "updateElementName", updateElementName)
- def hasBlock(self, name):
- if self.getBodyType() in ["FBD", "LD", "SFC"]:
- for instance in self.getInstances():
- if isinstance(instance, PLCOpenClasses["block"]) and instance.getInstanceName() == name:
+ def hasblock(self, name):
+ if self.getbodyType() in ["FBD", "LD", "SFC"]:
+ for instance in self.getinstances():
+ if isinstance(instance, PLCOpenClasses["fbdObjects_block"]) and instance.getinstanceName() == name:
return True
return False
- setattr(cls, "hasBlock", hasBlock)
+ setattr(cls, "hasblock", hasblock)
cls = PLCOpenClasses.get("body", None)
if cls:
cls.currentExecutionOrderId = 0
- def resetCurrentExecutionOrderId(self):
+ def resetcurrentExecutionOrderId(self):
self.currentExecutionOrderId = 0
- setattr(cls, "resetCurrentExecutionOrderId", resetCurrentExecutionOrderId)
-
- def getNewExecutionOrderId(self):
+ setattr(cls, "resetcurrentExecutionOrderId", resetcurrentExecutionOrderId)
+
+ def getnewExecutionOrderId(self):
self.currentExecutionOrderId += 1
return self.currentExecutionOrderId
- setattr(cls, "getNewExecutionOrderId", getNewExecutionOrderId)
-
- def resetExecutionOrder(self):
+ 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("comment", None), PLCOpenClasses.get("connector", None), PLCOpenClasses.get("continuation", None))):
- element["value"].setExecutionOrderId(0)
+ 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)
else:
raise TypeError, "Can only generate execution order on FBD networks!"
- setattr(cls, "resetExecutionOrder", resetExecutionOrder)
-
- def compileExecutionOrder(self):
+ setattr(cls, "resetexecutionOrder", resetexecutionOrder)
+
+ def compileexecutionOrder(self):
if self.content["name"] == "FBD":
- self.resetExecutionOrder()
- self.resetCurrentExecutionOrderId()
- for element in self.content["value"].getContent():
- if isinstance(element["value"], PLCOpenClasses.get("outVariable", None)) and element["value"].getExecutionOrderId() == 0:
- connections = element["value"].connectionPointIn.getConnections()
+ 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()
if connections and len(connections) == 1:
- self.compileElementExecutionOrder(connections[0])
- element["value"].setExecutionOrderId(self.getNewExecutionOrderId())
+ self.compileelementExecutionOrder(connections[0])
+ element["value"].setexecutionOrderId(self.getnewExecutionOrderId())
else:
raise TypeError, "Can only generate execution order on FBD networks!"
- setattr(cls, "compileExecutionOrder", compileExecutionOrder)
-
- def compileElementExecutionOrder(self, link):
+ setattr(cls, "compileexecutionOrder", compileexecutionOrder)
+
+ def compileelementExecutionOrder(self, link):
if self.content["name"] == "FBD":
- localid = link.getRefLocalId()
- instance = self.getContentInstance(localid)
- if isinstance(instance, PLCOpenClasses.get("block", None)) and instance.getExecutionOrderId() == 0:
- for variable in instance.inputVariables.getVariable():
- connections = variable.connectionPointIn.getConnections()
+ localid = link.getrefLocalId()
+ instance = self.getcontentInstance(localid)
+ if isinstance(instance, PLCOpenClasses.get("fbdObjects_block", None)) 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("continuation", None)) and instance.getExecutionOrderId() == 0:
- name = instance.getName()
- for tmp_instance in self.getContentInstances():
- if isinstance(tmp_instance, PLCOpenClasses.get("connector", None)) and tmp_instance.getName() == name and tmp_instance.getExecutionOrderId() == 0:
- connections = tmp_instance.connectionPointIn.getConnections()
+ self.compileelementExecutionOrder(connections[0])
+ instance.setexecutionOrderId(self.getnewExecutionOrderId())
+ elif isinstance(instance, PLCOpenClasses.get("commonObjects_continuation", None)) 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:
+ connections = tmp_instance.connectionPointIn.getconnections()
if connections and len(connections) == 1:
- self.compileElementExecutionOrder(connections[0])
+ self.compileelementExecutionOrder(connections[0])
else:
raise TypeError, "Can only generate execution order on FBD networks!"
- setattr(cls, "compileElementExecutionOrder", compileElementExecutionOrder)
-
- def setElementExecutionOrder(self, instance, new_executionOrder):
+ setattr(cls, "compileelementExecutionOrder", compileelementExecutionOrder)
+
+ def setelementExecutionOrder(self, instance, new_executionOrder):
if self.content["name"] == "FBD":
- old_executionOrder = instance.getExecutionOrderId()
+ 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("comment", None)):
- element_executionOrder = element["value"].getExecutionOrderId()
+ 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()
if old_executionOrder <= element_executionOrder <= new_executionOrder:
- element["value"].setExecutionOrderId(element_executionOrder - 1)
+ element["value"].setexecutionOrderId(element_executionOrder - 1)
if new_executionOrder <= element_executionOrder <= old_executionOrder:
- element["value"].setExecutionOrderId(element_executionOrder + 1)
- instance.setExecutionOrderId(new_executionOrder)
+ element["value"].setexecutionOrderId(element_executionOrder + 1)
+ instance.setexecutionOrderId(new_executionOrder)
else:
raise TypeError, "Can only generate execution order on FBD networks!"
- setattr(cls, "setElementExecutionOrder", setElementExecutionOrder)
-
- def appendContentInstance(self, name, instance):
+ setattr(cls, "setelementExecutionOrder", setelementExecutionOrder)
+
+ def appendcontentInstance(self, name, instance):
if self.content["name"] in ["LD","FBD","SFC"]:
- self.content["value"].appendContent(name, instance)
+ self.content["value"].appendcontent({"name" : name, "value" : instance})
else:
raise TypeError, "%s body don't have instances!"%self.content["name"]
- setattr(cls, "appendContentInstance", appendContentInstance)
-
- def getContentInstances(self):
+ setattr(cls, "appendcontentInstance", appendcontentInstance)
+
+ def getcontentInstances(self):
if self.content["name"] in ["LD","FBD","SFC"]:
instances = []
- for element in self.content["value"].getContent():
+ for element in self.content["value"].getcontent():
instances.append(element["value"])
return instances
else:
raise TypeError, "%s body don't have instances!"%self.content["name"]
- setattr(cls, "getContentInstances", getContentInstances)
-
- def getContentInstance(self, id):
+ setattr(cls, "getcontentInstances", getcontentInstances)
+
+ def getcontentInstance(self, id):
if self.content["name"] in ["LD","FBD","SFC"]:
- for element in self.content["value"].getContent():
- if element["value"].getLocalId() == id:
+ for element in self.content["value"].getcontent():
+ if element["value"].getlocalId() == id:
return element["value"]
return None
else:
raise TypeError, "%s body don't have instances!"%self.content["name"]
- setattr(cls, "getContentInstance", getContentInstance)
-
- def getContentRandomInstance(self, exclude):
+ setattr(cls, "getcontentInstance", getcontentInstance)
+
+ def getcontentRandomInstance(self, exclude):
if self.content["name"] in ["LD","FBD","SFC"]:
- for element in self.content["value"].getContent():
- if element["value"].getLocalId() not in exclude:
+ for element in self.content["value"].getcontent():
+ if element["value"].getlocalId() not in exclude:
return element["value"]
return None
else:
raise TypeError, "%s body don't have instances!"%self.content["name"]
- setattr(cls, "getContentRandomInstance", getContentRandomInstance)
-
- def getContentInstanceByName(self, name):
+ setattr(cls, "getcontentRandomInstance", getcontentRandomInstance)
+
+ def getcontentInstanceByName(self, name):
if self.content["name"] in ["LD","FBD","SFC"]:
- for element in self.content["value"].getContent():
+ for element in self.content["value"].getcontent():
if element["value"].getLocalId() == name:
return element["value"]
else:
raise TypeError, "%s body don't have instances!"%self.content["name"]
- setattr(cls, "getContentInstanceByName", getContentInstanceByName)
-
- def removeContentInstance(self, id):
+ setattr(cls, "getcontentInstanceByName", getcontentInstanceByName)
+
+ def removecontentInstance(self, id):
if self.content["name"] in ["LD","FBD","SFC"]:
i = 0
removed = False
- elements = self.content["value"].getContent()
+ elements = self.content["value"].getcontent()
while i < len(elements) and not removed:
- if elements[i]["value"].getLocalId() == id:
- self.content["value"].removeContent(i)
+ if elements[i]["value"].getlocalId() == id:
+ self.content["value"].removecontent(i)
removed = True
i += 1
if not removed:
raise ValueError, "Instance with id %d doesn't exists!"%id
else:
raise TypeError, "%s body don't have instances!"%self.content["name"]
- setattr(cls, "removeContentInstance", removeContentInstance)
-
- def setText(self, text):
+ setattr(cls, "removecontentInstance", removecontentInstance)
+
+ def settext(self, text):
if self.content["name"] in ["IL","ST"]:
- self.content["value"].setText(text)
+ self.content["value"].settext(text)
else:
raise TypeError, "%s body don't have text!"%self.content["name"]
- setattr(cls, "setText", setText)
-
- def getText(self):
+ setattr(cls, "settext", settext)
+
+ def gettext(self):
if self.content["name"] in ["IL","ST"]:
- return self.content["value"].getText()
+ return self.content["value"].gettext()
else:
raise TypeError, "%s body don't have text!"%self.content["name"]
- setattr(cls, "getText", getText)
+ setattr(cls, "gettext", gettext)
def updateElementName(self, old_name, new_name):
if self.content["name"] in ["IL", "ST"]:
self.content["value"].updateElementName(old_name, new_name)
else:
- for element in self.content["value"].getContent():
+ for element in self.content["value"].getcontent():
element["value"].updateElementName(old_name, new_name)
setattr(cls, "updateElementName", updateElementName)
-def getX(self):
- return self.position.getX()
-
-def getY(self):
- return self.position.getY()
-
-def setX(self, x):
- self.position.setX(x)
-
-def setY(self, y):
- self.position.setY(y)
-
-cls = PLCOpenClasses.get("comment", None)
-if cls:
- setattr(cls, "getX", getX)
- setattr(cls, "getY", getY)
- setattr(cls, "setX", setX)
- setattr(cls, "setY", setY)
-
- def setContentText(self, text):
- self.content.setText(text)
- setattr(cls, "setContentText", setContentText)
+def getx(self):
+ return self.position.getx()
+
+def gety(self):
+ return self.position.gety()
+
+def setx(self, x):
+ self.position.setx(x)
+
+def sety(self, y):
+ self.position.sety(y)
+
+cls = PLCOpenClasses.get("commonObjects_comment", None)
+if cls:
+ setattr(cls, "getx", getx)
+ setattr(cls, "gety", gety)
+ setattr(cls, "setx", setx)
+ setattr(cls, "sety", sety)
+
+ def setcontentText(self, text):
+ self.content.settext(text)
+ setattr(cls, "setcontentText", setcontentText)
- def getContentText(self):
- return self.content.getText()
- setattr(cls, "getContentText", getContentText)
+ def getcontentText(self):
+ return self.content.gettext()
+ setattr(cls, "getcontentText", getcontentText)
def updateElementName(self, old_name, new_name):
self.content.updateElementName(old_name, new_name)
setattr(cls, "updateElementName", updateElementName)
-cls = PLCOpenClasses.get("block", None)
-if cls:
- setattr(cls, "getX", getX)
- setattr(cls, "getY", getY)
- setattr(cls, "setX", setX)
- setattr(cls, "setY", setY)
+cls = PLCOpenClasses.get("fbdObjects_block", None)
+if cls:
+ setattr(cls, "getx", getx)
+ setattr(cls, "gety", gety)
+ setattr(cls, "setx", setx)
+ setattr(cls, "sety", sety)
def updateElementName(self, old_name, new_name):
if self.typeName == old_name:
self.typeName = new_name
setattr(cls, "updateElementName", updateElementName)
-cls = PLCOpenClasses.get("inputVariables_variable", None)
-if cls:
- def setConnectorEdge(self, edge):
- if not self.edge:
- self.edge = PLCOpenClasses["edgeModifierType"]()
- self.edge.setValue(edge)
- setattr(cls, "setConnectorEdge", setConnectorEdge)
-
- def getConnectorEdge(self):
- if self.edge:
- return self.edge.getValue()
- return None
- setattr(cls, "getConnectorEdge", getConnectorEdge)
-
-cls = PLCOpenClasses.get("outputVariables_variable", None)
-if cls:
- def setConnectorEdge(self, edge):
- if not self.edge:
- self.edge = PLCOpenClasses["edgeModifierType"]()
- self.edge.setValue(edge)
- setattr(cls, "setConnectorEdge", setConnectorEdge)
-
- def getConnectorEdge(self):
- if self.edge:
- return self.edge.getValue()
- return None
- setattr(cls, "getConnectorEdge", getConnectorEdge)
-
-cls = PLCOpenClasses.get("leftPowerRail", None)
-if cls:
- setattr(cls, "getX", getX)
- setattr(cls, "getY", getY)
- setattr(cls, "setX", setX)
- setattr(cls, "setY", setY)
+cls = PLCOpenClasses.get("ldObjects_leftPowerRail", None)
+if cls:
+ setattr(cls, "getx", getx)
+ setattr(cls, "gety", gety)
+ setattr(cls, "setx", setx)
+ setattr(cls, "sety", sety)
def updateElementName(self, old_name, new_name):
pass
setattr(cls, "updateElementName", updateElementName)
-cls = PLCOpenClasses.get("rightPowerRail", None)
-if cls:
- setattr(cls, "getX", getX)
- setattr(cls, "getY", getY)
- setattr(cls, "setX", setX)
- setattr(cls, "setY", setY)
+cls = PLCOpenClasses.get("ldObjects_rightPowerRail", None)
+if cls:
+ setattr(cls, "getx", getx)
+ setattr(cls, "gety", gety)
+ setattr(cls, "setx", setx)
+ setattr(cls, "sety", sety)
def updateElementName(self, old_name, new_name):
pass
setattr(cls, "updateElementName", updateElementName)
-cls = PLCOpenClasses.get("contact", None)
-if cls:
- setattr(cls, "getX", getX)
- setattr(cls, "getY", getY)
- setattr(cls, "setX", setX)
- setattr(cls, "setY", setY)
-
- def setContactEdge(self, edge):
- if not self.edge:
- self.edge = PLCOpenClasses["edgeModifierType"]()
- self.edge.setValue(edge)
- setattr(cls, "setContactEdge", setContactEdge)
-
- def getContactEdge(self):
- if self.edge:
- return self.edge.getValue()
- return None
- setattr(cls, "getContactEdge", getContactEdge)
+cls = PLCOpenClasses.get("ldObjects_contact", None)
+if cls:
+ setattr(cls, "getx", getx)
+ setattr(cls, "gety", gety)
+ setattr(cls, "setx", setx)
+ setattr(cls, "sety", sety)
def updateElementName(self, old_name, new_name):
if self.variable == old_name:
self.variable = new_name
setattr(cls, "updateElementName", updateElementName)
-cls = PLCOpenClasses.get("coil", None)
-if cls:
- setattr(cls, "getX", getX)
- setattr(cls, "getY", getY)
- setattr(cls, "setX", setX)
- setattr(cls, "setY", setY)
-
- def setCoilStorage(self, edge):
- if not self.storage:
- self.storage = PLCOpenClasses["storageModifierType"]()
- self.storage.setValue(edge)
- setattr(cls, "setCoilStorage", setCoilStorage)
-
- def getCoilStorage(self):
- if self.storage:
- return self.storage.getValue()
- return None
- setattr(cls, "getCoilStorage", getCoilStorage)
+cls = PLCOpenClasses.get("ldObjects_coil", None)
+if cls:
+ setattr(cls, "getx", getx)
+ setattr(cls, "gety", gety)
+ setattr(cls, "setx", setx)
+ setattr(cls, "sety", sety)
def updateElementName(self, old_name, new_name):
if self.variable == old_name:
self.variable = new_name
setattr(cls, "updateElementName", updateElementName)
-cls = PLCOpenClasses.get("step", None)
-if cls:
- setattr(cls, "getX", getX)
- setattr(cls, "getY", getY)
- setattr(cls, "setX", setX)
- setattr(cls, "setY", setY)
+cls = PLCOpenClasses.get("sfcObjects_step", None)
+if cls:
+ setattr(cls, "getx", getx)
+ setattr(cls, "gety", gety)
+ setattr(cls, "setx", setx)
+ setattr(cls, "sety", sety)
def updateElementName(self, old_name, new_name):
pass
setattr(cls, "updateElementName", updateElementName)
-cls = PLCOpenClasses.get("transition", None)
-if cls:
- setattr(cls, "getX", getX)
- setattr(cls, "getY", getY)
- setattr(cls, "setX", setX)
- setattr(cls, "setY", setY)
-
- def setConditionContent(self, type, value):
+cls = PLCOpenClasses.get("sfcObjects_transition", None)
+if cls:
+ setattr(cls, "getx", getx)
+ setattr(cls, "gety", gety)
+ setattr(cls, "setx", setx)
+ setattr(cls, "sety", sety)
+
+ def setconditionContent(self, type, value):
if not self.condition:
- self.addCondition()
+ self.addcondition()
if type == "reference":
condition = PLCOpenClasses["condition_reference"]()
- condition.setName(value)
+ condition.setname(value)
elif type == "inline":
condition = PLCOpenClasses["condition_inline"]()
- condition.setContent("ST", PLCOpenClasses["formattedText"]())
- condition.setText(value)
+ condition.setcontent({"name" : "ST", "value" : PLCOpenClasses["formattedText"]()})
+ condition.settext(value)
elif type == "connection":
condition = []
- self.condition.setContent(type, condition)
- setattr(cls, "setConditionContent", setConditionContent)
+ self.condition.setcontent({"name" : type, "value" : condition})
+ setattr(cls, "setconditionContent", setconditionContent)
- def getConditionContent(self):
+ def getconditionContent(self):
if self.condition:
- content = self.condition.getContent()
+ content = self.condition.getcontent()
values = {"type" : content["name"]}
if values["type"] == "reference":
- values["value"] = content["value"].getName()
+ values["value"] = content["value"].getname()
elif values["type"] == "inline":
- values["value"] = content["value"].getText()
+ values["value"] = content["value"].gettext()
return values
return ""
- setattr(cls, "getConditionContent", getConditionContent)
+ setattr(cls, "getconditionContent", getconditionContent)
def updateElementName(self, old_name, new_name):
if self.condition:
- content = self.condition.getContent()
+ content = self.condition.getcontent()
if content["name"] == "reference":
- if content["value"].getName() == old_name:
- content["value"].setName(new_name)
+ if content["value"].getname() == old_name:
+ content["value"].setname(new_name)
elif content["name"] == "inline":
content["value"].updateElementName(old_name, new_name)
setattr(cls, "updateElementName", updateElementName)
- def addConnection(self):
+ def addconnection(self):
if self.condition:
- content = self.condition.getContent()
+ content = self.condition.getcontent()
if content["name"] != "connection":
- self.condition.setContent("connection", [])
- content = self.condition.getContent()
+ self.condition.setcontent({"name" : "connection", "value" : []})
+ content = self.condition.getcontent()
content["value"].append(PLCOpenClasses["connection"]())
- setattr(cls, "addConnection", addConnection)
-
- def removeConnection(self, idx):
+ setattr(cls, "addconnection", addconnection)
+
+ def removeconnection(self, idx):
if self.condition:
- content = self.condition.getContent()
+ content = self.condition.getcontent()
if content["name"] == "connection":
content["value"].pop(idx)
- setattr(cls, "removeConnection", removeConnection)
-
- def removeConnections(self):
+ setattr(cls, "removeconnection", removeconnection)
+
+ def removeconnections(self):
if self.condition:
- content = self.condition.getContent()
+ content = self.condition.getcontent()
if content["name"] == "connection":
content["value"] = []
- setattr(cls, "removeConnections", removeConnections)
-
- def getConnections(self):
+ setattr(cls, "removeconnections", removeconnections)
+
+ def getconnections(self):
if self.condition:
- content = self.condition.getContent()
+ content = self.condition.getcontent()
if content["name"] == "connection":
return content["value"]
- setattr(cls, "getConnections", getConnections)
-
- def setConnectionId(self, idx, id):
+ setattr(cls, "getconnections", getconnections)
+
+ def setconnectionId(self, idx, id):
if self.condition:
- content = self.condition.getContent()
+ content = self.condition.getcontent()
if content["name"] == "connection":
- content["value"][idx].setRefLocalId(id)
- setattr(cls, "setConnectionId", setConnectionId)
-
- def getConnectionId(self, idx):
+ content["value"][idx].setrefLocalId(id)
+ setattr(cls, "setconnectionId", setconnectionId)
+
+ def getconnectionId(self, idx):
if self.condition:
- content = self.condition.getContent()
+ content = self.condition.getcontent()
if content["name"] == "connection":
- return content["value"][idx].getRefLocalId()
+ return content["value"][idx].getrefLocalId()
return None
- setattr(cls, "getConnectionId", getConnectionId)
-
- def setConnectionPoints(self, idx, points):
+ setattr(cls, "getconnectionId", getconnectionId)
+
+ def setconnectionPoints(self, idx, points):
if self.condition:
- content = self.condition.getContent()
+ content = self.condition.getcontent()
if content["name"] == "connection":
- content["value"][idx].setPoints(points)
- setattr(cls, "setConnectionPoints", setConnectionPoints)
-
- def getConnectionPoints(self, idx):
+ content["value"][idx].setpoints(points)
+ setattr(cls, "setconnectionPoints", setconnectionPoints)
+
+ def getconnectionPoints(self, idx):
if self.condition:
- content = self.condition.getContent()
+ content = self.condition.getcontent()
if content["name"] == "connection":
- return content["value"][idx].getPoints()
+ return content["value"][idx].getpoints()
return None
- setattr(cls, "getConnectionPoints", getConnectionPoints)
-
- def setConnectionParameter(self, idx, parameter):
+ setattr(cls, "getconnectionPoints", getconnectionPoints)
+
+ def setconnectionParameter(self, idx, parameter):
if self.condition:
- content = self.condition.getContent()
+ content = self.condition.getcontent()
if content["name"] == "connection":
- content["value"][idx].setFormalParameter(parameter)
- setattr(cls, "setConnectionParameter", setConnectionParameter)
-
- def getConnectionParameter(self, idx):
+ content["value"][idx].setformalParameter(parameter)
+ setattr(cls, "setconnectionParameter", setconnectionParameter)
+
+ def getconnectionParameter(self, idx):
if self.condition:
- content = self.condition.getContent()
+ content = self.condition.getcontent()
if content["name"] == "connection":
- return content["value"][idx].getFormalParameter()
+ return content["value"][idx].getformalParameter()
return None
- setattr(cls, "getConnectionParameter", getConnectionParameter)
-
- setattr(cls, "addConnection", addConnection)
-
-cls = PLCOpenClasses.get("selectionDivergence", None)
-if cls:
- setattr(cls, "getX", getX)
- setattr(cls, "getY", getY)
- setattr(cls, "setX", setX)
- setattr(cls, "setY", setY)
+ setattr(cls, "getconnectionParameter", getconnectionParameter)
+
+cls = PLCOpenClasses.get("sfcObjects_selectionDivergence", None)
+if cls:
+ setattr(cls, "getx", getx)
+ setattr(cls, "gety", gety)
+ setattr(cls, "setx", setx)
+ setattr(cls, "sety", sety)
def updateElementName(self, old_name, new_name):
pass
setattr(cls, "updateElementName", updateElementName)
-cls = PLCOpenClasses.get("selectionConvergence", None)
-if cls:
- setattr(cls, "getX", getX)
- setattr(cls, "getY", getY)
- setattr(cls, "setX", setX)
- setattr(cls, "setY", setY)
+cls = PLCOpenClasses.get("sfcObjects_selectionConvergence", None)
+if cls:
+ setattr(cls, "getx", getx)
+ setattr(cls, "gety", gety)
+ setattr(cls, "setx", setx)
+ setattr(cls, "sety", sety)
def updateElementName(self, old_name, new_name):
pass
setattr(cls, "updateElementName", updateElementName)
-cls = PLCOpenClasses.get("simultaneousDivergence", None)
-if cls:
- setattr(cls, "getX", getX)
- setattr(cls, "getY", getY)
- setattr(cls, "setX", setX)
- setattr(cls, "setY", setY)
+cls = PLCOpenClasses.get("sfcObjects_simultaneousDivergence", None)
+if cls:
+ setattr(cls, "getx", getx)
+ setattr(cls, "gety", gety)
+ setattr(cls, "setx", setx)
+ setattr(cls, "sety", sety)
def updateElementName(self, old_name, new_name):
pass
setattr(cls, "updateElementName", updateElementName)
-cls = PLCOpenClasses.get("simultaneousConvergence", None)
-if cls:
- setattr(cls, "getX", getX)
- setattr(cls, "getY", getY)
- setattr(cls, "setX", setX)
- setattr(cls, "setY", setY)
+cls = PLCOpenClasses.get("sfcObjects_simultaneousConvergence", None)
+if cls:
+ setattr(cls, "getx", getx)
+ setattr(cls, "gety", gety)
+ setattr(cls, "setx", setx)
+ setattr(cls, "sety", sety)
def updateElementName(self, old_name, new_name):
pass
setattr(cls, "updateElementName", updateElementName)
-cls = PLCOpenClasses.get("jumpStep", None)
-if cls:
- setattr(cls, "getX", getX)
- setattr(cls, "getY", getY)
- setattr(cls, "setX", setX)
- setattr(cls, "setY", setY)
+cls = PLCOpenClasses.get("sfcObjects_jumpStep", None)
+if cls:
+ setattr(cls, "getx", getx)
+ setattr(cls, "gety", gety)
+ setattr(cls, "setx", setx)
+ setattr(cls, "sety", sety)
def updateElementName(self, old_name, new_name):
pass
@@ -1230,202 +1151,142 @@
cls = PLCOpenClasses.get("actionBlock_action", None)
if cls:
- def setQualifierValue(self, value):
- if self.qualifier:
- self.qualifier.setValue(value)
- setattr(cls, "setQualifierValue", setQualifierValue)
-
- def getQualifierValue(self):
- if self.qualifier:
- return self.qualifier.getValue()
+ def setreferenceName(self, name):
+ if self.reference:
+ self.reference.setname(name)
+ setattr(cls, "setreferenceName", setreferenceName)
+
+ def getreferenceName(self):
+ if self.reference:
+ return self.reference.getname()
return None
- setattr(cls, "getQualifierValue", getQualifierValue)
-
- def setReferenceName(self, name):
- if self.reference:
- self.reference.setName(name)
- setattr(cls, "setReferenceName", setReferenceName)
-
- def getReferenceName(self):
- if self.reference:
- return self.reference.getName()
+ setattr(cls, "getreferenceName", getreferenceName)
+
+ def setinlineContent(self, content):
+ if self.inline:
+ self.inline.setcontent({"name" : "ST", "value" : PLCOpenClasses["formattedText"]()})
+ self.inline.settext(content)
+ setattr(cls, "setinlineContent", setinlineContent)
+
+ def getinlineContent(self):
+ if self.inline:
+ return self.inline.gettext()
return None
- setattr(cls, "getReferenceName", getReferenceName)
-
- def setInlineContent(self, content):
- if self.inline:
- self.inline.setContent("ST", PLCOpenClasses["formattedText"]())
- self.inline.setText(content)
- setattr(cls, "setInlineContent", setInlineContent)
-
- def getInlineContent(self):
- if self.inline:
- return self.inline.getText()
- return None
- setattr(cls, "getInlineContent", getInlineContent)
-
- def updateElementName(self, old_name, new_name):
- if self.reference and self.reference.getName() == old_name:
- self.reference.setName(new_name)
+ setattr(cls, "getinlineContent", getinlineContent)
+
+ def updateElementName(self, old_name, new_name):
+ if self.reference and self.reference.getname() == old_name:
+ self.reference.setname(new_name)
if self.inline:
self.inline.updateElementName(old_name, new_name)
setattr(cls, "updateElementName", updateElementName)
-cls = PLCOpenClasses.get("actionBlock", None)
-if cls:
- setattr(cls, "getX", getX)
- setattr(cls, "getY", getY)
- setattr(cls, "setX", setX)
- setattr(cls, "setY", setY)
-
- def setActions(self, actions):
+cls = PLCOpenClasses.get("commonObjects_actionBlock", None)
+if cls:
+ setattr(cls, "getx", getx)
+ setattr(cls, "gety", gety)
+ setattr(cls, "setx", setx)
+ setattr(cls, "sety", sety)
+
+ def setactions(self, actions):
self.action = []
for params in actions:
action = PLCOpenClasses["actionBlock_action"]()
- action.addQualifier()
- action.setQualifierValue(params["qualifier"])
+ action.setqualifier(params["qualifier"])
if params["type"] == "reference":
- action.addReference()
- action.setReferenceName(params["value"])
+ action.addreference()
+ action.setreferenceName(params["value"])
else:
- action.addInline()
- action.setInlineContent(params["value"])
+ action.addinline()
+ action.setinlineContent(params["value"])
if "duration" in params:
- action.setDuration(params["duration"])
+ action.setduration(params["duration"])
if "indicator" in params:
- action.setIndicator(params["indicator"])
+ action.setindicator(params["indicator"])
self.action.append(action)
- setattr(cls, "setActions", setActions)
-
- def getActions(self):
+ setattr(cls, "setactions", setactions)
+
+ def getactions(self):
actions = []
for action in self.action:
params = {}
- params["qualifier"] = action.getQualifierValue()
+ params["qualifier"] = action.getqualifier()
if params["qualifier"] is None:
params["qualifier"] = "N"
- if action.getReference():
+ if action.getreference():
params["type"] = "reference"
- params["value"] = action.getReferenceName()
- elif action.getInline():
+ params["value"] = action.getreferenceName()
+ elif action.getinline():
params["type"] = "inline"
- params["value"] = action.getInlineContent()
- duration = action.getDuration()
+ params["value"] = action.getinlineContent()
+ duration = action.getduration()
if duration:
params["duration"] = duration
- indicator = action.getIndicator()
+ indicator = action.getindicator()
if indicator:
params["indicator"] = indicator
actions.append(params)
return actions
- setattr(cls, "getActions", getActions)
+ setattr(cls, "getactions", getactions)
def updateElementName(self, old_name, new_name):
for action in self.action:
action.updateElementName(old_name, new_name)
setattr(cls, "updateElementName", updateElementName)
-cls = PLCOpenClasses.get("inVariable", None)
-if cls:
- setattr(cls, "getX", getX)
- setattr(cls, "getY", getY)
- setattr(cls, "setX", setX)
- setattr(cls, "setY", setY)
-
- def setConnectorEdge(self, edge):
- if not self.edge:
- self.edge = PLCOpenClasses["edgeModifierType"]()
- self.edge.setValue(edge)
- setattr(cls, "setConnectorEdge", setConnectorEdge)
-
- def getConnectorEdge(self):
- if self.edge:
- return self.edge.getValue()
- return None
- setattr(cls, "getConnectorEdge", getConnectorEdge)
+cls = PLCOpenClasses.get("fbdObjects_inVariable", None)
+if cls:
+ setattr(cls, "getx", getx)
+ setattr(cls, "gety", gety)
+ setattr(cls, "setx", setx)
+ setattr(cls, "sety", sety)
def updateElementName(self, old_name, new_name):
if self.expression == old_name:
self.expression = new_name
setattr(cls, "updateElementName", updateElementName)
-cls = PLCOpenClasses.get("outVariable", None)
-if cls:
- setattr(cls, "getX", getX)
- setattr(cls, "getY", getY)
- setattr(cls, "setX", setX)
- setattr(cls, "setY", setY)
-
- def setConnectorEdge(self, edge):
- if not self.edge:
- self.edge = PLCOpenClasses["edgeModifierType"]()
- self.edge.setValue(edge)
- setattr(cls, "setConnectorEdge", setConnectorEdge)
-
- def getConnectorEdge(self):
- if self.edge:
- return self.edge.getValue()
- return None
- setattr(cls, "getConnectorEdge", getConnectorEdge)
+cls = PLCOpenClasses.get("fbdObjects_outVariable", None)
+if cls:
+ setattr(cls, "getx", getx)
+ setattr(cls, "gety", gety)
+ setattr(cls, "setx", setx)
+ setattr(cls, "sety", sety)
def updateElementName(self, old_name, new_name):
if self.expression == old_name:
self.expression = new_name
setattr(cls, "updateElementName", updateElementName)
-cls = PLCOpenClasses.get("inOutVariable", None)
-if cls:
- setattr(cls, "getX", getX)
- setattr(cls, "getY", getY)
- setattr(cls, "setX", setX)
- setattr(cls, "setY", setY)
-
- def setInputEdge(self, edge):
- if not self.edgeIn:
- self.edgeIn = PLCOpenClasses["edgeModifierType"]()
- self.edgeIn.setValue(edge)
- setattr(cls, "setInputEdge", setInputEdge)
-
- def getInputEdge(self):
- if self.edgeIn:
- return self.edgeIn.getValue()
- return None
- setattr(cls, "getInputEdge", getInputEdge)
-
- def setOutputEdge(self, edge):
- if not self.edgeOut:
- self.edgeOut = PLCOpenClasses["edgeModifierType"]()
- self.edgeOut.setValue(edge)
- setattr(cls, "setInputEdge", setInputEdge)
-
- def getOutputEdge(self):
- if self.edgeOut:
- return self.edgeOut.getValue()
- return None
- setattr(cls, "getOutputEdge", getOutputEdge)
+cls = PLCOpenClasses.get("fbdObjects_inOutVariable", None)
+if cls:
+ setattr(cls, "getx", getx)
+ setattr(cls, "gety", gety)
+ setattr(cls, "setx", setx)
+ setattr(cls, "sety", sety)
def updateElementName(self, old_name, new_name):
if self.expression == old_name:
self.expression = new_name
setattr(cls, "updateElementName", updateElementName)
-cls = PLCOpenClasses.get("continuation", None)
-if cls:
- setattr(cls, "getX", getX)
- setattr(cls, "getY", getY)
- setattr(cls, "setX", setX)
- setattr(cls, "setY", setY)
+cls = PLCOpenClasses.get("commonObjects_continuation", None)
+if cls:
+ setattr(cls, "getx", getx)
+ setattr(cls, "gety", gety)
+ setattr(cls, "setx", setx)
+ setattr(cls, "sety", sety)
def updateElementName(self, old_name, new_name):
pass
setattr(cls, "updateElementName", updateElementName)
-cls = PLCOpenClasses.get("connector", None)
-if cls:
- setattr(cls, "getX", getX)
- setattr(cls, "getY", getY)
- setattr(cls, "setX", setX)
- setattr(cls, "setY", setY)
+cls = PLCOpenClasses.get("commonObjects_connector", None)
+if cls:
+ setattr(cls, "getx", getx)
+ setattr(cls, "gety", gety)
+ setattr(cls, "setx", setx)
+ setattr(cls, "sety", sety)
def updateElementName(self, old_name, new_name):
pass
@@ -1433,126 +1294,126 @@
cls = PLCOpenClasses.get("connection", None)
if cls:
- def setPoints(self, points):
+ def setpoints(self, points):
self.position = []
for point in points:
position = PLCOpenClasses["position"]()
- position.setX(point.x)
- position.setY(point.y)
+ position.setx(point.x)
+ position.sety(point.y)
self.position.append(position)
- setattr(cls, "setPoints", setPoints)
-
- def getPoints(self):
+ setattr(cls, "setpoints", setpoints)
+
+ def getpoints(self):
points = []
for position in self.position:
- points.append((position.getX(),position.getY()))
+ points.append((position.getx(),position.gety()))
return points
- setattr(cls, "getPoints", getPoints)
+ setattr(cls, "getpoints", getpoints)
cls = PLCOpenClasses.get("connectionPointIn", None)
if cls:
- def setRelPosition(self, x, y):
+ def setrelPositionXY(self, x, y):
self.relPosition = PLCOpenClasses["position"]()
- self.relPosition.setX(x)
- self.relPosition.setY(y)
- setattr(cls, "setRelPosition", setRelPosition)
-
- def getRelPosition(self):
+ self.relPosition.setx(x)
+ self.relPosition.sety(y)
+ setattr(cls, "setrelPositionXY", setrelPositionXY)
+
+ def getrelPositionXY(self):
if self.relPosition:
- return self.relPosition.getX(), self.relPosition.getY()
+ return self.relPosition.getx(), self.relPosition.gety()
else:
return self.relPosition
- setattr(cls, "getRelPosition", getRelPosition)
-
- def addConnection(self):
+ setattr(cls, "getrelPositionXY", getrelPositionXY)
+
+ def addconnection(self):
if not self.content:
- self.content = {"name":"connection","value":[PLCOpenClasses["connection"]()]}
+ self.content = {"name" : "connection", "value" : [PLCOpenClasses["connection"]()]}
else:
self.content["value"].append(PLCOpenClasses["connection"]())
- setattr(cls, "addConnection", addConnection)
-
- def removeConnection(self, idx):
+ setattr(cls, "addconnection", addconnection)
+
+ def removeconnection(self, idx):
if self.content:
self.content["value"].pop(idx)
if len(self.content["value"]) == 0:
self.content = None
- setattr(cls, "removeConnection", removeConnection)
-
- def removeConnections(self):
+ setattr(cls, "removeconnection", removeconnection)
+
+ def removeconnections(self):
if self.content:
self.content = None
- setattr(cls, "removeConnections", removeConnections)
-
- def getConnections(self):
+ setattr(cls, "removeconnections", removeconnections)
+
+ def getconnections(self):
if self.content:
return self.content["value"]
- setattr(cls, "getConnections", getConnections)
-
- def setConnectionId(self, idx, id):
+ setattr(cls, "getconnections", getconnections)
+
+ def setconnectionId(self, idx, id):
if self.content:
- self.content["value"][idx].setRefLocalId(id)
- setattr(cls, "setConnectionId", setConnectionId)
-
- def getConnectionId(self, idx):
+ self.content["value"][idx].setrefLocalId(id)
+ setattr(cls, "setconnectionId", setconnectionId)
+
+ def getconnectionId(self, idx):
if self.content:
- return self.content["value"][idx].getRefLocalId()
+ return self.content["value"][idx].getrefLocalId()
return None
- setattr(cls, "getConnectionId", getConnectionId)
-
- def setConnectionPoints(self, idx, points):
+ setattr(cls, "getconnectionId", getconnectionId)
+
+ def setconnectionPoints(self, idx, points):
if self.content:
- self.content["value"][idx].setPoints(points)
- setattr(cls, "setConnectionPoints", setConnectionPoints)
-
- def getConnectionPoints(self, idx):
+ self.content["value"][idx].setpoints(points)
+ setattr(cls, "setconnectionPoints", setconnectionPoints)
+
+ def getconnectionPoints(self, idx):
if self.content:
- return self.content["value"][idx].getPoints()
+ return self.content["value"][idx].getpoints()
return None
- setattr(cls, "getConnectionPoints", getConnectionPoints)
-
- def setConnectionParameter(self, idx, parameter):
+ setattr(cls, "getconnectionPoints", getconnectionPoints)
+
+ def setconnectionParameter(self, idx, parameter):
if self.content:
- self.content["value"][idx].setFormalParameter(parameter)
- setattr(cls, "setConnectionParameter", setConnectionParameter)
-
- def getConnectionParameter(self, idx):
+ self.content["value"][idx].setformalParameter(parameter)
+ setattr(cls, "setconnectionParameter", setconnectionParameter)
+
+ def getconnectionParameter(self, idx):
if self.content:
- return self.content["value"][idx].getFormalParameter()
+ return self.content["value"][idx].getformalParameter()
return None
- setattr(cls, "getConnectionParameter", getConnectionParameter)
+ setattr(cls, "getconnectionParameter", getconnectionParameter)
cls = PLCOpenClasses.get("connectionPointOut", None)
if cls:
- def setRelPosition(self, x, y):
+ def setrelPositionXY(self, x, y):
self.relPosition = PLCOpenClasses["position"]()
- self.relPosition.setX(x)
- self.relPosition.setY(y)
- setattr(cls, "setRelPosition", setRelPosition)
-
- def getRelPosition(self):
+ self.relPosition.setx(x)
+ self.relPosition.sety(y)
+ setattr(cls, "setrelPositionXY", setrelPositionXY)
+
+ def getrelPositionXY(self):
if self.relPosition:
- return self.relPosition.getX(), self.relPosition.getY()
+ return self.relPosition.getx(), self.relPosition.gety()
return self.relPosition
- setattr(cls, "getRelPosition", getRelPosition)
+ setattr(cls, "getrelPositionXY", getrelPositionXY)
cls = PLCOpenClasses.get("value", None)
if cls:
- def setValue(self, value):
+ def setvalue(self, value):
if value.startswith("[") and value.endswith("]"):
arrayValue = PLCOpenClasses["value_arrayValue"]()
- self.content = {"name":"arrayValue","value":arrayValue}
+ self.content = {"name" : "arrayValue", "value" : arrayValue}
elif value.startswith("(") and value.endswith(")"):
structValue = PLCOpenClasses["value_structValue"]()
- self.content = {"name":"structValue","value":structValue}
+ self.content = {"name" : "structValue", "value" : structValue}
else:
simpleValue = PLCOpenClasses["value_simpleValue"]()
- self.content = {"name":"simpleValue","value":simpleValue}
- self.content["value"].setValue(value)
- setattr(cls, "setValue", setValue)
-
- def getValue(self):
- return self.content["value"].getValue()
- setattr(cls, "getValue", getValue)
+ self.content = {"name" : "simpleValue", "value": simpleValue}
+ self.content["value"].setvalue(value)
+ setattr(cls, "setvalue", setvalue)
+
+ def getvalue(self):
+ return self.content["value"].getvalue()
+ setattr(cls, "getvalue", getvalue)
def extractValues(values):
items = values.split(",")
@@ -1572,7 +1433,7 @@
if cls:
arrayValue_model = re.compile("([0-9]*)\((.*)\)$")
- def setValue(self, value):
+ def setvalue(self, value):
self.value = []
for item in extractValues(value[1:-1]):
item = item.strip()
@@ -1580,43 +1441,43 @@
result = arrayValue_model.match(item)
if result is not None:
groups = result.groups()
- element.setRepetitionValue(int(groups[0]))
- element.setValue(groups[1].strip())
+ element.setrepetitionValue(int(groups[0]))
+ element.setvalue(groups[1].strip())
else:
- element.setValue(item)
+ element.setvalue(item)
self.value.append(element)
- setattr(cls, "setValue", setValue)
-
- def getValue(self):
+ setattr(cls, "setvalue", setvalue)
+
+ def getvalue(self):
values = []
for element in self.value:
- repetition = element.getRepetitionValue()
+ repetition = element.getrepetitionValue()
if repetition is not None and repetition > 1:
- values.append("%d(%s)"%(repetition, element.getValue()))
+ values.append("%d(%s)"%(repetition, element.getvalue()))
else:
- values.append(element.getValue())
+ values.append(element.getvalue())
return "[%s]"%", ".join(values)
- setattr(cls, "getValue", getValue)
+ setattr(cls, "getvalue", getvalue)
cls = PLCOpenClasses.get("value_structValue", None)
if cls:
structValue_model = re.compile("(.*):=(.*)")
- def setValue(self, value):
+ def setvalue(self, value):
self.value = []
for item in extractValues(value[1:-1]):
result = arrayValue_model.match(item)
if result is not None:
groups = result.groups()
element = PLCOpenClasses["structValue_value"]()
- element.setMember(groups[0].strip())
- element.setValue(groups[1].strip())
+ element.setmember(groups[0].strip())
+ element.setvalue(groups[1].strip())
self.value.append(element)
- setattr(cls, "setValue", setValue)
-
- def getValue(self):
+ setattr(cls, "setvalue", setvalue)
+
+ def getvalue(self):
values = []
for element in self.value:
- values.append("%s := %s"%(element.getMember(), element.getValue()))
+ values.append("%s := %s"%(element.getmember(), element.getvalue()))
return "(%s)"%", ".join(values)
- setattr(cls, "getValue", getValue)
+ setattr(cls, "getvalue", getvalue)
--- a/plcopen/structures.py Tue Jan 22 10:53:34 2008 +0100
+++ b/plcopen/structures.py Tue Jan 22 10:57:41 2008 +0100
@@ -34,14 +34,14 @@
"L" : ["LINT", "ULINT", "LREAL", "LWORD"]}
def generate_block(generator, block, body, link, order=False):
- body_type = body.getContent()["name"]
- name = block.getInstanceName()
- type = block.getTypeName()
- executionOrderId = block.getExecutionOrderId()
+ body_type = body.getcontent()["name"]
+ name = block.getinstanceName()
+ type = block.gettypeName()
+ executionOrderId = block.getexecutionOrderId()
block_infos = GetBlockType(type)
if block_infos["type"] == "function":
- output_variable = block.outputVariables.getVariable()[0]
- output_name = "%s%d_OUT"%(type, block.getLocalId())
+ output_variable = block.outputVariables.getvariable()[0]
+ output_name = "%s%d_OUT"%(type, block.getlocalId())
if not generator.ComputedBlocks.get(block, False) and not order:
if generator.Interface[-1][0] != "VAR" or generator.Interface[-1][1] or generator.Interface[-1][2] or generator.Interface[-1][3]:
generator.Interface.append(("VAR", False, False, False, []))
@@ -50,8 +50,8 @@
else:
generator.Interface[-1][4].append(("ANY", output_name, None, None))
vars = []
- for variable in block.inputVariables.getVariable():
- connections = variable.connectionPointIn.getConnections()
+ for variable in block.inputVariables.getvariable():
+ connections = variable.connectionPointIn.getconnections()
if connections and len(connections) == 1:
if body_type == "FBD" or body_type == "SFC":
value = generator.ComputeFBDExpression(body, connections[0], executionOrderId > 0)
@@ -69,15 +69,15 @@
elif block_infos["type"] == "functionBlock":
if not generator.ComputedBlocks.get(block, False) and not order:
vars = []
- for variable in block.inputVariables.getVariable():
- connections = variable.connectionPointIn.getConnections()
+ for variable in block.inputVariables.getvariable():
+ connections = variable.connectionPointIn.getconnections()
if connections and len(connections) == 1:
- parameter = variable.getFormalParameter()
+ parameter = variable.getformalParameter()
if body_type == "FBD" or body_type == "SFC":
value = generator.ComputeFBDExpression(body, connections[0], executionOrderId > 0)
vars.append("%s := %s"%(parameter, generator.ExtractModifier(variable, value)))
elif body_type == "LD":
- paths = generator.GenerateLDPaths(variable.connectionPointIn.getConnections(), body)
+ paths = generator.GenerateLDPaths(variable.connectionPointIn.getconnections(), body)
if len(paths) > 0:
paths = tuple(paths)
else:
@@ -87,13 +87,13 @@
generator.Program += " %s(%s);\n"%(name, ", ".join(vars))
generator.ComputedBlocks[block] = True
if link:
- connectionPoint = link.getPosition()[-1]
+ connectionPoint = link.getposition()[-1]
else:
connectionPoint = None
- for variable in block.outputVariables.getVariable():
- blockPointx, blockPointy = variable.connectionPointOut.getRelPosition()
- if not connectionPoint or block.getX() + blockPointx == connectionPoint.getX() and block.getY() + blockPointy == connectionPoint.getY():
- return generator.ExtractModifier(variable, "%s.%s"%(name, variable.getFormalParameter()))
+ for variable in block.outputVariables.getvariable():
+ blockPointx, blockPointy = variable.connectionPointOut.getrelPositionXY()
+ if not connectionPoint or block.getx() + blockPointx == connectionPoint.getx() and block.gety() + blockPointy == connectionPoint.gety():
+ return generator.ExtractModifier(variable, "%s.%s"%(name, variable.getformalParameter()))
raise ValueError, "No output variable found"
def initialise_block(type, name):
--- a/xmlclass/__init__.py Tue Jan 22 10:53:34 2008 +0100
+++ b/xmlclass/__init__.py Tue Jan 22 10:57:41 2008 +0100
@@ -25,3 +25,4 @@
# Package initialisation
from xmlclass import *
+from xsdschema import *
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/xmlclass/po.xml Tue Jan 22 10:57:41 2008 +0100
@@ -0,0 +1,32 @@
+<?xml version="1.0"?>
+<purchaseOrder orderDate="1999-10-20">
+ <shipTo country="US">
+ <name>Alice Smith</name>
+ <street>123 Maple Street</street>
+ <city>Mill Valley</city>
+ <state>CA</state>
+ <zip>90952</zip>
+ </shipTo>
+ <billTo country="US">
+ <name>Robert Smith</name>
+ <street>8 Oak Avenue</street>
+ <city>Old Town</city>
+ <state>PA</state>
+ <zip>95819</zip>
+ </billTo>
+ <comment>Hurry, my lawn is going wild!</comment>
+ <items>
+ <item partNum="872-AA">
+ <productName>Lawnmower</productName>
+ <quantity>1</quantity>
+ <USPrice>148.95</USPrice>
+ <comment>Confirm this is electric</comment>
+ </item>
+ <item partNum="926-AA">
+ <productName>Baby Monitor</productName>
+ <quantity>1</quantity>
+ <USPrice>39.98</USPrice>
+ <shipDate>1999-05-21</shipDate>
+ </item>
+ </items>
+</purchaseOrder>
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/xmlclass/test.xsd Tue Jan 22 10:57:41 2008 +0100
@@ -0,0 +1,66 @@
+<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
+
+ <xsd:annotation>
+ <xsd:documentation xml:lang="en">
+ Purchase order schema for Example.com.
+ Copyright 2000 Example.com. All rights reserved.
+ </xsd:documentation>
+ </xsd:annotation>
+
+ <xsd:element name="purchaseOrder" type="PurchaseOrderType"/>
+
+ <xsd:element name="comment" type="xsd:string"/>
+
+ <xsd:complexType name="PurchaseOrderType">
+ <xsd:sequence>
+ <xsd:element name="shipTo" type="USAddress"/>
+ <xsd:element name="billTo" type="USAddress"/>
+ <xsd:element ref="comment" minOccurs="0"/>
+ <xsd:element name="items" type="Items"/>
+ </xsd:sequence>
+ <xsd:attribute name="orderDate" type="xsd:date"/>
+ </xsd:complexType>
+
+ <xsd:complexType name="USAddress">
+ <xsd:sequence>
+ <xsd:element name="name" type="xsd:string"/>
+ <xsd:element name="street" type="xsd:string"/>
+ <xsd:element name="city" type="xsd:string"/>
+ <xsd:element name="state" type="xsd:string"/>
+ <xsd:element name="zip" type="xsd:decimal"/>
+ </xsd:sequence>
+ <xsd:attribute name="country" type="xsd:NMTOKEN"
+ fixed="US"/>
+ </xsd:complexType>
+
+ <xsd:complexType name="Items">
+ <xsd:sequence>
+ <xsd:element name="item" minOccurs="0" maxOccurs="unbounded">
+ <xsd:complexType>
+ <xsd:sequence>
+ <xsd:element name="productName" type="xsd:string"/>
+ <xsd:element name="quantity">
+ <xsd:simpleType>
+ <xsd:restriction base="xsd:positiveInteger">
+ <xsd:maxExclusive value="100"/>
+ </xsd:restriction>
+ </xsd:simpleType>
+ </xsd:element>
+ <xsd:element name="USPrice" type="xsd:decimal"/>
+ <xsd:element ref="comment" minOccurs="0"/>
+ <xsd:element name="shipDate" type="xsd:date" minOccurs="0"/>
+ </xsd:sequence>
+ <xsd:attribute name="partNum" type="SKU" use="required"/>
+ </xsd:complexType>
+ </xsd:element>
+ </xsd:sequence>
+ </xsd:complexType>
+
+ <!-- Stock Keeping Unit, a code for identifying products -->
+ <xsd:simpleType name="SKU">
+ <xsd:restriction base="xsd:string">
+ <xsd:pattern value="\d{3}-[A-Z]{2}"/>
+ </xsd:restriction>
+ </xsd:simpleType>
+
+</xsd:schema>
--- a/xmlclass/xmlclass.py Tue Jan 22 10:53:34 2008 +0100
+++ b/xmlclass/xmlclass.py Tue Jan 22 10:57:41 2008 +0100
@@ -23,19 +23,34 @@
#Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
from xml.dom import minidom
-import sys,re
+import sys, re, datetime
from types import *
-from datetime import *
from new import classobj
+LANGUAGES = ["en-US", "fr-FR", "en", "fr"]
+
+"""
+Regular expression models for check all kind of string
+"""
+Name_model = re.compile('([a-zA-Z_\:][\w\.\-\:]*)$')
+Names_model = re.compile('([a-zA-Z_\:][\w\.\-\:]*(?: [a-zA-Z_\:][\w\.\-\:]*)*)$')
+NMToken_model = re.compile('([\w\.\-\:]*)$')
+NMTokens_model = re.compile('([\w\.\-\:]*(?: [\w\.\-\:]*)*)$')
+QName_model = re.compile('((?:[a-zA-Z_][\w]*:)?[a-zA-Z_][\w]*)$')
+QNames_model = re.compile('((?:[a-zA-Z_][\w]*:)?[a-zA-Z_][\w]*(?: (?:[a-zA-Z_][\w]*:)?[a-zA-Z_][\w]*)*)$')
+NCName_model = re.compile('([a-zA-Z_][\w]*)$')
+URI_model = re.compile('((?:http://|/)?(?:[\w.]*/?)*)$')
+
+ONLY_ANNOTATION = re.compile("((?:annotation )?)")
+
"""
Regular expression models for extracting dates and times from a string
"""
-time_model = re.compile('([0-9]{2}):([0-9]{2}):([0-9]{2}(?:\.[0-9]*)?)(?:Z)?')
-date_model = re.compile('([0-9]{4})-([0-9]{2})-([0-9]{2})((?:[\-\+][0-9]{2}:[0-9]{2})|Z)?')
-datetime_model = re.compile('([0-9]{4})-([0-9]{2})-([0-9]{2})[ T]([0-9]{2}):([0-9]{2}):([0-9]{2}(?:\.[0-9]*)?)((?:[\-\+][0-9]{2}:[0-9]{2})|Z)?')
-
-class xml_timezone(tzinfo):
+time_model = re.compile('([0-9]{2}):([0-9]{2}):([0-9]{2}(?:\.[0-9]*)?)(?:Z)?$')
+date_model = re.compile('([0-9]{4})-([0-9]{2})-([0-9]{2})((?:[\-\+][0-9]{2}:[0-9]{2})|Z)?$')
+datetime_model = re.compile('([0-9]{4})-([0-9]{2})-([0-9]{2})[ T]([0-9]{2}):([0-9]{2}):([0-9]{2}(?:\.[0-9]*)?)((?:[\-\+][0-9]{2}:[0-9]{2})|Z)?$')
+
+class xml_timezone(datetime.tzinfo):
def SetOffset(self, offset):
if offset == "Z":
@@ -56,11 +71,20 @@
def dst(self, dt):
return ZERO
-XSD_INTEGER_TYPES = ["integer","nonPositiveInteger","negativeInteger","long",
- "int","short","byte","nonNegativeInteger","unsignedLong","unsignedInt",
- "unsignedShort","unsignedByte","positiveInteger"]
-
-XSD_STRING_TYPES = ["string","normalizedString","token","anyURI","NMTOKEN","language"]
+[SYNTAXELEMENT, SYNTAXATTRIBUTE, SIMPLETYPE, COMPLEXTYPE, COMPILEDCOMPLEXTYPE,
+ ATTRIBUTESGROUP, ELEMENTSGROUP, ATTRIBUTE, ELEMENT, CHOICE, ANY, TAG
+] = range(12)
+
+def NotSupportedYet(type):
+ """
+ Function that generates a function that point out to user that datatype asked
+ are not yet supported by xmlclass
+ @param type: data type
+ @return: function generated
+ """
+ def GetUnknownValue(attr):
+ raise ValueError, "\"%s\" type isn't supported by \"xmlclass\" yet!"%type
+ return GetUnknownValue
"""
This function calculates the number of whitespace for indentation
@@ -70,529 +94,893 @@
second = first + len(balise) + 1
return "\t".expandtabs(first), "\t".expandtabs(second)
-"""
-Function that extracts data from a node
-"""
-def GetAttributeValue(attr):
+
+def GetAttributeValue(attr, extract = True):
+ """
+ Function that extracts data from a tree node
+ @param attr: tree node containing data to extract
+ @param extract: attr is a tree node or not
+ @return: data extracted as string
+ """
+ if not extract:
+ return attr
if len(attr.childNodes) == 1:
return attr.childNodes[0].data.encode()
else:
+ # content is a CDATA
text = ""
for node in attr.childNodes:
if node.nodeName != "#text":
text += node.data.encode()
return text
-"""
-Function that computes value from a python type (Only Boolean are critical because
-there is no uppercase in plcopen)
-"""
-def ComputeValue(value):
- if type(value) == BooleanType:
- if value:
- return "true"
- else:
- return "false"
+
+def GetNormalizedString(attr, extract = True):
+ """
+ Function that normalizes a string according to XML 1.0. Replace tabulations,
+ line feed and carriage return by white space
+ @param attr: tree node containing data to extract or data to normalize
+ @param extract: attr is a tree node or not
+ @return: data normalized as string
+ """
+ if extract:
+ return GetAttributeValue(attr).replace("\n", " ").replace("\t", " ")
else:
- return str(value)
-
-"""
-Function that extracts a value from a string following the xsd type given
-"""
-def GetComputedValue(attr_type, value):
- type_compute = attr_type[4:].replace("[]", "")
- if type_compute == "boolean":
- if value == "true":
- return True
- elif value == "false":
- return False
- else:
- raise ValueError, "\"%s\" is not a valid boolean!"%value
- elif type_compute in XSD_INTEGER_TYPES:
- return int(value)
- elif type_compute in ["decimal", "float", "double"]:
- computed_value = float(value)
- if computed_value % 1 == 0:
- return int(computed_value)
- return computed_value
- elif type_compute in XSD_STRING_TYPES:
+ return attr.replace("\n", " ").replace("\t", " ")
+
+
+def GetToken(attr, extract = True):
+ """
+ Function that tokenizes a string according to XML 1.0. Remove any leading and
+ trailing white space and replace internal sequence of two or more spaces by
+ only one white space
+ @param attr: tree node containing data to extract or data to tokenize
+ @param extract: attr is a tree node or not
+ @return: data tokenized as string
+ """
+ return " ".join([part for part in GetNormalizedString(attr, extract).split(" ") if part])
+
+
+def GetHexInteger(attr, extract = True):
+ """
+ Function that extracts an hexadecimal integer from a tree node or a string
+ @param attr: tree node containing data to extract or data as a string
+ @param extract: attr is a tree node or not
+ @return: data as an integer
+ """
+ if extract:
+ value = GetAttributeValue(attr)
+ else:
+ value = attr
+ try:
+ return int(value, 16)
+ except:
+ raise ValueError, "\"%s\" isn't a valid hexadecimal integer!"%value
+
+
+def GenerateIntegerExtraction(minInclusive = None, maxInclusive = None, minExclusive = None, maxExclusive = None):
+ """
+ Function that generates an extraction function for integer defining min and max
+ of integer value
+ @param minInclusive: inclusive minimum
+ @param maxInclusive: inclusive maximum
+ @param minExclusive: exclusive minimum
+ @param maxExclusive: exclusive maximum
+ @return: function generated
+ """
+ def GetInteger(attr, extract = True):
+ """
+ Function that extracts an integer from a tree node or a string
+ @param attr: tree node containing data to extract or data as a string
+ @param extract: attr is a tree node or not
+ @return: data as an integer
+ """
+
+ if extract:
+ value = GetAttributeValue(attr)
+ else:
+ value = attr
+ try:
+ # TODO: permit to write value like 1E2
+ value = int(value)
+ except:
+ raise ValueError, "\"%s\" isn't a valid integer!"%value
+ if minInclusive is not None and value < minInclusive:
+ raise ValueError, "%d isn't greater or equal to %d!"%(value, minInclusive)
+ if maxInclusive is not None and value > maxInclusive:
+ raise ValueError, "%d isn't lesser or equal to %d!"%(value, maxInclusive)
+ if minExclusive is not None and value <= minExclusive:
+ raise ValueError, "%d isn't greater than %d!"%(value, minExclusive)
+ if maxExclusive is not None and value >= maxExclusive:
+ raise ValueError, "%d isn't lesser than %d!"%(value, maxExclusive)
return value
- elif type_compute == "time":
- result = time_model.match(value)
- if result:
- 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)])
- return time(*time_values)
- else:
- raise ValueError, "\"%s\" is not a valid time!"%value
- elif type_compute == "date":
- result = date_model.match(value)
- if result:
- values = result.groups()
- date_values = [int(v) for v in values[:3]]
- if values[3] is not None:
- tz = xml_timezone()
- tz.SetOffset(values[3])
- date_values.append(tz)
- return date(*date_values)
- else:
- raise ValueError, "\"%s\" is not a valid date!"%value
- elif type_compute == "dateTime":
- result = datetime_model.match(value)
- if result:
- values = result.groups()
- datetime_values = [int(v) for v in values[:5]]
- seconds = float(values[5])
- datetime_values.extend([int(seconds), int((seconds % 1) * 1000000)])
- if values[6] is not None:
- tz = xml_timezone()
- tz.SetOffset(values[6])
- datetime_values.append(tz)
- return datetime(*datetime_values)
- else:
- raise ValueError, "\"%s\" is not a valid datetime!"%value
+ return GetInteger
+
+
+def GenerateFloatExtraction(type, extra_values = []):
+ """
+ Function that generates an extraction function for float
+ @param type: name of the type of float
+ @return: function generated
+ """
+ def GetFloat(attr, extract = True):
+ """
+ Function that extracts a float from a tree node or a string
+ @param attr: tree node containing data to extract or data as a string
+ @param extract: attr is a tree node or not
+ @return: data as a float
+ """
+ if extract:
+ value = GetAttributeValue(attr)
+ else:
+ value = attr
+ try:
+ if value in extra_values:
+ return value
+ return float(value)
+ except:
+ raise ValueError, "\"%s\" isn't a valid %s!"%(value, type)
+ return GetFloat
+
+
+def GetBoolean(attr, extract = True):
+ """
+ Function that extracts a boolean from a tree node or a string
+ @param attr: tree node containing data to extract or data as a string
+ @param extract: attr is a tree node or not
+ @return: data as a boolean
+ """
+ if extract:
+ value = GetAttributeValue(attr)
else:
- print "Can't affect: %s"%type_compute
+ value = attr
+ if value == "true" or value == "1":
+ return True
+ elif value == "false" or value == "0":
+ return False
+ else:
+ raise ValueError, "\"%s\" isn't a valid boolean!"%value
+
+
+def GetTime(attr, extract = True):
+ """
+ Function that extracts a time from a tree node or a string
+ @param attr: tree node containing data to extract or data as a string
+ @param extract: attr is a tree node or not
+ @return: data as a time
+ """
+ if extract:
+ result = time_model.match(GetAttributeValue(attr))
+ else:
+ result = time_model.match(attr)
+ if result:
+ 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)])
+ return datetime.time(*time_values)
+ else:
+ raise ValueError, "\"%s\" is not a valid time!"%value
+
+
+def GetDate(attr, extract = True):
+ """
+ Function that extracts a date from a tree node or a string
+ @param attr: tree node containing data to extract or data as a string
+ @param extract: attr is a tree node or not
+ @return: data as a date
+ """
+ if extract:
+ result = date_model.match(GetAttributeValue(attr))
+ else:
+ result = date_model.match(attr)
+ if result:
+ values = result.groups()
+ date_values = [int(v) for v in values[:3]]
+ if values[3] is not None:
+ tz = xml_timezone()
+ tz.SetOffset(values[3])
+ date_values.append(tz)
+ return datetime.date(*date_values)
+ else:
+ raise ValueError, "\"%s\" is not a valid date!"%value
+
+
+def GetDateTime(attr, extract = True):
+ """
+ Function that extracts date and time from a tree node or a string
+ @param attr: tree node containing data to extract or data as a string
+ @param extract: attr is a tree node or not
+ @return: data as date and time
+ """
+ if extract:
+ result = datetime_model.match(GetAttributeValue(attr))
+ else:
+ result = datetime_model.match(attr)
+ if result:
+ values = result.groups()
+ datetime_values = [int(v) for v in values[:5]]
+ seconds = float(values[5])
+ datetime_values.extend([int(seconds), int((seconds % 1) * 1000000)])
+ if values[6] is not None:
+ tz = xml_timezone()
+ tz.SetOffset(values[6])
+ datetime_values.append(tz)
+ return datetime.datetime(*datetime_values)
+ else:
+ raise ValueError, "\"%s\" is not a valid datetime!"%value
+
+
+def GenerateModelNameExtraction(type, model):
+ """
+ Function that generates an extraction function for string matching a model
+ @param type: name of the data type
+ @param model: model that data must match
+ @return: function generated
+ """
+ def GetModelName(attr, extract = True):
+ """
+ Function that extracts a string from a tree node or not and check that
+ string extracted or given match the model
+ @param attr: tree node containing data to extract or data as a string
+ @param extract: attr is a tree node or not
+ @return: data as a string if matching
+ """
+ if extract:
+ value = GetAttributeValue(attr)
+ else:
+ value = attr
+ result = model.match(value)
+ if not result:
+ raise ValueError, "\"%s\" is not a valid %s!"%(value, type)
+ return value
+ return GetModelName
+
+
+def GenerateLimitExtraction(min = None, max = None, unbounded = True):
+ """
+ Function that generates an extraction function for integer defining min and max
+ of integer value
+ @param min: minimum limit value
+ @param max: maximum limit value
+ @param unbounded: value can be "unbounded" or not
+ @return: function generated
+ """
+ def GetLimit(attr, extract = True):
+ """
+ Function that extracts a string from a tree node or not and check that
+ string extracted or given is in a list of values
+ @param attr: tree node containing data to extract or data as a string
+ @param extract: attr is a tree node or not
+ @return: data as a string
+ """
+ if extract:
+ value = GetAttributeValue(attr)
+ else:
+ value = attr
+ if value == "unbounded":
+ if unbounded:
+ return value
+ else:
+ raise "\"%s\" isn't a valid value for this member limit!"%value
+ try:
+ limit = int(value)
+ except:
+ raise "\"%s\" isn't a valid value for this member limit!"%value
+ if limit < 0:
+ raise "\"%s\" isn't a valid value for this member limit!"%value
+ elif min is not None and limit < min:
+ raise "\"%s\" isn't a valid value for this member limit!"%value
+ elif max is not None and limit > max:
+ raise "\"%s\" isn't a valid value for this member limit!"%value
+ return limit
+ return GetLimit
+
+
+def GenerateEnumeratedExtraction(type, list):
+ """
+ Function that generates an extraction function for enumerated values
+ @param type: name of the data type
+ @param list: list of possible values
+ @return: function generated
+ """
+ def GetEnumerated(attr, extract = True):
+ """
+ Function that extracts a string from a tree node or not and check that
+ string extracted or given is in a list of values
+ @param attr: tree node containing data to extract or data as a string
+ @param extract: attr is a tree node or not
+ @return: data as a string
+ """
+ if extract:
+ value = GetAttributeValue(attr)
+ else:
+ value = attr
+ if value in list:
+ return value
+ else:
+ raise ValueError, "\"%s\" isn't a valid value for %s!"%(value, type)
+ return GetEnumerated
+
+
+def GetNamespaces(attr, extract = True):
+ """
+ Function that extracts a list of namespaces from a tree node or a string
+ @param attr: tree node containing data to extract or data as a string
+ @param extract: attr is a tree node or not
+ @return: list of namespaces
+ """
+ if extract:
+ value = GetAttributeValue(attr)
+ else:
+ value = attr
+ if value == "":
+ return []
+ elif value == "##any" or value == "##other":
+ namespaces = [value]
+ else:
+ namespaces = []
+ for item in value.split(" "):
+ if item == "##targetNamespace" or item == "##local":
+ namespaces.append(item)
+ else:
+ result = URI_model.match(item)
+ if result is not None:
+ namespaces.append(item)
+ else:
+ raise ValueError, "\"%s\" isn't a valid value for namespace!"%value
+ return namespaces
+
+
+def GenerateGetList(type, list):
+ """
+ Function that generates an extraction function for a list of values
+ @param type: name of the data type
+ @param list: list of possible values
+ @return: function generated
+ """
+ def GetLists(attr, extract = True):
+ """
+ Function that extracts a list of values from a tree node or a string
+ @param attr: tree node containing data to extract or data as a string
+ @param extract: attr is a tree node or not
+ @return: list of values
+ """
+ if extract:
+ value = GetAttributeValue(attr)
+ else:
+ value = attr
+ if value == "":
+ return []
+ elif value == "#all":
+ return [value]
+ else:
+ values = []
+ for item in value.split(" "):
+ if item in list:
+ values.append(item)
+ else:
+ raise ValueError, "\"%s\" isn't a valid value for %s!"%(value, type)
+ return values
+ return GetLists
+
+
+def GenerateModelNameListExtraction(type, model):
+ """
+ Function that generates an extraction function for list of string matching a model
+ @param type: name of the data type
+ @param model: model that list elements must match
+ @return: function generated
+ """
+ def GetModelNameList(attr, extract = True):
+ """
+ Function that extracts a list of string from a tree node or not and check
+ that all the items extracted match the model
+ @param attr: tree node containing data to extract or data as a string
+ @param extract: attr is a tree node or not
+ @return: data as a list of string if matching
+ """
+ if extract:
+ value = GetAttributeValue(attr)
+ else:
+ value = attr
+ values = []
+ for item in value.split(" "):
+ result = model.match(item)
+ if result is not None:
+ values.append(item)
+ else:
+ raise ValueError, "\"%s\" isn't a valid value for %s!"%(value, type)
+ return values
+ return GetModelNameList
+
+def GenerateAnyInfos():
+ def ExtractAny(tree):
+ return tree.data.encode()
+
+ def GenerateAny(value, name = None, indent = 0):
+ return "<![CDATA[%s]]>\n"%str(value)
+
+ return {
+ "type" : COMPLEXTYPE,
+ "extract" : ExtractAny,
+ "generate" : GenerateAny,
+ "initial" : lambda: "",
+ "check" : lambda x: isinstance(x, (StringType, UnicodeType))
+ }
+
+def GenerateTagInfos(name):
+ def ExtractTag(tree):
+ if len(tree._attrs) > 0:
+ raise ValueError, "\"%s\" musn't have attributes!"%name
+ if len(tree.childNodes) > 0:
+ raise ValueError, "\"%s\" musn't have children!"%name
return None
-
-def GetInitialValueFunction(value):
- def GetInitialValue():
- return value
- return GetInitialValue
-
-"""
-Class that generate class from an XML Tree
+
+ def GenerateTag(value, name = None, indent = 0):
+ if name is not None:
+ ind1, ind2 = getIndent(indent, name)
+ return ind1 + "<%s/>\n"%name
+ else:
+ return ""
+
+ return {
+ "type" : TAG,
+ "extract" : ExtractTag,
+ "generate" : GenerateTag,
+ "initial" : lambda: None,
+ "check" : lambda x: x == None
+ }
+
+def GenerateContentInfos(factory, choices):
+ def GetContentInitial():
+ content_name, infos = choices[0]
+ if isinstance(infos["elmt_type"], (UnicodeType, StringType)):
+ namespace, name = DecomposeQualifiedName(infos["elmt_type"])
+ infos["elmt_type"] = factory.GetQualifiedNameInfos(name, namespace)
+ if infos["maxOccurs"] == "unbounded" or infos["maxOccurs"] > 1:
+ return {"name" : content_name, "value" : map(infos["elmt_type"]["initial"], range(infos["minOccurs"]))}
+ else:
+ return {"name" : content_name, "value" : infos["elmt_type"]["initial"]()}
+
+ def CheckContent(value):
+ for content_name, infos in choices:
+ if content_name == value["name"]:
+ if isinstance(infos["elmt_type"], (UnicodeType, StringType)):
+ namespace, name = DecomposeQualifiedName(infos["elmt_type"])
+ infos["elmt_type"] = factory.GetQualifiedNameInfos(name, namespace)
+ if infos["maxOccurs"] == "unbounded" or infos["maxOccurs"] > 1:
+ if isinstance(value["value"], ListType) and infos["minOccurs"] <= len(value["value"]) <= infos["maxOccurs"]:
+ return reduce(lambda x, y: x and y, map(infos["elmt_type"]["check"], value["value"]), True)
+ else:
+ return infos["elmt_type"]["check"](value["value"])
+ return False
+
+ def ExtractContent(tree, content):
+ for content_name, infos in choices:
+ if content_name == tree.nodeName:
+ if isinstance(infos["elmt_type"], (UnicodeType, StringType)):
+ namespace, name = DecomposeQualifiedName(infos["elmt_type"])
+ infos["elmt_type"] = factory.GetQualifiedNameInfos(name, namespace)
+ if infos["maxOccurs"] == "unbounded" or infos["maxOccurs"] > 1:
+ if isinstance(content, ListType) and len(content) > 0 and content[-1]["name"] == content_name:
+ content_item = content.pop(-1)
+ content_item["value"].append(infos["elmt_type"]["extract"](tree))
+ return content_item
+ elif not isinstance(content, ListType) and content is not None and content["name"] == content_name:
+ return {"name" : content_name, "value" : content["value"] + [infos["elmt_type"]["extract"](tree)]}
+ else:
+ return {"name" : content_name, "value" : [infos["elmt_type"]["extract"](tree)]}
+ else:
+ return {"name" : content_name, "value" : infos["elmt_type"]["extract"](tree)}
+ raise ValueError, "Invalid element \"%s\" for content!"%tree.nodeName
+
+ def GenerateContent(value, name = None, indent = 0):
+ for content_name, infos in choices:
+ if content_name == value["name"]:
+ if isinstance(infos["elmt_type"], (UnicodeType, StringType)):
+ namespace, name = DecomposeQualifiedName(infos["elmt_type"])
+ infos["elmt_type"] = factory.GetQualifiedNameInfos(name, namespace)
+ if infos["maxOccurs"] == "unbounded" or infos["maxOccurs"] > 1:
+ text = ""
+ for item in value["value"]:
+ text += infos["elmt_type"]["generate"](item, content_name, indent)
+ return text
+ else:
+ return infos["elmt_type"]["generate"](value["value"], content_name, indent)
+ return ""
+
+ return {
+ "initial" : GetContentInitial,
+ "check" : CheckContent,
+ "extract" : ExtractContent,
+ "generate" : GenerateContent
+ }
+
+#-------------------------------------------------------------------------------
+# Structure extraction functions
+#-------------------------------------------------------------------------------
+
+
+def DecomposeQualifiedName(name):
+ result = QName_model.match(name)
+ if not result:
+ raise ValueError, "\"%s\" isn't a valid QName value!"%name
+ parts = result.groups()[0].split(':')
+ if len(parts) == 1:
+ return None, parts[0]
+ return parts
+
+def GenerateElement(element_name, attributes, elements_model, accept_text = False):
+ def ExtractElement(factory, node):
+ attrs = factory.ExtractNodeAttrs(element_name, node, attributes)
+ children_structure = ""
+ children_infos = []
+ children = []
+ for child in node.childNodes:
+ if child.nodeName not in ["#comment", "#text"]:
+ namespace, childname = DecomposeQualifiedName(child.nodeName)
+ children_structure += "%s "%childname
+ result = elements_model.match(children_structure)
+ if not result:
+ raise ValueError, "Invalid structure for \"%s\" children!. First element invalid."%node.nodeName
+ valid = result.groups()[0]
+ if len(valid) < len(children_structure):
+ raise ValueError, "Invalid structure for \"%s\" children!. Element number %d invalid."%(node.nodeName, len(valid.split(" ")) - 1)
+ for child in node.childNodes:
+ if child.nodeName != "#comment" and (accept_text or child.nodeName != "#text"):
+ if child.nodeName == "#text":
+ children.append(GetAttributeValue(node))
+ else:
+ namespace, childname = DecomposeQualifiedName(child.nodeName)
+ infos = factory.GetQualifiedNameInfos(childname, namespace)
+ if infos["type"] != SYNTAXELEMENT:
+ raise ValueError, "\"%s\" can't be a member child!"%name
+ if element_name in infos["extract"]:
+ children.append(infos["extract"][element_name](factory, child))
+ else:
+ children.append(infos["extract"]["default"](factory, child))
+ return node.nodeName, attrs, children
+ return ExtractElement
+
+
+"""
+Class that generate class from an XML Tree
"""
class ClassFactory:
- def __init__(self, xsd_tree):
- self.XML_Tree = xsd_tree
+ def __init__(self, document, debug = False):
+ self.Document = document
+ self.Debug = debug
# Dictionary for stocking Classes and Types definitions created from the XML tree
self.XMLClassDefinitions = {}
+ self.DefinedNamespaces = {}
+ self.Namespaces = {}
+ self.SchemaNamespace = None
+ self.TargetNamespace = None
+
+ self.CurrentCompilations = []
+
# Dictionaries for stocking Classes and Types generated
+ self.ComputeAfter = []
self.ComputedClasses = {}
- self.ComputedTypes = {}
self.AlreadyComputed = {}
- """
- This function recursively creates a definition of the classes and their attributes
- for plcopen from the xsd file of plcopen opened in a DOM model
- """
- def GenerateXSDClasses(self, tree, parent, sequence = False):
- attributes = {}
- inheritance = []
- if sequence:
- order = []
- # The lists of attributes and inheritance of the node are generated from the childrens
- for node in tree.childNodes:
- # We make fun of #text elements and all other tags that don't are xsd tags
- if node.nodeName != "#text" and node.nodeName.startswith("xsd:"):
- recursion = False
- name = node.nodeName[4:].encode()
-
- # This tags defines an attribute of the class
- if name in ["element", "attribute"]:
- nodename = GetAttributeValue(node._attrs["name"])
- default = None
- if "type" in node._attrs:
- nodetype = GetAttributeValue(node._attrs["type"])
- if nodetype.startswith("xsd"):
- nodetype = nodetype.replace("xsd", "bse")
- elif nodetype.startswith("ppx"):
- nodetype = nodetype.replace("ppx", "cls")
+ def GetQualifiedNameInfos(self, name, namespace = None, canbenone = False):
+ if namespace is None:
+ if name in self.Namespaces[self.SchemaNamespace]:
+ return self.Namespaces[self.SchemaNamespace][name]
+ for space, elements in self.Namespaces.items():
+ if space != self.SchemaNamespace and name in elements:
+ return elements[name]
+ parts = name.split("_", 1)
+ if len(parts) > 1:
+ group = self.GetQualifiedNameInfos(parts[0], namespace)
+ if group is not None and group["type"] == ELEMENTSGROUP:
+ elements = []
+ if "elements" in group:
+ elements = group["elements"]
+ elif "choices" in group:
+ elements = group["choices"]
+ for element in elements:
+ if element["name"] == parts[1]:
+ return element
+ if not canbenone:
+ raise ValueError, "Unknown element \"%s\" for any defined namespaces!"%name
+ elif namespace in self.Namespaces:
+ if name in self.Namespaces[namespace]:
+ return self.Namespaces[namespace][name]
+ parts = name.split("_", 1)
+ if len(parts) > 1:
+ group = self.GetQualifiedNameInfos(parts[0], namespace)
+ if group is not None and group["type"] == ELEMENTSGROUP:
+ elements = []
+ if "elements" in group:
+ elements = group["elements"]
+ elif "choices" in group:
+ elements = group["choices"]
+ for element in elements:
+ if element["name"] == parts[1]:
+ return element
+ if not canbenone:
+ raise ValueError, "Unknown element \"%s\" for namespace \"%s\"!"%(name, namespace)
+ elif not canbenone:
+ raise ValueError, "Unknown namespace \"%s\"!"%namespace
+ return None
+
+ def SplitQualifiedName(self, name, namespace = None, canbenone = False):
+ if namespace is None:
+ if name in self.Namespaces[self.SchemaNamespace]:
+ return name, None
+ for space, elements in self.Namespaces.items():
+ if space != self.SchemaNamespace and name in elements:
+ return name, None
+ parts = name.split("_", 1)
+ if len(parts) > 1:
+ group = self.GetQualifiedNameInfos(parts[0], namespace)
+ if group is not None and group["type"] == ELEMENTSGROUP:
+ elements = []
+ if "elements" in group:
+ elements = group["elements"]
+ elif "choices" in group:
+ elements = group["choices"]
+ for element in elements:
+ if element["name"] == parts[1]:
+ return part[1], part[0]
+ if not canbenone:
+ raise ValueError, "Unknown element \"%s\" for any defined namespaces!"%name
+ elif namespace in self.Namespaces:
+ if name in self.Namespaces[namespace]:
+ return name, None
+ parts = name.split("_", 1)
+ if len(parts) > 1:
+ group = self.GetQualifiedNameInfos(parts[0], namespace)
+ if group is not None and group["type"] == ELEMENTSGROUP:
+ elements = []
+ if "elements" in group:
+ elements = group["elements"]
+ elif "choices" in group:
+ elements = group["choices"]
+ for element in elements:
+ if element["name"] == parts[1]:
+ return parts[1], parts[0]
+ if not canbenone:
+ raise ValueError, "Unknown element \"%s\" for namespace \"%s\"!"%(name, namespace)
+ elif not canbenone:
+ raise ValueError, "Unknown namespace \"%s\"!"%namespace
+ return None, None
+
+ def ExtractNodeAttrs(self, element_name, node, valid_attrs):
+ attrs = {}
+ for qualified_name, attr in node._attrs.items():
+ namespace, name = DecomposeQualifiedName(qualified_name)
+ if name in valid_attrs:
+ infos = self.GetQualifiedNameInfos(name, namespace)
+ if infos["type"] != SYNTAXATTRIBUTE:
+ raise ValueError, "\"%s\" can't be a member attribute!"%name
+ elif name in attrs:
+ raise ValueError, "\"%s\" attribute has been twice!"%name
+ elif element_name in infos["extract"]:
+ attrs[name] = infos["extract"][element_name](attr)
+ else:
+ attrs[name] = infos["extract"]["default"](attr)
+ elif namespace == "xmlns":
+ infos = self.GetQualifiedNameInfos("anyURI", self.SchemaNamespace)
+ self.DefinedNamespaces[infos["extract"](attr)] = name
+ else:
+ raise ValueError, "Invalid attribute \"%s\" for member \"%s\"!"%(qualified_name, node.nodeName)
+ for attr in valid_attrs:
+ if attr not in attrs and attr in self.Namespaces[self.SchemaNamespace] and "default" in self.Namespaces[self.SchemaNamespace][attr]:
+ if element_name in self.Namespaces[self.SchemaNamespace][attr]["default"]:
+ default = self.Namespaces[self.SchemaNamespace][attr]["default"][element_name]
+ else:
+ default = self.Namespaces[self.SchemaNamespace][attr]["default"]["default"]
+ if default is not None:
+ attrs[attr] = default
+ return attrs
+
+ def ReduceElements(self, elements, schema=False):
+ result = []
+ for child_infos in elements:
+ if "name" in child_infos[1] and schema:
+ self.CurrentCompilations.append(child_infos[1]["name"])
+ namespace, name = DecomposeQualifiedName(child_infos[0])
+ infos = self.GetQualifiedNameInfos(name, namespace)
+ if infos["type"] != SYNTAXELEMENT:
+ raise ValueError, "\"%s\" can't be a member child!"%name
+ result.append(infos["reduce"](self, child_infos[1], child_infos[2]))
+ if "name" in child_infos[1] and schema:
+ self.CurrentCompilations.pop(-1)
+ annotations = []
+ children = []
+ for element in result:
+ if element["type"] == "annotation":
+ annotations.append(element)
+ else:
+ children.append(element)
+ return annotations, children
+
+ def AddComplexType(self, typename, infos):
+ if typename not in self.XMLClassDefinitions:
+ self.XMLClassDefinitions[typename] = infos
+ else:
+ raise ValueError, "\"%s\" class already defined. Choose another name!"%typename
+
+ def ParseSchema(self):
+ pass
+
+ def ExtractTypeInfos(self, name, parent, typeinfos):
+ if isinstance(typeinfos, (StringType, UnicodeType)):
+ namespace, name = DecomposeQualifiedName(typeinfos)
+ infos = self.GetQualifiedNameInfos(name, namespace)
+ if infos["type"] == COMPLEXTYPE:
+ name, parent = self.SplitQualifiedName(name, namespace)
+ result = self.CreateClass(name, parent, infos)
+ if result is not None and not isinstance(result, (UnicodeType, StringType)):
+ self.Namespaces[self.TargetNamespace][result["name"]] = result
+ return result
+ elif infos["type"] == ELEMENT and infos["elmt_type"]["type"] == COMPLEXTYPE:
+ name, parent = self.SplitQualifiedName(name, namespace)
+ result = self.CreateClass(name, parent, infos["elmt_type"])
+ if result is not None and not isinstance(result, (UnicodeType, StringType)):
+ self.Namespaces[self.TargetNamespace][result["name"]] = result
+ return result
+ else:
+ return infos
+ elif typeinfos["type"] == COMPLEXTYPE:
+ return self.CreateClass(name, parent, typeinfos)
+ elif typeinfos["type"] == SIMPLETYPE:
+ return typeinfos
+
+ """
+ Methods that generates the classes
+ """
+ def CreateClasses(self):
+ self.ParseSchema()
+ for name, infos in self.Namespaces[self.TargetNamespace].items():
+ if infos["type"] == ELEMENT:
+ if not isinstance(infos["elmt_type"], (UnicodeType, StringType)) and infos["elmt_type"]["type"] == COMPLEXTYPE:
+ self.ComputeAfter.append((name, None, infos["elmt_type"], True))
+ while len(self.ComputeAfter) > 0:
+ result = self.CreateClass(*self.ComputeAfter.pop(0))
+ if result is not None and not isinstance(result, (UnicodeType, StringType)):
+ self.Namespaces[self.TargetNamespace][result["name"]] = result
+ elif infos["type"] == COMPLEXTYPE:
+ self.ComputeAfter.append((name, None, infos))
+ while len(self.ComputeAfter) > 0:
+ result = self.CreateClass(*self.ComputeAfter.pop(0))
+ if result is not None and not isinstance(result, (UnicodeType, StringType)):
+ self.Namespaces[self.TargetNamespace][result["name"]] = result
+ elif infos["type"] == ELEMENTSGROUP:
+ elements = []
+ if "elements" in infos:
+ elements = infos["elements"]
+ elif "choices" in infos:
+ elements = infos["choices"]
+ for element in elements:
+ if not isinstance(element["elmt_type"], (UnicodeType, StringType)) and element["elmt_type"]["type"] == COMPLEXTYPE:
+ self.ComputeAfter.append((element["name"], infos["name"], element["elmt_type"]))
+ while len(self.ComputeAfter) > 0:
+ result = self.CreateClass(*self.ComputeAfter.pop(0))
+ if result is not None and not isinstance(result, (UnicodeType, StringType)):
+ self.Namespaces[self.TargetNamespace][result["name"]] = result
+ return self.ComputedClasses
+
+ def CreateClass(self, name, parent, classinfos, baseclass = False):
+ if parent is not None:
+ classname = "%s_%s"%(parent, name)
+ else:
+ classname = name
+
+ # Checks that classe haven't been generated yet
+ if self.AlreadyComputed.get(classname, False):
+ if baseclass:
+ self.AlreadyComputed[classname].IsBaseClass = baseclass
+ return None
+
+ # If base classes haven't been generated
+ bases = []
+ if "base" in classinfos:
+ result = self.ExtractTypeInfos("base", name, classinfos["base"])
+ if result is None:
+ namespace, base_name = DecomposeQualifiedName(classinfos["base"])
+ if self.AlreadyComputed.get(base_name, False):
+ self.ComputeAfter.append((name, parent, classinfos))
+ if self.TargetNamespace is not None:
+ return "%s:%s"%(self.TargetNamespace, classname)
else:
- # The type of attribute is defines in the child tree so we generate a new class
- # No name is defined so we create one from nodename and parent class name
- # (because some different nodes can have the same name)
- if parent:
- classname = "%s_%s"%(parent, nodename)
- else:
- classname = nodename
- if len(node.childNodes) > 0:
- self.GenerateXSDClasses(node, classname)
- nodetype = "cls:%s"%classname
- else:
- nodetype = classname
- if name == "attribute":
- if "use" in node._attrs:
- use = GetAttributeValue(node._attrs["use"])
- else:
- use = "optional"
- if "default" in node._attrs:
- default = GetAttributeValue(node._attrs["default"])
- elif name == "element":
- # If a tag can be written more than one time we define a list attribute
- if "maxOccurs" in node._attrs and GetAttributeValue(node._attrs["maxOccurs"]) == "unbounded":
- nodetype = "%s[]"%nodetype
- if "minOccurs" in node._attrs and GetAttributeValue(node._attrs["minOccurs"]) == "0":
- use = "optional"
- else:
- use = "required"
- attributes[nodename] = (nodetype, name, use, default)
- if sequence:
- order.append(nodename)
-
- # This tag defines a new class
- elif name == "complexType" or name == "simpleType":
- if "name" in node._attrs:
- classname = GetAttributeValue(node._attrs["name"])
- super, attrs = self.GenerateXSDClasses(node, classname)
+ return classname
+ elif result is not None:
+ classinfos["base"] = self.ComputedClasses[result["name"]]
+ bases.append(self.ComputedClasses[result["name"]])
+ bases.append(object)
+ bases = tuple(bases)
+ classmembers = {"__doc__" : classinfos.get("doc", ""), "IsBaseClass" : baseclass}
+
+ self.AlreadyComputed[classname] = True
+
+ for attribute in classinfos["attributes"]:
+ infos = self.ExtractTypeInfos(attribute["name"], name, attribute["attr_type"])
+ if infos is not None:
+ if infos["type"] != SIMPLETYPE:
+ raise ValueError, "\"%s\" type is not a simple type!"%attribute["attr_type"]
+ attrname = attribute["name"]
+ if attribute["use"] == "optional":
+ classmembers[attrname] = None
+ classmembers["add%s"%attrname] = generateAddMethod(attrname, self, attribute)
+ classmembers["delete%s"%attrname] = generateDeleteMethod(attrname)
+ else:
+ classmembers[attrname] = infos["initial"]()
+ classmembers["set%s"%attrname] = generateSetMethod(attrname)
+ classmembers["get%s"%attrname] = generateGetMethod(attrname)
+ else:
+ raise ValueError, "\"%s\" type unrecognized!"%attribute["attr_type"]
+ attribute["attr_type"] = infos
+
+ for element in classinfos["elements"]:
+ if element["type"] == CHOICE:
+ elmtname = element["name"]
+ choices = []
+ for choice in element["choices"]:
+ if choice["elmt_type"] == "tag":
+ choice["elmt_type"] = GenerateTagInfos(choice["name"])
else:
- classname = parent
- super, attrs = self.GenerateXSDClasses(node, classname.split("_")[-1])
- # When all attributes and inheritances have been extracted, the
- # values are added in the list of classes to create
- if self.XMLClassDefinitions.get(classname, None) == None:
- self.XMLClassDefinitions[classname] = (super, attrs)
- elif self.XMLClassDefinitions[classname] != (super, attrs):
- print "A different class has already got %s for name"%classname
-
- # This tag defines an attribute that can have different types
- elif name == "choice":
- super, attrs = self.GenerateXSDClasses(node, parent)
-
- choices = {}
- for attr, values in attrs.items():
- if attr == "ref":
- choices[attr] = values
- else:
- choices[attr] = values[0]
- if "maxOccurs" in node._attrs and GetAttributeValue(node._attrs["maxOccurs"]) == "unbounded":
- attributes["multichoice_content"] = choices
- if sequence:
- order.append("multichoice_content")
- else:
- attributes["choice_content"] = choices
- if sequence:
- order.append("choice_content")
-
- # This tag defines the order in which class attributes must be written
- # in plcopen xml file. We have to store this order like an attribute
- elif name in "sequence":
- super, attrs, order = self.GenerateXSDClasses(node, parent, True)
- if "maxOccurs" in node._attrs and GetAttributeValue(node._attrs["maxOccurs"]) == "unbounded":
- for attr, (attr_type, xml_type, write_type, default) in attrs.items():
- attrs[attr] = ("%s[]"%attr_type, xml_type, write_type, default)
- if "minOccurs" in node._attrs and GetAttributeValue(node._attrs["minOccurs"]) == "0":
- for attr, (attr_type, xml_type, write_type, default) in attrs.items():
- attrs[attr] = (attr_type, xml_type, "optional", default)
- inheritance.extend(super)
- attributes.update(attrs)
- attributes["order"] = order
-
- # This tag defines of types
- elif name == "group":
- if "name" in node._attrs:
- nodename = GetAttributeValue(node._attrs["name"])
- super, attrs = self.GenerateXSDClasses(node, None)
- self.XMLClassDefinitions[nodename] = (super, {"group":attrs["choice_content"]})
- elif "ref" in node._attrs:
- if "ref" not in attributes:
- attributes["ref"] = [GetAttributeValue(node._attrs["ref"])]
- else:
- attributes["ref"].append(GetAttributeValue(node._attrs["ref"]))
-
- # This tag define a base class for the node
- elif name == "extension":
- super = GetAttributeValue(node._attrs["base"])
- if super.startswith("xsd"):
- super = super.replace("xsd", "bse")
- elif super.startswith("ppx"):
- super = super.replace("ppx", "cls")
- inheritance.append(super[4:])
- recursion = True
-
- # This tag defines a restriction on the type of attribute
- elif name == "restriction":
- basetype = GetAttributeValue(node._attrs["base"])
- if basetype.startswith("xsd"):
- basetype = basetype.replace("xsd", "bse")
- elif basetype.startswith("ppx"):
- basetype = basetype.replace("ppx", "cls")
- attributes["basetype"] = basetype
- recursion = True
-
- # This tag defines an enumerated type
- elif name == "enumeration":
- if "enum" not in attributes:
- attributes["enum"] = [GetAttributeValue(node._attrs["value"])]
- else:
- attributes["enum"].append(GetAttributeValue(node._attrs["value"]))
-
- # This tags defines a restriction on a numerical value
- elif name in ["minInclusive","maxInclusive"]:
- if "limit" not in attributes:
- attributes["limit"] = {}
- if name == "minInclusive":
- attributes["limit"]["min"] = eval(GetAttributeValue(node._attrs["value"]))
- elif name == "maxInclusive":
- attributes["limit"]["max"] = eval(GetAttributeValue(node._attrs["value"]))
-
- # This tag are not important but their childrens are. The childrens are then parsed.
- elif name in ["complexContent", "schema"]:
- recursion = True
-
- # We make fun of xsd documentation
- elif name in ["annotation"]:
- pass
-
- else:
- # Unable this line to print XSD element that is not yet supported
- #print name
- self.GenerateXSDClasses(node, parent)
-
- # Parse the childrens of node
- if recursion:
- super, attrs = self.GenerateXSDClasses(node, parent)
- inheritance.extend(super)
- attributes.update(attrs)
-
- # if sequence tag have been found, order is returned
- if sequence:
- return inheritance, attributes, order
- else:
- return inheritance, attributes
-
- """
- Funtion that returns the Python type and default value for a given type
- """
- def GetTypeInitialValue(self, attr_type, default = None):
- type_compute = attr_type[4:].replace("[]", "")
- if attr_type.startswith("bse:"):
- if type_compute == "boolean":
- if default:
- def GetBooleanInitialValue():
- return default == "true"
- return BooleanType, GetBooleanInitialValue
- else:
- return BooleanType, lambda:False
- elif type_compute in ["unsignedLong","long","integer"]:
- if default:
- def GetIntegerInitialValue():
- return int(default)
- return IntType, GetIntegerInitialValue
- else:
- return IntType, lambda:0
- elif type_compute == "decimal":
- if default:
- def GetFloatInitialValue():
- return float(default)
- return FloatType, GetFloatInitialValue
- else:
- return FloatType, lambda:0.
- elif type_compute in ["string","anyURI","NMTOKEN"]:
- if default:
- def GetStringInitialValue():
- return default
- return StringType, GetStringInitialValue
- else:
- return StringType, lambda:""
- elif type_compute == "time":
- if default:
- def GetTimeInitialValue():
- result = time_model.match(value)
- if result:
- 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)])
- return time(*time_values)
- return time(0,0,0,0)
- return time, GetTimeInitialValue
- else:
- return time, lambda:time(0,0,0,0)
- elif type_compute == "date":
- if default:
- def GetDateInitialValue():
- result = date_model.match(value)
- if result:
- date_values = [int(v) for v in result.groups()]
- return date(*date_values)
- return date(1,1,1)
- return date, GetDateInitialValue
- else:
- return date, lambda:date(1,1,1)
- elif type_compute == "dateTime":
- if default:
- def GetDateTimeInitialValue():
- result = datetime_model.match(value)
- if result:
- values = result.groups()
- datetime_values = [int(v) for v in values[:5]]
- seconds = float(values[5])
- datetime_values.extend([int(seconds), int((seconds % 1) * 1000000)])
- return datetime(*datetime_values)
- return datetime(1,1,1,0,0,0,0)
- return datetime, GetDateTimeInitialValue
- else:
- return datetime, lambda:datetime(1,1,1,0,0,0,0)
- elif type_compute == "language":
- if default:
- def GetStringInitialValue():
- return default
- return StringType, GetStringInitialValue
- else:
- return StringType, lambda:"en-US"
- else:
- print "Can't affect: %s"%type_compute
- elif attr_type.startswith("cls:"):
- if self.XMLClassDefinitions.get(type_compute, None) != None:
- def GetClassInitialValue():
- if self.XMLClassDefinitions.get(type_compute, None) != None:
- obj = self.ComputedClasses[type_compute]()
- if default:
- obj.setValue(default)
- return obj
- return None
- return self.XMLClassDefinitions[type_compute], GetClassInitialValue
- return None, lambda:None
-
- """
- Funtion that returns the Python type and default value for a given type
- """
- def GetInitialValues(self, value_types):
- initial_values = {}
- for name, value_type in value_types.items():
- result = self.GetTypeInitialValue(value_type)
- if result:
- initial_values[name] = result[1]
- return initial_values
-
- """
- Methods that generate the classes
- """
- def CreateClasses(self):
- self.GenerateXSDClasses(self.XML_Tree, None)
- for classname in self.XMLClassDefinitions.keys():
- self.CreateClass(classname)
- for classname in self.XMLClassDefinitions.keys():
- self.MarkUsedClasses(classname)
- return self.ComputedClasses, self.ComputedTypes
-
- def CreateClass(self, classname):
- # Checks that classe haven't been generated yet
- if not self.AlreadyComputed.get(classname, False) and classname in self.XMLClassDefinitions:
- self.AlreadyComputed[classname] = True
- inheritance, attributes = self.XMLClassDefinitions[classname]
- #print classname, inheritance, attributes
- members = {}
- bases = []
+ infos = self.ExtractTypeInfos(choice["name"], name, choice["elmt_type"])
+ if infos is not None:
+ choice["elmt_type"] = infos
+ choices.append((choice["name"], choice))
+ classmembers["get%schoices"%elmtname] = generateGetChoicesMethod(element["choices"])
+ classmembers["add%sbytype"%elmtname] = generateAddChoiceByTypeMethod(element["choices"])
+ infos = GenerateContentInfos(self, choices)
+ elif element["type"] == ANY:
+ elmtname = element["name"] = "text"
+ element["minOccurs"] = element["maxOccurs"] = 1
+ infos = GenerateAnyInfos()
+ else:
+ elmtname = element["name"]
+ infos = self.ExtractTypeInfos(element["name"], name, element["elmt_type"])
+ if infos is not None:
+ element["elmt_type"] = infos
+ if element["maxOccurs"] == "unbounded" or element["maxOccurs"] > 1:
+ classmembers[elmtname] = []
+ classmembers["append%s"%elmtname] = generateAppendMethod(elmtname, element["maxOccurs"], self, element)
+ classmembers["insert%s"%elmtname] = generateInsertMethod(elmtname, element["maxOccurs"], self, element)
+ classmembers["remove%s"%elmtname] = generateRemoveMethod(elmtname, element["minOccurs"])
+ classmembers["count%s"%elmtname] = generateCountMethod(elmtname)
+ else:
+ if element["minOccurs"] == 0:
+ classmembers[elmtname] = None
+ classmembers["add%s"%elmtname] = generateAddMethod(elmtname, self, element)
+ classmembers["delete%s"%elmtname] = generateDeleteMethod(elmtname)
+ elif not isinstance(element["elmt_type"], (UnicodeType, StringType)):
+ classmembers[elmtname] = element["elmt_type"]["initial"]()
+ else:
+ classmembers[elmtname] = None
+ classmembers["set%s"%elmtname] = generateSetMethod(elmtname)
+ classmembers["get%s"%elmtname] = generateGetMethod(elmtname)
- # If inheritance classes haven't been generated
- for base in inheritance:
- self.CreateClass(base)
- bases.append(self.ComputedClasses[base])
-
- # Checks that all attribute types are available
- for attribute, type_attribute in attributes.items():
- if attribute == "group":
- self.ComputedTypes[classname] = type_attribute
- elif attribute in ["choice_content","multichoice_content"]:
- element_types = {}
- for attr, value in type_attribute.items():
- if attr == "ref":
- for ref in value:
- self.CreateClass(ref[4:])
- element_types.update(self.ComputedTypes[ref[4:]])
- else:
- element_types[attr] = value
- members[attribute] = element_types
- else:
- members[attribute] = type_attribute
- if attribute == "enum":
- self.ComputedTypes["%s_enum"%classname] = type_attribute
- elif attribute not in ["limit", "order"]:
- if type_attribute[0].startswith("cls:"):
- type_compute = type_attribute[0][4:].replace("[]","")
- self.CreateClass(type_compute)
- if "group" not in attributes:
- bases = tuple(bases)
- classmembers = {"IsBaseClass" : True}
- initialValues = {}
- for attr, values in members.items():
- if attr in ["order", "basetype"]:
- pass
-
- # Class is a enumerated type
- elif attr == "enum":
- value_type, initial = self.GetTypeInitialValue(members["basetype"])
- initialValues["value"] = GetInitialValueFunction(values[0])
- classmembers["value"] = values[0]
- classmembers["setValue"] = generateSetEnumMethod(values, value_type)
- classmembers["getValue"] = generateGetMethod("value")
- classmembers["getValidValues"] = generateGetChoicesMethod(values)
-
- # Class is a limited type
- elif attr == "limit":
- value_type, initial = self.GetTypeInitialValue(members["basetype"])
- if "min" in values:
- initial = max(initial, values["min"])
- elif "max" in values:
- initial = min(initial, values["max"])
- initialValues["value"] = GetInitialValueFunction(initial)
- classmembers["value"] = initial
- classmembers["setValue"] = generateSetLimitMethod(values, value_type)
- classmembers["getValue"] = generateGetMethod("value")
-
- # Class has an attribute that can have different value types
- elif attr == "choice_content":
- classmembers["content"] = None
- initialValues["content"] = lambda:None
- classmembers["deleteContent"] = generateDeleteMethod("content")
- classmembers["addContent"] = generateAddChoiceMethod(values, self.GetInitialValues(values))
- classmembers["setContent"] = generateSetChoiceMethod(values)
- classmembers["getContent"] = generateGetMethod("content")
- classmembers["getChoices"] = generateGetChoicesMethod(values)
- elif attr == "multichoice_content":
- classmembers["content"] = []
- initialValues["content"] = lambda:[]
- classmembers["appendContent"] = generateAppendChoiceMethod(values)
- classmembers["appendContentByType"] = generateAppendChoiceByTypeMethod(values, self.GetInitialValues(values))
- classmembers["insertContent"] = generateInsertChoiceMethod(values)
- classmembers["removeContent"] = generateRemoveMethod("content")
- classmembers["countContent"] = generateCountMethod("content")
- classmembers["setContent"] = generateSetMethod("content", ListType)
- classmembers["getContent"] = generateGetMethod("content")
- classmembers["getChoices"] = generateGetChoicesMethod(values)
-
- # It's an attribute of the class
- else:
- attrname = attr[0].upper()+attr[1:]
- attr_type, xml_type, write_type, default = values
- value_type, initial = self.GetTypeInitialValue(attr_type, default)
- # Value of the attribute is a list
- if attr_type.endswith("[]"):
- classmembers[attr] = []
- initialValues[attr] = lambda:[]
- classmembers["append"+attrname] = generateAppendMethod(attr, value_type)
- classmembers["insert"+attrname] = generateInsertMethod(attr, value_type)
- classmembers["remove"+attrname] = generateRemoveMethod(attr)
- classmembers["count"+attrname] = generateCountMethod(attr)
- classmembers["set"+attrname] = generateSetMethod(attr, ListType)
- else:
- if write_type == "optional":
- classmembers[attr] = None
- initialValues[attr] = lambda:None
- classmembers["add"+attrname] = generateAddMethod(attr, initial)
- classmembers["delete"+attrname] = generateDeleteMethod(attr)
- else:
- classmembers[attr] = initial()
- initialValues[attr] = initial
- classmembers["set"+attrname] = generateSetMethod(attr, value_type)
- classmembers["get"+attrname] = generateGetMethod(attr)
- classmembers["__init__"] = generateInitMethod(bases, initialValues)
- classmembers["loadXMLTree"] = generateLoadXMLTree(bases, members, self.ComputedClasses)
- classmembers["generateXMLText"] = generateGenerateXMLText(bases, members)
- classmembers["getElementAttributes"] = generateGetElementAttributes(members, self.ComputedClasses)
- classmembers["getElementInfos"] = generateGetElementInfos(members, self.ComputedClasses)
- classmembers["setElementValue"] = generateSetElementValue(members)
- classmembers["singleLineAttributes"] = True
-
- self.ComputedClasses[classname] = classobj(classname, bases, classmembers)
+ classmembers["__init__"] = generateInitMethod(self, classinfos)
+ classmembers["__setattr__"] = generateSetattrMethod(self, classinfos)
+ classmembers["getStructure"] = generateStructureMethod(classinfos)
+ classmembers["loadXMLTree"] = generateLoadXMLTree(self, classinfos)
+ classmembers["generateXMLText"] = generateGenerateXMLText(self, classinfos)
+ classmembers["getElementAttributes"] = generateGetElementAttributes(self, classinfos)
+ classmembers["getElementInfos"] = generateGetElementInfos(self, classinfos)
+ classmembers["setElementValue"] = generateSetElementValue(self, classinfos)
+ classmembers["singleLineAttributes"] = True
+
+ class_definition = classobj(str(classname), bases, classmembers)
+
+ self.ComputedClasses[classname] = class_definition
+
+ return {"type" : COMPILEDCOMPLEXTYPE,
+ "name" : classname,
+ "check" : generateClassCheckFunction(class_definition),
+ "initial" : generateClassCreateFunction(class_definition),
+ "extract" : generateClassExtractFunction(class_definition),
+ "generate" : class_definition.generateXMLText}
def MarkUsedClasses(self, classname):
# Checks that classe haven't been generated yet
@@ -629,7 +1017,9 @@
Methods that print the classes generated
"""
def PrintClasses(self):
- for classname, xmlclass in self.ComputedClasses.items():
+ items = self.ComputedClasses.items()
+ items.sort()
+ for classname, xmlclass in items:
print "%s : %s"%(classname, str(xmlclass))
def PrintClassNames(self):
@@ -639,211 +1029,268 @@
print classname
"""
+Method that generate the method for checking a class instance
+"""
+def generateClassCheckFunction(class_definition):
+ def classCheckfunction(instance):
+ return isinstance(instance, class_definition)
+ return classCheckfunction
+
+"""
+Method that generate the method for creating a class instance
+"""
+def generateClassCreateFunction(class_definition):
+ def classCreatefunction():
+ return class_definition()
+ return classCreatefunction
+
+"""
+Method that generate the method for extracting a class instance
+"""
+def generateClassExtractFunction(class_definition):
+ def classExtractfunction(node):
+ instance = class_definition()
+ instance.loadXMLTree(node)
+ return instance
+ return classExtractfunction
+
+"""
Method that generate the method for loading an xml tree by following the
attributes list defined
"""
-def generateLoadXMLTree(bases, members, classes):
- def loadXMLTreeMethod(self, tree):
- # If class is derived, values of inheritance classes are loaded
- for base in bases:
- base.loadXMLTree(self, tree)
- # Class is a enumerated or limited value
- if "enum" in members.keys() or "limit" in members.keys():
- attr_value = GetAttributeValue(tree)
- attr_type = members["basetype"]
- val = GetComputedValue(attr_type, attr_value)
- self.setValue(val)
- else:
-
- # Load the node attributes if they are defined in the list
- for attrname, attr in tree._attrs.items():
- if attrname in members.keys():
- attr_type, xml_type, write_type, default = members[attrname]
- attr_value = GetAttributeValue(attr)
- if write_type != "optional" or attr_value != "":
- # Extracts the value
- if attr_type.startswith("bse:"):
- val = GetComputedValue(attr_type, attr_value)
- elif attr_type.startswith("cls:"):
- val = classes[attr_type[4:]]()
- val.loadXMLTree(attr)
- setattr(self, attrname, val)
-
- # Load the node childs if they are defined in the list
+def generateSetattrMethod(factory, classinfos):
+ attributes = dict([(attr["name"], attr) for attr in classinfos["attributes"] if attr["use"] != "prohibited"])
+ optional_attributes = [attr["name"] 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 name in attributes:
+ if isinstance(attributes[name]["attr_type"], (UnicodeType, StringType)):
+ namespace, name = DecomposeQualifiedName(infos)
+ attributes[name]["attr_type"] = factory.GetQualifiedNameInfos(name, namespace)
+ if value is None:
+ if name in optional_attributes:
+ return object.__setattr__(self, name, None)
+ else:
+ raise ValueError, "Attribute '%s' isn't optional."%name
+ elif "fixed" in attributes[name] and value != attributes[name]["fixed"]:
+ raise ValueError, "Value of attribute '%s' can only be '%s'."%(name, str(attributes[name]["fixed"]))
+ elif attributes[name]["attr_type"]["check"](value):
+ return object.__setattr__(self, name, value)
+ else:
+ raise ValueError, "Invalid value for attribute '%s'."%(name)
+ elif name in elements:
+ if isinstance(elements[name]["elmt_type"], (UnicodeType, StringType)):
+ namespace, name = DecomposeQualifiedName(infos)
+ elements[name]["elmt_type"] = factory.GetQualifiedNameInfos(name, namespace)
+ if value is None:
+ if elements[name]["minOccurs"] == 0 and elements[name]["maxOccurs"] == 1:
+ return object.__setattr__(self, name, None)
+ else:
+ raise ValueError, "Attribute '%s' isn't optional."%name
+ elif elements[name]["maxOccurs"] == "unbounded" or elements[name]["maxOccurs"] > 1:
+ if isinstance(value, ListType) and elements[name]["minOccurs"] <= len(value) <= elements[name]["maxOccurs"]:
+ if reduce(lambda x, y: x and y, map(elements[name]["elmt_type"]["check"], value), True):
+ return object.__setattr__(self, name, value)
+ raise ValueError, "Attribute '%s' must be a list of valid elements."%name
+ elif "fixed" in elements[name] and value != elements[name]["fixed"]:
+ raise ValueError, "Value of attribute '%s' can only be '%s'."%(name, str(elements[name]["fixed"]))
+ elif elements[name]["elmt_type"]["check"](value):
+ return object.__setattr__(self, name, value)
+ else:
+ raise ValueError, "Invalid value for attribute '%s'."%(name)
+ elif "base" in classinfos:
+ return classinfos["base"].__setattr__(self, name, value)
+ else:
+ raise AttributeError, "'%s' can't have an attribute '%s'."%(classinfos["name"], name)
+
+ return setattrMethod
+
+"""
+Method that generate the method for generating the xml tree structure model by
+following the attributes list defined
+"""
+def ComputeMultiplicity(name, infos):
+ if infos["minOccurs"] == 0:
+ if infos["maxOccurs"] == "unbounded":
+ return "(?:%s)*"%name
+ elif infos["maxOccurs"] == 1:
+ return "(?:%s)?"%name
+ else:
+ return "(?:%s){0, %d}"%(name, infos["maxOccurs"])
+ elif infos["minOccurs"] == 1:
+ if infos["maxOccurs"] == "unbounded":
+ return "(?:%s)+"%name
+ elif infos["maxOccurs"] == 1:
+ return name
+ else:
+ return "(?:%s){1, %d}"%(name, infos["maxOccurs"])
+ else:
+ if infos["maxOccurs"] == "unbounded":
+ return "(?:%s){%d}(?:%s )*"%(name, infos["minOccurs"], name)
+ else:
+ return "(?:%s){%d, %d}"%(name, infos["minOccurs"], infos["maxOccurs"])
+
+def generateStructureMethod(classinfos):
+ elements = []
+ for element in classinfos["elements"]:
+ if element["type"] == ANY:
+ elements.append(ComputeMultiplicity("(?:#cdata-section )?", element))
+ elif element["type"] == CHOICE:
+ elements.append(ComputeMultiplicity(
+ "|".join([ComputeMultiplicity("%s "%infos["name"], infos) for infos in element["choices"]]),
+ element))
+ else:
+ elements.append(ComputeMultiplicity("%s "%element["name"], element))
+ if classinfos.get("order") or len(elements) == 0:
+ structure = "".join(elements)
+ else:
+ raise ValueError, "XSD structure not yet supported!"
+
+ def getStructureMethod(self):
+ if "base" in classinfos:
+ return classinfos["base"].getStructure(self) + structure
+ return structure
+ return getStructureMethod
+
+"""
+Method that generate the method for loading an xml tree by following the
+attributes list defined
+"""
+def generateLoadXMLTree(factory, classinfos):
+ attributes = dict([(attr["name"], attr) for attr in classinfos["attributes"] if attr["use"] != "prohibited"])
+ elements = dict([(element["name"], element) for element in classinfos["elements"]])
+
+ def loadXMLTreeMethod(self, tree, extras = [], derived = False):
+ if not derived:
+ children_structure = ""
for node in tree.childNodes:
- if node.nodeType == node.COMMENT_NODE:
- continue
- name = node.nodeName
- # We make fun of #text elements
- if name != "#text":
-
- # Class has an attribute that can have different value types
- if "choice_content" in members.keys() and name in members["choice_content"].keys():
- attr_type = members["choice_content"][name]
- # Extracts the value
- if attr_type.startswith("bse:"):
- val = GetComputedValue(attr_type.replace("[]",""), GetAttributeValue(node))
- elif attr_type.startswith("cls:"):
- val = classes[attr_type[4:].replace("[]","")]()
- val.loadXMLTree(node)
- else:
- val = None
- # Stock value in content attribute
- if val is not None:
- if attr_type.endswith("[]"):
- if self.content:
- self.content["value"].append(val)
- else:
- self.content = {"name":name,"value":[val]}
- else:
- self.content = {"name":name,"value":val}
- else:
- self.content = {"name":name,"value":None}
-
- # Class has a list of attributes that can have different value types
- elif "multichoice_content" in members.keys() and name in members["multichoice_content"].keys():
- attr_type = members["multichoice_content"][name]
- # Extracts the value
- if attr_type.startswith("bse:"):
- val = GetComputedValue(attr_type, GetAttributeValue(node))
- elif attr_type.startswith("cls:"):
- val = classes[attr_type[4:]]()
- val.loadXMLTree(node)
- # Add to content attribute list
- if val:
- self.content.append({"name":name,"value":val})
-
- # The node child is defined in the list
- elif name in members.keys():
- attr_type, xml_type, write_type, default = members[name]
- # Extracts the value
- if attr_type.startswith("bse:"):
- attr_value = GetAttributeValue(node)
- if write_type != "optional" or attr_value != "":
- val = GetComputedValue(attr_type.replace("[]",""), attr_value)
- else:
- val = None
- elif attr_type.startswith("cls:"):
- val = classes[attr_type[4:].replace("[]","")]()
- val.loadXMLTree(node)
- # Stock value in attribute
- if val:
- if attr_type.endswith("[]"):
- getattr(self, name).append(val)
- else:
- setattr(self, name, val)
+ if node.nodeName not in ["#comment", "#text"]:
+ children_structure += "%s "%node.nodeName
+ structure_model = re.compile("(%s)$"%self.getStructure())
+ result = structure_model.match(children_structure)
+ if not result:
+ raise ValueError, "Invalid structure for \"%s\" children!."%tree.nodeName
+ required_attributes = [attr["name"] for attr in classinfos["attributes"] if attr["use"] == "required"]
+ if "base" in classinfos:
+ 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.items():
+ if attrname in attributes:
+ if isinstance(attributes[attrname]["attr_type"], (UnicodeType, StringType)):
+ namespace, name = DecomposeQualifiedName(infos)
+ attributes[attrname]["attr_type"] = factory.GetQualifiedNameInfos(name, namespace)
+ setattr(self, attrname, attributes[attrname]["attr_type"]["extract"](attr))
+ elif "base" not in classinfos and attrname not in extras:
+ raise ValueError, "Invalid attribute \"%s\" for \"%s\" element!"%(attrname, tree.nodeName)
+ if attrname in required_attributes:
+ required_attributes.remove(attrname)
+ if len(required_attributes) > 0:
+ raise ValueError, "Required attributes %s missing for \"%s\" element!"%(", ".join(["\"%s\""%name for name in required_attributes]), tree.nodeName)
+ first = {}
+ for node in tree.childNodes:
+ name = node.nodeName
+ if name in ["#text", "#comment"]:
+ continue
+ if name in elements:
+ if isinstance(elements[name]["elmt_type"], (UnicodeType, StringType)):
+ namespace, name = DecomposeQualifiedName(infos)
+ elements[name]["elmt_type"] = factory.GetQualifiedNameInfos(name, namespace)
+ if elements[name]["maxOccurs"] == "unbounded" or elements[name]["maxOccurs"] > 1:
+ if first.get(name, True):
+ setattr(self, name, [elements[name]["elmt_type"]["extract"](node)])
+ first[name] = False
+ else:
+ getattr(self, name).append(elements[name]["elmt_type"]["extract"](node))
+ else:
+ setattr(self, name, elements[name]["elmt_type"]["extract"](node))
+ elif name == "#cdata-section" and "text" in elements:
+ if elements["text"]["maxOccurs"] == "unbounded" or elements["text"]["maxOccurs"] > 1:
+ if first.get("text", True):
+ setattr(self, "text", [elements["text"]["elmt_type"]["extract"](node)])
+ first["text"] = False
+ else:
+ getattr(self, "text").append(elements["text"]["elmt_type"]["extract"](node))
+ else:
+ setattr(self, "text", elements["text"]["elmt_type"]["extract"](node))
+ elif "content" in elements:
+ content = getattr(self, "content")
+ if elements["content"]["maxOccurs"] == "unbounded" or elements["content"]["maxOccurs"] > 1:
+ if first.get("content", True):
+ setattr(self, "content", [elements["content"]["elmt_type"]["extract"](node, None)])
+ first["content"] = False
+ else:
+ content.append(elements["content"]["elmt_type"]["extract"](node, content))
+ else:
+ setattr(self, "content", elements["content"]["elmt_type"]["extract"](node, content))
return loadXMLTreeMethod
+
"""
Method that generates the method for generating an xml text by following the
attributes list defined
"""
-def generateGenerateXMLText(bases, members):
- def generateXMLTextMethod(self, name, indent, extras = {}, derived = False):
+def generateGenerateXMLText(factory, classinfos):
+ def generateXMLTextMethod(self, name, indent = 0, extras = {}, derived = False):
ind1, ind2 = getIndent(indent, name)
if not derived:
text = ind1 + "<%s"%name
else:
text = ""
- if len(bases) > 0:
- base_extras = {}
- if "order" in members.keys():
- order = members["order"]
- else:
- order = []
- for attr, values in members.items():
- if attr != "order" and (attr in ("choice_content", "multichoice_content") or values[1] != "attribute"):
- if attr not in order:
- order.append(attr)
- size = 0
+
first = True
- for attr, value in extras.items():
- if not first and not self.singleLineAttributes:
- text += "\n%s"%(ind2)
- text += " %s=\"%s\""%(attr, ComputeValue(value))
- first = False
- for attr, values in members.items():
- if attr in ["order","choice_content","multichoice_content"]:
- pass
- elif attr in ["enum","limit"]:
- if not derived:
- text += ">%s</%s>\n"%(ComputeValue(self.value),name)
- else:
- text += ComputeValue(self.value)
- return text
- elif values[1] == "attribute":
- value = getattr(self, attr, None)
+ if "base" not in classinfos:
+ for attr, value in extras.items():
+ if not first and not self.singleLineAttributes:
+ text += "\n%s"%(ind2)
+ text += " %s=\"%s\""%(attr, value)
+ first = False
+ extras.clear()
+ for attr in classinfos["attributes"]:
+ if attr["use"] != "prohibited":
+ if isinstance(attr["attr_type"], (UnicodeType, StringType)):
+ namespace, name = DecomposeQualifiedName(infos)
+ attr["attr_type"] = factory.GetQualifiedNameInfos(name, namespace)
+ value = getattr(self, attr["name"], None)
if value != None:
- if values[0].startswith("cls"):
- value = value.getValue()
- computed_value = ComputeValue(value)
+ computed_value = attr["attr_type"]["generate"](value)
else:
computed_value = None
- if values[2] != "optional" or (value != None and computed_value != values[3]):
- if len(bases) > 0:
- base_extras[attr] = value
+ if attr["use"] != "optional" or (value != None and computed_value != attr.get("default", attr["attr_type"]["generate"](attr["attr_type"]["initial"]()))):
+ if "base" in classinfos:
+ extras[attr["name"]] = computed_value
else:
if not first and not self.singleLineAttributes:
text += "\n%s"%(ind2)
- text += " %s=\"%s\""%(attr, computed_value)
+ text += " %s=\"%s\""%(attr["name"], computed_value)
first = False
- if len(bases) > 0:
- first, new_text = bases[0].generateXMLText(self, name, indent, base_extras, True)
+ if "base" in classinfos:
+ first, new_text = classinfos["base"].generateXMLText(self, name, indent, extras, True)
text += new_text
else:
first = True
- ind3, ind4 = getIndent(indent + 1, name)
- for attr in order:
- value = getattr(self, attr, None)
- if attr == "choice_content":
- if self.content:
+ for element in classinfos["elements"]:
+ if isinstance(element["elmt_type"], (UnicodeType, StringType)):
+ namespace, name = DecomposeQualifiedName(infos)
+ element["elmt_type"] = factory.GetQualifiedNameInfos(name, namespace)
+ value = getattr(self, element["name"], None)
+ if element["minOccurs"] == 0 and element["maxOccurs"] == 1:
+ if value is not None:
if first:
text += ">\n"
first = False
- value_type = members[attr][self.content["name"]]
- if value_type.startswith("bse:"):
- if value_type.endswith("[]"):
- for content in self.content["value"]:
- text += ind1 + "<%s>%s</%s>\n"%(self.content["name"], ComputeValue(content), self.content["name"])
- else:
- text += ind1 + "<%s>%s</%s>\n"%(self.content["name"], ComputeValue(self.content["value"]), self.content["name"])
- elif value_type.endswith("[]"):
- for content in self.content["value"]:
- text += content.generateXMLText(self.content["name"], indent + 1)
- elif self.content["value"] is not None:
- text += self.content["value"].generateXMLText(self.content["name"], indent + 1)
- else:
- ind5, ind6 = getIndent(indent + 1, self.content["name"])
- text += ind5 + "<%s/>\n"%self.content["name"]
- elif attr == "multichoice_content":
- if len(self.content) > 0:
- for element in self.content:
- if first:
- text += ">\n"
- first = False
- value_type = members[attr][element["name"]]
- if value_type.startswith("bse:"):
- text += ind1 + "<%s>%s</%s>\n"%(element["name"], ComputeValue(element["value"]), element["name"])
- else:
- text += element["value"].generateXMLText(element["name"], indent + 1)
- elif members[attr][2] != "optional" or value != None:
- if members[attr][0].endswith("[]"):
- if first and len(value) > 0:
- text += ">\n"
- first = False
- for element in value:
- if members[attr][0].startswith("bse:"):
- text += ind3 + "<%s>%s</%s>\n"%(attr, ComputeValue(element), attr)
- else:
- text += element.generateXMLText(attr, indent + 1)
- else:
- if first:
- text += ">\n"
- first = False
- if members[attr][0].startswith("bse:"):
- text += ind3 + "<%s>%s</%s>\n"%(attr, ComputeValue(value), attr)
- else:
- text += getattr(self, attr).generateXMLText(attr, indent + 1)
+ text += element["elmt_type"]["generate"](value, element["name"], indent + 1)
+ elif element["minOccurs"] == 1 and element["maxOccurs"] == 1:
+ if first:
+ text += ">\n"
+ first = False
+ text += element["elmt_type"]["generate"](value, element["name"], indent + 1)
+ else:
+ if first and len(value) > 0:
+ text += ">\n"
+ first = False
+ for item in value:
+ text += element["elmt_type"]["generate"](item, element["name"], indent + 1)
if not derived:
if first:
text += "/>\n"
@@ -854,178 +1301,188 @@
return first, text
return generateXMLTextMethod
-
-def generateGetElementAttributes(members, classes):
+def gettypeinfos(name, facets):
+ if "enumeration" in facets and facets["enumeration"][0] is not None:
+ return facets["enumeration"][0]
+ elif "maxInclusive" in facets:
+ limits = {"max" : None, "min" : None}
+ if facets["maxInclusive"][0] is not None:
+ limits["max"] = facets["maxInclusive"][0]
+ elif facets["maxExclusive"][0] is not None:
+ limits["max"] = facets["maxExclusive"][0] - 1
+ if facets["minInclusive"][0] is not None:
+ limits["min"] = facets["minInclusive"][0]
+ elif facets["minExclusive"][0] is not None:
+ limits["min"] = facets["minExclusive"][0] + 1
+ if limits["max"] is not None or limits["min"] is not None:
+ return limits
+ return name
+
+def generateGetElementAttributes(factory, classinfos):
def getElementAttributes(self):
attr_list = []
- for attr, values in members.items():
- if attr in ["order","choice_content","multichoice_content"]:
- pass
- elif values[1] == "attribute":
- attr_params = {"name": attr, "require": values[2] == "required"}
- if values[0].startswith("cls:"):
- attr_value = getattr(self, attr, None)
- if attr_value:
- attr_params["value"] = attr_value.getValue()
- else:
- attr_params["value"] = ""
- attr_params["type"] = classes[values[0][4:]]().getValidValues()
- else:
- attr_params["value"] = getattr(self, attr, "")
- attr_params["type"] = values[0][4:]
+ for attr in classinfos["attributes"]:
+ if attr["use"] != "prohibited":
+ attr_params = {"name" : attr["name"], "require" : attr["use"] == "required",
+ "type" : gettypeinfos(attr["attr_type"]["basename"], attr["attr_type"]["facets"]),
+ "value" : getattr(self, attr["name"], "")}
attr_list.append(attr_params)
return attr_list
return getElementAttributes
-def generateGetElementInfos(members, classes):
+def generateGetElementInfos(factory, classinfos):
+ attributes = dict([(attr["name"], attr) for attr in classinfos["attributes"] if attr["use"] != "prohibited"])
+ elements = dict([(element["name"], element) for element in classinfos["elements"]])
+
def getElementInfos(self, name, path = None):
attr_type = "element"
value = None
children = []
- if "enum" in members:
- attr_type = self.getValidValues()
- value = self.value
- elif "limit" in members:
- attr_type = {"min" : None, "max" : None}
- if "min" in members:
- attr_type["min"] = members["min"]
- if "max" in members:
- attr_type["max"] = members["max"]
- value = self.value
- elif path:
- if "choice_content" in members:
- return self.content["value"].getElementInfos(self.content["name"], path)
- elif "multichoice_content" not in members:
- parts = path.split(".", 1)
- if parts[0] in members:
- values = members[parts[0]]
- if values[1] == "attribute" and len(parts) == 1:
- attr = getattr(self, parts[0], None)
- if attr != None:
- if values[0].startswith("cls:"):
- return attr.getElementInfos(parts[0])
- else:
- attr_type = values[0][4:]
- value = getattr(self, attr, "")
- elif values[1] == "element":
- attr = getattr(self, parts[0], None)
- if attr != None:
- if len(parts) == 1:
- return attr.getElementInfos(parts[0])
- else:
- return attr.getElementInfos(parts[0], parts[1])
- else:
- for attr, values in members.items():
- if attr == "order":
- pass
- elif attr == "choice_content":
- attr_type = self.getChoices().items()
- if self.content:
- value = self.content["name"]
- children.extend(self.content["value"].getElementInfos(self.content["name"])["children"])
- elif attr == "multichoice_content":
- for element_infos in self.content:
- children.append(element_infos["value"].getElementInfos(element_infos["name"]))
- elif values[1] == "attribute" and not values[0].startswith("cls:"):
- children.append({"name" : attr, "value" : getattr(self, attr, ""), "type" : values[0][4:], "children" : []})
- else:
- element = getattr(self, attr, None)
- if not element:
- element = classes[values[0][4:]]()
- children.append(element.getElementInfos(attr))
+ if path is not None:
+ parts = path.split(".", 1)
+ if parts[0] in attributes:
+ if len(parts) != 0:
+ raise ValueError, "Wrong path!"
+ attr_type = gettypeinfos(attributes[parts[0]]["attr_type"]["basename"],
+ attributes[parts[0]]["attr_type"]["facets"])
+ value = getattr(self, parts[0], "")
+ elif parts[0] in elements:
+ if element["elmt_type"]["type"] == SIMPLETYPE:
+ if len(parts) != 0:
+ raise ValueError, "Wrong path!"
+ attr_type = gettypeinfos(elements[parts[0]]["elmt_type"]["basename"],
+ elements[parts[0]]["elmt_type"]["facets"])
+ value = getattr(self, parts[0], "")
+ elif parts[0] == "content":
+ return self.content["value"].getElementInfos(self.content["name"], path)
+ elif len(parts) == 1:
+ return attr.getElementInfos(parts[0])
+ else:
+ return attr.getElementInfos(parts[0], parts[1])
+ else:
+ raise ValueError, "Wrong path!"
+ else:
+ children.extend(self.getElementAttributes())
+ for element_name, element in elements.items():
+ if element_name == "content":
+ attr_type = [(choice["name"], None) for choice in element["choices"]]
+ value = self.content["name"]
+ children.extend(self.content["value"].getElementInfos(self.content["name"])["children"])
+ elif element["elmt_type"]["type"] == SIMPLETYPE:
+ children.append({"name" : element_name, "require" : element["minOccurs"] != 0,
+ "type" : gettypeinfos(element["elmt_type"]["basename"],
+ element["elmt_type"]["facets"]),
+ "value" : getattr(self, element_name, None)})
+ else:
+ instance = getattr(self, element_name, None)
+ if instance is None:
+ instance = elmt_type["elmt_type"]["initial"]()
+ children.append(instance.getElementInfos(element_name))
return {"name" : name, "type" : attr_type, "value" : value, "children" : children}
return getElementInfos
-def generateSetElementValue(members):
+def generateSetElementValue(factory, classinfos):
+ attributes = dict([(attr["name"], attr) for attr in classinfos["attributes"] if attr["use"] != "prohibited"])
+ elements = dict([(element["name"], element) for element in classinfos["elements"]])
+
def setElementValue(self, path, value):
- if "enum" in members or "limit" in members:
- if not path:
- self.setValue(value)
- elif "choice_content" in members:
+ if "content" in elements:
if path:
self.content["value"].setElementValue(path, value)
else:
- self.addContent(value)
+ self.addcontentbytype(value)
else:
parts = path.split(".", 1)
- if parts[0] in members:
- values = members[parts[0]]
- if values[1] == "attribute" and len(parts) == 1:
- attr = getattr(self, parts[0], None)
- if attr != None:
- if values[0].startswith("cls:"):
- attr.setElementValue(None, value)
- elif values[0][4:] == "boolean":
- setattr(self, parts[0], value)
+ if parts[0] in attributes:
+ if len(parts) != 1:
+ raise ValueError, "Wrong path!"
+ if attributes[parts[0]]["attr_type"]["basename"] == "boolean":
+ setattr(self, parts[0], value)
+ else:
+ setattr(self, parts[0], attributes[parts[0]]["attr_type"]["extract"](value, False))
+ elif parts[0] in elements:
+ if elements[parts[0]]["elmt_type"]["type"] == SIMPLETYPE:
+ if len(parts) != 1:
+ raise ValueError, "Wrong path!"
+ if elements[parts[0]]["elmt_type"]["basename"] == "boolean":
+ setattr(self, parts[0], value)
+ else:
+ setattr(self, parts[0], elements[parts[0]]["elmt_type"]["extract"](value, False))
+ else:
+ instance = getattr(self, parts[0], None)
+ if instance != None:
+ if len(parts) == 1:
+ instance.setElementValue(None, value)
else:
- setattr(self, parts[0], GetComputedValue(values[0], value))
- elif values[1] == "element":
- attr = getattr(self, parts[0], None)
- if attr != None:
- if len(parts) == 1:
- attr.setElementValue(None, value)
- else:
- attr.setElementValue(parts[1], value)
+ instance.setElementValue(parts[1], value)
return setElementValue
"""
Methods that generates the different methods for setting and getting the attributes
"""
-def generateInitMethod(bases, members):
+def generateInitMethod(factory, classinfos):
def initMethod(self):
- for base in bases:
- base.__init__(self)
- for attr, initial in members.items():
- setattr(self, attr, initial())
+ if "base" in classinfos:
+ classinfos["base"].__init__(self)
+ for attribute in classinfos["attributes"]:
+ if isinstance(attribute["attr_type"], (UnicodeType, StringType)):
+ namespace, name = DecomposeQualifiedName(attribute["attr_type"])
+ attribute["attr_type"] = factory.GetQualifiedNameInfos(name, namespace)
+ if attribute["use"] == "required":
+ setattr(self, attribute["name"], attribute["attr_type"]["initial"]())
+ elif attribute["use"] == "optional":
+ if "default" in attribute:
+ setattr(self, attribute["name"], attribute["attr_type"]["extract"](attribute["default"], False))
+ else:
+ setattr(self, attribute["name"], None)
+ for element in classinfos["elements"]:
+ if isinstance(element["elmt_type"], (UnicodeType, StringType)):
+ namespace, name = DecomposeQualifiedName(element["elmt_type"])
+ element["elmt_type"] = factory.GetQualifiedNameInfos(name, namespace)
+ if element["minOccurs"] == 0 and element["maxOccurs"] == 1:
+ if "default" in element:
+ setattr(self, element["name"], element["elmt_type"]["extract"](element["default"], False))
+ else:
+ setattr(self, element["name"], None)
+ elif element["minOccurs"] == 1 and element["maxOccurs"] == 1:
+ setattr(self, element["name"], element["elmt_type"]["initial"]())
+ else:
+ value = []
+ for i in xrange(element["minOccurs"]):
+ value.append(element["elmt_type"]["initial"]())
+ setattr(self, element["name"], value)
return initMethod
-def generateSetMethod(attr, attr_type):
+def generateSetMethod(attr):
def setMethod(self, value):
setattr(self, attr, value)
return setMethod
-def generateAddChoiceMethod(choice_type, initial_values):
- def addChoiceMethod(self, name):
- if name in choice_type:
- self.content = {"name" : name, "value" : initial_values[name]()}
- return addChoiceMethod
-
-def generateSetChoiceMethod(choice_type):
- def setChoiceMethod(self, name, value):
- self.content = {"name" : name, "value" : value}
- return setChoiceMethod
-
-def generateGetChoicesMethod(choice_type):
- def getChoicesMethod(self):
- return choice_type
- return getChoicesMethod
-
-def generateSetEnumMethod(enum, attr_type):
- def setEnumMethod(self, value):
- if value in enum:
- self.value = value
- else:
- raise ValueError, "%s is not a valid value. Must be in %s"%(value, str(enum))
- return setEnumMethod
-
-def generateSetLimitMethod(limit, attr_type):
- def setMethod(self, value):
- if "min" in limit and value < limit["min"]:
- raise ValueError, "%s is not a valid value. Must be greater than %d"%(value, limit["min"])
- elif "max" in limit and value > limit["max"]:
- raise ValueError, "%s is not a valid value. Must be smaller than %d"%(value, limit["max"])
- else:
- self.value = value
- return setMethod
-
def generateGetMethod(attr):
def getMethod(self):
return getattr(self, attr, None)
return getMethod
-def generateAddMethod(attr, initial):
+def generateAddMethod(attr, factory, infos):
def addMethod(self):
- setattr(self, attr, initial())
+ if infos["type"] == ATTRIBUTE:
+ if isinstance(infos["attr_type"], (UnicodeType, StringType)):
+ namespace, name = DecomposeQualifiedName(infos)
+ infos["attr_type"] = factory.GetQualifiedNameInfos(name, namespace)
+ initial = infos["attr_type"]["initial"]
+ extract = infos["attr_type"]["extract"]
+ elif infos["type"] == ELEMENT:
+ if isinstance(infos["elmt_type"], (UnicodeType, StringType)):
+ namespace, name = DecomposeQualifiedName(infos)
+ infos["elmt_type"] = factory.GetQualifiedNameInfos(name, namespace)
+ initial = infos["elmt_type"]["initial"]
+ extract = infos["elmt_type"]["extract"]
+ else:
+ raise ValueError, "Invalid class attribute!"
+ if "default" in infos:
+ setattr(self, attr, extract(infos["default"], False))
+ else:
+ setattr(self, attr, initial())
return addMethod
def generateDeleteMethod(attr):
@@ -1033,35 +1490,58 @@
setattr(self, attr, None)
return deleteMethod
-def generateAppendMethod(attr, attr_type):
+def generateAppendMethod(attr, maxOccurs, factory, infos):
def appendMethod(self, value):
- getattr(self, attr).append(value)
+ if isinstance(infos["elmt_type"], (UnicodeType, StringType)):
+ namespace, name = DecomposeQualifiedName(infos)
+ infos["elmt_type"] = factory.GetQualifiedNameInfos(name, namespace)
+ attr_list = getattr(self, attr)
+ if maxOccurs == "unbounded" or len(attr_list) < maxOccurs:
+ if infos["elmt_type"]["check"](value):
+ attr_list.append(value)
+ else:
+ raise ValueError, "\"%s\" value isn't valid!"%attr
+ else:
+ raise ValueError, "There can't be more than %d values in \"%s\"!"%(maxOccurs, attr)
return appendMethod
-def generateInsertMethod(attr, attr_type):
+def generateInsertMethod(attr, maxOccurs, factory, infos):
def insertMethod(self, index, value):
- getattr(self, attr).insert(index, value)
+ if isinstance(infos["elmt_type"], (UnicodeType, StringType)):
+ namespace, name = DecomposeQualifiedName(infos)
+ infos["elmt_type"] = factory.GetQualifiedNameInfos(name, namespace)
+ attr_list = getattr(self, attr)
+ if maxOccurs == "unbounded" or len(attr_list) < maxOccurs:
+ if infos["elmt_type"]["check"](value):
+ attr_list.insert(index, value)
+ else:
+ raise ValueError, "\"%s\" value isn't valid!"%attr
+ else:
+ raise ValueError, "There can't be more than %d values in \"%s\"!"%(maxOccurs, attr)
return insertMethod
-def generateAppendChoiceByTypeMethod(choice_type, initial_values):
+def generateGetChoicesMethod(choice_types):
+ def getChoicesMethod(self):
+ return [choice["name"] for choice in choice_types]
+ return getChoicesMethod
+
+def generateAddChoiceByTypeMethod(choice_types):
+ choices = dict([(choice["name"], choice) for choice in choice_types])
def addChoiceMethod(self, name):
- if name in choice_type:
- self.content.append({"name" : name, "value" : initial_values[name]()})
+ if name in choices:
+ if isinstance(choices["name"]["elmt_type"], (UnicodeType, StringType)):
+ namespace, name = DecomposeQualifiedName(infos)
+ choices["name"]["elmt_type"] = factory.GetQualifiedNameInfos(name, namespace)
+ self.content = {"name" : name, "value" : choices["name"]["elmt_type"]["initial"]()}
return addChoiceMethod
-def generateAppendChoiceMethod(choice_types):
- def appendMethod(self, name, value):
- self.content.append({"name":name,"value":value})
- return appendMethod
-
-def generateInsertChoiceMethod(choice_types):
- def insertMethod(self, index, name, value):
- self.content.insert(index, {"name":name,"value":value})
- return insertMethod
-
-def generateRemoveMethod(attr):
+def generateRemoveMethod(attr, minOccurs):
def removeMethod(self, index):
- getattr(self, attr).pop(index)
+ attr_list = getattr(self, attr)
+ if len(attr_list) > minOccurs:
+ getattr(self, attr).pop(index)
+ else:
+ raise ValueError, "There can't be less than %d values in \"%s\"!"%(minOccurs, attr)
return removeMethod
def generateCountMethod(attr):
@@ -1073,28 +1553,13 @@
This function generate the classes from a class factory
"""
def GenerateClasses(factory, declare = False):
- ComputedClasses, ComputedTypes = factory.CreateClasses()
+ ComputedClasses = factory.CreateClasses()
+ #factory.PrintClasses()
if declare:
for ClassName, Class in pluginClasses.items():
sys._getframe(1).f_locals[ClassName] = Class
for TypeName, Type in pluginTypes.items():
sys._getframe(1).f_locals[TypeName] = Type
globals().update(ComputedClasses)
- return ComputedClasses, ComputedTypes
-
-"""
-This function opens the xsd file and generate the classes from the xml tree
-"""
-def GenerateClassesFromXSD(filename, declare = False):
- xsdfile = open(filename, 'r')
- factory = ClassFactory(minidom.parse(xsdfile))
- xsdfile.close()
- return GenerateClasses(factory, declare)
-
-"""
-This function generate the classes from the xsd given as a string
-"""
-def GenerateClassesFromXSDstring(xsdstring, declare = False):
- factory = ClassFactory(minidom.parseString(xsdstring))
- return GenerateClasses(factory, declare)
-
+ return ComputedClasses
+
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/xmlclass/xsdschema.py Tue Jan 22 10:57:41 2008 +0100
@@ -0,0 +1,2451 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+
+#This file is part of PLCOpenEditor, a library implementing an IEC 61131-3 editor
+#based on the plcopen standard.
+#
+#Copyright (C) 2007: Edouard TISSERANT and Laurent BESSARD
+#
+#See COPYING file for copyrights details.
+#
+#This library is free software; you can redistribute it and/or
+#modify it under the terms of the GNU General Public
+#License as published by the Free Software Foundation; either
+#version 2.1 of the License, or (at your option) any later version.
+#
+#This library is distributed in the hope that it will be useful,
+#but WITHOUT ANY WARRANTY; without even the implied warranty of
+#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+#General Public License for more details.
+#
+#You should have received a copy of the GNU General Public
+#License along with this library; if not, write to the Free Software
+#Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+
+from xml.dom import minidom
+from types import *
+import re, datetime
+from xmlclass import *
+
+def GenerateDictFacets(facets):
+ return dict([(name, (None, False)) for name in facets])
+
+def GenerateSimpleTypeXMLText(function):
+ def generateXMLTextMethod(value, name = None, indent = 0):
+ text = ""
+ if name is not None:
+ ind1, ind2 = getIndent(indent, name)
+ text += ind1 + "<%s>"%name
+ text += function(value)
+ if name is not None:
+ text += "</%s>\n"%name
+ return text
+ return generateXMLTextMethod
+
+def GenerateFloatXMLText(extra_values = []):
+ def generateXMLTextMethod(value, name = None, indent = 0):
+ text = ""
+ if name is not None:
+ ind1, ind2 = getIndent(indent, name)
+ text += ind1 + "<%s>"%name
+ if value in extra_values or value % 1 != 0 or isinstance(value, IntType):
+ text += str(value)
+ else:
+ text += "%.0f"%value
+ if name is not None:
+ text += "</%s>\n"%name
+ return text
+ return generateXMLTextMethod
+
+DEFAULT_FACETS = GenerateDictFacets(["pattern", "whiteSpace", "enumeration"])
+NUMBER_FACETS = GenerateDictFacets(DEFAULT_FACETS.keys() + ["maxInclusive", "maxExclusive", "minInclusive", "minExclusive"])
+DECIMAL_FACETS = GenerateDictFacets(NUMBER_FACETS.keys() + ["totalDigits", "fractionDigits"])
+STRING_FACETS = GenerateDictFacets(DEFAULT_FACETS.keys() + ["length", "minLength", "maxLength"])
+
+ALL_FACETS = ["pattern", "whiteSpace", "enumeration", "maxInclusive",
+ "maxExclusive", "minInclusive", "minExclusive", "totalDigits",
+ "fractionDigits", "length", "minLength", "maxLength"]
+
+
+#-------------------------------------------------------------------------------
+# Structure reducing functions
+#-------------------------------------------------------------------------------
+
+
+# Documentation elements
+
+def ReduceAppInfo(factory, attributes, elements):
+ return {"type" : "appinfo", "source" : attributes.get("source", None),
+ "content" : "\n".join(elements)}
+
+
+def ReduceDocumentation(factory, attributes, elements):
+ return {"type" : "documentation", "source" : attributes.get("source", None),
+ "language" : attributes.get("lang", "any"), "content" : "\n".join(elements)}
+
+
+def ReduceAnnotation(factory, attributes, elements):
+ annotations, children = factory.ReduceElements(elements)
+ annotation = {"type" : "annotation", "appinfo" : [], "documentation" : {}}
+ for child in children:
+ if child["type"] == "appinfo":
+ annotation["appinfo"].append((child["source"], child["content"]))
+ elif child["type"] == "documentation":
+ if child["source"] is not None:
+ text = "(source : %(source)s):\n%(content)s\n\n"%child
+ else:
+ text = child["content"] + "\n\n"
+ if child["language"] not in annotation["documentation"]:
+ annotation["documentation"] = text
+ else:
+ annotation["documentation"] += text
+ return annotation
+
+# Simple type elements
+
+def GenerateFacetReducing(facetname, canbefixed):
+ def ReduceFacet(factory, attributes, elements):
+ annotations, children = factory.ReduceElements(elements)
+ if "value" in attributes:
+ facet = {"type" : facetname, "value" : attributes["value"], "doc" : annotations}
+ if canbefixed:
+ facet["fixed"] = attributes.get("fixed", False)
+ return facet
+ raise ValueError, "A value must be defined for the \"%s\" facet!"%facetname
+ return ReduceFacet
+
+
+def ReduceList(factory, attributes, elements):
+ annotations, children = factory.ReduceElements(elements)
+ list = {"type" : "list", "itemType" : attributes.get("itemType", None), "doc" : annotations}
+
+ if len(children) > 0 and children[0]["type"] == SIMPLETYPE:
+ if list["itemType"] is None:
+ list["itemType"] = children[0]
+ else:
+ raise ValueError, "Only one base type can be defined for restriction!"
+ if list["itemType"] is None:
+ raise ValueError, "No base type has been defined for list!"
+ return list
+
+
+def ReduceUnion(factory, attributes, elements):
+ annotations, children = factory.ReduceElements(elements)
+ union = {"type" : "union", "memberTypes" : attributes.get("memberTypes", []), "doc" : annotations}
+
+ if child in children:
+ if child["type"] == SIMPLETYPE:
+ union["memberTypes"] = child
+ if len(union["memberTypes"]) == 0:
+ raise ValueError, "No base type has been defined for union!"
+ return list
+
+
+def ReduceSimpleType(factory, attributes, elements):
+ # Reduce all the simple type children
+ annotations, children = factory.ReduceElements(elements)
+
+ typeinfos = children[0]
+
+ # Initialize type informations
+ facets = {}
+ simpleType = {"type" : SIMPLETYPE, "final" : attributes.get("final", []), "doc" : annotations}
+ if "name" in attributes:
+ simpleType["name"] = attributes["name"]
+
+ if typeinfos["type"] == "restriction":
+ # Search for base type definition
+ if isinstance(typeinfos["base"], (StringType, UnicodeType)):
+ basetypeinfos = factory.FindSchemaElement(typeinfos["base"], SIMPLETYPE)
+ if basetypeinfos is None:
+ raise "\"%s\" isn't defined!"%typeinfos["base"]
+ else:
+ basetypeinfos = typeinfos["base"]
+
+ # Check that base type is a simple type
+ if basetypeinfos["type"] != SIMPLETYPE:
+ raise ValueError, "Base type given isn't a simpleType!"
+
+ typeinfos["basename"] = basetypeinfos["basename"]
+
+ # Check that derivation is allowed
+ if "final" in basetypeinfos:
+ if "#all" in basetypeinfos["final"]:
+ raise ValueError, "Base type can't be derivated!"
+ if "restriction" in basetypeinfos["final"]:
+ raise ValueError, "Base type can't be derivated by restriction!"
+
+ # Extract simple type facets
+ for facet in typeinfos["facets"]:
+ facettype = facet["type"]
+ if facettype not in basetypeinfos["facets"]:
+ raise ValueError, "\"%s\" facet can't be defined for \"%s\" type!"%(facettype, type)
+ elif basetypeinfos["facets"][facettype][1]:
+ raise ValueError, "\"%s\" facet is fixed on base type!"%facettype
+ value = facet["value"]
+ basevalue = basetypeinfos["facets"][facettype][0]
+ if facettype == "enumeration":
+ value = basetypeinfos["extract"](value, False)
+ if len(facets) == 0:
+ facets["enumeration"] = ([value], False)
+ continue
+ elif facets.keys() == ["enumeration"]:
+ facets["enumeration"][0].append(value)
+ continue
+ else:
+ raise ValueError, "\"enumeration\" facet can't be defined with another facet type!"
+ elif "enumeration" in facets:
+ raise ValueError, "\"enumeration\" facet can't be defined with another facet type!"
+ elif facettype in facets:
+ raise ValueError, "\"%s\" facet can't be defined two times!"%facettype
+ elif facettype == "length":
+ if "minLength" in facets:
+ raise ValueError, "\"length\" and \"minLength\" facets can't be defined at the same time!"
+ if "maxLength" in facets:
+ raise ValueError, "\"length\" and \"maxLength\" facets can't be defined at the same time!"
+ try:
+ value = int(value)
+ except:
+ raise ValueError, "\"length\" must be an integer!"
+ if value < 0:
+ raise ValueError, "\"length\" can't be negative!"
+ elif basevalue is not None and basevalue != value:
+ raise ValueError, "\"length\" can't be different from \"length\" defined in base type!"
+ elif facettype == "minLength":
+ if "length" in facets:
+ raise ValueError, "\"length\" and \"minLength\" facets can't be defined at the same time!"
+ try:
+ value = int(value)
+ except:
+ raise ValueError, "\"minLength\" must be an integer!"
+ if value < 0:
+ raise ValueError, "\"minLength\" can't be negative!"
+ elif "maxLength" in facets and value > facets["maxLength"]:
+ raise ValueError, "\"minLength\" must be lesser than or equal to \"maxLength\"!"
+ elif basevalue is not None and basevalue < value:
+ raise ValueError, "\"minLength\" can't be lesser than \"minLength\" defined in base type!"
+ elif facettype == "maxLength":
+ if "length" in facets:
+ raise ValueError, "\"length\" and \"maxLength\" facets can't be defined at the same time!"
+ try:
+ value = int(value)
+ except:
+ raise ValueError, "\"maxLength\" must be an integer!"
+ if value < 0:
+ raise ValueError, "\"maxLength\" can't be negative!"
+ elif "minLength" in facets and value < facets["minLength"]:
+ raise ValueError, "\"minLength\" must be lesser than or equal to \"maxLength\"!"
+ elif basevalue is not None and basevalue > value:
+ raise ValueError, "\"maxLength\" can't be greater than \"maxLength\" defined in base type!"
+ elif facettype == "minInclusive":
+ if "minExclusive" in facets:
+ raise ValueError, "\"minExclusive\" and \"minInclusive\" facets can't be defined at the same time!"
+ value = basetypeinfos["extract"](facet["value"], False)
+ if "maxInclusive" in facets and value > facets["maxInclusive"][0]:
+ raise ValueError, "\"minInclusive\" must be lesser than or equal to \"maxInclusive\"!"
+ elif "maxExclusive" in facets and value >= facets["maxExclusive"][0]:
+ raise ValueError, "\"minInclusive\" must be lesser than \"maxExclusive\"!"
+ elif facettype == "minExclusive":
+ if "minInclusive" in facets:
+ raise ValueError, "\"minExclusive\" and \"minInclusive\" facets can't be defined at the same time!"
+ value = basetypeinfos["extract"](facet["value"], False)
+ if "maxInclusive" in facets and value >= facets["maxInclusive"][0]:
+ raise ValueError, "\"minExclusive\" must be lesser than \"maxInclusive\"!"
+ elif "maxExclusive" in facets and value >= facets["maxExclusive"][0]:
+ raise ValueError, "\"minExclusive\" must be lesser than \"maxExclusive\"!"
+ elif facettype == "maxInclusive":
+ if "maxExclusive" in facets:
+ raise ValueError, "\"maxExclusive\" and \"maxInclusive\" facets can't be defined at the same time!"
+ value = basetypeinfos["extract"](facet["value"], False)
+ if "minInclusive" in facets and value < facets["minInclusive"][0]:
+ raise ValueError, "\"minInclusive\" must be lesser than or equal to \"maxInclusive\"!"
+ elif "minExclusive" in facets and value <= facets["minExclusive"][0]:
+ raise ValueError, "\"minExclusive\" must be lesser than \"maxInclusive\"!"
+ elif facettype == "maxExclusive":
+ if "maxInclusive" in facets:
+ raise ValueError, "\"maxExclusive\" and \"maxInclusive\" facets can't be defined at the same time!"
+ value = basetypeinfos["extract"](facet["value"], False)
+ if "minInclusive" in facets and value <= facets["minInclusive"][0]:
+ raise ValueError, "\"minInclusive\" must be lesser than \"maxExclusive\"!"
+ elif "minExclusive" in facets and value <= facets["minExclusive"][0]:
+ raise ValueError, "\"minExclusive\" must be lesser than \"maxExclusive\"!"
+ elif facettype == "whiteSpace":
+ if basevalue == "collapse" and value in ["preserve", "replace"] or basevalue == "replace" and value == "preserve":
+ raise ValueError, "\"whiteSpace\" is incompatible with \"whiteSpace\" defined in base type!"
+ elif facettype == "totalDigits":
+ if "fractionDigits" in facets and value <= facets["fractionDigits"][0]:
+ raise ValueError, "\"fractionDigits\" must be lesser than or equal to \"totalDigits\"!"
+ elif basevalue is not None and value > basevalue:
+ raise ValueError, "\"totalDigits\" can't be greater than \"totalDigits\" defined in base type!"
+ elif facettype == "fractionDigits":
+ if "totalDigits" in facets and value <= facets["totalDigits"][0]:
+ raise ValueError, "\"fractionDigits\" must be lesser than or equal to \"totalDigits\"!"
+ elif basevalue is not None and value > basevalue:
+ raise ValueError, "\"totalDigits\" can't be greater than \"totalDigits\" defined in base type!"
+ facets[facettype] = (value, facet.get("fixed", False))
+
+ # Report not redefined facet from base type to new created type
+ for facettype, facetvalue in basetypeinfos["facets"].items():
+ if facettype not in facets:
+ facets[facettype] = facetvalue
+
+ # Generate extract value for new created type
+ def ExtractSimpleTypeValue(attr, extract = True):
+ value = basetypeinfos["extract"](attr, extract)
+ for facetname, (facetvalue, facetfixed) in facets.items():
+ if facetvalue is not None:
+ if facetname == "enumeration" and value not in facetvalue:
+ raise ValueError, "\"%s\" not in enumerated values"%value
+ elif facetname == "length" and len(value) != facetvalue:
+ raise ValueError, "value must have a length of %d"%facetvalue
+ elif facetname == "minLength" and len(value) < facetvalue:
+ raise ValueError, "value must have a length of %d at least"%facetvalue
+ elif facetname == "maxLength" and len(value) > facetvalue:
+ raise ValueError, "value must have a length of %d at most"%facetvalue
+ elif facetname == "minInclusive" and value < facetvalue:
+ raise ValueError, "value must be greater than or equal to %s"%str(facetvalue)
+ elif facetname == "minExclusive" and value <= facetvalue:
+ raise ValueError, "value must be greater than %s"%str(facetvalue)
+ elif facetname == "maxInclusive" and value > facetvalue:
+ raise ValueError, "value must be lesser than or equal to %s"%str(facetvalue)
+ elif facetname == "maxExclusive" and value >= facetvalue:
+ raise ValueError, "value must be lesser than %s"%str(facetvalue)
+ elif facetname == "pattern":
+ model = re.compile("(?:%s)?$"%facetvalue)
+ result = model.match(value)
+ if result is None:
+ raise ValueError, "value doesn't follow the pattern %s"%facetvalue
+ elif facetname == "whiteSpace":
+ if facetvalue == "replace":
+ value = GetNormalizedString(value, False)
+ elif facetvalue == "collapse":
+ value = GetToken(value, False)
+ return value
+
+ def CheckSimpleTypeValue(value):
+ for facetname, (facetvalue, facetfixed) in facets.items():
+ if facetvalue is not None:
+ if facetname == "enumeration" and value not in facetvalue:
+ return False
+ elif facetname == "length" and len(value) != facetvalue:
+ return False
+ elif facetname == "minLength" and len(value) < facetvalue:
+ return False
+ elif facetname == "maxLength" and len(value) > facetvalue:
+ return False
+ elif facetname == "minInclusive" and value < facetvalue:
+ return False
+ elif facetname == "minExclusive" and value <= facetvalue:
+ return False
+ elif facetname == "maxInclusive" and value > facetvalue:
+ return False
+ elif facetname == "maxExclusive" and value >= facetvalue:
+ return False
+ elif facetname == "pattern":
+ model = re.compile("(?:%s)?$"%facetvalue)
+ result = model.match(value)
+ if result is None:
+ raise ValueError, "value doesn't follow the pattern %s"%facetvalue
+ return True
+
+ def SimpleTypeInitialValue():
+ for facetname, (facetvalue, facetfixed) in facets.items():
+ if facetvalue is not None:
+ if facetname == "enumeration":
+ return facetvalue[0]
+ elif facetname == "length":
+ return " "*facetvalue
+ elif facetname == "minLength":
+ return " "*minLength
+ elif facetname == "minInclusive" and facetvalue > 0:
+ return facetvalue
+ elif facetname == "minExclusive" and facetvalue >= 0:
+ return facetvalue + 1
+ elif facetname == "maxInclusive" and facetvalue < 0:
+ return facetvalue
+ elif facetname == "maxExclusive" and facetvalue <= 0:
+ return facetvalue - 1
+ return basetypeinfos["initial"]()
+
+ GenerateSimpleType = basetypeinfos["generate"]
+
+ elif typeinfos["type"] == "list":
+ # Search for item type definition
+ if isinstance(typeinfos["itemType"], (StringType, UnicodeType)):
+ itemtypeinfos = factory.FindSchemaElement(typeinfos["itemType"], SIMPLETYPE)
+ if itemtypeinfos is None:
+ raise "\"%s\" isn't defined!"%typeinfos["itemType"]
+ else:
+ itemtypeinfos = typeinfos["itemType"]
+
+ # Check that item type is a simple type
+ if itemtypeinfos["type"] != SIMPLETYPE:
+ raise ValueError, "Item type given isn't a simpleType!"
+
+ # Check that derivation is allowed
+ if "#all" in itemtypeinfos["final"]:
+ raise ValueError, "Item type can't be derivated!"
+ if "list" in itemtypeinfos["final"]:
+ raise ValueError, "Item type can't be derivated by list!"
+
+ # Generate extract value for new created type
+ def ExtractSimpleTypeValue(attr, extract = True):
+ values = []
+ for value in GetToken(attr, extract).split(" "):
+ values.append(itemtypeinfos["extract"](value, False))
+ return values
+
+ def CheckSimpleTypeValue(value):
+ for value in GetToken(attr, extract).split(" "):
+ result = itemtypeinfos["check"](value)
+ if not result:
+ return result
+ return True
+
+ SimpleTypeInitialValue = lambda: ""
+
+ GenerateSimpleType = GenerateSimpleTypeXMLText(lambda x : " ".join(map(itemtypeinfos, values)))
+
+ facets = GenerateDictFacets(["length", "maxLength", "minLength", "enumeration", "pattern"])
+ facet["whiteSpace"] = ("collapse", False)
+
+ elif typeinfos["type"] == "union":
+ # Search for member types definition
+ membertypesinfos = []
+ for membertype in typeinfos["memberTypes"]:
+ if isinstance(membertype, (StringType, UnicodeType)):
+ infos = factory.FindSchemaElement(typeinfos["memberTypes"], SIMPLETYPE)
+ if infos is None:
+ raise "\"%s\" isn't defined!"%typeinfos["itemType"]
+ else:
+ infos = membertype
+
+ # Check that member type is a simple type
+ if infos["type"] != SIMPLETYPE:
+ raise ValueError, "Member type given isn't a simpleType!"
+
+ # Check that derivation is allowed
+ if "#all" in infos["final"]:
+ raise ValueError, "Item type can't be derivated!"
+ if "union" in infos["final"]:
+ raise ValueError, "Member type can't be derivated by union!"
+
+ membertypesinfos.append(infos)
+
+ # Generate extract value for new created type
+ def ExtractSimpleTypeValue(attr, extract = True):
+ if extract:
+ value = GetAttributeValue(attr)
+ else:
+ value = attr
+ for infos in membertypesinfos:
+ try:
+ return infos["extract"](attr, False)
+ except:
+ pass
+ raise ValueError, "\"%s\" isn't valid for type defined for union!"
+
+ def CheckSimpleTypeValue(value):
+ for infos in membertypesinfos:
+ result = infos["check"](value)
+ if result:
+ return result
+ return False
+
+ SimpleTypeInitialValue = membertypesinfos[0]["initial"]
+
+ def GenerateSimpleTypeFunction(value):
+ if isinstance(value, BooleanType):
+ return {True : "true", False : "false"}[value]
+ else:
+ return str(value)
+ GenerateSimpleType = GenerateSimpleTypeXMLText(GenerateSimpleTypeFunction)
+
+ facets = GenerateDictFacets(["pattern", "enumeration"])
+
+ simpleType["facets"] = facets
+ simpleType["extract"] = ExtractSimpleTypeValue
+ simpleType["initial"] = SimpleTypeInitialValue
+ simpleType["check"] = CheckSimpleTypeValue
+ simpleType["generate"] = GenerateSimpleType
+ return simpleType
+
+
+# Complex type
+
+def ExtractAttributes(factory, elements, base = None):
+ if base is not None:
+ basetypeinfos = factory.FindSchemaElement(base, COMPLEXTYPE)
+ if isinstance(basetypeinfos, (UnicodeType, StringType)):
+ attrnames = {}
+ else:
+ attrnames = dict(map(lambda x:(x["name"], True), basetypeinfos["attributes"]))
+ else:
+ attrnames = {}
+ attrs = []
+ for element in elements:
+ if element["type"] == ATTRIBUTE:
+ if attrnames.get(element["name"], False):
+ raise ValueError, "\"%s\" attribute has been defined two times!"%element["name"]
+ else:
+ attrnames[element["name"]] = True
+ attrs.append(element)
+ elif element["type"] == "attributeGroup":
+ attrgroup = factory.FindSchemaElement(element["ref"], ATTRIBUTESGROUP)
+ for attr in attrgroup["attributes"]:
+ if attrnames.get(attr["name"], False):
+ raise ValueError, "\"%s\" attribute has been defined two times!"%attr["name"]
+ else:
+ attrnames[attr["name"]] = True
+ attrs.append(attr)
+ elif element["type"] == "anyAttribute":
+ raise ValueError, "\"anyAttribute\" element isn't supported yet!"
+ return attrs
+
+
+def ReduceRestriction(factory, attributes, elements):
+ annotations, children = factory.ReduceElements(elements)
+ restriction = {"type" : "restriction", "base" : attributes.get("base", None), "facets" : [], "doc" : annotations}
+ if len(children) > 0 and children[0]["type"] == SIMPLETYPE:
+ if restriction["base"] is None:
+ restriction["base"] = children.pop(0)
+ else:
+ raise ValueError, "Only one base type can be defined for restriction!"
+ if restriction["base"] is None:
+ raise ValueError, "No base type has been defined for restriction!"
+
+ while len(children) > 0 and children[0]["type"] in ALL_FACETS:
+ restriction["facets"].append(children.pop(0))
+ restriction["attributes"] = ExtractAttributes(factory, children)
+ return restriction
+
+
+def ReduceExtension(factory, attributes, elements):
+ annotations, children = factory.ReduceElements(elements)
+ extension = {"type" : "extension", "attributes" : [], "elements" : [], "base" : attributes.get("base", None), "doc" : annotations}
+ if len(children) > 0:
+ if children[0]["type"] in ["group", "all", CHOICE, "sequence"]:
+ group = children.pop(0)
+ if group["type"] in ["all", "sequence"]:
+ extension["elements"] = group["elements"]
+ extension["order"] = group["order"]
+ elif group["type"] == CHOICE:
+ content = group.copy()
+ content["name"] = "content"
+ extension["elements"].append(content)
+ elif group["type"] == "group":
+ elmtgroup = factory.FindSchemaElement(child["ref"], ELEMENTSGROUP)
+ if "elements" in elmtgroup:
+ extension["elements"] = elmtgroup["elements"]
+ extension["order"] = elmtgroup["order"]
+ else:
+ content = elmtgroup.copy()
+ content["name"] = "content"
+ extension["elements"].append(content)
+ extension["attributes"] = ExtractAttributes(factory, children, extension["base"])
+ return extension
+
+
+def ReduceSimpleContent(factory, attributes, elements):
+ annotations, children = factory.ReduceElements(elements)
+ simpleContent = children[0].copy()
+ simpleContent["type"] = "simpleContent"
+ return simpleContent
+
+
+def ReduceComplexContent(factory, attributes, elements):
+ annotations, children = factory.ReduceElements(elements)
+ complexContent = children[0].copy()
+ complexContent["type"] = "complexContent"
+ return complexContent
+
+
+def ReduceComplexType(factory, attributes, elements):
+ annotations, children = factory.ReduceElements(elements)
+
+ if len(children) > 0:
+ if children[0]["type"] in ["simpleContent", "complexContent"]:
+ complexType = children[0].copy()
+ complexType.update(attributes)
+ complexType["type"] = COMPLEXTYPE
+ return complexType
+ elif children[0]["type"] in ["group", "all", CHOICE, "sequence"]:
+ complexType = {"type" : COMPLEXTYPE, "elements" : [], "order" : True, "doc" : annotations}
+ complexType.update(attributes)
+ group = children.pop(0)
+ if group["type"] in ["all", "sequence"]:
+ if group["minOccurs"] == 0 or group["maxOccurs"] != 1:
+ if len(group["elements"]) > 1:
+ raise ValueError, "Not supported yet!"
+ if group["minOccurs"] == 0:
+ group["elements"][0]["minOccurs"] = group["minOccurs"]
+ if group["maxOccurs"] != 1:
+ group["elements"][0]["maxOccurs"] = group["maxOccurs"]
+ complexType["elements"] = group["elements"]
+ complexType["order"] = group["order"]
+ elif group["type"] == CHOICE:
+ content = group.copy()
+ content["name"] = "content"
+ complexType["elements"].append(content)
+ elif group["type"] == "group":
+ elmtgroup = factory.FindSchemaElement(child["ref"], ELEMENTSGROUP)
+ if "elements" in elmtgroup:
+ complexType["elements"] = elmtgroup["elements"]
+ complexType["order"] = elmtgroup["order"]
+ else:
+ content = elmtgroup.copy()
+ content["name"] = "content"
+ complexType["elements"].append(content)
+ else:
+ complexType = {"elements" : [], "order" : True, "doc" : annotations}
+ complexType.update(attributes)
+ complexType["type"] = COMPLEXTYPE
+ complexType["attributes"] = ExtractAttributes(factory, children)
+ return complexType
+ else:
+ raise ValueError, "\"ComplexType\" can't be empty!"
+
+
+# Attribute elements
+
+def ReduceAnyAttribute(factory, attributes, elements):
+ return {"type" : "anyAttribute"}
+
+
+def ReduceAttribute(factory, attributes, elements):
+ annotations, children = factory.ReduceElements(elements)
+
+ if "default" in attributes:
+ if "fixed" in attributes:
+ raise ValueError, "\"default\" and \"fixed\" can't be defined at the same time!"
+ elif attributes.get("use", "optional") != "optional":
+ raise ValueError, "if \"default\" present, \"use\" can only have the value \"optional\"!"
+
+ attribute = {"type" : ATTRIBUTE, "attr_type" : attributes.get("type", None), "doc" : annotations}
+ if len(children) > 0:
+ if attribute["attr_type"] is None:
+ attribute["attr_type"] = children[0]
+ else:
+ raise ValueError, "Only one type can be defined for attribute!"
+
+ if "ref" in attributes:
+ if "name" in attributes:
+ raise ValueError, "\"ref\" and \"name\" can't be defined at the same time!"
+ elif "form" in attributes:
+ raise ValueError, "\"ref\" and \"form\" can't be defined at the same time!"
+ elif attribute["attr_type"] is not None:
+ raise ValueError, "if \"ref\" is present, no type can be defined!"
+ elif attribute["attr_type"] is None:
+ raise ValueError, "No type has been defined for attribute!"
+
+ if "type" in attributes:
+ tmp_attrs = attributes.copy()
+ tmp_attrs.pop("type")
+ attribute.update(tmp_attrs)
+ else:
+ attribute.update(attributes)
+ return attribute
+
+
+def ReduceAttributeGroup(factory, attributes, elements):
+ annotations, children = factory.ReduceElements(elements)
+ if "ref" in attributes:
+ return {"type" : "attributeGroup", "ref" : attributes["ref"], "doc" : annotations}
+ else:
+ return {"type" : ATTRIBUTESGROUP, "attributes" : ExtractAttributes(factory, children), "doc" : annotations}
+
+
+# Elements groups
+
+def ReduceAny(factory, attributes, elements):
+ annotations, children = factory.ReduceElements(elements)
+
+ any = {"type" : ANY, "doc" : annotations}
+ any.update(attributes)
+ return any
+
+def ReduceElement(factory, attributes, elements):
+ if "default" in attributes and "fixed" in attributes:
+ raise ValueError, "\"default\" and \"fixed\" can't be defined at the same time!"
+
+ if "ref" in attributes:
+ annotations, children = factory.ReduceElements(elements)
+
+ for attr in ["name", "default", "fixed", "form", "block", "type"]:
+ if attr in attributes:
+ raise ValueError, "\"ref\" and \"%s\" can't be defined at the same time!"%attr
+ if attributes.get("nillable", False):
+ raise ValueError, "\"ref\" and \"nillable\" can't be defined at the same time!"
+ if len(children) > 0:
+ raise ValueError, "No type and no constraints can be defined where \"ref\" is defined!"
+
+ infos = factory.FindSchemaElement(attributes["ref"], ELEMENT)
+ if infos is not None:
+ element = infos.copy()
+ element["minOccurs"] = attributes["minOccurs"]
+ element["maxOccurs"] = attributes["maxOccurs"]
+ return element
+ else:
+ raise ValueError, "\"%s\" base type isn't defined or circular referenced!"%name
+
+ elif "name" in attributes:
+ annotations, children = factory.ReduceElements(elements)
+
+ element = {"type" : ELEMENT, "elmt_type" : attributes.get("type", None), "doc" : annotations}
+ if len(children) > 0:
+ if element["elmt_type"] is None:
+ element["elmt_type"] = children[0]
+ else:
+ raise ValueError, "Only one type can be defined for attribute!"
+ elif element["elmt_type"] is None:
+ element["elmt_type"] = "tag"
+ element["type"] = TAG
+
+ if "type" in attributes:
+ tmp_attrs = attributes.copy()
+ tmp_attrs.pop("type")
+ element.update(tmp_attrs)
+ else:
+ element.update(attributes)
+ return element
+ else:
+ raise ValueError, "\"Element\" must have at least a \"ref\" or a \"name\" defined!"
+
+def ReduceAll(factory, attributes, elements):
+ annotations, children = factory.ReduceElements(elements)
+
+ for child in children:
+ if children["maxOccurs"] == "unbounded" or children["maxOccurs"] > 1:
+ raise ValueError, "\"all\" item can't have \"maxOccurs\" attribute greater than 1!"
+
+ return {"type" : "all", "elements" : children, "minOccurs" : attributes["minOccurs"],
+ "maxOccurs" : attributes["maxOccurs"], "order" : False, "doc" : annotations}
+
+
+def ReduceChoice(factory, attributes, elements):
+ annotations, children = factory.ReduceElements(elements)
+
+ choices = []
+ for child in children:
+ if child["type"] in [ELEMENT, ANY, TAG]:
+ choices.append(child)
+ elif child["type"] == "sequence":
+ raise ValueError, "\"sequence\" in \"choice\" is not supported. Create instead a new complex type!"
+ elif child["type"] == CHOICE:
+ choices.extend(child["choices"])
+ elif child["type"] == "group":
+ elmtgroup = factory.FindSchemaElement(child["ref"], ELEMENTSGROUP)
+ if "choices" not in elmtgroup:
+ raise ValueError, "Only group composed of \"choice\" can be referenced in \"choice\" element!"
+ choices_tmp = []
+ for choice in elmtgroup["choices"]:
+ if not isinstance(choice["elmt_type"], (UnicodeType, StringType)) and choice["elmt_type"]["type"] == COMPLEXTYPE:
+ elmt_type = "%s_%s"%(elmtgroup["name"], choice["name"])
+ if factory.TargetNamespace is not None:
+ elmt_type = "%s:%s"%(factory.TargetNamespace, elmt_type)
+ new_choice = choice.copy()
+ new_choice["elmt_type"] = elmt_type
+ choices_tmp.append(new_choice)
+ else:
+ choices_tmp.append(choice)
+ choices.extend(choices_tmp)
+
+ return {"type" : CHOICE, "choices" : choices, "minOccurs" : attributes["minOccurs"],
+ "maxOccurs" : attributes["maxOccurs"], "doc" : annotations}
+
+
+def ReduceSequence(factory, attributes, elements):
+ annotations, children = factory.ReduceElements(elements)
+
+ sequence = []
+ for child in children:
+ if child["type"] in [ELEMENT, ANY, TAG]:
+ sequence.append(child)
+ elif child["type"] == CHOICE:
+ content = child.copy()
+ content["name"] = "content"
+ sequence.append(content)
+ elif child["type"] == "sequence":
+ sequence.extend(child["elements"])
+ elif child["type"] == "group":
+ elmtgroup = factory.FindSchemaElement(child["ref"], ELEMENTSGROUP)
+ if "elements" not in elmtgroup or not elmtgroup["order"]:
+ raise ValueError, "Only group composed of \"sequence\" can be referenced in \"sequence\" element!"
+ elements_tmp = []
+ for element in elmtgroup["elements"]:
+ if not isinstance(element["elmt_type"], (UnicodeType, StringType)) and element["elmt_type"]["type"] == COMPLEXTYPE:
+ elmt_type = "%s_%s"%(elmtgroup["name"], element["name"])
+ if factory.TargetNamespace is not None:
+ elmt_type = "%s:%s"%(factory.TargetNamespace, elmt_type)
+ new_element = element.copy()
+ new_element["elmt_type"] = elmt_type
+ elements_tmp.append(new_element)
+ else:
+ elements_tmp.append(element)
+ sequence.extend(elements_tmp)
+
+ return {"type" : "sequence", "elements" : sequence, "minOccurs" : attributes["minOccurs"],
+ "maxOccurs" : attributes["maxOccurs"], "order" : True, "doc" : annotations}
+
+
+def ReduceGroup(factory, attributes, elements):
+ annotations, children = factory.ReduceElements(elements)
+
+ if "ref" in attributes:
+ return {"type" : "group", "ref" : attributes["ref"], "doc" : annotations}
+ else:
+ element = children[0]
+ group = {"type" : ELEMENTSGROUP, "doc" : annotations}
+ if element["type"] == CHOICE:
+ group["choices"] = element["choices"]
+ else:
+ group.update({"elements" : element["elements"], "order" : group["order"]})
+ group.update(attributes)
+ return group
+
+# Constraint elements
+
+def ReduceUnique(factory, attributes, elements):
+ annotations, children = factory.ReduceElements(elements)
+ raise ValueError, "\"unique\" element isn't supported yet!"
+
+def ReduceKey(factory, attributes, elements):
+ annotations, children = factory.ReduceElements(elements)
+ raise ValueError, "\"key\" element isn't supported yet!"
+
+def ReduceKeyRef(factory, attributes, elements):
+ annotations, children = factory.ReduceElements(elements)
+ raise ValueError, "\"keyref\" element isn't supported yet!"
+
+def ReduceSelector(factory, attributes, elements):
+ annotations, children = factory.ReduceElements(elements)
+ raise ValueError, "\"selector\" element isn't supported yet!"
+
+def ReduceField(factory, attributes, elements):
+ annotations, children = factory.ReduceElements(elements)
+ raise ValueError, "\"field\" element isn't supported yet!"
+
+
+# Inclusion elements
+
+def ReduceImport(factory, attributes, elements):
+ annotations, children = factory.ReduceElements(elements)
+ raise ValueError, "\"import\" element isn't supported yet!"
+
+def ReduceInclude(factory, attributes, elements):
+ annotations, children = factory.ReduceElements(elements)
+ raise ValueError, "\"include\" element isn't supported yet!"
+
+def ReduceRedefine(factory, attributes, elements):
+ annotations, children = factory.ReduceElements(elements)
+ raise ValueError, "\"redefine\" element isn't supported yet!"
+
+
+# Schema element
+
+def ReduceSchema(factory, attributes, elements):
+ factory.AttributeFormDefault = attributes["attributeFormDefault"]
+ factory.ElementFormDefault = attributes["elementFormDefault"]
+ factory.BlockDefault = attributes["blockDefault"]
+ factory.FinalDefault = attributes["finalDefault"]
+
+ if "targetNamespace" in attributes:
+ factory.TargetNamespace = factory.DefinedNamespaces.get(attributes["targetNamespace"], None)
+ factory.Namespaces[factory.TargetNamespace] = {}
+
+ annotations, children = factory.ReduceElements(elements, True)
+
+ for child in children:
+ if "name" in child:
+ infos = factory.GetQualifiedNameInfos(child["name"], factory.TargetNamespace, True)
+ if infos is None:
+ factory.Namespaces[factory.TargetNamespace][child["name"]] = child
+ elif not CompareSchema(infos, child):
+ raise ValueError, "\"%s\" is defined twice in targetNamespace!"%child["name"]
+
+def CompareSchema(schema, reference):
+ if isinstance(schema, ListType):
+ if not isinstance(reference, ListType) or len(schema) != len(reference):
+ return False
+ for i, value in enumerate(schema):
+ result = CompareSchema(value, reference[i])
+ if not result:
+ return result
+ return True
+ elif isinstance(schema, DictType):
+ if not isinstance(reference, DictType) or len(schema) != len(reference):
+ return False
+ for name, value in schema.items():
+ ref_value = reference.get(name, None)
+ if ref_value is None:
+ return False
+ result = CompareSchema(value, ref_value)
+ if not result:
+ return result
+ return True
+ elif isinstance(schema, FunctionType):
+ if not isinstance(reference, FunctionType) or schema.__name__ != reference.__name__:
+ return False
+ else:
+ return True
+ return schema == reference
+
+#-------------------------------------------------------------------------------
+# Base class for XSD schema extraction
+#-------------------------------------------------------------------------------
+
+
+class XSDClassFactory(ClassFactory):
+
+ def __init__(self, document, debug = False):
+ ClassFactory.__init__(self, document, debug)
+ self.Namespaces["xml"] = {
+ "lang" : {
+ "type" : SYNTAXATTRIBUTE,
+ "extract" : {
+ "default" : GenerateEnumeratedExtraction("lang", LANGUAGES)
+ }
+ }
+ }
+ self.Namespaces["xsi"] = {
+ "noNamespaceSchemaLocation" : {
+ "type" : SYNTAXATTRIBUTE,
+ "extract" : {
+ "default" : NotSupportedYet("noNamespaceSchemaLocation")
+ }
+ },
+ "nil" : {
+ "type" : SYNTAXATTRIBUTE,
+ "extract" : {
+ "default" : NotSupportedYet("nil")
+ }
+ },
+ "schemaLocation" : {
+ "type" : SYNTAXATTRIBUTE,
+ "extract" : {
+ "default" : NotSupportedYet("schemaLocation")
+ }
+ },
+ "type" : {
+ "type" : SYNTAXATTRIBUTE,
+ "extract" : {
+ "default" : NotSupportedYet("type")
+ }
+ }
+ }
+
+ def ParseSchema(self):
+ schema = self.Document.childNodes[0]
+ for qualified_name, attr in schema._attrs.items():
+ value = GetAttributeValue(attr)
+ if value == "http://www.w3.org/2001/XMLSchema":
+ namespace, name = DecomposeQualifiedName(qualified_name)
+ if namespace == "xmlns":
+ self.DefinedNamespaces["http://www.w3.org/2001/XMLSchema"] = name
+ self.SchemaNamespace = name
+ else:
+ self.DefinedNamespaces["http://www.w3.org/2001/XMLSchema"] = self.SchemaNamespace
+ self.Namespaces[self.SchemaNamespace] = XSD_NAMESPACE
+ self.Schema = XSD_NAMESPACE["schema"]["extract"]["default"](self, schema)
+ ReduceSchema(self, self.Schema[1], self.Schema[2])
+
+ def FindSchemaElement(self, element_name, element_type):
+ namespace, name = DecomposeQualifiedName(element_name)
+ element = self.GetQualifiedNameInfos(name, namespace, True)
+ if element is None and namespace == self.TargetNamespace and name not in self.CurrentCompilations:
+ self.CurrentCompilations.append(name)
+ element = self.CreateSchemaElement(name, element_type)
+ self.CurrentCompilations.pop(-1)
+ if element is not None:
+ self.Namespaces[self.TargetNamespace][name] = element
+ if element is None:
+ if name in self.CurrentCompilations:
+ if self.Debug:
+ print "Warning : \"%s\" is circular referenced!"%element_name
+ return element_name
+ else:
+ raise ValueError, "\"%s\" isn't defined!"%element_name
+ if element["type"] != element_type:
+ raise ValueError, "\"%s\" isn't a group!"%element_name
+ return element
+
+ def CreateSchemaElement(self, element_name, element_type):
+ for type, attributes, elements in self.Schema[2]:
+ namespace, name = DecomposeQualifiedName(type)
+ if "name" in attributes and attributes["name"] == element_name:
+ element_infos = None
+ if element_type == ATTRIBUTE and name == "attribute":
+ element_infos = ReduceAttribute(self, attributes, elements)
+ elif element_type == ELEMENT and name == "element":
+ element_infos = ReduceElement(self, attributes, elements)
+ elif element_type == ATTRIBUTESGROUP and name == "attributeGroup":
+ element_infos = ReduceAttributeGroup(self, attributes, elements)
+ elif element_type == ELEMENTSGROUP and name == "group":
+ element_infos = ReduceGroup(self, attributes, elements)
+ elif element_type == SIMPLETYPE and name == "simpleType":
+ element_infos = ReduceSimpleType(self, attributes, elements)
+ elif element_type == COMPLEXTYPE and name == "complexType":
+ element_infos = ReduceComplexType(self, attributes, elements)
+ if element_infos is not None:
+ self.Namespaces[self.TargetNamespace][element_name] = element_infos
+ return element_infos
+ return None
+
+"""
+This function opens the xsd file and generate the classes from the xml tree
+"""
+def GenerateClassesFromXSD(filename, declare = False):
+ xsdfile = open(filename, 'r')
+ factory = XSDClassFactory(minidom.parse(xsdfile))
+ xsdfile.close()
+ factory.ParseSchema()
+ return GenerateClasses(factory, declare)
+
+"""
+This function generate the classes from the xsd given as a string
+"""
+def GenerateClassesFromXSDstring(xsdstring, declare = False):
+ factory = XSDClassFactory(minidom.parseString(xsdstring))
+ factory.ParseSchema()
+ return GenerateClasses(factory, declare)
+
+
+#-------------------------------------------------------------------------------
+# XSD schema syntax elements
+#-------------------------------------------------------------------------------
+
+XSD_NAMESPACE = {
+
+#-------------------------------------------------------------------------------
+# Syntax elements definition
+#-------------------------------------------------------------------------------
+
+ "all" : {"struct" : """
+ <all
+ id = ID
+ maxOccurs = 1 : 1
+ minOccurs = (0 | 1) : 1
+ {any attributes with non-schema namespace . . .}>
+ Content: (annotation?, element*)
+ </all>""",
+ "type" : SYNTAXELEMENT,
+ "extract" : {
+ "default" : GenerateElement("all", ["id", "maxOccurs", "minOccurs"],
+ re.compile("((?:annotation )?(?:element )*)"))
+ },
+ "reduce" : ReduceAll
+ },
+
+ "annotation" : {"struct" : """
+ <annotation
+ id = ID
+ {any attributes with non-schema namespace . . .}>
+ Content: (appinfo | documentation)*
+ </annotation>""",
+ "type" : SYNTAXELEMENT,
+ "extract" : {
+ "default" : GenerateElement("annotation", ["id"],
+ re.compile("((?:app_info |documentation )*)"))
+ },
+ "reduce" : ReduceAnnotation
+ },
+
+ "any" : {"struct": """
+ <any
+ id = ID
+ maxOccurs = (nonNegativeInteger | unbounded) : 1
+ minOccurs = nonNegativeInteger : 1
+ namespace = ((##any | ##other) | List of (anyURI | (##targetNamespace | ##local)) ) : ##any
+ processContents = (lax | skip | strict) : strict
+ {any attributes with non-schema namespace . . .}>
+ Content: (annotation?)
+ </any>""",
+ "type" : SYNTAXELEMENT,
+ "extract" : {
+ "default" : GenerateElement("any",
+ ["id", "maxOccurs", "minOccurs", "namespace", "processContents"],
+ re.compile("((?:annotation )?(?:simpleType )*)"))
+ },
+ "reduce" : ReduceAny
+ },
+
+ "anyAttribute" : {"struct" : """
+ <anyAttribute
+ id = ID
+ namespace = ((##any | ##other) | List of (anyURI | (##targetNamespace | ##local)) ) : ##any
+ processContents = (lax | skip | strict) : strict
+ {any attributes with non-schema namespace . . .}>
+ Content: (annotation?)
+ </anyAttribute>""",
+ "type" : SYNTAXELEMENT,
+ "extract" : {
+ "default" : GenerateElement("anyAttribute",
+ ["id", "namespace", "processContents"], ONLY_ANNOTATION)
+ },
+ "reduce" : ReduceAnyAttribute
+ },
+
+ "appinfo" : {"struct" : """
+ <appinfo
+ source = anyURI
+ {any attributes with non-schema namespace . . .}>
+ Content: ({any})*
+ </appinfo>""",
+ "type" : SYNTAXELEMENT,
+ "extract" : {
+ "default" : GenerateElement("appinfo", ["source"], re.compile("(.*)"), True)
+ },
+ "reduce" : ReduceAppInfo
+ },
+
+ "attribute" : {"struct" : """
+ <attribute
+ default = string
+ fixed = string
+ form = (qualified | unqualified)
+ id = ID
+ name = NCName
+ ref = QName
+ type = QName
+ use = (optional | prohibited | required) : optional
+ {any attributes with non-schema namespace . . .}>
+ Content: (annotation?, simpleType?)
+ </attribute>""",
+ "type" : SYNTAXELEMENT,
+ "extract" : {
+ "default" : GenerateElement("attribute",
+ ["default", "fixed", "form", "id", "name", "ref", "type", "use"],
+ re.compile("((?:annotation )?(?:simpleType )?)")),
+ "schema" : GenerateElement("attribute",
+ ["default", "fixed", "form", "id", "name", "type"],
+ re.compile("((?:annotation )?(?:simpleType )?)"))
+ },
+ "reduce" : ReduceAttribute
+ },
+
+ "attributeGroup" : {"struct" : """
+ <attributeGroup
+ id = ID
+ name = NCName
+ ref = QName
+ {any attributes with non-schema namespace . . .}>
+ Content: (annotation?, ((attribute | attributeGroup)*, anyAttribute?))
+ </attributeGroup>""",
+ "type" : SYNTAXELEMENT,
+ "extract" : {
+ "default" : GenerateElement("attributeGroup",
+ ["id", "ref"], ONLY_ANNOTATION),
+ "schema" : GenerateElement("attributeGroup",
+ ["id", "name"],
+ re.compile("((?:annotation )?(?:(?:attribute |attributeGroup )*(?:anyAttribute )?))"))
+ },
+ "reduce" : ReduceAttributeGroup
+ },
+
+ "choice" : {"struct" : """
+ <choice
+ id = ID
+ maxOccurs = (nonNegativeInteger | unbounded) : 1
+ minOccurs = nonNegativeInteger : 1
+ {any attributes with non-schema namespace . . .}>
+ Content: (annotation?, (element | group | choice | sequence | any)*)
+ </choice>""",
+ "type" : SYNTAXELEMENT,
+ "extract" : {
+ "default" : GenerateElement("choice", ["id", "maxOccurs", "minOccurs"],
+ re.compile("((?:annotation )?(?:element |group |choice |sequence |any )*)"))
+ },
+ "reduce" : ReduceChoice
+ },
+
+ "complexContent" : {"struct" : """
+ <complexContent
+ id = ID
+ mixed = boolean
+ {any attributes with non-schema namespace . . .}>
+ Content: (annotation?, (restriction | extension))
+ </complexContent>""",
+ "type" : SYNTAXELEMENT,
+ "extract" : {
+ "default" : GenerateElement("complexContent", ["id", "mixed"],
+ re.compile("((?:annotation )?(?:restriction |extension ))"))
+ },
+ "reduce" : ReduceComplexContent
+ },
+
+ "complexType" : {"struct" : """
+ <complexType
+ abstract = boolean : false
+ block = (#all | List of (extension | restriction))
+ final = (#all | List of (extension | restriction))
+ id = ID
+ mixed = boolean : false
+ name = NCName
+ {any attributes with non-schema namespace . . .}>
+ Content: (annotation?, (simpleContent | complexContent | ((group | all | choice | sequence)?, ((attribute | attributeGroup)*, anyAttribute?))))
+ </complexType>""",
+ "type" : SYNTAXELEMENT,
+ "extract" : {
+ "default" : GenerateElement("complexType",
+ ["abstract", "block", "final", "id", "mixed", "name"],
+ re.compile("((?:annotation )?(?:simpleContent |complexContent |(?:(?:group |all |choice |sequence )?(?:(?:attribute |attributeGroup )*(?:anyAttribute )?))))"))
+ },
+ "reduce" : ReduceComplexType
+ },
+
+ "documentation" : {"struct" : """
+ <documentation
+ source = anyURI
+ xml:lang = language
+ {any attributes with non-schema namespace . . .}>
+ Content: ({any})*
+ </documentation>""",
+ "type" : SYNTAXELEMENT,
+ "extract" : {
+ "default" : GenerateElement("documentation",
+ ["source", "lang"], re.compile("(.*)"), True)
+ },
+ "reduce" : ReduceDocumentation
+ },
+
+ "element" : {"struct" : """
+ <element
+ abstract = boolean : false
+ block = (#all | List of (extension | restriction | substitution))
+ default = string
+ final = (#all | List of (extension | restriction))
+ fixed = string
+ form = (qualified | unqualified)
+ id = ID
+ maxOccurs = (nonNegativeInteger | unbounded) : 1
+ minOccurs = nonNegativeInteger : 1
+ name = NCName
+ nillable = boolean : false
+ ref = QName
+ substitutionGroup = QName
+ type = QName
+ {any attributes with non-schema namespace . . .}>
+ Content: (annotation?, ((simpleType | complexType)?, (unique | key | keyref)*))
+ </element>""",
+ "type" : SYNTAXELEMENT,
+ "extract" : {
+ "default" : GenerateElement("element",
+ ["abstract", "block", "default", "final", "fixed", "form", "id", "maxOccurs", "minOccurs", "name", "nillable", "ref", "substitutionGroup", "type"],
+ re.compile("((?:annotation )?(?:simpleType |complexType )?(?:unique |key |keyref )*)")),
+ "schema" : GenerateElement("element",
+ ["abstract", "block", "default", "final", "fixed", "form", "id", "name", "nillable", "substitutionGroup", "type"],
+ re.compile("((?:annotation )?(?:simpleType |complexType )?(?:unique |key |keyref )*)"))
+ },
+ "reduce" : ReduceElement
+ },
+
+ "enumeration" : {"struct" : """
+ <enumeration
+ id = ID
+ value = anySimpleType
+ {any attributes with non-schema namespace . . .}>
+ Content: (annotation?)
+ </enumeration>""",
+ "type" : SYNTAXELEMENT,
+ "extract" : {
+ "default" : GenerateElement("enumeration", ["id", "value"], ONLY_ANNOTATION)
+ },
+ "reduce" : GenerateFacetReducing("enumeration", False)
+ },
+
+ "extension" : {"struct" : """
+ <extension
+ base = QName
+ id = ID
+ {any attributes with non-schema namespace . . .}>
+ Content: (annotation?, ((group | all | choice | sequence)?, ((attribute | attributeGroup)*, anyAttribute?)))
+ </extension>""",
+ "type" : SYNTAXELEMENT,
+ "extract" : {
+ "default" : GenerateElement("extension", ["base", "id"],
+ re.compile("((?:annotation )?(?:(?:attribute |attributeGroup )*(?:anyAttribute )?))")),
+ "complexContent" : GenerateElement("extension", ["base", "id"],
+ re.compile("((?:annotation )?(?:group |all |choice |sequence )?(?:(?:attribute |attributeGroup )*(?:anyAttribute )?))"))
+ },
+ "reduce" : ReduceExtension
+ },
+
+ "field" : {"struct" : """
+ <field
+ id = ID
+ xpath = a subset of XPath expression, see below
+ {any attributes with non-schema namespace . . .}>
+ Content: (annotation?)
+ </field>""",
+ "type" : SYNTAXELEMENT,
+ "extract" : {
+ "default" : GenerateElement("field", ["id", "xpath"], ONLY_ANNOTATION)
+ },
+ "reduce" : ReduceField
+ },
+
+ "fractionDigits" : {"struct" : """
+ <fractionDigits
+ fixed = boolean : false
+ id = ID
+ value = nonNegativeInteger
+ {any attributes with non-schema namespace . . .}>
+ Content: (annotation?)
+ </fractionDigits>""",
+ "type" : SYNTAXELEMENT,
+ "extract" : {
+ "default" : GenerateElement("fractionDigits",
+ ["fixed", "id", "value"], ONLY_ANNOTATION)
+ },
+ "reduce" : GenerateFacetReducing("fractionDigits", True)
+ },
+
+ "group" : {"struct" : """
+ <group
+ id = ID
+ maxOccurs = (nonNegativeInteger | unbounded) : 1
+ minOccurs = nonNegativeInteger : 1
+ name = NCName
+ ref = QName
+ {any attributes with non-schema namespace . . .}>
+ Content: (annotation?, (all | choice | sequence)?)
+ </group>""",
+ "type" : SYNTAXELEMENT,
+ "extract" : {
+ "default" : GenerateElement("group",
+ ["id", "maxOccurs", "minOccurs", "ref"],
+ re.compile("((?:annotation )?(?:all |choice |sequence )?)")),
+ "schema" : GenerateElement("group",
+ ["id", "name"],
+ re.compile("((?:annotation )?(?:all |choice |sequence )?)"))
+ },
+ "reduce" : ReduceGroup
+ },
+
+ "import" : {"struct" : """
+ <import
+ id = ID
+ namespace = anyURI
+ schemaLocation = anyURI
+ {any attributes with non-schema namespace . . .}>
+ Content: (annotation?)
+ </import>""",
+ "type" : SYNTAXELEMENT,
+ "extract" : {
+ "default" : GenerateElement("import",
+ ["id", "namespace", "schemaLocation"], ONLY_ANNOTATION)
+ },
+ "reduce" : ReduceImport
+ },
+
+ "include" : {"struct" : """
+ <include
+ id = ID
+ schemaLocation = anyURI
+ {any attributes with non-schema namespace . . .}>
+ Content: (annotation?)
+ </include>""",
+ "type" : SYNTAXELEMENT,
+ "extract" : {
+ "default" : GenerateElement("include",
+ ["id", "schemaLocation"], ONLY_ANNOTATION)
+ },
+ "reduce" : ReduceInclude
+ },
+
+ "key" : {"struct" : """
+ <key
+ id = ID
+ name = NCName
+ {any attributes with non-schema namespace . . .}>
+ Content: (annotation?, (selector, field+))
+ </key>""",
+ "type" : SYNTAXELEMENT,
+ "extract" : {
+ "default" : GenerateElement("key", ["id", "name"],
+ re.compile("((?:annotation )?(?:selector |(?:field )+))"))
+ },
+ "reduce" : ReduceKey
+ },
+
+ "keyref" : {"struct" : """
+ <keyref
+ id = ID
+ name = NCName
+ refer = QName
+ {any attributes with non-schema namespace . . .}>
+ Content: (annotation?, (selector, field+))
+ </keyref>""",
+ "type" : SYNTAXELEMENT,
+ "extract" : {
+ "default" : GenerateElement("keyref", ["id", "name", "refer"],
+ re.compile("((?:annotation )?(?:selector |(?:field )+))"))
+ },
+ "reduce" : ReduceKeyRef
+ },
+
+ "length" : {"struct" : """
+ <length
+ fixed = boolean : false
+ id = ID
+ value = nonNegativeInteger
+ {any attributes with non-schema namespace . . .}>
+ Content: (annotation?)
+ </length>""",
+ "type" : SYNTAXELEMENT,
+ "extract" : {
+ "default" : GenerateElement("length",
+ ["fixed", "id", "value"], ONLY_ANNOTATION)
+ },
+ "reduce" : GenerateFacetReducing("length", True)
+ },
+
+ "list" : {"struct" : """
+ <list
+ id = ID
+ itemType = QName
+ {any attributes with non-schema namespace . . .}>
+ Content: (annotation?, simpleType?)
+ </list>""",
+ "type" : SYNTAXELEMENT,
+ "extract" : {
+ "default" : GenerateElement("list", ["id", "itemType"],
+ re.compile("((?:annotation )?(?:simpleType )?)$"))
+ },
+ "reduce" : ReduceList
+ },
+
+ "maxExclusive" : {"struct" : """
+ <maxInclusive
+ fixed = boolean : false
+ id = ID
+ value = anySimpleType
+ {any attributes with non-schema namespace . . .}>
+ Content: (annotation?)
+ </maxInclusive>""",
+ "type" : SYNTAXELEMENT,
+ "extract" : {
+ "default" : GenerateElement("maxExclusive",
+ ["fixed", "id", "value"], ONLY_ANNOTATION)
+ },
+ "reduce" : GenerateFacetReducing("maxExclusive", True)
+ },
+
+ "maxInclusive" : {"struct" : """
+ <maxExclusive
+ fixed = boolean : false
+ id = ID
+ value = anySimpleType
+ {any attributes with non-schema namespace . . .}>
+ Content: (annotation?)
+ </maxExclusive>""",
+ "type" : SYNTAXELEMENT,
+ "extract" : {
+ "default" : GenerateElement("maxInclusive",
+ ["fixed", "id", "value"], ONLY_ANNOTATION)
+ },
+ "reduce" : GenerateFacetReducing("maxInclusive", True)
+ },
+
+ "maxLength" : {"struct" : """
+ <maxLength
+ fixed = boolean : false
+ id = ID
+ value = nonNegativeInteger
+ {any attributes with non-schema namespace . . .}>
+ Content: (annotation?)
+ </maxLength>""",
+ "type" : SYNTAXELEMENT,
+ "extract" : {
+ "default" : GenerateElement("maxLength",
+ ["fixed", "id", "value"], ONLY_ANNOTATION)
+ },
+ "reduce" : GenerateFacetReducing("maxLength", True)
+ },
+
+ "minExclusive" : {"struct" : """
+ <minExclusive
+ fixed = boolean : false
+ id = ID
+ value = anySimpleType
+ {any attributes with non-schema namespace . . .}>
+ Content: (annotation?)
+ </minExclusive>""",
+ "type" : SYNTAXELEMENT,
+ "extract" : {
+ "default" : GenerateElement("minExclusive",
+ ["fixed", "id", "value"], ONLY_ANNOTATION)
+ },
+ "reduce" : GenerateFacetReducing("minExclusive", True)
+ },
+
+ "minInclusive" : {"struct" : """
+ <minInclusive
+ fixed = boolean : false
+ id = ID
+ value = anySimpleType
+ {any attributes with non-schema namespace . . .}>
+ Content: (annotation?)
+ </minInclusive>""",
+ "type" : SYNTAXELEMENT,
+ "extract" : {
+ "default" : GenerateElement("minInclusive",
+ ["fixed", "id", "value"], ONLY_ANNOTATION)
+ },
+ "reduce" : GenerateFacetReducing("minInclusive", True)
+ },
+
+ "minLength" : {"struct" : """
+ <minLength
+ fixed = boolean : false
+ id = ID
+ value = nonNegativeInteger
+ {any attributes with non-schema namespace . . .}>
+ Content: (annotation?)
+ </minLength>""",
+ "type" : SYNTAXELEMENT,
+ "extract" : {
+ "default" : GenerateElement("minLength",
+ ["fixed", "id", "value"], ONLY_ANNOTATION)
+ },
+ "reduce" : GenerateFacetReducing("minLength", True)
+ },
+
+ "pattern" : {"struct" : """
+ <pattern
+ id = ID
+ value = string
+ {any attributes with non-schema namespace . . .}>
+ Content: (annotation?)
+ </pattern>""",
+ "type" : SYNTAXELEMENT,
+ "extract" : {
+ "default" : GenerateElement("pattern", ["id", "value"], ONLY_ANNOTATION)
+ },
+ "reduce" : GenerateFacetReducing("pattern", False)
+ },
+
+ "redefine" : {"struct" : """
+ <redefine
+ id = ID
+ schemaLocation = anyURI
+ {any attributes with non-schema namespace . . .}>
+ Content: (annotation | (simpleType | complexType | group | attributeGroup))*
+ </redefine>""",
+ "type" : SYNTAXELEMENT,
+ "extract" : {
+ "default" : GenerateElement("refine", ["id", "schemaLocation"],
+ re.compile("((?:annotation |(?:simpleType |complexType |group |attributeGroup ))*)"))
+ },
+ "reduce" : ReduceRedefine
+ },
+
+ "restriction" : {"struct" : """
+ <restriction
+ base = QName
+ id = ID
+ {any attributes with non-schema namespace . . .}>
+ Content: (annotation?, (group | all | choice | sequence)?, ((attribute | attributeGroup)*, anyAttribute?))
+ </restriction>""",
+ "type" : SYNTAXELEMENT,
+ "extract" : {
+ "default" : GenerateElement("restriction", ["base", "id"],
+ re.compile("((?:annotation )?(?:(?:simpleType )?(?:(?:minExclusive |minInclusive |maxExclusive |maxInclusive |totalDigits |fractionDigits |length |minLength |maxLength |enumeration |whiteSpace |pattern )*)))")),
+ "simpleContent" : GenerateElement("restriction", ["base", "id"],
+ re.compile("((?:annotation )?(?:(?:simpleType )?(?:(?:minExclusive |minInclusive |maxExclusive |maxInclusive |totalDigits |fractionDigits |length |minLength |maxLength |enumeration |whiteSpace |pattern )*)?(?:(?:attribute |attributeGroup )*(?:anyAttribute )?)))")),
+ "complexContent" : GenerateElement("restriction", ["base", "id"],
+ re.compile("((?:annotation )?(?:(?:simpleType )?(?:group |all |choice |sequence )?(?:(?:attribute |attributeGroup )*(?:anyAttribute )?)))")),
+ },
+ "reduce" : ReduceRestriction
+ },
+
+ "schema" : {"struct" : """
+ <schema
+ attributeFormDefault = (qualified | unqualified) : unqualified
+ blockDefault = (#all | List of (extension | restriction | substitution)) : ''
+ elementFormDefault = (qualified | unqualified) : unqualified
+ finalDefault = (#all | List of (extension | restriction | list | union)) : ''
+ id = ID
+ targetNamespace = anyURI
+ version = token
+ xml:lang = language
+ {any attributes with non-schema namespace . . .}>
+ Content: ((include | import | redefine | annotation)*, (((simpleType | complexType | group | attributeGroup) | element | attribute | notation), annotation*)*)
+ </schema>""",
+ "type" : SYNTAXELEMENT,
+ "extract" : {
+ "default" : GenerateElement("schema",
+ ["attributeFormDefault", "blockDefault", "elementFormDefault", "finalDefault", "id", "targetNamespace", "version", "lang"],
+ re.compile("((?:include |import |redefine |annotation )*(?:(?:(?:simpleType |complexType |group |attributeGroup )|element |attribute |annotation )(?:annotation )*)*)"))
+ }
+ },
+
+ "selector" : {"struct" : """
+ <selector
+ id = ID
+ xpath = a subset of XPath expression, see below
+ {any attributes with non-schema namespace . . .}>
+ Content: (annotation?)
+ </selector>""",
+ "type" : SYNTAXELEMENT,
+ "extract" : {
+ "default" : GenerateElement("selector", ["id", "xpath"], ONLY_ANNOTATION)
+ },
+ "reduce" : ReduceSelector
+ },
+
+ "sequence" : {"struct" : """
+ <sequence
+ id = ID
+ maxOccurs = (nonNegativeInteger | unbounded) : 1
+ minOccurs = nonNegativeInteger : 1
+ {any attributes with non-schema namespace . . .}>
+ Content: (annotation?, (element | group | choice | sequence | any)*)
+ </sequence>""",
+ "type" : SYNTAXELEMENT,
+ "extract" : {
+ "default" : GenerateElement("sequence", ["id", "maxOccurs", "minOccurs"],
+ re.compile("((?:annotation )?(?:element |group |choice |sequence |any )*)"))
+ },
+ "reduce" : ReduceSequence
+ },
+
+ "simpleContent" : {"struct" : """
+ <simpleContent
+ id = ID
+ {any attributes with non-schema namespace . . .}>
+ Content: (annotation?, (restriction | extension))
+ </simpleContent>""",
+ "type" : SYNTAXELEMENT,
+ "extract" : {
+ "default" : GenerateElement("simpleContent", ["id"],
+ re.compile("((?:annotation )?(?:restriction |extension ))"))
+ },
+ "reduce" : ReduceSimpleContent
+ },
+
+ "simpleType" : {"struct" : """
+ <simpleType
+ final = (#all | List of (list | union | restriction))
+ id = ID
+ name = NCName
+ {any attributes with non-schema namespace . . .}>
+ Content: (annotation?, (restriction | list | union))
+ </simpleType>""",
+ "type" : SYNTAXELEMENT,
+ "extract" : {
+ "default" : GenerateElement("simpleType", ["final", "id", "name"],
+ re.compile("((?:annotation )?(?:restriction |list |union ))"))
+ },
+ "reduce" : ReduceSimpleType
+ },
+
+ "totalDigits" : {"struct" : """
+ <totalDigits
+ fixed = boolean : false
+ id = ID
+ value = positiveInteger
+ {any attributes with non-schema namespace . . .}>
+ Content: (annotation?)
+ </totalDigits>""",
+ "type" : SYNTAXELEMENT,
+ "extract" : {
+ "default" : GenerateElement("totalDigits",
+ ["fixed", "id", "value"], ONLY_ANNOTATION),
+ },
+ "reduce" : GenerateFacetReducing("totalDigits", True)
+ },
+
+ "union" : {"struct" : """
+ <union
+ id = ID
+ memberTypes = List of QName
+ {any attributes with non-schema namespace . . .}>
+ Content: (annotation?, simpleType*)
+ </union>""",
+ "type" : SYNTAXELEMENT,
+ "extract" : {
+ "default" : GenerateElement("union", ["id", "memberTypes"],
+ re.compile("((?:annotation )?(?:simpleType )*)"))
+ },
+ "reduce" : ReduceUnion
+ },
+
+ "unique" : {"struct" : """
+ <unique
+ id = ID
+ name = NCName
+ {any attributes with non-schema namespace . . .}>
+ Content: (annotation?, (selector, field+))
+ </unique>""",
+ "type" : SYNTAXELEMENT,
+ "extract" : {
+ "default" : GenerateElement("unique", ["id", "name"],
+ re.compile("((?:annotation )?(?:selector |(?:field )+))"))
+ },
+ "reduce" : ReduceUnique
+ },
+
+ "whiteSpace" : {"struct" : """
+ <whiteSpace
+ fixed = boolean : false
+ id = ID
+ value = (collapse | preserve | replace)
+ {any attributes with non-schema namespace . . .}>
+ Content: (annotation?)
+ </whiteSpace>""",
+ "type" : SYNTAXELEMENT,
+ "extract" : {
+ "default" : GenerateElement("whiteSpace",
+ ["fixed", "id", "value"], ONLY_ANNOTATION)
+ },
+ "reduce" : GenerateFacetReducing("whiteSpace", True)
+ },
+
+#-------------------------------------------------------------------------------
+# Syntax attributes definition
+#-------------------------------------------------------------------------------
+
+ "abstract" : {
+ "type" : SYNTAXATTRIBUTE,
+ "extract" : {
+ "default" : GetBoolean
+ },
+ "default" : {
+ "default" : False
+ }
+ },
+
+ "attributeFormDefault" : {
+ "type" : SYNTAXATTRIBUTE,
+ "extract" : {
+ "default" : GenerateEnumeratedExtraction("member attributeFormDefault", ["qualified", "unqualified"])
+ },
+ "default" : {
+ "default" : "unqualified"
+ }
+ },
+
+ "base" : {
+ "type" : SYNTAXATTRIBUTE,
+ "extract" : {
+ "default" : GenerateModelNameExtraction("member base", QName_model)
+ }
+ },
+
+ "block" : {
+ "type" : SYNTAXATTRIBUTE,
+ "extract" : {
+ "default" : GenerateGetList("block", ["restriction", "extension", "substitution"])
+ }
+ },
+
+ "blockDefault" : {
+ "type" : SYNTAXATTRIBUTE,
+ "extract" : {
+ "default" : GenerateGetList("block", ["restriction", "extension", "substitution"])
+ },
+ "default" : {
+ "default" : ""
+ }
+ },
+
+ "default" : {
+ "type" : SYNTAXATTRIBUTE,
+ "extract" : {
+ "default" : GetAttributeValue
+ }
+ },
+
+ "elementFormDefault" : {
+ "type" : SYNTAXATTRIBUTE,
+ "extract" : {
+ "default" : GenerateEnumeratedExtraction("member elementFormDefault", ["qualified", "unqualified"])
+ },
+ "default" : {
+ "default" : "unqualified"
+ }
+ },
+
+ "final" : {
+ "type" : SYNTAXATTRIBUTE,
+ "extract" : {
+ "default" : GenerateGetList("final", ["restriction", "extension", "substitution"]),
+ "simpleType" : GenerateGetList("final", ["list", "union", "restriction"])
+ }
+ },
+
+ "finalDefault" : {
+ "type" : SYNTAXATTRIBUTE,
+ "extract" : {
+ "default" : GenerateGetList("finalDefault", ["restriction", "extension", "list", "union"])
+ },
+ "default" : {
+ "default" : ""
+ }
+ },
+
+ "fixed" : {
+ "type" : SYNTAXATTRIBUTE,
+ "extract" : {
+ "default" : GetBoolean,
+ "attribute" : GetAttributeValue,
+ "element" : GetAttributeValue
+ },
+ "default" : {
+ "default" : False,
+ "attribute" : None,
+ "element" : None
+ }
+ },
+
+ "form" : {
+ "type" : SYNTAXATTRIBUTE,
+ "extract" : {
+ "default" : GenerateEnumeratedExtraction("member form", ["qualified", "unqualified"])
+ }
+ },
+
+ "id" : {
+ "type" : SYNTAXATTRIBUTE,
+ "extract" : {
+ "default" : GenerateModelNameExtraction("member id", NCName_model)
+ }
+ },
+
+ "itemType" : {
+ "type" : SYNTAXATTRIBUTE,
+ "extract" : {
+ "default" : GenerateModelNameExtraction("member itemType", QName_model)
+ }
+ },
+
+ "memberTypes" : {
+ "type" : SYNTAXATTRIBUTE,
+ "extract" : {
+ "default" : GenerateModelNameListExtraction("member memberTypes", QNames_model)
+ },
+ },
+
+ "maxOccurs" : {
+ "type" : SYNTAXATTRIBUTE,
+ "extract" : {
+ "default" : GenerateLimitExtraction(),
+ "all" : GenerateLimitExtraction(1, 1, False)
+ },
+ "default" : {
+ "default" : 1
+ }
+ },
+
+ "minOccurs" : {
+ "type" : SYNTAXATTRIBUTE,
+ "extract" : {
+ "default" : GenerateLimitExtraction(unbounded = False),
+ "all" : GenerateLimitExtraction(0, 1, False)
+ },
+ "default" : {
+ "default" : 1
+ }
+ },
+
+ "mixed" : {
+ "type" : SYNTAXATTRIBUTE,
+ "extract" : {
+ "default" : GetBoolean
+ },
+ "default" : {
+ "default" : None,
+ "complexType" : False
+ }
+ },
+
+ "name" : {
+ "type" : SYNTAXATTRIBUTE,
+ "extract" : {
+ "default" : GenerateModelNameExtraction("member name", NCName_model)
+ }
+ },
+
+ "namespace" : {
+ "type" : SYNTAXATTRIBUTE,
+ "extract" : {
+ "default" : GenerateModelNameExtraction("member namespace", URI_model),
+ "any" : GetNamespaces
+ },
+ "default" : {
+ "default" : None,
+ "any" : "##any"
+ }
+ },
+
+ "nillable" : {
+ "type" : SYNTAXATTRIBUTE,
+ "extract" : {
+ "default" : GetBoolean
+ },
+ "default" : {
+ "default" : False
+ }
+ },
+
+ "processContents" : {
+ "type" : SYNTAXATTRIBUTE,
+ "extract" : {
+ "default" : GenerateEnumeratedExtraction("member processContents", ["lax", "skip", "strict"])
+ },
+ "default" : {
+ "default" : "strict"
+ }
+ },
+
+ "ref" : {
+ "type" : SYNTAXATTRIBUTE,
+ "extract" : {
+ "default" : GenerateModelNameExtraction("member ref", QName_model)
+ }
+ },
+
+ "refer" : {
+ "type" : SYNTAXATTRIBUTE,
+ "extract" : {
+ "default" : GenerateModelNameExtraction("member refer", QName_model)
+ }
+ },
+
+ "schemaLocation" : {
+ "type" : SYNTAXATTRIBUTE,
+ "extract" : {
+ "default" : GenerateModelNameExtraction("member schemaLocation", URI_model)
+ }
+ },
+
+ "source" : {
+ "type" : SYNTAXATTRIBUTE,
+ "extract" : {
+ "default" : GenerateModelNameExtraction("member source", URI_model)
+ }
+ },
+
+ "substitutionGroup" : {
+ "type" : SYNTAXATTRIBUTE,
+ "extract" : {
+ "default" : GenerateModelNameExtraction("member substitutionGroup", QName_model)
+ }
+ },
+
+ "targetNamespace" : {
+ "type" : SYNTAXATTRIBUTE,
+ "extract" : {
+ "default" : GenerateModelNameExtraction("member targetNamespace", URI_model)
+ }
+ },
+
+ "type" : {
+ "type" : SYNTAXATTRIBUTE,
+ "extract" : {
+ "default" : GenerateModelNameExtraction("member type", QName_model)
+ }
+ },
+
+ "use" : {
+ "type" : SYNTAXATTRIBUTE,
+ "extract" : {
+ "default" : GenerateEnumeratedExtraction("member usage", ["required", "optional", "prohibited"])
+ },
+ "default" : {
+ "default" : "optional"
+ }
+ },
+
+ "value" : {
+ "type" : SYNTAXATTRIBUTE,
+ "extract" : {
+ "default" : GetAttributeValue,
+ "fractionDigits" : GenerateIntegerExtraction(minInclusive=0),
+ "length" : GenerateIntegerExtraction(minInclusive=0),
+ "maxLength" : GenerateIntegerExtraction(minInclusive=0),
+ "minLength" : GenerateIntegerExtraction(minInclusive=0),
+ "totalDigits" : GenerateIntegerExtraction(minExclusive=0),
+ "whiteSpace" : GenerateEnumeratedExtraction("value", ["collapse", "preserve", "replace"])
+ }
+ },
+
+ "version" : {
+ "type" : SYNTAXATTRIBUTE,
+ "extract" : {
+ "default" : GetToken
+ }
+ },
+
+ "xpath" : {
+ "type" : SYNTAXATTRIBUTE,
+ "extract" : {
+ "default" : NotSupportedYet("xpath")
+ }
+ },
+
+#-------------------------------------------------------------------------------
+# Simple types definition
+#-------------------------------------------------------------------------------
+
+ "string" : {
+ "type" : SIMPLETYPE,
+ "basename" : "string",
+ "extract" : GetAttributeValue,
+ "facets" : STRING_FACETS,
+ "generate" : GenerateSimpleTypeXMLText(lambda x : x),
+ "initial" : lambda: "",
+ "check" : lambda x: isinstance(x, (StringType, UnicodeType))
+ },
+
+ "normalizedString" : {
+ "type" : SIMPLETYPE,
+ "basename" : "normalizedString",
+ "extract" : GetNormalizedString,
+ "facets" : STRING_FACETS,
+ "generate" : GenerateSimpleTypeXMLText(lambda x : x),
+ "initial" : lambda: "",
+ "check" : lambda x: isinstance(x, (StringType, UnicodeType))
+ },
+
+ "token" : {
+ "type" : SIMPLETYPE,
+ "basename" : "token",
+ "extract" : GetToken,
+ "facets" : STRING_FACETS,
+ "generate" : GenerateSimpleTypeXMLText(lambda x : x),
+ "initial" : lambda: "",
+ "check" : lambda x: isinstance(x, (StringType, UnicodeType))
+ },
+
+ "base64Binary" : {
+ "type" : SIMPLETYPE,
+ "basename" : "base64Binary",
+ "extract" : NotSupportedYet("base64Binary"),
+ "facets" : STRING_FACETS,
+ "generate" : GenerateSimpleTypeXMLText(str),
+ "initial" : lambda: 0,
+ "check" : lambda x: isinstance(x, IntType)
+ },
+
+ "hexBinary" : {
+ "type" : SIMPLETYPE,
+ "basename" : "hexBinary",
+ "extract" : GetHexInteger,
+ "facets" : STRING_FACETS,
+ "generate" : GenerateSimpleTypeXMLText(lambda x : "%X"%x),
+ "initial" : lambda: 0,
+ "check" : lambda x: isinstance(x, IntType)
+ },
+
+ "integer" : {
+ "type" : SIMPLETYPE,
+ "basename" : "integer",
+ "extract" : GenerateIntegerExtraction(),
+ "facets" : DECIMAL_FACETS,
+ "generate" : GenerateSimpleTypeXMLText(str),
+ "initial" : lambda: 0,
+ "check" : lambda x: isinstance(x, IntType)
+ },
+
+ "positiveInteger" : {
+ "type" : SIMPLETYPE,
+ "basename" : "positiveInteger",
+ "extract" : GenerateIntegerExtraction(minExclusive=0),
+ "facets" : DECIMAL_FACETS,
+ "generate" : GenerateSimpleTypeXMLText(str),
+ "initial" : lambda: 0,
+ "check" : lambda x: isinstance(x, IntType)
+ },
+
+ "negativeInteger" : {
+ "type" : SIMPLETYPE,
+ "basename" : "negativeInteger",
+ "extract" : GenerateIntegerExtraction(maxExclusive=0),
+ "facets" : DECIMAL_FACETS,
+ "generate" : GenerateSimpleTypeXMLText(str),
+ "initial" : lambda: 0,
+ "check" : lambda x: isinstance(x, IntType)
+ },
+
+ "nonNegativeInteger" : {
+ "type" : SIMPLETYPE,
+ "basename" : "nonNegativeInteger",
+ "extract" : GenerateIntegerExtraction(minInclusive=0),
+ "facets" : DECIMAL_FACETS,
+ "generate" : GenerateSimpleTypeXMLText(str),
+ "initial" : lambda: 0,
+ "check" : lambda x: isinstance(x, IntType)
+ },
+
+ "nonPositiveInteger" : {
+ "type" : SIMPLETYPE,
+ "basename" : "nonPositiveInteger",
+ "extract" : GenerateIntegerExtraction(maxInclusive=0),
+ "facets" : DECIMAL_FACETS,
+ "generate" : GenerateSimpleTypeXMLText(str),
+ "initial" : lambda: 0,
+ "check" : lambda x: isinstance(x, IntType)
+ },
+
+ "long" : {
+ "type" : SIMPLETYPE,
+ "basename" : "long",
+ "extract" : GenerateIntegerExtraction(minInclusive=-2**63,maxExclusive=2**63),
+ "facets" : DECIMAL_FACETS,
+ "generate" : GenerateSimpleTypeXMLText(str),
+ "initial" : lambda: 0,
+ "check" : lambda x: isinstance(x, IntType)
+ },
+
+ "unsignedLong" : {
+ "type" : SIMPLETYPE,
+ "basename" : "unsignedLong",
+ "extract" : GenerateIntegerExtraction(minInclusive=0,maxExclusive=2**64),
+ "facets" : DECIMAL_FACETS,
+ "generate" : GenerateSimpleTypeXMLText(str),
+ "initial" : lambda: 0,
+ "check" : lambda x: isinstance(x, IntType)
+ },
+
+ "int" : {
+ "type" : SIMPLETYPE,
+ "basename" : "int",
+ "extract" : GenerateIntegerExtraction(minInclusive=-2**31,maxExclusive=2**31),
+ "facets" : DECIMAL_FACETS,
+ "generate" : GenerateSimpleTypeXMLText(str),
+ "initial" : lambda: 0,
+ "check" : lambda x: isinstance(x, IntType)
+ },
+
+ "unsignedInt" : {
+ "type" : SIMPLETYPE,
+ "basename" : "unsignedInt",
+ "extract" : GenerateIntegerExtraction(minInclusive=0,maxExclusive=2**32),
+ "facets" : DECIMAL_FACETS,
+ "generate" : GenerateSimpleTypeXMLText(str),
+ "initial" : lambda: 0,
+ "check" : lambda x: isinstance(x, IntType)
+ },
+
+ "short" : {
+ "type" : SIMPLETYPE,
+ "basename" : "short",
+ "extract" : GenerateIntegerExtraction(minInclusive=-2**15,maxExclusive=2**15),
+ "facets" : DECIMAL_FACETS,
+ "generate" : GenerateSimpleTypeXMLText(str),
+ "initial" : lambda: 0,
+ "check" : lambda x: isinstance(x, IntType)
+ },
+
+ "unsignedShort" : {
+ "type" : SIMPLETYPE,
+ "basename" : "unsignedShort",
+ "extract" : GenerateIntegerExtraction(minInclusive=0,maxExclusive=2**16),
+ "facets" : DECIMAL_FACETS,
+ "generate" : GenerateSimpleTypeXMLText(str),
+ "initial" : lambda: 0,
+ "check" : lambda x: isinstance(x, IntType)
+ },
+
+ "byte" : {
+ "type" : SIMPLETYPE,
+ "basename" : "byte",
+ "extract" : GenerateIntegerExtraction(minInclusive=-2**7,maxExclusive=2**7),
+ "facets" : DECIMAL_FACETS,
+ "generate" : GenerateSimpleTypeXMLText(str),
+ "initial" : lambda: 0,
+ "check" : lambda x: isinstance(x, IntType)
+ },
+
+ "unsignedByte" : {
+ "type" : SIMPLETYPE,
+ "basename" : "unsignedByte",
+ "extract" : GenerateIntegerExtraction(minInclusive=0,maxExclusive=2**8),
+ "facets" : DECIMAL_FACETS,
+ "generate" : GenerateSimpleTypeXMLText(str),
+ "initial" : lambda: 0,
+ "check" : lambda x: isinstance(x, IntType)
+ },
+
+ "decimal" : {
+ "type" : SIMPLETYPE,
+ "basename" : "decimal",
+ "extract" : GenerateFloatExtraction("decimal"),
+ "facets" : DECIMAL_FACETS,
+ "generate" : GenerateFloatXMLText(),
+ "initial" : lambda: 0.,
+ "check" : lambda x: isinstance(x, (IntType, FloatType))
+ },
+
+ "float" : {
+ "type" : SIMPLETYPE,
+ "basename" : "float",
+ "extract" : GenerateFloatExtraction("float", ["INF", "-INF", "NaN"]),
+ "facets" : NUMBER_FACETS,
+ "generate" : GenerateFloatXMLText(["INF", "-INF", "NaN"]),
+ "initial" : lambda: 0.,
+ "check" : lambda x: {"INF" : True, "-INF" : True, "NaN" : True}.get(x, isinstance(x, (IntType, FloatType)))
+ },
+
+ "double" : {
+ "type" : SIMPLETYPE,
+ "basename" : "double",
+ "extract" : GenerateFloatExtraction("double", ["INF", "-INF", "NaN"]),
+ "facets" : NUMBER_FACETS,
+ "generate" : GenerateFloatXMLText(["INF", "-INF", "NaN"]),
+ "initial" : lambda: 0.,
+ "check" : lambda x: {"INF" : True, "-INF" : True, "NaN" : True}.get(x, isinstance(x, (IntType, FloatType)))
+ },
+
+ "boolean" : {
+ "type" : SIMPLETYPE,
+ "basename" : "boolean",
+ "extract" : GetBoolean,
+ "facets" : ["pattern", "whiteSpace"],
+ "generate" : GenerateSimpleTypeXMLText(lambda x:{True : "true", False : "false"}[x]),
+ "initial" : lambda: False,
+ "check" : lambda x: isinstance(x, BooleanType)
+ },
+
+ "duration" : {
+ "type" : SIMPLETYPE,
+ "basename" : "duration",
+ "extract" : NotSupportedYet("duration"),
+ "facets" : NUMBER_FACETS,
+ "generate" : GenerateSimpleTypeXMLText(str),
+ "initial" : lambda: "",
+ "check" : lambda x: isinstance(x, (StringType, UnicodeType))
+ },
+
+ "dateTime" : {
+ "type" : SIMPLETYPE,
+ "basename" : "dateTime",
+ "extract" : GetDateTime,
+ "facets" : NUMBER_FACETS,
+ "generate" : GenerateSimpleTypeXMLText(str),
+ "initial" : lambda: datetime.datetime(1,1,1,0,0,0,0),
+ "check" : lambda x: isinstance(x, datetime.datetime)
+ },
+
+ "date" : {
+ "type" : SIMPLETYPE,
+ "basename" : "date",
+ "extract" : GetDate,
+ "facets" : NUMBER_FACETS,
+ "generate" : GenerateSimpleTypeXMLText(str),
+ "initial" : lambda: datetime.date(1,1,1),
+ "check" : lambda x: isinstance(x, datetime.date)
+ },
+
+ "time" : {
+ "type" : SIMPLETYPE,
+ "basename" : "time",
+ "extract" : GetTime,
+ "facets" : NUMBER_FACETS,
+ "generate" : GenerateSimpleTypeXMLText(str),
+ "initial" : lambda: datetime.time(0,0,0,0),
+ "check" : lambda x: isinstance(x, datetime.time)
+ },
+
+ "gYear" : {
+ "type" : SIMPLETYPE,
+ "basename" : "gYear",
+ "extract" : NotSupportedYet("gYear"),
+ "facets" : NUMBER_FACETS,
+ "generate" : GenerateSimpleTypeXMLText(str),
+ "initial" : lambda: "",
+ "check" : lambda x: isinstance(x, (StringType, UnicodeType))
+ },
+
+ "gYearMonth" : {
+ "type" : SIMPLETYPE,
+ "basename" : "gYearMonth",
+ "extract" : NotSupportedYet("gYearMonth"),
+ "facets" : NUMBER_FACETS,
+ "generate" : GenerateSimpleTypeXMLText(str),
+ "initial" : lambda: "",
+ "check" : lambda x: isinstance(x, (StringType, UnicodeType))
+ },
+
+ "gMonth" : {
+ "type" : SIMPLETYPE,
+ "basename" : "gMonth",
+ "extract" : NotSupportedYet("gMonth"),
+ "facets" : NUMBER_FACETS,
+ "generate" : GenerateSimpleTypeXMLText(str),
+ "initial" : lambda: "",
+ "check" : lambda x: isinstance(x, (StringType, UnicodeType))
+ },
+
+ "gMonthDay" : {
+ "type" : SIMPLETYPE,
+ "basename" : "gMonthDay",
+ "extract" : NotSupportedYet("gMonthDay"),
+ "facets" : NUMBER_FACETS,
+ "generate" : GenerateSimpleTypeXMLText(str),
+ "initial" : lambda: "",
+ "check" : lambda x: isinstance(x, (StringType, UnicodeType))
+ },
+
+ "gDay" : {
+ "type" : SIMPLETYPE,
+ "basename" : "gDay",
+ "extract" : NotSupportedYet("gDay"),
+ "facets" : NUMBER_FACETS,
+ "generate" : GenerateSimpleTypeXMLText(str),
+ "initial" : lambda: "",
+ "check" : lambda x: isinstance(x, (StringType, UnicodeType))
+ },
+
+ "Name" : {
+ "type" : SIMPLETYPE,
+ "basename" : "Name",
+ "extract" : GenerateModelNameExtraction("Name", Name_model),
+ "facets" : STRING_FACETS,
+ "generate" : GenerateSimpleTypeXMLText(lambda x: x),
+ "initial" : lambda: "",
+ "check" : lambda x: isinstance(x, (StringType, UnicodeType))
+ },
+
+ "QName" : {
+ "type" : SIMPLETYPE,
+ "basename" : "QName",
+ "extract" : GenerateModelNameExtraction("QName", QName_model),
+ "facets" : STRING_FACETS,
+ "generate" : GenerateSimpleTypeXMLText(lambda x: x),
+ "initial" : lambda: "",
+ "check" : lambda x: isinstance(x, (StringType, UnicodeType))
+ },
+
+ "NCName" : {
+ "type" : SIMPLETYPE,
+ "basename" : "NCName",
+ "extract" : GenerateModelNameExtraction("NCName", NCName_model),
+ "facets" : STRING_FACETS,
+ "generate" : GenerateSimpleTypeXMLText(lambda x: x),
+ "initial" : lambda: "",
+ "check" : lambda x: isinstance(x, (StringType, UnicodeType))
+ },
+
+ "anyURI" : {
+ "type" : SIMPLETYPE,
+ "basename" : "anyURI",
+ "extract" : GenerateModelNameExtraction("anyURI", URI_model),
+ "facets" : STRING_FACETS,
+ "generate" : GenerateSimpleTypeXMLText(lambda x: x),
+ "initial" : lambda: "",
+ "check" : lambda x: isinstance(x, (StringType, UnicodeType))
+ },
+
+ "language" : {
+ "type" : SIMPLETYPE,
+ "basename" : "language",
+ "extract" : GenerateEnumeratedExtraction("language", LANGUAGES),
+ "facets" : STRING_FACETS,
+ "generate" : GenerateSimpleTypeXMLText(lambda x: x),
+ "initial" : lambda: "en",
+ "check" : lambda x: isinstance(x, (StringType, UnicodeType))
+ },
+
+ "ID" : {
+ "type" : SIMPLETYPE,
+ "basename" : "ID",
+ "extract" : GenerateModelNameExtraction("ID", Name_model),
+ "facets" : STRING_FACETS,
+ "generate" : GenerateSimpleTypeXMLText(lambda x: x),
+ "initial" : lambda: "",
+ "check" : lambda x: isinstance(x, (StringType, UnicodeType))
+ },
+
+ "IDREF" : {
+ "type" : SIMPLETYPE,
+ "basename" : "IDREF",
+ "extract" : GenerateModelNameExtraction("IDREF", Name_model),
+ "facets" : STRING_FACETS,
+ "generate" : GenerateSimpleTypeXMLText(lambda x: x),
+ "initial" : lambda: "",
+ "check" : lambda x: isinstance(x, (StringType, UnicodeType))
+ },
+
+ "IDREFS" : {
+ "type" : SIMPLETYPE,
+ "basename" : "IDREFS",
+ "extract" : GenerateModelNameExtraction("IDREFS", Names_model),
+ "facets" : STRING_FACETS,
+ "generate" : GenerateSimpleTypeXMLText(lambda x: x),
+ "initial" : lambda: "",
+ "check" : lambda x: isinstance(x, (StringType, UnicodeType))
+ },
+
+ "ENTITY" : {
+ "type" : SIMPLETYPE,
+ "basename" : "ENTITY",
+ "extract" : GenerateModelNameExtraction("ENTITY", Name_model),
+ "facets" : STRING_FACETS,
+ "generate" : GenerateSimpleTypeXMLText(lambda x: x),
+ "initial" : lambda: "",
+ "check" : lambda x: isinstance(x, (StringType, UnicodeType))
+ },
+
+ "ENTITIES" : {
+ "type" : SIMPLETYPE,
+ "basename" : "ENTITIES",
+ "extract" : GenerateModelNameExtraction("ENTITIES", Names_model),
+ "facets" : STRING_FACETS,
+ "generate" : GenerateSimpleTypeXMLText(lambda x: x),
+ "initial" : lambda: "",
+ "check" : lambda x: isinstance(x, (StringType, UnicodeType))
+ },
+
+ "NOTATION" : {
+ "type" : SIMPLETYPE,
+ "basename" : "NOTATION",
+ "extract" : GenerateModelNameExtraction("NOTATION", Name_model),
+ "facets" : STRING_FACETS,
+ "generate" : GenerateSimpleTypeXMLText(lambda x: x),
+ "initial" : lambda: "",
+ "check" : lambda x: isinstance(x, (StringType, UnicodeType))
+ },
+
+ "NMTOKEN" : {
+ "type" : SIMPLETYPE,
+ "basename" : "NMTOKEN",
+ "extract" : GenerateModelNameExtraction("NMTOKEN", NMToken_model),
+ "facets" : STRING_FACETS,
+ "generate" : GenerateSimpleTypeXMLText(lambda x: x),
+ "initial" : lambda: "",
+ "check" : lambda x: isinstance(x, (StringType, UnicodeType))
+ },
+
+ "NMTOKENS" : {
+ "type" : SIMPLETYPE,
+ "basename" : "NMTOKENS",
+ "extract" : GenerateModelNameExtraction("NMTOKENS", NMTokens_model),
+ "facets" : STRING_FACETS,
+ "generate" : GenerateSimpleTypeXMLText(lambda x: x),
+ "initial" : lambda: "",
+ "check" : lambda x: isinstance(x, (StringType, UnicodeType))
+ },
+
+ # Complex Types
+ "anyType" : {"type" : COMPLEXTYPE, "extract" : lambda x:None},
+}
+
+if __name__ == '__main__':
+ classes = GenerateClassesFromXSD("test.xsd")
+
+ # Code for test of test.xsd
+ xmlfile = open("po.xml", 'r')
+ tree = minidom.parse(xmlfile)
+ xmlfile.close()
+ test = classes["PurchaseOrderType"]()
+ for child in tree.childNodes:
+ if child.nodeType == tree.ELEMENT_NODE and child.nodeName == "purchaseOrder":
+ test.loadXMLTree(child)
+ test.items.item[0].setquantity(2)
+ testfile = open("test.xml", 'w')
+ testfile.write("<?xml version=\"1.0\"?>\n")
+ testfile.write(test.generateXMLText("purchaseOrder"))
+ testfile.close()