Laurent@814: #!/usr/bin/env python Laurent@814: # -*- coding: utf-8 -*- Laurent@814: Laurent@814: #This file is part of PLCOpenEditor, a library implementing an IEC 61131-3 editor Laurent@814: #based on the plcopen standard. Laurent@814: # Laurent@814: #Copyright (C) 2007: Edouard TISSERANT and Laurent BESSARD Laurent@814: # Laurent@814: #See COPYING file for copyrights details. Laurent@814: # Laurent@814: #This library is free software; you can redistribute it and/or Laurent@814: #modify it under the terms of the GNU General Public Laurent@814: #License as published by the Free Software Foundation; either Laurent@814: #version 2.1 of the License, or (at your option) any later version. Laurent@814: # Laurent@814: #This library is distributed in the hope that it will be useful, Laurent@814: #but WITHOUT ANY WARRANTY; without even the implied warranty of Laurent@814: #MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Laurent@814: #General Public License for more details. Laurent@814: # Laurent@814: #You should have received a copy of the GNU General Public Laurent@814: #License along with this library; if not, write to the Free Software Laurent@814: #Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Laurent@814: Laurent@814: from plcopen import plcopen Laurent@814: from plcopen.structures import * Laurent@814: from types import * Laurent@814: import re Laurent@814: Laurent@814: # Dictionary associating PLCOpen variable categories to the corresponding Laurent@814: # IEC 61131-3 variable categories Laurent@814: varTypeNames = {"localVars" : "VAR", "tempVars" : "VAR_TEMP", "inputVars" : "VAR_INPUT", Laurent@814: "outputVars" : "VAR_OUTPUT", "inOutVars" : "VAR_IN_OUT", "externalVars" : "VAR_EXTERNAL", Laurent@814: "globalVars" : "VAR_GLOBAL", "accessVars" : "VAR_ACCESS"} Laurent@814: Laurent@814: Laurent@814: # Dictionary associating PLCOpen POU categories to the corresponding Laurent@814: # IEC 61131-3 POU categories Laurent@814: pouTypeNames = {"function" : "FUNCTION", "functionBlock" : "FUNCTION_BLOCK", "program" : "PROGRAM"} Laurent@814: Laurent@814: Laurent@814: errorVarTypes = { Laurent@814: "VAR_INPUT": "var_input", Laurent@814: "VAR_OUTPUT": "var_output", Laurent@814: "VAR_INOUT": "var_inout", Laurent@814: } Laurent@814: Laurent@814: # Helper function for reindenting text Laurent@814: def ReIndentText(text, nb_spaces): Laurent@814: compute = "" Laurent@814: lines = text.splitlines() Laurent@814: if len(lines) > 0: Laurent@814: line_num = 0 Laurent@814: while line_num < len(lines) and len(lines[line_num].strip()) == 0: Laurent@814: line_num += 1 Laurent@814: if line_num < len(lines): Laurent@814: spaces = 0 Laurent@814: while lines[line_num][spaces] == " ": Laurent@814: spaces += 1 Laurent@814: indent = "" Laurent@814: for i in xrange(spaces, nb_spaces): Laurent@814: indent += " " Laurent@814: for line in lines: Laurent@814: if line != "": Laurent@814: compute += "%s%s\n"%(indent, line) Laurent@814: else: Laurent@814: compute += "\n" Laurent@814: return compute Laurent@814: Laurent@814: def SortInstances(a, b): Laurent@814: ax, ay = int(a.getx()), int(a.gety()) Laurent@814: bx, by = int(b.getx()), int(b.gety()) Laurent@814: if abs(ay - by) < 10: Laurent@814: return cmp(ax, bx) Laurent@814: else: Laurent@814: return cmp(ay, by) Laurent@814: Laurent@814: #------------------------------------------------------------------------------- Laurent@814: # Specific exception for PLC generating errors Laurent@814: #------------------------------------------------------------------------------- Laurent@814: Laurent@814: Laurent@814: class PLCGenException(Exception): Laurent@814: pass Laurent@814: Laurent@814: Laurent@814: #------------------------------------------------------------------------------- Laurent@814: # Generator of PLC program Laurent@814: #------------------------------------------------------------------------------- Laurent@814: Laurent@814: Laurent@814: class ProgramGenerator: Laurent@814: Laurent@814: # Create a new PCL program generator Laurent@814: def __init__(self, controler, project, errors, warnings): Laurent@814: # Keep reference of the controler and project Laurent@814: self.Controler = controler Laurent@814: self.Project = project Laurent@814: # Reset the internal variables used to generate PLC programs Laurent@814: self.Program = [] Laurent@814: self.DatatypeComputed = {} Laurent@814: self.PouComputed = {} Laurent@814: self.Errors = errors Laurent@814: self.Warnings = warnings Laurent@814: Laurent@814: # Compute value according to type given Laurent@814: def ComputeValue(self, value, var_type): Laurent@814: base_type = self.Controler.GetBaseType(var_type) Laurent@1032: if base_type == "STRING" and not value.startswith("'") and not value.endswith("'"): Laurent@814: return "'%s'"%value Laurent@1032: elif base_type == "WSTRING" and not value.startswith('"') and not value.endswith('"'): Laurent@814: return "\"%s\""%value Laurent@814: return value Laurent@814: Laurent@814: # Generate a data type from its name Laurent@814: def GenerateDataType(self, datatype_name): Laurent@814: # Verify that data type hasn't been generated yet Laurent@814: if not self.DatatypeComputed.get(datatype_name, True): Laurent@814: # If not mark data type as computed Laurent@814: self.DatatypeComputed[datatype_name] = True Laurent@814: Laurent@814: # Getting datatype model from project Laurent@814: datatype = self.Project.getdataType(datatype_name) Laurent@814: tagname = self.Controler.ComputeDataTypeName(datatype.getname()) Laurent@814: datatype_def = [(" ", ()), Laurent@814: (datatype.getname(), (tagname, "name")), Laurent@814: (" : ", ())] Laurent@814: basetype_content = datatype.baseType.getcontent() Laurent@814: # Data type derived directly from a string type Laurent@814: if basetype_content["name"] in ["string", "wstring"]: Laurent@814: datatype_def += [(basetype_content["name"].upper(), (tagname, "base"))] Laurent@814: # Data type derived directly from a user defined type Laurent@814: elif basetype_content["name"] == "derived": Laurent@814: basetype_name = basetype_content["value"].getname() Laurent@814: self.GenerateDataType(basetype_name) Laurent@814: datatype_def += [(basetype_name, (tagname, "base"))] Laurent@814: # Data type is a subrange Laurent@814: elif basetype_content["name"] in ["subrangeSigned", "subrangeUnsigned"]: Laurent@814: base_type = basetype_content["value"].baseType.getcontent() Laurent@814: # Subrange derived directly from a user defined type Laurent@814: if base_type["name"] == "derived": Laurent@814: basetype_name = base_type["value"].getname() Laurent@814: self.GenerateDataType(basetype_name) Laurent@814: # Subrange derived directly from an elementary type Laurent@814: else: Laurent@814: basetype_name = base_type["name"] Laurent@814: min_value = basetype_content["value"].range.getlower() Laurent@814: max_value = basetype_content["value"].range.getupper() Laurent@814: datatype_def += [(basetype_name, (tagname, "base")), Laurent@814: (" (", ()), Laurent@814: ("%s"%min_value, (tagname, "lower")), Laurent@814: ("..", ()), Laurent@814: ("%s"%max_value, (tagname, "upper")), Laurent@814: (")",())] Laurent@814: # Data type is an enumerated type Laurent@814: elif basetype_content["name"] == "enum": Laurent@814: values = [[(value.getname(), (tagname, "value", i))] Laurent@814: for i, value in enumerate(basetype_content["value"].values.getvalue())] Laurent@814: datatype_def += [("(", ())] Laurent@814: datatype_def += JoinList([(", ", ())], values) Laurent@814: datatype_def += [(")", ())] Laurent@814: # Data type is an array Laurent@814: elif basetype_content["name"] == "array": Laurent@814: base_type = basetype_content["value"].baseType.getcontent() Laurent@814: # Array derived directly from a user defined type Laurent@814: if base_type["name"] == "derived": Laurent@814: basetype_name = base_type["value"].getname() Laurent@814: self.GenerateDataType(basetype_name) Laurent@814: # Array derived directly from a string type Laurent@814: elif base_type["name"] in ["string", "wstring"]: Laurent@814: basetype_name = base_type["name"].upper() Laurent@814: # Array derived directly from an elementary type Laurent@814: else: Laurent@814: basetype_name = base_type["name"] Laurent@814: dimensions = [[("%s"%dimension.getlower(), (tagname, "range", i, "lower")), Laurent@814: ("..", ()), Laurent@814: ("%s"%dimension.getupper(), (tagname, "range", i, "upper"))] Laurent@814: for i, dimension in enumerate(basetype_content["value"].getdimension())] Laurent@814: datatype_def += [("ARRAY [", ())] Laurent@814: datatype_def += JoinList([(",", ())], dimensions) Laurent@814: datatype_def += [("] OF " , ()), Laurent@814: (basetype_name, (tagname, "base"))] Laurent@814: # Data type is a structure Laurent@814: elif basetype_content["name"] == "struct": Laurent@814: elements = [] Laurent@814: for i, element in enumerate(basetype_content["value"].getvariable()): Laurent@814: element_type = element.type.getcontent() Laurent@814: # Structure element derived directly from a user defined type Laurent@814: if element_type["name"] == "derived": Laurent@814: elementtype_name = element_type["value"].getname() Laurent@814: self.GenerateDataType(elementtype_name) Laurent@864: elif element_type["name"] == "array": Laurent@864: base_type = element_type["value"].baseType.getcontent() Laurent@864: # Array derived directly from a user defined type Laurent@864: if base_type["name"] == "derived": Laurent@864: basetype_name = base_type["value"].getname() Laurent@864: self.GenerateDataType(basetype_name) Laurent@864: # Array derived directly from a string type Laurent@864: elif base_type["name"] in ["string", "wstring"]: Laurent@864: basetype_name = base_type["name"].upper() Laurent@864: # Array derived directly from an elementary type Laurent@864: else: Laurent@864: basetype_name = base_type["name"] Laurent@864: dimensions = ["%s..%s" % (dimension.getlower(), dimension.getupper()) Laurent@864: for dimension in element_type["value"].getdimension()] Laurent@864: elementtype_name = "ARRAY [%s] OF %s" % (",".join(dimensions), basetype_name) Laurent@814: # Structure element derived directly from a string type Laurent@814: elif element_type["name"] in ["string", "wstring"]: Laurent@814: elementtype_name = element_type["name"].upper() Laurent@814: # Structure element derived directly from an elementary type Laurent@814: else: Laurent@814: elementtype_name = element_type["name"] Laurent@814: element_text = [("\n ", ()), Laurent@814: (element.getname(), (tagname, "struct", i, "name")), Laurent@814: (" : ", ()), Laurent@814: (elementtype_name, (tagname, "struct", i, "type"))] Laurent@814: if element.initialValue is not None: Laurent@814: element_text.extend([(" := ", ()), Laurent@814: (self.ComputeValue(element.initialValue.getvalue(), elementtype_name), (tagname, "struct", i, "initial value"))]) Laurent@814: element_text.append((";", ())) Laurent@814: elements.append(element_text) Laurent@814: datatype_def += [("STRUCT", ())] Laurent@814: datatype_def += JoinList([("", ())], elements) Laurent@814: datatype_def += [("\n END_STRUCT", ())] Laurent@814: # Data type derived directly from a elementary type Laurent@814: else: Laurent@814: datatype_def += [(basetype_content["name"], (tagname, "base"))] Laurent@814: # Data type has an initial value Laurent@814: if datatype.initialValue is not None: Laurent@814: datatype_def += [(" := ", ()), Laurent@814: (self.ComputeValue(datatype.initialValue.getvalue(), datatype_name), (tagname, "initial value"))] Laurent@814: datatype_def += [(";\n", ())] Laurent@814: self.Program += datatype_def Laurent@814: Laurent@814: # Generate a POU from its name Laurent@814: def GeneratePouProgram(self, pou_name): Laurent@814: # Verify that POU hasn't been generated yet Laurent@814: if not self.PouComputed.get(pou_name, True): Laurent@814: # If not mark POU as computed Laurent@814: self.PouComputed[pou_name] = True Laurent@814: Laurent@814: # Getting POU model from project Laurent@814: pou = self.Project.getpou(pou_name) Laurent@814: pou_type = pou.getpouType() Laurent@814: # Verify that POU type exists Laurent@814: if pouTypeNames.has_key(pou_type): Laurent@814: # Create a POU program generator Laurent@814: pou_program = PouProgramGenerator(self, pou.getname(), pouTypeNames[pou_type], self.Errors, self.Warnings) Laurent@814: program = pou_program.GenerateProgram(pou) Laurent@814: self.Program += program Laurent@814: else: Laurent@814: raise PLCGenException, _("Undefined pou type \"%s\"")%pou_type Laurent@814: Laurent@814: # Generate a POU defined and used in text Laurent@814: def GeneratePouProgramInText(self, text): Laurent@814: for pou_name in self.PouComputed.keys(): Laurent@814: model = re.compile("(?:^|[^0-9^A-Z])%s(?:$|[^0-9^A-Z])"%pou_name.upper()) Laurent@814: if model.search(text) is not None: Laurent@814: self.GeneratePouProgram(pou_name) Laurent@814: Laurent@814: # Generate a configuration from its model Laurent@814: def GenerateConfiguration(self, configuration): Laurent@814: tagname = self.Controler.ComputeConfigurationName(configuration.getname()) Laurent@814: config = [("\nCONFIGURATION ", ()), Laurent@814: (configuration.getname(), (tagname, "name")), Laurent@814: ("\n", ())] Laurent@814: var_number = 0 Laurent@883: Laurent@883: varlists = [(varlist, varlist.getvariable()[:]) for varlist in configuration.getglobalVars()] Laurent@883: Laurent@883: extra_variables = self.Controler.GetConfigurationExtraVariables() Laurent@883: if len(extra_variables) > 0: Laurent@883: if len(varlists) == 0: Laurent@883: varlists = [(plcopen.interface_globalVars(), [])] Laurent@883: varlists[-1][1].extend(extra_variables) Laurent@883: Laurent@814: # Generate any global variable in configuration Laurent@883: for varlist, varlist_variables in varlists: Laurent@814: variable_type = errorVarTypes.get("VAR_GLOBAL", "var_local") Laurent@814: # Generate variable block with modifier Laurent@814: config += [(" VAR_GLOBAL", ())] Laurent@814: if varlist.getconstant(): Laurent@814: config += [(" CONSTANT", (tagname, variable_type, (var_number, var_number + len(varlist.getvariable())), "constant"))] Laurent@814: elif varlist.getretain(): Laurent@814: config += [(" RETAIN", (tagname, variable_type, (var_number, var_number + len(varlist.getvariable())), "retain"))] Laurent@814: elif varlist.getnonretain(): Laurent@814: config += [(" NON_RETAIN", (tagname, variable_type, (var_number, var_number + len(varlist.getvariable())), "non_retain"))] Laurent@814: config += [("\n", ())] Laurent@814: # Generate any variable of this block Laurent@883: for var in varlist_variables: Laurent@814: vartype_content = var.gettype().getcontent() Laurent@814: if vartype_content["name"] == "derived": Laurent@814: var_type = vartype_content["value"].getname() Laurent@814: self.GenerateDataType(var_type) Laurent@814: else: Laurent@814: var_type = var.gettypeAsText() Laurent@814: Laurent@814: config += [(" ", ()), Laurent@814: (var.getname(), (tagname, variable_type, var_number, "name")), Laurent@814: (" ", ())] Laurent@814: # Generate variable address if exists Laurent@814: address = var.getaddress() Laurent@814: if address: Laurent@814: config += [("AT ", ()), Laurent@814: (address, (tagname, variable_type, var_number, "location")), Laurent@814: (" ", ())] Laurent@814: config += [(": ", ()), Laurent@814: (var.gettypeAsText(), (tagname, variable_type, var_number, "type"))] Laurent@814: # Generate variable initial value if exists Laurent@814: initial = var.getinitialValue() Laurent@814: if initial: Laurent@814: config += [(" := ", ()), Laurent@814: (self.ComputeValue(initial.getvalue(), var_type), (tagname, variable_type, var_number, "initial value"))] Laurent@814: config += [(";\n", ())] Laurent@814: var_number += 1 Laurent@814: config += [(" END_VAR\n", ())] Laurent@814: # Generate any resource in the configuration Laurent@814: for resource in configuration.getresource(): Laurent@814: config += self.GenerateResource(resource, configuration.getname()) Laurent@814: config += [("END_CONFIGURATION\n", ())] Laurent@814: return config Laurent@814: Laurent@814: # Generate a resource from its model Laurent@814: def GenerateResource(self, resource, config_name): Laurent@814: tagname = self.Controler.ComputeConfigurationResourceName(config_name, resource.getname()) Laurent@814: resrce = [("\n RESOURCE ", ()), Laurent@814: (resource.getname(), (tagname, "name")), Laurent@814: (" ON PLC\n", ())] Laurent@814: var_number = 0 Laurent@814: # Generate any global variable in configuration Laurent@814: for varlist in resource.getglobalVars(): Laurent@814: variable_type = errorVarTypes.get("VAR_GLOBAL", "var_local") Laurent@814: # Generate variable block with modifier Laurent@814: resrce += [(" VAR_GLOBAL", ())] Laurent@814: if varlist.getconstant(): Laurent@814: resrce += [(" CONSTANT", (tagname, variable_type, (var_number, var_number + len(varlist.getvariable())), "constant"))] Laurent@814: elif varlist.getretain(): Laurent@814: resrce += [(" RETAIN", (tagname, variable_type, (var_number, var_number + len(varlist.getvariable())), "retain"))] Laurent@814: elif varlist.getnonretain(): Laurent@814: resrce += [(" NON_RETAIN", (tagname, variable_type, (var_number, var_number + len(varlist.getvariable())), "non_retain"))] Laurent@814: resrce += [("\n", ())] Laurent@814: # Generate any variable of this block Laurent@814: for var in varlist.getvariable(): Laurent@814: vartype_content = var.gettype().getcontent() Laurent@814: if vartype_content["name"] == "derived": Laurent@814: var_type = vartype_content["value"].getname() Laurent@814: self.GenerateDataType(var_type) Laurent@814: else: Laurent@814: var_type = var.gettypeAsText() Laurent@814: Laurent@814: resrce += [(" ", ()), Laurent@814: (var.getname(), (tagname, variable_type, var_number, "name")), Laurent@814: (" ", ())] Laurent@814: address = var.getaddress() Laurent@814: # Generate variable address if exists Laurent@814: if address: Laurent@814: resrce += [("AT ", ()), Laurent@814: (address, (tagname, variable_type, var_number, "location")), Laurent@814: (" ", ())] Laurent@814: resrce += [(": ", ()), Laurent@814: (var.gettypeAsText(), (tagname, variable_type, var_number, "type"))] Laurent@814: # Generate variable initial value if exists Laurent@814: initial = var.getinitialValue() Laurent@814: if initial: Laurent@814: resrce += [(" := ", ()), Laurent@814: (self.ComputeValue(initial.getvalue(), var_type), (tagname, variable_type, var_number, "initial value"))] Laurent@814: resrce += [(";\n", ())] Laurent@814: var_number += 1 Laurent@814: resrce += [(" END_VAR\n", ())] Laurent@814: # Generate any task in the resource Laurent@814: tasks = resource.gettask() Laurent@814: task_number = 0 Laurent@814: for task in tasks: Laurent@814: # Task declaration Laurent@814: resrce += [(" TASK ", ()), Laurent@814: (task.getname(), (tagname, "task", task_number, "name")), Laurent@814: ("(", ())] Laurent@814: args = [] Laurent@814: single = task.getsingle() Laurent@814: # Single argument if exists Laurent@814: if single: Laurent@814: resrce += [("SINGLE := ", ()), Laurent@814: (single, (tagname, "task", task_number, "single")), Laurent@814: (",", ())] Laurent@814: # Interval argument if exists Laurent@814: interval = task.getinterval() Laurent@814: if interval: Laurent@814: resrce += [("INTERVAL := ", ()), Laurent@814: (interval, (tagname, "task", task_number, "interval")), Laurent@814: (",", ())] Laurent@814: ## resrce += [("INTERVAL := t#", ())] Laurent@814: ## if interval.hour != 0: Laurent@814: ## resrce += [("%dh"%interval.hour, (tagname, "task", task_number, "interval", "hour"))] Laurent@814: ## if interval.minute != 0: Laurent@814: ## resrce += [("%dm"%interval.minute, (tagname, "task", task_number, "interval", "minute"))] Laurent@814: ## if interval.second != 0: Laurent@814: ## resrce += [("%ds"%interval.second, (tagname, "task", task_number, "interval", "second"))] Laurent@814: ## if interval.microsecond != 0: Laurent@814: ## resrce += [("%dms"%(interval.microsecond / 1000), (tagname, "task", task_number, "interval", "millisecond"))] Laurent@814: ## resrce += [(",", ())] Laurent@814: # Priority argument Laurent@814: resrce += [("PRIORITY := ", ()), Laurent@814: ("%d"%task.getpriority(), (tagname, "task", task_number, "priority")), Laurent@814: (");\n", ())] Laurent@814: task_number += 1 Laurent@814: instance_number = 0 Laurent@814: # Generate any program assign to each task Laurent@814: for task in tasks: Laurent@814: for instance in task.getpouInstance(): Laurent@814: resrce += [(" PROGRAM ", ()), Laurent@814: (instance.getname(), (tagname, "instance", instance_number, "name")), Laurent@814: (" WITH ", ()), Laurent@814: (task.getname(), (tagname, "instance", instance_number, "task")), Laurent@814: (" : ", ()), Laurent@814: (instance.gettypeName(), (tagname, "instance", instance_number, "type")), Laurent@814: (";\n", ())] Laurent@814: instance_number += 1 Laurent@814: # Generate any program assign to no task Laurent@814: for instance in resource.getpouInstance(): Laurent@814: resrce += [(" PROGRAM ", ()), Laurent@814: (instance.getname(), (tagname, "instance", instance_number, "name")), Laurent@814: (" : ", ()), Laurent@814: (instance.gettypeName(), (tagname, "instance", instance_number, "type")), Laurent@814: (";\n", ())] Laurent@814: instance_number += 1 Laurent@814: resrce += [(" END_RESOURCE\n", ())] Laurent@814: return resrce Laurent@814: Laurent@814: # Generate the entire program for current project Laurent@814: def GenerateProgram(self): Laurent@814: # Find all data types defined Laurent@814: for datatype in self.Project.getdataTypes(): Laurent@814: self.DatatypeComputed[datatype.getname()] = False Laurent@814: # Find all data types defined Laurent@814: for pou in self.Project.getpous(): Laurent@814: self.PouComputed[pou.getname()] = False Laurent@814: # Generate data type declaration structure if there is at least one data Laurent@814: # type defined Laurent@814: if len(self.DatatypeComputed) > 0: Laurent@814: self.Program += [("TYPE\n", ())] Laurent@814: # Generate every data types defined Laurent@814: for datatype_name in self.DatatypeComputed.keys(): Laurent@814: self.GenerateDataType(datatype_name) Laurent@814: self.Program += [("END_TYPE\n\n", ())] Laurent@814: # Generate every POUs defined Laurent@814: for pou_name in self.PouComputed.keys(): Laurent@814: self.GeneratePouProgram(pou_name) Laurent@814: # Generate every configurations defined Laurent@814: for config in self.Project.getconfigurations(): Laurent@814: self.Program += self.GenerateConfiguration(config) Laurent@814: Laurent@814: # Return generated program Laurent@814: def GetGeneratedProgram(self): Laurent@814: return self.Program Laurent@814: Laurent@814: Laurent@814: #------------------------------------------------------------------------------- Laurent@814: # Generator of POU programs Laurent@814: #------------------------------------------------------------------------------- Laurent@814: Laurent@814: Laurent@814: class PouProgramGenerator: Laurent@814: Laurent@814: # Create a new POU program generator Laurent@814: def __init__(self, parent, name, type, errors, warnings): Laurent@814: # Keep Reference to the parent generator Laurent@814: self.ParentGenerator = parent Laurent@814: self.Name = name Laurent@814: self.Type = type Laurent@814: self.TagName = self.ParentGenerator.Controler.ComputePouName(name) Laurent@814: self.CurrentIndent = " " Laurent@814: self.ReturnType = None Laurent@814: self.Interface = [] Laurent@814: self.InitialSteps = [] Laurent@814: self.ComputedBlocks = {} Laurent@814: self.ComputedConnectors = {} Laurent@814: self.ConnectionTypes = {} Laurent@814: self.RelatedConnections = [] Laurent@814: self.SFCNetworks = {"Steps":{}, "Transitions":{}, "Actions":{}} Laurent@814: self.SFCComputedBlocks = [] Laurent@814: self.ActionNumber = 0 Laurent@814: self.Program = [] Laurent@814: self.Errors = errors Laurent@814: self.Warnings = warnings Laurent@814: Laurent@814: def GetBlockType(self, type, inputs=None): Laurent@814: return self.ParentGenerator.Controler.GetBlockType(type, inputs) Laurent@814: Laurent@814: def IndentLeft(self): Laurent@814: if len(self.CurrentIndent) >= 2: Laurent@814: self.CurrentIndent = self.CurrentIndent[:-2] Laurent@814: Laurent@814: def IndentRight(self): Laurent@814: self.CurrentIndent += " " Laurent@814: Laurent@814: # Generator of unique ID for inline actions Laurent@814: def GetActionNumber(self): Laurent@814: self.ActionNumber += 1 Laurent@814: return self.ActionNumber Laurent@814: Laurent@814: # Test if a variable has already been defined Laurent@814: def IsAlreadyDefined(self, name): Laurent@814: for list_type, option, located, vars in self.Interface: Laurent@814: for var_type, var_name, var_address, var_initial in vars: Laurent@814: if name == var_name: Laurent@814: return True Laurent@814: return False Laurent@814: Laurent@814: # Return the type of a variable defined in interface Laurent@814: def GetVariableType(self, name): Laurent@814: parts = name.split('.') Laurent@814: current_type = None Laurent@814: if len(parts) > 0: Laurent@814: name = parts.pop(0) Laurent@814: for list_type, option, located, vars in self.Interface: Laurent@814: for var_type, var_name, var_address, var_initial in vars: Laurent@814: if name == var_name: Laurent@814: current_type = var_type Laurent@814: break Laurent@814: while current_type is not None and len(parts) > 0: Laurent@883: blocktype = self.ParentGenerator.Controler.GetBlockType(current_type) Laurent@883: if blocktype is not None: Laurent@883: name = parts.pop(0) Laurent@883: current_type = None Laurent@883: for var_name, var_type, var_modifier in blocktype["inputs"] + blocktype["outputs"]: Laurent@883: if var_name == name: Laurent@883: current_type = var_type Laurent@814: break Laurent@883: else: Laurent@883: tagname = self.ParentGenerator.Controler.ComputeDataTypeName(current_type) Laurent@883: infos = self.ParentGenerator.Controler.GetDataTypeInfos(tagname) Laurent@883: if infos is not None and infos["type"] == "Structure": Laurent@883: name = parts.pop(0) Laurent@883: current_type = None Laurent@883: for element in infos["elements"]: Laurent@883: if element["Name"] == name: Laurent@883: current_type = element["Type"] Laurent@883: break Laurent@814: return current_type Laurent@814: Laurent@814: # Return connectors linked by a connection to the given connector Laurent@814: def GetConnectedConnector(self, connector, body): Laurent@814: links = connector.getconnections() Laurent@814: if links and len(links) == 1: Laurent@814: return self.GetLinkedConnector(links[0], body) Laurent@814: return None Laurent@814: Laurent@814: def GetLinkedConnector(self, link, body): Laurent@814: parameter = link.getformalParameter() Laurent@814: instance = body.getcontentInstance(link.getrefLocalId()) Laurent@814: if isinstance(instance, (plcopen.fbdObjects_inVariable, plcopen.fbdObjects_inOutVariable, plcopen.commonObjects_continuation, plcopen.ldObjects_contact, plcopen.ldObjects_coil)): Laurent@814: return instance.connectionPointOut Laurent@814: elif isinstance(instance, plcopen.fbdObjects_block): Laurent@814: outputvariables = instance.outputVariables.getvariable() Laurent@814: if len(outputvariables) == 1: Laurent@814: return outputvariables[0].connectionPointOut Laurent@814: elif parameter: Laurent@814: for variable in outputvariables: Laurent@814: if variable.getformalParameter() == parameter: Laurent@814: return variable.connectionPointOut Laurent@814: else: Laurent@814: point = link.getposition()[-1] Laurent@814: for variable in outputvariables: Laurent@814: relposition = variable.connectionPointOut.getrelPositionXY() Laurent@814: blockposition = instance.getposition() Laurent@814: if point.x == blockposition.x + relposition[0] and point.y == blockposition.y + relposition[1]: Laurent@814: return variable.connectionPointOut Laurent@814: elif isinstance(instance, plcopen.ldObjects_leftPowerRail): Laurent@814: outputconnections = instance.getconnectionPointOut() Laurent@814: if len(outputconnections) == 1: Laurent@814: return outputconnections[0] Laurent@814: else: Laurent@814: point = link.getposition()[-1] Laurent@814: for outputconnection in outputconnections: Laurent@814: relposition = outputconnection.getrelPositionXY() Laurent@814: powerrailposition = instance.getposition() Laurent@814: if point.x == powerrailposition.x + relposition[0] and point.y == powerrailposition.y + relposition[1]: Laurent@814: return outputconnection Laurent@814: return None Laurent@814: Laurent@814: def ExtractRelatedConnections(self, connection): Laurent@814: for i, related in enumerate(self.RelatedConnections): Laurent@814: if connection in related: Laurent@814: return self.RelatedConnections.pop(i) Laurent@814: return [connection] Laurent@814: Laurent@814: def ComputeInterface(self, pou): Laurent@814: interface = pou.getinterface() Laurent@814: if interface is not None: Laurent@814: body = pou.getbody() Laurent@814: if isinstance(body, ListType): Laurent@814: body = body[0] Laurent@814: body_content = body.getcontent() Laurent@814: if self.Type == "FUNCTION": Laurent@814: returntype_content = interface.getreturnType().getcontent() Laurent@814: if returntype_content["name"] == "derived": Laurent@814: self.ReturnType = returntype_content["value"].getname() Laurent@814: elif returntype_content["name"] in ["string", "wstring"]: Laurent@814: self.ReturnType = returntype_content["name"].upper() Laurent@814: else: Laurent@814: self.ReturnType = returntype_content["name"] Laurent@814: for varlist in interface.getcontent(): Laurent@814: variables = [] Laurent@814: located = [] Laurent@814: for var in varlist["value"].getvariable(): Laurent@814: vartype_content = var.gettype().getcontent() Laurent@814: if vartype_content["name"] == "derived": Laurent@814: var_type = vartype_content["value"].getname() Laurent@814: blocktype = self.GetBlockType(var_type) Laurent@814: if blocktype is not None: Laurent@814: self.ParentGenerator.GeneratePouProgram(var_type) Laurent@814: if body_content["name"] in ["FBD", "LD", "SFC"]: Laurent@814: block = pou.getinstanceByName(var.getname()) Laurent@814: else: Laurent@814: block = None Laurent@814: for variable in blocktype["initialise"](var_type, var.getname(), block): Laurent@814: if variable[2] is not None: Laurent@814: located.append(variable) Laurent@814: else: Laurent@814: variables.append(variable) Laurent@814: else: Laurent@814: self.ParentGenerator.GenerateDataType(var_type) Laurent@814: initial = var.getinitialValue() Laurent@814: if initial: Laurent@814: initial_value = initial.getvalue() Laurent@814: else: Laurent@814: initial_value = None Laurent@814: address = var.getaddress() Laurent@814: if address is not None: Laurent@814: located.append((vartype_content["value"].getname(), var.getname(), address, initial_value)) Laurent@814: else: Laurent@814: variables.append((vartype_content["value"].getname(), var.getname(), None, initial_value)) Laurent@814: else: Laurent@814: var_type = var.gettypeAsText() Laurent@814: initial = var.getinitialValue() Laurent@814: if initial: Laurent@814: initial_value = initial.getvalue() Laurent@814: else: Laurent@814: initial_value = None Laurent@814: address = var.getaddress() Laurent@814: if address is not None: Laurent@814: located.append((var_type, var.getname(), address, initial_value)) Laurent@814: else: Laurent@814: variables.append((var_type, var.getname(), None, initial_value)) Laurent@814: if varlist["value"].getconstant(): Laurent@814: option = "CONSTANT" Laurent@814: elif varlist["value"].getretain(): Laurent@814: option = "RETAIN" Laurent@814: elif varlist["value"].getnonretain(): Laurent@814: option = "NON_RETAIN" Laurent@814: else: Laurent@814: option = None Laurent@814: if len(variables) > 0: Laurent@814: self.Interface.append((varTypeNames[varlist["name"]], option, False, variables)) Laurent@814: if len(located) > 0: Laurent@814: self.Interface.append((varTypeNames[varlist["name"]], option, True, located)) Laurent@814: Laurent@814: def ComputeConnectionTypes(self, pou): Laurent@814: body = pou.getbody() Laurent@814: if isinstance(body, ListType): Laurent@814: body = body[0] Laurent@814: body_content = body.getcontent() Laurent@814: body_type = body_content["name"] Laurent@814: if body_type in ["FBD", "LD", "SFC"]: Laurent@814: undefined_blocks = [] Laurent@814: for instance in body.getcontentInstances(): Laurent@814: if isinstance(instance, (plcopen.fbdObjects_inVariable, plcopen.fbdObjects_outVariable, plcopen.fbdObjects_inOutVariable)): Laurent@814: expression = instance.getexpression() Laurent@814: var_type = self.GetVariableType(expression) laurent@822: if isinstance(pou, plcopen.transitions_transition) and expression == pou.getname(): laurent@822: var_type = "BOOL" laurent@822: elif (not isinstance(pou, (plcopen.transitions_transition, plcopen.actions_action)) and laurent@822: pou.getpouType() == "function" and expression == pou.getname()): Laurent@814: returntype_content = pou.interface.getreturnType().getcontent() Laurent@814: if returntype_content["name"] == "derived": Laurent@814: var_type = returntype_content["value"].getname() Laurent@814: elif returntype_content["name"] in ["string", "wstring"]: Laurent@814: var_type = returntype_content["name"].upper() Laurent@814: else: Laurent@814: var_type = returntype_content["name"] Laurent@814: elif var_type is None: Laurent@814: parts = expression.split("#") Laurent@814: if len(parts) > 1: Laurent@814: var_type = parts[0] Laurent@814: elif expression.startswith("'"): Laurent@814: var_type = "STRING" Laurent@814: elif expression.startswith('"'): Laurent@814: var_type = "WSTRING" Laurent@814: if var_type is not None: Laurent@814: if isinstance(instance, (plcopen.fbdObjects_inVariable, plcopen.fbdObjects_inOutVariable)): Laurent@814: for connection in self.ExtractRelatedConnections(instance.connectionPointOut): Laurent@814: self.ConnectionTypes[connection] = var_type Laurent@814: if isinstance(instance, (plcopen.fbdObjects_outVariable, plcopen.fbdObjects_inOutVariable)): Laurent@814: self.ConnectionTypes[instance.connectionPointIn] = var_type Laurent@814: connected = self.GetConnectedConnector(instance.connectionPointIn, body) Laurent@814: if connected and not self.ConnectionTypes.has_key(connected): Laurent@814: for connection in self.ExtractRelatedConnections(connected): Laurent@814: self.ConnectionTypes[connection] = var_type Laurent@814: elif isinstance(instance, (plcopen.ldObjects_contact, plcopen.ldObjects_coil)): Laurent@814: for connection in self.ExtractRelatedConnections(instance.connectionPointOut): Laurent@814: self.ConnectionTypes[connection] = "BOOL" Laurent@814: self.ConnectionTypes[instance.connectionPointIn] = "BOOL" Laurent@814: connected = self.GetConnectedConnector(instance.connectionPointIn, body) Laurent@814: if connected and not self.ConnectionTypes.has_key(connected): Laurent@814: for connection in self.ExtractRelatedConnections(connected): Laurent@814: self.ConnectionTypes[connection] = "BOOL" Laurent@814: elif isinstance(instance, plcopen.ldObjects_leftPowerRail): Laurent@814: for connection in instance.getconnectionPointOut(): Laurent@814: for related in self.ExtractRelatedConnections(connection): Laurent@814: self.ConnectionTypes[related] = "BOOL" Laurent@814: elif isinstance(instance, plcopen.ldObjects_rightPowerRail): Laurent@814: for connection in instance.getconnectionPointIn(): Laurent@814: self.ConnectionTypes[connection] = "BOOL" Laurent@814: connected = self.GetConnectedConnector(connection, body) Laurent@814: if connected and not self.ConnectionTypes.has_key(connected): Laurent@814: for connection in self.ExtractRelatedConnections(connected): Laurent@814: self.ConnectionTypes[connection] = "BOOL" Laurent@814: elif isinstance(instance, plcopen.sfcObjects_transition): Laurent@814: content = instance.condition.getcontent() Laurent@814: if content["name"] == "connection" and len(content["value"]) == 1: Laurent@814: connected = self.GetLinkedConnector(content["value"][0], body) Laurent@814: if connected and not self.ConnectionTypes.has_key(connected): Laurent@814: for connection in self.ExtractRelatedConnections(connected): Laurent@814: self.ConnectionTypes[connection] = "BOOL" Laurent@814: elif isinstance(instance, plcopen.commonObjects_continuation): Laurent@814: name = instance.getname() Laurent@814: connector = None Laurent@814: var_type = "ANY" Laurent@814: for element in body.getcontentInstances(): Laurent@814: if isinstance(element, plcopen.commonObjects_connector) and element.getname() == name: Laurent@814: if connector is not None: Laurent@814: raise PLCGenException, _("More than one connector found corresponding to \"%s\" continuation in \"%s\" POU")%(name, self.Name) Laurent@814: connector = element Laurent@814: if connector is not None: Laurent@814: undefined = [instance.connectionPointOut, connector.connectionPointIn] Laurent@814: connected = self.GetConnectedConnector(connector.connectionPointIn, body) Laurent@814: if connected: Laurent@814: undefined.append(connected) Laurent@814: related = [] Laurent@814: for connection in undefined: Laurent@814: if self.ConnectionTypes.has_key(connection): Laurent@814: var_type = self.ConnectionTypes[connection] Laurent@814: else: Laurent@814: related.extend(self.ExtractRelatedConnections(connection)) Laurent@814: if var_type.startswith("ANY") and len(related) > 0: Laurent@814: self.RelatedConnections.append(related) Laurent@814: else: Laurent@814: for connection in related: Laurent@814: self.ConnectionTypes[connection] = var_type Laurent@814: else: Laurent@814: raise PLCGenException, _("No connector found corresponding to \"%s\" continuation in \"%s\" POU")%(name, self.Name) Laurent@814: elif isinstance(instance, plcopen.fbdObjects_block): Laurent@814: block_infos = self.GetBlockType(instance.gettypeName(), "undefined") Laurent@814: if block_infos is not None: Laurent@814: self.ComputeBlockInputTypes(instance, block_infos, body) Laurent@814: else: Laurent@814: for variable in instance.inputVariables.getvariable(): Laurent@814: connected = self.GetConnectedConnector(variable.connectionPointIn, body) Laurent@814: if connected is not None: Laurent@814: var_type = self.ConnectionTypes.get(connected, None) Laurent@814: if var_type is not None: Laurent@814: self.ConnectionTypes[variable.connectionPointIn] = var_type Laurent@814: else: Laurent@814: related = self.ExtractRelatedConnections(connected) Laurent@814: related.append(variable.connectionPointIn) Laurent@814: self.RelatedConnections.append(related) Laurent@814: undefined_blocks.append(instance) Laurent@814: for instance in undefined_blocks: Laurent@814: block_infos = self.GetBlockType(instance.gettypeName(), tuple([self.ConnectionTypes.get(variable.connectionPointIn, "ANY") for variable in instance.inputVariables.getvariable() if variable.getformalParameter() != "EN"])) Laurent@814: if block_infos is not None: Laurent@814: self.ComputeBlockInputTypes(instance, block_infos, body) Laurent@814: else: Laurent@814: raise PLCGenException, _("No informations found for \"%s\" block")%(instance.gettypeName()) laurent@822: if body_type == "SFC": laurent@822: previous_tagname = self.TagName laurent@822: for action in pou.getactionList(): laurent@822: self.TagName = self.ParentGenerator.Controler.ComputePouActionName(self.Name, action.getname()) laurent@822: self.ComputeConnectionTypes(action) laurent@822: for transition in pou.gettransitionList(): laurent@822: self.TagName = self.ParentGenerator.Controler.ComputePouTransitionName(self.Name, transition.getname()) laurent@822: self.ComputeConnectionTypes(transition) laurent@822: self.TagName = previous_tagname Laurent@814: Laurent@814: def ComputeBlockInputTypes(self, instance, block_infos, body): Laurent@814: undefined = {} Laurent@814: for variable in instance.outputVariables.getvariable(): Laurent@814: output_name = variable.getformalParameter() Laurent@814: if output_name == "ENO": Laurent@814: for connection in self.ExtractRelatedConnections(variable.connectionPointOut): Laurent@814: self.ConnectionTypes[connection] = "BOOL" Laurent@814: else: Laurent@814: for oname, otype, oqualifier in block_infos["outputs"]: Laurent@814: if output_name == oname: Laurent@814: if otype.startswith("ANY"): Laurent@814: if not undefined.has_key(otype): Laurent@814: undefined[otype] = [] Laurent@814: undefined[otype].append(variable.connectionPointOut) Laurent@814: elif not self.ConnectionTypes.has_key(variable.connectionPointOut): Laurent@814: for connection in self.ExtractRelatedConnections(variable.connectionPointOut): Laurent@814: self.ConnectionTypes[connection] = otype Laurent@814: for variable in instance.inputVariables.getvariable(): Laurent@814: input_name = variable.getformalParameter() Laurent@814: if input_name == "EN": Laurent@814: for connection in self.ExtractRelatedConnections(variable.connectionPointIn): Laurent@814: self.ConnectionTypes[connection] = "BOOL" Laurent@814: else: Laurent@814: for iname, itype, iqualifier in block_infos["inputs"]: Laurent@814: if input_name == iname: Laurent@814: connected = self.GetConnectedConnector(variable.connectionPointIn, body) Laurent@814: if itype.startswith("ANY"): Laurent@814: if not undefined.has_key(itype): Laurent@814: undefined[itype] = [] Laurent@814: undefined[itype].append(variable.connectionPointIn) Laurent@814: if connected: Laurent@814: undefined[itype].append(connected) Laurent@814: else: Laurent@814: self.ConnectionTypes[variable.connectionPointIn] = itype Laurent@814: if connected and not self.ConnectionTypes.has_key(connected): Laurent@814: for connection in self.ExtractRelatedConnections(connected): Laurent@814: self.ConnectionTypes[connection] = itype Laurent@814: for var_type, connections in undefined.items(): Laurent@814: related = [] Laurent@814: for connection in connections: Laurent@854: connection_type = self.ConnectionTypes.get(connection) Laurent@854: if connection_type and not connection_type.startswith("ANY"): Laurent@854: var_type = connection_type Laurent@814: else: Laurent@814: related.extend(self.ExtractRelatedConnections(connection)) Laurent@814: if var_type.startswith("ANY") and len(related) > 0: Laurent@814: self.RelatedConnections.append(related) Laurent@814: else: Laurent@814: for connection in related: Laurent@814: self.ConnectionTypes[connection] = var_type Laurent@814: Laurent@814: def ComputeProgram(self, pou): Laurent@814: body = pou.getbody() Laurent@814: if isinstance(body, ListType): Laurent@814: body = body[0] Laurent@814: body_content = body.getcontent() Laurent@814: body_type = body_content["name"] Laurent@814: if body_type in ["IL","ST"]: Laurent@814: text = body_content["value"].gettext() Laurent@814: self.ParentGenerator.GeneratePouProgramInText(text.upper()) Laurent@814: self.Program = [(ReIndentText(text, len(self.CurrentIndent)), Laurent@814: (self.TagName, "body", len(self.CurrentIndent)))] Laurent@814: elif body_type == "SFC": Laurent@814: self.IndentRight() Laurent@814: for instance in body.getcontentInstances(): Laurent@814: if isinstance(instance, plcopen.sfcObjects_step): Laurent@814: self.GenerateSFCStep(instance, pou) Laurent@814: elif isinstance(instance, plcopen.commonObjects_actionBlock): Laurent@814: self.GenerateSFCStepActions(instance, pou) Laurent@814: elif isinstance(instance, plcopen.sfcObjects_transition): Laurent@814: self.GenerateSFCTransition(instance, pou) Laurent@814: elif isinstance(instance, plcopen.sfcObjects_jumpStep): Laurent@814: self.GenerateSFCJump(instance, pou) Laurent@814: if len(self.InitialSteps) > 0 and len(self.SFCComputedBlocks) > 0: Laurent@814: action_name = "COMPUTE_FUNCTION_BLOCKS" Laurent@814: action_infos = {"qualifier" : "S", "content" : action_name} Laurent@814: self.SFCNetworks["Steps"][self.InitialSteps[0]]["actions"].append(action_infos) Laurent@814: self.SFCNetworks["Actions"][action_name] = (self.SFCComputedBlocks, ()) Laurent@814: self.Program = [] Laurent@814: self.IndentLeft() Laurent@814: for initialstep in self.InitialSteps: Laurent@814: self.ComputeSFCStep(initialstep) Laurent@814: else: Laurent@814: otherInstances = {"outVariables&coils" : [], "blocks" : [], "connectors" : []} Laurent@814: orderedInstances = [] Laurent@814: for instance in body.getcontentInstances(): Laurent@814: if isinstance(instance, (plcopen.fbdObjects_outVariable, plcopen.fbdObjects_inOutVariable, plcopen.fbdObjects_block)): Laurent@814: executionOrderId = instance.getexecutionOrderId() Laurent@814: if executionOrderId > 0: Laurent@814: orderedInstances.append((executionOrderId, instance)) Laurent@814: elif isinstance(instance, (plcopen.fbdObjects_outVariable, plcopen.fbdObjects_inOutVariable)): Laurent@814: otherInstances["outVariables&coils"].append(instance) Laurent@814: elif isinstance(instance, plcopen.fbdObjects_block): Laurent@814: otherInstances["blocks"].append(instance) Laurent@814: elif isinstance(instance, plcopen.commonObjects_connector): Laurent@814: otherInstances["connectors"].append(instance) Laurent@814: elif isinstance(instance, plcopen.ldObjects_coil): Laurent@814: otherInstances["outVariables&coils"].append(instance) Laurent@814: orderedInstances.sort() Laurent@814: otherInstances["outVariables&coils"].sort(SortInstances) Laurent@814: otherInstances["blocks"].sort(SortInstances) Laurent@814: instances = [instance for (executionOrderId, instance) in orderedInstances] Laurent@1048: instances.extend(otherInstances["outVariables&coils"] + otherInstances["blocks"] + otherInstances["connectors"]) Laurent@814: for instance in instances: Laurent@814: if isinstance(instance, (plcopen.fbdObjects_outVariable, plcopen.fbdObjects_inOutVariable)): Laurent@814: connections = instance.connectionPointIn.getconnections() Laurent@814: if connections is not None: Laurent@814: expression = self.ComputeExpression(body, connections) Laurent@814: self.Program += [(self.CurrentIndent, ()), Laurent@814: (instance.getexpression(), (self.TagName, "io_variable", instance.getlocalId(), "expression")), Laurent@814: (" := ", ())] Laurent@814: self.Program += expression Laurent@814: self.Program += [(";\n", ())] Laurent@814: elif isinstance(instance, plcopen.fbdObjects_block): Laurent@814: block_type = instance.gettypeName() Laurent@814: self.ParentGenerator.GeneratePouProgram(block_type) Laurent@814: block_infos = self.GetBlockType(block_type, tuple([self.ConnectionTypes.get(variable.connectionPointIn, "ANY") for variable in instance.inputVariables.getvariable() if variable.getformalParameter() != "EN"])) Laurent@814: if block_infos is None: Laurent@814: block_infos = self.GetBlockType(block_type) Laurent@814: if block_infos is None: Laurent@814: raise PLCGenException, _("Undefined block type \"%s\" in \"%s\" POU")%(block_type, self.Name) Laurent@1134: try: Laurent@1134: block_infos["generate"](self, instance, block_infos, body, None) Laurent@1134: except ValueError, e: Laurent@1134: raise PLCGenException, e.message Laurent@814: elif isinstance(instance, plcopen.commonObjects_connector): Laurent@814: connector = instance.getname() Laurent@814: if self.ComputedConnectors.get(connector, None): Laurent@814: continue Laurent@814: self.ComputedConnectors[connector] = self.ComputeExpression(body, instance.connectionPointIn.getconnections()) Laurent@814: elif isinstance(instance, plcopen.ldObjects_coil): Laurent@814: connections = instance.connectionPointIn.getconnections() Laurent@814: if connections is not None: Laurent@814: coil_info = (self.TagName, "coil", instance.getlocalId()) Laurent@814: expression = self.ExtractModifier(instance, self.ComputeExpression(body, connections), coil_info) Laurent@814: self.Program += [(self.CurrentIndent, ())] Laurent@814: self.Program += [(instance.getvariable(), coil_info + ("reference",))] Laurent@814: self.Program += [(" := ", ())] + expression + [(";\n", ())] Laurent@814: Laurent@814: def FactorizePaths(self, paths): Laurent@814: same_paths = {} Laurent@814: uncomputed_index = range(len(paths)) Laurent@814: factorized_paths = [] Laurent@814: for num, path in enumerate(paths): Laurent@814: if type(path) == ListType: Laurent@814: if len(path) > 1: Laurent@814: str_path = str(path[-1:]) Laurent@814: same_paths.setdefault(str_path, []) Laurent@814: same_paths[str_path].append((path[:-1], num)) Laurent@814: else: Laurent@814: factorized_paths.append(path) Laurent@814: uncomputed_index.remove(num) Laurent@814: for same_path, elements in same_paths.items(): Laurent@814: if len(elements) > 1: Laurent@814: elements_paths = self.FactorizePaths([path for path, num in elements]) Laurent@814: if len(elements_paths) > 1: Laurent@814: factorized_paths.append([tuple(elements_paths)] + eval(same_path)) Laurent@814: else: Laurent@814: factorized_paths.append(elements_paths + eval(same_path)) Laurent@814: for path, num in elements: Laurent@814: uncomputed_index.remove(num) Laurent@814: for num in uncomputed_index: Laurent@814: factorized_paths.append(paths[num]) Laurent@814: factorized_paths.sort() Laurent@814: return factorized_paths Laurent@814: Laurent@814: def GeneratePaths(self, connections, body, order = False, to_inout = False): Laurent@814: paths = [] Laurent@814: for connection in connections: Laurent@814: localId = connection.getrefLocalId() Laurent@814: next = body.getcontentInstance(localId) Laurent@814: if isinstance(next, plcopen.ldObjects_leftPowerRail): Laurent@814: paths.append(None) Laurent@814: elif isinstance(next, (plcopen.fbdObjects_inVariable, plcopen.fbdObjects_inOutVariable)): Laurent@814: paths.append(str([(next.getexpression(), (self.TagName, "io_variable", localId, "expression"))])) Laurent@814: elif isinstance(next, plcopen.fbdObjects_block): Laurent@814: block_type = next.gettypeName() Laurent@814: self.ParentGenerator.GeneratePouProgram(block_type) Laurent@814: block_infos = self.GetBlockType(block_type, tuple([self.ConnectionTypes.get(variable.connectionPointIn, "ANY") for variable in next.inputVariables.getvariable() if variable.getformalParameter() != "EN"])) Laurent@814: if block_infos is None: Laurent@814: block_infos = self.GetBlockType(block_type) Laurent@814: if block_infos is None: Laurent@814: raise PLCGenException, _("Undefined block type \"%s\" in \"%s\" POU")%(block_type, self.Name) Laurent@1134: try: Laurent@1134: paths.append(str(block_infos["generate"](self, next, block_infos, body, connection, order, to_inout))) Laurent@1134: except ValueError, e: Laurent@1134: raise PLCGenException, e.message Laurent@814: elif isinstance(next, plcopen.commonObjects_continuation): Laurent@814: name = next.getname() Laurent@814: computed_value = self.ComputedConnectors.get(name, None) Laurent@814: if computed_value != None: Laurent@814: paths.append(str(computed_value)) Laurent@814: else: Laurent@814: connector = None Laurent@814: for instance in body.getcontentInstances(): Laurent@814: if isinstance(instance, plcopen.commonObjects_connector) and instance.getname() == name: Laurent@814: if connector is not None: Laurent@814: raise PLCGenException, _("More than one connector found corresponding to \"%s\" continuation in \"%s\" POU")%(name, self.Name) Laurent@814: connector = instance Laurent@814: if connector is not None: Laurent@814: connections = connector.connectionPointIn.getconnections() Laurent@814: if connections is not None: Laurent@814: expression = self.ComputeExpression(body, connections, order) Laurent@814: self.ComputedConnectors[name] = expression Laurent@814: paths.append(str(expression)) Laurent@814: else: Laurent@814: raise PLCGenException, _("No connector found corresponding to \"%s\" continuation in \"%s\" POU")%(name, self.Name) Laurent@814: elif isinstance(next, plcopen.ldObjects_contact): Laurent@814: contact_info = (self.TagName, "contact", next.getlocalId()) Laurent@814: variable = str(self.ExtractModifier(next, [(next.getvariable(), contact_info + ("reference",))], contact_info)) Laurent@814: result = self.GeneratePaths(next.connectionPointIn.getconnections(), body, order) Laurent@814: if len(result) > 1: Laurent@814: factorized_paths = self.FactorizePaths(result) Laurent@814: if len(factorized_paths) > 1: Laurent@814: paths.append([variable, tuple(factorized_paths)]) Laurent@814: else: Laurent@814: paths.append([variable] + factorized_paths) Laurent@814: elif type(result[0]) == ListType: Laurent@814: paths.append([variable] + result[0]) Laurent@814: elif result[0] is not None: Laurent@814: paths.append([variable, result[0]]) Laurent@814: else: Laurent@814: paths.append(variable) Laurent@814: elif isinstance(next, plcopen.ldObjects_coil): Laurent@814: paths.append(str(self.GeneratePaths(next.connectionPointIn.getconnections(), body, order))) Laurent@814: return paths Laurent@814: Laurent@814: def ComputePaths(self, paths, first = False): Laurent@814: if type(paths) == TupleType: Laurent@814: if None in paths: Laurent@814: return [("TRUE", ())] Laurent@814: else: Laurent@814: vars = [self.ComputePaths(path) for path in paths] Laurent@814: if first: Laurent@814: return JoinList([(" OR ", ())], vars) Laurent@814: else: Laurent@814: return [("(", ())] + JoinList([(" OR ", ())], vars) + [(")", ())] Laurent@814: elif type(paths) == ListType: Laurent@814: vars = [self.ComputePaths(path) for path in paths] Laurent@814: return JoinList([(" AND ", ())], vars) Laurent@814: elif paths is None: Laurent@814: return [("TRUE", ())] Laurent@814: else: Laurent@814: return eval(paths) Laurent@814: Laurent@814: def ComputeExpression(self, body, connections, order = False, to_inout = False): Laurent@814: paths = self.GeneratePaths(connections, body, order, to_inout) Laurent@814: if len(paths) > 1: Laurent@814: factorized_paths = self.FactorizePaths(paths) Laurent@814: if len(factorized_paths) > 1: Laurent@814: paths = tuple(factorized_paths) Laurent@814: else: Laurent@814: paths = factorized_paths[0] Laurent@814: else: Laurent@814: paths = paths[0] Laurent@814: return self.ComputePaths(paths, True) Laurent@814: Laurent@814: def ExtractModifier(self, variable, expression, var_info): Laurent@814: if variable.getnegated(): Laurent@814: return [("NOT(", var_info + ("negated",))] + expression + [(")", ())] Laurent@814: else: Laurent@814: storage = variable.getstorage() Laurent@814: if storage in ["set", "reset"]: Laurent@814: self.Program += [(self.CurrentIndent + "IF ", var_info + (storage,))] + expression Laurent@814: self.Program += [(" THEN\n ", ())] Laurent@814: if storage == "set": Laurent@814: return [("TRUE; (*set*)\n" + self.CurrentIndent + "END_IF", ())] Laurent@814: else: Laurent@814: return [("FALSE; (*reset*)\n" + self.CurrentIndent + "END_IF", ())] Laurent@814: edge = variable.getedge() Laurent@814: if edge == "rising": Laurent@814: return self.AddTrigger("R_TRIG", expression, var_info + ("rising",)) Laurent@814: elif edge == "falling": Laurent@814: return self.AddTrigger("F_TRIG", expression, var_info + ("falling",)) Laurent@814: return expression Laurent@814: Laurent@814: def AddTrigger(self, edge, expression, var_info): Laurent@814: if self.Interface[-1][0] != "VAR" or self.Interface[-1][1] is not None or self.Interface[-1][2]: Laurent@814: self.Interface.append(("VAR", None, False, [])) Laurent@814: i = 1 Laurent@814: name = "%s%d"%(edge, i) Laurent@814: while self.IsAlreadyDefined(name): Laurent@814: i += 1 Laurent@814: name = "%s%d"%(edge, i) Laurent@814: self.Interface[-1][3].append((edge, name, None, None)) Laurent@814: self.Program += [(self.CurrentIndent, ()), (name, var_info), ("(CLK := ", ())] Laurent@814: self.Program += expression Laurent@814: self.Program += [(");\n", ())] Laurent@814: return [("%s.Q"%name, var_info)] Laurent@814: Laurent@814: def ExtractDivergenceInput(self, divergence, pou): Laurent@814: connectionPointIn = divergence.getconnectionPointIn() Laurent@814: if connectionPointIn: Laurent@814: connections = connectionPointIn.getconnections() Laurent@814: if connections is not None and len(connections) == 1: Laurent@814: instanceLocalId = connections[0].getrefLocalId() Laurent@814: body = pou.getbody() Laurent@814: if isinstance(body, ListType): Laurent@814: body = body[0] Laurent@814: return body.getcontentInstance(instanceLocalId) Laurent@814: return None Laurent@814: Laurent@814: def ExtractConvergenceInputs(self, convergence, pou): Laurent@814: instances = [] Laurent@814: for connectionPointIn in convergence.getconnectionPointIn(): Laurent@814: connections = connectionPointIn.getconnections() Laurent@814: if connections is not None and len(connections) == 1: Laurent@814: instanceLocalId = connections[0].getrefLocalId() Laurent@814: body = pou.getbody() Laurent@814: if isinstance(body, ListType): Laurent@814: body = body[0] Laurent@814: instances.append(body.getcontentInstance(instanceLocalId)) Laurent@814: return instances Laurent@814: Laurent@814: def GenerateSFCStep(self, step, pou): Laurent@814: step_name = step.getname() Laurent@814: if step_name not in self.SFCNetworks["Steps"].keys(): Laurent@814: if step.getinitialStep(): Laurent@814: self.InitialSteps.append(step_name) Laurent@814: step_infos = {"id" : step.getlocalId(), Laurent@814: "initial" : step.getinitialStep(), Laurent@814: "transitions" : [], Laurent@814: "actions" : []} Laurent@889: self.SFCNetworks["Steps"][step_name] = step_infos Laurent@814: if step.connectionPointIn: Laurent@814: instances = [] Laurent@814: connections = step.connectionPointIn.getconnections() Laurent@814: if connections is not None and len(connections) == 1: Laurent@814: instanceLocalId = connections[0].getrefLocalId() Laurent@814: body = pou.getbody() Laurent@814: if isinstance(body, ListType): Laurent@814: body = body[0] Laurent@814: instance = body.getcontentInstance(instanceLocalId) Laurent@814: if isinstance(instance, plcopen.sfcObjects_transition): Laurent@814: instances.append(instance) Laurent@814: elif isinstance(instance, plcopen.sfcObjects_selectionConvergence): Laurent@814: instances.extend(self.ExtractConvergenceInputs(instance, pou)) Laurent@814: elif isinstance(instance, plcopen.sfcObjects_simultaneousDivergence): Laurent@814: transition = self.ExtractDivergenceInput(instance, pou) Laurent@814: if transition: Laurent@814: if isinstance(transition, plcopen.sfcObjects_transition): Laurent@814: instances.append(transition) Laurent@814: elif isinstance(transition, plcopen.sfcObjects_selectionConvergence): Laurent@814: instances.extend(self.ExtractConvergenceInputs(transition, pou)) Laurent@814: for instance in instances: Laurent@814: self.GenerateSFCTransition(instance, pou) Laurent@814: if instance in self.SFCNetworks["Transitions"].keys(): Laurent@814: target_info = (self.TagName, "transition", instance.getlocalId(), "to", step_infos["id"]) Laurent@814: self.SFCNetworks["Transitions"][instance]["to"].append([(step_name, target_info)]) Laurent@814: Laurent@814: def GenerateSFCJump(self, jump, pou): Laurent@814: jump_target = jump.gettargetName() Laurent@814: if jump.connectionPointIn: Laurent@814: instances = [] Laurent@814: connections = jump.connectionPointIn.getconnections() Laurent@814: if connections is not None and len(connections) == 1: Laurent@814: instanceLocalId = connections[0].getrefLocalId() Laurent@814: body = pou.getbody() Laurent@814: if isinstance(body, ListType): Laurent@814: body = body[0] Laurent@814: instance = body.getcontentInstance(instanceLocalId) Laurent@814: if isinstance(instance, plcopen.sfcObjects_transition): Laurent@814: instances.append(instance) Laurent@814: elif isinstance(instance, plcopen.sfcObjects_selectionConvergence): Laurent@814: instances.extend(self.ExtractConvergenceInputs(instance, pou)) Laurent@814: elif isinstance(instance, plcopen.sfcObjects_simultaneousDivergence): Laurent@814: transition = self.ExtractDivergenceInput(instance, pou) Laurent@814: if transition: Laurent@814: if isinstance(transition, plcopen.sfcObjects_transition): Laurent@814: instances.append(transition) Laurent@814: elif isinstance(transition, plcopen.sfcObjects_selectionConvergence): Laurent@814: instances.extend(self.ExtractConvergenceInputs(transition, pou)) Laurent@814: for instance in instances: Laurent@814: self.GenerateSFCTransition(instance, pou) Laurent@814: if instance in self.SFCNetworks["Transitions"].keys(): Laurent@814: target_info = (self.TagName, "jump", jump.getlocalId(), "target") Laurent@814: self.SFCNetworks["Transitions"][instance]["to"].append([(jump_target, target_info)]) Laurent@814: Laurent@814: def GenerateSFCStepActions(self, actionBlock, pou): Laurent@814: connections = actionBlock.connectionPointIn.getconnections() Laurent@814: if connections is not None and len(connections) == 1: Laurent@814: stepLocalId = connections[0].getrefLocalId() Laurent@814: body = pou.getbody() Laurent@814: if isinstance(body, ListType): Laurent@814: body = body[0] Laurent@814: step = body.getcontentInstance(stepLocalId) Laurent@814: self.GenerateSFCStep(step, pou) Laurent@814: step_name = step.getname() Laurent@814: if step_name in self.SFCNetworks["Steps"].keys(): Laurent@814: actions = actionBlock.getactions() Laurent@814: for i, action in enumerate(actions): Laurent@814: action_infos = {"id" : actionBlock.getlocalId(), Laurent@814: "qualifier" : action["qualifier"], Laurent@814: "content" : action["value"], Laurent@814: "num" : i} Laurent@814: if "duration" in action: Laurent@814: action_infos["duration"] = action["duration"] Laurent@814: if "indicator" in action: Laurent@814: action_infos["indicator"] = action["indicator"] Laurent@814: if action["type"] == "reference": Laurent@814: self.GenerateSFCAction(action["value"], pou) Laurent@814: else: Laurent@814: action_name = "%s_INLINE%d"%(step_name.upper(), self.GetActionNumber()) Laurent@814: self.SFCNetworks["Actions"][action_name] = ([(self.CurrentIndent, ()), Laurent@814: (action["value"], (self.TagName, "action_block", action_infos["id"], "action", i, "inline")), Laurent@814: ("\n", ())], ()) Laurent@814: action_infos["content"] = action_name Laurent@814: self.SFCNetworks["Steps"][step_name]["actions"].append(action_infos) Laurent@814: Laurent@814: def GenerateSFCAction(self, action_name, pou): Laurent@814: if action_name not in self.SFCNetworks["Actions"].keys(): Laurent@814: actionContent = pou.getaction(action_name) Laurent@814: if actionContent: Laurent@814: previous_tagname = self.TagName Laurent@814: self.TagName = self.ParentGenerator.Controler.ComputePouActionName(self.Name, action_name) Laurent@814: self.ComputeProgram(actionContent) Laurent@814: self.SFCNetworks["Actions"][action_name] = (self.Program, (self.TagName, "name")) Laurent@814: self.Program = [] Laurent@814: self.TagName = previous_tagname Laurent@814: Laurent@814: def GenerateSFCTransition(self, transition, pou): Laurent@814: if transition not in self.SFCNetworks["Transitions"].keys(): Laurent@814: steps = [] Laurent@814: connections = transition.connectionPointIn.getconnections() Laurent@814: if connections is not None and len(connections) == 1: Laurent@814: instanceLocalId = connections[0].getrefLocalId() Laurent@814: body = pou.getbody() Laurent@814: if isinstance(body, ListType): Laurent@814: body = body[0] Laurent@814: instance = body.getcontentInstance(instanceLocalId) Laurent@814: if isinstance(instance, plcopen.sfcObjects_step): Laurent@814: steps.append(instance) Laurent@814: elif isinstance(instance, plcopen.sfcObjects_selectionDivergence): Laurent@814: step = self.ExtractDivergenceInput(instance, pou) Laurent@814: if step: Laurent@814: if isinstance(step, plcopen.sfcObjects_step): Laurent@814: steps.append(step) Laurent@814: elif isinstance(step, plcopen.sfcObjects_simultaneousConvergence): Laurent@814: steps.extend(self.ExtractConvergenceInputs(step, pou)) Laurent@814: elif isinstance(instance, plcopen.sfcObjects_simultaneousConvergence): Laurent@814: steps.extend(self.ExtractConvergenceInputs(instance, pou)) Laurent@814: transition_infos = {"id" : transition.getlocalId(), Laurent@814: "priority": transition.getpriority(), Laurent@814: "from": [], Laurent@814: "to" : []} Laurent@889: self.SFCNetworks["Transitions"][transition] = transition_infos Laurent@814: transitionValues = transition.getconditionContent() Laurent@814: if transitionValues["type"] == "inline": Laurent@814: transition_infos["content"] = [("\n%s:= "%self.CurrentIndent, ()), Laurent@814: (transitionValues["value"], (self.TagName, "transition", transition.getlocalId(), "inline")), Laurent@814: (";\n", ())] Laurent@814: elif transitionValues["type"] == "reference": Laurent@814: transitionContent = pou.gettransition(transitionValues["value"]) Laurent@814: transitionType = transitionContent.getbodyType() Laurent@814: transitionBody = transitionContent.getbody() Laurent@814: previous_tagname = self.TagName Laurent@814: self.TagName = self.ParentGenerator.Controler.ComputePouTransitionName(self.Name, transitionValues["value"]) Laurent@814: if transitionType == "IL": Laurent@814: transition_infos["content"] = [(":\n", ()), Laurent@814: (ReIndentText(transitionBody.gettext(), len(self.CurrentIndent)), (self.TagName, "body", len(self.CurrentIndent)))] Laurent@814: elif transitionType == "ST": Laurent@814: transition_infos["content"] = [("\n", ()), Laurent@814: (ReIndentText(transitionBody.gettext(), len(self.CurrentIndent)), (self.TagName, "body", len(self.CurrentIndent)))] Laurent@814: else: Laurent@814: for instance in transitionBody.getcontentInstances(): Laurent@814: if isinstance(instance, plcopen.fbdObjects_outVariable) and instance.getexpression() == transitionValues["value"]\ Laurent@814: or isinstance(instance, plcopen.ldObjects_coil) and instance.getvariable() == transitionValues["value"]: Laurent@814: connections = instance.connectionPointIn.getconnections() Laurent@814: if connections is not None: Laurent@814: expression = self.ComputeExpression(transitionBody, connections) Laurent@814: transition_infos["content"] = [("\n%s:= "%self.CurrentIndent, ())] + expression + [(";\n", ())] Laurent@814: self.SFCComputedBlocks += self.Program Laurent@814: self.Program = [] Laurent@814: if not transition_infos.has_key("content"): Laurent@814: raise PLCGenException, _("Transition \"%s\" body must contain an output variable or coil referring to its name") % transitionValues["value"] Laurent@814: self.TagName = previous_tagname Laurent@814: elif transitionValues["type"] == "connection": Laurent@814: body = pou.getbody() Laurent@814: if isinstance(body, ListType): Laurent@814: body = body[0] Laurent@814: connections = transition.getconnections() Laurent@814: if connections is not None: Laurent@814: expression = self.ComputeExpression(body, connections) Laurent@814: transition_infos["content"] = [("\n%s:= "%self.CurrentIndent, ())] + expression + [(";\n", ())] Laurent@814: self.SFCComputedBlocks += self.Program Laurent@814: self.Program = [] Laurent@814: for step in steps: Laurent@814: self.GenerateSFCStep(step, pou) Laurent@814: step_name = step.getname() Laurent@814: if step_name in self.SFCNetworks["Steps"].keys(): Laurent@814: transition_infos["from"].append([(step_name, (self.TagName, "transition", transition.getlocalId(), "from", step.getlocalId()))]) Laurent@814: self.SFCNetworks["Steps"][step_name]["transitions"].append(transition) Laurent@814: Laurent@814: def ComputeSFCStep(self, step_name): Laurent@814: if step_name in self.SFCNetworks["Steps"].keys(): Laurent@814: step_infos = self.SFCNetworks["Steps"].pop(step_name) Laurent@814: self.Program += [(self.CurrentIndent, ())] Laurent@814: if step_infos["initial"]: Laurent@814: self.Program += [("INITIAL_", ())] Laurent@814: self.Program += [("STEP ", ()), Laurent@814: (step_name, (self.TagName, "step", step_infos["id"], "name")), Laurent@814: (":\n", ())] Laurent@814: actions = [] Laurent@814: self.IndentRight() Laurent@814: for action_infos in step_infos["actions"]: Laurent@814: if action_infos.get("id", None) is not None: Laurent@814: action_info = (self.TagName, "action_block", action_infos["id"], "action", action_infos["num"]) Laurent@814: else: Laurent@814: action_info = () Laurent@814: actions.append(action_infos["content"]) Laurent@814: self.Program += [(self.CurrentIndent, ()), Laurent@814: (action_infos["content"], action_info + ("reference",)), Laurent@814: ("(", ()), Laurent@814: (action_infos["qualifier"], action_info + ("qualifier",))] Laurent@814: if "duration" in action_infos: Laurent@814: self.Program += [(", ", ()), Laurent@814: (action_infos["duration"], action_info + ("duration",))] Laurent@814: if "indicator" in action_infos: Laurent@814: self.Program += [(", ", ()), Laurent@814: (action_infos["indicator"], action_info + ("indicator",))] Laurent@814: self.Program += [(");\n", ())] Laurent@814: self.IndentLeft() Laurent@814: self.Program += [("%sEND_STEP\n\n"%self.CurrentIndent, ())] Laurent@814: for action in actions: Laurent@814: self.ComputeSFCAction(action) Laurent@814: for transition in step_infos["transitions"]: Laurent@814: self.ComputeSFCTransition(transition) Laurent@814: Laurent@814: def ComputeSFCAction(self, action_name): Laurent@814: if action_name in self.SFCNetworks["Actions"].keys(): Laurent@814: action_content, action_info = self.SFCNetworks["Actions"].pop(action_name) Laurent@814: self.Program += [("%sACTION "%self.CurrentIndent, ()), Laurent@814: (action_name, action_info), Laurent@814: (" :\n", ())] Laurent@814: self.Program += action_content Laurent@814: self.Program += [("%sEND_ACTION\n\n"%self.CurrentIndent, ())] Laurent@814: Laurent@814: def ComputeSFCTransition(self, transition): Laurent@814: if transition in self.SFCNetworks["Transitions"].keys(): Laurent@814: transition_infos = self.SFCNetworks["Transitions"].pop(transition) Laurent@814: self.Program += [("%sTRANSITION"%self.CurrentIndent, ())] Laurent@814: if transition_infos["priority"] != None: Laurent@814: self.Program += [(" (PRIORITY := ", ()), Laurent@814: ("%d"%transition_infos["priority"], (self.TagName, "transition", transition_infos["id"], "priority")), Laurent@814: (")", ())] Laurent@814: self.Program += [(" FROM ", ())] Laurent@814: if len(transition_infos["from"]) > 1: Laurent@814: self.Program += [("(", ())] Laurent@814: self.Program += JoinList([(", ", ())], transition_infos["from"]) Laurent@814: self.Program += [(")", ())] Laurent@814: elif len(transition_infos["from"]) == 1: Laurent@814: self.Program += transition_infos["from"][0] Laurent@814: else: Laurent@814: raise PLCGenException, _("Transition with content \"%s\" not connected to a previous step in \"%s\" POU")%(transition_infos["content"], self.Name) Laurent@814: self.Program += [(" TO ", ())] Laurent@814: if len(transition_infos["to"]) > 1: Laurent@814: self.Program += [("(", ())] Laurent@814: self.Program += JoinList([(", ", ())], transition_infos["to"]) Laurent@814: self.Program += [(")", ())] Laurent@814: elif len(transition_infos["to"]) == 1: Laurent@814: self.Program += transition_infos["to"][0] Laurent@814: else: Laurent@814: raise PLCGenException, _("Transition with content \"%s\" not connected to a next step in \"%s\" POU")%(transition_infos["content"], self.Name) Laurent@814: self.Program += transition_infos["content"] Laurent@814: self.Program += [("%sEND_TRANSITION\n\n"%self.CurrentIndent, ())] Laurent@814: for [(step_name, step_infos)] in transition_infos["to"]: Laurent@814: self.ComputeSFCStep(step_name) Laurent@814: Laurent@814: def GenerateProgram(self, pou): Laurent@814: self.ComputeInterface(pou) Laurent@814: self.ComputeConnectionTypes(pou) Laurent@814: self.ComputeProgram(pou) Laurent@814: Laurent@814: program = [("%s "%self.Type, ()), Laurent@814: (self.Name, (self.TagName, "name"))] Laurent@814: if self.ReturnType: Laurent@814: program += [(" : ", ()), Laurent@814: (self.ReturnType, (self.TagName, "return"))] Laurent@814: program += [("\n", ())] Laurent@814: if len(self.Interface) == 0: Laurent@814: raise PLCGenException, _("No variable defined in \"%s\" POU")%self.Name Laurent@814: if len(self.Program) == 0 : Laurent@814: raise PLCGenException, _("No body defined in \"%s\" POU")%self.Name Laurent@814: var_number = 0 Laurent@814: for list_type, option, located, variables in self.Interface: Laurent@814: variable_type = errorVarTypes.get(list_type, "var_local") Laurent@814: program += [(" %s"%list_type, ())] Laurent@814: if option is not None: Laurent@814: program += [(" %s"%option, (self.TagName, variable_type, (var_number, var_number + len(variables)), option.lower()))] Laurent@814: program += [("\n", ())] Laurent@814: for var_type, var_name, var_address, var_initial in variables: Laurent@814: program += [(" ", ())] Laurent@814: if var_name: Laurent@814: program += [(var_name, (self.TagName, variable_type, var_number, "name")), Laurent@814: (" ", ())] Laurent@814: if var_address != None: Laurent@814: program += [("AT ", ()), Laurent@814: (var_address, (self.TagName, variable_type, var_number, "location")), Laurent@814: (" ", ())] Laurent@814: program += [(": ", ()), Laurent@814: (var_type, (self.TagName, variable_type, var_number, "type"))] Laurent@814: if var_initial != None: Laurent@814: program += [(" := ", ()), Laurent@814: (self.ParentGenerator.ComputeValue(var_initial, var_type), (self.TagName, variable_type, var_number, "initial value"))] Laurent@814: program += [(";\n", ())] Laurent@814: var_number += 1 Laurent@814: program += [(" END_VAR\n", ())] Laurent@814: program += [("\n", ())] Laurent@814: program += self.Program Laurent@814: program += [("END_%s\n\n"%self.Type, ())] Laurent@814: return program Laurent@814: Laurent@814: def GenerateCurrentProgram(controler, project, errors, warnings): Laurent@814: generator = ProgramGenerator(controler, project, errors, warnings) Laurent@814: generator.GenerateProgram() Laurent@814: return generator.GetGeneratedProgram() Laurent@814: