Laurent@814: #!/usr/bin/env python Laurent@814: # -*- coding: utf-8 -*- Laurent@814: Laurent@814: import string, os, sys Laurent@814: Laurent@814: #This file is part of PLCOpenEditor, a library implementing an IEC 61131-3 editor Laurent@814: #based on the plcopen standard. Laurent@814: # Laurent@814: #Copyright (C) 2007: Edouard TISSERANT and Laurent BESSARD Laurent@814: # Laurent@814: #See COPYING file for copyrights details. Laurent@814: # Laurent@814: #This library is free software; you can redistribute it and/or Laurent@814: #modify it under the terms of the GNU General Public Laurent@814: #License as published by the Free Software Foundation; either Laurent@814: #version 2.1 of the License, or (at your option) any later version. Laurent@814: # Laurent@814: #This library is distributed in the hope that it will be useful, Laurent@814: #but WITHOUT ANY WARRANTY; without even the implied warranty of Laurent@814: #MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Laurent@814: #General Public License for more details. Laurent@814: # Laurent@814: #You should have received a copy of the GNU General Public Laurent@814: #License along with this library; if not, write to the Free Software Laurent@814: #Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Laurent@814: Laurent@814: Laurent@814: LANGUAGES = ["IL","ST","FBD","LD","SFC"] Laurent@814: Laurent@814: LOCATIONDATATYPES = {"X" : ["BOOL"], Laurent@814: "B" : ["SINT", "USINT", "BYTE", "STRING"], Laurent@814: "W" : ["INT", "UINT", "WORD", "WSTRING"], Laurent@814: "D" : ["DINT", "UDINT", "REAL", "DWORD"], Laurent@814: "L" : ["LINT", "ULINT", "LREAL", "LWORD"]} Laurent@814: Laurent@814: _ = lambda x:x Laurent@814: Laurent@814: # Helper for emulate join on element list Laurent@814: def JoinList(separator, mylist): Laurent@814: if len(mylist) > 0 : Laurent@814: return reduce(lambda x, y: x + separator + y, mylist) Laurent@814: else : Laurent@814: return mylist Laurent@814: Laurent@814: def generate_block(generator, block, block_infos, body, link, order=False, to_inout=False): Laurent@814: body_type = body.getcontent()["name"] Laurent@814: name = block.getinstanceName() Laurent@814: type = block.gettypeName() Laurent@814: executionOrderId = block.getexecutionOrderId() Laurent@814: inout_variables = {} Laurent@814: for input_variable in block.inputVariables.getvariable(): Laurent@814: for output_variable in block.outputVariables.getvariable(): Laurent@814: if input_variable.getformalParameter() == output_variable.getformalParameter(): Laurent@814: inout_variables[input_variable.getformalParameter()] = "" Laurent@814: if block_infos["type"] == "function": Laurent@814: output_variables = block.outputVariables.getvariable() Laurent@814: if not generator.ComputedBlocks.get(block, False) and not order: Laurent@814: generator.ComputedBlocks[block] = True Laurent@814: vars = [] Laurent@814: one_input_connected = False Laurent@814: for i, variable in enumerate(block.inputVariables.getvariable()): Laurent@814: input_info = (generator.TagName, "block", block.getlocalId(), "input", i) Laurent@814: connections = variable.connectionPointIn.getconnections() Laurent@814: if connections is not None: Laurent@814: parameter = variable.getformalParameter() Laurent@814: if parameter != "EN": Laurent@814: one_input_connected = True Laurent@814: if inout_variables.has_key(parameter): Laurent@814: value = generator.ComputeExpression(body, connections, executionOrderId > 0, True) Laurent@814: inout_variables[parameter] = value Laurent@814: else: Laurent@814: value = generator.ComputeExpression(body, connections, executionOrderId > 0) Laurent@814: if len(output_variables) > 1: Laurent@814: vars.append([(parameter, input_info), Laurent@814: (" := ", ())] + generator.ExtractModifier(variable, value, input_info)) Laurent@814: else: Laurent@814: vars.append(generator.ExtractModifier(variable, value, input_info)) Laurent@814: if one_input_connected: Laurent@814: for i, variable in enumerate(output_variables): Laurent@814: parameter = variable.getformalParameter() Laurent@814: if not inout_variables.has_key(parameter): Laurent@814: if variable.getformalParameter() == "": Laurent@814: variable_name = "%s%d"%(type, block.getlocalId()) Laurent@814: else: Laurent@814: variable_name = "%s%d_%s"%(type, block.getlocalId(), parameter) Laurent@814: if generator.Interface[-1][0] != "VAR" or generator.Interface[-1][1] is not None or generator.Interface[-1][2]: Laurent@814: generator.Interface.append(("VAR", None, False, [])) Laurent@814: if variable.connectionPointOut in generator.ConnectionTypes: Laurent@814: generator.Interface[-1][3].append((generator.ConnectionTypes[variable.connectionPointOut], variable_name, None, None)) Laurent@814: else: Laurent@814: generator.Interface[-1][3].append(("ANY", variable_name, None, None)) Laurent@814: if len(output_variables) > 1 and parameter not in ["", "OUT"]: Laurent@814: vars.append([(parameter, (generator.TagName, "block", block.getlocalId(), "output", i)), Laurent@814: (" => %s"%variable_name, ())]) Laurent@814: else: Laurent@814: output_info = (generator.TagName, "block", block.getlocalId(), "output", i) Laurent@814: output_name = variable_name Laurent@814: generator.Program += [(generator.CurrentIndent, ()), Laurent@814: (output_name, output_info), Laurent@814: (" := ", ()), Laurent@814: (type, (generator.TagName, "block", block.getlocalId(), "type")), Laurent@814: ("(", ())] Laurent@814: generator.Program += JoinList([(", ", ())], vars) Laurent@814: generator.Program += [(");\n", ())] Laurent@814: else: Laurent@814: generator.Warnings.append(_("\"%s\" function cancelled in \"%s\" POU: No input connected")%(type, generator.TagName.split("::")[-1])) Laurent@814: if link: Laurent@814: connectionPoint = link.getposition()[-1] Laurent@814: else: Laurent@814: connectionPoint = None Laurent@814: for i, variable in enumerate(output_variables): Laurent@814: blockPointx, blockPointy = variable.connectionPointOut.getrelPositionXY() Laurent@814: if not connectionPoint or block.getx() + blockPointx == connectionPoint.getx() and block.gety() + blockPointy == connectionPoint.gety(): Laurent@814: output_info = (generator.TagName, "block", block.getlocalId(), "output", i) Laurent@814: parameter = variable.getformalParameter() Laurent@814: if inout_variables.has_key(parameter): Laurent@814: output_value = inout_variables[parameter] Laurent@814: else: Laurent@814: if parameter == "": Laurent@814: output_name = "%s%d"%(type, block.getlocalId()) Laurent@814: else: Laurent@814: output_name = "%s%d_%s"%(type, block.getlocalId(), parameter) Laurent@814: output_value = [(output_name, output_info)] Laurent@814: return generator.ExtractModifier(variable, output_value, output_info) Laurent@814: elif block_infos["type"] == "functionBlock": Laurent@814: if not generator.ComputedBlocks.get(block, False) and not order: Laurent@814: generator.ComputedBlocks[block] = True Laurent@814: vars = [] Laurent@814: for i, variable in enumerate(block.inputVariables.getvariable()): Laurent@814: input_info = (generator.TagName, "block", block.getlocalId(), "input", i) Laurent@814: connections = variable.connectionPointIn.getconnections() Laurent@814: if connections is not None: Laurent@814: parameter = variable.getformalParameter() Laurent@814: value = generator.ComputeExpression(body, connections, executionOrderId > 0, inout_variables.has_key(parameter)) Laurent@814: vars.append([(parameter, input_info), Laurent@814: (" := ", ())] + generator.ExtractModifier(variable, value, input_info)) Laurent@814: generator.Program += [(generator.CurrentIndent, ()), Laurent@814: (name, (generator.TagName, "block", block.getlocalId(), "name")), Laurent@814: ("(", ())] Laurent@814: generator.Program += JoinList([(", ", ())], vars) Laurent@814: generator.Program += [(");\n", ())] Laurent@814: if link: Laurent@814: connectionPoint = link.getposition()[-1] Laurent@814: else: Laurent@814: connectionPoint = None Laurent@814: for i, variable in enumerate(block.outputVariables.getvariable()): Laurent@814: blockPointx, blockPointy = variable.connectionPointOut.getrelPositionXY() Laurent@814: if not connectionPoint or block.getx() + blockPointx == connectionPoint.getx() and block.gety() + blockPointy == connectionPoint.gety(): Laurent@814: output_info = (generator.TagName, "block", block.getlocalId(), "output", i) Laurent@814: output_name = generator.ExtractModifier(variable, [("%s.%s"%(name, variable.getformalParameter()), output_info)], output_info) Laurent@814: if to_inout: Laurent@814: variable_name = "%s_%s"%(name, variable.getformalParameter()) Laurent@814: if not generator.IsAlreadyDefined(variable_name): Laurent@814: if generator.Interface[-1][0] != "VAR" or generator.Interface[-1][1] is not None or generator.Interface[-1][2]: Laurent@814: generator.Interface.append(("VAR", None, False, [])) Laurent@814: if variable.connectionPointOut in generator.ConnectionTypes: Laurent@814: generator.Interface[-1][3].append((generator.ConnectionTypes[variable.connectionPointOut], variable_name, None, None)) Laurent@814: else: Laurent@814: generator.Interface[-1][3].append(("ANY", variable_name, None, None)) Laurent@814: generator.Program += [(generator.CurrentIndent, ()), Laurent@814: ("%s := "%variable_name, ())] Laurent@814: generator.Program += output_name Laurent@814: generator.Program += [(";\n", ())] Laurent@814: return [(variable_name, ())] Laurent@814: return output_name Laurent@814: if link is not None: Laurent@814: raise ValueError, _("No output variable found") Laurent@814: Laurent@814: def initialise_block(type, name, block = None): Laurent@814: return [(type, name, None, None)] Laurent@814: Laurent@814: #------------------------------------------------------------------------------- Laurent@814: # Function Block Types definitions Laurent@814: #------------------------------------------------------------------------------- Laurent@814: Laurent@814: Laurent@814: """ Laurent@814: Ordored list of common Function Blocks defined in the IEC 61131-3 Laurent@814: Each block have this attributes: Laurent@814: - "name" : The block name Laurent@814: - "type" : The block type. It can be "function", "functionBlock" or "program" Laurent@814: - "extensible" : Boolean that define if the block is extensible Laurent@814: - "inputs" : List of the block inputs Laurent@814: - "outputs" : List of the block outputs Laurent@814: - "comment" : Comment that will be displayed in the block popup Laurent@814: - "generate" : Method that generator will call for generating ST block code Laurent@814: Inputs and outputs are a tuple of characteristics that are in order: Laurent@814: - The name Laurent@814: - The data type Laurent@814: - The default modifier which can be "none", "negated", "rising" or "falling" Laurent@814: """ Laurent@814: Laurent@814: BlockTypes = [{"name" : _("Standard function blocks"), "list": Laurent@814: [{"name" : "SR", "type" : "functionBlock", "extensible" : False, Laurent@814: "inputs" : [("S1","BOOL","none"),("R","BOOL","none")], Laurent@814: "outputs" : [("Q1","BOOL","none")], Laurent@814: "comment" : _("SR bistable\nThe SR bistable is a latch where the Set dominates."), Laurent@814: "generate" : generate_block, "initialise" : initialise_block}, Laurent@814: {"name" : "RS", "type" : "functionBlock", "extensible" : False, Laurent@814: "inputs" : [("S","BOOL","none"),("R1","BOOL","none")], Laurent@814: "outputs" : [("Q1","BOOL","none")], Laurent@814: "comment" : _("RS bistable\nThe RS bistable is a latch where the Reset dominates."), Laurent@814: "generate" : generate_block, "initialise" : initialise_block}, Laurent@814: {"name" : "SEMA", "type" : "functionBlock", "extensible" : False, Laurent@814: "inputs" : [("CLAIM","BOOL","none"),("RELEASE","BOOL","none")], Laurent@814: "outputs" : [("BUSY","BOOL","none")], Laurent@814: "comment" : _("Semaphore\nThe semaphore provides a mechanism to allow software elements mutually exclusive access to certain ressources."), Laurent@814: "generate" : generate_block, "initialise" : initialise_block}, Laurent@814: {"name" : "R_TRIG", "type" : "functionBlock", "extensible" : False, Laurent@814: "inputs" : [("CLK","BOOL","none")], Laurent@814: "outputs" : [("Q","BOOL","none")], Laurent@814: "comment" : _("Rising edge detector\nThe output produces a single pulse when a rising edge is detected."), Laurent@814: "generate" : generate_block, "initialise" : initialise_block}, Laurent@814: {"name" : "F_TRIG", "type" : "functionBlock", "extensible" : False, Laurent@814: "inputs" : [("CLK","BOOL","none")], Laurent@814: "outputs" : [("Q","BOOL","none")], Laurent@814: "comment" : _("Falling edge detector\nThe output produces a single pulse when a falling edge is detected."), Laurent@814: "generate" : generate_block, "initialise" : initialise_block}, Laurent@814: {"name" : "CTU", "type" : "functionBlock", "extensible" : False, Laurent@814: "inputs" : [("CU","BOOL","rising"),("R","BOOL","none"),("PV","INT","none")], Laurent@814: "outputs" : [("Q","BOOL","none"),("CV","INT","none")], Laurent@814: "comment" : _("Up-counter\nThe up-counter can be used to signal when a count has reached a maximum value."), Laurent@814: "generate" : generate_block, "initialise" : initialise_block}, Laurent@814: {"name" : "CTD", "type" : "functionBlock", "extensible" : False, Laurent@814: "inputs" : [("CD","BOOL","rising"),("LD","BOOL","none"),("PV","INT","none")], Laurent@814: "outputs" : [("Q","BOOL","none"),("CV","INT","none")], Laurent@814: "comment" : _("Down-counter\nThe down-counter can be used to signal when a count has reached zero, on counting down from a preset value."), Laurent@814: "generate" : generate_block, "initialise" : initialise_block}, Laurent@814: {"name" : "CTUD", "type" : "functionBlock", "extensible" : False, Laurent@814: "inputs" : [("CU","BOOL","rising"),("CD","BOOL","rising"),("R","BOOL","none"),("LD","BOOL","none"),("PV","INT","none")], Laurent@814: "outputs" : [("QU","BOOL","none"),("QD","BOOL","none"),("CV","INT","none")], Laurent@814: "comment" : _("Up-down counter\nThe up-down counter has two inputs CU and CD. It can be used to both count up on one input and down on the other."), Laurent@814: "generate" : generate_block, "initialise" : initialise_block}, Laurent@814: {"name" : "TP", "type" : "functionBlock", "extensible" : False, Laurent@814: "inputs" : [("IN","BOOL","none"),("PT","TIME","none")], Laurent@814: "outputs" : [("Q","BOOL","none"),("ET","TIME","none")], Laurent@814: "comment" : _("Pulse timer\nThe pulse timer can be used to generate output pulses of a given time duration."), Laurent@814: "generate" : generate_block, "initialise" : initialise_block}, Laurent@814: {"name" : "TON", "type" : "functionBlock", "extensible" : False, Laurent@814: "inputs" : [("IN","BOOL","none"),("PT","TIME","none")], Laurent@814: "outputs" : [("Q","BOOL","none"),("ET","TIME","none")], Laurent@814: "comment" : _("On-delay timer\nThe on-delay timer can be used to delay setting an output true, for fixed period after an input becomes true."), Laurent@814: "generate" : generate_block, "initialise" : initialise_block}, Laurent@814: {"name" : "TOF", "type" : "functionBlock", "extensible" : False, Laurent@814: "inputs" : [("IN","BOOL","none"),("PT","TIME","none")], Laurent@814: "outputs" : [("Q","BOOL","none"),("ET","TIME","none")], Laurent@814: "comment" : _("Off-delay timer\nThe off-delay timer can be used to delay setting an output false, for fixed period after input goes false."), Laurent@814: "generate" : generate_block, "initialise" : initialise_block}, Laurent@814: ]}, Laurent@814: {"name" : _("Additional function blocks"), "list": Laurent@814: [{"name" : "RTC", "type" : "functionBlock", "extensible" : False, Laurent@814: "inputs" : [("IN","BOOL","none"),("PDT","DATE_AND_TIME","none")], Laurent@814: "outputs" : [("Q","BOOL","none"),("CDT","DATE_AND_TIME","none")], Laurent@814: "comment" : _("Real time clock\nThe real time clock has many uses including time stamping, setting dates and times of day in batch reports, in alarm messages and so on."), Laurent@814: "generate" : generate_block, "initialise" : initialise_block}, Laurent@814: {"name" : "INTEGRAL", "type" : "functionBlock", "extensible" : False, Laurent@814: "inputs" : [("RUN","BOOL","none"),("R1","BOOL","none"),("XIN","REAL","none"),("X0","REAL","none"),("CYCLE","TIME","none")], Laurent@814: "outputs" : [("Q","BOOL","none"),("XOUT","REAL","none")], Laurent@814: "comment" : _("Integral\nThe integral function block integrates the value of input XIN over time."), Laurent@814: "generate" : generate_block, "initialise" : initialise_block}, Laurent@814: {"name" : "DERIVATIVE", "type" : "functionBlock", "extensible" : False, Laurent@814: "inputs" : [("RUN","BOOL","none"),("XIN","REAL","none"),("CYCLE","TIME","none")], Laurent@814: "outputs" : [("XOUT","REAL","none")], Laurent@814: "comment" : _("Derivative\nThe derivative function block produces an output XOUT proportional to the rate of change of the input XIN."), Laurent@814: "generate" : generate_block, "initialise" : initialise_block}, Laurent@814: {"name" : "PID", "type" : "functionBlock", "extensible" : False, Laurent@814: "inputs" : [("AUTO","BOOL","none"),("PV","REAL","none"),("SP","REAL","none"),("X0","REAL","none"),("KP","REAL","none"),("TR","REAL","none"),("TD","REAL","none"),("CYCLE","TIME","none")], Laurent@814: "outputs" : [("XOUT","REAL","none")], Laurent@814: "comment" : _("PID\nThe PID (proportional, Integral, Derivative) function block provides the classical three term controller for closed loop control."), Laurent@814: "generate" : generate_block, "initialise" : initialise_block}, Laurent@814: {"name" : "RAMP", "type" : "functionBlock", "extensible" : False, Laurent@814: "inputs" : [("RUN","BOOL","none"),("X0","REAL","none"),("X1","REAL","none"),("TR","TIME","none"),("CYCLE","TIME","none")], Laurent@814: "outputs" : [("BUSY","BOOL","none"),("XOUT","REAL","none")], Laurent@814: "comment" : _("Ramp\nThe RAMP function block is modelled on example given in the standard."), Laurent@814: "generate" : generate_block, "initialise" : initialise_block}, Laurent@814: {"name" : "HYSTERESIS", "type" : "functionBlock", "extensible" : False, Laurent@814: "inputs" : [("XIN1","REAL","none"),("XIN2","REAL","none"),("EPS","REAL","none")], Laurent@814: "outputs" : [("Q","BOOL","none")], Laurent@814: "comment" : _("Hysteresis\nThe hysteresis function block provides a hysteresis boolean output driven by the difference of two floating point (REAL) inputs XIN1 and XIN2."), Laurent@814: "generate" : generate_block, "initialise" : initialise_block}, Laurent@814: ## {"name" : "RATIO_MONITOR", "type" : "functionBlock", "extensible" : False, Laurent@814: ## "inputs" : [("PV1","REAL","none"),("PV2","REAL","none"),("RATIO","REAL","none"),("TIMON","TIME","none"),("TIMOFF","TIME","none"),("TOLERANCE","BOOL","none"),("RESET","BOOL","none"),("CYCLE","TIME","none")], Laurent@814: ## "outputs" : [("ALARM","BOOL","none"),("TOTAL_ERR","BOOL","none")], Laurent@814: ## "comment" : _("Ratio monitor\nThe ratio_monitor function block checks that one process value PV1 is always a given ratio (defined by input RATIO) of a second process value PV2."), Laurent@814: ## "generate" : generate_block, "initialise" : initialise_block} Laurent@814: ]}, Laurent@814: ] Laurent@814: Laurent@814: Laurent@814: #------------------------------------------------------------------------------- Laurent@814: # Data Types definitions Laurent@814: #------------------------------------------------------------------------------- Laurent@814: Laurent@814: """ Laurent@814: Ordored list of common data types defined in the IEC 61131-3 Laurent@814: Each type is associated to his direct parent type. It defines then a hierarchy Laurent@814: between type that permits to make a comparison of two types Laurent@814: """ Laurent@814: TypeHierarchy_list = [ Laurent@814: ("ANY", None), Laurent@814: ("ANY_DERIVED", "ANY"), Laurent@814: ("ANY_ELEMENTARY", "ANY"), Laurent@814: ("ANY_MAGNITUDE", "ANY_ELEMENTARY"), Laurent@814: ("ANY_BIT", "ANY_ELEMENTARY"), Laurent@814: ("ANY_NBIT", "ANY_BIT"), Laurent@814: ("ANY_STRING", "ANY_ELEMENTARY"), Laurent@814: ("ANY_DATE", "ANY_ELEMENTARY"), Laurent@814: ("ANY_NUM", "ANY_MAGNITUDE"), Laurent@814: ("ANY_REAL", "ANY_NUM"), Laurent@814: ("ANY_INT", "ANY_NUM"), Laurent@814: ("ANY_SINT", "ANY_INT"), Laurent@814: ("ANY_UINT", "ANY_INT"), Laurent@814: ("BOOL", "ANY_BIT"), Laurent@814: ("SINT", "ANY_SINT"), Laurent@814: ("INT", "ANY_SINT"), Laurent@814: ("DINT", "ANY_SINT"), Laurent@814: ("LINT", "ANY_SINT"), Laurent@814: ("USINT", "ANY_UINT"), Laurent@814: ("UINT", "ANY_UINT"), Laurent@814: ("UDINT", "ANY_UINT"), Laurent@814: ("ULINT", "ANY_UINT"), Laurent@814: ("REAL", "ANY_REAL"), Laurent@814: ("LREAL", "ANY_REAL"), Laurent@814: ("TIME", "ANY_MAGNITUDE"), Laurent@814: ("DATE", "ANY_DATE"), Laurent@814: ("TOD", "ANY_DATE"), Laurent@814: ("DT", "ANY_DATE"), Laurent@814: ("STRING", "ANY_STRING"), Laurent@814: ("BYTE", "ANY_NBIT"), Laurent@814: ("WORD", "ANY_NBIT"), Laurent@814: ("DWORD", "ANY_NBIT"), Laurent@814: ("LWORD", "ANY_NBIT") Laurent@814: #("WSTRING", "ANY_STRING") # TODO Laurent@814: ] Laurent@814: Laurent@814: TypeHierarchy = dict(TypeHierarchy_list) Laurent@814: Laurent@814: """ Laurent@814: returns true if the given data type is the same that "reference" meta-type or one of its types. Laurent@814: """ Laurent@814: def IsOfType(type, reference): Laurent@814: if reference is None: Laurent@814: return True Laurent@814: elif type == reference: Laurent@814: return True Laurent@814: else: Laurent@814: parent_type = TypeHierarchy[type] Laurent@814: if parent_type is not None: Laurent@814: return IsOfType(parent_type, reference) Laurent@814: return False Laurent@814: Laurent@814: """ Laurent@814: returns list of all types that correspont to the ANY* meta type Laurent@814: """ Laurent@814: def GetSubTypes(type): Laurent@814: return [typename for typename, parenttype in TypeHierarchy.items() if not typename.startswith("ANY") and IsOfType(typename, type)] Laurent@814: Laurent@814: Laurent@814: DataTypeRange_list = [ Laurent@814: ("SINT", (-2**7, 2**7 - 1)), Laurent@814: ("INT", (-2**15, 2**15 - 1)), Laurent@814: ("DINT", (-2**31, 2**31 - 1)), Laurent@814: ("LINT", (-2**31, 2**31 - 1)), Laurent@814: ("USINT", (0, 2**8 - 1)), Laurent@814: ("UINT", (0, 2**16 - 1)), Laurent@814: ("UDINT", (0, 2**31 - 1)), Laurent@814: ("ULINT", (0, 2**31 - 1)) Laurent@814: ] Laurent@814: Laurent@814: DataTypeRange = dict(DataTypeRange_list) Laurent@814: Laurent@814: Laurent@814: Laurent@814: #------------------------------------------------------------------------------- Laurent@814: # Test identifier Laurent@814: #------------------------------------------------------------------------------- Laurent@814: Laurent@814: Laurent@814: Laurent@814: # Test if identifier is valid Laurent@814: def TestIdentifier(identifier): Laurent@814: if identifier[0].isdigit(): Laurent@814: return False Laurent@814: words = identifier.split('_') Laurent@814: for i, word in enumerate(words): Laurent@814: if len(word) == 0 and i != 0: Laurent@814: return False Laurent@814: if len(word) != 0 and not word.isalnum(): Laurent@814: return False Laurent@814: return True Laurent@814: Laurent@814: Laurent@814: #------------------------------------------------------------------------------- Laurent@814: # Standard functions list generation Laurent@814: #------------------------------------------------------------------------------- Laurent@814: Laurent@814: Laurent@814: """ Laurent@814: take a .csv file and translate it it a "csv_table" Laurent@814: """ Laurent@814: def csv_file_to_table(file): Laurent@814: return [ map(string.strip,line.split(';')) for line in file.xreadlines()] Laurent@814: Laurent@814: """ Laurent@814: seek into the csv table to a section ( section_name match 1st field ) Laurent@814: return the matching row without first field Laurent@814: """ Laurent@814: def find_section(section_name, table): Laurent@814: fields = [None] Laurent@814: while(fields[0] != section_name): Laurent@814: fields = table.pop(0) Laurent@814: return fields[1:] Laurent@814: Laurent@814: """ Laurent@814: extract the standard functions standard parameter names and types... Laurent@814: return a { ParameterName: Type, ...} Laurent@814: """ Laurent@814: def get_standard_funtions_input_variables(table): Laurent@814: variables = find_section("Standard_functions_variables_types", table) Laurent@814: standard_funtions_input_variables = {} Laurent@814: fields = [True,True] Laurent@814: while(fields[1]): Laurent@814: fields = table.pop(0) Laurent@814: variable_from_csv = dict([(champ, val) for champ, val in zip(variables, fields[1:]) if champ!='']) Laurent@814: standard_funtions_input_variables[variable_from_csv['name']] = variable_from_csv['type'] Laurent@814: return standard_funtions_input_variables Laurent@814: Laurent@814: """ Laurent@814: translate .csv file input declaration into PLCOpenEditor interessting values Laurent@814: in : "(ANY_NUM, ANY_NUM)" and { ParameterName: Type, ...} Laurent@814: return [("IN1","ANY_NUM","none"),("IN2","ANY_NUM","none")] Laurent@814: """ Laurent@814: def csv_input_translate(str_decl, variables, base): Laurent@814: decl = str_decl.replace('(','').replace(')','').replace(' ','').split(',') Laurent@814: params = [] Laurent@814: Laurent@814: len_of_not_predifined_variable = len([True for param_type in decl if param_type not in variables]) Laurent@814: Laurent@814: for param_type in decl: Laurent@814: if param_type in variables.keys(): Laurent@814: param_name = param_type Laurent@814: param_type = variables[param_type] Laurent@814: elif len_of_not_predifined_variable > 1: Laurent@814: param_name = "IN%d"%base Laurent@814: base += 1 Laurent@814: else: Laurent@814: param_name = "IN" Laurent@814: params.append((param_name, param_type, "none")) Laurent@814: return params Laurent@814: Laurent@814: Laurent@814: ANY_TO_ANY_LIST=[ Laurent@814: # simple type conv are let as C cast Laurent@814: (("ANY_INT","ANY_BIT"),("ANY_NUM","ANY_BIT"), ("return_type", "__move_", "IN_type")), Laurent@814: (("ANY_REAL",),("ANY_REAL",), ("return_type", "__move_", "IN_type")), Laurent@814: # REAL_TO_INT Laurent@814: (("ANY_REAL",),("ANY_SINT",), ("return_type", "__real_to_sint", None)), Laurent@814: (("ANY_REAL",),("ANY_UINT",), ("return_type", "__real_to_uint", None)), Laurent@814: (("ANY_REAL",),("ANY_BIT",), ("return_type", "__real_to_bit", None)), Laurent@814: # TO_TIME Laurent@814: (("ANY_INT","ANY_BIT"),("ANY_DATE","TIME"), ("return_type", "__int_to_time", None)), Laurent@814: (("ANY_REAL",),("ANY_DATE","TIME"), ("return_type", "__real_to_time", None)), Laurent@814: (("ANY_STRING",), ("ANY_DATE","TIME"), ("return_type", "__string_to_time", None)), Laurent@814: # FROM_TIME Laurent@814: (("ANY_DATE","TIME"), ("ANY_REAL",), ("return_type", "__time_to_real", None)), Laurent@814: (("ANY_DATE","TIME"), ("ANY_INT","ANY_NBIT"), ("return_type", "__time_to_int", None)), Laurent@814: (("TIME",), ("ANY_STRING",), ("return_type", "__time_to_string", None)), Laurent@814: (("DATE",), ("ANY_STRING",), ("return_type", "__date_to_string", None)), Laurent@814: (("TOD",), ("ANY_STRING",), ("return_type", "__tod_to_string", None)), Laurent@814: (("DT",), ("ANY_STRING",), ("return_type", "__dt_to_string", None)), Laurent@814: # TO_STRING Laurent@814: (("BOOL",), ("ANY_STRING",), ("return_type", "__bool_to_string", None)), Laurent@814: (("ANY_BIT",), ("ANY_STRING",), ("return_type", "__bit_to_string", None)), Laurent@814: (("ANY_REAL",), ("ANY_STRING",), ("return_type", "__real_to_string", None)), Laurent@814: (("ANY_SINT",), ("ANY_STRING",), ("return_type", "__sint_to_string", None)), Laurent@814: (("ANY_UINT",), ("ANY_STRING",), ("return_type", "__uint_to_string", None)), Laurent@814: # FROM_STRING Laurent@814: (("ANY_STRING",), ("BOOL",), ("return_type", "__string_to_bool", None)), Laurent@814: (("ANY_STRING",), ("ANY_BIT",), ("return_type", "__string_to_bit", None)), Laurent@814: (("ANY_STRING",), ("ANY_SINT",), ("return_type", "__string_to_sint", None)), Laurent@814: (("ANY_STRING",), ("ANY_UINT",), ("return_type", "__string_to_uint", None)), Laurent@814: (("ANY_STRING",), ("ANY_REAL",), ("return_type", "__string_to_real", None))] Laurent@814: Laurent@814: Laurent@814: BCD_TO_ANY_LIST=[ Laurent@814: (("BYTE",),("USINT",), ("return_type", "__bcd_to_uint", None)), Laurent@814: (("WORD",),("UINT",), ("return_type", "__bcd_to_uint", None)), Laurent@814: (("DWORD",),("UDINT",), ("return_type", "__bcd_to_uint", None)), Laurent@814: (("LWORD",),("ULINT",), ("return_type", "__bcd_to_uint", None))] Laurent@814: Laurent@814: Laurent@814: ANY_TO_BCD_LIST=[ Laurent@814: (("USINT",),("BYTE",), ("return_type", "__uint_to_bcd", None)), Laurent@814: (("UINT",),("WORD",), ("return_type", "__uint_to_bcd", None)), Laurent@814: (("UDINT",),("DWORD",), ("return_type", "__uint_to_bcd", None)), Laurent@814: (("ULINT",),("LWORD",), ("return_type", "__uint_to_bcd", None))] Laurent@814: Laurent@814: Laurent@814: def ANY_TO_ANY_FORMAT_GEN(any_to_any_list, fdecl): Laurent@814: Laurent@814: for (InTypes, OutTypes, Format) in any_to_any_list: Laurent@814: outs = reduce(lambda a,b: a or b, map(lambda testtype : IsOfType(fdecl["outputs"][0][1],testtype), OutTypes)) Laurent@814: inps = reduce(lambda a,b: a or b, map(lambda testtype : IsOfType(fdecl["inputs"][0][1],testtype), InTypes)) Laurent@814: if inps and outs and fdecl["outputs"][0][1] != fdecl["inputs"][0][1]: Laurent@814: return Format Laurent@814: Laurent@814: return None Laurent@814: Laurent@814: Laurent@814: """ Laurent@814: Returns this kind of declaration for all standard functions Laurent@814: Laurent@814: [{"name" : "Numerical", 'list': [ { Laurent@814: 'baseinputnumber': 1, Laurent@814: 'comment': 'Addition', Laurent@814: 'extensible': True, Laurent@814: 'inputs': [ ('IN1', 'ANY_NUM', 'none'), Laurent@814: ('IN2', 'ANY_NUM', 'none')], Laurent@814: 'name': 'ADD', Laurent@814: 'outputs': [('OUT', 'ANY_NUM', 'none')], Laurent@814: 'type': 'function'}, ...... ] },.....] Laurent@814: """ Laurent@814: def get_standard_funtions(table): Laurent@814: Laurent@814: variables = get_standard_funtions_input_variables(table) Laurent@814: Laurent@814: fonctions = find_section("Standard_functions_type",table) Laurent@814: Laurent@814: Standard_Functions_Decl = [] Laurent@814: Current_section = None Laurent@814: Laurent@814: translate = { Laurent@814: "extensible" : lambda x: {"yes":True, "no":False}[x], Laurent@814: "inputs" : lambda x:csv_input_translate(x,variables,baseinputnumber), Laurent@814: "outputs":lambda x:[("OUT",x,"none")]} Laurent@814: Laurent@814: for fields in table: Laurent@814: if fields[1]: Laurent@814: # If function section name given Laurent@814: if fields[0]: Laurent@814: words = fields[0].split('"') Laurent@814: if len(words) > 1: Laurent@814: section_name = words[1] Laurent@814: else: Laurent@814: section_name = fields[0] Laurent@814: Current_section = {"name" : section_name, "list" : []} Laurent@814: Standard_Functions_Decl.append(Current_section) Laurent@814: Function_decl_list = [] Laurent@814: if Current_section: Laurent@814: Function_decl = dict([(champ, val) for champ, val in zip(fonctions, fields[1:]) if champ]) Laurent@814: Function_decl["generate"] = generate_block Laurent@814: Function_decl["initialise"] = lambda x,y:[] Laurent@814: baseinputnumber = int(Function_decl.get("baseinputnumber",1)) Laurent@814: Function_decl["baseinputnumber"] = baseinputnumber Laurent@814: for param, value in Function_decl.iteritems(): Laurent@814: if param in translate: Laurent@814: Function_decl[param] = translate[param](value) Laurent@814: Function_decl["type"] = "function" Laurent@814: Laurent@814: if Function_decl["name"].startswith('*') or Function_decl["name"].endswith('*') : Laurent@814: input_ovrloading_types = GetSubTypes(Function_decl["inputs"][0][1]) Laurent@814: output_types = GetSubTypes(Function_decl["outputs"][0][1]) Laurent@814: else: Laurent@814: input_ovrloading_types = [None] Laurent@814: output_types = [None] Laurent@814: Laurent@814: funcdeclname_orig = Function_decl["name"] Laurent@814: funcdeclname = Function_decl["name"].strip('*_') Laurent@814: fdc = Function_decl["inputs"][:] Laurent@814: for intype in input_ovrloading_types: Laurent@814: if intype != None: Laurent@814: Function_decl["inputs"] = [] Laurent@814: for decl_tpl in fdc: Laurent@814: if IsOfType(intype, decl_tpl[1]): Laurent@814: Function_decl["inputs"] += [(decl_tpl[0], intype, decl_tpl[2])] Laurent@814: else: Laurent@814: Function_decl["inputs"] += [(decl_tpl)] Laurent@814: Laurent@814: if funcdeclname_orig.startswith('*'): Laurent@814: funcdeclin = intype + '_' + funcdeclname Laurent@814: else: Laurent@814: funcdeclin = funcdeclname Laurent@814: else: Laurent@814: funcdeclin = funcdeclname Laurent@814: Laurent@814: for outype in output_types: Laurent@814: if outype != None: Laurent@814: decl_tpl = Function_decl["outputs"][0] Laurent@814: Function_decl["outputs"] = [ (decl_tpl[0] , outype, decl_tpl[2])] Laurent@814: if funcdeclname_orig.endswith('*'): Laurent@814: funcdeclout = funcdeclin + '_' + outype Laurent@814: else: Laurent@814: funcdeclout = funcdeclin Laurent@814: else: Laurent@814: funcdeclout = funcdeclin Laurent@814: Function_decl["name"] = funcdeclout Laurent@814: Laurent@814: Laurent@814: fdecl = Function_decl Laurent@814: res = eval(Function_decl["python_eval_c_code_format"]) Laurent@814: Laurent@814: if res != None : Laurent@814: # create the copy of decl dict to be appended to section Laurent@814: Function_decl_copy = Function_decl.copy() Laurent@814: Current_section["list"].append(Function_decl_copy) Laurent@814: else: Laurent@814: raise "First function must be in a category" Laurent@814: Laurent@814: return Standard_Functions_Decl Laurent@814: Laurent@814: std_decl = get_standard_funtions(csv_file_to_table(open(os.path.join(os.path.split(__file__)[0],"iec_std.csv"))))#, True) Laurent@814: Laurent@814: BlockTypes.extend(std_decl) Laurent@814: Laurent@814: for section in BlockTypes: Laurent@814: for desc in section["list"]: Laurent@814: words = desc["comment"].split('"') Laurent@814: if len(words) > 1: Laurent@814: desc["comment"] = words[1] Laurent@814: desc["usage"] = ( Laurent@814: "\n (" + Laurent@814: str([ " " + fctdecl[1]+":"+fctdecl[0] for fctdecl in desc["inputs"]]).strip("[]").replace("'",'') + Laurent@814: " ) => (" + Laurent@814: str([ " " + fctdecl[1]+":"+fctdecl[0] for fctdecl in desc["outputs"]]).strip("[]").replace("'",'') + Laurent@814: " )") Laurent@814: Laurent@814: Laurent@814: #------------------------------------------------------------------------------- Laurent@814: # Languages Keywords Laurent@814: #------------------------------------------------------------------------------- Laurent@814: Laurent@814: Laurent@814: # Keywords for Pou Declaration Laurent@814: POU_BLOCK_START_KEYWORDS = ["FUNCTION", "FUNCTION_BLOCK", "PROGRAM"] Laurent@814: POU_BLOCK_END_KEYWORDS = ["END_FUNCTION", "END_FUNCTION_BLOCK", "END_PROGRAM"] Laurent@814: POU_KEYWORDS = ["EN", "ENO", "F_EDGE", "R_EDGE"] + POU_BLOCK_START_KEYWORDS + POU_BLOCK_END_KEYWORDS Laurent@814: for category in BlockTypes: Laurent@814: for block in category["list"]: Laurent@814: if block["name"] not in POU_KEYWORDS: Laurent@814: POU_KEYWORDS.append(block["name"]) Laurent@814: Laurent@814: Laurent@814: # Keywords for Type Declaration Laurent@814: TYPE_BLOCK_START_KEYWORDS = ["TYPE", "STRUCT"] Laurent@814: TYPE_BLOCK_END_KEYWORDS = ["END_TYPE", "END_STRUCT"] Laurent@814: TYPE_KEYWORDS = ["ARRAY", "OF", "T", "D", "TIME_OF_DAY", "DATE_AND_TIME"] + TYPE_BLOCK_START_KEYWORDS + TYPE_BLOCK_END_KEYWORDS Laurent@814: TYPE_KEYWORDS.extend([keyword for keyword in TypeHierarchy.keys() if keyword not in TYPE_KEYWORDS]) Laurent@814: Laurent@814: Laurent@814: # Keywords for Variable Declaration Laurent@814: VAR_BLOCK_START_KEYWORDS = ["VAR", "VAR_INPUT", "VAR_OUTPUT", "VAR_IN_OUT", "VAR_TEMP", "VAR_EXTERNAL"] Laurent@814: VAR_BLOCK_END_KEYWORDS = ["END_VAR"] Laurent@814: VAR_KEYWORDS = ["AT", "CONSTANT", "RETAIN", "NON_RETAIN"] + VAR_BLOCK_START_KEYWORDS + VAR_BLOCK_END_KEYWORDS Laurent@814: Laurent@814: Laurent@814: # Keywords for Configuration Declaration Laurent@814: CONFIG_BLOCK_START_KEYWORDS = ["CONFIGURATION", "RESOURCE", "VAR_ACCESS", "VAR_CONFIG", "VAR_GLOBAL"] Laurent@814: CONFIG_BLOCK_END_KEYWORDS = ["END_CONFIGURATION", "END_RESOURCE", "END_VAR"] Laurent@814: CONFIG_KEYWORDS = ["ON", "PROGRAM", "WITH", "READ_ONLY", "READ_WRITE", "TASK"] + CONFIG_BLOCK_START_KEYWORDS + CONFIG_BLOCK_END_KEYWORDS Laurent@814: Laurent@814: # Keywords for Structured Function Chart Laurent@814: SFC_BLOCK_START_KEYWORDS = ["ACTION", "INITIAL_STEP", "STEP", "TRANSITION"] Laurent@814: SFC_BLOCK_END_KEYWORDS = ["END_ACTION", "END_STEP", "END_TRANSITION"] Laurent@814: SFC_KEYWORDS = ["FROM", "TO"] + SFC_BLOCK_START_KEYWORDS + SFC_BLOCK_START_KEYWORDS Laurent@814: Laurent@814: Laurent@814: # Keywords for Instruction List Laurent@814: IL_KEYWORDS = ["TRUE", "FALSE", "LD", "LDN", "ST", "STN", "S", "R", "AND", "ANDN", "OR", "ORN", Laurent@814: "XOR", "XORN", "NOT", "ADD", "SUB", "MUL", "DIV", "MOD", "GT", "GE", "EQ", "NE", Laurent@814: "LE", "LT", "JMP", "JMPC", "JMPCN", "CAL", "CALC", "CALCN", "RET", "RETC", "RETCN"] Laurent@814: Laurent@814: Laurent@814: # Keywords for Structured Text Laurent@814: ST_BLOCK_START_KEYWORDS = ["IF", "ELSIF", "ELSE", "CASE", "FOR", "WHILE", "REPEAT"] Laurent@814: ST_BLOCK_END_KEYWORDS = ["END_IF", "END_CASE", "END_FOR", "END_WHILE", "END_REPEAT"] Laurent@814: ST_KEYWORDS = ["TRUE", "FALSE", "THEN", "OF", "TO", "BY", "DO", "DO", "UNTIL", "EXIT", Laurent@814: "RETURN", "NOT", "MOD", "AND", "XOR", "OR"] + ST_BLOCK_START_KEYWORDS + ST_BLOCK_END_KEYWORDS Laurent@814: Laurent@814: # All the keywords of IEC Laurent@814: IEC_BLOCK_START_KEYWORDS = [] Laurent@814: IEC_BLOCK_END_KEYWORDS = [] Laurent@814: IEC_KEYWORDS = ["E", "TRUE", "FALSE"] Laurent@814: for all_keywords, keywords_list in [(IEC_BLOCK_START_KEYWORDS, [POU_BLOCK_START_KEYWORDS, TYPE_BLOCK_START_KEYWORDS, Laurent@814: VAR_BLOCK_START_KEYWORDS, CONFIG_BLOCK_START_KEYWORDS, Laurent@814: SFC_BLOCK_START_KEYWORDS, ST_BLOCK_START_KEYWORDS]), Laurent@814: (IEC_BLOCK_END_KEYWORDS, [POU_BLOCK_END_KEYWORDS, TYPE_BLOCK_END_KEYWORDS, Laurent@814: VAR_BLOCK_END_KEYWORDS, CONFIG_BLOCK_END_KEYWORDS, Laurent@814: SFC_BLOCK_END_KEYWORDS, ST_BLOCK_END_KEYWORDS]), Laurent@814: (IEC_KEYWORDS, [POU_KEYWORDS, TYPE_KEYWORDS, VAR_KEYWORDS, CONFIG_KEYWORDS, Laurent@814: SFC_KEYWORDS, IL_KEYWORDS, ST_KEYWORDS])]: Laurent@814: for keywords in keywords_list: Laurent@814: all_keywords.extend([keyword for keyword in keywords if keyword not in all_keywords]) Laurent@814: