PLCGenerator.py
author lbessard
Wed, 23 Jan 2008 18:25:57 +0100
changeset 153 f0e8e7f58a5a
parent 151 aaa80b48bead
child 168 fb500cc79164
permissions -rw-r--r--
Removing old outdated code
#!/usr/bin/env python
# -*- coding: utf-8 -*-

#This file is part of PLCOpenEditor, a library implementing an IEC 61131-3 editor
#based on the plcopen standard. 
#
#Copyright (C) 2007: Edouard TISSERANT and Laurent BESSARD
#
#See COPYING file for copyrights details.
#
#This library is free software; you can redistribute it and/or
#modify it under the terms of the GNU General Public
#License as published by the Free Software Foundation; either
#version 2.1 of the License, or (at your option) any later version.
#
#This library is distributed in the hope that it will be useful,
#but WITHOUT ANY WARRANTY; without even the implied warranty of
#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
#General Public License for more details.
#
#You should have received a copy of the GNU General Public
#License along with this library; if not, write to the Free Software
#Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

from plcopen import plcopen
from plcopen.structures import *
from types import *

varTypeNames = {"localVars" : "VAR", "tempVars" : "VAR_TEMP", "inputVars" : "VAR_INPUT", 
                "outputVars" : "VAR_OUTPUT", "inOutVars" : "VAR_IN_OUT", "externalVars" : "VAR_EXTERNAL",
                "globalVars" : "VAR_GLOBAL", "accessVars" : "VAR_ACCESS"}

pouTypeNames = {"function" : "FUNCTION", "functionBlock" : "FUNCTION_BLOCK", "program" : "PROGRAM"}

currentProject = None
currentProgram = ""
datatypeComputed = {}
pouComputed = {}

def ReIndentText(text, nb_spaces):
    compute = ""
    lines = text.splitlines()
    if len(lines) > 0:
        line_num = 0
        while line_num < len(lines) and len(lines[line_num].strip()) == 0:
            line_num += 1
        if line_num < len(lines):
            spaces = 0
            while lines[line_num][spaces] == " ":
                spaces += 1
            indent = ""
            for i in xrange(spaces, nb_spaces):
                indent += " "
            for line in lines:
                if line != "":
                    compute += "%s%s\n"%(indent, line)
                else:
                    compute += "\n"
    return compute

def GenerateDataType(datatype_name):
    if not datatypeComputed.get(datatype_name, True):
        datatypeComputed[datatype_name] = True
        global currentProject, currentProgram
        datatype = currentProject.getdataType(datatype_name)
        datatype_def = "  %s :"%datatype.getname()
        basetype_content = datatype.baseType.getcontent()
        if basetype_content["name"] in ["string", "wstring"]:
            datatype_def += " %s"%basetype_content["name"].upper()
        elif basetype_content["name"] == "derived":
            basetype_name = basetype_content["value"].getname()
            GenerateDataType(basetype_name)
            datatype_def += " %s"%basetype_name
        elif basetype_content["name"] in ["subrangeSigned", "subrangeUnsigned"]:
            base_type = basetype_content["value"].baseType.getcontent()
            if base_type["name"] == "derived":
                basetype_name = base_type["value"].getname()
            else:
                basetype_name = base_type["name"]
                GenerateDataType(basetype_name)
            min_value = basetype_content["value"].range.getlower()
            max_value = basetype_content["value"].range.getupper()
            datatype_def += " %s (%d..%d)"%(basetype_name, min_value, max_value)
        elif basetype_content["name"] == "enum":
            values = []
            for value in basetype_content["value"].values.getvalue():
                values.append(value.getname())
            datatype_def += " (%s)"%", ".join(values)
        elif basetype_content["name"] == "array":
            base_type = basetype_content["value"].baseType.getcontent()
            if base_type["name"] == "derived":
                basetype_name = base_type["value"].getname()
            elif base_type["name"] in ["string", "wstring"]:
                basetype_name = base_type["name"].upper()
            else:
                basetype_name = base_type["name"]
                GenerateDataType(basetype_name)
            dimensions = []
            for dimension in basetype_content["value"].getdimension():
                dimensions.append("0..%d"%(dimension.getupper() - 1))
            datatype_def += " ARRAY [%s] OF %s"%(",".join(dimensions), basetype_name)
        else:
            datatype_def += " %s"%basetype_content["name"]
        if datatype.initialValue is not None:
            datatype_def += " := %s"%str(datatype.initialValue.getvalue())
        currentProgram += "%s;\n"%datatype_def

def GeneratePouProgram(pou_name):
    if not pouComputed.get(pou_name, True):
        pouComputed[pou_name] = True
        global currentProject, currentProgram
        pou = currentProject.getpou(pou_name)
        pou_type = pou.getpouType()
        if pou_type in pouTypeNames:
            pou_program = PouProgram(pou.getname(), pouTypeNames[pou_type])
        else:
            raise ValueError, "Undefined pou type"
        pou_program.GenerateInterface(pou.getinterface())
        pou_program.GenerateConnectionTypes(pou)
        pou_program.GenerateProgram(pou)
        currentProgram += pou_program.GenerateSTProgram()

def GenerateConfiguration(configuration):
    config = "\nCONFIGURATION %s\n"%configuration.getname()
    for varlist in configuration.getglobalVars():
        config += "  VAR_GLOBAL"
        if varlist.getretain():
            config += " RETAIN"
        if varlist.getconstant():
            config += " CONSTANT"
        config += "\n"
        for var in varlist.getvariable():
            vartype_content = var.gettype().getcontent()
            if vartype_content["name"] == "derived":
                var_type = vartype_content["value"].getname()
            elif vartype_content["name"] in ["string", "wstring"]:
                var_type = vartype_content["name"].upper()
            else:
                var_type = vartype_content["name"]
            config += "    %s "%var.getname()
            address = var.getaddress()
            if address:
                config += "AT %s "%address
            config += ": %s"%var_type
            initial = var.getinitialValue()
            if initial:
                value = str(initial.getvalue())
                value = {"TRUE":"0","FALSE":"1"}.get(value.upper(), value)
                if var_type == "STRING":
                    config += " := '%s'"%value
                elif var_type == "WSTRING":
                    config += " := \"%s\""%value
                else:
                    config += " := %s"%value
            config += ";\n"
        config += "  END_VAR\n"
    for resource in configuration.getresource():
        config += GenerateResource(resource)
    config += "END_CONFIGURATION\n"
    return config
    
def GenerateResource(resource):
    resrce = "\n  RESOURCE %s ON BEREMIZ\n"%resource.getname()
    for varlist in resource.getglobalVars():
        resrce += "    VAR_GLOBAL"
        if varlist.getretain():
            resrce += " RETAIN"
        if varlist.getconstant():
            resrce += " CONSTANT"
        resrce += "\n"
        for var in varlist.getvariable():
            vartype_content = var.gettype().getcontent()
            if vartype_content["name"] == "derived":
                var_type = vartype_content["value"].getname()
            elif vartype_content["name"] in ["string", "wstring"]:
                var_type = vartype_content["name"].upper()
            else:
                var_type = vartype_content["name"]
            resrce += "      %s "%var.getname()
            address = var.getaddress()
            if address:
                resrce += "AT %s "%address
            resrce += ": %s"%var_type
            initial = var.getinitialValue()
            if initial:
                value = str(initial.getvalue())
                value = {"TRUE":"0","FALSE":"1"}.get(value.upper(), value)
                if var_type == "STRING":
                    resrce += " := '%s'"%value
                elif var_type == "WSTRING":
                    resrce += " := \"%s\""%value
                else:
                    resrce += " := %s"%value
            resrce += ";\n"
        resrce += "    END_VAR\n"
    tasks = resource.gettask()
    for task in tasks:
        resrce += "    TASK %s("%task.getname()
        args = []
        single = task.getsingle()
        if single:
            args.append("SINGLE := %s"%single)
        interval = task.getinterval()
        if interval:
            text = "t#"
            if interval.hour != 0:
                text += "%dh"%interval.hour
            if interval.minute != 0:
                text += "%dm"%interval.minute
            if interval.second != 0:
                text += "%ds"%interval.second
            if interval.microsecond != 0:
                text += "%dms"%(interval.microsecond / 1000)
            args.append("INTERVAL := %s"%text)
        args.append("PRIORITY := %s"%str(task.getpriority()))
        resrce += ",".join(args) + ");\n"
    for task in tasks:
        for instance in task.getpouInstance():
            resrce += "    PROGRAM %s WITH %s : %s;\n"%(instance.getname(), task.getname(), instance.gettype())
    for instance in resource.getpouInstance():
        resrce += "    PROGRAM %s : %s;\n"%(instance.getname(), instance.gettype())
    resrce += "  END_RESOURCE\n"
    return resrce

"""
Module implementing methods for generating PLC programs in ST or IL
"""

class PouProgram:
    
    def __init__(self, name, type):
        self.Name = name
        self.Type = type
        self.ReturnType = None
        self.Interface = []
        self.InitialSteps = []
        self.ComputedBlocks = {}
        self.ComputedConnectors = {}
        self.ConnectionTypes = {}
        self.RelatedConnections = []
        self.SFCNetworks = {"Steps":{}, "Transitions":{}, "Actions":{}}
        self.SFCComputedBlocks = ""
        self.ActionNumber = 0
        self.Program = ""
    
    def GetActionNumber(self):
        self.ActionNumber += 1
        return self.ActionNumber
    
    def IsAlreadyDefined(self, name):
        for list_type, retain, constant, located, vars in self.Interface:
            for var_type, var_name, var_address, var_initial in vars:
                if name == var_name:
                    return True
        return False
    
    def GetVariableType(self, name):
        for list_type, retain, constant, located, vars in self.Interface:
            for var_type, var_name, var_address, var_initial in vars:
                if name == var_name:
                    return var_type
        return None
    
    def GetConnectedConnection(self, connection, body):
        links = connection.getconnections()
        if links and len(links) == 1:
            return self.GetLinkedConnection(links[0], body)
        return None
        
    def GetLinkedConnection(self, link, body):
        parameter = link.getformalParameter()
        instance = body.getcontentInstance(link.getrefLocalId())
        if isinstance(instance, (plcopen.fbdObjects_inVariable, plcopen.fbdObjects_inOutVariable, plcopen.commonObjects_continuation, plcopen.ldObjects_contact, plcopen.ldObjects_coil)):
            return instance.connectionPointOut
        elif isinstance(instance, plcopen.fbdObjects_block):
            outputvariables = instance.outputVariables.getvariable()
            if len(outputvariables) == 1:
                return outputvariables[0].connectionPointOut
            elif parameter:
                for variable in outputvariables:
                    if variable.getformalParameter() == parameter:
                        return variable.connectionPointOut
            else:
                point = link.getPosition()[-1]
                for variable in outputvariables:
                    relposition = variable.connectionPointOut.getrelPositionXY()
                    blockposition = instance.getposition()
                    if point.x == blockposition.x + relposition[0] and point.y == blockposition.y + relposition[1]:
                        return variable.connectionPointOut
        elif isinstance(instance, plcopen.ldObjects_leftPowerRail):
            outputconnections = instance.getconnectionPointOut()
            if len(outputconnections) == 1:
                return outputconnections[0]
            else:
                point = link.getposition()[-1]
                for outputconnection in outputconnections:
                    relposition = outputconnection.getrelPositionXY()
                    powerrailposition = instance.getposition()
                    if point.x == powerrailposition.x + relposition[0] and point.y == powerrailposition.y + relposition[1]:
                        return outputconnection
        return None
        
    def ExtractRelatedConnections(self, connection):
        for i, related in enumerate(self.RelatedConnections):
            if connection in related:
                return self.RelatedConnections.pop(i)
        return [connection]
    
    def GenerateInterface(self, interface):
        if self.Type == "FUNCTION":
            returntype_content = interface.getreturnType().getcontent()
            if returntype_content["value"] is None:
                self.ReturnType = returntype_content["name"]
            else:
                self.ReturnType = returntype_content["value"].getname()
        for varlist in interface.getcontent():
            variables = []
            located = False
            for var in varlist["value"].getvariable():
                vartype_content = var.gettype().getcontent()
                if vartype_content["name"] == "derived":
                    var_type = vartype_content["value"].getname()
                    GeneratePouProgram(var_type)
                    blocktype = GetBlockType(var_type)
                    if blocktype is not None:
                        variables.extend(blocktype["initialise"](var_type, var.getname()))
                        located = False
                    else:
                        initial = var.getinitialValue()
                        if initial:
                            initial_value = initial.getvalue()
                        else:
                            initial_value = None
                        address = var.getaddress()
                        if address:
                            located = True
                        variables.append((vartype_content["value"].getname(), var.getname(), address, initial_value))
                else:
                    initial = var.getinitialValue()
                    if initial:
                        initial_value = initial.getvalue()
                    else:
                        initial_value = None
                    address = var.getaddress()
                    if address:
                        located = True
                    if vartype_content["name"] in ["string", "wstring"]:
                        variables.append((vartype_content["name"].upper(), var.getname(), address, initial_value))
                    else:
                        variables.append((vartype_content["name"], var.getname(), address, initial_value))
            if len(variables) > 0:
                self.Interface.append((varTypeNames[varlist["name"]], varlist["value"].getretain(), 
                            varlist["value"].getconstant(), located, variables))
    
    def GenerateConnectionTypes(self, pou):
        body = pou.getbody()
        body_content = body.getcontent()
        body_type = body_content["name"]
        if body_type in ["FBD", "LD", "SFC"]:
            for instance in body.getcontentInstances():
                if isinstance(instance, (plcopen.fbdObjects_inVariable, plcopen.fbdObjects_outVariable, plcopen.fbdObjects_inOutVariable)):
                    expression = instance.getexpression()
                    var_type = self.GetVariableType(expression)
                    if expression == pou.getname():
                        returntype_content = pou.interface.getreturnType().getcontent()
                        if returntype_content["name"] == "derived":
                            var_type = returntype_content["value"].getname()
                        elif returntype_content["name"] in ["string", "wstring"]:
                            var_type = returntype_content["name"].upper()
                        else:
                            var_type = returntype_content["name"]
                    elif var_type is None:
                        var_type = expression.split("#")[0]
                    if isinstance(instance, (plcopen.fbdObjects_inVariable, plcopen.fbdObjects_inOutVariable)):
                        self.ConnectionTypes[instance.connectionPointOut] = var_type
                    if isinstance(instance, (plcopen.fbdObjects_outVariable, plcopen.fbdObjects_inOutVariable)):
                        self.ConnectionTypes[instance.connectionPointIn] = var_type
                        connected = self.GetConnectedConnection(instance.connectionPointIn, body)
                        if connected and connected not in self.ConnectionTypes:
                            for connection in self.ExtractRelatedConnections(connected):
                                self.ConnectionTypes[connection] = var_type
                elif isinstance(instance, (plcopen.ldObjects_contact, plcopen.ldObjects_coil)):
                    self.ConnectionTypes[instance.connectionPointOut] = "BOOL"
                    self.ConnectionTypes[instance.connectionPointIn] = "BOOL"
                    connected = self.GetConnectedConnection(instance.connectionPointIn, body)
                    if connected and connected not in self.ConnectionTypes:
                        for connection in self.ExtractRelatedConnections(connected):
                            self.ConnectionTypes[connection] = "BOOL"
                elif isinstance(instance, plcopen.ldObjects_leftPowerRail):
                    for connection in instance.getconnectionPointOut():
                        self.ConnectionTypes[connection] = "BOOL"
                elif isinstance(instance, plcopen.ldObjects_rightPowerRail):
                    for connection in instance.getconnectionPointIn():
                        self.ConnectionTypes[connection] = "BOOL"
                        connected = self.GetConnectedConnection(connection, body)
                        if connected and connected not in self.ConnectionTypes:
                            for connection in self.ExtractRelatedConnections(connected):
                                self.ConnectionTypes[connection] = "BOOL"
                elif isinstance(instance, plcopen.sfcObjects_transition):
                    content = instance.condition.getcontent()
                    if content["name"] == "connection" and len(content["value"]) == 1:
                        connected = self.GetLinkedConnection(content["value"][0], body)
                        if connected and connected not in self.ConnectionTypes:
                            for connection in self.ExtractRelatedConnections(connected):
                                self.ConnectionTypes[connection] = "BOOL"
                elif isinstance(instance, plcopen.fbdObjects_block):
                    block_infos = GetBlockType(instance.gettypeName())
                    undefined = {}
                    for variable in instance.outputVariables.getvariable():
                        output_name = variable.getformalParameter()
                        for oname, otype, oqualifier in block_infos["outputs"]:
                            if output_name == oname and variable.connectionPointOut not in self.ConnectionTypes:
                                if otype.startswith("ANY"):
                                    if otype not in undefined:
                                        undefined[otype] = []
                                    undefined[otype].append(variable.connectionPointOut)
                                else:
                                    for connection in self.ExtractRelatedConnections(variable.connectionPointOut):
                                        self.ConnectionTypes[connection] = otype
                    for variable in instance.inputVariables.getvariable():
                        input_name = variable.getformalParameter()
                        for iname, itype, iqualifier in block_infos["inputs"]:
                            if input_name == iname:
                                connected = self.GetConnectedConnection(variable.connectionPointIn, body)
                                if itype.startswith("ANY"):
                                    if itype not in undefined:
                                        undefined[itype] = []
                                    undefined[itype].append(variable.connectionPointIn)
                                    if connected:
                                        undefined[itype].append(connected)
                                else:
                                    self.ConnectionTypes[variable.connectionPointIn] = itype
                                    if connected and connected not in self.ConnectionTypes:
                                        for connection in self.ExtractRelatedConnections(connected):
                                            self.ConnectionTypes[connection] = itype
                    for var_type, connections in undefined.items():
                        related = []
                        for connection in connections:
                            if connection in self.ConnectionTypes:
                                var_type = self.ConnectionTypes[connection]
                            else:
                                related.extend(self.ExtractRelatedConnections(connection))
                        if var_type.startswith("ANY") and len(related) > 0:
                            self.RelatedConnections.append(related)
                        else:
                            for connection in related:
                                self.ConnectionTypes[connection] = var_type
                                    
    def GenerateProgram(self, pou):
        body = pou.getbody()
        body_content = body.getcontent()
        body_type = body_content["name"]
        if body_type in ["IL","ST"]:
            self.Program = ReIndentText(body_content["value"].gettext(), 2)
        elif body_type == "FBD":
            orderedInstances = []
            otherInstances = []
            for instance in body.getcontentInstances():
                if isinstance(instance, (plcopen.fbdObjects_outVariable, plcopen.fbdObjects_inOutVariable, plcopen.fbdObjects_block)):
                    executionOrderId = instance.getexecutionOrderId()
                    if executionOrderId > 0:
                        orderedInstances.append((executionOrderId, instance))
                    else:
                        otherInstances.append(instance)
                elif isinstance(instance, plcopen.commonObjects_connector):
                    otherInstances.append(instance)
            orderedInstances.sort()
            instances = [instance for (executionOrderId, instance) in orderedInstances] + otherInstances
            for instance in instances:
                if isinstance(instance, (plcopen.fbdObjects_outVariable, plcopen.fbdObjects_inOutVariable)):
                    var = instance.getexpression()
                    connections = instance.connectionPointIn.getconnections()
                    if connections and len(connections) == 1:
                        expression = self.ComputeFBDExpression(body, connections[0])
                        self.Program += "  %s := %s;\n"%(var, expression)
                elif isinstance(instance, plcopen.fbdObjects_block):
                    block_type = instance.gettypeName()
                    self.GeneratePouProgram(block_type)
                    block_infos = GetBlockType(block_type)
                    block_infos["generate"](self, instance, body, None)
                elif isinstance(instance, plcopen.commonObjects_connector):
                    connector = instance.getname()
                    if self.ComputedConnectors.get(connector, None):
                        continue 
                    connections = instance.connectionPointIn.getconnections()
                    if connections and len(connections) == 1:
                        self.ComputedConnectors[connector] = self.ComputeFBDExpression(body, connections[0])
        elif body_type == "LD":
            for instance in body.getcontentInstances():
                if isinstance(instance, plcopen.ldObjects_coil):
                    paths = self.GenerateLDPaths(instance.connectionPointIn.getconnections(), body)
                    if len(paths) > 0:
                        paths = tuple(paths)
                    else:
                        paths = paths[0] 
                    variable = self.ExtractModifier(instance, instance.getvariable())
                    expression = self.ComputeLDExpression(paths, True)
                    self.Program += "  %s := %s;\n"%(variable, expression)
        elif body_type == "SFC":
            for instance in body.getcontentInstances():
                if isinstance(instance, plcopen.sfcObjects_step):
                    self.GenerateSFCStep(instance, pou)
                elif isinstance(instance, plcopen.commonObjects_actionBlock):
                    self.GenerateSFCStepActions(instance, pou)
                elif isinstance(instance, plcopen.sfcObjects_transition):
                    self.GenerateSFCTransition(instance, pou)
                elif isinstance(instance, plcopen.sfcObjects_jumpStep):
                    self.GenerateSFCJump(instance, pou)
            if len(self.InitialSteps) > 0 and self.SFCComputedBlocks != "":
                action_name = "COMPUTE_FUNCTION_BLOCKS"
                action_infos = {"qualifier" : "S", "content" : action_name}
                self.SFCNetworks["Steps"][self.InitialSteps[0]]["actions"].append(action_infos)
                self.SFCNetworks["Actions"][action_name] = ReIndentText(self.SFCComputedBlocks, 4)
                self.Program = ""
            for initialstep in self.InitialSteps:
                self.ComputeSFCStep(initialstep)
    
    def ComputeFBDExpression(self, body, link, order = False):
        localid = link.getrefLocalId()
        instance = body.getcontentInstance(localid)
        if isinstance(instance, (plcopen.fbdObjects_inVariable, plcopen.fbdObjects_inOutVariable)):
            return instance.getexpression()
        elif isinstance(instance, plcopen.fbdObjects_block):
            block_type = instance.gettypeName()
            self.GeneratePouProgram(block_type)
            block_infos = GetBlockType(block_type)
            return block_infos["generate"](self, instance, body, link, order)
        elif isinstance(instance, plcopen.commonObjects_continuation):
            name = instance.getname()
            computed_value = self.ComputedConnectors.get(name, None)
            if computed_value != None:
                return computed_value
            for tmp_instance in body.getcontentInstances():
                if isinstance(tmp_instance, plcopen.commonObjects_connector):
                    if tmp_instance.getname() == name:
                        connections = tmp_instance.connectionPointIn.getconnections()
                        if connections and len(connections) == 1:
                            expression = self.ComputeFBDExpression(body, connections[0], order)
                            self.ComputedConnectors[name] = expression
                            return expression
            raise ValueError, "No connector found"

    def GenerateLDPaths(self, connections, body):
        paths = []
        for connection in connections:
            localId = connection.getrefLocalId()
            next = body.getcontentInstance(localId)
            if isinstance(next, plcopen.ldObjects_leftPowerRail):
                paths.append(None)
            elif isinstance(next, plcopen.fbdObjects_block):
                block_type = next.gettypeName()
                self.GeneratePouProgram(block_type)
                block_infos = GetBlockType(block_type)
                paths.append(block_infos["generate"](self, next, body, connection))
            else:
                variable = self.ExtractModifier(next, next.getvariable())
                result = self.GenerateLDPaths(next.connectionPointIn.getconnections(), body)
                if len(result) > 1:
                    paths.append([variable, tuple(result)])
                elif type(result[0]) == ListType:
                    paths.append([variable] + result[0])
                elif result[0]:
                    paths.append([variable, result[0]])
                else:
                    paths.append(variable)
        return paths

    def GetNetworkType(self, connections, body):
        network_type = "FBD"
        for connection in connections:
            localId = connection.getrefLocalId()
            next = body.getcontentInstance(localId)
            if isinstance(next, plcopen.ldObjects_leftPowerRail) or isinstance(next, plcopen.ldObjects_contact):
                return "LD"
            elif isinstance(next, plcopen.fbdObjects_block):
                 for variable in next.inputVariables.getvariable():
                     result = self.GetNetworkType(variable.connectionPointIn.getconnections(), body)
                     if result != "FBD":
                         return result
            elif isinstance(next, plcopen.fbdObjects_inVariable):
                return "FBD"
            elif isinstance(next, plcopen.fbdObjects_inOutVariable):
                return self.GetNetworkType(next.connectionPointIn.getconnections(), body)
            else:
                return None
        return "FBD"
    
    def ExtractDivergenceInput(self, divergence, pou):
        connectionPointIn = divergence.getconnectionPointIn()
        if connectionPointIn:
            connections = connectionPointIn.getconnections()
            if len(connections) == 1:
                instanceLocalId = connections[0].getrefLocalId()
                return pou.body.getcontentInstance(instanceLocalId)
        return None

    def ExtractConvergenceInputs(self, convergence, pou):
        instances = []
        for connectionPointIn in convergence.getconnectionPointIn():
            connections = connectionPointIn.getconnections()
            if len(connections) == 1:
                instanceLocalId = connections[0].getrefLocalId()
                instances.append(pou.body.getcontentInstance(instanceLocalId))
        return instances

    def GenerateSFCStep(self, step, pou):
        step_name = step.getname()
        if step_name not in self.SFCNetworks["Steps"].keys():
            if step.getinitialStep():
                self.InitialSteps.append(step_name)
            step_infos = {"initial" : step.getinitialStep(), "transitions" : [], "actions" : []}
            if step.connectionPointIn:
                instances = []
                connections = step.connectionPointIn.getconnections()
                if len(connections) == 1:
                    instanceLocalId = connections[0].getrefLocalId()
                    instance = pou.body.getcontentInstance(instanceLocalId)
                    if isinstance(instance, plcopen.sfcObjects_transition):
                        instances.append(instance)
                    elif isinstance(instance, plcopen.sfcObjects_selectionConvergence):
                        instances.extend(self.ExtractConvergenceInputs(instance, pou))
                    elif isinstance(instance, plcopen.sfcObjects_simultaneousDivergence):
                        transition = self.ExtractDivergenceInput(instance, pou)
                        if transition:
                            if isinstance(transition, plcopen.sfcObjects_transition):
                                instances.append(transition)
                            elif isinstance(transition, plcopen.sfcObjects_selectionConvergence):
                                instances.extend(self.ExtractConvergenceInputs(transition, pou))
                for instance in instances:
                    self.GenerateSFCTransition(instance, pou)
                    if instance in self.SFCNetworks["Transitions"].keys():
                        self.SFCNetworks["Transitions"][instance]["to"].append(step_name)
            self.SFCNetworks["Steps"][step_name] = step_infos
    
    def GenerateSFCJump(self, jump, pou):
        jump_target = jump.gettargetName()
        if jump.connectionPointIn:
            instances = []
            connections = jump.connectionPointIn.getconnections()
            if len(connections) == 1:
                instanceLocalId = connections[0].getrefLocalId()
                instance = pou.body.getcontentInstance(instanceLocalId)
                if isinstance(instance, plcopen.sfcObjects_transition):
                    instances.append(instance)
                elif isinstance(instance, plcopen.sfcObjects_selectionConvergence):
                    instances.extend(self.ExtractConvergenceInputs(instance, pou))
                elif isinstance(instance, plcopen.sfcObjects_simultaneousDivergence):
                    transition = self.ExtractDivergenceInput(instance, pou)
                    if transition:
                        if isinstance(transition, plcopen.sfcObjects_transition):
                            instances.append(transition)
                        elif isinstance(transition, plcopen.sfcObjects_selectionConvergence):
                            instances.extend(self.ExtractConvergenceInputs(transition, pou))
            for instance in instances:
                self.GenerateSFCTransition(instance, pou)
                if instance in self.SFCNetworks["Transitions"].keys():
                    self.SFCNetworks["Transitions"][instance]["to"].append(jump_target)
    
    def GenerateSFCStepActions(self, actionBlock, pou):
        connections = actionBlock.connectionPointIn.getconnections()
        if len(connections) == 1:
            stepLocalId = connections[0].getrefLocalId()
            step = pou.body.getcontentInstance(stepLocalId)
            self.GenerateSFCStep(step, pou)
            step_name = step.getname()
            if step_name in self.SFCNetworks["Steps"].keys():
                actions = actionBlock.getactions()
                for action in actions:
                    action_infos = {"qualifier" : action["qualifier"], "content" : action["value"]}
                    if "duration" in action:
                        action_infos["duration"] = action["duration"]
                    if "indicator" in action:
                        action_infos["indicator"] = action["indicator"]
                    if action["type"] == "reference":
                        self.GenerateSFCAction(action["value"], pou)
                    else:
                        action_name = "INLINE%d"%self.GetActionNumber()
                        self.SFCNetworks["Actions"][action_name] = "    %s\n"%action["value"]
                        action_infos["content"] = action_name
                    self.SFCNetworks["Steps"][step_name]["actions"].append(action_infos)
    
    def GenerateSFCAction(self, action_name, pou):
        if action_name not in self.SFCNetworks["Actions"].keys():
            actionContent = pou.getaction(action_name)
            if actionContent:
                actionType = actionContent.getbodyType()
                actionBody = actionContent.getbody()
                if actionType in ["ST", "IL"]:
                    self.SFCNetworks["Actions"][action_name] = ReIndentText(actionContent.gettext(), 4)
                elif actionType == "FBD":
                    for instance in actionBody.getcontentInstances():
                        if isinstance(instance, plcopen.fbdObjects_outVariable):
                            var = instance.getexpression()
                            connections = instance.connectionPointIn.getconnections()
                            if connections and len(connections) == 1:
                                expression = self.ComputeFBDExpression(actionBody, connections[0])
                                action_content = self.Program + "  %s := %s;\n"%(var, expression)
                                self.Program = ""
                                self.SFCNetworks["Actions"][action_name] = ReIndentText(action_content, 4)
                elif actionType == "LD":
                    for instance in actionbody.getcontentInstances():
                        if isinstance(instance, plcopen.ldObjects_coil):
                            paths = self.GenerateLDPaths(instance.connectionPointIn.getconnections(), actionBody)
                            variable = self.ExtractModifier(instance, instance.getvariable())
                            expression = self.ComputeLDExpression(paths, True)
                            action_content = self.Program + "  %s := %s;\n"%(variable, expression)
                            self.Program = ""
                            self.SFCNetworks["Actions"][action_name] = ReIndentText(action_content, 4)
    
    def GenerateSFCTransition(self, transition, pou):
        if transition not in self.SFCNetworks["Transitions"].keys():
            steps = []
            connections = transition.connectionPointIn.getconnections()
            if len(connections) == 1:
                instanceLocalId = connections[0].getrefLocalId()
                instance = pou.body.getcontentInstance(instanceLocalId)
                if isinstance(instance, plcopen.sfcObjects_step):
                    steps.append(instance)
                elif isinstance(instance, plcopen.sfcObjects_selectionDivergence):
                    step = self.ExtractDivergenceInput(instance, pou)
                    if step:
                        if isinstance(step, plcopen.sfcObjects_step):
                            steps.append(step)
                        elif isinstance(step, plcopen.sfcObjects_simultaneousConvergence):
                            steps.extend(self.ExtractConvergenceInputs(step, pou))
                elif isinstance(instance, plcopen.sfcObjects_simultaneousConvergence):
                    steps.extend(self.ExtractConvergenceInputs(instance, pou))
            transition_infos = {"priority": transition.getpriority(), "from": [], "to" : []}
            transitionValues = transition.getconditionContent()
            if transitionValues["type"] == "inline":
                transition_infos["content"] = "\n    := %s;\n"%transitionValues["value"]
            elif transitionValues["type"] == "reference":
                transitionContent = pou.gettransition(transitionValues["value"])
                transitionType = transitionContent.getbodyType()
                transitionBody = transitionContent.getbody()
                if transitionType == "IL":
                    transition_infos["content"] = ":\n%s"%ReIndentText(transitionBody.gettext(), 4)
                elif transitionType == "ST":
                    transition_infos["content"] = "\n%s"%ReIndentText(transitionBody.gettext(), 4)
                elif transitionType == "FBD":
                    for instance in transitionBody.getcontentInstances():
                        if isinstance(instance, plcopen.fbdObjects_outVariable):
                            connections = instance.connectionPointIn.getconnections()
                            if connections and len(connections) == 1:
                                expression = self.ComputeFBDExpression(transitionBody, connections[0])
                                transition_infos["content"] = "\n    := %s;\n"%expression
                                self.SFCComputedBlocks += self.Program
                                self.Program = ""
                elif transitionType == "LD":
                    for instance in transitionBody.getcontentInstances():
                        if isinstance(instance, plcopen.ldObjects_coil):
                            paths = self.GenerateLDPaths(instance.connectionPointIn.getconnections(), transitionBody)
                            expression = self.ComputeLDExpression(paths, True)
                            transition_infos["content"] = "\n    := %s;\n"%expression
                            self.SFCComputedBlocks += self.Program
                            self.Program = ""
            elif transitionValues["type"] == "connection":
                body = pou.getbody()
                connections = transition.getconnections()
                network_type = self.GetNetworkType(connections, body)
                if network_type == None:
                    raise Exception
                if len(connections) > 1 or network_type == "LD":
                    paths = self.GenerateLDPaths(connections, body)
                    expression = self.ComputeLDExpression(paths, True)
                    transition_infos["content"] = "\n    := %s;\n"%expression
                    self.SFCComputedBlocks += self.Program
                    self.Program = ""
                else:
                    expression = self.ComputeFBDExpression(body, connections[0])
                    transition_infos["content"] = "\n    := %s;\n"%expression
                    self.SFCComputedBlocks += self.Program
                    self.Program = ""
            for step in steps:
                self.GenerateSFCStep(step, pou)
                step_name = step.getname()
                if step_name in self.SFCNetworks["Steps"].keys():
                    transition_infos["from"].append(step_name)
                    self.SFCNetworks["Steps"][step_name]["transitions"].append(transition)
            self.SFCNetworks["Transitions"][transition] = transition_infos

    def ComputeSFCStep(self, step_name):
        if step_name in self.SFCNetworks["Steps"].keys():
            step_infos = self.SFCNetworks["Steps"].pop(step_name)
            if step_infos["initial"]:
                self.Program += "  INITIAL_STEP %s:\n"%step_name
            else:
                self.Program += "  STEP %s:\n"%step_name
            actions = []
            for action_infos in step_infos["actions"]:
                actions.append(action_infos["content"])
                self.Program += "    %(content)s(%(qualifier)s"%action_infos
                if "duration" in action_infos:
                    self.Program += ", %(duration)s"%action_infos
                if "indicator" in action_infos:
                    self.Program += ", %(indicator)s"%action_infos
                self.Program += ");\n"
            self.Program += "  END_STEP\n\n"
            for action in actions:
                self.ComputeSFCAction(action)
            for transition in step_infos["transitions"]:
                self.ComputeSFCTransition(transition)
                
    def ComputeSFCAction(self, action_name):
        if action_name in self.SFCNetworks["Actions"].keys():
            action_content = self.SFCNetworks["Actions"].pop(action_name)
            self.Program += "  ACTION %s:\n%s  END_ACTION\n\n"%(action_name, action_content)
    
    def ComputeSFCTransition(self, transition):
        if transition in self.SFCNetworks["Transitions"].keys():
            transition_infos = self.SFCNetworks["Transitions"].pop(transition)
            self.Program += "  TRANSITION"
            if transition_infos["priority"] != None:
                self.Program += " (PRIORITY := %d)"%transition_infos["priority"]
            self.Program += " FROM "
            if len(transition_infos["from"]) > 1:
                self.Program += "(%s)"%", ".join(transition_infos["from"])
            else:
                self.Program += "%s"%transition_infos["from"][0]
            self.Program += " TO "
            if len(transition_infos["to"]) > 1:
                self.Program += "(%s)"%", ".join(transition_infos["to"])
            else:
                self.Program += "%s"%transition_infos["to"][0]
            self.Program += transition_infos["content"]
            self.Program += "  END_TRANSITION\n\n"
            for step_name in transition_infos["to"]:
                self.ComputeSFCStep(step_name)
        
    def ComputeLDExpression(self, paths, first = False):
        if type(paths) == TupleType:
            if None in paths:
                return "TRUE"
            else:
                var = [self.ComputeLDExpression(path) for path in paths]
                if first:
                    return " OR ".join(var)
                else:
                    return "(%s)"%" OR ".join(var)
        elif type(paths) == ListType:
            var = [self.ComputeLDExpression(path) for path in paths]
            return " AND ".join(var)
        else:
            return paths

    def ExtractModifier(self, variable, text):
        if variable.getnegated():
            return "NOT(%s)"%text
        else:
            edge = variable.getedge()
            if edge == "rising":
                return self.AddTrigger("R_TRIG", text)
            elif edge == "falling":
                return self.AddTrigger("F_TRIG", text)
        return text
    
    def AddTrigger(self, edge, text):
        if self.Interface[-1][0] != "VAR" or self.Interface[-1][1] or self.Interface[-1][2] or self.Interface[-1][3]:
            self.Interface.append(("VAR", False, False, False, []))
        i = 1
        name = "%s%d"%(edge, i)
        while self.IsAlreadyDefined(name):
            i += 1
            name = "%s%d"%(edge, i)
        self.Interface[-1][4].append((edge, name, None, None))
        self.Program += "  %s(CLK := %s);\n"%(name, text)
        return "%s.Q"%name
    
    def GenerateSTProgram(self):
        if self.ReturnType:
            program = "%s %s : %s\n"%(self.Type, self.Name, self.ReturnType)
        else:
            program = "%s %s\n"%(self.Type, self.Name)
        for list_type, retain, constant, located, variables in self.Interface:
            program += "  %s"%list_type
            if retain:
                program += " RETAIN"
            if constant:
                program += " CONSTANT"
            program += "\n"
            for var_type, var_name, var_address, var_initial in variables:
                program += "    "
                if var_name:
                    program += "%s "%var_name
                if var_address != None:
                    program += "AT %s "%var_address
                program += ": %s"%var_type
                if var_initial != None:
                    value = {"TRUE":"0","FALSE":"1"}.get(str(var_initial).upper(), str(var_initial))
                    if var_type == "STRING":
                        program += " := '%s'"%value
                    elif var_type == "WSTRING":
                        program += " := \"%s\""%value
                    else:
                        program += " := %s"%value
                program += ";\n"
            program += "  END_VAR\n"
        program += "\n"
        program += self.Program
        program += "END_%s\n\n"%self.Type
        return program

    def GeneratePouProgram(self, pou_name):
        GeneratePouProgram(pou_name)

def GenerateCurrentProgram(project):
    global currentProject, currentProgram
    currentProject = project
    currentProgram = ""
    for datatype in project.getdataTypes():
        datatypeComputed[datatype.getname()] = False
    for pou in project.getpous():
        pouComputed[pou.getname()] = False
    if len(datatypeComputed) > 0:
        currentProgram += "TYPE\n"
        for datatype_name in datatypeComputed.keys():
            GenerateDataType(datatype_name)
        currentProgram += "END_TYPE\n\n"
    for pou_name in pouComputed.keys():
        GeneratePouProgram(pou_name)
    for config in project.getconfigurations():
        currentProgram += GenerateConfiguration(config)
    return currentProgram