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: etisserant@0: #------------------------------------------------------------------------------- etisserant@0: # Function Block Types definitions etisserant@0: #------------------------------------------------------------------------------- etisserant@0: 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 = [ etisserant@18: ("ANY" , None), etisserant@18: ("ANY_DERIVED" , "ANY"), etisserant@18: ("ANY_ELEMENTARY" , "ANY"), etisserant@18: ("ANY_MAGNITUDE", "ANY_ELEMENTARY"), etisserant@18: ("ANY_BIT" , "ANY_ELEMENTARY"), etisserant@18: ("ANY_STRING" , "ANY_ELEMENTARY"), etisserant@18: ("ANY_DATE" , "ANY_ELEMENTARY"), etisserant@18: ("ANY_NUM" , "ANY_MAGNITUDE"), etisserant@18: ("ANY_REAL" , "ANY_NUM"), etisserant@18: ("ANY_INT" , "ANY_NUM"), etisserant@18: ("REAL" , "ANY_REAL"), etisserant@18: ("LREAL" , "ANY_REAL"), etisserant@18: ("SINT" , "ANY_INT"), etisserant@18: ("INT" , "ANY_INT"), etisserant@18: ("DINT" , "ANY_INT"), etisserant@18: ("LINT" , "ANY_INT"), etisserant@18: ("USINT" , "ANY_INT"), etisserant@18: ("UINT" , "ANY_INT"), etisserant@18: ("UDINT" , "ANY_INT"), etisserant@18: ("ULINT" , "ANY_INT"), etisserant@18: ("TIME" , "ANY_MAGNITUDE"), etisserant@18: ("BOOL" , "ANY_BIT"), etisserant@18: ("BYTE" , "ANY_BIT"), etisserant@18: ("WORD" , "ANY_BIT"), etisserant@18: ("DWORD" , "ANY_BIT"), etisserant@18: ("LWORD" , "ANY_BIT"), etisserant@18: ("STRING" , "ANY_STRING"), etisserant@18: ("WSTRING" , "ANY_STRING"), etisserant@18: ("DATE" , "ANY_DATE"), etisserant@18: ("TOD" , "ANY_DATE"), etisserant@18: ("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): etisserant@14: return [ typename for typename in TypeHierarchy.iterkeys() if typename[:3] != "ANY" and IsOfType(typename, reference)] etisserant@14: etisserant@18: etisserant@18: def IsATime(iectype): etisserant@18: return IsOfType(iectype, TIME) or IsOfType(iectype, ANY_DATE) 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): etisserant@14: 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): etisserant@14: fields = [None] etisserant@14: while(fields[0] != section_name): etisserant@14: fields = table.pop(0) etisserant@14: 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): etisserant@14: variables = find_section("Standard_functions_variables_types", table) etisserant@14: standard_funtions_input_variables = {} etisserant@14: fields = [True,True] etisserant@14: while(fields[1]): etisserant@14: fields = table.pop(0) etisserant@18: variable_from_csv = dict([(champ, val) for champ, val in zip(variables, fields[1:]) if champ!='']) etisserant@14: standard_funtions_input_variables[variable_from_csv['name']] = variable_from_csv['type'] etisserant@14: return standard_funtions_input_variables etisserant@14: 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): etisserant@14: decl = str_decl.replace('(','').replace(')','').replace(' ','').split(',') etisserant@14: param_types = [] etisserant@14: param_names = [] etisserant@14: modifiers = [] etisserant@18: etisserant@18: len_of_not_predifined_variable = 0 etisserant@18: for param_type in decl: etisserant@18: predifined_variable_param_type = variables.get(param_type,None) etisserant@18: if not predifined_variable_param_type : etisserant@18: len_of_not_predifined_variable += 1 etisserant@18: etisserant@18: if len_of_not_predifined_variable>1 : suffix = str(base) etisserant@14: else: suffix = '' etisserant@14: etisserant@14: for param_type in decl: etisserant@14: predifined_variable_param_type = variables.get(param_type,None) etisserant@14: if predifined_variable_param_type : etisserant@14: param_types.append(predifined_variable_param_type) etisserant@14: param_names.append(param_type) etisserant@14: else: etisserant@14: param_types.append(param_type) etisserant@14: param_names.append("IN"+suffix) etisserant@14: base+=1 etisserant@14: suffix = str(base) etisserant@14: etisserant@14: modifiers = ["none"]*len(param_types) etisserant@14: return zip(param_names,param_types,modifiers) etisserant@14: etisserant@15: """ etisserant@15: Fillin the PLCOpenEditor standard function dictionnary etisserant@15: translate input and output declaration to something more pythonesque etisserant@15: and add interface description to comment etisserant@15: """ etisserant@14: def decl_function(dico_from_table, variables): etisserant@14: Function_decl = { "type" : "function" } etisserant@14: for field, val in dico_from_table: etisserant@14: translate = { etisserant@14: "baseinputnumber" : lambda x:int(x), etisserant@14: "extensible" : lambda x: {"yes":True, "no":False}[x], etisserant@14: "inputs" : lambda x:csv_input_translate(x,variables,Function_decl.get("baseinputnumber",1)), etisserant@14: "outputs":lambda x:[("OUT",x,"none")]} etisserant@14: Function_decl[field] = translate.get(field,lambda x:x)(val) etisserant@14: return Function_decl etisserant@14: etisserant@18: etisserant@18: def ANY_TO_ANY_FORMAT_GEN(fdecl): etisserant@18: etisserant@18: ANY_T0_ANY_LIST=[ etisserant@18: (("ANY_NUM","ANY_BIT"),("ANY_NUM","ANY_BIT"), "(%(return_type)s)%(IN_value)s"), etisserant@18: (("ANY_NUM","ANY_BIT"),("ANY_DATE","TIME"), "(%(return_type)s)real_to_time(%(IN_value)s)"), etisserant@18: (("ANY_DATE","TIME"), ("ANY_NUM","ANY_BIT"), "(%(return_type)s)time_to_real(%(IN_value)s)"), etisserant@18: (("ANY_DATE","TIME"), ("ANY_STRING",), "(%(return_type)s)time_to_string(%(IN_value)s)"), etisserant@18: (("ANY_STRING",), ("ANY_DATE","TIME"), "(%(return_type)s)string_to_time(%(IN_value)s)"), etisserant@18: (("ANY_BIT",), ("ANY_STRING",), "(%(return_type)s)int_to_string(%(IN_value)s, 16)"), etisserant@18: (("ANY_NUM",), ("ANY_STRING",), "(%(return_type)s)int_to_string(%(IN_value)s, 10)"), etisserant@18: (("ANY_STRING",), ("ANY_BIT",), "(%(return_type)s)string_to_int(%(IN_value)s, 16)"), etisserant@18: (("ANY_STRING",), ("ANY_NUM",), "(%(return_type)s)string_to_int(%(IN_value)s, 10)")] etisserant@18: etisserant@18: for (InTypes, OutTypes, Format) in ANY_T0_ANY_LIST: etisserant@18: inps = reduce(lambda a,b: a or b, map(lambda testtype : IsOfType(fdecl["outputs"][0][1],testtype), InTypes)) etisserant@18: #print "IN ",inps , fdecl["outputs"][0][1], InTypes etisserant@18: outs = reduce(lambda a,b: a or b, map(lambda testtype : IsOfType(fdecl["inputs"][0][1],testtype), OutTypes)) etisserant@18: #print "OUT ",outs , fdecl["inputs"][0][1], OutTypes etisserant@18: if (inps and outs ): etisserant@18: return Format etisserant@18: etisserant@18: #print "IN:", fdecl["outputs"][0][1], " OUT:", fdecl["inputs"][0][1] etisserant@18: etisserant@18: return "#error %s_TO_%s not implemented!"%(fdecl["inputs"][0][1],fdecl["outputs"][0][1]) 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): etisserant@14: etisserant@14: variables = get_standard_funtions_input_variables(table) etisserant@14: etisserant@14: fonctions = find_section("Standard_functions_type",table) etisserant@14: etisserant@14: Standard_Functions_Decl = [] etisserant@14: Current_section = None etisserant@14: for fields in table: etisserant@14: if fields[1]: etisserant@14: # If function section name given etisserant@14: if fields[0] : etisserant@14: if Current_section: etisserant@14: Standard_Functions_Decl.append(Current_section) etisserant@14: Current_section = { "name" : fields[0], "list" : [] } etisserant@14: Function_decl_list = [] etisserant@14: etisserant@18: dico_from_table = [ (champ,val) for champ,val in zip(fonctions, fields[1:]) if champ ] etisserant@14: Function_decl = decl_function(dico_from_table,variables) etisserant@18: if Function_decl["name"].startswith('*') : etisserant@18: input_types = [ GetSubTypes(inpdecl[1]) for inpdecl in Function_decl["inputs"] ] etisserant@18: input_ovrloading_types = input_types[map(len,input_types).index(max(map(len,input_types)))] etisserant@14: else: etisserant@18: input_ovrloading_types = [None] etisserant@18: etisserant@18: if Function_decl["name"].endswith('*') : etisserant@14: output_types = GetSubTypes(Function_decl["outputs"][0][1]) etisserant@14: else: etisserant@14: output_types = [None] etisserant@14: etisserant@18: funcdeclname_orig = Function_decl["name"] etisserant@18: funcdeclname = Function_decl["name"].strip('*_') etisserant@18: fdc = Function_decl["inputs"][:] etisserant@18: for intype in input_ovrloading_types: etisserant@14: if intype != None: etisserant@18: Function_decl["inputs"] = [] etisserant@18: for decl_tpl in fdc: etisserant@18: if IsOfType(intype, decl_tpl[1]): etisserant@18: Function_decl["inputs"] += [(decl_tpl[0], intype, decl_tpl[2])] etisserant@18: else: etisserant@18: Function_decl["inputs"] += [(decl_tpl)] etisserant@18: etisserant@18: if funcdeclname_orig.startswith('*'): etisserant@18: funcdeclin = intype + '_' + funcdeclname etisserant@18: else: etisserant@18: funcdeclin = funcdeclname etisserant@18: else: etisserant@18: funcdeclin = funcdeclname etisserant@18: etisserant@18: etisserant@18: if Function_decl["return_type_rule"] == "copy_input": etisserant@18: output_types = [intype] etisserant@18: elif Function_decl["return_type_rule"] == "defined": etisserant@18: pass etisserant@14: etisserant@14: for outype in output_types: etisserant@14: if outype != None: etisserant@14: decl_tpl = Function_decl["outputs"][0] etisserant@18: Function_decl["outputs"] = [ (decl_tpl[0] , outype, decl_tpl[2])] etisserant@18: if funcdeclname_orig.endswith('*'): etisserant@18: funcdeclout = funcdeclin + '_' + outype etisserant@18: else: etisserant@18: funcdeclout = funcdeclin etisserant@18: else: etisserant@18: funcdeclout = funcdeclin etisserant@18: Function_decl["name"] = funcdeclout etisserant@18: etisserant@18: etisserant@18: try: etisserant@18: fdecl = Function_decl etisserant@18: res = eval(Function_decl["python_eval_c_code_format"]) etisserant@18: except Exception,e: etisserant@18: res = None etisserant@18: etisserant@18: if res != None : etisserant@18: # create the copy of decl dict to be appended to section etisserant@18: Function_decl_copy = Function_decl.copy() etisserant@18: # Have to generate type description in comment with freshly redefined types etisserant@18: Function_decl_copy["comment"] += ( etisserant@18: "\n (" + etisserant@18: str([ " " + fctdecl[1]+":"+fctdecl[0] for fctdecl in Function_decl["inputs"]]).strip("[]").replace("'",'') + etisserant@18: " ) => (" + etisserant@18: str([ " " + fctdecl[1]+":"+fctdecl[0] for fctdecl in Function_decl["outputs"]]).strip("[]").replace("'",'') + etisserant@18: " )") etisserant@18: Current_section["list"].append(Function_decl_copy) etisserant@18: #pp.pprint(Function_decl_copy) etisserant@18: etisserant@18: Standard_Functions_Decl.append(Current_section) etisserant@14: etisserant@14: return Standard_Functions_Decl etisserant@14: etisserant@0: #------------------------------------------------------------------------------- lbessard@9: # Test identifier lbessard@9: #------------------------------------------------------------------------------- lbessard@9: lbessard@9: lbessard@9: lbessard@9: # Test if identifier is valid lbessard@9: def TestIdentifier(identifier): lbessard@9: if identifier[0].isdigit(): lbessard@9: return False lbessard@9: words = identifier.split('_') lbessard@9: for i, word in enumerate(words): lbessard@9: if len(word) == 0 and i != 0: lbessard@9: return False lbessard@9: if len(word) != 0 and not word.isalnum(): lbessard@9: return False lbessard@9: return True lbessard@9: lbessard@9: #------------------------------------------------------------------------------- etisserant@0: # Languages Keywords etisserant@0: #------------------------------------------------------------------------------- etisserant@0: etisserant@0: etisserant@0: etisserant@0: # Keywords for Pou Declaration etisserant@0: POU_KEYWORDS = ["FUNCTION", "END_FUNCTION", "FUNCTION_BLOCK", "END_FUNCTION_BLOCK", etisserant@0: "PROGRAM", "END_PROGRAM", "EN", "ENO", "F_EDGE", "R_EDGE"] etisserant@0: for category in BlockTypes: etisserant@0: for block in category["list"]: etisserant@0: if block["name"] not in POU_KEYWORDS: etisserant@0: POU_KEYWORDS.append(block["name"]) etisserant@0: etisserant@0: etisserant@0: # Keywords for Type Declaration etisserant@0: TYPE_KEYWORDS = ["TYPE", "END_TYPE", "STRUCT", "END_STRUCT", "ARRAY", "OF", "T", etisserant@0: "D", "TIME_OF_DAY", "DATE_AND_TIME"] etisserant@0: TYPE_KEYWORDS.extend([keyword for keyword in TypeHierarchy.keys() if keyword not in TYPE_KEYWORDS]) etisserant@0: etisserant@0: etisserant@0: # Keywords for Variable Declaration etisserant@0: VAR_KEYWORDS = ["VAR", "VAR_INPUT", "VAR_OUTPUT", "VAR_IN_OUT", "VAR_TEMP", etisserant@0: "VAR_EXTERNAL", "END_VAR", "AT", "CONSTANT", "RETAIN", "NON_RETAIN"] etisserant@0: etisserant@0: etisserant@0: # Keywords for Configuration Declaration etisserant@0: CONFIG_KEYWORDS = ["CONFIGURATION", "END_CONFIGURATION", "RESOURCE", "ON", "END_RESOURCE", etisserant@0: "PROGRAM", "WITH", "READ_ONLY", "READ_WRITE", "TASK", "VAR_ACCESS", "VAR_CONFIG", etisserant@0: "VAR_GLOBAL", "END_VAR"] etisserant@0: etisserant@0: etisserant@0: # Keywords for Structured Function Chart etisserant@0: SFC_KEYWORDS = ["ACTION", "END_ACTION", "INITIAL_STEP", "STEP", "END_STEP", "TRANSITION", etisserant@0: "FROM", "TO", "END_TRANSITION"] etisserant@0: etisserant@0: etisserant@0: # Keywords for Instruction List etisserant@0: IL_KEYWORDS = ["LD", "LDN", "ST", "STN", "S", "R", "AND", "ANDN", "OR", "ORN", etisserant@0: "XOR", "XORN", "NOT", "ADD", "SUB", "MUL", "DIV", "MOD", "GT", "GE", "EQ", "NE", etisserant@0: "LE", "LT", "JMP", "JMPC", "JMPNC", "CAL", "CALC", "CALNC", "RET", "RETC", "RETNC"] etisserant@0: etisserant@0: etisserant@0: # Keywords for Instruction List and Structured Text etisserant@0: ST_KEYWORDS = ["IF", "THEN", "ELSIF", "ELSE", "END_IF", "CASE", "OF", "END_CASE", etisserant@0: "FOR", "TO", "BY", "DO", "END_FOR", "WHILE", "DO", "END_WHILE", "REPEAT", "UNTIL", etisserant@0: "END_REPEAT", "EXIT", "RETURN", "NOT", "MOD", "AND", "XOR", "OR"] etisserant@0: etisserant@0: etisserant@0: # All the keywords of IEC etisserant@0: IEC_KEYWORDS = ["E", "TRUE", "FALSE"] etisserant@0: IEC_KEYWORDS.extend([keyword for keyword in POU_KEYWORDS if keyword not in IEC_KEYWORDS]) etisserant@0: IEC_KEYWORDS.extend([keyword for keyword in TYPE_KEYWORDS if keyword not in IEC_KEYWORDS]) etisserant@0: IEC_KEYWORDS.extend([keyword for keyword in VAR_KEYWORDS if keyword not in IEC_KEYWORDS]) etisserant@0: IEC_KEYWORDS.extend([keyword for keyword in CONFIG_KEYWORDS if keyword not in IEC_KEYWORDS]) etisserant@0: IEC_KEYWORDS.extend([keyword for keyword in SFC_KEYWORDS if keyword not in IEC_KEYWORDS]) etisserant@0: IEC_KEYWORDS.extend([keyword for keyword in IL_KEYWORDS if keyword not in IEC_KEYWORDS]) etisserant@0: IEC_KEYWORDS.extend([keyword for keyword in ST_KEYWORDS if keyword not in IEC_KEYWORDS]) etisserant@0: etisserant@15: if __name__ == '__main__': etisserant@18: etisserant@15: import pprint etisserant@15: pp = pprint.PrettyPrinter(indent=4) etisserant@18: etisserant@18: def ANY_to_compiler_test_type_GEN(typename, paramname): etisserant@18: return {"ANY" : "", etisserant@18: "ANY_BIT" : "if(search_expression_type->is_binary_type(%(paramname)s_param_value))", etisserant@18: "ANY_NUM" : "if(search_expression_type->is_num_type(%(paramname)s_param_value))", etisserant@18: "ANY_REAL" : "if(search_expression_type->is_real_type(%(paramname)s_param_value))", etisserant@18: "ANY_INT" : "if(search_expression_type->is_integer_type(%(paramname)s_param_value))" etisserant@18: }.get(typename, etisserant@18: "if (typeid(*last_type_symbol) == typeid(%(typename)s_type_name_c))")%{ etisserant@18: "paramname" : paramname, "typename": typename.lower()} etisserant@18: etisserant@19: def recurse_and_indent(fdecls, indent, do_type_search_only = False): etisserant@18: if type(fdecls) != type(tuple()): etisserant@18: res = "" etisserant@18: for Paramname, ParamTypes in fdecls.iteritems(): etisserant@18: res += (""" etisserant@18: { etisserant@19: identifier_c param_name("%(input_name)s"); etisserant@18: /* Get the value from a foo( = ) style call */ etisserant@18: symbol_c *%(input_name)s_param_value = function_call_param_iterator.search(¶m_name); etisserant@18: etisserant@18: /* Get the value from a foo() style call */ etisserant@18: if (%(input_name)s_param_value == NULL) etisserant@18: %(input_name)s_param_value = function_call_param_iterator.next(); etisserant@18: symbol_c *%(input_name)s_type_symbol = search_expression_type->get_type(%(input_name)s_param_value); etisserant@18: 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 ; etisserant@18: """%{"input_name":Paramname}) etisserant@18: etisserant@18: for ParamType,NextParamDecl in ParamTypes.iteritems(): etisserant@18: etisserant@18: res += (""" etisserant@18: %(type_test)s etisserant@18: { etisserant@18: %(if_good_type_code)s etisserant@18: } etisserant@18: """%{ etisserant@18: "type_test":ANY_to_compiler_test_type_GEN(ParamType,Paramname), etisserant@19: "if_good_type_code":recurse_and_indent(NextParamDecl,indent,do_type_search_only).replace('\n','\n ')}) etisserant@18: etisserant@18: res += """ etisserant@18: ERROR; etisserant@18: } etisserant@18: """ etisserant@18: etisserant@18: return res.replace('\n','\n'+indent) etisserant@18: else: etisserant@18: res = "\n" etisserant@18: fdecl=fdecls[0] etisserant@18: etisserant@18: result_type_rule = fdecl["return_type_rule"] etisserant@18: res += { etisserant@18: "copy_input" : "symbol_c * return_type_symbol = last_type_symbol;\n", etisserant@19: "defined" : "symbol_c * return_type_symbol = &search_constant_type_c::%s_type_name;\n"%fdecl["outputs"][0][1].lower(), etisserant@18: }.get(result_type_rule, "symbol_c * return_type_symbol = %s;\n"%result_type_rule) etisserant@18: etisserant@19: if not do_type_search_only: etisserant@19: try: etisserant@19: code_gen = eval(fdecl["python_eval_c_code_format"]) etisserant@19: except Exception: etisserant@19: code_gen = "#error in eval of " + fdecl["name"] etisserant@19: etisserant@19: code_gen_dic_decl = {} etisserant@18: for paramname,paramtype,unused in fdecl["inputs"]: etisserant@19: code_gen_dic_decl[paramname+"_value"] = '");\n%s_param_value->accept(*this);\ns4o.print("'%(paramname) etisserant@19: code_gen_dic_decl[paramname+"_type"] = '");\n%s_type_symbol->accept(*this);\ns4o.print("'%(paramname) etisserant@19: code_gen_dic_decl["return_type"] = '");\nreturn_type_symbol->accept(*this);\ns4o.print("' etisserant@19: code_gen_dic_decl["param_count"] = '");\ns4o.print_integer(nb_param);\ns4o.print("' etisserant@19: etisserant@19: if type(code_gen) == type(tuple()): etisserant@19: res += 's4o.print("%s");\n'%(code_gen[0]%code_gen_dic_decl) etisserant@19: static_param_accept_list = [] etisserant@19: for paramname,paramtype,unused in fdecl["inputs"]: etisserant@19: static_param_accept_list.append("%s_param_value->accept(*this);\n"%(paramname)) etisserant@19: res += ('s4o.print("%s");\n'%(code_gen[1])).join(static_param_accept_list) etisserant@19: code = 's4o.print("%s");\nparam_value->accept(*this);\n'%(code_gen[1]) etisserant@19: end_code = 's4o.print("%s");\nreturn NULL;\n'%(code_gen[2]) etisserant@19: else: etisserant@19: code = '' etisserant@19: end_code = ('s4o.print("' + code_gen%code_gen_dic_decl + '");\nreturn NULL;\n').replace('s4o.print("");\n','') etisserant@19: etisserant@19: if fdecl["extensible"]: etisserant@19: res += (""" etisserant@19: int base_num = %d; etisserant@19: symbol_c *param_value = NULL; etisserant@18: do{ etisserant@18: char my_name[10]; etisserant@18: sprintf(my_name, "IN%%d", base_num++); etisserant@19: identifier_c param_name(my_name); etisserant@18: etisserant@18: /* Get the value from a foo( = ) style call */ etisserant@19: param_value = function_call_param_iterator.search(¶m_name); etisserant@18: etisserant@18: /* Get the value from a foo() style call */ etisserant@18: if (param_value == NULL) etisserant@18: param_value = function_call_param_iterator.next(); etisserant@18: if (param_value != NULL){ etisserant@18: symbol_c *current_type_symbol = search_expression_type->get_type(param_value); etisserant@18: 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 ; etisserant@18: etisserant@18: /*Function specific CODE */ etisserant@18: %s etisserant@18: } etisserant@18: etisserant@19: }while(param_value != NULL); etisserant@18: %s etisserant@18: """%(fdecl["baseinputnumber"]+2, code.replace('\n','\n '), end_code)) etisserant@19: else: etisserant@19: #res += code + end_code etisserant@19: res += end_code etisserant@18: else: etisserant@19: res += "return return_type_symbol;\n" etisserant@19: etisserant@19: etisserant@18: return res.replace('\n','\n'+indent) etisserant@18: etisserant@18: ################################################################### etisserant@18: ### ### etisserant@18: ### MAIN ### etisserant@18: ### ### etisserant@18: ################################################################### etisserant@18: etisserant@18: # Get definitions etisserant@18: std_decl = get_standard_funtions(csv_file_to_table(open("iec_std.csv")))#, True) etisserant@18: etisserant@18: # Reorganize into a dict of dict, according etisserant@18: # fname : paramname : paramtype : paraname : paramtype... etisserant@18: # Keep ptrack of original order in a separated list etisserant@18: std_fdecls = {} etisserant@18: official_order = [] etisserant@18: for section in std_decl: etisserant@18: for fdecl in section["list"]: etisserant@19: if len(official_order)==0 or official_order[-1] != fdecl["name"]: etisserant@18: official_order.append(fdecl["name"]) etisserant@18: # store all func by name in a dict etisserant@18: std_fdecls_fdecl_name = std_fdecls.get(fdecl["name"], {}) etisserant@18: current = std_fdecls_fdecl_name etisserant@18: for i in fdecl["inputs"]: etisserant@18: current[i[0]] = current.get(i[0], {}) etisserant@18: current = current[i[0]] etisserant@18: last = current etisserant@18: current[i[1]] = current.get(i[1], {}) etisserant@18: current = current[i[1]] etisserant@18: last[i[1]]=(fdecl,) etisserant@18: std_fdecls[fdecl["name"]] = std_fdecls_fdecl_name etisserant@18: etisserant@18: # Generate the long enumeration of std function types etisserant@18: 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: """ etisserant@18: for fname, fdecls in [ (fname,std_fdecls[fname]) for fname in official_order ]: etisserant@18: function_type_decl += " function_"+fname.lower()+",\n" etisserant@18: etisserant@18: function_type_decl += """ function_none etisserant@18: } function_type_t; etisserant@18: """ etisserant@18: etisserant@18: # Generate the funct thaat return enumerated according function name etisserant@18: 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: """ etisserant@18: for fname, fdecls in [ (fname,std_fdecls[fname]) for fname in official_order ]: etisserant@18: get_function_type_decl += """ etisserant@18: if (!strcasecmp(function_name->value, "%s")) etisserant@18: return function_%s; etisserant@18: """%(fname,fname.lower()) etisserant@18: etisserant@18: get_function_type_decl += """ etisserant@18: else return function_none; etisserant@18: } etisserant@18: etisserant@18: """ etisserant@18: etisserant@18: # Generate the part of generate_cc_st_c::visit(function_invocation) etisserant@18: # that is responsible to generate C code for std lib calls. etisserant@19: 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: """ etisserant@18: etisserant@18: for fname, fdecls in [ (fname,std_fdecls[fname]) for fname in official_order ]: etisserant@18: st_code_gen += """ etisserant@18: /**** etisserant@18: *%s etisserant@18: */ etisserant@18: case function_%s : etisserant@18: { etisserant@18: symbol_c *last_type_symbol = NULL; etisserant@18: """ %(fname, fname.lower()) etisserant@18: indent = " " etisserant@18: etisserant@18: st_code_gen += recurse_and_indent(fdecls, indent).replace('\n','\n ') etisserant@18: etisserant@18: st_code_gen += """ etisserant@18: }/*function_%s*/ etisserant@18: break; etisserant@18: """ %(fname.lower()) etisserant@19: st_code_gen += """ etisserant@19: case function_none : etisserant@19: ERROR; etisserant@19: } etisserant@19: return NULL; etisserant@19: """ etisserant@19: etisserant@19: etisserant@19: # Generate the part of search_expression_type_c::visit(function_invocation) etisserant@19: # that is responsible of returning type symbol for function invocation. etisserant@19: search_type_code = """ 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: """ etisserant@19: etisserant@19: for fname, fdecls in [ (fname,std_fdecls[fname]) for fname in official_order ]: etisserant@19: search_type_code += """ etisserant@19: /**** etisserant@19: *%s etisserant@19: */ etisserant@19: case function_%s : etisserant@19: { etisserant@19: symbol_c *last_type_symbol = NULL; etisserant@19: """ %(fname, fname.lower()) etisserant@19: indent = " " etisserant@19: etisserant@19: search_type_code += recurse_and_indent(fdecls, indent, True).replace('\n','\n ') etisserant@19: etisserant@19: search_type_code += """ etisserant@19: }/*function_%s*/ etisserant@19: break; etisserant@19: """ %(fname.lower()) etisserant@19: search_type_code += """ etisserant@19: case function_none : etisserant@19: ERROR; etisserant@19: } etisserant@19: return NULL; etisserant@19: """ etisserant@19: etisserant@18: etisserant@18: # Now, print that out, or write to files from sys.argv etisserant@19: for name, ext in [ etisserant@19: ('function_type_decl','h'), etisserant@19: ('get_function_type_decl','c'), etisserant@19: ('st_code_gen','c'), etisserant@19: ('search_type_code','c')]: etisserant@19: fd = open(os.path.join(sys.argv[1],name+'.'+ext),'w') etisserant@19: fd.write(eval(name)) etisserant@19: fd.close() etisserant@15: else: etisserant@15: # Put standard functions declaration in Bloktypes etisserant@15: BlockTypes.extend(get_standard_funtions(csv_file_to_table(open(os.path.join(sys.path[0], "plcopen/iec_std.csv"))))) etisserant@15: