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