Laurent@814: #!/usr/bin/env python Laurent@814: # -*- coding: utf-8 -*- Laurent@814: andrej@1571: # This file is part of Beremiz, a Integrated Development Environment for andrej@1571: # programming IEC 61131-3 automates supporting plcopen standard and CanFestival. Laurent@814: # andrej@1571: # Copyright (C) 2007: Edouard TISSERANT and Laurent BESSARD Laurent@814: # andrej@1571: # See COPYING file for copyrights details. Laurent@814: # andrej@1571: # This program is free software; you can redistribute it and/or andrej@1571: # modify it under the terms of the GNU General Public License andrej@1571: # as published by the Free Software Foundation; either version 2 andrej@1571: # of the License, or (at your option) any later version. Laurent@814: # andrej@1571: # This program is distributed in the hope that it will be useful, andrej@1571: # but WITHOUT ANY WARRANTY; without even the implied warranty of andrej@1571: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the andrej@1571: # GNU General Public License for more details. Laurent@814: # andrej@1571: # You should have received a copy of the GNU General Public License andrej@1571: # along with this program; if not, write to the Free Software andrej@1571: # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. Laurent@814: andrej@1832: andrej@1881: from __future__ import absolute_import andrej@1832: import re andrej@2456: from functools import reduce andrej@2432: from six.moves import xrange andrej@2432: Laurent@1297: from plcopen import PLCOpenParser Laurent@814: from plcopen.structures import * Edouard@1948: from plcopen.types_enums import * andrej@1832: Laurent@814: Edouard@1418: # Dictionary associating PLCOpen variable categories to the corresponding Laurent@814: # IEC 61131-3 variable categories andrej@1739: varTypeNames = {"localVars": "VAR", "tempVars": "VAR_TEMP", "inputVars": "VAR_INPUT", andrej@1739: "outputVars": "VAR_OUTPUT", "inOutVars": "VAR_IN_OUT", "externalVars": "VAR_EXTERNAL", andrej@1739: "globalVars": "VAR_GLOBAL", "accessVars": "VAR_ACCESS"} Laurent@814: Laurent@814: Edouard@1418: # Dictionary associating PLCOpen POU categories to the corresponding Laurent@814: # IEC 61131-3 POU categories andrej@1739: 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: andrej@1736: Laurent@814: def ReIndentText(text, nb_spaces): andrej@1736: """ Helper function for reindenting text """ 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 = "" andrej@1847: for dummy in xrange(spaces, nb_spaces): Laurent@814: indent += " " Laurent@814: for line in lines: Laurent@814: if line != "": andrej@1734: compute += "%s%s\n" % (indent, line) Laurent@814: else: Laurent@814: compute += "\n" Laurent@814: return compute Laurent@814: andrej@1736: 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: andrej@1736: Laurent@1310: def JoinList(separator, mylist): andrej@1736: """ Helper for emulate join on element list """ andrej@1739: if len(mylist) > 0: Laurent@1310: return reduce(lambda x, y: x + separator + y, mylist) andrej@1739: else: Laurent@1310: return mylist Laurent@1310: andrej@1782: # ------------------------------------------------------------------------------- Laurent@814: # Specific exception for PLC generating errors andrej@1782: # ------------------------------------------------------------------------------- Laurent@814: Laurent@814: Laurent@814: class PLCGenException(Exception): Laurent@814: pass Laurent@814: Laurent@814: andrej@1782: # ------------------------------------------------------------------------------- Laurent@814: # Generator of PLC program andrej@1782: # ------------------------------------------------------------------------------- Laurent@814: Laurent@814: andrej@1831: class ProgramGenerator(object): 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("'"): andrej@1734: return "'%s'" % value Laurent@1032: elif base_type == "WSTRING" and not value.startswith('"') and not value.endswith('"'): andrej@1734: 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 Edouard@1418: Laurent@814: # Getting datatype model from project Laurent@814: datatype = self.Project.getdataType(datatype_name) Edouard@1948: tagname = ComputeDataTypeName(datatype.getname()) Edouard@1418: datatype_def = [(" ", ()), Laurent@814: (datatype.getname(), (tagname, "name")), Laurent@814: (" : ", ())] Laurent@814: basetype_content = datatype.baseType.getcontent() Laurent@1297: basetype_content_type = basetype_content.getLocalTag() Edouard@1418: # Data type derived directly from a user defined type Laurent@1297: if basetype_content_type == "derived": Laurent@1297: basetype_name = basetype_content.getname() Laurent@814: self.GenerateDataType(basetype_name) Laurent@814: datatype_def += [(basetype_name, (tagname, "base"))] Laurent@814: # Data type is a subrange Laurent@1297: elif basetype_content_type in ["subrangeSigned", "subrangeUnsigned"]: Laurent@1297: base_type = basetype_content.baseType.getcontent() Laurent@1297: base_type_type = base_type.getLocalTag() Edouard@1418: # Subrange derived directly from a user defined type Laurent@1297: if base_type_type == "derived": Laurent@1297: basetype_name = base_type_type.getname() Laurent@814: self.GenerateDataType(basetype_name) Edouard@1418: # Subrange derived directly from an elementary type Laurent@814: else: Laurent@1297: basetype_name = base_type_type Laurent@1297: min_value = basetype_content.range.getlower() Laurent@1297: max_value = basetype_content.range.getupper() Laurent@814: datatype_def += [(basetype_name, (tagname, "base")), Laurent@814: (" (", ()), andrej@1734: ("%s" % min_value, (tagname, "lower")), Laurent@814: ("..", ()), andrej@1734: ("%s" % max_value, (tagname, "upper")), andrej@1740: (")", ())] Laurent@814: # Data type is an enumerated type Laurent@1297: elif basetype_content_type == "enum": Laurent@814: values = [[(value.getname(), (tagname, "value", i))] Laurent@1297: for i, value in enumerate( Edouard@1418: basetype_content.xpath("ppx:values/ppx:value", andrej@1768: namespaces=PLCOpenParser.NSMAP))] Laurent@814: datatype_def += [("(", ())] Laurent@814: datatype_def += JoinList([(", ", ())], values) Laurent@814: datatype_def += [(")", ())] Laurent@814: # Data type is an array Laurent@1297: elif basetype_content_type == "array": Laurent@1297: base_type = basetype_content.baseType.getcontent() Laurent@1297: base_type_type = base_type.getLocalTag() Edouard@1418: # Array derived directly from a user defined type Laurent@1297: if base_type_type == "derived": Laurent@1297: basetype_name = base_type.getname() Laurent@814: self.GenerateDataType(basetype_name) Edouard@1418: # Array derived directly from an elementary type Laurent@814: else: Laurent@1297: basetype_name = base_type_type.upper() andrej@1734: dimensions = [[("%s" % dimension.getlower(), (tagname, "range", i, "lower")), Laurent@814: ("..", ()), andrej@1734: ("%s" % dimension.getupper(), (tagname, "range", i, "upper"))] Laurent@1297: for i, dimension in enumerate(basetype_content.getdimension())] Laurent@814: datatype_def += [("ARRAY [", ())] Laurent@814: datatype_def += JoinList([(",", ())], dimensions) andrej@1739: datatype_def += [("] OF ", ()), Laurent@814: (basetype_name, (tagname, "base"))] Laurent@814: # Data type is a structure Laurent@1297: elif basetype_content_type == "struct": Laurent@814: elements = [] Laurent@1297: for i, element in enumerate(basetype_content.getvariable()): Laurent@814: element_type = element.type.getcontent() Laurent@1297: element_type_type = element_type.getLocalTag() Edouard@1418: # Structure element derived directly from a user defined type Laurent@1297: if element_type_type == "derived": Laurent@1297: elementtype_name = element_type.getname() Laurent@814: self.GenerateDataType(elementtype_name) Laurent@1297: elif element_type_type == "array": Laurent@1297: base_type = element_type.baseType.getcontent() Laurent@1297: base_type_type = base_type.getLocalTag() Edouard@1418: # Array derived directly from a user defined type Laurent@1297: if base_type_type == "derived": Laurent@1297: basetype_name = base_type.getname() Laurent@864: self.GenerateDataType(basetype_name) Edouard@1418: # Array derived directly from an elementary type Laurent@864: else: Laurent@1297: basetype_name = base_type_type.upper() Laurent@864: dimensions = ["%s..%s" % (dimension.getlower(), dimension.getupper()) Laurent@1297: for dimension in element_type.getdimension()] Laurent@864: elementtype_name = "ARRAY [%s] OF %s" % (",".join(dimensions), basetype_name) Edouard@1418: # Structure element derived directly from an elementary type Laurent@814: else: Laurent@1297: elementtype_name = element_type_type.upper() 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", ())] Edouard@1418: # Data type derived directly from a elementary type Laurent@814: else: Laurent@1297: datatype_def += [(basetype_content_type.upper(), (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 Edouard@1418: 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 andrej@1763: if pou_type in pouTypeNames: 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: andrej@1765: raise PLCGenException(_("Undefined pou type \"%s\"") % pou_type) Edouard@1418: 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(): andrej@1734: 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) Edouard@1418: Laurent@814: # Generate a configuration from its model Laurent@814: def GenerateConfiguration(self, configuration): Edouard@1948: tagname = ComputeConfigurationName(configuration.getname()) Laurent@814: config = [("\nCONFIGURATION ", ()), Laurent@814: (configuration.getname(), (tagname, "name")), Laurent@814: ("\n", ())] Laurent@814: var_number = 0 Edouard@1418: Laurent@883: varlists = [(varlist, varlist.getvariable()[:]) for varlist in configuration.getglobalVars()] Edouard@1418: Laurent@883: extra_variables = self.Controler.GetConfigurationExtraVariables() Laurent@1315: extra_global_vars = None Laurent@1315: if len(extra_variables) > 0 and len(varlists) == 0: Laurent@1315: extra_global_vars = PLCOpenParser.CreateElement("globalVars", "interface") Laurent@1315: configuration.setglobalVars([extra_global_vars]) Laurent@1315: varlists = [(extra_global_vars, [])] Edouard@1418: Laurent@1315: for variable in extra_variables: Laurent@1315: varlists[-1][0].appendvariable(variable) Laurent@1315: varlists[-1][1].append(variable) Edouard@1418: 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@1297: if vartype_content.getLocalTag() == "derived": Laurent@1297: var_type = vartype_content.getname() Laurent@814: self.GenerateDataType(var_type) Laurent@814: else: Laurent@814: var_type = var.gettypeAsText() Edouard@1418: 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@1315: if initial is not None: 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", ())] Edouard@1418: Laurent@1315: if extra_global_vars is not None: Laurent@1315: configuration.remove(extra_global_vars) Laurent@1315: else: Laurent@1315: for variable in extra_variables: Laurent@1358: varlists[-1][0].remove(variable) Edouard@1418: 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 Edouard@1418: Laurent@814: # Generate a resource from its model Laurent@814: def GenerateResource(self, resource, config_name): Edouard@1948: tagname = 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@1297: if vartype_content.getLocalTag() == "derived": Laurent@1297: var_type = vartype_content.getname() Laurent@814: self.GenerateDataType(var_type) Laurent@814: else: Laurent@814: var_type = var.gettypeAsText() Edouard@1418: 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@1315: if initial is not None: 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: single = task.getsingle() Laurent@814: # Single argument if exists Laurent@1315: if single is not None: andrej@1614: if len(single) == 0: andrej@1765: raise PLCGenException( andrej@1765: _("Source signal has to be defined for single task '{a1}' in resource '{a2}.{a3}'."). andrej@1765: format(a1=task.getname(), a2=config_name, a3=resource.getname())) andrej@1614: andrej@1742: if single[0] == '[' and single[-1] == ']': Edouard@1420: SNGLKW = "MULTI" Edouard@1420: else: Edouard@1420: SNGLKW = "SINGLE" Edouard@1420: resrce += [(SNGLKW + " := ", ()), Laurent@814: (single, (tagname, "task", task_number, "single")), Laurent@814: (",", ())] Laurent@814: # Interval argument if exists Laurent@814: interval = task.getinterval() Laurent@1315: if interval is not None: Laurent@814: resrce += [("INTERVAL := ", ()), Laurent@814: (interval, (tagname, "task", task_number, "interval")), Laurent@814: (",", ())] andrej@1753: # resrce += [("INTERVAL := t#", ())] andrej@1753: # if interval.hour != 0: andrej@1753: # resrce += [("%dh"%interval.hour, (tagname, "task", task_number, "interval", "hour"))] andrej@1753: # if interval.minute != 0: andrej@1753: # resrce += [("%dm"%interval.minute, (tagname, "task", task_number, "interval", "minute"))] andrej@1753: # if interval.second != 0: andrej@1753: # resrce += [("%ds"%interval.second, (tagname, "task", task_number, "interval", "second"))] andrej@1753: # if interval.microsecond != 0: andrej@1753: # resrce += [("%dms"%(interval.microsecond / 1000), (tagname, "task", task_number, "interval", "millisecond"))] andrej@1753: # resrce += [(",", ())] Laurent@814: # Priority argument Edouard@1418: resrce += [("PRIORITY := ", ()), andrej@1734: ("%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 ", ()), andrej@1767: (instance.getname(), (tagname, "instance", instance_number, "name")), andrej@1767: (" : ", ()), andrej@1767: (instance.gettypeName(), (tagname, "instance", instance_number, "type")), andrej@1767: (";\n", ())] Laurent@814: instance_number += 1 Laurent@814: resrce += [(" END_RESOURCE\n", ())] Laurent@814: return resrce Edouard@1418: Laurent@814: # Generate the entire program for current project Edouard@1418: 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 Edouard@1418: # 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) Edouard@1418: Laurent@814: # Return generated program Laurent@814: def GetGeneratedProgram(self): Laurent@814: return self.Program Laurent@814: Laurent@814: andrej@1782: # ------------------------------------------------------------------------------- Laurent@814: # Generator of POU programs andrej@1782: # ------------------------------------------------------------------------------- Laurent@814: Laurent@1297: [ConnectorClass, ContinuationClass, ActionBlockClass] = [ Laurent@1297: PLCOpenParser.GetElementClass(instance_name, "commonObjects") Laurent@1297: for instance_name in ["connector", "continuation", "actionBlock"]] Laurent@1297: [InVariableClass, InOutVariableClass, OutVariableClass, BlockClass] = [ Laurent@1297: PLCOpenParser.GetElementClass(instance_name, "fbdObjects") Laurent@1297: for instance_name in ["inVariable", "inOutVariable", "outVariable", "block"]] Laurent@1297: [ContactClass, CoilClass, LeftPowerRailClass, RightPowerRailClass] = [ Laurent@1297: PLCOpenParser.GetElementClass(instance_name, "ldObjects") Laurent@1297: for instance_name in ["contact", "coil", "leftPowerRail", "rightPowerRail"]] Edouard@1418: [StepClass, TransitionClass, JumpStepClass, Laurent@1297: SelectionConvergenceClass, SelectionDivergenceClass, Laurent@1297: SimultaneousConvergenceClass, SimultaneousDivergenceClass] = [ andrej@1878: PLCOpenParser.GetElementClass(instance_name, "sfcObjects") andrej@1878: for instance_name in ["step", andrej@1878: "transition", andrej@1878: "jumpStep", andrej@1878: "selectionConvergence", andrej@1878: "selectionDivergence", andrej@1878: "simultaneousConvergence", andrej@1878: "simultaneousDivergence"]] Laurent@1297: TransitionObjClass = PLCOpenParser.GetElementClass("transition", "transitions") Laurent@1297: ActionObjClass = PLCOpenParser.GetElementClass("action", "actions") Laurent@814: andrej@1736: andrej@1831: class PouProgramGenerator(object): Edouard@1418: 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 Edouard@1948: self.TagName = 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 = [] andrej@1740: 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 Edouard@1418: Laurent@814: def GetBlockType(self, type, inputs=None): Laurent@814: return self.ParentGenerator.Controler.GetBlockType(type, inputs) Edouard@1418: Laurent@814: def IndentLeft(self): Laurent@814: if len(self.CurrentIndent) >= 2: Laurent@814: self.CurrentIndent = self.CurrentIndent[:-2] Edouard@1418: Laurent@814: def IndentRight(self): Laurent@814: self.CurrentIndent += " " Edouard@1418: Laurent@814: # Generator of unique ID for inline actions Laurent@814: def GetActionNumber(self): Laurent@814: self.ActionNumber += 1 Laurent@814: return self.ActionNumber Edouard@1418: Laurent@814: # Test if a variable has already been defined Laurent@814: def IsAlreadyDefined(self, name): andrej@1847: for _list_type, _option, _located, vars in self.Interface: andrej@1847: 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 Edouard@1418: 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) andrej@1847: for _list_type, _option, _located, vars in self.Interface: andrej@1847: 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 andrej@1847: 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: Edouard@1948: tagname = 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 Edouard@1418: 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@1298: if links is not None and len(links) == 1: Laurent@814: return self.GetLinkedConnector(links[0], body) Edouard@1418: return None Laurent@814: Laurent@814: def GetLinkedConnector(self, link, body): Laurent@814: parameter = link.getformalParameter() Laurent@814: instance = body.getcontentInstance(link.getrefLocalId()) Edouard@1418: if isinstance(instance, (InVariableClass, InOutVariableClass, andrej@1768: ContinuationClass, ContactClass, CoilClass)): Laurent@814: return instance.connectionPointOut Laurent@1297: elif isinstance(instance, BlockClass): 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@1297: elif isinstance(instance, LeftPowerRailClass): 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 Edouard@1418: 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] Edouard@1418: Laurent@814: def ComputeInterface(self, pou): Laurent@814: interface = pou.getinterface() Laurent@814: if interface is not None: Laurent@814: if self.Type == "FUNCTION": Edouard@1418: returntype_content = interface.getreturnType()[0] Laurent@1297: returntype_content_type = returntype_content.getLocalTag() Laurent@1297: if returntype_content_type == "derived": Laurent@1297: self.ReturnType = returntype_content.getname() Laurent@1297: else: Laurent@1297: self.ReturnType = returntype_content_type.upper() Laurent@814: for varlist in interface.getcontent(): Laurent@814: variables = [] Laurent@814: located = [] Laurent@1297: varlist_type = varlist.getLocalTag() Laurent@1297: for var in varlist.getvariable(): Laurent@814: vartype_content = var.gettype().getcontent() Laurent@1297: if vartype_content.getLocalTag() == "derived": Laurent@1297: var_type = vartype_content.getname() Laurent@814: blocktype = self.GetBlockType(var_type) Laurent@814: if blocktype is not None: Laurent@814: self.ParentGenerator.GeneratePouProgram(var_type) Laurent@1310: variables.append((var_type, var.getname(), None, None)) Laurent@814: else: Laurent@814: self.ParentGenerator.GenerateDataType(var_type) Laurent@814: initial = var.getinitialValue() Laurent@1310: if initial is not None: 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@1297: located.append((vartype_content.getname(), var.getname(), address, initial_value)) Laurent@814: else: Laurent@1297: variables.append((vartype_content.getname(), var.getname(), None, initial_value)) Laurent@814: else: Laurent@814: var_type = var.gettypeAsText() Laurent@814: initial = var.getinitialValue() Laurent@1310: if initial is not None: 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@1297: if varlist.getconstant(): Laurent@814: option = "CONSTANT" Laurent@1297: elif varlist.getretain(): Laurent@814: option = "RETAIN" Laurent@1297: elif varlist.getnonretain(): Laurent@814: option = "NON_RETAIN" Laurent@814: else: Laurent@814: option = None Laurent@814: if len(variables) > 0: Laurent@1297: self.Interface.append((varTypeNames[varlist_type], option, False, variables)) Laurent@814: if len(located) > 0: Laurent@1297: self.Interface.append((varTypeNames[varlist_type], option, True, located)) Edouard@1418: Laurent@1181: LITERAL_TYPES = { andrej@1751: "T": "TIME", andrej@1751: "D": "DATE", Laurent@1181: "TOD": "TIME_OF_DAY", andrej@1751: "DT": "DATE_AND_TIME", andrej@1751: "2": None, andrej@1751: "8": None, andrej@1751: "16": None, Laurent@1181: } andrej@1751: Laurent@814: def ComputeConnectionTypes(self, pou): Laurent@814: body = pou.getbody() andrej@2450: if isinstance(body, list): Laurent@814: body = body[0] Laurent@814: body_content = body.getcontent() Laurent@1297: body_type = body_content.getLocalTag() Laurent@814: if body_type in ["FBD", "LD", "SFC"]: Laurent@814: undefined_blocks = [] Laurent@814: for instance in body.getcontentInstances(): Edouard@1418: if isinstance(instance, (InVariableClass, OutVariableClass, Laurent@1297: InOutVariableClass)): Laurent@1322: expression = instance.getexpression() Laurent@814: var_type = self.GetVariableType(expression) andrej@1766: if isinstance(pou, TransitionObjClass) and expression == pou.getname(): laurent@822: var_type = "BOOL" Laurent@1297: elif (not isinstance(pou, (TransitionObjClass, ActionObjClass)) and laurent@822: pou.getpouType() == "function" and expression == pou.getname()): Laurent@814: returntype_content = pou.interface.getreturnType().getcontent() Laurent@1297: returntype_content_type = returntype_content.getLocalTag() Laurent@1297: if returntype_content_type == "derived": Laurent@1297: var_type = returntype_content.getname() Laurent@814: else: Laurent@1297: var_type = returntype_content_type.upper() Laurent@814: elif var_type is None: Laurent@814: parts = expression.split("#") Laurent@814: if len(parts) > 1: Laurent@1181: literal_prefix = parts[0].upper() Edouard@1418: var_type = self.LITERAL_TYPES.get(literal_prefix, Laurent@1181: literal_prefix) 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@1297: if isinstance(instance, (InVariableClass, InOutVariableClass)): Laurent@814: for connection in self.ExtractRelatedConnections(instance.connectionPointOut): Laurent@814: self.ConnectionTypes[connection] = var_type Laurent@1297: if isinstance(instance, (OutVariableClass, InOutVariableClass)): Laurent@814: self.ConnectionTypes[instance.connectionPointIn] = var_type Laurent@814: connected = self.GetConnectedConnector(instance.connectionPointIn, body) andrej@1775: if connected is not None and connected not in self.ConnectionTypes: Laurent@1298: for related in self.ExtractRelatedConnections(connected): Laurent@1298: self.ConnectionTypes[related] = var_type Laurent@1297: elif isinstance(instance, (ContactClass, CoilClass)): Laurent@814: for connection in self.ExtractRelatedConnections(instance.connectionPointOut): Laurent@814: self.ConnectionTypes[connection] = "BOOL" Laurent@814: self.ConnectionTypes[instance.connectionPointIn] = "BOOL" Laurent@1298: for link in instance.connectionPointIn.getconnections(): Laurent@1298: connected = self.GetLinkedConnector(link, body) andrej@1775: if connected is not None and connected not in self.ConnectionTypes: Laurent@1298: for related in self.ExtractRelatedConnections(connected): Laurent@1298: self.ConnectionTypes[related] = "BOOL" Laurent@1297: elif isinstance(instance, LeftPowerRailClass): Laurent@814: for connection in instance.getconnectionPointOut(): Laurent@814: for related in self.ExtractRelatedConnections(connection): Laurent@814: self.ConnectionTypes[related] = "BOOL" Laurent@1297: elif isinstance(instance, RightPowerRailClass): Laurent@814: for connection in instance.getconnectionPointIn(): Laurent@814: self.ConnectionTypes[connection] = "BOOL" Laurent@1298: for link in connection.getconnections(): Laurent@1298: connected = self.GetLinkedConnector(link, body) andrej@1775: if connected is not None and connected not in self.ConnectionTypes: Laurent@1298: for related in self.ExtractRelatedConnections(connected): Laurent@1298: self.ConnectionTypes[related] = "BOOL" Laurent@1297: elif isinstance(instance, TransitionClass): Laurent@1297: content = instance.getconditionContent() Laurent@1297: if content["type"] == "connection": Laurent@1298: self.ConnectionTypes[content["value"]] = "BOOL" andrej@1603: connections = content["value"].getconnections() andrej@1603: if not connections: andrej@1765: raise PLCGenException( andrej@1765: _("SFC transition in POU \"%s\" must be connected.") % self.Name) andrej@1765: andrej@1730: for link in connections: Laurent@1298: connected = self.GetLinkedConnector(link, body) andrej@1775: if connected is not None and connected not in self.ConnectionTypes: Laurent@1298: for related in self.ExtractRelatedConnections(connected): Laurent@1298: self.ConnectionTypes[related] = "BOOL" Laurent@1297: elif isinstance(instance, ContinuationClass): Laurent@814: name = instance.getname() Laurent@814: connector = None Laurent@814: var_type = "ANY" Laurent@814: for element in body.getcontentInstances(): Laurent@1297: if isinstance(element, ConnectorClass) and element.getname() == name: Laurent@814: if connector is not None: andrej@1765: raise PLCGenException( andrej@1765: _("More than one connector found corresponding to \"{a1}\" continuation in \"{a2}\" POU"). andrej@1765: format(a1=name, a2=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@1298: if connected is not None: Laurent@814: undefined.append(connected) Laurent@814: related = [] Laurent@814: for connection in undefined: andrej@1763: if connection in self.ConnectionTypes: 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: andrej@1765: raise PLCGenException( andrej@1765: _("No connector found corresponding to \"{a1}\" continuation in \"{a2}\" POU"). andrej@1765: format(a1=name, a2=self.Name)) andrej@1765: Laurent@1297: elif isinstance(instance, BlockClass): 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: andrej@1765: raise PLCGenException( andrej@1765: _("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(): Edouard@1948: self.TagName = ComputePouActionName(self.Name, action.getname()) laurent@822: self.ComputeConnectionTypes(action) laurent@822: for transition in pou.gettransitionList(): Edouard@1948: self.TagName = ComputePouTransitionName(self.Name, transition.getname()) laurent@822: self.ComputeConnectionTypes(transition) laurent@822: self.TagName = previous_tagname Edouard@1418: 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: andrej@1847: for oname, otype, _oqualifier in block_infos["outputs"]: Laurent@814: if output_name == oname: Laurent@814: if otype.startswith("ANY"): andrej@1775: if otype not in undefined: Laurent@814: undefined[otype] = [] Laurent@814: undefined[otype].append(variable.connectionPointOut) andrej@1775: elif variable.connectionPointOut not in self.ConnectionTypes: 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: andrej@1847: 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"): andrej@1775: if itype not in undefined: Laurent@814: undefined[itype] = [] Laurent@814: undefined[itype].append(variable.connectionPointIn) Laurent@1298: if connected is not None: Laurent@814: undefined[itype].append(connected) Laurent@814: else: Laurent@814: self.ConnectionTypes[variable.connectionPointIn] = itype andrej@1775: if connected is not None and connected not in self.ConnectionTypes: 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: andrej@2258: def GetUsedEno(self, body, connections): andrej@2258: """ andrej@2258: Function checks whether value on given connection andrej@2258: comes from block, that has used EN input and andrej@2258: returns variable name for ENO output. andrej@2258: andrej@2258: This is needed to avoid value propagation from blocks andrej@2258: with false signal on EN input. andrej@2258: andrej@2258: :param body: andrej@2258: body of the block for that program is currently generated andrej@2258: :param connections: andrej@2258: connection, that's source is checked for EN/ENO usage andrej@2258: :return: andrej@2258: if EN/ENO are not used, then None is returned andrej@2258: Otherwise BOOL variable corresponding to ENO andrej@2258: output is returned. andrej@2258: """ andrej@2258: andrej@2258: if len(connections) != 1: andrej@2258: return None andrej@2258: ref_local_id = connections[0].getrefLocalId() andrej@2258: blk = body.getcontentInstance(ref_local_id) andrej@2258: if blk is None: andrej@2258: return None andrej@2258: andrej@2275: if not hasattr(blk, "inputVariables"): andrej@2275: return None andrej@2275: andrej@2258: for invar in blk.inputVariables.getvariable(): andrej@2258: if invar.getformalParameter() == "EN": andrej@2258: if len(invar.getconnectionPointIn().getconnections()) > 0: andrej@2258: if blk.getinstanceName() is None: andrej@2258: var_name = "%s%d_ENO" % (blk.gettypeName(), blk.getlocalId()) andrej@2258: else: andrej@2258: var_name = "%s.ENO" % blk.getinstanceName() andrej@2258: return var_name andrej@2258: return None andrej@2258: Laurent@814: def ComputeProgram(self, pou): Laurent@814: body = pou.getbody() andrej@2450: if isinstance(body, list): Laurent@814: body = body[0] Laurent@814: body_content = body.getcontent() Laurent@1297: body_type = body_content.getLocalTag() andrej@1740: if body_type in ["IL", "ST"]: Laurent@1297: text = body_content.getanyText() Laurent@814: self.ParentGenerator.GeneratePouProgramInText(text.upper()) Edouard@1418: self.Program = [(ReIndentText(text, len(self.CurrentIndent)), andrej@1878: (self.TagName, "body", len(self.CurrentIndent)))] Laurent@814: elif body_type == "SFC": Laurent@814: self.IndentRight() Laurent@814: for instance in body.getcontentInstances(): Laurent@1297: if isinstance(instance, StepClass): Laurent@814: self.GenerateSFCStep(instance, pou) Laurent@1297: elif isinstance(instance, ActionBlockClass): Laurent@814: self.GenerateSFCStepActions(instance, pou) Laurent@1297: elif isinstance(instance, TransitionClass): Laurent@814: self.GenerateSFCTransition(instance, pou) Laurent@1298: elif isinstance(instance, JumpStepClass): 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" andrej@1739: 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: andrej@1739: otherInstances = {"outVariables&coils": [], "blocks": [], "connectors": []} Laurent@814: orderedInstances = [] Laurent@814: for instance in body.getcontentInstances(): Laurent@1297: if isinstance(instance, (OutVariableClass, InOutVariableClass, BlockClass)): Laurent@814: executionOrderId = instance.getexecutionOrderId() Laurent@814: if executionOrderId > 0: Laurent@814: orderedInstances.append((executionOrderId, instance)) Laurent@1297: elif isinstance(instance, (OutVariableClass, InOutVariableClass)): Laurent@814: otherInstances["outVariables&coils"].append(instance) Laurent@1297: elif isinstance(instance, BlockClass): Laurent@814: otherInstances["blocks"].append(instance) Laurent@1297: elif isinstance(instance, ConnectorClass): Laurent@814: otherInstances["connectors"].append(instance) Laurent@1297: elif isinstance(instance, CoilClass): 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@1297: if isinstance(instance, (OutVariableClass, InOutVariableClass)): Laurent@814: connections = instance.connectionPointIn.getconnections() Laurent@814: if connections is not None: Laurent@814: expression = self.ComputeExpression(body, connections) Laurent@1239: if expression is not None: andrej@2258: eno_var = self.GetUsedEno(body, connections) andrej@2258: if eno_var is not None: andrej@2258: self.Program += [(self.CurrentIndent + "IF %s" % eno_var, ())] andrej@2258: self.Program += [(" THEN\n ", ())] andrej@2258: self.IndentRight() andrej@2258: Laurent@1239: self.Program += [(self.CurrentIndent, ()), Laurent@1322: (instance.getexpression(), (self.TagName, "io_variable", instance.getlocalId(), "expression")), Laurent@1239: (" := ", ())] Laurent@1239: self.Program += expression Laurent@1239: self.Program += [(";\n", ())] andrej@2258: andrej@2258: if eno_var is not None: andrej@2258: self.IndentLeft() andrej@2258: self.Program += [(self.CurrentIndent + "END_IF;\n", ())] Laurent@1297: elif isinstance(instance, BlockClass): 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: andrej@1765: raise PLCGenException( andrej@1765: _("Undefined block type \"{a1}\" in \"{a2}\" POU"). andrej@1765: format(a1=block_type, a2=self.Name)) Laurent@1134: try: Laurent@1310: self.GenerateBlock(instance, block_infos, body, None) andrej@2418: except ValueError as e: andrej@2447: raise PLCGenException(str(e)) Laurent@1297: elif isinstance(instance, ConnectorClass): Laurent@814: connector = instance.getname() Laurent@814: if self.ComputedConnectors.get(connector, None): Laurent@1239: continue Laurent@1239: expression = self.ComputeExpression(body, instance.connectionPointIn.getconnections()) Laurent@1239: if expression is not None: Laurent@1239: self.ComputedConnectors[connector] = expression Laurent@1297: elif isinstance(instance, CoilClass): Laurent@814: connections = instance.connectionPointIn.getconnections() Laurent@814: if connections is not None: Laurent@814: coil_info = (self.TagName, "coil", instance.getlocalId()) Laurent@1239: expression = self.ComputeExpression(body, connections) Laurent@1239: if expression is not None: Laurent@1239: expression = self.ExtractModifier(instance, expression, coil_info) Laurent@1239: self.Program += [(self.CurrentIndent, ())] Laurent@1322: self.Program += [(instance.getvariable(), coil_info + ("reference",))] Laurent@1239: self.Program += [(" := ", ())] + expression + [(";\n", ())] Edouard@1418: 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): andrej@2450: if isinstance(path, list): 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: Edouard@1418: 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@1310: def GenerateBlock(self, block, block_infos, body, link, order=False, to_inout=False): andrej@1864: andrej@1864: def _GetBlockName(name, type): andrej@1864: """function returns name of function or function block instance""" andrej@1864: if name: andrej@1864: # function blocks andrej@1864: blockname = "{a1}({a2})".format(a1=name, a2=type) andrej@1864: else: andrej@1864: # functions andrej@1864: blockname = type andrej@1864: return blockname andrej@1864: andrej@1864: def _RaiseUnconnectedInOutError(name, type, parameter, place): andrej@1864: blockname = _GetBlockName(name, type) andrej@1864: raise ValueError( andrej@1864: _("InOut variable {a1} in block {a2} in POU {a3} must be connected."). andrej@1864: format(a1=parameter, a2=blockname, a3=place)) andrej@1864: Laurent@1310: name = block.getinstanceName() Laurent@1310: type = block.gettypeName() Laurent@1310: executionOrderId = block.getexecutionOrderId() Laurent@1310: input_variables = block.inputVariables.getvariable() Laurent@1310: output_variables = block.outputVariables.getvariable() Laurent@1310: inout_variables = {} Laurent@1310: for input_variable in input_variables: Laurent@1310: for output_variable in output_variables: Laurent@1310: if input_variable.getformalParameter() == output_variable.getformalParameter(): Laurent@1310: inout_variables[input_variable.getformalParameter()] = "" Laurent@1310: input_names = [input[0] for input in block_infos["inputs"]] Laurent@1310: output_names = [output[0] for output in block_infos["outputs"]] Laurent@1310: if block_infos["type"] == "function": Laurent@1310: if not self.ComputedBlocks.get(block, False) and not order: Laurent@1310: self.ComputedBlocks[block] = True Laurent@1310: connected_vars = [] Laurent@1310: if not block_infos["extensible"]: Edouard@1418: input_connected = dict([("EN", None)] + Laurent@1310: [(input_name, None) for input_name in input_names]) Laurent@1310: for variable in input_variables: Laurent@1310: parameter = variable.getformalParameter() andrej@1763: if parameter in input_connected: Laurent@1310: input_connected[parameter] = variable Laurent@1310: if input_connected["EN"] is None: Laurent@1310: input_connected.pop("EN") Laurent@1310: input_parameters = input_names Laurent@1310: else: Laurent@1310: input_parameters = ["EN"] + input_names Laurent@1310: else: Laurent@1310: input_connected = dict([(variable.getformalParameter(), variable) Laurent@1310: for variable in input_variables]) Laurent@1310: input_parameters = [variable.getformalParameter() Laurent@1310: for variable in input_variables] Laurent@1310: one_input_connected = False Laurent@1310: all_input_connected = True Laurent@1310: for i, parameter in enumerate(input_parameters): Laurent@1310: variable = input_connected.get(parameter) Laurent@1310: if variable is not None: Laurent@1310: input_info = (self.TagName, "block", block.getlocalId(), "input", i) Laurent@1310: connections = variable.connectionPointIn.getconnections() Laurent@1310: if connections is not None: Laurent@1310: if parameter != "EN": Laurent@1310: one_input_connected = True andrej@1763: if parameter in inout_variables: Laurent@1310: expression = self.ComputeExpression(body, connections, executionOrderId > 0, True) Laurent@1310: if expression is not None: andrej@1863: inout_variables[parameter] = expression andrej@1864: else: andrej@1864: _RaiseUnconnectedInOutError(name, type, parameter, self.Name) Laurent@1310: else: Laurent@1310: expression = self.ComputeExpression(body, connections, executionOrderId > 0) Laurent@1310: if expression is not None: Laurent@1310: connected_vars.append(([(parameter, input_info), (" := ", ())], Laurent@1310: self.ExtractModifier(variable, expression, input_info))) Laurent@1310: else: Laurent@1310: all_input_connected = False Laurent@1310: else: Laurent@1310: all_input_connected = False Laurent@1310: if len(output_variables) > 1 or not all_input_connected: Laurent@1310: vars = [name + value for name, value in connected_vars] Laurent@1310: else: Laurent@1310: vars = [value for name, value in connected_vars] Laurent@1310: if one_input_connected: Laurent@1310: for i, variable in enumerate(output_variables): Laurent@1310: parameter = variable.getformalParameter() andrej@1775: if parameter not in inout_variables and parameter in output_names + ["", "ENO"]: Laurent@1310: if variable.getformalParameter() == "": andrej@1734: variable_name = "%s%d" % (type, block.getlocalId()) Laurent@1310: else: andrej@1734: variable_name = "%s%d_%s" % (type, block.getlocalId(), parameter) Laurent@1310: if self.Interface[-1][0] != "VAR" or self.Interface[-1][1] is not None or self.Interface[-1][2]: Laurent@1310: self.Interface.append(("VAR", None, False, [])) Laurent@1310: if variable.connectionPointOut in self.ConnectionTypes: Laurent@1310: self.Interface[-1][3].append((self.ConnectionTypes[variable.connectionPointOut], variable_name, None, None)) Laurent@1310: else: Laurent@1310: self.Interface[-1][3].append(("ANY", variable_name, None, None)) Laurent@1310: if len(output_variables) > 1 and parameter not in ["", "OUT"]: Edouard@1418: vars.append([(parameter, (self.TagName, "block", block.getlocalId(), "output", i)), andrej@1734: (" => %s" % variable_name, ())]) Laurent@1310: else: Laurent@1310: output_info = (self.TagName, "block", block.getlocalId(), "output", i) Laurent@1310: output_name = variable_name Laurent@1310: self.Program += [(self.CurrentIndent, ()), Laurent@1310: (output_name, output_info), Laurent@1310: (" := ", ()), Laurent@1310: (type, (self.TagName, "block", block.getlocalId(), "type")), Laurent@1310: ("(", ())] Laurent@1310: self.Program += JoinList([(", ", ())], vars) Laurent@1310: self.Program += [(");\n", ())] Laurent@1310: else: andrej@1744: msg = _("\"{a1}\" function cancelled in \"{a2}\" POU: No input connected").format(a1=type, a2=self.TagName.split("::")[-1]) andrej@1581: self.Warnings.append(msg) Laurent@1310: elif block_infos["type"] == "functionBlock": Laurent@1310: if not self.ComputedBlocks.get(block, False) and not order: Laurent@1310: self.ComputedBlocks[block] = True Laurent@1310: vars = [] Laurent@1310: offset_idx = 0 Laurent@1310: for variable in input_variables: Laurent@1310: parameter = variable.getformalParameter() Laurent@1310: if parameter in input_names or parameter == "EN": Laurent@1310: if parameter == "EN": Laurent@1310: input_idx = 0 Laurent@1310: offset_idx = 1 Laurent@1310: else: Laurent@1310: input_idx = offset_idx + input_names.index(parameter) Laurent@1310: input_info = (self.TagName, "block", block.getlocalId(), "input", input_idx) Laurent@1310: connections = variable.connectionPointIn.getconnections() Laurent@1310: if connections is not None: andrej@1763: expression = self.ComputeExpression(body, connections, executionOrderId > 0, parameter in inout_variables) Laurent@1310: if expression is not None: Laurent@1310: vars.append([(parameter, input_info), Laurent@1310: (" := ", ())] + self.ExtractModifier(variable, expression, input_info)) andrej@1864: elif parameter in inout_variables: andrej@1864: _RaiseUnconnectedInOutError(name, type, parameter, self.Name) Edouard@1418: self.Program += [(self.CurrentIndent, ()), Laurent@1310: (name, (self.TagName, "block", block.getlocalId(), "name")), Laurent@1310: ("(", ())] Laurent@1310: self.Program += JoinList([(", ", ())], vars) Laurent@1310: self.Program += [(");\n", ())] Edouard@1418: Laurent@1310: if link is not None: Laurent@1310: connectionPoint = link.getposition()[-1] Laurent@1310: output_parameter = link.getformalParameter() Laurent@1310: else: Laurent@1310: connectionPoint = None Laurent@1310: output_parameter = None Edouard@1418: Laurent@1310: output_variable = None Laurent@1310: output_idx = 0 Laurent@1310: if output_parameter is not None: Laurent@1310: if output_parameter in output_names or output_parameter == "ENO": Laurent@1310: for variable in output_variables: Laurent@1310: if variable.getformalParameter() == output_parameter: Laurent@1310: output_variable = variable Laurent@1310: if output_parameter != "ENO": Laurent@1310: output_idx = output_names.index(output_parameter) Laurent@1310: else: Laurent@1310: for i, variable in enumerate(output_variables): Laurent@1310: blockPointx, blockPointy = variable.connectionPointOut.getrelPositionXY() andrej@1766: if connectionPoint is None or \ andrej@1766: block.getx() + blockPointx == connectionPoint.getx() and \ andrej@1766: block.gety() + blockPointy == connectionPoint.gety(): Laurent@1310: output_variable = variable Laurent@1310: output_parameter = variable.getformalParameter() Laurent@1310: output_idx = i Edouard@1418: Laurent@1310: if output_variable is not None: Laurent@1310: if block_infos["type"] == "function": Laurent@1310: output_info = (self.TagName, "block", block.getlocalId(), "output", output_idx) andrej@1763: if output_parameter in inout_variables: andrej@1864: for variable in input_variables: andrej@1864: if variable.getformalParameter() == output_parameter: andrej@1864: connections = variable.connectionPointIn.getconnections() andrej@1864: if connections is not None: andrej@1864: expression = self.ComputeExpression( andrej@1864: body, connections, executionOrderId > 0, True) andrej@1864: output_value = expression andrej@1864: break Laurent@1310: else: Laurent@1310: if output_parameter == "": andrej@1734: output_name = "%s%d" % (type, block.getlocalId()) Laurent@1310: else: andrej@1734: output_name = "%s%d_%s" % (type, block.getlocalId(), output_parameter) Laurent@1310: output_value = [(output_name, output_info)] Laurent@1310: return self.ExtractModifier(output_variable, output_value, output_info) Laurent@1310: if block_infos["type"] == "functionBlock": Laurent@1310: output_info = (self.TagName, "block", block.getlocalId(), "output", output_idx) andrej@1734: output_name = self.ExtractModifier(output_variable, [("%s.%s" % (name, output_parameter), output_info)], output_info) Laurent@1310: if to_inout: andrej@1734: variable_name = "%s_%s" % (name, output_parameter) Laurent@1310: if not self.IsAlreadyDefined(variable_name): Laurent@1310: if self.Interface[-1][0] != "VAR" or self.Interface[-1][1] is not None or self.Interface[-1][2]: Laurent@1310: self.Interface.append(("VAR", None, False, [])) Laurent@1310: if variable.connectionPointOut in self.ConnectionTypes: Laurent@1310: self.Interface[-1][3].append( Laurent@1310: (self.ConnectionTypes[output_variable.connectionPointOut], variable_name, None, None)) Laurent@1310: else: Laurent@1310: self.Interface[-1][3].append(("ANY", variable_name, None, None)) Laurent@1310: self.Program += [(self.CurrentIndent, ()), andrej@1734: ("%s := " % variable_name, ())] Laurent@1310: self.Program += output_name Laurent@1310: self.Program += [(";\n", ())] Laurent@1310: return [(variable_name, ())] Edouard@1418: return output_name Laurent@1310: if link is not None: Laurent@1310: if output_parameter is None: Laurent@1310: output_parameter = "" andrej@1864: blockname = _GetBlockName(name, type) andrej@1765: raise ValueError( andrej@1765: _("No output {a1} variable found in block {a2} in POU {a3}. Connection must be broken"). andrej@1765: format(a1=output_parameter, a2=blockname, a3=self.Name)) Laurent@1310: andrej@1744: 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@1297: if isinstance(next, LeftPowerRailClass): Laurent@814: paths.append(None) Laurent@1297: elif isinstance(next, (InVariableClass, InOutVariableClass)): Laurent@1322: paths.append(str([(next.getexpression(), (self.TagName, "io_variable", localId, "expression"))])) Laurent@1297: elif isinstance(next, BlockClass): 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: andrej@1765: raise PLCGenException( andrej@1765: _("Undefined block type \"{a1}\" in \"{a2}\" POU"). andrej@1765: format(a1=block_type, a2=self.Name)) Laurent@1134: try: Laurent@1310: paths.append(str(self.GenerateBlock(next, block_infos, body, connection, order, to_inout))) andrej@2418: except ValueError as e: andrej@2447: raise PLCGenException(str(e)) Laurent@1297: elif isinstance(next, ContinuationClass): Laurent@814: name = next.getname() Laurent@814: computed_value = self.ComputedConnectors.get(name, None) andrej@1743: if computed_value is not None: Laurent@814: paths.append(str(computed_value)) Laurent@814: else: Laurent@814: connector = None Laurent@814: for instance in body.getcontentInstances(): Laurent@1297: if isinstance(instance, ConnectorClass) and instance.getname() == name: Laurent@814: if connector is not None: andrej@1765: raise PLCGenException( andrej@1765: _("More than one connector found corresponding to \"{a1}\" continuation in \"{a2}\" POU"). andrej@1765: format(a1=name, a2=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@1239: if expression is not None: Laurent@1239: self.ComputedConnectors[name] = expression Laurent@1239: paths.append(str(expression)) Laurent@814: else: andrej@1765: raise PLCGenException( andrej@1765: _("No connector found corresponding to \"{a1}\" continuation in \"{a2}\" POU"). andrej@1765: format(a1=name, a2=self.Name)) Laurent@1297: elif isinstance(next, ContactClass): Laurent@814: contact_info = (self.TagName, "contact", next.getlocalId()) Laurent@1322: variable = str(self.ExtractModifier(next, [(next.getvariable(), contact_info + ("reference",))], contact_info)) Laurent@814: result = self.GeneratePaths(next.connectionPointIn.getconnections(), body, order) andrej@2519: if len(result) == 0: andrej@2519: raise PLCGenException(_("Contact \"{a1}\" in POU \"{a2}\" must be connected."). andrej@2519: format(a1=next.getvariable(), a2=self.Name)) 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) andrej@2450: elif isinstance(result[0], list): 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@1297: elif isinstance(next, CoilClass): andrej@2277: paths.append(self.GeneratePaths(next.connectionPointIn.getconnections(), body, order)) Laurent@814: return paths Laurent@814: andrej@1744: def ComputePaths(self, paths, first=False): andrej@2450: if isinstance(paths, tuple): 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) + [(")", ())] andrej@2450: elif isinstance(paths, list): 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: andrej@1744: def ComputeExpression(self, body, connections, order=False, to_inout=False): Laurent@814: paths = self.GeneratePaths(connections, body, order, to_inout) Laurent@1239: if len(paths) == 0: Laurent@1239: return None 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 Edouard@1418: 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 andrej@1734: name = "%s%d" % (edge, i) Laurent@814: while self.IsAlreadyDefined(name): Laurent@814: i += 1 andrej@1734: name = "%s%d" % (edge, i) Laurent@814: self.Interface[-1][3].append((edge, name, None, None)) Edouard@1418: self.Program += [(self.CurrentIndent, ()), (name, var_info), ("(CLK := ", ())] Laurent@814: self.Program += expression Laurent@814: self.Program += [(");\n", ())] andrej@1734: return [("%s.Q" % name, var_info)] Edouard@1418: Laurent@814: def ExtractDivergenceInput(self, divergence, pou): Laurent@814: connectionPointIn = divergence.getconnectionPointIn() Laurent@1298: if connectionPointIn is not None: 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() andrej@2450: if isinstance(body, list): 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() andrej@2450: if isinstance(body, list): 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) andrej@1739: step_infos = {"id": step.getlocalId(), andrej@1739: "initial": step.getinitialStep(), andrej@1739: "transitions": [], andrej@1739: "actions": []} Laurent@889: self.SFCNetworks["Steps"][step_name] = step_infos Laurent@1298: if step.connectionPointIn is not None: 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() andrej@2450: if isinstance(body, list): Laurent@814: body = body[0] Laurent@814: instance = body.getcontentInstance(instanceLocalId) Laurent@1297: if isinstance(instance, TransitionClass): Laurent@814: instances.append(instance) Laurent@1297: elif isinstance(instance, SelectionConvergenceClass): Laurent@814: instances.extend(self.ExtractConvergenceInputs(instance, pou)) Laurent@1297: elif isinstance(instance, SimultaneousDivergenceClass): Laurent@814: transition = self.ExtractDivergenceInput(instance, pou) Laurent@1298: if transition is not None: Laurent@1297: if isinstance(transition, TransitionClass): Laurent@814: instances.append(transition) Laurent@1297: elif isinstance(transition, SelectionConvergenceClass): 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)]) Edouard@1418: Laurent@814: def GenerateSFCJump(self, jump, pou): Laurent@814: jump_target = jump.gettargetName() andrej@1626: if not pou.hasstep(jump_target): andrej@1626: pname = pou.getname() andrej@1765: raise PLCGenException( andrej@1765: _("SFC jump in pou \"{a1}\" refers to non-existent SFC step \"{a2}\""). andrej@1765: format(a1=pname, a2=jump_target)) andrej@1765: Laurent@1298: if jump.connectionPointIn is not None: 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() andrej@2450: if isinstance(body, list): Laurent@814: body = body[0] Laurent@814: instance = body.getcontentInstance(instanceLocalId) Laurent@1297: if isinstance(instance, TransitionClass): Laurent@814: instances.append(instance) Laurent@1297: elif isinstance(instance, SelectionConvergenceClass): Laurent@814: instances.extend(self.ExtractConvergenceInputs(instance, pou)) Laurent@1297: elif isinstance(instance, SimultaneousDivergenceClass): Laurent@814: transition = self.ExtractDivergenceInput(instance, pou) Laurent@1298: if transition is not None: Laurent@1297: if isinstance(transition, TransitionClass): Laurent@814: instances.append(transition) Laurent@1297: elif isinstance(transition, SelectionConvergenceClass): 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)]) Edouard@1418: 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() andrej@2450: if isinstance(body, list): 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): andrej@1739: action_infos = {"id": actionBlock.getlocalId(), andrej@1739: "qualifier": action["qualifier"], andrej@1739: "content": action["value"], andrej@1739: "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: andrej@1734: action_name = "%s_INLINE%d" % (step_name.upper(), self.GetActionNumber()) andrej@1768: self.SFCNetworks["Actions"][action_name] = ([ andrej@1768: (self.CurrentIndent, ()), andrej@1768: (action["value"], ( andrej@1768: self.TagName, "action_block", action_infos["id"], andrej@1768: "action", i, "inline")), Laurent@814: ("\n", ())], ()) Laurent@814: action_infos["content"] = action_name Laurent@814: self.SFCNetworks["Steps"][step_name]["actions"].append(action_infos) Edouard@1418: 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@1298: if actionContent is not None: Laurent@814: previous_tagname = self.TagName Edouard@1948: self.TagName = 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 Edouard@1418: 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() andrej@2450: if isinstance(body, list): Laurent@814: body = body[0] Laurent@814: instance = body.getcontentInstance(instanceLocalId) Laurent@1297: if isinstance(instance, StepClass): Laurent@814: steps.append(instance) Laurent@1297: elif isinstance(instance, SelectionDivergenceClass): Laurent@814: step = self.ExtractDivergenceInput(instance, pou) Laurent@1298: if step is not None: Laurent@1297: if isinstance(step, StepClass): Laurent@814: steps.append(step) Laurent@1297: elif isinstance(step, SimultaneousConvergenceClass): Laurent@814: steps.extend(self.ExtractConvergenceInputs(step, pou)) Laurent@1297: elif isinstance(instance, SimultaneousConvergenceClass): Laurent@814: steps.extend(self.ExtractConvergenceInputs(instance, pou)) andrej@1739: transition_infos = {"id": transition.getlocalId(), Edouard@1418: "priority": transition.getpriority(), andrej@1739: "from": [], andrej@1739: "to": [], andrej@1739: "content": []} Laurent@889: self.SFCNetworks["Transitions"][transition] = transition_infos Laurent@814: transitionValues = transition.getconditionContent() Laurent@814: if transitionValues["type"] == "inline": andrej@1734: 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 Edouard@1948: self.TagName = ComputePouTransitionName(self.Name, transitionValues["value"]) Laurent@814: if transitionType == "IL": Laurent@814: transition_infos["content"] = [(":\n", ()), Edouard@1450: (ReIndentText(transitionBody.getcontent().getanyText(), len(self.CurrentIndent)), (self.TagName, "body", len(self.CurrentIndent)))] Laurent@814: elif transitionType == "ST": Laurent@814: transition_infos["content"] = [("\n", ()), Edouard@1450: (ReIndentText(transitionBody.getcontent().getanyText(), len(self.CurrentIndent)), (self.TagName, "body", len(self.CurrentIndent)))] Laurent@814: else: Laurent@814: for instance in transitionBody.getcontentInstances(): andrej@1769: if isinstance(instance, OutVariableClass) and instance.getexpression() == transitionValues["value"] or \ andrej@1769: isinstance(instance, CoilClass) 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@1239: if expression is not None: andrej@1734: transition_infos["content"] = [("\n%s:= " % self.CurrentIndent, ())] + expression + [(";\n", ())] Laurent@1239: self.SFCComputedBlocks += self.Program Laurent@1239: self.Program = [] andrej@1775: if "content" not in transition_infos: andrej@1765: raise PLCGenException( andrej@1765: _("Transition \"%s\" body must contain an output variable or coil referring to its name") andrej@1765: % transitionValues["value"]) Laurent@814: self.TagName = previous_tagname Laurent@814: elif transitionValues["type"] == "connection": Laurent@814: body = pou.getbody() andrej@2450: if isinstance(body, list): Laurent@814: body = body[0] Laurent@1298: connections = transitionValues["value"].getconnections() Laurent@814: if connections is not None: Laurent@814: expression = self.ComputeExpression(body, connections) Laurent@1239: if expression is not None: andrej@1734: transition_infos["content"] = [("\n%s:= " % self.CurrentIndent, ())] + expression + [(";\n", ())] Laurent@1239: self.SFCComputedBlocks += self.Program Laurent@1239: 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() andrej@1734: 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) Edouard@1418: 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) andrej@1734: self.Program += [("%sACTION " % self.CurrentIndent, ()), Laurent@814: (action_name, action_info), Laurent@1298: (":\n", ())] Laurent@814: self.Program += action_content andrej@1734: self.Program += [("%sEND_ACTION\n\n" % self.CurrentIndent, ())] Edouard@1418: Laurent@814: def ComputeSFCTransition(self, transition): Laurent@814: if transition in self.SFCNetworks["Transitions"].keys(): Laurent@814: transition_infos = self.SFCNetworks["Transitions"].pop(transition) andrej@1734: self.Program += [("%sTRANSITION" % self.CurrentIndent, ())] andrej@1743: if transition_infos["priority"] is not None: Laurent@814: self.Program += [(" (PRIORITY := ", ()), andrej@1734: ("%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: andrej@1765: raise PLCGenException( andrej@1765: _("Transition with content \"{a1}\" not connected to a previous step in \"{a2}\" POU"). andrej@1765: format(a1=transition_infos["content"], a2=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: andrej@1765: raise PLCGenException( andrej@1765: _("Transition with content \"{a1}\" not connected to a next step in \"{a2}\" POU"). andrej@1765: format(a1=transition_infos["content"], a2=self.Name)) Laurent@814: self.Program += transition_infos["content"] andrej@1734: self.Program += [("%sEND_TRANSITION\n\n" % self.CurrentIndent, ())] andrej@1847: for [(step_name, _step_infos)] in transition_infos["to"]: Laurent@814: self.ComputeSFCStep(step_name) Edouard@1418: Laurent@814: def GenerateProgram(self, pou): Laurent@814: self.ComputeInterface(pou) Laurent@814: self.ComputeConnectionTypes(pou) Laurent@814: self.ComputeProgram(pou) Edouard@1418: andrej@1734: program = [("%s " % self.Type, ()), Laurent@814: (self.Name, (self.TagName, "name"))] Laurent@1310: if self.ReturnType is not None: Laurent@814: program += [(" : ", ()), Laurent@814: (self.ReturnType, (self.TagName, "return"))] Laurent@814: program += [("\n", ())] Laurent@814: if len(self.Interface) == 0: andrej@1765: raise PLCGenException(_("No variable defined in \"%s\" POU") % self.Name) andrej@1739: if len(self.Program) == 0: andrej@1765: raise PLCGenException(_("No body defined in \"%s\" POU") % self.Name) Laurent@814: var_number = 0 andrej@1847: for list_type, option, _located, variables in self.Interface: Laurent@814: variable_type = errorVarTypes.get(list_type, "var_local") andrej@1734: program += [(" %s" % list_type, ())] Laurent@814: if option is not None: andrej@1734: 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: (" ", ())] andrej@1743: if var_address is not 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"))] andrej@1743: if var_initial is not 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 andrej@1734: program += [("END_%s\n\n" % self.Type, ())] Laurent@814: return program Laurent@814: andrej@1736: 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()