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