plcopen/plcopen.py
changeset 1730 64d8f52bc8c8
parent 1695 a63bb4025852
child 1732 94ffe74e6895
equal deleted inserted replaced
1726:d51af006fa6b 1730:64d8f52bc8c8
    47 Define in which order var types must be displayed
    47 Define in which order var types must be displayed
    48 """
    48 """
    49 VarOrder = ["Local","Temp","Input","Output","InOut","External","Global","Access"]
    49 VarOrder = ["Local","Temp","Input","Output","InOut","External","Global","Access"]
    50 
    50 
    51 """
    51 """
    52 Define which action qualifier must be associated with a duration 
    52 Define which action qualifier must be associated with a duration
    53 """
    53 """
    54 QualifierList = OrderedDict([("N", False), ("R", False), ("S", False), 
    54 QualifierList = OrderedDict([("N", False), ("R", False), ("S", False),
    55     ("L", True), ("D", True), ("P", False), ("P0", False), 
    55     ("L", True), ("D", True), ("P", False), ("P0", False),
    56     ("P1", False), ("SD", True), ("DS", True), ("SL", True)])
    56     ("P1", False), ("SD", True), ("DS", True), ("SL", True)])
    57 
    57 
    58 
    58 
    59 FILTER_ADDRESS_MODEL = "(%%[IQM](?:[XBWDL])?)(%s)((?:\.[0-9]+)*)" 
    59 FILTER_ADDRESS_MODEL = "(%%[IQM](?:[XBWDL])?)(%s)((?:\.[0-9]+)*)"
    60 
    60 
    61 def update_address(address, address_model, new_leading):
    61 def update_address(address, address_model, new_leading):
    62     result = address_model.match(address)
    62     result = address_model.match(address)
    63     if result is None:
    63     if result is None:
    64         return address
    64         return address
    71     if v2 is not None:
    71     if v2 is not None:
    72         return function(v1, v2)
    72         return function(v1, v2)
    73     return v1
    73     return v1
    74 
    74 
    75 """
    75 """
    76 Helper class for bounding_box calculation 
    76 Helper class for bounding_box calculation
    77 """
    77 """
    78 class rect:
    78 class rect:
    79     
    79 
    80     def __init__(self, x=None, y=None, width=None, height=None):
    80     def __init__(self, x=None, y=None, width=None, height=None):
    81         self.x_min = x
    81         self.x_min = x
    82         self.x_max = None
    82         self.x_max = None
    83         self.y_min = y
    83         self.y_min = y
    84         self.y_max = None
    84         self.y_max = None
    85         if width is not None and x is not None:
    85         if width is not None and x is not None:
    86             self.x_max = x + width
    86             self.x_max = x + width
    87         if height is not None and y is not None:
    87         if height is not None and y is not None:
    88             self.y_max = y + height
    88             self.y_max = y + height
    89     
    89 
    90     def update(self, x, y):
    90     def update(self, x, y):
    91         self.x_min = _init_and_compare(min, self.x_min, x)
    91         self.x_min = _init_and_compare(min, self.x_min, x)
    92         self.x_max = _init_and_compare(max, self.x_max, x)
    92         self.x_max = _init_and_compare(max, self.x_max, x)
    93         self.y_min = _init_and_compare(min, self.y_min, y)
    93         self.y_min = _init_and_compare(min, self.y_min, y)
    94         self.y_max = _init_and_compare(max, self.y_max, y)
    94         self.y_max = _init_and_compare(max, self.y_max, y)
    95         
    95 
    96     def union(self, rect):
    96     def union(self, rect):
    97         self.x_min = _init_and_compare(min, self.x_min, rect.x_min)
    97         self.x_min = _init_and_compare(min, self.x_min, rect.x_min)
    98         self.x_max = _init_and_compare(max, self.x_max, rect.x_max)
    98         self.x_max = _init_and_compare(max, self.x_max, rect.x_max)
    99         self.y_min = _init_and_compare(min, self.y_min, rect.y_min)
    99         self.y_min = _init_and_compare(min, self.y_min, rect.y_min)
   100         self.y_max = _init_and_compare(max, self.y_max, rect.y_max)
   100         self.y_max = _init_and_compare(max, self.y_max, rect.y_max)
   101     
   101 
   102     def bounding_box(self):
   102     def bounding_box(self):
   103         width = height = None
   103         width = height = None
   104         if self.x_min is not None and self.x_max is not None:
   104         if self.x_min is not None and self.x_max is not None:
   105             width = self.x_max - self.x_min
   105             width = self.x_max - self.x_min
   106         if self.y_min is not None and self.y_max is not None:
   106         if self.y_min is not None and self.y_max is not None:
   123 def TestTextElement(text, criteria):
   123 def TestTextElement(text, criteria):
   124     lines = text.splitlines()
   124     lines = text.splitlines()
   125     test_result = []
   125     test_result = []
   126     result = criteria["pattern"].search(text)
   126     result = criteria["pattern"].search(text)
   127     while result is not None:
   127     while result is not None:
   128         prev_pos=result.endpos        
   128         prev_pos=result.endpos
   129         start = TextLenInRowColumn(text[:result.start()])
   129         start = TextLenInRowColumn(text[:result.start()])
   130         end = TextLenInRowColumn(text[:result.end() - 1])
   130         end = TextLenInRowColumn(text[:result.end() - 1])
   131         test_result.append((start, end, "\n".join(lines[start[0]:end[0] + 1])))
   131         test_result.append((start, end, "\n".join(lines[start[0]:end[0] + 1])))
   132         result = criteria["pattern"].search(text, result.end())
   132         result = criteria["pattern"].search(text, result.end())
   133         if result is not None and prev_pos==result.endpos:
   133         if result is not None and prev_pos==result.endpos:
   139 
   139 
   140 PLCOpenParser = GenerateParserFromXSD(paths.AbsNeighbourFile(__file__, "tc6_xml_v201.xsd"))
   140 PLCOpenParser = GenerateParserFromXSD(paths.AbsNeighbourFile(__file__, "tc6_xml_v201.xsd"))
   141 PLCOpen_XPath = lambda xpath: etree.XPath(xpath, namespaces=PLCOpenParser.NSMAP)
   141 PLCOpen_XPath = lambda xpath: etree.XPath(xpath, namespaces=PLCOpenParser.NSMAP)
   142 
   142 
   143 LOAD_POU_PROJECT_TEMPLATE = """
   143 LOAD_POU_PROJECT_TEMPLATE = """
   144 <project xmlns:ns1="http://www.plcopen.org/xml/tc6_0201" 
   144 <project xmlns:ns1="http://www.plcopen.org/xml/tc6_0201"
   145          xmlns:xhtml="http://www.w3.org/1999/xhtml" 
   145          xmlns:xhtml="http://www.w3.org/1999/xhtml"
   146          xmlns:xsd="http://www.w3.org/2001/XMLSchema" 
   146          xmlns:xsd="http://www.w3.org/2001/XMLSchema"
   147          xmlns="http://www.plcopen.org/xml/tc6_0201">
   147          xmlns="http://www.plcopen.org/xml/tc6_0201">
   148   <fileHeader companyName="" productName="" productVersion="" 
   148   <fileHeader companyName="" productName="" productVersion=""
   149               creationDateTime="1970-01-01T00:00:00"/>
   149               creationDateTime="1970-01-01T00:00:00"/>
   150   <contentHeader name="paste_project">
   150   <contentHeader name="paste_project">
   151     <coordinateInfo>
   151     <coordinateInfo>
   152       <fbd><scaling x="0" y="0"/></fbd>
   152       <fbd><scaling x="0" y="0"/></fbd>
   153       <ld><scaling x="0" y="0"/></ld>
   153       <ld><scaling x="0" y="0"/></ld>
   174 
   174 
   175 PLCOpen_v1_file = open(paths.AbsNeighbourFile(__file__, "TC6_XML_V10_B.xsd"))
   175 PLCOpen_v1_file = open(paths.AbsNeighbourFile(__file__, "TC6_XML_V10_B.xsd"))
   176 PLCOpen_v1_xml = PLCOpen_v1_file.read()
   176 PLCOpen_v1_xml = PLCOpen_v1_file.read()
   177 PLCOpen_v1_file.close()
   177 PLCOpen_v1_file.close()
   178 PLCOpen_v1_xml = PLCOpen_v1_xml.replace(
   178 PLCOpen_v1_xml = PLCOpen_v1_xml.replace(
   179         "http://www.plcopen.org/xml/tc6.xsd", 
   179         "http://www.plcopen.org/xml/tc6.xsd",
   180         "http://www.plcopen.org/xml/tc6_0201") 
   180         "http://www.plcopen.org/xml/tc6_0201")
   181 PLCOpen_v1_xsd = etree.XMLSchema(etree.fromstring(PLCOpen_v1_xml))
   181 PLCOpen_v1_xsd = etree.XMLSchema(etree.fromstring(PLCOpen_v1_xml))
   182 
   182 
   183 # XPath for file compatibility process
   183 # XPath for file compatibility process
   184 ProjectResourcesXPath = PLCOpen_XPath("ppx:instances/ppx:configurations/ppx:configuration/ppx:resource")
   184 ProjectResourcesXPath = PLCOpen_XPath("ppx:instances/ppx:configurations/ppx:configuration/ppx:resource")
   185 ResourceInstancesXpath = PLCOpen_XPath("ppx:pouInstance | ppx:task/ppx:pouInstance")
   185 ResourceInstancesXpath = PLCOpen_XPath("ppx:pouInstance | ppx:task/ppx:pouInstance")
   188 ActionBlocksXPath = PLCOpen_XPath("ppx:types/ppx:pous/ppx:pou/ppx:body/*/ppx:actionBlock")
   188 ActionBlocksXPath = PLCOpen_XPath("ppx:types/ppx:pous/ppx:pou/ppx:body/*/ppx:actionBlock")
   189 ActionBlocksConnectionPointOutXPath = PLCOpen_XPath("ppx:connectionPointOut")
   189 ActionBlocksConnectionPointOutXPath = PLCOpen_XPath("ppx:connectionPointOut")
   190 
   190 
   191 def LoadProjectXML(project_xml):
   191 def LoadProjectXML(project_xml):
   192     project_xml = project_xml.replace(
   192     project_xml = project_xml.replace(
   193         "http://www.plcopen.org/xml/tc6.xsd", 
   193         "http://www.plcopen.org/xml/tc6.xsd",
   194         "http://www.plcopen.org/xml/tc6_0201")
   194         "http://www.plcopen.org/xml/tc6_0201")
   195     for cre, repl in [
   195     for cre, repl in [
   196         (re.compile("(?<!<xhtml:p>)(?:<!\[CDATA\[)"), "<xhtml:p><![CDATA["),
   196         (re.compile("(?<!<xhtml:p>)(?:<!\[CDATA\[)"), "<xhtml:p><![CDATA["),
   197         (re.compile("(?:]]>)(?!</xhtml:p>)"), "]]></xhtml:p>")]:
   197         (re.compile("(?:]]>)(?!</xhtml:p>)"), "]]></xhtml:p>")]:
   198         project_xml = cre.sub(repl, project_xml)
   198         project_xml = cre.sub(repl, project_xml)
   199     
   199 
   200     try:
   200     try:
   201         tree, error = PLCOpenParser.LoadXMLString(project_xml)
   201         tree, error = PLCOpenParser.LoadXMLString(project_xml)
   202         if error is None:
   202         if error is None:
   203             return tree, None
   203             return tree, None
   204         
   204 
   205         if PLCOpen_v1_xsd.validate(tree):
   205         if PLCOpen_v1_xsd.validate(tree):
   206             # Make file compatible with PLCOpen v2
   206             # Make file compatible with PLCOpen v2
   207             
   207 
   208             # Update resource interval value
   208             # Update resource interval value
   209             for resource in ProjectResourcesXPath(tree):
   209             for resource in ProjectResourcesXPath(tree):
   210                 for task in resource.gettask():
   210                 for task in resource.gettask():
   211                     interval = task.get("interval")
   211                     interval = task.get("interval")
   212                     if interval is not None:
   212                     if interval is not None:
   227                                 if time_values[3] % 1000 != 0:
   227                                 if time_values[3] % 1000 != 0:
   228                                     text += "%.3fms"%(float(time_values[3]) / 1000)
   228                                     text += "%.3fms"%(float(time_values[3]) / 1000)
   229                                 else:
   229                                 else:
   230                                     text += "%dms"%(time_values[3] / 1000)
   230                                     text += "%dms"%(time_values[3] / 1000)
   231                             task.set("interval", text)
   231                             task.set("interval", text)
   232                 
   232 
   233                 # Update resources pou instance attributes
   233                 # Update resources pou instance attributes
   234                 for pouInstance in ResourceInstancesXpath(resource):
   234                 for pouInstance in ResourceInstancesXpath(resource):
   235                     type_name = pouInstance.attrib.pop("type")
   235                     type_name = pouInstance.attrib.pop("type")
   236                     if type_name is not None:
   236                     if type_name is not None:
   237                         pouInstance.set("typeName", type_name)
   237                         pouInstance.set("typeName", type_name)
   238             
   238 
   239             # Update transitions condition
   239             # Update transitions condition
   240             for transition_condition in TransitionsConditionXPath(tree):
   240             for transition_condition in TransitionsConditionXPath(tree):
   241                 connections = ConditionConnectionsXPath(transition_condition)
   241                 connections = ConditionConnectionsXPath(transition_condition)
   242                 if len(connections) > 0:
   242                 if len(connections) > 0:
   243                     connectionPointIn = PLCOpenParser.CreateElement("connectionPointIn", "condition")
   243                     connectionPointIn = PLCOpenParser.CreateElement("connectionPointIn", "condition")
   244                     transition_condition.setcontent(connectionPointIn)
   244                     transition_condition.setcontent(connectionPointIn)
   245                     connectionPointIn.setrelPositionXY(0, 0)
   245                     connectionPointIn.setrelPositionXY(0, 0)
   246                     for connection in connections:
   246                     for connection in connections:
   247                         connectionPointIn.append(connection)
   247                         connectionPointIn.append(connection)
   248             
   248 
   249             # Update actionBlocks
   249             # Update actionBlocks
   250             for actionBlock in ActionBlocksXPath(tree):
   250             for actionBlock in ActionBlocksXPath(tree):
   251                 for connectionPointOut in ActionBlocksConnectionPointOutXPath(actionBlock):
   251                 for connectionPointOut in ActionBlocksConnectionPointOutXPath(actionBlock):
   252                     actionBlock.remove(connectionPointOut)
   252                     actionBlock.remove(connectionPointOut)
   253                     
   253 
   254                 for action in actionBlock.getaction():
   254                 for action in actionBlock.getaction():
   255                     action.set("localId", "0")
   255                     action.set("localId", "0")
   256                     relPosition = PLCOpenParser.CreateElement("relPosition", "action")
   256                     relPosition = PLCOpenParser.CreateElement("relPosition", "action")
   257                     relPosition.set("x", "0")
   257                     relPosition.set("x", "0")
   258                     relPosition.set("y", "0")
   258                     relPosition.set("y", "0")
   259                     action.setrelPosition(relPosition)
   259                     action.setrelPosition(relPosition)
   260             
   260 
   261             return tree, None
   261             return tree, None
   262         
   262 
   263         return tree, error
   263         return tree, error
   264     
   264 
   265     except Exception, e:
   265     except Exception, e:
   266         return None, e.message
   266         return None, e.message
   267 
   267 
   268 def LoadProject(filepath):
   268 def LoadProject(filepath):
   269     project_file = open(filepath)
   269     project_file = open(filepath)
   286     return project_pou_instances_xpath[body_type](root), error
   286     return project_pou_instances_xpath[body_type](root), error
   287 
   287 
   288 def SaveProject(project, filepath):
   288 def SaveProject(project, filepath):
   289     project_file = open(filepath, 'w')
   289     project_file = open(filepath, 'w')
   290     project_file.write(etree.tostring(
   290     project_file.write(etree.tostring(
   291         project, 
   291         project,
   292         pretty_print=True, 
   292         pretty_print=True,
   293         xml_declaration=True, 
   293         xml_declaration=True,
   294         encoding='utf-8'))
   294         encoding='utf-8'))
   295     project_file.close()
   295     project_file.close()
   296 
   296 
   297 cls = PLCOpenParser.GetElementClass("formattedText")
   297 cls = PLCOpenParser.GetElementClass("formattedText")
   298 if cls:
   298 if cls:
   300         text = self.getanyText()
   300         text = self.getanyText()
   301         pattern = re.compile('\\b' + old_name + '\\b', re.IGNORECASE)
   301         pattern = re.compile('\\b' + old_name + '\\b', re.IGNORECASE)
   302         text = pattern.sub(new_name, text)
   302         text = pattern.sub(new_name, text)
   303         self.setanyText(text)
   303         self.setanyText(text)
   304     setattr(cls, "updateElementName", updateElementName)
   304     setattr(cls, "updateElementName", updateElementName)
   305     
   305 
   306     def updateElementAddress(self, address_model, new_leading):
   306     def updateElementAddress(self, address_model, new_leading):
   307         text = self.getanyText()
   307         text = self.getanyText()
   308         startpos = 0
   308         startpos = 0
   309         result = address_model.search(text, startpos)
   309         result = address_model.search(text, startpos)
   310         while result is not None:
   310         while result is not None:
   313             text = text[:result.start()] + new_address + text[result.end():]
   313             text = text[:result.start()] + new_address + text[result.end():]
   314             startpos = result.start() + len(new_address)
   314             startpos = result.start() + len(new_address)
   315             result = address_model.search(text, startpos)
   315             result = address_model.search(text, startpos)
   316         self.setanyText(text)
   316         self.setanyText(text)
   317     setattr(cls, "updateElementAddress", updateElementAddress)
   317     setattr(cls, "updateElementAddress", updateElementAddress)
   318     
   318 
   319     def hasblock(self, block_type):
   319     def hasblock(self, block_type):
   320         text = self.getanyText()        
   320         text = self.getanyText()
   321         pattern = re.compile('\\b' + block_type + '\\b', re.IGNORECASE)
   321         pattern = re.compile('\\b' + block_type + '\\b', re.IGNORECASE)
   322         return pattern.search(text) is not None
   322         return pattern.search(text) is not None
   323     setattr(cls, "hasblock", hasblock)
   323     setattr(cls, "hasblock", hasblock)
   324     
   324 
   325     def Search(self, criteria, parent_infos):
   325     def Search(self, criteria, parent_infos):
   326         return [(tuple(parent_infos),) + result for result in TestTextElement(self.getanyText(), criteria)]
   326         return [(tuple(parent_infos),) + result for result in TestTextElement(self.getanyText(), criteria)]
   327     setattr(cls, "Search", Search)
   327     setattr(cls, "Search", Search)
   328     
   328 
   329 cls = PLCOpenParser.GetElementClass("project")
   329 cls = PLCOpenParser.GetElementClass("project")
   330 if cls:
   330 if cls:
   331     
   331 
   332     def setname(self, name):
   332     def setname(self, name):
   333         self.contentHeader.setname(name)
   333         self.contentHeader.setname(name)
   334     setattr(cls, "setname", setname)
   334     setattr(cls, "setname", setname)
   335         
   335 
   336     def getname(self):
   336     def getname(self):
   337         return self.contentHeader.getname()
   337         return self.contentHeader.getname()
   338     setattr(cls, "getname", getname)
   338     setattr(cls, "getname", getname)
   339     
   339 
   340     def getfileHeader(self):
   340     def getfileHeader(self):
   341         fileheader_obj = self.fileHeader
   341         fileheader_obj = self.fileHeader
   342         return {
   342         return {
   343             attr: value if value is not None else ""
   343             attr: value if value is not None else ""
   344             for attr, value in [
   344             for attr, value in [
   349                 ("productRelease", fileheader_obj.getproductRelease()),
   349                 ("productRelease", fileheader_obj.getproductRelease()),
   350                 ("creationDateTime", fileheader_obj.getcreationDateTime()),
   350                 ("creationDateTime", fileheader_obj.getcreationDateTime()),
   351                 ("contentDescription", fileheader_obj.getcontentDescription())]
   351                 ("contentDescription", fileheader_obj.getcontentDescription())]
   352         }
   352         }
   353     setattr(cls, "getfileHeader", getfileHeader)
   353     setattr(cls, "getfileHeader", getfileHeader)
   354     
   354 
   355     def setfileHeader(self, fileheader):
   355     def setfileHeader(self, fileheader):
   356         fileheader_obj = self.fileHeader
   356         fileheader_obj = self.fileHeader
   357         for attr in ["companyName", "companyURL", "productName",
   357         for attr in ["companyName", "companyURL", "productName",
   358                      "productVersion", "productRelease", "creationDateTime",
   358                      "productVersion", "productRelease", "creationDateTime",
   359                      "contentDescription"]:
   359                      "contentDescription"]:
   360             value = fileheader.get(attr)
   360             value = fileheader.get(attr)
   361             if value is not None:
   361             if value is not None:
   362                 setattr(fileheader_obj, attr, value)
   362                 setattr(fileheader_obj, attr, value)
   363     setattr(cls, "setfileHeader", setfileHeader)
   363     setattr(cls, "setfileHeader", setfileHeader)
   364     
   364 
   365     def getcontentHeader(self):
   365     def getcontentHeader(self):
   366         contentheader_obj = self.contentHeader
   366         contentheader_obj = self.contentHeader
   367         contentheader = {
   367         contentheader = {
   368             attr: value if value is not None else ""
   368             attr: value if value is not None else ""
   369             for attr, value in [
   369             for attr, value in [
   376         }
   376         }
   377         contentheader["pageSize"] = self.contentHeader.getpageSize()
   377         contentheader["pageSize"] = self.contentHeader.getpageSize()
   378         contentheader["scaling"] = self.contentHeader.getscaling()
   378         contentheader["scaling"] = self.contentHeader.getscaling()
   379         return contentheader
   379         return contentheader
   380     setattr(cls, "getcontentHeader", getcontentHeader)
   380     setattr(cls, "getcontentHeader", getcontentHeader)
   381     
   381 
   382     def setcontentHeader(self, contentheader):
   382     def setcontentHeader(self, contentheader):
   383         contentheader_obj = self.contentHeader
   383         contentheader_obj = self.contentHeader
   384         for attr, value in contentheader.iteritems():
   384         for attr, value in contentheader.iteritems():
   385             func = {"projectName": contentheader_obj.setname,
   385             func = {"projectName": contentheader_obj.setname,
   386                     "projectVersion": contentheader_obj.setversion,
   386                     "projectVersion": contentheader_obj.setversion,
   390             if func is not None:
   390             if func is not None:
   391                 func(value)
   391                 func(value)
   392             elif attr in ["modificationDateTime", "organization", "language"]:
   392             elif attr in ["modificationDateTime", "organization", "language"]:
   393                 setattr(contentheader_obj, attr, value)
   393                 setattr(contentheader_obj, attr, value)
   394     setattr(cls, "setcontentHeader", setcontentHeader)
   394     setattr(cls, "setcontentHeader", setcontentHeader)
   395     
   395 
   396     def gettypeElementFunc(element_type):
   396     def gettypeElementFunc(element_type):
   397         elements_xpath = PLCOpen_XPath(
   397         elements_xpath = PLCOpen_XPath(
   398             "ppx:types/ppx:%(element_type)ss/ppx:%(element_type)s[@name=$name]" % locals())
   398             "ppx:types/ppx:%(element_type)ss/ppx:%(element_type)s[@name=$name]" % locals())
   399         def gettypeElement(self, name):
   399         def gettypeElement(self, name):
   400             elements = elements_xpath(self, name=name)
   400             elements = elements_xpath(self, name=name)
   401             if len(elements) == 1:
   401             if len(elements) == 1:
   402                 return elements[0]
   402                 return elements[0]
   403             return None
   403             return None
   404         return gettypeElement
   404         return gettypeElement
   405     
   405 
   406     datatypes_xpath = PLCOpen_XPath("ppx:types/ppx:dataTypes/ppx:dataType")
   406     datatypes_xpath = PLCOpen_XPath("ppx:types/ppx:dataTypes/ppx:dataType")
   407     filtered_datatypes_xpath = PLCOpen_XPath(
   407     filtered_datatypes_xpath = PLCOpen_XPath(
   408         "ppx:types/ppx:dataTypes/ppx:dataType[@name!=$exclude]")
   408         "ppx:types/ppx:dataTypes/ppx:dataType[@name!=$exclude]")
   409     def getdataTypes(self, exclude=None):
   409     def getdataTypes(self, exclude=None):
   410         if exclude is not None:
   410         if exclude is not None:
   411             return filtered_datatypes_xpath(self, exclude=exclude)
   411             return filtered_datatypes_xpath(self, exclude=exclude)
   412         return datatypes_xpath(self)
   412         return datatypes_xpath(self)
   413     setattr(cls, "getdataTypes", getdataTypes)
   413     setattr(cls, "getdataTypes", getdataTypes)
   414     
   414 
   415     setattr(cls, "getdataType", gettypeElementFunc("dataType"))
   415     setattr(cls, "getdataType", gettypeElementFunc("dataType"))
   416     
   416 
   417     def appenddataType(self, name):
   417     def appenddataType(self, name):
   418         if self.getdataType(name) is not None:
   418         if self.getdataType(name) is not None:
   419             raise ValueError, "\"%s\" Data Type already exists !!!"%name
   419             raise ValueError, "\"%s\" Data Type already exists !!!"%name
   420         self.types.appenddataTypeElement(name)
   420         self.types.appenddataTypeElement(name)
   421     setattr(cls, "appenddataType", appenddataType)
   421     setattr(cls, "appenddataType", appenddataType)
   422         
   422 
   423     def insertdataType(self, index, datatype):
   423     def insertdataType(self, index, datatype):
   424         self.types.insertdataTypeElement(index, datatype)
   424         self.types.insertdataTypeElement(index, datatype)
   425     setattr(cls, "insertdataType", insertdataType)
   425     setattr(cls, "insertdataType", insertdataType)
   426     
   426 
   427     def removedataType(self, name):
   427     def removedataType(self, name):
   428         self.types.removedataTypeElement(name)
   428         self.types.removedataTypeElement(name)
   429     setattr(cls, "removedataType", removedataType)
   429     setattr(cls, "removedataType", removedataType)
   430     
   430 
   431     def getpous(self, exclude=None, filter=[]):
   431     def getpous(self, exclude=None, filter=[]):
   432         return self.xpath(
   432         return self.xpath(
   433             "ppx:types/ppx:pous/ppx:pou%s%s" % 
   433             "ppx:types/ppx:pous/ppx:pou%s%s" %
   434                 (("[@name!='%s']" % exclude) if exclude is not None else '',
   434                 (("[@name!='%s']" % exclude) if exclude is not None else '',
   435                  ("[%s]" % " or ".join(
   435                  ("[%s]" % " or ".join(
   436                     map(lambda x: "@pouType='%s'" % x, filter)))
   436                     map(lambda x: "@pouType='%s'" % x, filter)))
   437                  if len(filter) > 0 else ""),
   437                  if len(filter) > 0 else ""),
   438             namespaces=PLCOpenParser.NSMAP)
   438             namespaces=PLCOpenParser.NSMAP)
   439     setattr(cls, "getpous", getpous)
   439     setattr(cls, "getpous", getpous)
   440     
   440 
   441     setattr(cls, "getpou", gettypeElementFunc("pou"))
   441     setattr(cls, "getpou", gettypeElementFunc("pou"))
   442     
   442 
   443     def appendpou(self, name, pou_type, body_type):
   443     def appendpou(self, name, pou_type, body_type):
   444         self.types.appendpouElement(name, pou_type, body_type)
   444         self.types.appendpouElement(name, pou_type, body_type)
   445     setattr(cls, "appendpou", appendpou)
   445     setattr(cls, "appendpou", appendpou)
   446         
   446 
   447     def insertpou(self, index, pou):
   447     def insertpou(self, index, pou):
   448         self.types.insertpouElement(index, pou)
   448         self.types.insertpouElement(index, pou)
   449     setattr(cls, "insertpou", insertpou)
   449     setattr(cls, "insertpou", insertpou)
   450     
   450 
   451     def removepou(self, name):
   451     def removepou(self, name):
   452         self.types.removepouElement(name)
   452         self.types.removepouElement(name)
   453     setattr(cls, "removepou", removepou)
   453     setattr(cls, "removepou", removepou)
   454 
   454 
   455     configurations_xpath = PLCOpen_XPath(
   455     configurations_xpath = PLCOpen_XPath(
   471         if self.getconfiguration(name) is not None:
   471         if self.getconfiguration(name) is not None:
   472             raise ValueError, _("\"%s\" configuration already exists !!!") % name
   472             raise ValueError, _("\"%s\" configuration already exists !!!") % name
   473         new_configuration = PLCOpenParser.CreateElement("configuration", "configurations")
   473         new_configuration = PLCOpenParser.CreateElement("configuration", "configurations")
   474         new_configuration.setname(name)
   474         new_configuration.setname(name)
   475         self.instances.configurations.appendconfiguration(new_configuration)
   475         self.instances.configurations.appendconfiguration(new_configuration)
   476     setattr(cls, "addconfiguration", addconfiguration)    
   476     setattr(cls, "addconfiguration", addconfiguration)
   477 
   477 
   478     def removeconfiguration(self, name):
   478     def removeconfiguration(self, name):
   479         configuration = self.getconfiguration(name)
   479         configuration = self.getconfiguration(name)
   480         if configuration is None:
   480         if configuration is None:
   481             raise ValueError, ("\"%s\" configuration doesn't exist !!!") % name
   481             raise ValueError, ("\"%s\" configuration doesn't exist !!!") % name
   482         self.instances.configurations.remove(configuration)
   482         self.instances.configurations.remove(configuration)
   483     setattr(cls, "removeconfiguration", removeconfiguration)
   483     setattr(cls, "removeconfiguration", removeconfiguration)
   484     
   484 
   485     resources_xpath = PLCOpen_XPath(
   485     resources_xpath = PLCOpen_XPath(
   486         "ppx:instances/ppx:configurations/ppx:configuration[@name=$configname]/ppx:resource[@name=$name]")
   486         "ppx:instances/ppx:configurations/ppx:configuration[@name=$configname]/ppx:resource[@name=$name]")
   487     def getconfigurationResource(self, config_name, name):
   487     def getconfigurationResource(self, config_name, name):
   488         resources = resources_xpath(self, configname=config_name, name=name)
   488         resources = resources_xpath(self, configname=config_name, name=name)
   489         if len(resources) == 1:
   489         if len(resources) == 1:
   560         return result
   560         return result
   561     setattr(cls, "Search", Search)
   561     setattr(cls, "Search", Search)
   562 
   562 
   563 cls = PLCOpenParser.GetElementClass("contentHeader", "project")
   563 cls = PLCOpenParser.GetElementClass("contentHeader", "project")
   564 if cls:
   564 if cls:
   565     
   565 
   566     def setpageSize(self, width, height):
   566     def setpageSize(self, width, height):
   567         self.coordinateInfo.setpageSize(width, height)
   567         self.coordinateInfo.setpageSize(width, height)
   568     setattr(cls, "setpageSize", setpageSize)
   568     setattr(cls, "setpageSize", setpageSize)
   569     
   569 
   570     def getpageSize(self):
   570     def getpageSize(self):
   571         return self.coordinateInfo.getpageSize()
   571         return self.coordinateInfo.getpageSize()
   572     setattr(cls, "getpageSize", getpageSize)
   572     setattr(cls, "getpageSize", getpageSize)
   573 
   573 
   574     def setscaling(self, scaling):
   574     def setscaling(self, scaling):
   575         for language, (x, y) in scaling.items():
   575         for language, (x, y) in scaling.items():
   576             self.coordinateInfo.setscaling(language, x, y)
   576             self.coordinateInfo.setscaling(language, x, y)
   577     setattr(cls, "setscaling", setscaling)
   577     setattr(cls, "setscaling", setscaling)
   578     
   578 
   579     def getscaling(self):
   579     def getscaling(self):
   580         scaling = {}
   580         scaling = {}
   581         scaling["FBD"] = self.coordinateInfo.getscaling("FBD")
   581         scaling["FBD"] = self.coordinateInfo.getscaling("FBD")
   582         scaling["LD"] = self.coordinateInfo.getscaling("LD")
   582         scaling["LD"] = self.coordinateInfo.getscaling("LD")
   583         scaling["SFC"] = self.coordinateInfo.getscaling("SFC")
   583         scaling["SFC"] = self.coordinateInfo.getscaling("SFC")
   593             if self.pageSize is None:
   593             if self.pageSize is None:
   594                 self.addpageSize()
   594                 self.addpageSize()
   595             self.pageSize.setx(width)
   595             self.pageSize.setx(width)
   596             self.pageSize.sety(height)
   596             self.pageSize.sety(height)
   597     setattr(cls, "setpageSize", setpageSize)
   597     setattr(cls, "setpageSize", setpageSize)
   598     
   598 
   599     def getpageSize(self):
   599     def getpageSize(self):
   600         if self.pageSize is not None:
   600         if self.pageSize is not None:
   601             return self.pageSize.getx(), self.pageSize.gety()
   601             return self.pageSize.getx(), self.pageSize.gety()
   602         return 0, 0
   602         return 0, 0
   603     setattr(cls, "getpageSize", getpageSize)
   603     setattr(cls, "getpageSize", getpageSize)
   611             self.ld.scaling.sety(y)
   611             self.ld.scaling.sety(y)
   612         elif language == "SFC":
   612         elif language == "SFC":
   613             self.sfc.scaling.setx(x)
   613             self.sfc.scaling.setx(x)
   614             self.sfc.scaling.sety(y)
   614             self.sfc.scaling.sety(y)
   615     setattr(cls, "setscaling", setscaling)
   615     setattr(cls, "setscaling", setscaling)
   616     
   616 
   617     def getscaling(self, language):
   617     def getscaling(self, language):
   618         if language == "FBD":
   618         if language == "FBD":
   619             return self.fbd.scaling.getx(), self.fbd.scaling.gety()
   619             return self.fbd.scaling.getx(), self.fbd.scaling.gety()
   620         elif language == "LD":
   620         elif language == "LD":
   621             return self.ld.scaling.getx(), self.ld.scaling.gety()
   621             return self.ld.scaling.getx(), self.ld.scaling.gety()
   683             var_number += 1
   683             var_number += 1
   684     return search_result
   684     return search_result
   685 
   685 
   686 cls = PLCOpenParser.GetElementClass("configuration", "configurations")
   686 cls = PLCOpenParser.GetElementClass("configuration", "configurations")
   687 if cls:
   687 if cls:
   688     
   688 
   689     def addglobalVar(self, var_type, name, location="", description=""):
   689     def addglobalVar(self, var_type, name, location="", description=""):
   690         globalvars = self.getglobalVars()
   690         globalvars = self.getglobalVars()
   691         if len(globalvars) == 0:
   691         if len(globalvars) == 0:
   692             globalvars.append(PLCOpenParser.CreateElement("varList"))
   692             globalvars.append(PLCOpenParser.CreateElement("varList"))
   693         var = PLCOpenParser.CreateElement("variable", "varListPlain")
   693         var = PLCOpenParser.CreateElement("variable", "varListPlain")
   699             ft = PLCOpenParser.CreateElement("documentation", "variable")
   699             ft = PLCOpenParser.CreateElement("documentation", "variable")
   700             ft.setanyText(description)
   700             ft.setanyText(description)
   701             var.setdocumentation(ft)
   701             var.setdocumentation(ft)
   702         globalvars[-1].appendvariable(var)
   702         globalvars[-1].appendvariable(var)
   703     setattr(cls, "addglobalVar", addglobalVar)
   703     setattr(cls, "addglobalVar", addglobalVar)
   704     
   704 
   705     def updateElementName(self, old_name, new_name):
   705     def updateElementName(self, old_name, new_name):
   706         _updateConfigurationResourceElementName(self, old_name, new_name)
   706         _updateConfigurationResourceElementName(self, old_name, new_name)
   707         for resource in self.getresource():
   707         for resource in self.getresource():
   708             resource.updateElementName(old_name, new_name)
   708             resource.updateElementName(old_name, new_name)
   709     setattr(cls, "updateElementName", updateElementName)
   709     setattr(cls, "updateElementName", updateElementName)
   725             search_result = _SearchInConfigurationResource(self, criteria, parent_infos)
   725             search_result = _SearchInConfigurationResource(self, criteria, parent_infos)
   726             for resource in self.getresource():
   726             for resource in self.getresource():
   727                 search_result.extend(resource.Search(criteria, parent_infos))
   727                 search_result.extend(resource.Search(criteria, parent_infos))
   728         return search_result
   728         return search_result
   729     setattr(cls, "Search", Search)
   729     setattr(cls, "Search", Search)
   730     
   730 
   731 cls = PLCOpenParser.GetElementClass("resource", "configuration")
   731 cls = PLCOpenParser.GetElementClass("resource", "configuration")
   732 if cls:
   732 if cls:
   733     def updateElementName(self, old_name, new_name):
   733     def updateElementName(self, old_name, new_name):
   734         _updateConfigurationResourceElementName(self, old_name, new_name)
   734         _updateConfigurationResourceElementName(self, old_name, new_name)
   735         for instance in self.getpouInstance():
   735         for instance in self.getpouInstance():
   786         if self.interval is not None:
   786         if self.interval is not None:
   787             self.interval = update_address(self.interval, address_model, new_leading)
   787             self.interval = update_address(self.interval, address_model, new_leading)
   788     setattr(cls, "updateElementAddress", updateElementAddress)
   788     setattr(cls, "updateElementAddress", updateElementAddress)
   789 
   789 
   790     def Search(self, criteria, parent_infos=[]):
   790     def Search(self, criteria, parent_infos=[]):
   791         return _Search([("single", self.getsingle()), 
   791         return _Search([("single", self.getsingle()),
   792                         ("interval", self.getinterval()),
   792                         ("interval", self.getinterval()),
   793                         ("priority", str(self.getpriority()))],
   793                         ("priority", str(self.getpriority()))],
   794                        criteria, parent_infos)
   794                        criteria, parent_infos)
   795     setattr(cls, "Search", Search)
   795     setattr(cls, "Search", Search)
   796 
   796 
   800         if TextMatched(self.typeName, old_name):
   800         if TextMatched(self.typeName, old_name):
   801             self.typeName = new_name
   801             self.typeName = new_name
   802     setattr(cls, "updateElementName", updateElementName)
   802     setattr(cls, "updateElementName", updateElementName)
   803 
   803 
   804     def Search(self, criteria, parent_infos=[]):
   804     def Search(self, criteria, parent_infos=[]):
   805         return _Search([("name", self.getname()), 
   805         return _Search([("name", self.getname()),
   806                         ("type", self.gettypeName())],
   806                         ("type", self.gettypeName())],
   807                        criteria, parent_infos)
   807                        criteria, parent_infos)
   808     setattr(cls, "Search", Search)
   808     setattr(cls, "Search", Search)
   809 
   809 
   810 cls = PLCOpenParser.GetElementClass("variable", "varListPlain")
   810 cls = PLCOpenParser.GetElementClass("variable", "varListPlain")
   820             return vartype_content_name.upper()
   820             return vartype_content_name.upper()
   821         # Variable type is an array
   821         # Variable type is an array
   822         elif vartype_content_name == "array":
   822         elif vartype_content_name == "array":
   823             base_type = vartype_content.baseType.getcontent()
   823             base_type = vartype_content.baseType.getcontent()
   824             base_type_name = base_type.getLocalTag()
   824             base_type_name = base_type.getLocalTag()
   825             # Array derived directly from a user defined type 
   825             # Array derived directly from a user defined type
   826             if base_type_name == "derived":
   826             if base_type_name == "derived":
   827                 basetype_name = base_type.getname()
   827                 basetype_name = base_type.getname()
   828             # Array derived directly from a string type 
   828             # Array derived directly from a string type
   829             elif base_type_name in ["string", "wstring"]:
   829             elif base_type_name in ["string", "wstring"]:
   830                 basetype_name = base_type_name.upper()
   830                 basetype_name = base_type_name.upper()
   831             # Array derived directly from an elementary type 
   831             # Array derived directly from an elementary type
   832             else:
   832             else:
   833                 basetype_name = base_type_name
   833                 basetype_name = base_type_name
   834             return "ARRAY [%s] OF %s" % (",".join(map(lambda x : "%s..%s" % (x.getlower(), x.getupper()), vartype_content.getdimension())), basetype_name)
   834             return "ARRAY [%s] OF %s" % (",".join(map(lambda x : "%s..%s" % (x.getlower(), x.getupper()), vartype_content.getdimension())), basetype_name)
   835         # Variable type is an elementary type
   835         # Variable type is an elementary type
   836         return vartype_content_name
   836         return vartype_content_name
   837     setattr(cls, "gettypeAsText", gettypeAsText)
   837     setattr(cls, "gettypeAsText", gettypeAsText)
   838     
   838 
   839     def Search(self, criteria, parent_infos=[]):
   839     def Search(self, criteria, parent_infos=[]):
   840         search_result = _Search([("name", self.getname()), 
   840         search_result = _Search([("name", self.getname()),
   841                                  ("type", self.gettypeAsText()),
   841                                  ("type", self.gettypeAsText()),
   842                                  ("location", self.getaddress())],
   842                                  ("location", self.getaddress())],
   843                                 criteria, parent_infos)
   843                                 criteria, parent_infos)
   844         initial = self.getinitialValue()
   844         initial = self.getinitialValue()
   845         if initial is not None:
   845         if initial is not None:
   853 cls = PLCOpenParser.GetElementClass("types", "project")
   853 cls = PLCOpenParser.GetElementClass("types", "project")
   854 if cls:
   854 if cls:
   855     def getdataTypeElements(self):
   855     def getdataTypeElements(self):
   856         return self.dataTypes.getdataType()
   856         return self.dataTypes.getdataType()
   857     setattr(cls, "getdataTypeElements", getdataTypeElements)
   857     setattr(cls, "getdataTypeElements", getdataTypeElements)
   858     
   858 
   859     def getdataTypeElement(self, name):
   859     def getdataTypeElement(self, name):
   860         elements = self.dataTypes.getdataType()
   860         elements = self.dataTypes.getdataType()
   861         for element in elements:
   861         for element in elements:
   862             if TextMatched(element.getname(), name):
   862             if TextMatched(element.getname(), name):
   863                 return element
   863                 return element
   868         new_datatype = PLCOpenParser.CreateElement("dataType", "dataTypes")
   868         new_datatype = PLCOpenParser.CreateElement("dataType", "dataTypes")
   869         self.dataTypes.appenddataType(new_datatype)
   869         self.dataTypes.appenddataType(new_datatype)
   870         new_datatype.setname(name)
   870         new_datatype.setname(name)
   871         new_datatype.baseType.setcontent(PLCOpenParser.CreateElement("BOOL", "dataType"))
   871         new_datatype.baseType.setcontent(PLCOpenParser.CreateElement("BOOL", "dataType"))
   872     setattr(cls, "appenddataTypeElement", appenddataTypeElement)
   872     setattr(cls, "appenddataTypeElement", appenddataTypeElement)
   873     
   873 
   874     def insertdataTypeElement(self, index, dataType):
   874     def insertdataTypeElement(self, index, dataType):
   875         self.dataTypes.insertdataType(index, dataType)
   875         self.dataTypes.insertdataType(index, dataType)
   876     setattr(cls, "insertdataTypeElement", insertdataTypeElement)
   876     setattr(cls, "insertdataTypeElement", insertdataTypeElement)
   877     
   877 
   878     def removedataTypeElement(self, name):
   878     def removedataTypeElement(self, name):
   879         found = False
   879         found = False
   880         for element in self.dataTypes.getdataType():
   880         for element in self.dataTypes.getdataType():
   881             if TextMatched(element.getname(), name):
   881             if TextMatched(element.getname(), name):
   882                 self.dataTypes.remove(element)
   882                 self.dataTypes.remove(element)
   883                 found = True
   883                 found = True
   884                 break
   884                 break
   885         if not found:
   885         if not found:
   886             raise ValueError, _("\"%s\" Data Type doesn't exist !!!")%name
   886             raise ValueError, _("\"%s\" Data Type doesn't exist !!!")%name
   887     setattr(cls, "removedataTypeElement", removedataTypeElement)
   887     setattr(cls, "removedataTypeElement", removedataTypeElement)
   888     
   888 
   889     def getpouElements(self):
   889     def getpouElements(self):
   890         return self.pous.getpou()
   890         return self.pous.getpou()
   891     setattr(cls, "getpouElements", getpouElements)
   891     setattr(cls, "getpouElements", getpouElements)
   892     
   892 
   893     def getpouElement(self, name):
   893     def getpouElement(self, name):
   894         elements = self.pous.getpou()
   894         elements = self.pous.getpou()
   895         for element in elements:
   895         for element in elements:
   896             if TextMatched(element.getname(), name):
   896             if TextMatched(element.getname(), name):
   897                 return element
   897                 return element
   907         new_pou.setname(name)
   907         new_pou.setname(name)
   908         new_pou.setpouType(pou_type)
   908         new_pou.setpouType(pou_type)
   909         new_pou.appendbody(PLCOpenParser.CreateElement("body", "pou"))
   909         new_pou.appendbody(PLCOpenParser.CreateElement("body", "pou"))
   910         new_pou.setbodyType(body_type)
   910         new_pou.setbodyType(body_type)
   911     setattr(cls, "appendpouElement", appendpouElement)
   911     setattr(cls, "appendpouElement", appendpouElement)
   912         
   912 
   913     def insertpouElement(self, index, pou):
   913     def insertpouElement(self, index, pou):
   914         self.pous.insertpou(index, pou)
   914         self.pous.insertpou(index, pou)
   915     setattr(cls, "insertpouElement", insertpouElement)
   915     setattr(cls, "insertpouElement", insertpouElement)
   916     
   916 
   917     def removepouElement(self, name):
   917     def removepouElement(self, name):
   918         found = False
   918         found = False
   919         for element in self.pous.getpou():
   919         for element in self.pous.getpou():
   920             if TextMatched(element.getname(), name):
   920             if TextMatched(element.getname(), name):
   921                 self.pous.remove(element)
   921                 self.pous.remove(element)
   939     self.baseType.updateElementName(old_name, new_name)
   939     self.baseType.updateElementName(old_name, new_name)
   940 
   940 
   941 cls = PLCOpenParser.GetElementClass("dataType", "dataTypes")
   941 cls = PLCOpenParser.GetElementClass("dataType", "dataTypes")
   942 if cls:
   942 if cls:
   943     setattr(cls, "updateElementName", _updateBaseTypeElementName)
   943     setattr(cls, "updateElementName", _updateBaseTypeElementName)
   944     
   944 
   945     def Search(self, criteria, parent_infos=[]):
   945     def Search(self, criteria, parent_infos=[]):
   946         search_result = []
   946         search_result = []
   947         filter = criteria["filter"]
   947         filter = criteria["filter"]
   948         if filter == "all" or "datatype" in filter:
   948         if filter == "all" or "datatype" in filter:
   949             parent_infos = parent_infos + ["D::%s" % self.getname()]
   949             parent_infos = parent_infos + ["D::%s" % self.getname()]
   954         return search_result
   954         return search_result
   955     setattr(cls, "Search", Search)
   955     setattr(cls, "Search", Search)
   956 
   956 
   957 cls = PLCOpenParser.GetElementClass("dataType")
   957 cls = PLCOpenParser.GetElementClass("dataType")
   958 if cls:
   958 if cls:
   959     
   959 
   960     def updateElementName(self, old_name, new_name):
   960     def updateElementName(self, old_name, new_name):
   961         content_name = self.content.getLocalTag()
   961         content_name = self.content.getLocalTag()
   962         if content_name in ["derived", "array", "subrangeSigned", "subrangeUnsigned"]:
   962         if content_name in ["derived", "array", "subrangeSigned", "subrangeUnsigned"]:
   963             self.content.updateElementName(old_name, new_name)
   963             self.content.updateElementName(old_name, new_name)
   964         elif content_name == "struct":
   964         elif content_name == "struct":
   985 if cls:
   985 if cls:
   986     def updateElementName(self, old_name, new_name):
   986     def updateElementName(self, old_name, new_name):
   987         if TextMatched(self.name, old_name):
   987         if TextMatched(self.name, old_name):
   988             self.name = new_name
   988             self.name = new_name
   989     setattr(cls, "updateElementName", updateElementName)
   989     setattr(cls, "updateElementName", updateElementName)
   990     
   990 
   991     def Search(self, criteria, parent_infos=[]):
   991     def Search(self, criteria, parent_infos=[]):
   992         return [(tuple(parent_infos),) + result for result in TestTextElement(self.name, criteria)]
   992         return [(tuple(parent_infos),) + result for result in TestTextElement(self.name, criteria)]
   993     setattr(cls, "Search", Search)
   993     setattr(cls, "Search", Search)
   994 
   994 
   995 cls = PLCOpenParser.GetElementClass("array", "dataType")
   995 cls = PLCOpenParser.GetElementClass("array", "dataType")
   996 if cls:
   996 if cls:
   997     setattr(cls, "updateElementName", _updateBaseTypeElementName)
   997     setattr(cls, "updateElementName", _updateBaseTypeElementName)
   998     
   998 
   999     def Search(self, criteria, parent_infos=[]):
   999     def Search(self, criteria, parent_infos=[]):
  1000         search_result = self.baseType.Search(criteria, parent_infos)
  1000         search_result = self.baseType.Search(criteria, parent_infos)
  1001         for i, dimension in enumerate(self.getdimension()):
  1001         for i, dimension in enumerate(self.getdimension()):
  1002             search_result.extend(_Search([("lower", dimension.getlower()),
  1002             search_result.extend(_Search([("lower", dimension.getlower()),
  1003                                           ("upper", dimension.getupper())],
  1003                                           ("upper", dimension.getupper())],
  1022     setattr(cls, "updateElementName", _updateBaseTypeElementName)
  1022     setattr(cls, "updateElementName", _updateBaseTypeElementName)
  1023     setattr(cls, "Search", _SearchInSubrange)
  1023     setattr(cls, "Search", _SearchInSubrange)
  1024 
  1024 
  1025 cls = PLCOpenParser.GetElementClass("enum", "dataType")
  1025 cls = PLCOpenParser.GetElementClass("enum", "dataType")
  1026 if cls:
  1026 if cls:
  1027     
  1027 
  1028     def updateElementName(self, old_name, new_name):
  1028     def updateElementName(self, old_name, new_name):
  1029         pass
  1029         pass
  1030     setattr(cls, "updateElementName", updateElementName)
  1030     setattr(cls, "updateElementName", updateElementName)
  1031     
  1031 
  1032     enumerated_datatype_values_xpath = PLCOpen_XPath("ppx:values/ppx:value")
  1032     enumerated_datatype_values_xpath = PLCOpen_XPath("ppx:values/ppx:value")
  1033     def Search(self, criteria, parent_infos=[]):
  1033     def Search(self, criteria, parent_infos=[]):
  1034         search_result = []
  1034         search_result = []
  1035         for i, value in enumerate(enumerated_datatype_values_xpath(self)):
  1035         for i, value in enumerate(enumerated_datatype_values_xpath(self)):
  1036             for result in TestTextElement(value.getname(), criteria):
  1036             for result in TestTextElement(value.getname(), criteria):
  1042     type_content = variable_type.getcontent()
  1042     type_content = variable_type.getcontent()
  1043     type_content_type = type_content.getLocalTag()
  1043     type_content_type = type_content.getLocalTag()
  1044     if type_content_type == "derived":
  1044     if type_content_type == "derived":
  1045         return type_content.getname()
  1045         return type_content.getname()
  1046     return type_content_type.upper()
  1046     return type_content_type.upper()
  1047     
  1047 
  1048 cls = PLCOpenParser.GetElementClass("pou", "pous")
  1048 cls = PLCOpenParser.GetElementClass("pou", "pous")
  1049 if cls:
  1049 if cls:
  1050     
  1050 
  1051     block_inputs_xpath = PLCOpen_XPath(
  1051     block_inputs_xpath = PLCOpen_XPath(
  1052         "ppx:interface/*[self::ppx:inputVars or self::ppx:inOutVars]/ppx:variable")
  1052         "ppx:interface/*[self::ppx:inputVars or self::ppx:inOutVars]/ppx:variable")
  1053     block_outputs_xpath = PLCOpen_XPath(
  1053     block_outputs_xpath = PLCOpen_XPath(
  1054         "ppx:interface/*[self::ppx:outputVars or self::ppx:inOutVars]/ppx:variable")
  1054         "ppx:interface/*[self::ppx:outputVars or self::ppx:inOutVars]/ppx:variable")
  1055     def getblockInfos(self): 
  1055     def getblockInfos(self):
  1056         block_infos = {
  1056         block_infos = {
  1057             "name" : self.getname(), 
  1057             "name" : self.getname(),
  1058             "type" : self.getpouType(), 
  1058             "type" : self.getpouType(),
  1059             "extensible" : False,
  1059             "extensible" : False,
  1060             "inputs" : [], 
  1060             "inputs" : [],
  1061             "outputs" : [], 
  1061             "outputs" : [],
  1062             "comment" : self.getdescription()}
  1062             "comment" : self.getdescription()}
  1063         if self.interface is not None:
  1063         if self.interface is not None:
  1064             return_type = self.interface.getreturnType()
  1064             return_type = self.interface.getreturnType()
  1065             if return_type is not None:
  1065             if return_type is not None:
  1066                 block_infos["outputs"].append(
  1066                 block_infos["outputs"].append(
  1069                 [(var.getname(), _getvariableTypeinfos(var.type), "none")
  1069                 [(var.getname(), _getvariableTypeinfos(var.type), "none")
  1070                  for var in block_inputs_xpath(self)])
  1070                  for var in block_inputs_xpath(self)])
  1071             block_infos["outputs"].extend(
  1071             block_infos["outputs"].extend(
  1072                 [(var.getname(), _getvariableTypeinfos(var.type), "none")
  1072                 [(var.getname(), _getvariableTypeinfos(var.type), "none")
  1073                  for var in block_outputs_xpath(self)])
  1073                  for var in block_outputs_xpath(self)])
  1074             
  1074 
  1075         block_infos["usage"] = ("\n (%s) => (%s)" % 
  1075         block_infos["usage"] = ("\n (%s) => (%s)" %
  1076             (", ".join(["%s:%s" % (input[1], input[0]) 
  1076             (", ".join(["%s:%s" % (input[1], input[0])
  1077                         for input in block_infos["inputs"]]),
  1077                         for input in block_infos["inputs"]]),
  1078              ", ".join(["%s:%s" % (output[1], output[0]) 
  1078              ", ".join(["%s:%s" % (output[1], output[0])
  1079                         for output in block_infos["outputs"]])))
  1079                         for output in block_infos["outputs"]])))
  1080         return block_infos
  1080         return block_infos
  1081     setattr(cls, "getblockInfos", getblockInfos)
  1081     setattr(cls, "getblockInfos", getblockInfos)
  1082     
  1082 
  1083     def setdescription(self, description):
  1083     def setdescription(self, description):
  1084         doc = self.getdocumentation()
  1084         doc = self.getdocumentation()
  1085         if doc is None:
  1085         if doc is None:
  1086             doc = PLCOpenParser.CreateElement("documentation", "pou")
  1086             doc = PLCOpenParser.CreateElement("documentation", "pou")
  1087             self.setdocumentation(doc)
  1087             self.setdocumentation(doc)
  1088         doc.setanyText(description)
  1088         doc.setanyText(description)
  1089     setattr(cls, "setdescription", setdescription)
  1089     setattr(cls, "setdescription", setdescription)
  1090     
  1090 
  1091     def getdescription(self):
  1091     def getdescription(self):
  1092         doc = self.getdocumentation()
  1092         doc = self.getdocumentation()
  1093         if doc is not None:
  1093         if doc is not None:
  1094             return doc.getanyText()
  1094             return doc.getanyText()
  1095         return ""
  1095         return ""
  1096     setattr(cls, "getdescription", getdescription)
  1096     setattr(cls, "getdescription", getdescription)
  1097     
  1097 
  1098     def setbodyType(self, body_type):
  1098     def setbodyType(self, body_type):
  1099         if len(self.body) > 0:
  1099         if len(self.body) > 0:
  1100             if body_type in ["IL", "ST", "LD", "FBD", "SFC"]:
  1100             if body_type in ["IL", "ST", "LD", "FBD", "SFC"]:
  1101                 self.body[0].setcontent(PLCOpenParser.CreateElement(body_type, "body"))
  1101                 self.body[0].setcontent(PLCOpenParser.CreateElement(body_type, "body"))
  1102             else:
  1102             else:
  1103                 raise ValueError, "%s isn't a valid body type!"%type
  1103                 raise ValueError, "%s isn't a valid body type!"%type
  1104     setattr(cls, "setbodyType", setbodyType)
  1104     setattr(cls, "setbodyType", setbodyType)
  1105     
  1105 
  1106     def getbodyType(self):
  1106     def getbodyType(self):
  1107         if len(self.body) > 0:
  1107         if len(self.body) > 0:
  1108             return self.body[0].getcontent().getLocalTag()
  1108             return self.body[0].getcontent().getLocalTag()
  1109     setattr(cls, "getbodyType", getbodyType)
  1109     setattr(cls, "getbodyType", getbodyType)
  1110     
  1110 
  1111     def resetexecutionOrder(self):
  1111     def resetexecutionOrder(self):
  1112         if len(self.body) > 0:
  1112         if len(self.body) > 0:
  1113             self.body[0].resetexecutionOrder()
  1113             self.body[0].resetexecutionOrder()
  1114     setattr(cls, "resetexecutionOrder", resetexecutionOrder)
  1114     setattr(cls, "resetexecutionOrder", resetexecutionOrder)
  1115     
  1115 
  1116     def compileexecutionOrder(self):
  1116     def compileexecutionOrder(self):
  1117         if len(self.body) > 0:
  1117         if len(self.body) > 0:
  1118             self.body[0].compileexecutionOrder()
  1118             self.body[0].compileexecutionOrder()
  1119     setattr(cls, "compileexecutionOrder", compileexecutionOrder)
  1119     setattr(cls, "compileexecutionOrder", compileexecutionOrder)
  1120     
  1120 
  1121     def setelementExecutionOrder(self, instance, new_executionOrder):
  1121     def setelementExecutionOrder(self, instance, new_executionOrder):
  1122         if len(self.body) > 0:
  1122         if len(self.body) > 0:
  1123             self.body[0].setelementExecutionOrder(instance, new_executionOrder)
  1123             self.body[0].setelementExecutionOrder(instance, new_executionOrder)
  1124     setattr(cls, "setelementExecutionOrder", setelementExecutionOrder)
  1124     setattr(cls, "setelementExecutionOrder", setelementExecutionOrder)
  1125     
  1125 
  1126     def addinstance(self, instance):
  1126     def addinstance(self, instance):
  1127         if len(self.body) > 0:
  1127         if len(self.body) > 0:
  1128             self.body[0].appendcontentInstance(instance)
  1128             self.body[0].appendcontentInstance(instance)
  1129     setattr(cls, "addinstance", addinstance)
  1129     setattr(cls, "addinstance", addinstance)
  1130     
  1130 
  1131     def getinstances(self):
  1131     def getinstances(self):
  1132         if len(self.body) > 0:
  1132         if len(self.body) > 0:
  1133             return self.body[0].getcontentInstances()
  1133             return self.body[0].getcontentInstances()
  1134         return []
  1134         return []
  1135     setattr(cls, "getinstances", getinstances)
  1135     setattr(cls, "getinstances", getinstances)
  1136     
  1136 
  1137     def getinstance(self, id):
  1137     def getinstance(self, id):
  1138         if len(self.body) > 0:
  1138         if len(self.body) > 0:
  1139             return self.body[0].getcontentInstance(id)
  1139             return self.body[0].getcontentInstance(id)
  1140         return None
  1140         return None
  1141     setattr(cls, "getinstance", getinstance)
  1141     setattr(cls, "getinstance", getinstance)
  1142     
  1142 
  1143     def getinstancesIds(self):
  1143     def getinstancesIds(self):
  1144         if len(self.body) > 0:
  1144         if len(self.body) > 0:
  1145             return self.body[0].getcontentInstancesIds()
  1145             return self.body[0].getcontentInstancesIds()
  1146         return []
  1146         return []
  1147     setattr(cls, "getinstancesIds", getinstancesIds)
  1147     setattr(cls, "getinstancesIds", getinstancesIds)
  1148     
  1148 
  1149     def getinstanceByName(self, name):
  1149     def getinstanceByName(self, name):
  1150         if len(self.body) > 0:
  1150         if len(self.body) > 0:
  1151             return self.body[0].getcontentInstanceByName(name)
  1151             return self.body[0].getcontentInstanceByName(name)
  1152         return None
  1152         return None
  1153     setattr(cls, "getinstanceByName", getinstanceByName)
  1153     setattr(cls, "getinstanceByName", getinstanceByName)
  1154     
  1154 
  1155     def removeinstance(self, id):
  1155     def removeinstance(self, id):
  1156         if len(self.body) > 0:
  1156         if len(self.body) > 0:
  1157             self.body[0].removecontentInstance(id)
  1157             self.body[0].removecontentInstance(id)
  1158     setattr(cls, "removeinstance", removeinstance)
  1158     setattr(cls, "removeinstance", removeinstance)
  1159     
  1159 
  1160     def settext(self, text):
  1160     def settext(self, text):
  1161         if len(self.body) > 0:
  1161         if len(self.body) > 0:
  1162             self.body[0].settext(text)
  1162             self.body[0].settext(text)
  1163     setattr(cls, "settext", settext)
  1163     setattr(cls, "settext", settext)
  1164     
  1164 
  1165     def gettext(self):
  1165     def gettext(self):
  1166         if len(self.body) > 0:
  1166         if len(self.body) > 0:
  1167             return self.body[0].gettext()
  1167             return self.body[0].gettext()
  1168         return ""
  1168         return ""
  1169     setattr(cls, "gettext", gettext)
  1169     setattr(cls, "gettext", gettext)
  1176                 reverse_types[value] = name
  1176                 reverse_types[value] = name
  1177             for varlist in self.interface.getcontent():
  1177             for varlist in self.interface.getcontent():
  1178                 vars.append((reverse_types[varlist.getLocalTag()], varlist))
  1178                 vars.append((reverse_types[varlist.getLocalTag()], varlist))
  1179         return vars
  1179         return vars
  1180     setattr(cls, "getvars", getvars)
  1180     setattr(cls, "getvars", getvars)
  1181     
  1181 
  1182     def setvars(self, vars):
  1182     def setvars(self, vars):
  1183         if self.interface is None:
  1183         if self.interface is None:
  1184             self.interface = PLCOpenParser.CreateElement("interface", "pou")
  1184             self.interface = PLCOpenParser.CreateElement("interface", "pou")
  1185         self.interface.setcontent(vars)
  1185         self.interface.setcontent(vars)
  1186     setattr(cls, "setvars", setvars)
  1186     setattr(cls, "setvars", setvars)
  1187         
  1187 
  1188     def addpouExternalVar(self, var_type, name):
  1188     def addpouExternalVar(self, var_type, name):
  1189         self.addpouVar(var_type, name, "externalVars")
  1189         self.addpouVar(var_type, name, "externalVars")
  1190     setattr(cls, "addpouExternalVar", addpouExternalVar)
  1190     setattr(cls, "addpouExternalVar", addpouExternalVar)
  1191     
  1191 
  1192     def addpouVar(self, var_type, name, var_class="localVars", location="", description="", initval=""):
  1192     def addpouVar(self, var_type, name, var_class="localVars", location="", description="", initval=""):
  1193         if self.interface is None:
  1193         if self.interface is None:
  1194             self.interface = PLCOpenParser.CreateElement("interface", "pou")
  1194             self.interface = PLCOpenParser.CreateElement("interface", "pou")
  1195         content = self.interface.getcontent()
  1195         content = self.interface.getcontent()
  1196         if len(content) == 0:
  1196         if len(content) == 0:
  1216             var.setdocumentation(ft)
  1216             var.setdocumentation(ft)
  1217         if initval != "":
  1217         if initval != "":
  1218             el = PLCOpenParser.CreateElement("initialValue", "variable")
  1218             el = PLCOpenParser.CreateElement("initialValue", "variable")
  1219             el.setvalue(initval)
  1219             el.setvalue(initval)
  1220             var.setinitialValue(el)
  1220             var.setinitialValue(el)
  1221         
  1221 
  1222         varlist.appendvariable(var)
  1222         varlist.appendvariable(var)
  1223     setattr(cls, "addpouVar", addpouVar)
  1223     setattr(cls, "addpouVar", addpouVar)
  1224     setattr(cls, "addpouLocalVar", addpouVar)
  1224     setattr(cls, "addpouLocalVar", addpouVar)
  1225     
  1225 
  1226     def changepouVar(self, old_type, old_name, new_type, new_name):
  1226     def changepouVar(self, old_type, old_name, new_type, new_name):
  1227         if self.interface is not None:
  1227         if self.interface is not None:
  1228             content = self.interface.getcontent()
  1228             content = self.interface.getcontent()
  1229             for varlist in content:
  1229             for varlist in content:
  1230                 variables = varlist.getvariable()
  1230                 variables = varlist.getvariable()
  1234                         if vartype_content.getLocalTag() == "derived" and TextMatched(vartype_content.getname(), old_type):
  1234                         if vartype_content.getLocalTag() == "derived" and TextMatched(vartype_content.getname(), old_type):
  1235                             var.setname(new_name)
  1235                             var.setname(new_name)
  1236                             vartype_content.setname(new_type)
  1236                             vartype_content.setname(new_type)
  1237                             return
  1237                             return
  1238     setattr(cls, "changepouVar", changepouVar)
  1238     setattr(cls, "changepouVar", changepouVar)
  1239     
  1239 
  1240     def removepouVar(self, var_type, name):
  1240     def removepouVar(self, var_type, name):
  1241         if self.interface is not None:
  1241         if self.interface is not None:
  1242             content = self.interface.getcontent()
  1242             content = self.interface.getcontent()
  1243             for varlist in content:
  1243             for varlist in content:
  1244                 for var in varlist.getvariable():
  1244                 for var in varlist.getvariable():
  1253 
  1253 
  1254     def hasstep(self, name=None):
  1254     def hasstep(self, name=None):
  1255         if self.getbodyType() in ["SFC"]:
  1255         if self.getbodyType() in ["SFC"]:
  1256             for instance in self.getinstances():
  1256             for instance in self.getinstances():
  1257                 if isinstance(instance, PLCOpenParser.GetElementClass("step", "sfcObjects")) and TextMatched(instance.getname(), name):
  1257                 if isinstance(instance, PLCOpenParser.GetElementClass("step", "sfcObjects")) and TextMatched(instance.getname(), name):
  1258                     return True         
  1258                     return True
  1259         return False
  1259         return False
  1260     setattr(cls, "hasstep", hasstep)
  1260     setattr(cls, "hasstep", hasstep)
  1261     
  1261 
  1262     def hasblock(self, name=None, block_type=None):
  1262     def hasblock(self, name=None, block_type=None):
  1263         if self.getbodyType() in ["FBD", "LD", "SFC"]:
  1263         if self.getbodyType() in ["FBD", "LD", "SFC"]:
  1264             for instance in self.getinstances():
  1264             for instance in self.getinstances():
  1265                 if (isinstance(instance, PLCOpenParser.GetElementClass("block", "fbdObjects")) and 
  1265                 if (isinstance(instance, PLCOpenParser.GetElementClass("block", "fbdObjects")) and
  1266                     (TextMatched(instance.getinstanceName(), name) or TextMatched(instance.gettypeName(), block_type))):
  1266                     (TextMatched(instance.getinstanceName(), name) or TextMatched(instance.gettypeName(), block_type))):
  1267                     return True
  1267                     return True
  1268             if self.transitions:
  1268             if self.transitions:
  1269                 for transition in self.transitions.gettransition():
  1269                 for transition in self.transitions.gettransition():
  1270                     result = transition.hasblock(name, block_type)
  1270                     result = transition.hasblock(name, block_type)
  1277                         return result
  1277                         return result
  1278         elif block_type is not None and len(self.body) > 0:
  1278         elif block_type is not None and len(self.body) > 0:
  1279             return self.body[0].hasblock(block_type)
  1279             return self.body[0].hasblock(block_type)
  1280         return False
  1280         return False
  1281     setattr(cls, "hasblock", hasblock)
  1281     setattr(cls, "hasblock", hasblock)
  1282     
  1282 
  1283     def addtransition(self, name, body_type):
  1283     def addtransition(self, name, body_type):
  1284         if self.transitions is None:
  1284         if self.transitions is None:
  1285             self.addtransitions()
  1285             self.addtransitions()
  1286             self.transitions.settransition([])
  1286             self.transitions.settransition([])
  1287         transition = PLCOpenParser.CreateElement("transition", "transitions")
  1287         transition = PLCOpenParser.CreateElement("transition", "transitions")
  1289         transition.setname(name)
  1289         transition.setname(name)
  1290         transition.setbodyType(body_type)
  1290         transition.setbodyType(body_type)
  1291         if body_type == "ST":
  1291         if body_type == "ST":
  1292             transition.settext(":= ;")
  1292             transition.settext(":= ;")
  1293     setattr(cls, "addtransition", addtransition)
  1293     setattr(cls, "addtransition", addtransition)
  1294     
  1294 
  1295     def gettransition(self, name):
  1295     def gettransition(self, name):
  1296         if self.transitions is not None:
  1296         if self.transitions is not None:
  1297             for transition in self.transitions.gettransition():
  1297             for transition in self.transitions.gettransition():
  1298                 if TextMatched(transition.getname(), name):
  1298                 if TextMatched(transition.getname(), name):
  1299                     return transition
  1299                     return transition
  1300         return None
  1300         return None
  1301     setattr(cls, "gettransition", gettransition)
  1301     setattr(cls, "gettransition", gettransition)
  1302         
  1302 
  1303     def gettransitionList(self):
  1303     def gettransitionList(self):
  1304         if self.transitions is not None:
  1304         if self.transitions is not None:
  1305             return self.transitions.gettransition()
  1305             return self.transitions.gettransition()
  1306         return []
  1306         return []
  1307     setattr(cls, "gettransitionList", gettransitionList)
  1307     setattr(cls, "gettransitionList", gettransitionList)
  1308     
  1308 
  1309     def removetransition(self, name):
  1309     def removetransition(self, name):
  1310         if self.transitions is not None:
  1310         if self.transitions is not None:
  1311             removed = False
  1311             removed = False
  1312             for transition in self.transitions.gettransition():
  1312             for transition in self.transitions.gettransition():
  1313                 if TextMatched(transition.getname(), name):
  1313                 if TextMatched(transition.getname(), name):
  1314                     if transition.getbodyType() in ["FBD", "LD", "SFC"]:
  1314                     if transition.getbodyType() in ["FBD", "LD", "SFC"]:
  1315                         for instance in transition.getinstances():
  1315                         for instance in transition.getinstances():
  1316                             if isinstance(instance, PLCOpenParser.GetElementClass("block", "fbdObjects")):
  1316                             if isinstance(instance, PLCOpenParser.GetElementClass("block", "fbdObjects")):
  1317                                 self.removepouVar(instance.gettypeName(), 
  1317                                 self.removepouVar(instance.gettypeName(),
  1318                                                   instance.getinstanceName())
  1318                                                   instance.getinstanceName())
  1319                     self.transitions.remove(transition)
  1319                     self.transitions.remove(transition)
  1320                     removed = True
  1320                     removed = True
  1321                     break
  1321                     break
  1322             if not removed:
  1322             if not removed:
  1330         action = PLCOpenParser.CreateElement("action", "actions")
  1330         action = PLCOpenParser.CreateElement("action", "actions")
  1331         self.actions.appendaction(action)
  1331         self.actions.appendaction(action)
  1332         action.setname(name)
  1332         action.setname(name)
  1333         action.setbodyType(body_type)
  1333         action.setbodyType(body_type)
  1334     setattr(cls, "addaction", addaction)
  1334     setattr(cls, "addaction", addaction)
  1335     
  1335 
  1336     def getaction(self, name):
  1336     def getaction(self, name):
  1337         if self.actions is not None:
  1337         if self.actions is not None:
  1338             for action in self.actions.getaction():
  1338             for action in self.actions.getaction():
  1339                 if TextMatched(action.getname(), name):
  1339                 if TextMatched(action.getname(), name):
  1340                     return action
  1340                     return action
  1341         return None
  1341         return None
  1342     setattr(cls, "getaction", getaction)
  1342     setattr(cls, "getaction", getaction)
  1343     
  1343 
  1344     def getactionList(self):
  1344     def getactionList(self):
  1345         if self.actions is not None:
  1345         if self.actions is not None:
  1346             return self.actions.getaction()
  1346             return self.actions.getaction()
  1347         return []
  1347         return []
  1348     setattr(cls, "getactionList", getactionList)
  1348     setattr(cls, "getactionList", getactionList)
  1349     
  1349 
  1350     def removeaction(self, name):
  1350     def removeaction(self, name):
  1351         if self.actions is not None:
  1351         if self.actions is not None:
  1352             removed = False
  1352             removed = False
  1353             for action in self.actions.getaction():
  1353             for action in self.actions.getaction():
  1354                 if TextMatched(action.getname(), name):
  1354                 if TextMatched(action.getname(), name):
  1355                     if action.getbodyType() in ["FBD", "LD", "SFC"]:
  1355                     if action.getbodyType() in ["FBD", "LD", "SFC"]:
  1356                         for instance in action.getinstances():
  1356                         for instance in action.getinstances():
  1357                             if isinstance(instance, PLCOpenParser.GetElementClass("block", "fbdObjects")):
  1357                             if isinstance(instance, PLCOpenParser.GetElementClass("block", "fbdObjects")):
  1358                                 self.removepouVar(instance.gettypeName(), 
  1358                                 self.removepouVar(instance.gettypeName(),
  1359                                                   instance.getinstanceName())
  1359                                                   instance.getinstanceName())
  1360                     self.actions.remove(action)
  1360                     self.actions.remove(action)
  1361                     removed = True
  1361                     removed = True
  1362                     break
  1362                     break
  1363             if not removed:
  1363             if not removed:
  1415                     if var_address is not None:
  1415                     if var_address is not None:
  1416                         result = address_model.match(var_address)
  1416                         result = address_model.match(var_address)
  1417                         if result is not None:
  1417                         if result is not None:
  1418                             content.remove(variable)
  1418                             content.remove(variable)
  1419     setattr(cls, "removeVariableByFilter", removeVariableByFilter)
  1419     setattr(cls, "removeVariableByFilter", removeVariableByFilter)
  1420     
  1420 
  1421     def Search(self, criteria, parent_infos=[]):
  1421     def Search(self, criteria, parent_infos=[]):
  1422         search_result = []
  1422         search_result = []
  1423         filter = criteria["filter"]
  1423         filter = criteria["filter"]
  1424         if filter == "all" or self.getpouType() in filter:
  1424         if filter == "all" or self.getpouType() in filter:
  1425             if parent_infos == []:
  1425             if parent_infos == []:
  1492     return self.body.gettext()
  1492     return self.body.gettext()
  1493 
  1493 
  1494 def hasblock(self, name=None, block_type=None):
  1494 def hasblock(self, name=None, block_type=None):
  1495     if self.getbodyType() in ["FBD", "LD", "SFC"]:
  1495     if self.getbodyType() in ["FBD", "LD", "SFC"]:
  1496         for instance in self.getinstances():
  1496         for instance in self.getinstances():
  1497             if (isinstance(instance, PLCOpenParser.GetElementClass("block", "fbdObjects")) and 
  1497             if (isinstance(instance, PLCOpenParser.GetElementClass("block", "fbdObjects")) and
  1498                 (TextMatched(instance.getinstanceName(), name) or TextMatched(instance.gettypeName(), block_type))):
  1498                 (TextMatched(instance.getinstanceName(), name) or TextMatched(instance.gettypeName(), block_type))):
  1499                 return True
  1499                 return True
  1500     elif block_type is not None:
  1500     elif block_type is not None:
  1501         return self.body.hasblock(block_type)
  1501         return self.body.hasblock(block_type)
  1502     return False
  1502     return False
  1504 def updateElementName(self, old_name, new_name):
  1504 def updateElementName(self, old_name, new_name):
  1505     self.body.updateElementName(old_name, new_name)
  1505     self.body.updateElementName(old_name, new_name)
  1506 
  1506 
  1507 def updateElementAddress(self, address_model, new_leading):
  1507 def updateElementAddress(self, address_model, new_leading):
  1508     self.body.updateElementAddress(address_model, new_leading)
  1508     self.body.updateElementAddress(address_model, new_leading)
  1509     
  1509 
  1510 
  1510 
  1511 cls = PLCOpenParser.GetElementClass("transition", "transitions")
  1511 cls = PLCOpenParser.GetElementClass("transition", "transitions")
  1512 if cls:
  1512 if cls:
  1513     setattr(cls, "setbodyType", setbodyType)
  1513     setattr(cls, "setbodyType", setbodyType)
  1514     setattr(cls, "getbodyType", getbodyType)
  1514     setattr(cls, "getbodyType", getbodyType)
  1524     setattr(cls, "settext", settext)
  1524     setattr(cls, "settext", settext)
  1525     setattr(cls, "gettext", gettext)
  1525     setattr(cls, "gettext", gettext)
  1526     setattr(cls, "hasblock", hasblock)
  1526     setattr(cls, "hasblock", hasblock)
  1527     setattr(cls, "updateElementName", updateElementName)
  1527     setattr(cls, "updateElementName", updateElementName)
  1528     setattr(cls, "updateElementAddress", updateElementAddress)
  1528     setattr(cls, "updateElementAddress", updateElementAddress)
  1529     
  1529 
  1530     def Search(self, criteria, parent_infos):
  1530     def Search(self, criteria, parent_infos):
  1531         search_result = []
  1531         search_result = []
  1532         parent_infos = parent_infos[:-1] + ["T::%s::%s" % (parent_infos[-1].split("::")[1], self.getname())]
  1532         parent_infos = parent_infos[:-1] + ["T::%s::%s" % (parent_infos[-1].split("::")[1], self.getname())]
  1533         for result in TestTextElement(self.getname(), criteria):
  1533         for result in TestTextElement(self.getname(), criteria):
  1534             search_result.append((tuple(parent_infos + ["name"]),) + result)
  1534             search_result.append((tuple(parent_infos + ["name"]),) + result)
  1552     setattr(cls, "settext", settext)
  1552     setattr(cls, "settext", settext)
  1553     setattr(cls, "gettext", gettext)
  1553     setattr(cls, "gettext", gettext)
  1554     setattr(cls, "hasblock", hasblock)
  1554     setattr(cls, "hasblock", hasblock)
  1555     setattr(cls, "updateElementName", updateElementName)
  1555     setattr(cls, "updateElementName", updateElementName)
  1556     setattr(cls, "updateElementAddress", updateElementAddress)
  1556     setattr(cls, "updateElementAddress", updateElementAddress)
  1557     
  1557 
  1558     def Search(self, criteria, parent_infos):
  1558     def Search(self, criteria, parent_infos):
  1559         search_result = []
  1559         search_result = []
  1560         parent_infos = parent_infos[:-1] + ["A::%s::%s" % (parent_infos[-1].split("::")[1], self.getname())]
  1560         parent_infos = parent_infos[:-1] + ["A::%s::%s" % (parent_infos[-1].split("::")[1], self.getname())]
  1561         for result in TestTextElement(self.getname(), criteria):
  1561         for result in TestTextElement(self.getname(), criteria):
  1562             search_result.append((tuple(parent_infos + ["name"]),) + result)
  1562             search_result.append((tuple(parent_infos + ["name"]),) + result)
  1569     cls.currentExecutionOrderId = 0
  1569     cls.currentExecutionOrderId = 0
  1570     cls.checkedBlocksDict = {}
  1570     cls.checkedBlocksDict = {}
  1571     def resetcurrentExecutionOrderId(self):
  1571     def resetcurrentExecutionOrderId(self):
  1572         object.__setattr__(self, "currentExecutionOrderId", 0)
  1572         object.__setattr__(self, "currentExecutionOrderId", 0)
  1573     setattr(cls, "resetcurrentExecutionOrderId", resetcurrentExecutionOrderId)
  1573     setattr(cls, "resetcurrentExecutionOrderId", resetcurrentExecutionOrderId)
  1574     
  1574 
  1575     def getnewExecutionOrderId(self):
  1575     def getnewExecutionOrderId(self):
  1576         object.__setattr__(self, "currentExecutionOrderId", self.currentExecutionOrderId + 1)
  1576         object.__setattr__(self, "currentExecutionOrderId", self.currentExecutionOrderId + 1)
  1577         return self.currentExecutionOrderId
  1577         return self.currentExecutionOrderId
  1578     setattr(cls, "getnewExecutionOrderId", getnewExecutionOrderId)
  1578     setattr(cls, "getnewExecutionOrderId", getnewExecutionOrderId)
  1579     
  1579 
  1580     def resetexecutionOrder(self):
  1580     def resetexecutionOrder(self):
  1581         if self.content.getLocalTag() == "FBD":
  1581         if self.content.getLocalTag() == "FBD":
  1582             for element in self.content.getcontent():
  1582             for element in self.content.getcontent():
  1583                 if not isinstance(element, (PLCOpenParser.GetElementClass("comment", "commonObjects"), 
  1583                 if not isinstance(element, (PLCOpenParser.GetElementClass("comment", "commonObjects"),
  1584                                             PLCOpenParser.GetElementClass("connector", "commonObjects"), 
  1584                                             PLCOpenParser.GetElementClass("connector", "commonObjects"),
  1585                                             PLCOpenParser.GetElementClass("continuation", "commonObjects"))):
  1585                                             PLCOpenParser.GetElementClass("continuation", "commonObjects"))):
  1586                     element.setexecutionOrderId(0)
  1586                     element.setexecutionOrderId(0)
  1587             self.checkedBlocksDict.clear()
  1587             self.checkedBlocksDict.clear()
  1588         else:
  1588         else:
  1589             raise TypeError, _("Can only generate execution order on FBD networks!")
  1589             raise TypeError, _("Can only generate execution order on FBD networks!")
  1590     setattr(cls, "resetexecutionOrder", resetexecutionOrder)
  1590     setattr(cls, "resetexecutionOrder", resetexecutionOrder)
  1591     
  1591 
  1592     def compileexecutionOrder(self):
  1592     def compileexecutionOrder(self):
  1593         if self.content.getLocalTag() == "FBD":
  1593         if self.content.getLocalTag() == "FBD":
  1594             self.resetexecutionOrder()
  1594             self.resetexecutionOrder()
  1595             self.resetcurrentExecutionOrderId()
  1595             self.resetcurrentExecutionOrderId()
  1596             for element in self.content.getcontent():
  1596             for element in self.content.getcontent():
  1600                         self.compileelementExecutionOrder(connections[0])
  1600                         self.compileelementExecutionOrder(connections[0])
  1601                     element.setexecutionOrderId(self.getnewExecutionOrderId())
  1601                     element.setexecutionOrderId(self.getnewExecutionOrderId())
  1602         else:
  1602         else:
  1603             raise TypeError, _("Can only generate execution order on FBD networks!")
  1603             raise TypeError, _("Can only generate execution order on FBD networks!")
  1604     setattr(cls, "compileexecutionOrder", compileexecutionOrder)
  1604     setattr(cls, "compileexecutionOrder", compileexecutionOrder)
  1605     
  1605 
  1606     def compileelementExecutionOrder(self, link):
  1606     def compileelementExecutionOrder(self, link):
  1607         if self.content.getLocalTag() == "FBD":
  1607         if self.content.getLocalTag() == "FBD":
  1608             localid = link.getrefLocalId()
  1608             localid = link.getrefLocalId()
  1609             instance = self.getcontentInstance(localid)
  1609             instance = self.getcontentInstance(localid)
  1610             self.checkedBlocksDict[localid] = True
  1610             self.checkedBlocksDict[localid] = True
  1624                         if connections and len(connections) == 1:
  1624                         if connections and len(connections) == 1:
  1625                             self.compileelementExecutionOrder(connections[0])
  1625                             self.compileelementExecutionOrder(connections[0])
  1626         else:
  1626         else:
  1627             raise TypeError, _("Can only generate execution order on FBD networks!")
  1627             raise TypeError, _("Can only generate execution order on FBD networks!")
  1628     setattr(cls, "compileelementExecutionOrder", compileelementExecutionOrder)
  1628     setattr(cls, "compileelementExecutionOrder", compileelementExecutionOrder)
  1629     
  1629 
  1630     def setelementExecutionOrder(self, instance, new_executionOrder):
  1630     def setelementExecutionOrder(self, instance, new_executionOrder):
  1631         if self.content.getLocalTag() == "FBD":
  1631         if self.content.getLocalTag() == "FBD":
  1632             old_executionOrder = instance.getexecutionOrderId()
  1632             old_executionOrder = instance.getexecutionOrderId()
  1633             if old_executionOrder is not None and old_executionOrder != 0 and new_executionOrder != 0:
  1633             if old_executionOrder is not None and old_executionOrder != 0 and new_executionOrder != 0:
  1634                 for element in self.content.getcontent():
  1634                 for element in self.content.getcontent():
  1640                             element.setexecutionOrderId(element_executionOrder + 1)
  1640                             element.setexecutionOrderId(element_executionOrder + 1)
  1641             instance.setexecutionOrderId(new_executionOrder)
  1641             instance.setexecutionOrderId(new_executionOrder)
  1642         else:
  1642         else:
  1643             raise TypeError, _("Can only generate execution order on FBD networks!")
  1643             raise TypeError, _("Can only generate execution order on FBD networks!")
  1644     setattr(cls, "setelementExecutionOrder", setelementExecutionOrder)
  1644     setattr(cls, "setelementExecutionOrder", setelementExecutionOrder)
  1645     
  1645 
  1646     def appendcontentInstance(self, instance):
  1646     def appendcontentInstance(self, instance):
  1647         if self.content.getLocalTag() in ["LD","FBD","SFC"]:
  1647         if self.content.getLocalTag() in ["LD","FBD","SFC"]:
  1648             self.content.appendcontent(instance)
  1648             self.content.appendcontent(instance)
  1649         else:
  1649         else:
  1650             raise TypeError, _("%s body don't have instances!")%self.content.getLocalTag()
  1650             raise TypeError, _("%s body don't have instances!")%self.content.getLocalTag()
  1651     setattr(cls, "appendcontentInstance", appendcontentInstance)
  1651     setattr(cls, "appendcontentInstance", appendcontentInstance)
  1652     
  1652 
  1653     def getcontentInstances(self):
  1653     def getcontentInstances(self):
  1654         if self.content.getLocalTag() in ["LD","FBD","SFC"]:
  1654         if self.content.getLocalTag() in ["LD","FBD","SFC"]:
  1655             return self.content.getcontent()
  1655             return self.content.getcontent()
  1656         else:
  1656         else:
  1657             raise TypeError, _("%s body don't have instances!")%self.content.getLocalTag()
  1657             raise TypeError, _("%s body don't have instances!")%self.content.getLocalTag()
  1658     setattr(cls, "getcontentInstances", getcontentInstances)
  1658     setattr(cls, "getcontentInstances", getcontentInstances)
  1659     
  1659 
  1660     instance_by_id_xpath = PLCOpen_XPath("*[@localId=$localId]")
  1660     instance_by_id_xpath = PLCOpen_XPath("*[@localId=$localId]")
  1661     instance_by_name_xpath = PLCOpen_XPath("ppx:block[@instanceName=$name]")
  1661     instance_by_name_xpath = PLCOpen_XPath("ppx:block[@instanceName=$name]")
  1662     def getcontentInstance(self, local_id):
  1662     def getcontentInstance(self, local_id):
  1663         if self.content.getLocalTag() in ["LD","FBD","SFC"]:
  1663         if self.content.getLocalTag() in ["LD","FBD","SFC"]:
  1664             instance = instance_by_id_xpath(self.content, localId=local_id)
  1664             instance = instance_by_id_xpath(self.content, localId=local_id)
  1666                 return instance[0]
  1666                 return instance[0]
  1667             return None
  1667             return None
  1668         else:
  1668         else:
  1669             raise TypeError, _("%s body don't have instances!")%self.content.getLocalTag()
  1669             raise TypeError, _("%s body don't have instances!")%self.content.getLocalTag()
  1670     setattr(cls, "getcontentInstance", getcontentInstance)
  1670     setattr(cls, "getcontentInstance", getcontentInstance)
  1671     
  1671 
  1672     def getcontentInstancesIds(self):
  1672     def getcontentInstancesIds(self):
  1673         if self.content.getLocalTag() in ["LD","FBD","SFC"]:
  1673         if self.content.getLocalTag() in ["LD","FBD","SFC"]:
  1674             return OrderedDict([(instance.getlocalId(), True)
  1674             return OrderedDict([(instance.getlocalId(), True)
  1675                                 for instance in self.content])
  1675                                 for instance in self.content])
  1676         else:
  1676         else:
  1677             raise TypeError, _("%s body don't have instances!")%self.content.getLocalTag()
  1677             raise TypeError, _("%s body don't have instances!")%self.content.getLocalTag()
  1678     setattr(cls, "getcontentInstancesIds", getcontentInstancesIds)
  1678     setattr(cls, "getcontentInstancesIds", getcontentInstancesIds)
  1679     
  1679 
  1680     def getcontentInstanceByName(self, name):
  1680     def getcontentInstanceByName(self, name):
  1681         if self.content.getLocalTag() in ["LD","FBD","SFC"]:
  1681         if self.content.getLocalTag() in ["LD","FBD","SFC"]:
  1682             instance = instance_by_name_xpath(self.content)
  1682             instance = instance_by_name_xpath(self.content)
  1683             if len(instance) > 0:
  1683             if len(instance) > 0:
  1684                 return instance[0]
  1684                 return instance[0]
  1685             return None
  1685             return None
  1686         else:
  1686         else:
  1687             raise TypeError, _("%s body don't have instances!")%self.content.getLocalTag()
  1687             raise TypeError, _("%s body don't have instances!")%self.content.getLocalTag()
  1688     setattr(cls, "getcontentInstanceByName", getcontentInstanceByName)
  1688     setattr(cls, "getcontentInstanceByName", getcontentInstanceByName)
  1689     
  1689 
  1690     def removecontentInstance(self, local_id):
  1690     def removecontentInstance(self, local_id):
  1691         if self.content.getLocalTag() in ["LD","FBD","SFC"]:
  1691         if self.content.getLocalTag() in ["LD","FBD","SFC"]:
  1692             instance = instance_by_id_xpath(self.content, localId=local_id)
  1692             instance = instance_by_id_xpath(self.content, localId=local_id)
  1693             if len(instance) > 0:
  1693             if len(instance) > 0:
  1694                 self.content.remove(instance[0])
  1694                 self.content.remove(instance[0])
  1695             else:
  1695             else:
  1696                 raise ValueError, _("Instance with id %d doesn't exist!")%id
  1696                 raise ValueError, _("Instance with id %d doesn't exist!")%id
  1697         else:
  1697         else:
  1698             raise TypeError, "%s body don't have instances!"%self.content.getLocalTag()
  1698             raise TypeError, "%s body don't have instances!"%self.content.getLocalTag()
  1699     setattr(cls, "removecontentInstance", removecontentInstance)
  1699     setattr(cls, "removecontentInstance", removecontentInstance)
  1700     
  1700 
  1701     def settext(self, text):
  1701     def settext(self, text):
  1702         if self.content.getLocalTag() in ["IL","ST"]:
  1702         if self.content.getLocalTag() in ["IL","ST"]:
  1703             self.content.setanyText(text)
  1703             self.content.setanyText(text)
  1704         else:
  1704         else:
  1705             raise TypeError, _("%s body don't have text!")%self.content.getLocalTag()
  1705             raise TypeError, _("%s body don't have text!")%self.content.getLocalTag()
  1709         if self.content.getLocalTag() in ["IL","ST"]:
  1709         if self.content.getLocalTag() in ["IL","ST"]:
  1710             return self.content.getanyText()
  1710             return self.content.getanyText()
  1711         else:
  1711         else:
  1712             raise TypeError, _("%s body don't have text!")%self.content.getLocalTag()
  1712             raise TypeError, _("%s body don't have text!")%self.content.getLocalTag()
  1713     setattr(cls, "gettext", gettext)
  1713     setattr(cls, "gettext", gettext)
  1714     
  1714 
  1715     def hasblock(self, block_type):
  1715     def hasblock(self, block_type):
  1716         if self.content.getLocalTag() in ["IL","ST"]:
  1716         if self.content.getLocalTag() in ["IL","ST"]:
  1717             return self.content.hasblock(block_type)
  1717             return self.content.hasblock(block_type)
  1718         else:
  1718         else:
  1719             raise TypeError, _("%s body don't have text!")%self.content.getLocalTag()
  1719             raise TypeError, _("%s body don't have text!")%self.content.getLocalTag()
  1720     setattr(cls, "hasblock", hasblock)
  1720     setattr(cls, "hasblock", hasblock)
  1721     
  1721 
  1722     def updateElementName(self, old_name, new_name):
  1722     def updateElementName(self, old_name, new_name):
  1723         if self.content.getLocalTag() in ["IL", "ST"]:
  1723         if self.content.getLocalTag() in ["IL", "ST"]:
  1724             self.content.updateElementName(old_name, new_name)
  1724             self.content.updateElementName(old_name, new_name)
  1725         else:
  1725         else:
  1726             for element in self.content.getcontent():
  1726             for element in self.content.getcontent():
  1751 def gety(self):
  1751 def gety(self):
  1752     return self.position.gety()
  1752     return self.position.gety()
  1753 
  1753 
  1754 def setx(self, x):
  1754 def setx(self, x):
  1755     self.position.setx(x)
  1755     self.position.setx(x)
  1756     
  1756 
  1757 def sety(self, y):
  1757 def sety(self, y):
  1758     self.position.sety(y)
  1758     self.position.sety(y)
  1759 
  1759 
  1760 def _getBoundingBox(self):
  1760 def _getBoundingBox(self):
  1761     return rect(self.getx(), self.gety(), self.getwidth(), self.getheight())
  1761     return rect(self.getx(), self.gety(), self.getwidth(), self.getheight())
  1826     return _getconnectionsdefinition(self, connections_end)
  1826     return _getconnectionsdefinition(self, connections_end)
  1827 
  1827 
  1828 def _translate(self, dx, dy):
  1828 def _translate(self, dx, dy):
  1829     self.setx(self.getx() + dx)
  1829     self.setx(self.getx() + dx)
  1830     self.sety(self.gety() + dy)
  1830     self.sety(self.gety() + dy)
  1831     
  1831 
  1832 def _translateConnections(connectionPointIn, dx, dy):
  1832 def _translateConnections(connectionPointIn, dx, dy):
  1833     connections = connectionPointIn.getconnections()
  1833     connections = connectionPointIn.getconnections()
  1834     if connections is not None:
  1834     if connections is not None:
  1835         for connection in connections:
  1835         for connection in connections:
  1836             for position in connection.getposition():
  1836             for position in connection.getposition():
  1890 cls = _initElementClass("comment", "commonObjects")
  1890 cls = _initElementClass("comment", "commonObjects")
  1891 if cls:
  1891 if cls:
  1892     def setcontentText(self, text):
  1892     def setcontentText(self, text):
  1893         self.content.setanyText(text)
  1893         self.content.setanyText(text)
  1894     setattr(cls, "setcontentText", setcontentText)
  1894     setattr(cls, "setcontentText", setcontentText)
  1895         
  1895 
  1896     def getcontentText(self):
  1896     def getcontentText(self):
  1897         return self.content.getanyText()
  1897         return self.content.getanyText()
  1898     setattr(cls, "getcontentText", getcontentText)
  1898     setattr(cls, "getcontentText", getcontentText)
  1899     
  1899 
  1900     def updateElementName(self, old_name, new_name):
  1900     def updateElementName(self, old_name, new_name):
  1901         self.content.updateElementName(old_name, new_name)
  1901         self.content.updateElementName(old_name, new_name)
  1902     setattr(cls, "updateElementName", updateElementName)
  1902     setattr(cls, "updateElementName", updateElementName)
  1903 
  1903 
  1904     def updateElementAddress(self, address_model, new_leading):
  1904     def updateElementAddress(self, address_model, new_leading):
  2002             condition.setname(value)
  2002             condition.setname(value)
  2003         elif condition_type == "inline":
  2003         elif condition_type == "inline":
  2004             condition.setcontent(PLCOpenParser.CreateElement("ST", "inline"))
  2004             condition.setcontent(PLCOpenParser.CreateElement("ST", "inline"))
  2005             condition.settext(value)
  2005             condition.settext(value)
  2006     setattr(cls, "setconditionContent", setconditionContent)
  2006     setattr(cls, "setconditionContent", setconditionContent)
  2007         
  2007 
  2008     def getconditionContent(self):
  2008     def getconditionContent(self):
  2009         if self.condition is not None:
  2009         if self.condition is not None:
  2010             content = self.condition.getcontent()
  2010             content = self.condition.getcontent()
  2011             values = {"type" : content.getLocalTag()}
  2011             values = {"type" : content.getLocalTag()}
  2012             if values["type"] == "reference":
  2012             if values["type"] == "reference":
  2033         condition_connection = self.getconditionConnection()
  2033         condition_connection = self.getconditionConnection()
  2034         if condition_connection is not None:
  2034         if condition_connection is not None:
  2035             bbox.union(_getConnectionsBoundingBox(condition_connection))
  2035             bbox.union(_getConnectionsBoundingBox(condition_connection))
  2036         return bbox
  2036         return bbox
  2037     setattr(cls, "getBoundingBox", getBoundingBox)
  2037     setattr(cls, "getBoundingBox", getBoundingBox)
  2038     
  2038 
  2039     def translate(self, dx, dy):
  2039     def translate(self, dx, dy):
  2040         _translateSingle(self, dx, dy)
  2040         _translateSingle(self, dx, dy)
  2041         condition_connection = self.getconditionConnection()
  2041         condition_connection = self.getconditionConnection()
  2042         if condition_connection is not None:
  2042         if condition_connection is not None:
  2043             _translateConnections(condition_connection, dx, dy)
  2043             _translateConnections(condition_connection, dx, dy)
  2044     setattr(cls, "translate", translate)
  2044     setattr(cls, "translate", translate)
  2045     
  2045 
  2046     def filterConnections(self, connections):
  2046     def filterConnections(self, connections):
  2047         _filterConnectionsSingle(self, connections)
  2047         _filterConnectionsSingle(self, connections)
  2048         condition_connection = self.getconditionConnection()
  2048         condition_connection = self.getconditionConnection()
  2049         if condition_connection is not None:
  2049         if condition_connection is not None:
  2050             _filterConnections(condition_connection, self.localId, connections)
  2050             _filterConnections(condition_connection, self.localId, connections)
  2051     setattr(cls, "filterConnections", filterConnections)
  2051     setattr(cls, "filterConnections", filterConnections)
  2052     
  2052 
  2053     def updateConnectionsId(self, translation):
  2053     def updateConnectionsId(self, translation):
  2054         connections_end = []
  2054         connections_end = []
  2055         if self.connectionPointIn is not None:
  2055         if self.connectionPointIn is not None:
  2056             connections_end = _updateConnectionsId(self.connectionPointIn, translation)
  2056             connections_end = _updateConnectionsId(self.connectionPointIn, translation)
  2057         condition_connection = self.getconditionConnection()
  2057         condition_connection = self.getconditionConnection()
  2085         condition_connection = self.getconditionConnection()
  2085         condition_connection = self.getconditionConnection()
  2086         if condition_connection is not None:
  2086         if condition_connection is not None:
  2087             return condition_connection.getconnections()
  2087             return condition_connection.getconnections()
  2088         return None
  2088         return None
  2089     setattr(cls, "getconnections", getconnections)
  2089     setattr(cls, "getconnections", getconnections)
  2090     
  2090 
  2091     def Search(self, criteria, parent_infos=[]):
  2091     def Search(self, criteria, parent_infos=[]):
  2092         parent_infos = parent_infos + ["transition", self.getlocalId()]
  2092         parent_infos = parent_infos + ["transition", self.getlocalId()]
  2093         search_result = []
  2093         search_result = []
  2094         content = self.condition.getcontent()
  2094         content = self.condition.getcontent()
  2095         content_name = content.getLocalTag()
  2095         content_name = content.getLocalTag()
  2102 
  2102 
  2103 _initElementClass("selectionDivergence", "sfcObjects", "single")
  2103 _initElementClass("selectionDivergence", "sfcObjects", "single")
  2104 _initElementClass("selectionConvergence", "sfcObjects", "multiple")
  2104 _initElementClass("selectionConvergence", "sfcObjects", "multiple")
  2105 _initElementClass("simultaneousDivergence", "sfcObjects", "single")
  2105 _initElementClass("simultaneousDivergence", "sfcObjects", "single")
  2106 _initElementClass("simultaneousConvergence", "sfcObjects", "multiple")
  2106 _initElementClass("simultaneousConvergence", "sfcObjects", "multiple")
  2107     
  2107 
  2108 cls = _initElementClass("jumpStep", "sfcObjects", "single")
  2108 cls = _initElementClass("jumpStep", "sfcObjects", "single")
  2109 if cls:
  2109 if cls:
  2110     def Search(self, criteria, parent_infos):
  2110     def Search(self, criteria, parent_infos):
  2111         return _Search([("target", self.gettargetName())], criteria, parent_infos + ["jump", self.getlocalId()])
  2111         return _Search([("target", self.gettargetName())], criteria, parent_infos + ["jump", self.getlocalId()])
  2112     setattr(cls, "Search", Search)
  2112     setattr(cls, "Search", Search)
  2115 if cls:
  2115 if cls:
  2116     def setreferenceName(self, name):
  2116     def setreferenceName(self, name):
  2117         if self.reference is not None:
  2117         if self.reference is not None:
  2118             self.reference.setname(name)
  2118             self.reference.setname(name)
  2119     setattr(cls, "setreferenceName", setreferenceName)
  2119     setattr(cls, "setreferenceName", setreferenceName)
  2120     
  2120 
  2121     def getreferenceName(self):
  2121     def getreferenceName(self):
  2122         if self.reference is not None:
  2122         if self.reference is not None:
  2123             return self.reference.getname()
  2123             return self.reference.getname()
  2124         return None
  2124         return None
  2125     setattr(cls, "getreferenceName", getreferenceName)
  2125     setattr(cls, "getreferenceName", getreferenceName)
  2127     def setinlineContent(self, content):
  2127     def setinlineContent(self, content):
  2128         if self.inline is not None:
  2128         if self.inline is not None:
  2129             self.inline.setcontent(PLCOpenParser.CreateElement("ST", "inline"))
  2129             self.inline.setcontent(PLCOpenParser.CreateElement("ST", "inline"))
  2130             self.inline.settext(content)
  2130             self.inline.settext(content)
  2131     setattr(cls, "setinlineContent", setinlineContent)
  2131     setattr(cls, "setinlineContent", setinlineContent)
  2132     
  2132 
  2133     def getinlineContent(self):
  2133     def getinlineContent(self):
  2134         if self.inline is not None:
  2134         if self.inline is not None:
  2135             return self.inline.gettext()
  2135             return self.inline.gettext()
  2136         return None
  2136         return None
  2137     setattr(cls, "getinlineContent", getinlineContent)
  2137     setattr(cls, "getinlineContent", getinlineContent)
  2153     def Search(self, criteria, parent_infos=[]):
  2153     def Search(self, criteria, parent_infos=[]):
  2154         qualifier = self.getqualifier()
  2154         qualifier = self.getqualifier()
  2155         if qualifier is None:
  2155         if qualifier is None:
  2156             qualifier = "N"
  2156             qualifier = "N"
  2157         return _Search([("inline", self.getinlineContent()),
  2157         return _Search([("inline", self.getinlineContent()),
  2158                         ("reference", self.getreferenceName()), 
  2158                         ("reference", self.getreferenceName()),
  2159                         ("qualifier", qualifier),
  2159                         ("qualifier", qualifier),
  2160                         ("duration", self.getduration()),
  2160                         ("duration", self.getduration()),
  2161                         ("indicator", self.getindicator())],
  2161                         ("indicator", self.getindicator())],
  2162                        criteria, parent_infos)
  2162                        criteria, parent_infos)
  2163     setattr(cls, "Search", Search)
  2163     setattr(cls, "Search", Search)
  2316     setattr(cls, "removeconnection", removeconnection)
  2316     setattr(cls, "removeconnection", removeconnection)
  2317 
  2317 
  2318     def removeconnections(self):
  2318     def removeconnections(self):
  2319         self.content = None
  2319         self.content = None
  2320     setattr(cls, "removeconnections", removeconnections)
  2320     setattr(cls, "removeconnections", removeconnections)
  2321     
  2321 
  2322     connection_xpath = PLCOpen_XPath("ppx:connection")
  2322     connection_xpath = PLCOpen_XPath("ppx:connection")
  2323     connection_by_position_xpath = PLCOpen_XPath("ppx:connection[position()=$pos]")
  2323     connection_by_position_xpath = PLCOpen_XPath("ppx:connection[position()=$pos]")
  2324     def getconnections(self):
  2324     def getconnections(self):
  2325         return connection_xpath(self)
  2325         return connection_xpath(self)
  2326     setattr(cls, "getconnections", getconnections)
  2326     setattr(cls, "getconnections", getconnections)
  2327     
  2327 
  2328     def getconnection(self, idx):
  2328     def getconnection(self, idx):
  2329         connection = connection_by_position_xpath(self, pos=idx+1)
  2329         connection = connection_by_position_xpath(self, pos=idx+1)
  2330         if len(connection) > 0:
  2330         if len(connection) > 0:
  2331             return connection[0]
  2331             return connection[0]
  2332         return None
  2332         return None
  2333     setattr(cls, "getconnection", getconnection)
  2333     setattr(cls, "getconnection", getconnection)
  2334     
  2334 
  2335     def setconnectionId(self, idx, local_id):
  2335     def setconnectionId(self, idx, local_id):
  2336         connection = self.getconnection(idx)
  2336         connection = self.getconnection(idx)
  2337         if connection is not None:
  2337         if connection is not None:
  2338             connection.setrefLocalId(local_id)
  2338             connection.setrefLocalId(local_id)
  2339     setattr(cls, "setconnectionId", setconnectionId)
  2339     setattr(cls, "setconnectionId", setconnectionId)
  2340     
  2340 
  2341     def getconnectionId(self, idx):
  2341     def getconnectionId(self, idx):
  2342         connection = self.getconnection(idx)
  2342         connection = self.getconnection(idx)
  2343         if connection is not None:
  2343         if connection is not None:
  2344             return connection.getrefLocalId()
  2344             return connection.getrefLocalId()
  2345         return None
  2345         return None
  2346     setattr(cls, "getconnectionId", getconnectionId)
  2346     setattr(cls, "getconnectionId", getconnectionId)
  2347     
  2347 
  2348     def setconnectionPoints(self, idx, points):
  2348     def setconnectionPoints(self, idx, points):
  2349         connection = self.getconnection(idx)
  2349         connection = self.getconnection(idx)
  2350         if connection is not None:
  2350         if connection is not None:
  2351             connection.setpoints(points)
  2351             connection.setpoints(points)
  2352     setattr(cls, "setconnectionPoints", setconnectionPoints)
  2352     setattr(cls, "setconnectionPoints", setconnectionPoints)
  2361     def setconnectionParameter(self, idx, parameter):
  2361     def setconnectionParameter(self, idx, parameter):
  2362         connection = self.getconnection(idx)
  2362         connection = self.getconnection(idx)
  2363         if connection is not None:
  2363         if connection is not None:
  2364             connection.setformalParameter(parameter)
  2364             connection.setformalParameter(parameter)
  2365     setattr(cls, "setconnectionParameter", setconnectionParameter)
  2365     setattr(cls, "setconnectionParameter", setconnectionParameter)
  2366     
  2366 
  2367     def getconnectionParameter(self, idx):
  2367     def getconnectionParameter(self, idx):
  2368         connection = self.getconnection(idx)
  2368         connection = self.getconnection(idx)
  2369         if connection is not None:
  2369         if connection is not None:
  2370             return connection.getformalParameter()
  2370             return connection.getformalParameter()
  2371         return None
  2371         return None
  2396         else:
  2396         else:
  2397             content = PLCOpenParser.CreateElement("simpleValue", "value")
  2397             content = PLCOpenParser.CreateElement("simpleValue", "value")
  2398         content.setvalue(value)
  2398         content.setvalue(value)
  2399         self.setcontent(content)
  2399         self.setcontent(content)
  2400     setattr(cls, "setvalue", setvalue)
  2400     setattr(cls, "setvalue", setvalue)
  2401     
  2401 
  2402     def getvalue(self):
  2402     def getvalue(self):
  2403         return self.content.getvalue()
  2403         return self.content.getvalue()
  2404     setattr(cls, "getvalue", getvalue)
  2404     setattr(cls, "getvalue", getvalue)
  2405 
  2405 
  2406 def extractValues(values):
  2406 def extractValues(values):
  2418     return items
  2418     return items
  2419 
  2419 
  2420 cls = PLCOpenParser.GetElementClass("arrayValue", "value")
  2420 cls = PLCOpenParser.GetElementClass("arrayValue", "value")
  2421 if cls:
  2421 if cls:
  2422     arrayValue_model = re.compile("([0-9]+)\((.*)\)$")
  2422     arrayValue_model = re.compile("([0-9]+)\((.*)\)$")
  2423     
  2423 
  2424     def setvalue(self, value):
  2424     def setvalue(self, value):
  2425         elements = []
  2425         elements = []
  2426         for item in extractValues(value[1:-1]):
  2426         for item in extractValues(value[1:-1]):
  2427             item = item.strip()
  2427             item = item.strip()
  2428             element = PLCOpenParser.CreateElement("value", "arrayValue")
  2428             element = PLCOpenParser.CreateElement("value", "arrayValue")
  2434             else:
  2434             else:
  2435                 element.setvalue(item)
  2435                 element.setvalue(item)
  2436             elements.append(element)
  2436             elements.append(element)
  2437         self.value = elements
  2437         self.value = elements
  2438     setattr(cls, "setvalue", setvalue)
  2438     setattr(cls, "setvalue", setvalue)
  2439     
  2439 
  2440     def getvalue(self):
  2440     def getvalue(self):
  2441         values = []
  2441         values = []
  2442         for element in self.value:
  2442         for element in self.value:
  2443             try:
  2443             try:
  2444                 repetition = int(element.getrepetitionValue())
  2444                 repetition = int(element.getrepetitionValue())
  2455     setattr(cls, "getvalue", getvalue)
  2455     setattr(cls, "getvalue", getvalue)
  2456 
  2456 
  2457 cls = PLCOpenParser.GetElementClass("structValue", "value")
  2457 cls = PLCOpenParser.GetElementClass("structValue", "value")
  2458 if cls:
  2458 if cls:
  2459     structValue_model = re.compile("(.*):=(.*)")
  2459     structValue_model = re.compile("(.*):=(.*)")
  2460     
  2460 
  2461     def setvalue(self, value):
  2461     def setvalue(self, value):
  2462         elements = []
  2462         elements = []
  2463         for item in extractValues(value[1:-1]):
  2463         for item in extractValues(value[1:-1]):
  2464             result = structValue_model.match(item)
  2464             result = structValue_model.match(item)
  2465             if result is not None:
  2465             if result is not None:
  2468                 element.setmember(groups[0].strip())
  2468                 element.setmember(groups[0].strip())
  2469                 element.setvalue(groups[1].strip())
  2469                 element.setvalue(groups[1].strip())
  2470                 elements.append(element)
  2470                 elements.append(element)
  2471         self.value = elements
  2471         self.value = elements
  2472     setattr(cls, "setvalue", setvalue)
  2472     setattr(cls, "setvalue", setvalue)
  2473     
  2473 
  2474     def getvalue(self):
  2474     def getvalue(self):
  2475         values = []
  2475         values = []
  2476         for element in self.value:
  2476         for element in self.value:
  2477             values.append("%s := %s"%(element.getmember(), element.getvalue()))
  2477             values.append("%s := %s"%(element.getmember(), element.getvalue()))
  2478         return "(%s)"%", ".join(values)
  2478         return "(%s)"%", ".join(values)
  2479     setattr(cls, "getvalue", getvalue)
  2479     setattr(cls, "getvalue", getvalue)
  2480