PLCGenerator.py
changeset 814 5743cbdff669
child 822 050045c32d98
equal deleted inserted replaced
813:1460273f40ed 814:5743cbdff669
       
     1 #!/usr/bin/env python
       
     2 # -*- coding: utf-8 -*-
       
     3 
       
     4 #This file is part of PLCOpenEditor, a library implementing an IEC 61131-3 editor
       
     5 #based on the plcopen standard. 
       
     6 #
       
     7 #Copyright (C) 2007: Edouard TISSERANT and Laurent BESSARD
       
     8 #
       
     9 #See COPYING file for copyrights details.
       
    10 #
       
    11 #This library is free software; you can redistribute it and/or
       
    12 #modify it under the terms of the GNU General Public
       
    13 #License as published by the Free Software Foundation; either
       
    14 #version 2.1 of the License, or (at your option) any later version.
       
    15 #
       
    16 #This library is distributed in the hope that it will be useful,
       
    17 #but WITHOUT ANY WARRANTY; without even the implied warranty of
       
    18 #MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
       
    19 #General Public License for more details.
       
    20 #
       
    21 #You should have received a copy of the GNU General Public
       
    22 #License along with this library; if not, write to the Free Software
       
    23 #Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
       
    24 
       
    25 from plcopen import plcopen
       
    26 from plcopen.structures import *
       
    27 from types import *
       
    28 import re
       
    29 
       
    30 # Dictionary associating PLCOpen variable categories to the corresponding 
       
    31 # IEC 61131-3 variable categories
       
    32 varTypeNames = {"localVars" : "VAR", "tempVars" : "VAR_TEMP", "inputVars" : "VAR_INPUT", 
       
    33                 "outputVars" : "VAR_OUTPUT", "inOutVars" : "VAR_IN_OUT", "externalVars" : "VAR_EXTERNAL",
       
    34                 "globalVars" : "VAR_GLOBAL", "accessVars" : "VAR_ACCESS"}
       
    35 
       
    36 
       
    37 # Dictionary associating PLCOpen POU categories to the corresponding 
       
    38 # IEC 61131-3 POU categories
       
    39 pouTypeNames = {"function" : "FUNCTION", "functionBlock" : "FUNCTION_BLOCK", "program" : "PROGRAM"}
       
    40 
       
    41 
       
    42 errorVarTypes = {
       
    43     "VAR_INPUT": "var_input",
       
    44     "VAR_OUTPUT": "var_output",
       
    45     "VAR_INOUT": "var_inout",
       
    46 }
       
    47 
       
    48 # Helper function for reindenting text
       
    49 def ReIndentText(text, nb_spaces):
       
    50     compute = ""
       
    51     lines = text.splitlines()
       
    52     if len(lines) > 0:
       
    53         line_num = 0
       
    54         while line_num < len(lines) and len(lines[line_num].strip()) == 0:
       
    55             line_num += 1
       
    56         if line_num < len(lines):
       
    57             spaces = 0
       
    58             while lines[line_num][spaces] == " ":
       
    59                 spaces += 1
       
    60             indent = ""
       
    61             for i in xrange(spaces, nb_spaces):
       
    62                 indent += " "
       
    63             for line in lines:
       
    64                 if line != "":
       
    65                     compute += "%s%s\n"%(indent, line)
       
    66                 else:
       
    67                     compute += "\n"
       
    68     return compute
       
    69 
       
    70 def SortInstances(a, b):
       
    71     ax, ay = int(a.getx()), int(a.gety())
       
    72     bx, by = int(b.getx()), int(b.gety())
       
    73     if abs(ay - by) < 10:
       
    74         return cmp(ax, bx)
       
    75     else:
       
    76         return cmp(ay, by)
       
    77 
       
    78 REAL_MODEL = re.compile("[0-9]+\.[0-9]+$")
       
    79 INTEGER_MODEL = re.compile("[0-9]+$")
       
    80 
       
    81 #-------------------------------------------------------------------------------
       
    82 #                  Specific exception for PLC generating errors
       
    83 #-------------------------------------------------------------------------------
       
    84 
       
    85 
       
    86 class PLCGenException(Exception):
       
    87     pass
       
    88 
       
    89 
       
    90 #-------------------------------------------------------------------------------
       
    91 #                           Generator of PLC program
       
    92 #-------------------------------------------------------------------------------
       
    93 
       
    94 
       
    95 class ProgramGenerator:
       
    96 
       
    97     # Create a new PCL program generator
       
    98     def __init__(self, controler, project, errors, warnings):
       
    99         # Keep reference of the controler and project
       
   100         self.Controler = controler
       
   101         self.Project = project
       
   102         # Reset the internal variables used to generate PLC programs
       
   103         self.Program = []
       
   104         self.DatatypeComputed = {}
       
   105         self.PouComputed = {}
       
   106         self.Errors = errors
       
   107         self.Warnings = warnings
       
   108 
       
   109     # Compute value according to type given
       
   110     def ComputeValue(self, value, var_type):
       
   111         base_type = self.Controler.GetBaseType(var_type)
       
   112         if base_type == "STRING":
       
   113             return "'%s'"%value
       
   114         elif base_type == "WSTRING":
       
   115             return "\"%s\""%value
       
   116         return value
       
   117 
       
   118     # Generate a data type from its name
       
   119     def GenerateDataType(self, datatype_name):
       
   120         # Verify that data type hasn't been generated yet
       
   121         if not self.DatatypeComputed.get(datatype_name, True):
       
   122             # If not mark data type as computed
       
   123             self.DatatypeComputed[datatype_name] = True
       
   124             
       
   125             # Getting datatype model from project
       
   126             datatype = self.Project.getdataType(datatype_name)
       
   127             tagname = self.Controler.ComputeDataTypeName(datatype.getname())
       
   128             datatype_def = [("  ", ()), 
       
   129                             (datatype.getname(), (tagname, "name")),
       
   130                             (" : ", ())]
       
   131             basetype_content = datatype.baseType.getcontent()
       
   132             # Data type derived directly from a string type 
       
   133             if basetype_content["name"] in ["string", "wstring"]:
       
   134                 datatype_def += [(basetype_content["name"].upper(), (tagname, "base"))]
       
   135             # Data type derived directly from a user defined type 
       
   136             elif basetype_content["name"] == "derived":
       
   137                 basetype_name = basetype_content["value"].getname()
       
   138                 self.GenerateDataType(basetype_name)
       
   139                 datatype_def += [(basetype_name, (tagname, "base"))]
       
   140             # Data type is a subrange
       
   141             elif basetype_content["name"] in ["subrangeSigned", "subrangeUnsigned"]:
       
   142                 base_type = basetype_content["value"].baseType.getcontent()
       
   143                 # Subrange derived directly from a user defined type 
       
   144                 if base_type["name"] == "derived":
       
   145                     basetype_name = base_type["value"].getname()
       
   146                     self.GenerateDataType(basetype_name)
       
   147                 # Subrange derived directly from an elementary type 
       
   148                 else:
       
   149                     basetype_name = base_type["name"]
       
   150                 min_value = basetype_content["value"].range.getlower()
       
   151                 max_value = basetype_content["value"].range.getupper()
       
   152                 datatype_def += [(basetype_name, (tagname, "base")),
       
   153                                  (" (", ()),
       
   154                                  ("%s"%min_value, (tagname, "lower")),
       
   155                                  ("..", ()),
       
   156                                  ("%s"%max_value, (tagname, "upper")),
       
   157                                  (")",())]
       
   158             # Data type is an enumerated type
       
   159             elif basetype_content["name"] == "enum":
       
   160                 values = [[(value.getname(), (tagname, "value", i))]
       
   161                           for i, value in enumerate(basetype_content["value"].values.getvalue())]
       
   162                 datatype_def += [("(", ())]
       
   163                 datatype_def += JoinList([(", ", ())], values)
       
   164                 datatype_def += [(")", ())]
       
   165             # Data type is an array
       
   166             elif basetype_content["name"] == "array":
       
   167                 base_type = basetype_content["value"].baseType.getcontent()
       
   168                 # Array derived directly from a user defined type 
       
   169                 if base_type["name"] == "derived":
       
   170                     basetype_name = base_type["value"].getname()
       
   171                     self.GenerateDataType(basetype_name)
       
   172                 # Array derived directly from a string type 
       
   173                 elif base_type["name"] in ["string", "wstring"]:
       
   174                     basetype_name = base_type["name"].upper()
       
   175                 # Array derived directly from an elementary type 
       
   176                 else:
       
   177                     basetype_name = base_type["name"]
       
   178                 dimensions = [[("%s"%dimension.getlower(), (tagname, "range", i, "lower")),
       
   179                                ("..", ()),
       
   180                                ("%s"%dimension.getupper(), (tagname, "range", i, "upper"))] 
       
   181                               for i, dimension in enumerate(basetype_content["value"].getdimension())]
       
   182                 datatype_def += [("ARRAY [", ())]
       
   183                 datatype_def += JoinList([(",", ())], dimensions)
       
   184                 datatype_def += [("] OF " , ()),
       
   185                                  (basetype_name, (tagname, "base"))]
       
   186             # Data type is a structure
       
   187             elif basetype_content["name"] == "struct":
       
   188                 elements = []
       
   189                 for i, element in enumerate(basetype_content["value"].getvariable()):
       
   190                     element_type = element.type.getcontent()
       
   191                     # Structure element derived directly from a user defined type 
       
   192                     if element_type["name"] == "derived":
       
   193                         elementtype_name = element_type["value"].getname()
       
   194                         self.GenerateDataType(elementtype_name)
       
   195                     # Structure element derived directly from a string type 
       
   196                     elif element_type["name"] in ["string", "wstring"]:
       
   197                         elementtype_name = element_type["name"].upper()
       
   198                     # Structure element derived directly from an elementary type 
       
   199                     else:
       
   200                         elementtype_name = element_type["name"]
       
   201                     element_text = [("\n    ", ()),
       
   202                                     (element.getname(), (tagname, "struct", i, "name")),
       
   203                                     (" : ", ()),
       
   204                                     (elementtype_name, (tagname, "struct", i, "type"))]
       
   205                     if element.initialValue is not None:
       
   206                         element_text.extend([(" := ", ()),
       
   207                                              (self.ComputeValue(element.initialValue.getvalue(), elementtype_name), (tagname, "struct", i, "initial value"))])
       
   208                     element_text.append((";", ()))
       
   209                     elements.append(element_text)
       
   210                 datatype_def += [("STRUCT", ())]
       
   211                 datatype_def += JoinList([("", ())], elements)
       
   212                 datatype_def += [("\n  END_STRUCT", ())]
       
   213             # Data type derived directly from a elementary type 
       
   214             else:
       
   215                 datatype_def += [(basetype_content["name"], (tagname, "base"))]
       
   216             # Data type has an initial value
       
   217             if datatype.initialValue is not None:
       
   218                 datatype_def += [(" := ", ()),
       
   219                                  (self.ComputeValue(datatype.initialValue.getvalue(), datatype_name), (tagname, "initial value"))]
       
   220             datatype_def += [(";\n", ())]
       
   221             self.Program += datatype_def
       
   222 
       
   223     # Generate a POU from its name
       
   224     def GeneratePouProgram(self, pou_name):
       
   225         # Verify that POU hasn't been generated yet
       
   226         if not self.PouComputed.get(pou_name, True):
       
   227             # If not mark POU as computed
       
   228             self.PouComputed[pou_name] = True
       
   229             
       
   230             # Getting POU model from project
       
   231             pou = self.Project.getpou(pou_name)
       
   232             pou_type = pou.getpouType()
       
   233             # Verify that POU type exists
       
   234             if pouTypeNames.has_key(pou_type):
       
   235                 # Create a POU program generator
       
   236                 pou_program = PouProgramGenerator(self, pou.getname(), pouTypeNames[pou_type], self.Errors, self.Warnings)
       
   237                 program = pou_program.GenerateProgram(pou)
       
   238                 self.Program += program
       
   239             else:
       
   240                 raise PLCGenException, _("Undefined pou type \"%s\"")%pou_type
       
   241     
       
   242     # Generate a POU defined and used in text
       
   243     def GeneratePouProgramInText(self, text):
       
   244         for pou_name in self.PouComputed.keys():
       
   245             model = re.compile("(?:^|[^0-9^A-Z])%s(?:$|[^0-9^A-Z])"%pou_name.upper())
       
   246             if model.search(text) is not None:
       
   247                 self.GeneratePouProgram(pou_name)
       
   248     
       
   249     # Generate a configuration from its model
       
   250     def GenerateConfiguration(self, configuration):
       
   251         tagname = self.Controler.ComputeConfigurationName(configuration.getname())
       
   252         config = [("\nCONFIGURATION ", ()),
       
   253                   (configuration.getname(), (tagname, "name")),
       
   254                   ("\n", ())]
       
   255         var_number = 0
       
   256         # Generate any global variable in configuration
       
   257         for varlist in configuration.getglobalVars():
       
   258             variable_type = errorVarTypes.get("VAR_GLOBAL", "var_local")
       
   259             # Generate variable block with modifier
       
   260             config += [("  VAR_GLOBAL", ())]
       
   261             if varlist.getconstant():
       
   262                 config += [(" CONSTANT", (tagname, variable_type, (var_number, var_number + len(varlist.getvariable())), "constant"))]
       
   263             elif varlist.getretain():
       
   264                 config += [(" RETAIN", (tagname, variable_type, (var_number, var_number + len(varlist.getvariable())), "retain"))]
       
   265             elif varlist.getnonretain():
       
   266                 config += [(" NON_RETAIN", (tagname, variable_type, (var_number, var_number + len(varlist.getvariable())), "non_retain"))]
       
   267             config += [("\n", ())]
       
   268             # Generate any variable of this block
       
   269             for var in varlist.getvariable():
       
   270                 vartype_content = var.gettype().getcontent()
       
   271                 if vartype_content["name"] == "derived":
       
   272                     var_type = vartype_content["value"].getname()
       
   273                     self.GenerateDataType(var_type)
       
   274                 else:
       
   275                     var_type = var.gettypeAsText()
       
   276                 
       
   277                 config += [("    ", ()),
       
   278                            (var.getname(), (tagname, variable_type, var_number, "name")),
       
   279                            (" ", ())]
       
   280                 # Generate variable address if exists
       
   281                 address = var.getaddress()
       
   282                 if address:
       
   283                     config += [("AT ", ()),
       
   284                                (address, (tagname, variable_type, var_number, "location")),
       
   285                                (" ", ())]
       
   286                 config += [(": ", ()),
       
   287                            (var.gettypeAsText(), (tagname, variable_type, var_number, "type"))]
       
   288                 # Generate variable initial value if exists
       
   289                 initial = var.getinitialValue()
       
   290                 if initial:
       
   291                     config += [(" := ", ()),
       
   292                                (self.ComputeValue(initial.getvalue(), var_type), (tagname, variable_type, var_number, "initial value"))]
       
   293                 config += [(";\n", ())]
       
   294                 var_number += 1
       
   295             config += [("  END_VAR\n", ())]
       
   296         # Generate any resource in the configuration
       
   297         for resource in configuration.getresource():
       
   298             config += self.GenerateResource(resource, configuration.getname())
       
   299         config += [("END_CONFIGURATION\n", ())]
       
   300         return config
       
   301     
       
   302     # Generate a resource from its model
       
   303     def GenerateResource(self, resource, config_name):
       
   304         tagname = self.Controler.ComputeConfigurationResourceName(config_name, resource.getname())
       
   305         resrce = [("\n  RESOURCE ", ()),
       
   306                   (resource.getname(), (tagname, "name")),
       
   307                   (" ON PLC\n", ())]
       
   308         var_number = 0
       
   309         # Generate any global variable in configuration
       
   310         for varlist in resource.getglobalVars():
       
   311             variable_type = errorVarTypes.get("VAR_GLOBAL", "var_local")
       
   312             # Generate variable block with modifier
       
   313             resrce += [("    VAR_GLOBAL", ())]
       
   314             if varlist.getconstant():
       
   315                 resrce += [(" CONSTANT", (tagname, variable_type, (var_number, var_number + len(varlist.getvariable())), "constant"))]
       
   316             elif varlist.getretain():
       
   317                 resrce += [(" RETAIN", (tagname, variable_type, (var_number, var_number + len(varlist.getvariable())), "retain"))]
       
   318             elif varlist.getnonretain():
       
   319                 resrce += [(" NON_RETAIN", (tagname, variable_type, (var_number, var_number + len(varlist.getvariable())), "non_retain"))]
       
   320             resrce += [("\n", ())]
       
   321             # Generate any variable of this block
       
   322             for var in varlist.getvariable():
       
   323                 vartype_content = var.gettype().getcontent()
       
   324                 if vartype_content["name"] == "derived":
       
   325                     var_type = vartype_content["value"].getname()
       
   326                     self.GenerateDataType(var_type)
       
   327                 else:
       
   328                     var_type = var.gettypeAsText()
       
   329                 
       
   330                 resrce += [("      ", ()),
       
   331                            (var.getname(), (tagname, variable_type, var_number, "name")),
       
   332                            (" ", ())]
       
   333                 address = var.getaddress()
       
   334                 # Generate variable address if exists
       
   335                 if address:
       
   336                     resrce += [("AT ", ()),
       
   337                                (address, (tagname, variable_type, var_number, "location")),
       
   338                                (" ", ())]
       
   339                 resrce += [(": ", ()),
       
   340                            (var.gettypeAsText(), (tagname, variable_type, var_number, "type"))]
       
   341                 # Generate variable initial value if exists
       
   342                 initial = var.getinitialValue()
       
   343                 if initial:
       
   344                     resrce += [(" := ", ()),
       
   345                                (self.ComputeValue(initial.getvalue(), var_type), (tagname, variable_type, var_number, "initial value"))]
       
   346                 resrce += [(";\n", ())]
       
   347                 var_number += 1
       
   348             resrce += [("    END_VAR\n", ())]
       
   349         # Generate any task in the resource
       
   350         tasks = resource.gettask()
       
   351         task_number = 0
       
   352         for task in tasks:
       
   353             # Task declaration
       
   354             resrce += [("    TASK ", ()),
       
   355                        (task.getname(), (tagname, "task", task_number, "name")),
       
   356                        ("(", ())]
       
   357             args = []
       
   358             single = task.getsingle()
       
   359             # Single argument if exists
       
   360             if single:
       
   361                 resrce += [("SINGLE := ", ()),
       
   362                            (single, (tagname, "task", task_number, "single")),
       
   363                            (",", ())]
       
   364             # Interval argument if exists
       
   365             interval = task.getinterval()
       
   366             if interval:
       
   367                 resrce += [("INTERVAL := ", ()),
       
   368                            (interval, (tagname, "task", task_number, "interval")),
       
   369                            (",", ())]
       
   370 ##                resrce += [("INTERVAL := t#", ())]
       
   371 ##                if interval.hour != 0:
       
   372 ##                    resrce += [("%dh"%interval.hour, (tagname, "task", task_number, "interval", "hour"))]
       
   373 ##                if interval.minute != 0:
       
   374 ##                    resrce += [("%dm"%interval.minute, (tagname, "task", task_number, "interval", "minute"))]
       
   375 ##                if interval.second != 0:
       
   376 ##                    resrce += [("%ds"%interval.second, (tagname, "task", task_number, "interval", "second"))]
       
   377 ##                if interval.microsecond != 0:
       
   378 ##                    resrce += [("%dms"%(interval.microsecond / 1000), (tagname, "task", task_number, "interval", "millisecond"))]
       
   379 ##                resrce += [(",", ())]
       
   380             # Priority argument
       
   381             resrce += [("PRIORITY := ", ()), 
       
   382                        ("%d"%task.getpriority(), (tagname, "task", task_number, "priority")),
       
   383                        (");\n", ())]
       
   384             task_number += 1
       
   385         instance_number = 0
       
   386         # Generate any program assign to each task
       
   387         for task in tasks:
       
   388             for instance in task.getpouInstance():
       
   389                 resrce += [("    PROGRAM ", ()),
       
   390                            (instance.getname(), (tagname, "instance", instance_number, "name")),
       
   391                            (" WITH ", ()),
       
   392                            (task.getname(), (tagname, "instance", instance_number, "task")),
       
   393                            (" : ", ()),
       
   394                            (instance.gettypeName(), (tagname, "instance", instance_number, "type")),
       
   395                            (";\n", ())]
       
   396                 instance_number += 1
       
   397         # Generate any program assign to no task
       
   398         for instance in resource.getpouInstance():
       
   399             resrce += [("    PROGRAM ", ()),
       
   400                            (instance.getname(), (tagname, "instance", instance_number, "name")),
       
   401                            (" : ", ()),
       
   402                            (instance.gettypeName(), (tagname, "instance", instance_number, "type")),
       
   403                            (";\n", ())]
       
   404             instance_number += 1
       
   405         resrce += [("  END_RESOURCE\n", ())]
       
   406         return resrce
       
   407     
       
   408     # Generate the entire program for current project
       
   409     def GenerateProgram(self):        
       
   410         # Find all data types defined
       
   411         for datatype in self.Project.getdataTypes():
       
   412             self.DatatypeComputed[datatype.getname()] = False
       
   413         # Find all data types defined
       
   414         for pou in self.Project.getpous():
       
   415             self.PouComputed[pou.getname()] = False
       
   416         # Generate data type declaration structure if there is at least one data 
       
   417         # type defined
       
   418         if len(self.DatatypeComputed) > 0:
       
   419             self.Program += [("TYPE\n", ())]
       
   420             # Generate every data types defined
       
   421             for datatype_name in self.DatatypeComputed.keys():
       
   422                 self.GenerateDataType(datatype_name)
       
   423             self.Program += [("END_TYPE\n\n", ())]
       
   424         # Generate every POUs defined
       
   425         for pou_name in self.PouComputed.keys():
       
   426             self.GeneratePouProgram(pou_name)
       
   427         # Generate every configurations defined
       
   428         for config in self.Project.getconfigurations():
       
   429             self.Program += self.GenerateConfiguration(config)
       
   430     
       
   431     # Return generated program
       
   432     def GetGeneratedProgram(self):
       
   433         return self.Program
       
   434 
       
   435 
       
   436 #-------------------------------------------------------------------------------
       
   437 #                           Generator of POU programs
       
   438 #-------------------------------------------------------------------------------
       
   439 
       
   440 
       
   441 class PouProgramGenerator:
       
   442     
       
   443     # Create a new POU program generator
       
   444     def __init__(self, parent, name, type, errors, warnings):
       
   445         # Keep Reference to the parent generator
       
   446         self.ParentGenerator = parent
       
   447         self.Name = name
       
   448         self.Type = type
       
   449         self.TagName = self.ParentGenerator.Controler.ComputePouName(name)
       
   450         self.CurrentIndent = "  "
       
   451         self.ReturnType = None
       
   452         self.Interface = []
       
   453         self.InitialSteps = []
       
   454         self.ComputedBlocks = {}
       
   455         self.ComputedConnectors = {}
       
   456         self.ConnectionTypes = {}
       
   457         self.RelatedConnections = []
       
   458         self.SFCNetworks = {"Steps":{}, "Transitions":{}, "Actions":{}}
       
   459         self.SFCComputedBlocks = []
       
   460         self.ActionNumber = 0
       
   461         self.Program = []
       
   462         self.Errors = errors
       
   463         self.Warnings = warnings
       
   464     
       
   465     def GetBlockType(self, type, inputs=None):
       
   466         return self.ParentGenerator.Controler.GetBlockType(type, inputs)
       
   467     
       
   468     def IndentLeft(self):
       
   469         if len(self.CurrentIndent) >= 2:
       
   470             self.CurrentIndent = self.CurrentIndent[:-2]
       
   471     
       
   472     def IndentRight(self):
       
   473         self.CurrentIndent += "  "
       
   474     
       
   475     # Generator of unique ID for inline actions
       
   476     def GetActionNumber(self):
       
   477         self.ActionNumber += 1
       
   478         return self.ActionNumber
       
   479     
       
   480     # Test if a variable has already been defined
       
   481     def IsAlreadyDefined(self, name):
       
   482         for list_type, option, located, vars in self.Interface:
       
   483             for var_type, var_name, var_address, var_initial in vars:
       
   484                 if name == var_name:
       
   485                     return True
       
   486         return False
       
   487     
       
   488     # Return the type of a variable defined in interface
       
   489     def GetVariableType(self, name):
       
   490         parts = name.split('.')
       
   491         current_type = None
       
   492         if len(parts) > 0:
       
   493             name = parts.pop(0)
       
   494             for list_type, option, located, vars in self.Interface:
       
   495                 for var_type, var_name, var_address, var_initial in vars:
       
   496                     if name == var_name:
       
   497                         current_type = var_type
       
   498                         break
       
   499             while current_type is not None and len(parts) > 0:
       
   500                 tagname = self.ParentGenerator.Controler.ComputeDataTypeName(current_type)
       
   501                 infos = self.ParentGenerator.Controler.GetDataTypeInfos(tagname)
       
   502                 name = parts.pop(0)
       
   503                 current_type = None
       
   504                 if infos is not None and infos["type"] == "Structure":
       
   505                     for element in infos["elements"]:
       
   506                         if element["Name"] == name:
       
   507                             current_type = element["Type"]
       
   508                             break
       
   509         return current_type
       
   510     
       
   511     # Return connectors linked by a connection to the given connector
       
   512     def GetConnectedConnector(self, connector, body):
       
   513         links = connector.getconnections()
       
   514         if links and len(links) == 1:
       
   515             return self.GetLinkedConnector(links[0], body)
       
   516         return None        
       
   517 
       
   518     def GetLinkedConnector(self, link, body):
       
   519         parameter = link.getformalParameter()
       
   520         instance = body.getcontentInstance(link.getrefLocalId())
       
   521         if isinstance(instance, (plcopen.fbdObjects_inVariable, plcopen.fbdObjects_inOutVariable, plcopen.commonObjects_continuation, plcopen.ldObjects_contact, plcopen.ldObjects_coil)):
       
   522             return instance.connectionPointOut
       
   523         elif isinstance(instance, plcopen.fbdObjects_block):
       
   524             outputvariables = instance.outputVariables.getvariable()
       
   525             if len(outputvariables) == 1:
       
   526                 return outputvariables[0].connectionPointOut
       
   527             elif parameter:
       
   528                 for variable in outputvariables:
       
   529                     if variable.getformalParameter() == parameter:
       
   530                         return variable.connectionPointOut
       
   531             else:
       
   532                 point = link.getposition()[-1]
       
   533                 for variable in outputvariables:
       
   534                     relposition = variable.connectionPointOut.getrelPositionXY()
       
   535                     blockposition = instance.getposition()
       
   536                     if point.x == blockposition.x + relposition[0] and point.y == blockposition.y + relposition[1]:
       
   537                         return variable.connectionPointOut
       
   538         elif isinstance(instance, plcopen.ldObjects_leftPowerRail):
       
   539             outputconnections = instance.getconnectionPointOut()
       
   540             if len(outputconnections) == 1:
       
   541                 return outputconnections[0]
       
   542             else:
       
   543                 point = link.getposition()[-1]
       
   544                 for outputconnection in outputconnections:
       
   545                     relposition = outputconnection.getrelPositionXY()
       
   546                     powerrailposition = instance.getposition()
       
   547                     if point.x == powerrailposition.x + relposition[0] and point.y == powerrailposition.y + relposition[1]:
       
   548                         return outputconnection
       
   549         return None
       
   550         
       
   551     def ExtractRelatedConnections(self, connection):
       
   552         for i, related in enumerate(self.RelatedConnections):
       
   553             if connection in related:
       
   554                 return self.RelatedConnections.pop(i)
       
   555         return [connection]
       
   556     
       
   557     def ComputeInterface(self, pou):
       
   558         interface = pou.getinterface()
       
   559         if interface is not None:
       
   560             body = pou.getbody()
       
   561             if isinstance(body, ListType):
       
   562                 body = body[0]
       
   563             body_content = body.getcontent()
       
   564             if self.Type == "FUNCTION":
       
   565                 returntype_content = interface.getreturnType().getcontent()
       
   566                 if returntype_content["name"] == "derived":
       
   567                     self.ReturnType = returntype_content["value"].getname()
       
   568                 elif returntype_content["name"] in ["string", "wstring"]:
       
   569                     self.ReturnType = returntype_content["name"].upper()
       
   570                 else:
       
   571                     self.ReturnType = returntype_content["name"]
       
   572             for varlist in interface.getcontent():
       
   573                 variables = []
       
   574                 located = []
       
   575                 for var in varlist["value"].getvariable():
       
   576                     vartype_content = var.gettype().getcontent()
       
   577                     if vartype_content["name"] == "derived":
       
   578                         var_type = vartype_content["value"].getname()
       
   579                         blocktype = self.GetBlockType(var_type)
       
   580                         if blocktype is not None:
       
   581                             self.ParentGenerator.GeneratePouProgram(var_type)
       
   582                             if body_content["name"] in ["FBD", "LD", "SFC"]:
       
   583                                 block = pou.getinstanceByName(var.getname())
       
   584                             else:
       
   585                                 block = None
       
   586                             for variable in blocktype["initialise"](var_type, var.getname(), block):
       
   587                                 if variable[2] is not None:
       
   588                                     located.append(variable)
       
   589                                 else:
       
   590                                     variables.append(variable)
       
   591                         else:
       
   592                             self.ParentGenerator.GenerateDataType(var_type)
       
   593                             initial = var.getinitialValue()
       
   594                             if initial:
       
   595                                 initial_value = initial.getvalue()
       
   596                             else:
       
   597                                 initial_value = None
       
   598                             address = var.getaddress()
       
   599                             if address is not None:
       
   600                                 located.append((vartype_content["value"].getname(), var.getname(), address, initial_value))
       
   601                             else:
       
   602                                 variables.append((vartype_content["value"].getname(), var.getname(), None, initial_value))
       
   603                     else:
       
   604                         var_type = var.gettypeAsText()
       
   605                         initial = var.getinitialValue()
       
   606                         if initial:
       
   607                             initial_value = initial.getvalue()
       
   608                         else:
       
   609                             initial_value = None
       
   610                         address = var.getaddress()
       
   611                         if address is not None:
       
   612                             located.append((var_type, var.getname(), address, initial_value))
       
   613                         else:
       
   614                             variables.append((var_type, var.getname(), None, initial_value))
       
   615                 if varlist["value"].getconstant():
       
   616                     option = "CONSTANT"
       
   617                 elif varlist["value"].getretain():
       
   618                     option = "RETAIN"
       
   619                 elif varlist["value"].getnonretain():
       
   620                     option = "NON_RETAIN"
       
   621                 else:
       
   622                     option = None
       
   623                 if len(variables) > 0:
       
   624                     self.Interface.append((varTypeNames[varlist["name"]], option, False, variables))
       
   625                 if len(located) > 0:
       
   626                     self.Interface.append((varTypeNames[varlist["name"]], option, True, located))
       
   627         
       
   628     def ComputeConnectionTypes(self, pou):
       
   629         body = pou.getbody()
       
   630         if isinstance(body, ListType):
       
   631             body = body[0]
       
   632         body_content = body.getcontent()
       
   633         body_type = body_content["name"]
       
   634         if body_type in ["FBD", "LD", "SFC"]:
       
   635             undefined_blocks = []
       
   636             for instance in body.getcontentInstances():
       
   637                 if isinstance(instance, (plcopen.fbdObjects_inVariable, plcopen.fbdObjects_outVariable, plcopen.fbdObjects_inOutVariable)):
       
   638                     expression = instance.getexpression()
       
   639                     var_type = self.GetVariableType(expression)
       
   640                     if pou.getpouType() == "function" and expression == pou.getname():
       
   641                         returntype_content = pou.interface.getreturnType().getcontent()
       
   642                         if returntype_content["name"] == "derived":
       
   643                             var_type = returntype_content["value"].getname()
       
   644                         elif returntype_content["name"] in ["string", "wstring"]:
       
   645                             var_type = returntype_content["name"].upper()
       
   646                         else:
       
   647                             var_type = returntype_content["name"]
       
   648                     elif var_type is None:
       
   649                         parts = expression.split("#")
       
   650                         if len(parts) > 1:
       
   651                             var_type = parts[0]
       
   652                         elif REAL_MODEL.match(expression):
       
   653                             var_type = "ANY_REAL"
       
   654                         elif INTEGER_MODEL.match(expression):
       
   655                             var_type = "ANY_NUM"
       
   656                         elif expression.startswith("'"):
       
   657                             var_type = "STRING"
       
   658                         elif expression.startswith('"'):
       
   659                             var_type = "WSTRING"
       
   660                     if var_type is not None:
       
   661                         if isinstance(instance, (plcopen.fbdObjects_inVariable, plcopen.fbdObjects_inOutVariable)):
       
   662                             for connection in self.ExtractRelatedConnections(instance.connectionPointOut):
       
   663                                 self.ConnectionTypes[connection] = var_type
       
   664                         if isinstance(instance, (plcopen.fbdObjects_outVariable, plcopen.fbdObjects_inOutVariable)):
       
   665                             self.ConnectionTypes[instance.connectionPointIn] = var_type
       
   666                             connected = self.GetConnectedConnector(instance.connectionPointIn, body)
       
   667                             if connected and not self.ConnectionTypes.has_key(connected):
       
   668                                 for connection in self.ExtractRelatedConnections(connected):
       
   669                                     self.ConnectionTypes[connection] = var_type
       
   670                 elif isinstance(instance, (plcopen.ldObjects_contact, plcopen.ldObjects_coil)):
       
   671                     for connection in self.ExtractRelatedConnections(instance.connectionPointOut):
       
   672                         self.ConnectionTypes[connection] = "BOOL"
       
   673                     self.ConnectionTypes[instance.connectionPointIn] = "BOOL"
       
   674                     connected = self.GetConnectedConnector(instance.connectionPointIn, body)
       
   675                     if connected and not self.ConnectionTypes.has_key(connected):
       
   676                         for connection in self.ExtractRelatedConnections(connected):
       
   677                             self.ConnectionTypes[connection] = "BOOL"
       
   678                 elif isinstance(instance, plcopen.ldObjects_leftPowerRail):
       
   679                     for connection in instance.getconnectionPointOut():
       
   680                         for related in self.ExtractRelatedConnections(connection):
       
   681                             self.ConnectionTypes[related] = "BOOL"
       
   682                 elif isinstance(instance, plcopen.ldObjects_rightPowerRail):
       
   683                     for connection in instance.getconnectionPointIn():
       
   684                         self.ConnectionTypes[connection] = "BOOL"
       
   685                         connected = self.GetConnectedConnector(connection, body)
       
   686                         if connected and not self.ConnectionTypes.has_key(connected):
       
   687                             for connection in self.ExtractRelatedConnections(connected):
       
   688                                 self.ConnectionTypes[connection] = "BOOL"
       
   689                 elif isinstance(instance, plcopen.sfcObjects_transition):
       
   690                     content = instance.condition.getcontent()
       
   691                     if content["name"] == "connection" and len(content["value"]) == 1:
       
   692                         connected = self.GetLinkedConnector(content["value"][0], body)
       
   693                         if connected and not self.ConnectionTypes.has_key(connected):
       
   694                             for connection in self.ExtractRelatedConnections(connected):
       
   695                                 self.ConnectionTypes[connection] = "BOOL"
       
   696                 elif isinstance(instance, plcopen.commonObjects_continuation):
       
   697                     name = instance.getname()
       
   698                     connector = None
       
   699                     var_type = "ANY"
       
   700                     for element in body.getcontentInstances():
       
   701                         if isinstance(element, plcopen.commonObjects_connector) and element.getname() == name:
       
   702                             if connector is not None:
       
   703                                 raise PLCGenException, _("More than one connector found corresponding to \"%s\" continuation in \"%s\" POU")%(name, self.Name)
       
   704                             connector = element
       
   705                     if connector is not None:
       
   706                         undefined = [instance.connectionPointOut, connector.connectionPointIn]
       
   707                         connected = self.GetConnectedConnector(connector.connectionPointIn, body)
       
   708                         if connected:
       
   709                             undefined.append(connected)
       
   710                         related = []
       
   711                         for connection in undefined:
       
   712                             if self.ConnectionTypes.has_key(connection):
       
   713                                 var_type = self.ConnectionTypes[connection]
       
   714                             else:
       
   715                                 related.extend(self.ExtractRelatedConnections(connection))
       
   716                         if var_type.startswith("ANY") and len(related) > 0:
       
   717                             self.RelatedConnections.append(related)
       
   718                         else:
       
   719                             for connection in related:
       
   720                                 self.ConnectionTypes[connection] = var_type
       
   721                     else:
       
   722                         raise PLCGenException, _("No connector found corresponding to \"%s\" continuation in \"%s\" POU")%(name, self.Name)
       
   723                 elif isinstance(instance, plcopen.fbdObjects_block):
       
   724                     block_infos = self.GetBlockType(instance.gettypeName(), "undefined")
       
   725                     if block_infos is not None:
       
   726                         self.ComputeBlockInputTypes(instance, block_infos, body)
       
   727                     else:
       
   728                         for variable in instance.inputVariables.getvariable():
       
   729                             connected = self.GetConnectedConnector(variable.connectionPointIn, body)
       
   730                             if connected is not None:
       
   731                                 var_type = self.ConnectionTypes.get(connected, None)
       
   732                                 if var_type is not None:
       
   733                                     self.ConnectionTypes[variable.connectionPointIn] = var_type
       
   734                                 else:
       
   735                                     related = self.ExtractRelatedConnections(connected)
       
   736                                     related.append(variable.connectionPointIn)
       
   737                                     self.RelatedConnections.append(related)
       
   738                         undefined_blocks.append(instance)
       
   739             for instance in undefined_blocks:
       
   740                 block_infos = self.GetBlockType(instance.gettypeName(), tuple([self.ConnectionTypes.get(variable.connectionPointIn, "ANY") for variable in instance.inputVariables.getvariable() if variable.getformalParameter() != "EN"]))
       
   741                 if block_infos is not None:
       
   742                     self.ComputeBlockInputTypes(instance, block_infos, body)
       
   743                 else:
       
   744                     raise PLCGenException, _("No informations found for \"%s\" block")%(instance.gettypeName())
       
   745                 
       
   746     def ComputeBlockInputTypes(self, instance, block_infos, body):
       
   747         undefined = {}
       
   748         for variable in instance.outputVariables.getvariable():
       
   749             output_name = variable.getformalParameter()
       
   750             if output_name == "ENO":
       
   751                 for connection in self.ExtractRelatedConnections(variable.connectionPointOut):
       
   752                     self.ConnectionTypes[connection] = "BOOL"
       
   753             else:
       
   754                 for oname, otype, oqualifier in block_infos["outputs"]:
       
   755                     if output_name == oname:
       
   756                         if otype.startswith("ANY"):
       
   757                             if not undefined.has_key(otype):
       
   758                                 undefined[otype] = []
       
   759                             undefined[otype].append(variable.connectionPointOut)
       
   760                         elif not self.ConnectionTypes.has_key(variable.connectionPointOut):
       
   761                             for connection in self.ExtractRelatedConnections(variable.connectionPointOut):
       
   762                                 self.ConnectionTypes[connection] = otype
       
   763         for variable in instance.inputVariables.getvariable():
       
   764             input_name = variable.getformalParameter()
       
   765             if input_name == "EN":
       
   766                 for connection in self.ExtractRelatedConnections(variable.connectionPointIn):
       
   767                     self.ConnectionTypes[connection] = "BOOL"
       
   768             else:
       
   769                 for iname, itype, iqualifier in block_infos["inputs"]:
       
   770                     if input_name == iname:
       
   771                         connected = self.GetConnectedConnector(variable.connectionPointIn, body)
       
   772                         if itype.startswith("ANY"):
       
   773                             if not undefined.has_key(itype):
       
   774                                 undefined[itype] = []
       
   775                             undefined[itype].append(variable.connectionPointIn)
       
   776                             if connected:
       
   777                                 undefined[itype].append(connected)
       
   778                         else:
       
   779                             self.ConnectionTypes[variable.connectionPointIn] = itype
       
   780                             if connected and not self.ConnectionTypes.has_key(connected):
       
   781                                 for connection in self.ExtractRelatedConnections(connected):
       
   782                                     self.ConnectionTypes[connection] = itype
       
   783         for var_type, connections in undefined.items():
       
   784             related = []
       
   785             for connection in connections:
       
   786                 if self.ConnectionTypes.has_key(connection):
       
   787                     var_type = self.ConnectionTypes[connection]
       
   788                 else:
       
   789                     related.extend(self.ExtractRelatedConnections(connection))
       
   790             if var_type.startswith("ANY") and len(related) > 0:
       
   791                 self.RelatedConnections.append(related)
       
   792             else:
       
   793                 for connection in related:
       
   794                     self.ConnectionTypes[connection] = var_type
       
   795 
       
   796     def ComputeProgram(self, pou):
       
   797         body = pou.getbody()
       
   798         if isinstance(body, ListType):
       
   799             body = body[0]
       
   800         body_content = body.getcontent()
       
   801         body_type = body_content["name"]
       
   802         if body_type in ["IL","ST"]:
       
   803             text = body_content["value"].gettext()
       
   804             self.ParentGenerator.GeneratePouProgramInText(text.upper())
       
   805             self.Program = [(ReIndentText(text, len(self.CurrentIndent)), 
       
   806                             (self.TagName, "body", len(self.CurrentIndent)))]
       
   807         elif body_type == "SFC":
       
   808             self.IndentRight()
       
   809             for instance in body.getcontentInstances():
       
   810                 if isinstance(instance, plcopen.sfcObjects_step):
       
   811                     self.GenerateSFCStep(instance, pou)
       
   812                 elif isinstance(instance, plcopen.commonObjects_actionBlock):
       
   813                     self.GenerateSFCStepActions(instance, pou)
       
   814                 elif isinstance(instance, plcopen.sfcObjects_transition):
       
   815                     self.GenerateSFCTransition(instance, pou)
       
   816                 elif isinstance(instance, plcopen.sfcObjects_jumpStep):
       
   817                     self.GenerateSFCJump(instance, pou)
       
   818             if len(self.InitialSteps) > 0 and len(self.SFCComputedBlocks) > 0:
       
   819                 action_name = "COMPUTE_FUNCTION_BLOCKS"
       
   820                 action_infos = {"qualifier" : "S", "content" : action_name}
       
   821                 self.SFCNetworks["Steps"][self.InitialSteps[0]]["actions"].append(action_infos)
       
   822                 self.SFCNetworks["Actions"][action_name] = (self.SFCComputedBlocks, ())
       
   823                 self.Program = []
       
   824             self.IndentLeft()
       
   825             for initialstep in self.InitialSteps:
       
   826                 self.ComputeSFCStep(initialstep)
       
   827         else:
       
   828             otherInstances = {"outVariables&coils" : [], "blocks" : [], "connectors" : []}
       
   829             orderedInstances = []
       
   830             for instance in body.getcontentInstances():
       
   831                 if isinstance(instance, (plcopen.fbdObjects_outVariable, plcopen.fbdObjects_inOutVariable, plcopen.fbdObjects_block)):
       
   832                     executionOrderId = instance.getexecutionOrderId()
       
   833                     if executionOrderId > 0:
       
   834                         orderedInstances.append((executionOrderId, instance))
       
   835                     elif isinstance(instance, (plcopen.fbdObjects_outVariable, plcopen.fbdObjects_inOutVariable)):
       
   836                         otherInstances["outVariables&coils"].append(instance)
       
   837                     elif isinstance(instance, plcopen.fbdObjects_block):
       
   838                         otherInstances["blocks"].append(instance)
       
   839                 elif isinstance(instance, plcopen.commonObjects_connector):
       
   840                     otherInstances["connectors"].append(instance)
       
   841                 elif isinstance(instance, plcopen.ldObjects_coil):
       
   842                     otherInstances["outVariables&coils"].append(instance)
       
   843             orderedInstances.sort()
       
   844             otherInstances["outVariables&coils"].sort(SortInstances)
       
   845             otherInstances["blocks"].sort(SortInstances)
       
   846             instances = [instance for (executionOrderId, instance) in orderedInstances]
       
   847             instances.extend(otherInstances["connectors"] + otherInstances["outVariables&coils"] + otherInstances["blocks"])
       
   848             for instance in instances:
       
   849                 if isinstance(instance, (plcopen.fbdObjects_outVariable, plcopen.fbdObjects_inOutVariable)):
       
   850                     connections = instance.connectionPointIn.getconnections()
       
   851                     if connections is not None:
       
   852                         expression = self.ComputeExpression(body, connections)
       
   853                         self.Program += [(self.CurrentIndent, ()),
       
   854                                          (instance.getexpression(), (self.TagName, "io_variable", instance.getlocalId(), "expression")),
       
   855                                          (" := ", ())]
       
   856                         self.Program += expression
       
   857                         self.Program += [(";\n", ())]
       
   858                 elif isinstance(instance, plcopen.fbdObjects_block):
       
   859                     block_type = instance.gettypeName()
       
   860                     self.ParentGenerator.GeneratePouProgram(block_type)
       
   861                     block_infos = self.GetBlockType(block_type, tuple([self.ConnectionTypes.get(variable.connectionPointIn, "ANY") for variable in instance.inputVariables.getvariable() if variable.getformalParameter() != "EN"]))
       
   862                     if block_infos is None:
       
   863                         block_infos = self.GetBlockType(block_type)
       
   864                     if block_infos is None:
       
   865                         raise PLCGenException, _("Undefined block type \"%s\" in \"%s\" POU")%(block_type, self.Name)
       
   866                     block_infos["generate"](self, instance, block_infos, body, None)
       
   867                 elif isinstance(instance, plcopen.commonObjects_connector):
       
   868                     connector = instance.getname()
       
   869                     if self.ComputedConnectors.get(connector, None):
       
   870                         continue 
       
   871                     self.ComputedConnectors[connector] = self.ComputeExpression(body, instance.connectionPointIn.getconnections())
       
   872                 elif isinstance(instance, plcopen.ldObjects_coil):
       
   873                     connections = instance.connectionPointIn.getconnections()
       
   874                     if connections is not None:
       
   875                         coil_info = (self.TagName, "coil", instance.getlocalId())
       
   876                         expression = self.ExtractModifier(instance, self.ComputeExpression(body, connections), coil_info)
       
   877                         self.Program += [(self.CurrentIndent, ())]
       
   878                         self.Program += [(instance.getvariable(), coil_info + ("reference",))]
       
   879                         self.Program += [(" := ", ())] + expression + [(";\n", ())]
       
   880                         
       
   881     def FactorizePaths(self, paths):
       
   882         same_paths = {}
       
   883         uncomputed_index = range(len(paths))
       
   884         factorized_paths = []
       
   885         for num, path in enumerate(paths):
       
   886             if type(path) == ListType:
       
   887                 if len(path) > 1:
       
   888                     str_path = str(path[-1:])
       
   889                     same_paths.setdefault(str_path, [])
       
   890                     same_paths[str_path].append((path[:-1], num))
       
   891             else:
       
   892                 factorized_paths.append(path)
       
   893                 uncomputed_index.remove(num)
       
   894         for same_path, elements in same_paths.items():
       
   895             if len(elements) > 1:
       
   896                 elements_paths = self.FactorizePaths([path for path, num in elements])
       
   897                 if len(elements_paths) > 1:
       
   898                     factorized_paths.append([tuple(elements_paths)] + eval(same_path))        
       
   899                 else:
       
   900                     factorized_paths.append(elements_paths + eval(same_path))
       
   901                 for path, num in elements:
       
   902                     uncomputed_index.remove(num)
       
   903         for num in uncomputed_index:
       
   904             factorized_paths.append(paths[num])
       
   905         factorized_paths.sort()
       
   906         return factorized_paths
       
   907 
       
   908     def GeneratePaths(self, connections, body, order = False, to_inout = False):
       
   909         paths = []
       
   910         for connection in connections:
       
   911             localId = connection.getrefLocalId()
       
   912             next = body.getcontentInstance(localId)
       
   913             if isinstance(next, plcopen.ldObjects_leftPowerRail):
       
   914                 paths.append(None)
       
   915             elif isinstance(next, (plcopen.fbdObjects_inVariable, plcopen.fbdObjects_inOutVariable)):
       
   916                 paths.append(str([(next.getexpression(), (self.TagName, "io_variable", localId, "expression"))]))
       
   917             elif isinstance(next, plcopen.fbdObjects_block):
       
   918                 block_type = next.gettypeName()
       
   919                 self.ParentGenerator.GeneratePouProgram(block_type)
       
   920                 block_infos = self.GetBlockType(block_type, tuple([self.ConnectionTypes.get(variable.connectionPointIn, "ANY") for variable in next.inputVariables.getvariable() if variable.getformalParameter() != "EN"]))
       
   921                 if block_infos is None:
       
   922                     block_infos = self.GetBlockType(block_type)
       
   923                 if block_infos is None:
       
   924                     raise PLCGenException, _("Undefined block type \"%s\" in \"%s\" POU")%(block_type, self.Name)
       
   925                 paths.append(str(block_infos["generate"](self, next, block_infos, body, connection, order, to_inout)))
       
   926             elif isinstance(next, plcopen.commonObjects_continuation):
       
   927                 name = next.getname()
       
   928                 computed_value = self.ComputedConnectors.get(name, None)
       
   929                 if computed_value != None:
       
   930                     paths.append(str(computed_value))
       
   931                 else:
       
   932                     connector = None
       
   933                     for instance in body.getcontentInstances():
       
   934                         if isinstance(instance, plcopen.commonObjects_connector) and instance.getname() == name:
       
   935                             if connector is not None:
       
   936                                 raise PLCGenException, _("More than one connector found corresponding to \"%s\" continuation in \"%s\" POU")%(name, self.Name)
       
   937                             connector = instance
       
   938                     if connector is not None:
       
   939                         connections = connector.connectionPointIn.getconnections()
       
   940                         if connections is not None:
       
   941                             expression = self.ComputeExpression(body, connections, order)
       
   942                             self.ComputedConnectors[name] = expression
       
   943                             paths.append(str(expression))
       
   944                     else:
       
   945                         raise PLCGenException, _("No connector found corresponding to \"%s\" continuation in \"%s\" POU")%(name, self.Name)
       
   946             elif isinstance(next, plcopen.ldObjects_contact):
       
   947                 contact_info = (self.TagName, "contact", next.getlocalId())
       
   948                 variable = str(self.ExtractModifier(next, [(next.getvariable(), contact_info + ("reference",))], contact_info))
       
   949                 result = self.GeneratePaths(next.connectionPointIn.getconnections(), body, order)
       
   950                 if len(result) > 1:
       
   951                     factorized_paths = self.FactorizePaths(result)
       
   952                     if len(factorized_paths) > 1:
       
   953                         paths.append([variable, tuple(factorized_paths)])
       
   954                     else:
       
   955                         paths.append([variable] + factorized_paths)
       
   956                 elif type(result[0]) == ListType:
       
   957                     paths.append([variable] + result[0])
       
   958                 elif result[0] is not None:
       
   959                     paths.append([variable, result[0]])
       
   960                 else:
       
   961                     paths.append(variable)
       
   962             elif isinstance(next, plcopen.ldObjects_coil):
       
   963                 paths.append(str(self.GeneratePaths(next.connectionPointIn.getconnections(), body, order)))
       
   964         return paths
       
   965 
       
   966     def ComputePaths(self, paths, first = False):
       
   967         if type(paths) == TupleType:
       
   968             if None in paths:
       
   969                 return [("TRUE", ())]
       
   970             else:
       
   971                 vars = [self.ComputePaths(path) for path in paths]
       
   972                 if first:
       
   973                     return JoinList([(" OR ", ())], vars)
       
   974                 else:
       
   975                     return [("(", ())] + JoinList([(" OR ", ())], vars) + [(")", ())]
       
   976         elif type(paths) == ListType:
       
   977             vars = [self.ComputePaths(path) for path in paths]
       
   978             return JoinList([(" AND ", ())], vars)
       
   979         elif paths is None:
       
   980             return [("TRUE", ())]
       
   981         else:
       
   982             return eval(paths)
       
   983 
       
   984     def ComputeExpression(self, body, connections, order = False, to_inout = False):
       
   985         paths = self.GeneratePaths(connections, body, order, to_inout)
       
   986         if len(paths) > 1:
       
   987             factorized_paths = self.FactorizePaths(paths)
       
   988             if len(factorized_paths) > 1:
       
   989                 paths = tuple(factorized_paths)
       
   990             else:
       
   991                 paths = factorized_paths[0]
       
   992         else:
       
   993             paths = paths[0]
       
   994         return self.ComputePaths(paths, True)
       
   995 
       
   996     def ExtractModifier(self, variable, expression, var_info):
       
   997         if variable.getnegated():
       
   998             return [("NOT(", var_info + ("negated",))] + expression + [(")", ())]
       
   999         else:
       
  1000             storage = variable.getstorage()
       
  1001             if storage in ["set", "reset"]:
       
  1002                 self.Program += [(self.CurrentIndent + "IF ", var_info + (storage,))] + expression
       
  1003                 self.Program += [(" THEN\n  ", ())]
       
  1004                 if storage == "set":
       
  1005                     return [("TRUE; (*set*)\n" + self.CurrentIndent + "END_IF", ())]
       
  1006                 else:
       
  1007                     return [("FALSE; (*reset*)\n" + self.CurrentIndent + "END_IF", ())]
       
  1008             edge = variable.getedge()
       
  1009             if edge == "rising":
       
  1010                 return self.AddTrigger("R_TRIG", expression, var_info + ("rising",))
       
  1011             elif edge == "falling":
       
  1012                 return self.AddTrigger("F_TRIG", expression, var_info + ("falling",))
       
  1013         return expression
       
  1014     
       
  1015     def AddTrigger(self, edge, expression, var_info):
       
  1016         if self.Interface[-1][0] != "VAR" or self.Interface[-1][1] is not None or self.Interface[-1][2]:
       
  1017             self.Interface.append(("VAR", None, False, []))
       
  1018         i = 1
       
  1019         name = "%s%d"%(edge, i)
       
  1020         while self.IsAlreadyDefined(name):
       
  1021             i += 1
       
  1022             name = "%s%d"%(edge, i)
       
  1023         self.Interface[-1][3].append((edge, name, None, None))
       
  1024         self.Program += [(self.CurrentIndent, ()), (name, var_info), ("(CLK := ", ())] 
       
  1025         self.Program += expression
       
  1026         self.Program += [(");\n", ())]
       
  1027         return [("%s.Q"%name, var_info)]
       
  1028     
       
  1029     def ExtractDivergenceInput(self, divergence, pou):
       
  1030         connectionPointIn = divergence.getconnectionPointIn()
       
  1031         if connectionPointIn:
       
  1032             connections = connectionPointIn.getconnections()
       
  1033             if connections is not None and len(connections) == 1:
       
  1034                 instanceLocalId = connections[0].getrefLocalId()
       
  1035                 body = pou.getbody()
       
  1036                 if isinstance(body, ListType):
       
  1037                     body = body[0]
       
  1038                 return body.getcontentInstance(instanceLocalId)
       
  1039         return None
       
  1040 
       
  1041     def ExtractConvergenceInputs(self, convergence, pou):
       
  1042         instances = []
       
  1043         for connectionPointIn in convergence.getconnectionPointIn():
       
  1044             connections = connectionPointIn.getconnections()
       
  1045             if connections is not None and len(connections) == 1:
       
  1046                 instanceLocalId = connections[0].getrefLocalId()
       
  1047                 body = pou.getbody()
       
  1048                 if isinstance(body, ListType):
       
  1049                     body = body[0]
       
  1050                 instances.append(body.getcontentInstance(instanceLocalId))
       
  1051         return instances
       
  1052 
       
  1053     def GenerateSFCStep(self, step, pou):
       
  1054         step_name = step.getname()
       
  1055         if step_name not in self.SFCNetworks["Steps"].keys():
       
  1056             if step.getinitialStep():
       
  1057                 self.InitialSteps.append(step_name)
       
  1058             step_infos = {"id" : step.getlocalId(), 
       
  1059                           "initial" : step.getinitialStep(), 
       
  1060                           "transitions" : [], 
       
  1061                           "actions" : []}
       
  1062             if step.connectionPointIn:
       
  1063                 instances = []
       
  1064                 connections = step.connectionPointIn.getconnections()
       
  1065                 if connections is not None and len(connections) == 1:
       
  1066                     instanceLocalId = connections[0].getrefLocalId()
       
  1067                     body = pou.getbody()
       
  1068                     if isinstance(body, ListType):
       
  1069                         body = body[0]
       
  1070                     instance = body.getcontentInstance(instanceLocalId)
       
  1071                     if isinstance(instance, plcopen.sfcObjects_transition):
       
  1072                         instances.append(instance)
       
  1073                     elif isinstance(instance, plcopen.sfcObjects_selectionConvergence):
       
  1074                         instances.extend(self.ExtractConvergenceInputs(instance, pou))
       
  1075                     elif isinstance(instance, plcopen.sfcObjects_simultaneousDivergence):
       
  1076                         transition = self.ExtractDivergenceInput(instance, pou)
       
  1077                         if transition:
       
  1078                             if isinstance(transition, plcopen.sfcObjects_transition):
       
  1079                                 instances.append(transition)
       
  1080                             elif isinstance(transition, plcopen.sfcObjects_selectionConvergence):
       
  1081                                 instances.extend(self.ExtractConvergenceInputs(transition, pou))
       
  1082                 for instance in instances:
       
  1083                     self.GenerateSFCTransition(instance, pou)
       
  1084                     if instance in self.SFCNetworks["Transitions"].keys():
       
  1085                         target_info = (self.TagName, "transition", instance.getlocalId(), "to", step_infos["id"])
       
  1086                         self.SFCNetworks["Transitions"][instance]["to"].append([(step_name, target_info)])
       
  1087             self.SFCNetworks["Steps"][step_name] = step_infos
       
  1088     
       
  1089     def GenerateSFCJump(self, jump, pou):
       
  1090         jump_target = jump.gettargetName()
       
  1091         if jump.connectionPointIn:
       
  1092             instances = []
       
  1093             connections = jump.connectionPointIn.getconnections()
       
  1094             if connections is not None and len(connections) == 1:
       
  1095                 instanceLocalId = connections[0].getrefLocalId()
       
  1096                 body = pou.getbody()
       
  1097                 if isinstance(body, ListType):
       
  1098                     body = body[0]
       
  1099                 instance = body.getcontentInstance(instanceLocalId)
       
  1100                 if isinstance(instance, plcopen.sfcObjects_transition):
       
  1101                     instances.append(instance)
       
  1102                 elif isinstance(instance, plcopen.sfcObjects_selectionConvergence):
       
  1103                     instances.extend(self.ExtractConvergenceInputs(instance, pou))
       
  1104                 elif isinstance(instance, plcopen.sfcObjects_simultaneousDivergence):
       
  1105                     transition = self.ExtractDivergenceInput(instance, pou)
       
  1106                     if transition:
       
  1107                         if isinstance(transition, plcopen.sfcObjects_transition):
       
  1108                             instances.append(transition)
       
  1109                         elif isinstance(transition, plcopen.sfcObjects_selectionConvergence):
       
  1110                             instances.extend(self.ExtractConvergenceInputs(transition, pou))
       
  1111             for instance in instances:
       
  1112                 self.GenerateSFCTransition(instance, pou)
       
  1113                 if instance in self.SFCNetworks["Transitions"].keys():
       
  1114                     target_info = (self.TagName, "jump", jump.getlocalId(), "target")
       
  1115                     self.SFCNetworks["Transitions"][instance]["to"].append([(jump_target, target_info)])
       
  1116     
       
  1117     def GenerateSFCStepActions(self, actionBlock, pou):
       
  1118         connections = actionBlock.connectionPointIn.getconnections()
       
  1119         if connections is not None and len(connections) == 1:
       
  1120             stepLocalId = connections[0].getrefLocalId()
       
  1121             body = pou.getbody()
       
  1122             if isinstance(body, ListType):
       
  1123                 body = body[0]
       
  1124             step = body.getcontentInstance(stepLocalId)
       
  1125             self.GenerateSFCStep(step, pou)
       
  1126             step_name = step.getname()
       
  1127             if step_name in self.SFCNetworks["Steps"].keys():
       
  1128                 actions = actionBlock.getactions()
       
  1129                 for i, action in enumerate(actions):
       
  1130                     action_infos = {"id" : actionBlock.getlocalId(), 
       
  1131                                     "qualifier" : action["qualifier"], 
       
  1132                                     "content" : action["value"],
       
  1133                                     "num" : i}
       
  1134                     if "duration" in action:
       
  1135                         action_infos["duration"] = action["duration"]
       
  1136                     if "indicator" in action:
       
  1137                         action_infos["indicator"] = action["indicator"]
       
  1138                     if action["type"] == "reference":
       
  1139                         self.GenerateSFCAction(action["value"], pou)
       
  1140                     else:
       
  1141                         action_name = "%s_INLINE%d"%(step_name.upper(), self.GetActionNumber())
       
  1142                         self.SFCNetworks["Actions"][action_name] = ([(self.CurrentIndent, ()), 
       
  1143                             (action["value"], (self.TagName, "action_block", action_infos["id"], "action", i, "inline")),
       
  1144                             ("\n", ())], ())
       
  1145                         action_infos["content"] = action_name
       
  1146                     self.SFCNetworks["Steps"][step_name]["actions"].append(action_infos)
       
  1147     
       
  1148     def GenerateSFCAction(self, action_name, pou):
       
  1149         if action_name not in self.SFCNetworks["Actions"].keys():
       
  1150             actionContent = pou.getaction(action_name)
       
  1151             if actionContent:
       
  1152                 previous_tagname = self.TagName
       
  1153                 self.TagName = self.ParentGenerator.Controler.ComputePouActionName(self.Name, action_name)
       
  1154                 self.ComputeProgram(actionContent)
       
  1155                 self.SFCNetworks["Actions"][action_name] = (self.Program, (self.TagName, "name"))
       
  1156                 self.Program = []
       
  1157                 self.TagName = previous_tagname
       
  1158     
       
  1159     def GenerateSFCTransition(self, transition, pou):
       
  1160         if transition not in self.SFCNetworks["Transitions"].keys():
       
  1161             steps = []
       
  1162             connections = transition.connectionPointIn.getconnections()
       
  1163             if connections is not None and len(connections) == 1:
       
  1164                 instanceLocalId = connections[0].getrefLocalId()
       
  1165                 body = pou.getbody()
       
  1166                 if isinstance(body, ListType):
       
  1167                     body = body[0]
       
  1168                 instance = body.getcontentInstance(instanceLocalId)
       
  1169                 if isinstance(instance, plcopen.sfcObjects_step):
       
  1170                     steps.append(instance)
       
  1171                 elif isinstance(instance, plcopen.sfcObjects_selectionDivergence):
       
  1172                     step = self.ExtractDivergenceInput(instance, pou)
       
  1173                     if step:
       
  1174                         if isinstance(step, plcopen.sfcObjects_step):
       
  1175                             steps.append(step)
       
  1176                         elif isinstance(step, plcopen.sfcObjects_simultaneousConvergence):
       
  1177                             steps.extend(self.ExtractConvergenceInputs(step, pou))
       
  1178                 elif isinstance(instance, plcopen.sfcObjects_simultaneousConvergence):
       
  1179                     steps.extend(self.ExtractConvergenceInputs(instance, pou))
       
  1180             transition_infos = {"id" : transition.getlocalId(), 
       
  1181                                 "priority": transition.getpriority(), 
       
  1182                                 "from": [], 
       
  1183                                 "to" : []}
       
  1184             transitionValues = transition.getconditionContent()
       
  1185             if transitionValues["type"] == "inline":
       
  1186                 transition_infos["content"] = [("\n%s:= "%self.CurrentIndent, ()),
       
  1187                                                (transitionValues["value"], (self.TagName, "transition", transition.getlocalId(), "inline")),
       
  1188                                                (";\n", ())]
       
  1189             elif transitionValues["type"] == "reference":
       
  1190                 transitionContent = pou.gettransition(transitionValues["value"])
       
  1191                 transitionType = transitionContent.getbodyType()
       
  1192                 transitionBody = transitionContent.getbody()
       
  1193                 previous_tagname = self.TagName
       
  1194                 self.TagName = self.ParentGenerator.Controler.ComputePouTransitionName(self.Name, transitionValues["value"])
       
  1195                 if transitionType == "IL":
       
  1196                     transition_infos["content"] = [(":\n", ()),
       
  1197                                                    (ReIndentText(transitionBody.gettext(), len(self.CurrentIndent)), (self.TagName, "body", len(self.CurrentIndent)))]
       
  1198                 elif transitionType == "ST":
       
  1199                     transition_infos["content"] = [("\n", ()),
       
  1200                                                    (ReIndentText(transitionBody.gettext(), len(self.CurrentIndent)), (self.TagName, "body", len(self.CurrentIndent)))]
       
  1201                 else:
       
  1202                     for instance in transitionBody.getcontentInstances():
       
  1203                         if isinstance(instance, plcopen.fbdObjects_outVariable) and instance.getexpression() == transitionValues["value"]\
       
  1204                             or isinstance(instance, plcopen.ldObjects_coil) and instance.getvariable() == transitionValues["value"]:
       
  1205                             connections = instance.connectionPointIn.getconnections()
       
  1206                             if connections is not None:
       
  1207                                 expression = self.ComputeExpression(transitionBody, connections)
       
  1208                                 transition_infos["content"] = [("\n%s:= "%self.CurrentIndent, ())] + expression + [(";\n", ())]
       
  1209                                 self.SFCComputedBlocks += self.Program
       
  1210                                 self.Program = []
       
  1211                     if not transition_infos.has_key("content"):
       
  1212                         raise PLCGenException, _("Transition \"%s\" body must contain an output variable or coil referring to its name") % transitionValues["value"]
       
  1213                 self.TagName = previous_tagname
       
  1214             elif transitionValues["type"] == "connection":
       
  1215                 body = pou.getbody()
       
  1216                 if isinstance(body, ListType):
       
  1217                     body = body[0]
       
  1218                 connections = transition.getconnections()
       
  1219                 if connections is not None:
       
  1220                     expression = self.ComputeExpression(body, connections)
       
  1221                     transition_infos["content"] = [("\n%s:= "%self.CurrentIndent, ())] + expression + [(";\n", ())]
       
  1222                     self.SFCComputedBlocks += self.Program
       
  1223                     self.Program = []
       
  1224             for step in steps:
       
  1225                 self.GenerateSFCStep(step, pou)
       
  1226                 step_name = step.getname()
       
  1227                 if step_name in self.SFCNetworks["Steps"].keys():
       
  1228                     transition_infos["from"].append([(step_name, (self.TagName, "transition", transition.getlocalId(), "from", step.getlocalId()))])
       
  1229                     self.SFCNetworks["Steps"][step_name]["transitions"].append(transition)
       
  1230             self.SFCNetworks["Transitions"][transition] = transition_infos
       
  1231 
       
  1232     def ComputeSFCStep(self, step_name):
       
  1233         if step_name in self.SFCNetworks["Steps"].keys():
       
  1234             step_infos = self.SFCNetworks["Steps"].pop(step_name)
       
  1235             self.Program += [(self.CurrentIndent, ())]
       
  1236             if step_infos["initial"]:
       
  1237                 self.Program += [("INITIAL_", ())]
       
  1238             self.Program += [("STEP ", ()),
       
  1239                              (step_name, (self.TagName, "step", step_infos["id"], "name")),
       
  1240                              (":\n", ())]
       
  1241             actions = []
       
  1242             self.IndentRight()
       
  1243             for action_infos in step_infos["actions"]:
       
  1244                 if action_infos.get("id", None) is not None:
       
  1245                     action_info = (self.TagName, "action_block", action_infos["id"], "action", action_infos["num"])
       
  1246                 else:
       
  1247                     action_info = ()
       
  1248                 actions.append(action_infos["content"])
       
  1249                 self.Program += [(self.CurrentIndent, ()),
       
  1250                                  (action_infos["content"], action_info + ("reference",)),
       
  1251                                  ("(", ()),
       
  1252                                  (action_infos["qualifier"], action_info + ("qualifier",))]
       
  1253                 if "duration" in action_infos:
       
  1254                     self.Program += [(", ", ()),
       
  1255                                      (action_infos["duration"], action_info + ("duration",))]
       
  1256                 if "indicator" in action_infos:
       
  1257                     self.Program += [(", ", ()),
       
  1258                                      (action_infos["indicator"], action_info + ("indicator",))]
       
  1259                 self.Program += [(");\n", ())]
       
  1260             self.IndentLeft()
       
  1261             self.Program += [("%sEND_STEP\n\n"%self.CurrentIndent, ())]
       
  1262             for action in actions:
       
  1263                 self.ComputeSFCAction(action)
       
  1264             for transition in step_infos["transitions"]:
       
  1265                 self.ComputeSFCTransition(transition)
       
  1266                 
       
  1267     def ComputeSFCAction(self, action_name):
       
  1268         if action_name in self.SFCNetworks["Actions"].keys():
       
  1269             action_content, action_info = self.SFCNetworks["Actions"].pop(action_name)
       
  1270             self.Program += [("%sACTION "%self.CurrentIndent, ()),
       
  1271                              (action_name, action_info),
       
  1272                              (" :\n", ())]
       
  1273             self.Program += action_content
       
  1274             self.Program += [("%sEND_ACTION\n\n"%self.CurrentIndent, ())]
       
  1275     
       
  1276     def ComputeSFCTransition(self, transition):
       
  1277         if transition in self.SFCNetworks["Transitions"].keys():
       
  1278             transition_infos = self.SFCNetworks["Transitions"].pop(transition)
       
  1279             self.Program += [("%sTRANSITION"%self.CurrentIndent, ())]
       
  1280             if transition_infos["priority"] != None:
       
  1281                 self.Program += [(" (PRIORITY := ", ()),
       
  1282                                  ("%d"%transition_infos["priority"], (self.TagName, "transition", transition_infos["id"], "priority")),
       
  1283                                  (")", ())]
       
  1284             self.Program += [(" FROM ", ())]
       
  1285             if len(transition_infos["from"]) > 1:
       
  1286                 self.Program += [("(", ())]
       
  1287                 self.Program += JoinList([(", ", ())], transition_infos["from"])
       
  1288                 self.Program += [(")", ())]
       
  1289             elif len(transition_infos["from"]) == 1:
       
  1290                 self.Program += transition_infos["from"][0]
       
  1291             else:
       
  1292                 raise PLCGenException, _("Transition with content \"%s\" not connected to a previous step in \"%s\" POU")%(transition_infos["content"], self.Name)
       
  1293             self.Program += [(" TO ", ())]
       
  1294             if len(transition_infos["to"]) > 1:
       
  1295                 self.Program += [("(", ())]
       
  1296                 self.Program += JoinList([(", ", ())], transition_infos["to"])
       
  1297                 self.Program += [(")", ())]
       
  1298             elif len(transition_infos["to"]) == 1:
       
  1299                 self.Program += transition_infos["to"][0]
       
  1300             else:
       
  1301                 raise PLCGenException, _("Transition with content \"%s\" not connected to a next step in \"%s\" POU")%(transition_infos["content"], self.Name)
       
  1302             self.Program += transition_infos["content"]
       
  1303             self.Program += [("%sEND_TRANSITION\n\n"%self.CurrentIndent, ())]
       
  1304             for [(step_name, step_infos)] in transition_infos["to"]:
       
  1305                 self.ComputeSFCStep(step_name)
       
  1306     
       
  1307     def GenerateProgram(self, pou):
       
  1308         self.ComputeInterface(pou)
       
  1309         self.ComputeConnectionTypes(pou)
       
  1310         self.ComputeProgram(pou)
       
  1311         
       
  1312         program = [("%s "%self.Type, ()),
       
  1313                    (self.Name, (self.TagName, "name"))]
       
  1314         if self.ReturnType:
       
  1315             program += [(" : ", ()),
       
  1316                         (self.ReturnType, (self.TagName, "return"))]
       
  1317         program += [("\n", ())]
       
  1318         if len(self.Interface) == 0:
       
  1319             raise PLCGenException, _("No variable defined in \"%s\" POU")%self.Name
       
  1320         if len(self.Program) == 0 :
       
  1321             raise PLCGenException, _("No body defined in \"%s\" POU")%self.Name
       
  1322         var_number = 0
       
  1323         for list_type, option, located, variables in self.Interface:
       
  1324             variable_type = errorVarTypes.get(list_type, "var_local")
       
  1325             program += [("  %s"%list_type, ())]
       
  1326             if option is not None:
       
  1327                 program += [(" %s"%option, (self.TagName, variable_type, (var_number, var_number + len(variables)), option.lower()))]
       
  1328             program += [("\n", ())]
       
  1329             for var_type, var_name, var_address, var_initial in variables:
       
  1330                 program += [("    ", ())]
       
  1331                 if var_name:
       
  1332                     program += [(var_name, (self.TagName, variable_type, var_number, "name")),
       
  1333                                 (" ", ())]
       
  1334                 if var_address != None:
       
  1335                     program += [("AT ", ()),
       
  1336                                 (var_address, (self.TagName, variable_type, var_number, "location")),
       
  1337                                 (" ", ())]
       
  1338                 program += [(": ", ()),
       
  1339                             (var_type, (self.TagName, variable_type, var_number, "type"))]
       
  1340                 if var_initial != None:
       
  1341                     program += [(" := ", ()),
       
  1342                                 (self.ParentGenerator.ComputeValue(var_initial, var_type), (self.TagName, variable_type, var_number, "initial value"))]
       
  1343                 program += [(";\n", ())]
       
  1344                 var_number += 1
       
  1345             program += [("  END_VAR\n", ())]
       
  1346         program += [("\n", ())]
       
  1347         program += self.Program
       
  1348         program += [("END_%s\n\n"%self.Type, ())]
       
  1349         return program
       
  1350 
       
  1351 def GenerateCurrentProgram(controler, project, errors, warnings):
       
  1352     generator = ProgramGenerator(controler, project, errors, warnings)
       
  1353     generator.GenerateProgram()
       
  1354     return generator.GetGeneratedProgram()
       
  1355