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: lbessard@230: # Helper for emulate join on element list lbessard@230: def JoinList(separator, list): lbessard@230: return reduce(lambda x, y: x + separator + y, list) lbessard@230: lbessard@125: def generate_block(generator, block, body, link, order=False): lbessard@151: body_type = body.getcontent()["name"] lbessard@151: name = block.getinstanceName() lbessard@151: type = block.gettypeName() lbessard@151: executionOrderId = block.getexecutionOrderId() lbessard@230: block_infos = generator.GetBlockType(type) 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@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@250: value = generator.ComputeExpression(body, connections, executionOrderId > 0) lbessard@270: if len(output_variables) > 1: lbessard@270: parameter = variable.getformalParameter() 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@270: for i, variable in enumerate(output_variables): lbessard@270: parameter = variable.getformalParameter() lbessard@270: if variable.getformalParameter() == "": lbessard@270: variable_name = "%s%d_OUT"%(type, block.getlocalId()) lbessard@270: else: lbessard@270: variable_name = "%s%d_%s"%(type, block.getlocalId(), parameter) lbessard@270: if generator.Interface[-1][0] != "VAR" or generator.Interface[-1][1] or generator.Interface[-1][2] or generator.Interface[-1][3]: lbessard@270: generator.Interface.append(("VAR", False, False, False, [])) lbessard@270: if variable.connectionPointOut in generator.ConnectionTypes: lbessard@270: generator.Interface[-1][4].append((generator.ConnectionTypes[variable.connectionPointOut], variable_name, None, None)) lbessard@270: else: lbessard@270: generator.Interface[-1][4].append(("ANY", variable_name, None, None)) lbessard@270: if len(output_variables) > 1 and parameter not in ["", "OUT"]: lbessard@270: vars.append([(parameter, (generator.TagName, "block", block.getlocalId(), "output", i)), lbessard@270: (" => %s"%variable_name, ())]) lbessard@270: else: lbessard@270: output_info = (generator.TagName, "block", block.getlocalId(), "output", i) lbessard@270: output_name = variable_name lbessard@230: generator.Program += [(generator.CurrentIndent, ()), lbessard@230: (output_name, output_info), lbessard@230: (" := ", ()), lbessard@230: (type, (generator.TagName, "block", block.getlocalId(), "type")), lbessard@230: ("(", ())] lbessard@230: generator.Program += JoinList([(", ", ())], vars) lbessard@230: generator.Program += [(");\n", ())] 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) lbessard@270: output_name = variable.getformalParameter() lbessard@270: if variable.getformalParameter() == "": lbessard@270: output_name = "%s%d_OUT"%(type, block.getlocalId()) lbessard@270: else: lbessard@270: output_name = "%s%d_%s"%(type, block.getlocalId(), variable.getformalParameter()) lbessard@270: return generator.ExtractModifier(variable, [(output_name, output_info)], 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() lbessard@250: value = generator.ComputeExpression(body, connections, executionOrderId > 0) 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) lbessard@230: return generator.ExtractModifier(variable, [("%s.%s"%(name, variable.getformalParameter()), output_info)], output_info) lbessard@270: 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: etisserant@14: 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")], lbessard@78: "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")], lbessard@78: "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")], lbessard@78: "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")], lbessard@78: "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")], lbessard@78: "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")], lbessard@78: "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")], lbessard@78: "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")], lbessard@78: "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 ans 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")], lbessard@78: "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")], lbessard@78: "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")], lbessard@78: "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}, etisserant@0: {"name" : "RTC", "type" : "functionBlock", "extensible" : False, etisserant@0: "inputs" : [("EN","BOOL","none"),("PDT","DATE_AND_TIME","none")], etisserant@0: "outputs" : [("Q","BOOL","none"),("CDT","DATE_AND_TIME","none")], lbessard@78: "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.", lbessard@93: "generate" : generate_block, "initialise" : initialise_block}, etisserant@0: {"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")], lbessard@78: "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")], lbessard@78: "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")], lbessard@78: "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, etisserant@0: "inputs" : [("RUN","BOOL","none"),("X0","REAL","none"),("X1","REAL","none"),("TR","TIME","none"),("CYCLE","TIME","none"),("HOLDBACK","BOOL","none"),("ERROR","REAL","none"),("PV","REAL","none")], etisserant@0: "outputs" : [("RAMP","BOOL","none"),("XOUT","REAL","none")], lbessard@78: "comment" : "Ramp\nThe RAMP function block is modelled on example given in the standard but with the addition of a 'Holdback' feature.", 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")], lbessard@78: "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}, etisserant@0: {"name" : "RATIO_MONITOR", "type" : "functionBlock", "extensible" : False, etisserant@0: "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")], etisserant@0: "outputs" : [("ALARM","BOOL","none"),("TOTAL_ERR","BOOL","none")], lbessard@78: "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@93: "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 lbessard@22: (("ANY_NUM","ANY_BIT"),("ANY_NUM","ANY_BIT"), "(%(return_type)s)%(IN_value)s"), etisserant@25: # TO_TIME etisserant@25: (("ANY_INT","ANY_BIT"),("ANY_DATE","TIME"), "(%(return_type)s)__int_to_time(%(IN_value)s)"), etisserant@25: (("ANY_REAL",),("ANY_DATE","TIME"), "(%(return_type)s)__real_to_time(%(IN_value)s)"), etisserant@25: (("ANY_STRING",), ("ANY_DATE","TIME"), "(%(return_type)s)__string_to_time(%(IN_value)s)"), etisserant@25: # FROM_TIME etisserant@25: (("ANY_DATE","TIME"), ("ANY_REAL",), "(%(return_type)s)__time_to_real(%(IN_value)s)"), etisserant@40: (("ANY_DATE","TIME"), ("ANY_INT","ANY_NBIT"), "(%(return_type)s)__time_to_int(%(IN_value)s)"), etisserant@25: (("TIME",), ("ANY_STRING",), "(%(return_type)s)__time_to_string(%(IN_value)s)"), etisserant@25: (("DATE",), ("ANY_STRING",), "(%(return_type)s)__date_to_string(%(IN_value)s)"), etisserant@25: (("TOD",), ("ANY_STRING",), "(%(return_type)s)__tod_to_string(%(IN_value)s)"), etisserant@25: (("DT",), ("ANY_STRING",), "(%(return_type)s)__dt_to_string(%(IN_value)s)"), etisserant@25: # TO_STRING etisserant@25: (("BOOL",), ("ANY_STRING",), "(%(return_type)s)__bool_to_string(%(IN_value)s)"), etisserant@25: (("ANY_BIT",), ("ANY_STRING",), "(%(return_type)s)__bit_to_string(%(IN_value)s)"), etisserant@25: (("ANY_REAL",), ("ANY_STRING",), "(%(return_type)s)__real_to_string(%(IN_value)s)"), etisserant@25: (("ANY_SINT",), ("ANY_STRING",), "(%(return_type)s)__sint_to_string(%(IN_value)s)"), etisserant@25: (("ANY_UINT",), ("ANY_STRING",), "(%(return_type)s)__uint_to_string(%(IN_value)s)"), etisserant@25: # FROM_STRING etisserant@25: (("ANY_STRING",), ("BOOL",), "(%(return_type)s)__string_to_bool(%(IN_value)s)"), etisserant@25: (("ANY_STRING",), ("ANY_BIT",), "(%(return_type)s)__string_to_bit(%(IN_value)s)"), etisserant@25: (("ANY_STRING",), ("ANY_SINT",), "(%(return_type)s)__string_to_sint(%(IN_value)s)"), etisserant@25: (("ANY_STRING",), ("ANY_UINT",), "(%(return_type)s)__string_to_uint(%(IN_value)s)"), etisserant@25: (("ANY_STRING",), ("ANY_REAL",), "(%(return_type)s)__string_to_real(%(IN_value)s)")] etisserant@25: etisserant@25: etisserant@25: BCD_TO_ANY_LIST=[ etisserant@25: (("BYTE",),("USINT",), "(%(return_type)s)__bcd_to_uint(%(IN_value)s)"), etisserant@25: (("WORD",),("UINT",), "(%(return_type)s)__bcd_to_uint(%(IN_value)s)"), etisserant@25: (("DWORD",),("UDINT",), "(%(return_type)s)__bcd_to_uint(%(IN_value)s)"), etisserant@25: (("LWORD",),("ULINT",), "(%(return_type)s)__bcd_to_uint(%(IN_value)s)")] etisserant@25: etisserant@25: etisserant@25: ANY_TO_BCD_LIST=[ etisserant@25: (("USINT",),("BYTE",), "(%(return_type)s)__uint_to_bcd(%(IN_value)s)"), etisserant@25: (("UINT",),("WORD",), "(%(return_type)s)__uint_to_bcd(%(IN_value)s)"), etisserant@25: (("UDINT",),("DWORD",), "(%(return_type)s)__uint_to_bcd(%(IN_value)s)"), etisserant@25: (("ULINT",),("LWORD",), "(%(return_type)s)__uint_to_bcd(%(IN_value)s)")] 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]: lbessard@22: Current_section = {"name" : fields[0], "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: # Have to generate type description in comment with freshly redefined types lbessard@22: Function_decl_copy["comment"] += ( lbessard@22: "\n (" + lbessard@22: str([ " " + fctdecl[1]+":"+fctdecl[0] for fctdecl in Function_decl["inputs"]]).strip("[]").replace("'",'') + lbessard@22: " ) => (" + lbessard@22: str([ " " + fctdecl[1]+":"+fctdecl[0] for fctdecl in Function_decl["outputs"]]).strip("[]").replace("'",'') + lbessard@22: " )") lbessard@22: Current_section["list"].append(Function_decl_copy) lbessard@22: #pp.pprint(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: lbessard@109: lbessard@109: #------------------------------------------------------------------------------- lbessard@109: # Languages Keywords lbessard@109: #------------------------------------------------------------------------------- lbessard@109: lbessard@109: lbessard@109: # Keywords for Pou Declaration lbessard@109: POU_KEYWORDS = ["FUNCTION", "END_FUNCTION", "FUNCTION_BLOCK", "END_FUNCTION_BLOCK", lbessard@109: "PROGRAM", "END_PROGRAM", "EN", "ENO", "F_EDGE", "R_EDGE"] 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 lbessard@109: TYPE_KEYWORDS = ["TYPE", "END_TYPE", "STRUCT", "END_STRUCT", "ARRAY", "OF", "T", lbessard@109: "D", "TIME_OF_DAY", "DATE_AND_TIME"] 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 lbessard@109: VAR_KEYWORDS = ["VAR", "VAR_INPUT", "VAR_OUTPUT", "VAR_IN_OUT", "VAR_TEMP", lbessard@109: "VAR_EXTERNAL", "END_VAR", "AT", "CONSTANT", "RETAIN", "NON_RETAIN"] lbessard@109: lbessard@109: lbessard@109: # Keywords for Configuration Declaration lbessard@109: CONFIG_KEYWORDS = ["CONFIGURATION", "END_CONFIGURATION", "RESOURCE", "ON", "END_RESOURCE", lbessard@109: "PROGRAM", "WITH", "READ_ONLY", "READ_WRITE", "TASK", "VAR_ACCESS", "VAR_CONFIG", lbessard@109: "VAR_GLOBAL", "END_VAR"] lbessard@109: lbessard@109: lbessard@109: # Keywords for Structured Function Chart lbessard@109: SFC_KEYWORDS = ["ACTION", "END_ACTION", "INITIAL_STEP", "STEP", "END_STEP", "TRANSITION", lbessard@109: "FROM", "TO", "END_TRANSITION"] 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 lbessard@109: ST_KEYWORDS = ["TRUE", "FALSE", "IF", "THEN", "ELSIF", "ELSE", "END_IF", "CASE", "OF", "END_CASE", lbessard@109: "FOR", "TO", "BY", "DO", "END_FOR", "WHILE", "DO", "END_WHILE", "REPEAT", "UNTIL", lbessard@109: "END_REPEAT", "EXIT", "RETURN", "NOT", "MOD", "AND", "XOR", "OR"] lbessard@109: lbessard@109: lbessard@109: # All the keywords of IEC lbessard@109: IEC_KEYWORDS = ["E", "TRUE", "FALSE"] lbessard@109: IEC_KEYWORDS.extend([keyword for keyword in POU_KEYWORDS if keyword not in IEC_KEYWORDS]) lbessard@109: IEC_KEYWORDS.extend([keyword for keyword in TYPE_KEYWORDS if keyword not in IEC_KEYWORDS]) lbessard@109: IEC_KEYWORDS.extend([keyword for keyword in VAR_KEYWORDS if keyword not in IEC_KEYWORDS]) lbessard@109: IEC_KEYWORDS.extend([keyword for keyword in CONFIG_KEYWORDS if keyword not in IEC_KEYWORDS]) lbessard@109: IEC_KEYWORDS.extend([keyword for keyword in SFC_KEYWORDS if keyword not in IEC_KEYWORDS]) lbessard@109: IEC_KEYWORDS.extend([keyword for keyword in IL_KEYWORDS if keyword not in IEC_KEYWORDS]) lbessard@109: IEC_KEYWORDS.extend([keyword for keyword in ST_KEYWORDS if keyword not in IEC_KEYWORDS]) lbessard@109: