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: # etisserant@0: #Copyright (C): 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 etisserant@0: #Lesser 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@21: 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 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")], etisserant@0: "comment" : "SR bistable\nThe SR bistable is a latch where the Set dominates."}, etisserant@0: {"name" : "RS", "type" : "functionBlock", "extensible" : False, etisserant@0: "inputs" : [("S","BOOL","none"),("R1","BOOL","none")], etisserant@0: "outputs" : [("Q1","BOOL","none")], etisserant@0: "comment" : "RS bistable\nThe RS bistable is a latch where the Reset dominates."}, etisserant@0: {"name" : "SEMA", "type" : "functionBlock", "extensible" : False, etisserant@0: "inputs" : [("CLAIM","BOOL","none"),("RELEASE","BOOL","none")], etisserant@0: "outputs" : [("BUSY","BOOL","none")], etisserant@0: "comment" : "Semaphore\nThe semaphore provides a mechanism to allow software elements mutually exclusive access to certain ressources."}, etisserant@0: {"name" : "R_TRIG", "type" : "functionBlock", "extensible" : False, etisserant@0: "inputs" : [("CLK","BOOL","none")], etisserant@0: "outputs" : [("Q","BOOL","none")], etisserant@0: "comment" : "Rising edge detector\nThe output produces a single pulse when a rising edge is detected."}, etisserant@0: {"name" : "F_TRIG", "type" : "functionBlock", "extensible" : False, etisserant@0: "inputs" : [("CLK","BOOL","none")], etisserant@0: "outputs" : [("Q","BOOL","none")], etisserant@0: "comment" : "Falling edge detector\nThe output produces a single pulse when a falling edge is detected."}, 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")], etisserant@0: "comment" : "Up-counter\nThe up-counter can be used to signal when a count has reached a maximum value."}, 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")], etisserant@0: "comment" : "Down-counter\nThe down-counter can be used to signal when a count has reached zero, on counting down from a preset value."}, 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")], etisserant@0: "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."}, 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")], etisserant@0: "comment" : "Pulse timer\nThe pulse timer can be used to generate output pulses of a given time duration."}, etisserant@0: {"name" : "TOF", "type" : "functionBlock", "extensible" : False, etisserant@0: "inputs" : [("IN","BOOL","none"),("PT","TIME","none")], etisserant@0: "outputs" : [("Q","BOOL","none"),("ET","TIME","none")], etisserant@0: "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."}, etisserant@0: {"name" : "TON", "type" : "functionBlock", "extensible" : False, etisserant@0: "inputs" : [("IN","BOOL","none"),("PT","TIME","none")], etisserant@0: "outputs" : [("Q","BOOL","none"),("ET","TIME","none")], etisserant@0: "comment" : "Off-delay timer\nThe off-delay timer can be used to delay setting an output false, for fixed period after input goes false."}, 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")], etisserant@0: "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."}, 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")], etisserant@0: "comment" : "Integral\nThe integral function block integrates the value of input XIN over time."}, 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")], etisserant@0: "comment" : "Derivative\nThe derivative function block produces an output XOUT proportional to the rate of change of the input XIN."}, 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")], etisserant@0: "comment" : "PID\nThe PID (proportional, Integral, Derivative) function block provides the classical three term controller for closed loop control."}, 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")], etisserant@0: "comment" : "Ramp\nThe RAMP function block is modelled on example given in the standard but with the addition of a 'Holdback' feature."}, 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")], etisserant@0: "comment" : "Hysteresis\nThe hysteresis function block provides a hysteresis boolean output driven by the difference of two floating point (REAL) inputs XIN1 and XIN2."}, 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")], etisserant@0: "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."}, etisserant@0: ]} etisserant@0: ] etisserant@0: etisserant@0: """ etisserant@0: Function that returns the block definition associated to the block type given etisserant@0: """ etisserant@0: etisserant@0: def GetBlockType(type): etisserant@0: for category in BlockTypes: etisserant@0: for blocktype in category["list"]: etisserant@0: if blocktype["name"] == type: etisserant@0: return blocktype etisserant@0: return None etisserant@0: 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"), 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"), lbessard@22: ("REAL", "ANY_REAL"), lbessard@22: ("LREAL", "ANY_REAL"), lbessard@22: ("SINT", "ANY_INT"), lbessard@22: ("INT", "ANY_INT"), lbessard@22: ("DINT", "ANY_INT"), lbessard@22: ("LINT", "ANY_INT"), lbessard@22: ("USINT", "ANY_INT"), lbessard@22: ("UINT", "ANY_INT"), lbessard@22: ("UDINT", "ANY_INT"), lbessard@22: ("ULINT", "ANY_INT"), lbessard@22: ("TIME", "ANY_MAGNITUDE"), lbessard@22: ("BOOL", "ANY_BIT"), lbessard@22: ("BYTE", "ANY_BIT"), lbessard@22: ("WORD", "ANY_BIT"), lbessard@22: ("DWORD", "ANY_BIT"), lbessard@22: ("LWORD", "ANY_BIT"), lbessard@22: ("STRING", "ANY_STRING"), lbessard@22: ("WSTRING", "ANY_STRING"), lbessard@22: ("DATE", "ANY_DATE"), lbessard@22: ("TOD", "ANY_DATE"), lbessard@22: ("DT", "ANY_DATE")] etisserant@18: etisserant@18: TypeHierarchy = dict(TypeHierarchy_list) etisserant@0: etisserant@0: """ etisserant@15: returns true if the given data type is the same that "reference" meta-type or one of its types. etisserant@0: """ etisserant@0: etisserant@0: def IsOfType(test, reference): etisserant@0: while test != None: etisserant@0: if test == reference: etisserant@0: return True etisserant@0: test = TypeHierarchy[test] etisserant@0: return False etisserant@0: etisserant@15: """ etisserant@15: returns list of all types that correspont to the ANY* meta type etisserant@15: """ etisserant@14: def GetSubTypes(reference): lbessard@22: return [ typename for typename, parenttype in TypeHierarchy_list if typename[:3] != "ANY" and IsOfType(typename, reference)] etisserant@14: 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@21: # Languages Keywords lbessard@21: #------------------------------------------------------------------------------- lbessard@21: lbessard@21: lbessard@21: # Keywords for Pou Declaration lbessard@21: POU_KEYWORDS = ["FUNCTION", "END_FUNCTION", "FUNCTION_BLOCK", "END_FUNCTION_BLOCK", lbessard@21: "PROGRAM", "END_PROGRAM", "EN", "ENO", "F_EDGE", "R_EDGE"] lbessard@21: for category in BlockTypes: lbessard@21: for block in category["list"]: lbessard@21: if block["name"] not in POU_KEYWORDS: lbessard@21: POU_KEYWORDS.append(block["name"]) lbessard@21: lbessard@21: lbessard@21: # Keywords for Type Declaration lbessard@21: TYPE_KEYWORDS = ["TYPE", "END_TYPE", "STRUCT", "END_STRUCT", "ARRAY", "OF", "T", lbessard@21: "D", "TIME_OF_DAY", "DATE_AND_TIME"] lbessard@21: TYPE_KEYWORDS.extend([keyword for keyword in TypeHierarchy.keys() if keyword not in TYPE_KEYWORDS]) lbessard@21: lbessard@21: lbessard@21: # Keywords for Variable Declaration lbessard@21: VAR_KEYWORDS = ["VAR", "VAR_INPUT", "VAR_OUTPUT", "VAR_IN_OUT", "VAR_TEMP", lbessard@21: "VAR_EXTERNAL", "END_VAR", "AT", "CONSTANT", "RETAIN", "NON_RETAIN"] lbessard@21: lbessard@21: lbessard@21: # Keywords for Configuration Declaration lbessard@21: CONFIG_KEYWORDS = ["CONFIGURATION", "END_CONFIGURATION", "RESOURCE", "ON", "END_RESOURCE", lbessard@21: "PROGRAM", "WITH", "READ_ONLY", "READ_WRITE", "TASK", "VAR_ACCESS", "VAR_CONFIG", lbessard@21: "VAR_GLOBAL", "END_VAR"] lbessard@21: lbessard@21: lbessard@21: # Keywords for Structured Function Chart lbessard@21: SFC_KEYWORDS = ["ACTION", "END_ACTION", "INITIAL_STEP", "STEP", "END_STEP", "TRANSITION", lbessard@21: "FROM", "TO", "END_TRANSITION"] lbessard@21: lbessard@21: lbessard@21: # Keywords for Instruction List lbessard@21: IL_KEYWORDS = ["LD", "LDN", "ST", "STN", "S", "R", "AND", "ANDN", "OR", "ORN", lbessard@21: "XOR", "XORN", "NOT", "ADD", "SUB", "MUL", "DIV", "MOD", "GT", "GE", "EQ", "NE", lbessard@21: "LE", "LT", "JMP", "JMPC", "JMPNC", "CAL", "CALC", "CALNC", "RET", "RETC", "RETNC"] lbessard@21: lbessard@21: lbessard@21: # Keywords for Instruction List and Structured Text lbessard@21: ST_KEYWORDS = ["IF", "THEN", "ELSIF", "ELSE", "END_IF", "CASE", "OF", "END_CASE", lbessard@21: "FOR", "TO", "BY", "DO", "END_FOR", "WHILE", "DO", "END_WHILE", "REPEAT", "UNTIL", lbessard@21: "END_REPEAT", "EXIT", "RETURN", "NOT", "MOD", "AND", "XOR", "OR"] lbessard@21: lbessard@21: lbessard@21: # All the keywords of IEC lbessard@21: IEC_KEYWORDS = ["E", "TRUE", "FALSE"] lbessard@21: IEC_KEYWORDS.extend([keyword for keyword in POU_KEYWORDS if keyword not in IEC_KEYWORDS]) lbessard@21: IEC_KEYWORDS.extend([keyword for keyword in TYPE_KEYWORDS if keyword not in IEC_KEYWORDS]) lbessard@21: IEC_KEYWORDS.extend([keyword for keyword in VAR_KEYWORDS if keyword not in IEC_KEYWORDS]) lbessard@21: IEC_KEYWORDS.extend([keyword for keyword in CONFIG_KEYWORDS if keyword not in IEC_KEYWORDS]) lbessard@21: IEC_KEYWORDS.extend([keyword for keyword in SFC_KEYWORDS if keyword not in IEC_KEYWORDS]) lbessard@21: IEC_KEYWORDS.extend([keyword for keyword in IL_KEYWORDS if keyword not in IEC_KEYWORDS]) lbessard@21: IEC_KEYWORDS.extend([keyword for keyword in ST_KEYWORDS if keyword not in IEC_KEYWORDS]) lbessard@21: 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: lbessard@22: ANY_T0_ANY_LIST=[ lbessard@22: (("ANY_NUM","ANY_BIT"),("ANY_NUM","ANY_BIT"), "(%(return_type)s)%(IN_value)s"), lbessard@22: (("ANY_NUM","ANY_BIT"),("ANY_DATE","TIME"), "(%(return_type)s)real_to_time(%(IN_value)s)"), lbessard@22: (("ANY_DATE","TIME"), ("ANY_NUM","ANY_BIT"), "(%(return_type)s)time_to_real(%(IN_value)s)"), lbessard@22: (("ANY_DATE","TIME"), ("ANY_STRING",), "(%(return_type)s)time_to_string(%(IN_value)s)"), lbessard@22: (("ANY_STRING",), ("ANY_DATE","TIME"), "(%(return_type)s)string_to_time(%(IN_value)s)"), lbessard@22: (("ANY_BIT",), ("ANY_STRING",), "(%(return_type)s)int_to_string(%(IN_value)s, 16)"), lbessard@22: (("ANY_NUM",), ("ANY_STRING",), "(%(return_type)s)int_to_string(%(IN_value)s, 10)"), lbessard@22: (("ANY_STRING",), ("ANY_BIT",), "(%(return_type)s)string_to_int(%(IN_value)s, 16)"), lbessard@22: (("ANY_STRING",), ("ANY_NUM",), "(%(return_type)s)string_to_int(%(IN_value)s, 10)")] etisserant@18: etisserant@18: def ANY_TO_ANY_FORMAT_GEN(fdecl): etisserant@18: lbessard@22: for (InTypes, OutTypes, Format) in ANY_T0_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@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: lbessard@22: if Function_decl["name"].startswith('*') : lbessard@22: input_ovrloading_types = GetSubTypes(Function_decl["inputs"][0][1]) lbessard@22: else: lbessard@22: input_ovrloading_types = [None] lbessard@22: lbessard@22: if Function_decl["name"].endswith('*') : lbessard@22: output_types = GetSubTypes(Function_decl["outputs"][0][1]) lbessard@22: else: lbessard@22: output_types = [None] lbessard@22: 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@0: etisserant@15: if __name__ == '__main__': lbessard@22: lbessard@22: import pprint lbessard@22: pp = pprint.PrettyPrinter(indent=4) lbessard@22: lbessard@22: def ANY_to_compiler_test_type_GEN(typename, paramname): lbessard@22: return {"ANY" : "", lbessard@22: "ANY_BIT" : "if(search_expression_type->is_binary_type(%(paramname)s_type_symbol))", lbessard@22: "ANY_NUM" : "if(search_expression_type->is_num_type(%(paramname)s_type_symbol))", lbessard@22: "ANY_REAL" : "if(search_expression_type->is_real_type(%(paramname)s_type_symbol))", lbessard@22: "ANY_INT" : "if(search_expression_type->is_integer_type(%(paramname)s_type_symbol))" lbessard@22: }.get(typename, lbessard@22: "if (typeid(*last_type_symbol) == typeid(%(typename)s_type_name_c))")%{ lbessard@22: "paramname" : paramname, "typename": typename.lower()} lbessard@22: lbessard@22: def recurse_and_indent(fdecls, indent, do_type_search_only = False, do_il = False): lbessard@22: if type(fdecls) != type(tuple()): lbessard@22: res = "" lbessard@22: for Paramname, ParamTypes in fdecls.iteritems(): lbessard@22: if do_il: lbessard@22: res += """ etisserant@18: { lbessard@22: /* Get the value from a foo( = ) style call */ lbessard@22: symbol_c *%(input_name)s_param_value = &this->default_variable_name; lbessard@22: lbessard@22: last_type_symbol = param_data_type; lbessard@22: """%{"input_name":Paramname} lbessard@22: else: lbessard@22: res += """ lbessard@22: { lbessard@22: identifier_c param_name("%(input_name)s"); lbessard@22: /* Get the value from a foo( = ) style call */ lbessard@22: symbol_c *%(input_name)s_param_value = function_call_param_iterator.search(¶m_name); lbessard@22: lbessard@22: /* Get the value from a foo() style call */ lbessard@22: if (%(input_name)s_param_value == NULL) lbessard@22: %(input_name)s_param_value = function_call_param_iterator.next(); lbessard@22: symbol_c *%(input_name)s_type_symbol = search_expression_type->get_type(%(input_name)s_param_value); lbessard@22: last_type_symbol = last_type_symbol && search_expression_type->is_same_type(%(input_name)s_type_symbol, last_type_symbol) ? search_expression_type->common_type(%(input_name)s_type_symbol, last_type_symbol) : %(input_name)s_type_symbol ; lbessard@22: """%{"input_name":Paramname} lbessard@22: lbessard@22: for ParamType,NextParamDecl in ParamTypes.iteritems(): lbessard@22: lbessard@22: res += """ lbessard@22: %(type_test)s lbessard@22: { etisserant@18: %(if_good_type_code)s lbessard@22: } etisserant@18: """%{ lbessard@22: "type_test":ANY_to_compiler_test_type_GEN(ParamType,Paramname), lbessard@22: "if_good_type_code":recurse_and_indent(NextParamDecl,indent,do_type_search_only).replace('\n','\n ')} lbessard@22: lbessard@22: res += """ lbessard@22: ERROR; etisserant@18: } etisserant@18: """ lbessard@22: lbessard@22: return res.replace('\n','\n'+indent) lbessard@22: else: lbessard@22: res = "\n" lbessard@22: fdecl=fdecls[0] lbessard@22: lbessard@22: result_type_rule = fdecl["return_type_rule"] lbessard@22: res += { lbessard@22: "copy_input" : "symbol_c * return_type_symbol = last_type_symbol;\n", lbessard@22: "defined" : "symbol_c * return_type_symbol = &search_constant_type_c::%s_type_name;\n"%fdecl["outputs"][0][1].lower(), lbessard@22: }.get(result_type_rule, "symbol_c * return_type_symbol = %s;\n"%result_type_rule) lbessard@22: lbessard@22: if not do_type_search_only: lbessard@22: code_gen = eval(fdecl["python_eval_c_code_format"]) lbessard@22: lbessard@22: code_gen_dic_decl = {} lbessard@22: for paramname,paramtype,unused in fdecl["inputs"]: lbessard@22: code_gen_dic_decl[paramname+"_value"] = '");\n%s_param_value->accept(*this);\ns4o.print("'%(paramname) lbessard@22: code_gen_dic_decl[paramname+"_type"] = '");\n%s_type_symbol->accept(*this);\ns4o.print("'%(paramname) lbessard@22: code_gen_dic_decl["return_type"] = '");\nreturn_type_symbol->accept(*this);\ns4o.print("' lbessard@22: code_gen_dic_decl["param_count"] = '");\ns4o.print_integer(nb_param);\ns4o.print("' lbessard@22: code_gen_dic_decl["start_bool_filter"] = '");\nif (search_expression_type->is_bool_type(last_type_symbol))\n s4o.print("(' lbessard@22: code_gen_dic_decl["end_bool_filter"] = '");\nif (search_expression_type->is_bool_type(last_type_symbol)) {\n s4o.print("&1");\n s4o.print(")");\n}\ns4o.print("' lbessard@21: lbessard@22: if type(code_gen) == type(tuple()): lbessard@22: res += 's4o.print("%s");\n'%(code_gen[0]%code_gen_dic_decl) lbessard@22: static_param_accept_list = [] lbessard@22: for paramname,paramtype,unused in fdecl["inputs"]: lbessard@22: static_param_accept_list.append("%s_param_value->accept(*this);\n"%(paramname)) lbessard@22: res += ('s4o.print("%s");\n'%(code_gen[1])).join(static_param_accept_list) lbessard@22: code = 's4o.print("%s");\nparam_value->accept(*this);\n'%(code_gen[1]) lbessard@22: end_code = 's4o.print("%s");\nreturn NULL;\n'%(code_gen[2]%code_gen_dic_decl) lbessard@22: else: lbessard@22: code = '' lbessard@22: end_code = ('s4o.print("' + code_gen%code_gen_dic_decl + '");\nreturn NULL;\n').replace('s4o.print("");\n','') lbessard@22: lbessard@22: if fdecl["extensible"]: lbessard@22: res += (""" etisserant@19: int base_num = %d; etisserant@19: symbol_c *param_value = NULL; etisserant@18: do{ lbessard@22: char my_name[10]; lbessard@22: sprintf(my_name, "IN%%d", base_num++); lbessard@22: identifier_c param_name(my_name); lbessard@22: lbessard@22: /* Get the value from a foo( = ) style call */ lbessard@22: param_value = function_call_param_iterator.search(¶m_name); lbessard@22: lbessard@22: /* Get the value from a foo() style call */ lbessard@22: if (param_value == NULL) lbessard@22: param_value = function_call_param_iterator.next(); lbessard@22: if (param_value != NULL){ lbessard@22: symbol_c *current_type_symbol = search_expression_type->get_type(param_value); lbessard@22: last_type_symbol = last_type_symbol && search_expression_type->is_same_type(current_type_symbol, last_type_symbol) ? search_expression_type->common_type(current_type_symbol, last_type_symbol) : current_type_symbol ; lbessard@22: lbessard@22: /*Function specific CODE */ lbessard@22: %s lbessard@22: } lbessard@22: etisserant@19: }while(param_value != NULL); etisserant@18: %s lbessard@22: """%(fdecl["baseinputnumber"]+2, code.replace('\n','\n '), end_code)) lbessard@22: else: lbessard@22: #res += code + end_code lbessard@22: res += end_code lbessard@22: else: lbessard@22: res += "return return_type_symbol;\n" lbessard@22: lbessard@22: lbessard@22: return res.replace('\n','\n'+indent) etisserant@18: etisserant@18: ################################################################### etisserant@18: ### ### etisserant@18: ### MAIN ### etisserant@18: ### ### etisserant@18: ################################################################### etisserant@18: lbessard@22: # Get definitions lbessard@22: std_decl = get_standard_funtions(csv_file_to_table(open("iec_std.csv")))#, True) lbessard@22: lbessard@22: # Reorganize into a dict of dict, according lbessard@22: # fname : paramname : paramtype : paraname : paramtype... lbessard@22: # Keep ptrack of original order in a separated list lbessard@22: std_fdecls = {} lbessard@22: official_order = [] lbessard@22: for section in std_decl: lbessard@22: for fdecl in section["list"]: lbessard@22: if len(official_order)==0 or official_order[-1] != fdecl["name"]: lbessard@22: official_order.append(fdecl["name"]) lbessard@22: # store all func by name in a dict lbessard@22: std_fdecls_fdecl_name = std_fdecls.get(fdecl["name"], {}) lbessard@22: current = std_fdecls_fdecl_name lbessard@22: for i in fdecl["inputs"]: lbessard@22: current[i[0]] = current.get(i[0], {}) lbessard@22: current = current[i[0]] lbessard@22: last = current lbessard@22: current[i[1]] = current.get(i[1], {}) lbessard@22: current = current[i[1]] lbessard@22: last[i[1]]=(fdecl,) lbessard@22: std_fdecls[fdecl["name"]] = std_fdecls_fdecl_name lbessard@22: lbessard@22: # Generate the long enumeration of std function types lbessard@22: function_type_decl = """ etisserant@18: /**** etisserant@18: * IEC 61131-3 standard function lib etisserant@18: * generated code, do not edit by hand etisserant@18: */ etisserant@18: typedef enum { etisserant@18: """ lbessard@22: for fname, fdecls in [ (fname,std_fdecls[fname]) for fname in official_order ]: lbessard@22: function_type_decl += " function_"+fname.lower()+",\n" lbessard@22: lbessard@22: function_type_decl += """ function_none etisserant@18: } function_type_t; etisserant@18: """ etisserant@18: lbessard@22: # Generate the funct thaat return enumerated according function name lbessard@22: get_function_type_decl = """ etisserant@19: /**** etisserant@19: * IEC 61131-3 standard function lib etisserant@19: * generated code, do not edit by hand etisserant@19: */ etisserant@18: function_type_t get_function_type(identifier_c *function_name) { etisserant@18: """ lbessard@22: for fname, fdecls in [ (fname,std_fdecls[fname]) for fname in official_order ]: lbessard@22: get_function_type_decl += """ lbessard@22: if (!strcasecmp(function_name->value, "%s")) lbessard@22: return function_%s; etisserant@18: """%(fname,fname.lower()) etisserant@18: lbessard@22: get_function_type_decl += """ lbessard@22: else return function_none; etisserant@18: } etisserant@18: etisserant@18: """ etisserant@18: lbessard@22: # Generate the part of generate_cc_st_c::visit(function_invocation) lbessard@22: # that is responsible to generate C code for std lib calls. lbessard@22: st_code_gen = """ etisserant@19: /**** etisserant@19: * IEC 61131-3 standard function lib etisserant@19: * generated code, do not edit by hand etisserant@19: */ etisserant@19: switch(current_function_type){ etisserant@19: """ lbessard@22: lbessard@22: for fname, fdecls in [ (fname,std_fdecls[fname]) for fname in official_order ]: lbessard@22: st_code_gen += """ etisserant@18: /**** etisserant@18: *%s etisserant@18: */ lbessard@22: case function_%s : lbessard@22: { lbessard@22: symbol_c *last_type_symbol = NULL; lbessard@22: """ %(fname, fname.lower()) lbessard@22: indent = " " lbessard@22: lbessard@22: st_code_gen += recurse_and_indent(fdecls, indent).replace('\n','\n ') lbessard@22: lbessard@22: st_code_gen += """ lbessard@22: }/*function_%s*/ lbessard@22: break; lbessard@22: """ %(fname.lower()) lbessard@22: st_code_gen += """ lbessard@22: case function_none : lbessard@22: ERROR; etisserant@19: } etisserant@19: return NULL; etisserant@19: """ etisserant@19: lbessard@22: # Generate the part of generate_cc_il_c::visit(il_function_call) lbessard@22: # that is responsible to generate C code for std lib calls. lbessard@22: il_code_gen = """ etisserant@19: /**** etisserant@19: * IEC 61131-3 standard function lib etisserant@19: * generated code, do not edit by hand etisserant@19: */ etisserant@19: switch(current_function_type){ etisserant@19: """ lbessard@22: lbessard@22: for fname, fdecls in [ (fname,std_fdecls[fname]) for fname in official_order ]: lbessard@22: il_code_gen += """ etisserant@19: /**** etisserant@19: *%s etisserant@19: */ lbessard@22: case function_%s : lbessard@22: { lbessard@22: symbol_c *last_type_symbol = NULL; lbessard@22: """ %(fname, fname.lower()) lbessard@22: indent = " " lbessard@22: lbessard@22: il_code_gen += recurse_and_indent(fdecls, indent).replace('\n','\n ') lbessard@22: lbessard@22: il_code_gen += """ lbessard@22: }/*function_%s*/ lbessard@22: break; lbessard@22: """ %(fname.lower()) lbessard@22: st_code_gen += """ lbessard@22: case function_none : lbessard@22: ERROR; etisserant@19: } etisserant@19: return NULL; etisserant@19: """ etisserant@19: lbessard@22: # Generate the part of search_expression_type_c::visit(function_invocation) lbessard@22: # that is responsible of returning type symbol for function invocation. lbessard@22: search_type_code = """ lbessard@22: /**** lbessard@22: * IEC 61131-3 standard function lib lbessard@22: * generated code, do not edit by hand lbessard@22: */ lbessard@22: switch(current_function_type){ lbessard@22: """ lbessard@22: lbessard@22: for fname, fdecls in [ (fname,std_fdecls[fname]) for fname in official_order ]: lbessard@22: search_type_code += """ lbessard@22: /**** lbessard@22: *%s lbessard@22: */ lbessard@22: case function_%s : lbessard@22: { lbessard@22: symbol_c *last_type_symbol = NULL; lbessard@22: """ %(fname, fname.lower()) lbessard@22: indent = " " lbessard@22: lbessard@22: search_type_code += recurse_and_indent(fdecls, indent, True).replace('\n','\n ') lbessard@22: lbessard@22: search_type_code += """ lbessard@22: }/*function_%s*/ lbessard@22: break; lbessard@22: """ %(fname.lower()) lbessard@22: search_type_code += """ lbessard@22: case function_none : lbessard@22: ERROR; lbessard@22: } lbessard@22: return NULL; lbessard@22: """ lbessard@22: lbessard@22: lbessard@22: # Now, print that out, or write to files from sys.argv lbessard@22: for name, ext in [ lbessard@22: ('function_type_decl','h'), lbessard@22: ('get_function_type_decl','c'), lbessard@22: ('st_code_gen','c'), lbessard@22: ('il_code_gen','c'), lbessard@22: ('search_type_code','c')]: lbessard@22: fd = open(os.path.join(sys.argv[1],name+'.'+ext),'w') lbessard@22: fd.write(eval(name)) lbessard@22: fd.close() etisserant@15: else: lbessard@22: # Put standard functions declaration in Bloktypes lbessard@22: BlockTypes.extend(get_standard_funtions(csv_file_to_table(open(os.path.join(sys.path[0], "plcopen/iec_std.csv"))))) lbessard@22: lbessard@22: