#!/usr/bin/env python
# -*- coding: utf-8 -*-
import string, os, sys
#This file is part of PLCOpenEditor, a library implementing an IEC 61131-3 editor
#based on the plcopen standard.
#
#Copyright (C): Edouard TISSERANT and Laurent BESSARD
#
#See COPYING file for copyrights details.
#
#This library is free software; you can redistribute it and/or
#modify it under the terms of the GNU General Public
#License as published by the Free Software Foundation; either
#version 2.1 of the License, or (at your option) any later version.
#
#This library is distributed in the hope that it will be useful,
#but WITHOUT ANY WARRANTY; without even the implied warranty of
#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
#Lesser General Public License for more details.
#
#You should have received a copy of the GNU General Public
#License along with this library; if not, write to the Free Software
#Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
LANGUAGES = ["IL","ST","FBD","LD","SFC"]
#-------------------------------------------------------------------------------
# Function Block Types definitions
#-------------------------------------------------------------------------------
"""
Ordored list of common Function Blocks defined in the IEC 61131-3
Each block have this attributes:
- "name" : The block name
- "type" : The block type. It can be "function", "functionBlock" or "program"
- "extensible" : Boolean that define if the block is extensible
- "inputs" : List of the block inputs
- "outputs" : List of the block outputs
- "comment" : Comment that will be displayed in the block popup
Inputs and outputs are a tuple of characteristics that are in order:
- The name
- The data type
- The default modifier which can be "none", "negated", "rising" or "falling"
"""
BlockTypes = [{"name" : "Standard function blocks", "list":
[{"name" : "SR", "type" : "functionBlock", "extensible" : False,
"inputs" : [("S1","BOOL","none"),("R","BOOL","none")],
"outputs" : [("Q1","BOOL","none")],
"comment" : "SR bistable\nThe SR bistable is a latch where the Set dominates."},
{"name" : "RS", "type" : "functionBlock", "extensible" : False,
"inputs" : [("S","BOOL","none"),("R1","BOOL","none")],
"outputs" : [("Q1","BOOL","none")],
"comment" : "RS bistable\nThe RS bistable is a latch where the Reset dominates."},
{"name" : "SEMA", "type" : "functionBlock", "extensible" : False,
"inputs" : [("CLAIM","BOOL","none"),("RELEASE","BOOL","none")],
"outputs" : [("BUSY","BOOL","none")],
"comment" : "Semaphore\nThe semaphore provides a mechanism to allow software elements mutually exclusive access to certain ressources."},
{"name" : "R_TRIG", "type" : "functionBlock", "extensible" : False,
"inputs" : [("CLK","BOOL","none")],
"outputs" : [("Q","BOOL","none")],
"comment" : "Rising edge detector\nThe output produces a single pulse when a rising edge is detected."},
{"name" : "F_TRIG", "type" : "functionBlock", "extensible" : False,
"inputs" : [("CLK","BOOL","none")],
"outputs" : [("Q","BOOL","none")],
"comment" : "Falling edge detector\nThe output produces a single pulse when a falling edge is detected."},
{"name" : "CTU", "type" : "functionBlock", "extensible" : False,
"inputs" : [("CU","BOOL","rising"),("R","BOOL","none"),("PV","INT","none")],
"outputs" : [("Q","BOOL","none"),("CV","INT","none")],
"comment" : "Up-counter\nThe up-counter can be used to signal when a count has reached a maximum value."},
{"name" : "CTD", "type" : "functionBlock", "extensible" : False,
"inputs" : [("CD","BOOL","rising"),("LD","BOOL","none"),("PV","INT","none")],
"outputs" : [("Q","BOOL","none"),("CV","INT","none")],
"comment" : "Down-counter\nThe down-counter can be used to signal when a count has reached zero, on counting down from a preset value."},
{"name" : "CTUD", "type" : "functionBlock", "extensible" : False,
"inputs" : [("CU","BOOL","rising"),("CD","BOOL","rising"),("R","BOOL","none"),("LD","BOOL","none"),("PV","INT","none")],
"outputs" : [("QU","BOOL","none"),("QD","BOOL","none"),("CV","INT","none")],
"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."},
{"name" : "TP", "type" : "functionBlock", "extensible" : False,
"inputs" : [("IN","BOOL","none"),("PT","TIME","none")],
"outputs" : [("Q","BOOL","none"),("ET","TIME","none")],
"comment" : "Pulse timer\nThe pulse timer can be used to generate output pulses of a given time duration."},
{"name" : "TOF", "type" : "functionBlock", "extensible" : False,
"inputs" : [("IN","BOOL","none"),("PT","TIME","none")],
"outputs" : [("Q","BOOL","none"),("ET","TIME","none")],
"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."},
{"name" : "TON", "type" : "functionBlock", "extensible" : False,
"inputs" : [("IN","BOOL","none"),("PT","TIME","none")],
"outputs" : [("Q","BOOL","none"),("ET","TIME","none")],
"comment" : "Off-delay timer\nThe off-delay timer can be used to delay setting an output false, for fixed period after input goes false."},
{"name" : "RTC", "type" : "functionBlock", "extensible" : False,
"inputs" : [("EN","BOOL","none"),("PDT","DATE_AND_TIME","none")],
"outputs" : [("Q","BOOL","none"),("CDT","DATE_AND_TIME","none")],
"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."},
{"name" : "INTEGRAL", "type" : "functionBlock", "extensible" : False,
"inputs" : [("RUN","BOOL","none"),("R1","BOOL","none"),("XIN","REAL","none"),("X0","REAL","none"),("CYCLE","TIME","none")],
"outputs" : [("Q","BOOL","none"),("XOUT","REAL","none")],
"comment" : "Integral\nThe integral function block integrates the value of input XIN over time."},
{"name" : "DERIVATIVE", "type" : "functionBlock", "extensible" : False,
"inputs" : [("RUN","BOOL","none"),("XIN","REAL","none"),("CYCLE","TIME","none")],
"outputs" : [("XOUT","REAL","none")],
"comment" : "Derivative\nThe derivative function block produces an output XOUT proportional to the rate of change of the input XIN."},
{"name" : "PID", "type" : "functionBlock", "extensible" : False,
"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")],
"outputs" : [("XOUT","REAL","none")],
"comment" : "PID\nThe PID (proportional, Integral, Derivative) function block provides the classical three term controller for closed loop control."},
{"name" : "RAMP", "type" : "functionBlock", "extensible" : False,
"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")],
"outputs" : [("RAMP","BOOL","none"),("XOUT","REAL","none")],
"comment" : "Ramp\nThe RAMP function block is modelled on example given in the standard but with the addition of a 'Holdback' feature."},
{"name" : "HYSTERESIS", "type" : "functionBlock", "extensible" : False,
"inputs" : [("XIN1","REAL","none"),("XIN2","REAL","none"),("EPS","REAL","none")],
"outputs" : [("Q","BOOL","none")],
"comment" : "Hysteresis\nThe hysteresis function block provides a hysteresis boolean output driven by the difference of two floating point (REAL) inputs XIN1 and XIN2."},
{"name" : "RATIO_MONITOR", "type" : "functionBlock", "extensible" : False,
"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")],
"outputs" : [("ALARM","BOOL","none"),("TOTAL_ERR","BOOL","none")],
"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."},
]}
]
"""
Function that returns the block definition associated to the block type given
"""
def GetBlockType(type):
for category in BlockTypes:
for blocktype in category["list"]:
if blocktype["name"] == type:
return blocktype
return None
#-------------------------------------------------------------------------------
# Data Types definitions
#-------------------------------------------------------------------------------
"""
Ordored list of common data types defined in the IEC 61131-3
Each type is associated to his direct parent type. It defines then a hierarchy
between type that permits to make a comparison of two types
"""
TypeHierarchy = {"ANY" : None,
"ANY_DERIVED" : "ANY",
"ANY_ELEMENTARY" : "ANY",
"ANY_MAGNITUDE": "ANY_ELEMENTARY",
"ANY_BIT" : "ANY_ELEMENTARY",
"ANY_STRING" : "ANY_ELEMENTARY",
"ANY_DATE" : "ANY_ELEMENTARY",
"ANY_NUM" : "ANY_MAGNITUDE",
"ANY_REAL" : "ANY_NUM",
"ANY_INT" : "ANY_NUM",
"REAL" : "ANY_REAL",
"LREAL" : "ANY_REAL",
"SINT" : "ANY_INT",
"INT" : "ANY_INT",
"DINT" : "ANY_INT",
"LINT" : "ANY_INT",
"USINT" : "ANY_INT",
"UINT" : "ANY_INT",
"UDINT" : "ANY_INT",
"ULINT" : "ANY_INT",
"TIME" : "ANY_MAGNITUDE",
"BOOL" : "ANY_BIT",
"BYTE" : "ANY_BIT",
"WORD" : "ANY_BIT",
"DWORD" : "ANY_BIT",
"LWORD" : "ANY_BIT",
"STRING" : "ANY_STRING",
"WSTRING" : "ANY_STRING",
"DATE" : "ANY_DATE",
"TOD" : "ANY_DATE",
"DT" : "ANY_DATE"
}
"""
returns true if the given data type is the same that "reference" meta-type or one of its types.
"""
def IsOfType(test, reference):
while test != None:
if test == reference:
return True
test = TypeHierarchy[test]
return False
"""
returns list of all types that correspont to the ANY* meta type
"""
def GetSubTypes(reference):
return [ typename for typename in TypeHierarchy.iterkeys() if typename[:3] != "ANY" and IsOfType(typename, reference)]
"""
take a .csv file and translate it it a "csv_table"
"""
def csv_file_to_table(file):
return [ map(string.strip,line.split(';')) for line in file.xreadlines()]
"""
seek into the csv table to a section ( section_name match 1st field )
return the matching row without first field
"""
def find_section(section_name, table):
fields = [None]
while(fields[0] != section_name):
fields = table.pop(0)
return fields[1:]
"""
extract the standard functions standard parameter names and types...
return a { ParameterName: Type, ...}
"""
def get_standard_funtions_input_variables(table):
variables = find_section("Standard_functions_variables_types", table)
standard_funtions_input_variables = {}
fields = [True,True]
while(fields[1]):
fields = table.pop(0)
variable_from_csv = dict([(champ, val) for champ, val in zip(variables, fields[1:])])
standard_funtions_input_variables[variable_from_csv['name']] = variable_from_csv['type']
return standard_funtions_input_variables
"""
translate .csv file input declaration into PLCOpenEditor interessting values
in : "(ANY_NUM, ANY_NUM)" and { ParameterName: Type, ...}
return [("IN1","ANY_NUM","none"),("IN2","ANY_NUM","none")]
"""
def csv_input_translate(str_decl, variables, base):
decl = str_decl.replace('(','').replace(')','').replace(' ','').split(',')
param_types = []
param_names = []
modifiers = []
if len(decl)>1 : suffix = str(base)
else: suffix = ''
for param_type in decl:
predifined_variable_param_type = variables.get(param_type,None)
if predifined_variable_param_type :
param_types.append(predifined_variable_param_type)
param_names.append(param_type)
else:
param_types.append(param_type)
param_names.append("IN"+suffix)
base+=1
suffix = str(base)
modifiers = ["none"]*len(param_types)
return zip(param_names,param_types,modifiers)
"""
Fillin the PLCOpenEditor standard function dictionnary
translate input and output declaration to something more pythonesque
and add interface description to comment
"""
def decl_function(dico_from_table, variables):
Function_decl = { "type" : "function" }
for field, val in dico_from_table:
translate = {
"baseinputnumber" : lambda x:int(x),
"extensible" : lambda x: {"yes":True, "no":False}[x],
"inputs" : lambda x:csv_input_translate(x,variables,Function_decl.get("baseinputnumber",1)),
"outputs":lambda x:[("OUT",x,"none")]}
Function_decl[field] = translate.get(field,lambda x:x)(val)
#Function_decl.pop("baseinputnumber")
Function_decl.pop("overloaded")
return Function_decl
"""
Returns this kind of declaration for all standard functions
[{"name" : "Numerical", 'list': [ {
'baseinputnumber': 1,
'comment': 'Addition',
'extensible': True,
'inputs': [ ('IN1', 'ANY_NUM', 'none'),
('IN2', 'ANY_NUM', 'none')],
'name': 'ADD',
'outputs': [('OUT', 'ANY_NUM', 'none')],
'type': 'function'}, ...... ] },.....]
"""
def get_standard_funtions(table):
variables = get_standard_funtions_input_variables(table)
fonctions = find_section("Standard_functions_type",table)
Standard_Functions_Decl = []
Current_section = None
for fields in table:
if fields[1]:
# If function section name given
if fields[0] :
if Current_section:
Standard_Functions_Decl.append(Current_section)
Current_section = { "name" : fields[0], "list" : [] }
Function_decl_list = []
dico_from_table = zip(fonctions, fields[1:])
Function_decl = decl_function(dico_from_table,variables)
if Function_decl["name"].startswith("*"):
input_types = GetSubTypes(Function_decl["inputs"][0][1])
else:
input_types = [None]
if Function_decl["name"].endswith("**"):
output_types = GetSubTypes(Function_decl["outputs"][0][1])
else:
output_types = [None]
funcdecl = Function_decl["name"]
for intype in input_types:
if intype != None:
decl_tpl = Function_decl["inputs"][0]
Function_decl["inputs"] = [decl_tpl[:1] + (intype,) + decl_tpl[2:]] + Function_decl["inputs"][1:]
funcdeclin = funcdecl.replace("*_", intype + '_')
Function_decl["name"] = funcdeclin
for outype in output_types:
if outype != None:
decl_tpl = Function_decl["outputs"][0]
Function_decl["outputs"] = [decl_tpl[:1] + (outype,) + decl_tpl[2:]] + Function_decl["outputs"][1:]
funcdeclout = funcdeclin.replace("_**", '_' + outype)
Function_decl["name"] = funcdeclout
# create the copy of decl dict to be appended to section
Function_decl_copy = Function_decl.copy()
# Have to generate type description in comment with freshly redefined types
Function_decl_copy["comment"] += ("\n (" +
str([ " " + fctdecl[1]+":"+fctdecl[0] for fctdecl in Function_decl["inputs"]]).strip("[]").replace("'",'') +
" ) => (" +
str([ " " + fctdecl[1]+":"+fctdecl[0] for fctdecl in Function_decl["outputs"]]).strip("[]").replace("'",'') +
" )")
Current_section["list"].append(Function_decl_copy)
return Standard_Functions_Decl
#-------------------------------------------------------------------------------
# Test identifier
#-------------------------------------------------------------------------------
# Test if identifier is valid
def TestIdentifier(identifier):
if identifier[0].isdigit():
return False
words = identifier.split('_')
for i, word in enumerate(words):
if len(word) == 0 and i != 0:
return False
if len(word) != 0 and not word.isalnum():
return False
return True
#-------------------------------------------------------------------------------
# Languages Keywords
#-------------------------------------------------------------------------------
# Keywords for Pou Declaration
POU_KEYWORDS = ["FUNCTION", "END_FUNCTION", "FUNCTION_BLOCK", "END_FUNCTION_BLOCK",
"PROGRAM", "END_PROGRAM", "EN", "ENO", "F_EDGE", "R_EDGE"]
for category in BlockTypes:
for block in category["list"]:
if block["name"] not in POU_KEYWORDS:
POU_KEYWORDS.append(block["name"])
# Keywords for Type Declaration
TYPE_KEYWORDS = ["TYPE", "END_TYPE", "STRUCT", "END_STRUCT", "ARRAY", "OF", "T",
"D", "TIME_OF_DAY", "DATE_AND_TIME"]
TYPE_KEYWORDS.extend([keyword for keyword in TypeHierarchy.keys() if keyword not in TYPE_KEYWORDS])
# Keywords for Variable Declaration
VAR_KEYWORDS = ["VAR", "VAR_INPUT", "VAR_OUTPUT", "VAR_IN_OUT", "VAR_TEMP",
"VAR_EXTERNAL", "END_VAR", "AT", "CONSTANT", "RETAIN", "NON_RETAIN"]
# Keywords for Configuration Declaration
CONFIG_KEYWORDS = ["CONFIGURATION", "END_CONFIGURATION", "RESOURCE", "ON", "END_RESOURCE",
"PROGRAM", "WITH", "READ_ONLY", "READ_WRITE", "TASK", "VAR_ACCESS", "VAR_CONFIG",
"VAR_GLOBAL", "END_VAR"]
# Keywords for Structured Function Chart
SFC_KEYWORDS = ["ACTION", "END_ACTION", "INITIAL_STEP", "STEP", "END_STEP", "TRANSITION",
"FROM", "TO", "END_TRANSITION"]
# Keywords for Instruction List
IL_KEYWORDS = ["LD", "LDN", "ST", "STN", "S", "R", "AND", "ANDN", "OR", "ORN",
"XOR", "XORN", "NOT", "ADD", "SUB", "MUL", "DIV", "MOD", "GT", "GE", "EQ", "NE",
"LE", "LT", "JMP", "JMPC", "JMPNC", "CAL", "CALC", "CALNC", "RET", "RETC", "RETNC"]
# Keywords for Instruction List and Structured Text
ST_KEYWORDS = ["IF", "THEN", "ELSIF", "ELSE", "END_IF", "CASE", "OF", "END_CASE",
"FOR", "TO", "BY", "DO", "END_FOR", "WHILE", "DO", "END_WHILE", "REPEAT", "UNTIL",
"END_REPEAT", "EXIT", "RETURN", "NOT", "MOD", "AND", "XOR", "OR"]
# All the keywords of IEC
IEC_KEYWORDS = ["E", "TRUE", "FALSE"]
IEC_KEYWORDS.extend([keyword for keyword in POU_KEYWORDS if keyword not in IEC_KEYWORDS])
IEC_KEYWORDS.extend([keyword for keyword in TYPE_KEYWORDS if keyword not in IEC_KEYWORDS])
IEC_KEYWORDS.extend([keyword for keyword in VAR_KEYWORDS if keyword not in IEC_KEYWORDS])
IEC_KEYWORDS.extend([keyword for keyword in CONFIG_KEYWORDS if keyword not in IEC_KEYWORDS])
IEC_KEYWORDS.extend([keyword for keyword in SFC_KEYWORDS if keyword not in IEC_KEYWORDS])
IEC_KEYWORDS.extend([keyword for keyword in IL_KEYWORDS if keyword not in IEC_KEYWORDS])
IEC_KEYWORDS.extend([keyword for keyword in ST_KEYWORDS if keyword not in IEC_KEYWORDS])
if __name__ == '__main__':
import pprint
pp = pprint.PrettyPrinter(indent=4)
std_decl = get_standard_funtions(csv_file_to_table(open("iec_std.csv")))
pp.pprint(std_decl)
else:
# Put standard functions declaration in Bloktypes
BlockTypes.extend(get_standard_funtions(csv_file_to_table(open(os.path.join(sys.path[0], "plcopen/iec_std.csv")))))