PLCGenerator.py
author lbessard
Wed, 17 Oct 2007 17:50:27 +0200
changeset 108 9aa1fdfb7cb2
parent 104 a9b8916d906d
child 125 394d9f168258
permissions -rw-r--r--
A lots of bugs fixed
#!/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 = ""
pouComputed = {}

def ReIndentText(text, nb_spaces):
    compute = ""
    lines = text.splitlines()
    if len(lines) > 0:
        spaces = 0
        while lines[0][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 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().getValue()
        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.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():
            var_type = var.getType().getValue()
            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():
            var_type = var.getType().getValue()
            resrce += "      %s "%var.getName()
            address = var.getAddress()
            if address:
                resrce += "AT %s "%address
            resrce += ": %s"%var.getType().getValue()
            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.priority.getValue()))
        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.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 GenerateInterface(self, interface):
        if self.Type == "FUNCTION":
            self.ReturnType = interface.getReturnType().getValue()
        for varlist in interface.getContent():
            variables = []
            located = False
            for var in varlist["value"].getVariable():
                type = var.getType().getValue()
                if not isinstance(type, (StringType, UnicodeType)):
                    type = type.getName()
                    GeneratePouProgram(type)
                    blocktype = GetBlockType(type)
                    if blocktype:
                        variables.extend(blocktype["initialise"](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((type, var.getName(), address, initial_value))
            if len(variables) > 0:
                self.Interface.append((varTypeNames[varlist["name"]], varlist["value"].getRetain(), 
                            varlist["value"].getConstant(), located, variables))
    
    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":
            for instance in body.getContentInstances():
                if isinstance(instance, (plcopen.outVariable, plcopen.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.block):
                    type = instance.getTypeName()
                    block_infos = GetBlockType(type)
                    block_infos["generate"](self, instance, body, None)
                elif isinstance(instance, plcopen.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.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.step):
                    self.GenerateSFCStep(instance, pou)
                elif isinstance(instance, plcopen.actionBlock):
                    self.GenerateSFCStepActions(instance, pou)
                elif isinstance(instance, plcopen.transition):
                    self.GenerateSFCTransition(instance, pou)
                elif isinstance(instance, plcopen.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):
        localid = link.getRefLocalId()
        instance = body.getContentInstance(localid)
        if isinstance(instance, (plcopen.inVariable, plcopen.inOutVariable)):
            return instance.getExpression()
        elif isinstance(instance, plcopen.block):
            block_type = instance.getTypeName()
            block_infos = GetBlockType(block_type)
            return block_infos["generate"](self, instance, body, link)
        elif isinstance(instance, plcopen.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.connector):
                    if tmp_instance.getName() == name:
                        connections = tmp_instance.connectionPointIn.getConnections()
                        if connections and len(connections) == 1:
                            expression = self.ComputeFBDExpression(body, connections[0])
                            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.leftPowerRail):
                paths.append(None)
            elif isinstance(next, plcopen.block):
                block_type = next.getTypeName()
                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.leftPowerRail) or isinstance(next, plcopen.contact):
                return "LD"
            elif isinstance(next, plcopen.block):
                 for variable in next.inputVariables.getVariable():
                     result = self.GetNetworkType(variable.connectionPointIn.getConnections(), body)
                     if result != "FBD":
                         return result
            elif isinstance(next, plcopen.inVariable):
                return "FBD"
            elif isinstance(next, plcopen.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.transition):
                        instances.append(instance)
                    elif isinstance(instance, plcopen.selectionConvergence):
                        instances.extend(self.ExtractConvergenceInputs(instance, pou))
                    elif isinstance(instance, plcopen.simultaneousDivergence):
                        transition = self.ExtractDivergenceInput(instance, pou)
                        if transition:
                            if isinstance(transition, plcopen.transition):
                                instances.append(transition)
                            elif isinstance(transition, plcopen.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.transition):
                    instances.append(instance)
                elif isinstance(instance, plcopen.selectionConvergence):
                    instances.extend(self.ExtractConvergenceInputs(instance, pou))
                elif isinstance(instance, plcopen.simultaneousDivergence):
                    transition = self.ExtractDivergenceInput(instance, pou)
                    if transition:
                        if isinstance(transition, plcopen.transition):
                            instances.append(transition)
                        elif isinstance(transition, plcopen.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.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.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.step):
                    steps.append(instance)
                elif isinstance(instance, plcopen.selectionDivergence):
                    step = self.ExtractDivergenceInput(instance, pou)
                    if step:
                        if isinstance(step, plcopen.step):
                            steps.append(step)
                        elif isinstance(step, plcopen.simultaneousConvergence):
                            steps.extend(self.ExtractConvergenceInputs(step, pou))
                elif isinstance(instance, plcopen.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.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.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:
                if edge.getValue() == "rising":
                    return self.AddTrigger("R_TRIG", text)
                elif edge.getValue() == "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 pou in project.getPous():
        pouComputed[pou.getName()] = False
    for pou_name in pouComputed.keys():
        GeneratePouProgram(pou_name)
    for config in project.getConfigurations():
        currentProgram += GenerateConfiguration(config)
    return currentProgram