author | Laurent Bessard |
Mon, 10 Jun 2013 01:15:39 +0200 | |
changeset 1237 | 0c8b8ef9559b |
parent 1183 | a01618805821 |
child 1239 | d1f6ea56555d |
permissions | -rw-r--r-- |
814 | 1 |
#!/usr/bin/env python |
2 |
# -*- coding: utf-8 -*- |
|
3 |
||
4 |
#This file is part of PLCOpenEditor, a library implementing an IEC 61131-3 editor |
|
5 |
#based on the plcopen standard. |
|
6 |
# |
|
7 |
#Copyright (C) 2007: Edouard TISSERANT and Laurent BESSARD |
|
8 |
# |
|
9 |
#See COPYING file for copyrights details. |
|
10 |
# |
|
11 |
#This library is free software; you can redistribute it and/or |
|
12 |
#modify it under the terms of the GNU General Public |
|
13 |
#License as published by the Free Software Foundation; either |
|
14 |
#version 2.1 of the License, or (at your option) any later version. |
|
15 |
# |
|
16 |
#This library is distributed in the hope that it will be useful, |
|
17 |
#but WITHOUT ANY WARRANTY; without even the implied warranty of |
|
18 |
#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU |
|
19 |
#General Public License for more details. |
|
20 |
# |
|
21 |
#You should have received a copy of the GNU General Public |
|
22 |
#License along with this library; if not, write to the Free Software |
|
23 |
#Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA |
|
24 |
||
25 |
from plcopen import plcopen |
|
26 |
from plcopen.structures import * |
|
27 |
from types import * |
|
28 |
import re |
|
29 |
||
30 |
# Dictionary associating PLCOpen variable categories to the corresponding |
|
31 |
# IEC 61131-3 variable categories |
|
32 |
varTypeNames = {"localVars" : "VAR", "tempVars" : "VAR_TEMP", "inputVars" : "VAR_INPUT", |
|
33 |
"outputVars" : "VAR_OUTPUT", "inOutVars" : "VAR_IN_OUT", "externalVars" : "VAR_EXTERNAL", |
|
34 |
"globalVars" : "VAR_GLOBAL", "accessVars" : "VAR_ACCESS"} |
|
35 |
||
36 |
||
37 |
# Dictionary associating PLCOpen POU categories to the corresponding |
|
38 |
# IEC 61131-3 POU categories |
|
39 |
pouTypeNames = {"function" : "FUNCTION", "functionBlock" : "FUNCTION_BLOCK", "program" : "PROGRAM"} |
|
40 |
||
41 |
||
42 |
errorVarTypes = { |
|
43 |
"VAR_INPUT": "var_input", |
|
44 |
"VAR_OUTPUT": "var_output", |
|
45 |
"VAR_INOUT": "var_inout", |
|
46 |
} |
|
47 |
||
48 |
# Helper function for reindenting text |
|
49 |
def ReIndentText(text, nb_spaces): |
|
50 |
compute = "" |
|
51 |
lines = text.splitlines() |
|
52 |
if len(lines) > 0: |
|
53 |
line_num = 0 |
|
54 |
while line_num < len(lines) and len(lines[line_num].strip()) == 0: |
|
55 |
line_num += 1 |
|
56 |
if line_num < len(lines): |
|
57 |
spaces = 0 |
|
58 |
while lines[line_num][spaces] == " ": |
|
59 |
spaces += 1 |
|
60 |
indent = "" |
|
61 |
for i in xrange(spaces, nb_spaces): |
|
62 |
indent += " " |
|
63 |
for line in lines: |
|
64 |
if line != "": |
|
65 |
compute += "%s%s\n"%(indent, line) |
|
66 |
else: |
|
67 |
compute += "\n" |
|
68 |
return compute |
|
69 |
||
70 |
def SortInstances(a, b): |
|
71 |
ax, ay = int(a.getx()), int(a.gety()) |
|
72 |
bx, by = int(b.getx()), int(b.gety()) |
|
73 |
if abs(ay - by) < 10: |
|
74 |
return cmp(ax, bx) |
|
75 |
else: |
|
76 |
return cmp(ay, by) |
|
77 |
||
78 |
#------------------------------------------------------------------------------- |
|
79 |
# Specific exception for PLC generating errors |
|
80 |
#------------------------------------------------------------------------------- |
|
81 |
||
82 |
||
83 |
class PLCGenException(Exception): |
|
84 |
pass |
|
85 |
||
86 |
||
87 |
#------------------------------------------------------------------------------- |
|
88 |
# Generator of PLC program |
|
89 |
#------------------------------------------------------------------------------- |
|
90 |
||
91 |
||
92 |
class ProgramGenerator: |
|
93 |
||
94 |
# Create a new PCL program generator |
|
95 |
def __init__(self, controler, project, errors, warnings): |
|
96 |
# Keep reference of the controler and project |
|
97 |
self.Controler = controler |
|
98 |
self.Project = project |
|
99 |
# Reset the internal variables used to generate PLC programs |
|
100 |
self.Program = [] |
|
101 |
self.DatatypeComputed = {} |
|
102 |
self.PouComputed = {} |
|
103 |
self.Errors = errors |
|
104 |
self.Warnings = warnings |
|
105 |
||
106 |
# Compute value according to type given |
|
107 |
def ComputeValue(self, value, var_type): |
|
108 |
base_type = self.Controler.GetBaseType(var_type) |
|
1032
c4989e53f9c3
Fix bug defining string initial value using quotes
Laurent Bessard
parents:
893
diff
changeset
|
109 |
if base_type == "STRING" and not value.startswith("'") and not value.endswith("'"): |
814 | 110 |
return "'%s'"%value |
1032
c4989e53f9c3
Fix bug defining string initial value using quotes
Laurent Bessard
parents:
893
diff
changeset
|
111 |
elif base_type == "WSTRING" and not value.startswith('"') and not value.endswith('"'): |
814 | 112 |
return "\"%s\""%value |
113 |
return value |
|
114 |
||
115 |
# Generate a data type from its name |
|
116 |
def GenerateDataType(self, datatype_name): |
|
117 |
# Verify that data type hasn't been generated yet |
|
118 |
if not self.DatatypeComputed.get(datatype_name, True): |
|
119 |
# If not mark data type as computed |
|
120 |
self.DatatypeComputed[datatype_name] = True |
|
121 |
||
122 |
# Getting datatype model from project |
|
123 |
datatype = self.Project.getdataType(datatype_name) |
|
124 |
tagname = self.Controler.ComputeDataTypeName(datatype.getname()) |
|
125 |
datatype_def = [(" ", ()), |
|
126 |
(datatype.getname(), (tagname, "name")), |
|
127 |
(" : ", ())] |
|
128 |
basetype_content = datatype.baseType.getcontent() |
|
129 |
# Data type derived directly from a string type |
|
130 |
if basetype_content["name"] in ["string", "wstring"]: |
|
131 |
datatype_def += [(basetype_content["name"].upper(), (tagname, "base"))] |
|
132 |
# Data type derived directly from a user defined type |
|
133 |
elif basetype_content["name"] == "derived": |
|
134 |
basetype_name = basetype_content["value"].getname() |
|
135 |
self.GenerateDataType(basetype_name) |
|
136 |
datatype_def += [(basetype_name, (tagname, "base"))] |
|
137 |
# Data type is a subrange |
|
138 |
elif basetype_content["name"] in ["subrangeSigned", "subrangeUnsigned"]: |
|
139 |
base_type = basetype_content["value"].baseType.getcontent() |
|
140 |
# Subrange derived directly from a user defined type |
|
141 |
if base_type["name"] == "derived": |
|
142 |
basetype_name = base_type["value"].getname() |
|
143 |
self.GenerateDataType(basetype_name) |
|
144 |
# Subrange derived directly from an elementary type |
|
145 |
else: |
|
146 |
basetype_name = base_type["name"] |
|
147 |
min_value = basetype_content["value"].range.getlower() |
|
148 |
max_value = basetype_content["value"].range.getupper() |
|
149 |
datatype_def += [(basetype_name, (tagname, "base")), |
|
150 |
(" (", ()), |
|
151 |
("%s"%min_value, (tagname, "lower")), |
|
152 |
("..", ()), |
|
153 |
("%s"%max_value, (tagname, "upper")), |
|
154 |
(")",())] |
|
155 |
# Data type is an enumerated type |
|
156 |
elif basetype_content["name"] == "enum": |
|
157 |
values = [[(value.getname(), (tagname, "value", i))] |
|
158 |
for i, value in enumerate(basetype_content["value"].values.getvalue())] |
|
159 |
datatype_def += [("(", ())] |
|
160 |
datatype_def += JoinList([(", ", ())], values) |
|
161 |
datatype_def += [(")", ())] |
|
162 |
# Data type is an array |
|
163 |
elif basetype_content["name"] == "array": |
|
164 |
base_type = basetype_content["value"].baseType.getcontent() |
|
165 |
# Array derived directly from a user defined type |
|
166 |
if base_type["name"] == "derived": |
|
167 |
basetype_name = base_type["value"].getname() |
|
168 |
self.GenerateDataType(basetype_name) |
|
169 |
# Array derived directly from a string type |
|
170 |
elif base_type["name"] in ["string", "wstring"]: |
|
171 |
basetype_name = base_type["name"].upper() |
|
172 |
# Array derived directly from an elementary type |
|
173 |
else: |
|
174 |
basetype_name = base_type["name"] |
|
175 |
dimensions = [[("%s"%dimension.getlower(), (tagname, "range", i, "lower")), |
|
176 |
("..", ()), |
|
177 |
("%s"%dimension.getupper(), (tagname, "range", i, "upper"))] |
|
178 |
for i, dimension in enumerate(basetype_content["value"].getdimension())] |
|
179 |
datatype_def += [("ARRAY [", ())] |
|
180 |
datatype_def += JoinList([(",", ())], dimensions) |
|
181 |
datatype_def += [("] OF " , ()), |
|
182 |
(basetype_name, (tagname, "base"))] |
|
183 |
# Data type is a structure |
|
184 |
elif basetype_content["name"] == "struct": |
|
185 |
elements = [] |
|
186 |
for i, element in enumerate(basetype_content["value"].getvariable()): |
|
187 |
element_type = element.type.getcontent() |
|
188 |
# Structure element derived directly from a user defined type |
|
189 |
if element_type["name"] == "derived": |
|
190 |
elementtype_name = element_type["value"].getname() |
|
191 |
self.GenerateDataType(elementtype_name) |
|
864
bf4f7f0801b9
Adding support for direct array declaration in structure element declaration
Laurent Bessard
parents:
854
diff
changeset
|
192 |
elif element_type["name"] == "array": |
bf4f7f0801b9
Adding support for direct array declaration in structure element declaration
Laurent Bessard
parents:
854
diff
changeset
|
193 |
base_type = element_type["value"].baseType.getcontent() |
bf4f7f0801b9
Adding support for direct array declaration in structure element declaration
Laurent Bessard
parents:
854
diff
changeset
|
194 |
# Array derived directly from a user defined type |
bf4f7f0801b9
Adding support for direct array declaration in structure element declaration
Laurent Bessard
parents:
854
diff
changeset
|
195 |
if base_type["name"] == "derived": |
bf4f7f0801b9
Adding support for direct array declaration in structure element declaration
Laurent Bessard
parents:
854
diff
changeset
|
196 |
basetype_name = base_type["value"].getname() |
bf4f7f0801b9
Adding support for direct array declaration in structure element declaration
Laurent Bessard
parents:
854
diff
changeset
|
197 |
self.GenerateDataType(basetype_name) |
bf4f7f0801b9
Adding support for direct array declaration in structure element declaration
Laurent Bessard
parents:
854
diff
changeset
|
198 |
# Array derived directly from a string type |
bf4f7f0801b9
Adding support for direct array declaration in structure element declaration
Laurent Bessard
parents:
854
diff
changeset
|
199 |
elif base_type["name"] in ["string", "wstring"]: |
bf4f7f0801b9
Adding support for direct array declaration in structure element declaration
Laurent Bessard
parents:
854
diff
changeset
|
200 |
basetype_name = base_type["name"].upper() |
bf4f7f0801b9
Adding support for direct array declaration in structure element declaration
Laurent Bessard
parents:
854
diff
changeset
|
201 |
# Array derived directly from an elementary type |
bf4f7f0801b9
Adding support for direct array declaration in structure element declaration
Laurent Bessard
parents:
854
diff
changeset
|
202 |
else: |
bf4f7f0801b9
Adding support for direct array declaration in structure element declaration
Laurent Bessard
parents:
854
diff
changeset
|
203 |
basetype_name = base_type["name"] |
bf4f7f0801b9
Adding support for direct array declaration in structure element declaration
Laurent Bessard
parents:
854
diff
changeset
|
204 |
dimensions = ["%s..%s" % (dimension.getlower(), dimension.getupper()) |
bf4f7f0801b9
Adding support for direct array declaration in structure element declaration
Laurent Bessard
parents:
854
diff
changeset
|
205 |
for dimension in element_type["value"].getdimension()] |
bf4f7f0801b9
Adding support for direct array declaration in structure element declaration
Laurent Bessard
parents:
854
diff
changeset
|
206 |
elementtype_name = "ARRAY [%s] OF %s" % (",".join(dimensions), basetype_name) |
814 | 207 |
# Structure element derived directly from a string type |
208 |
elif element_type["name"] in ["string", "wstring"]: |
|
209 |
elementtype_name = element_type["name"].upper() |
|
210 |
# Structure element derived directly from an elementary type |
|
211 |
else: |
|
212 |
elementtype_name = element_type["name"] |
|
213 |
element_text = [("\n ", ()), |
|
214 |
(element.getname(), (tagname, "struct", i, "name")), |
|
215 |
(" : ", ()), |
|
216 |
(elementtype_name, (tagname, "struct", i, "type"))] |
|
217 |
if element.initialValue is not None: |
|
218 |
element_text.extend([(" := ", ()), |
|
219 |
(self.ComputeValue(element.initialValue.getvalue(), elementtype_name), (tagname, "struct", i, "initial value"))]) |
|
220 |
element_text.append((";", ())) |
|
221 |
elements.append(element_text) |
|
222 |
datatype_def += [("STRUCT", ())] |
|
223 |
datatype_def += JoinList([("", ())], elements) |
|
224 |
datatype_def += [("\n END_STRUCT", ())] |
|
225 |
# Data type derived directly from a elementary type |
|
226 |
else: |
|
227 |
datatype_def += [(basetype_content["name"], (tagname, "base"))] |
|
228 |
# Data type has an initial value |
|
229 |
if datatype.initialValue is not None: |
|
230 |
datatype_def += [(" := ", ()), |
|
231 |
(self.ComputeValue(datatype.initialValue.getvalue(), datatype_name), (tagname, "initial value"))] |
|
232 |
datatype_def += [(";\n", ())] |
|
233 |
self.Program += datatype_def |
|
234 |
||
235 |
# Generate a POU from its name |
|
236 |
def GeneratePouProgram(self, pou_name): |
|
237 |
# Verify that POU hasn't been generated yet |
|
238 |
if not self.PouComputed.get(pou_name, True): |
|
239 |
# If not mark POU as computed |
|
240 |
self.PouComputed[pou_name] = True |
|
241 |
||
242 |
# Getting POU model from project |
|
243 |
pou = self.Project.getpou(pou_name) |
|
244 |
pou_type = pou.getpouType() |
|
245 |
# Verify that POU type exists |
|
246 |
if pouTypeNames.has_key(pou_type): |
|
247 |
# Create a POU program generator |
|
248 |
pou_program = PouProgramGenerator(self, pou.getname(), pouTypeNames[pou_type], self.Errors, self.Warnings) |
|
249 |
program = pou_program.GenerateProgram(pou) |
|
250 |
self.Program += program |
|
251 |
else: |
|
252 |
raise PLCGenException, _("Undefined pou type \"%s\"")%pou_type |
|
253 |
||
254 |
# Generate a POU defined and used in text |
|
255 |
def GeneratePouProgramInText(self, text): |
|
256 |
for pou_name in self.PouComputed.keys(): |
|
257 |
model = re.compile("(?:^|[^0-9^A-Z])%s(?:$|[^0-9^A-Z])"%pou_name.upper()) |
|
258 |
if model.search(text) is not None: |
|
259 |
self.GeneratePouProgram(pou_name) |
|
260 |
||
261 |
# Generate a configuration from its model |
|
262 |
def GenerateConfiguration(self, configuration): |
|
263 |
tagname = self.Controler.ComputeConfigurationName(configuration.getname()) |
|
264 |
config = [("\nCONFIGURATION ", ()), |
|
265 |
(configuration.getname(), (tagname, "name")), |
|
266 |
("\n", ())] |
|
267 |
var_number = 0 |
|
883
235a9ec83b95
Adding support for defining specific global variables for ConfTreeNodes
Laurent Bessard
parents:
864
diff
changeset
|
268 |
|
235a9ec83b95
Adding support for defining specific global variables for ConfTreeNodes
Laurent Bessard
parents:
864
diff
changeset
|
269 |
varlists = [(varlist, varlist.getvariable()[:]) for varlist in configuration.getglobalVars()] |
235a9ec83b95
Adding support for defining specific global variables for ConfTreeNodes
Laurent Bessard
parents:
864
diff
changeset
|
270 |
|
235a9ec83b95
Adding support for defining specific global variables for ConfTreeNodes
Laurent Bessard
parents:
864
diff
changeset
|
271 |
extra_variables = self.Controler.GetConfigurationExtraVariables() |
235a9ec83b95
Adding support for defining specific global variables for ConfTreeNodes
Laurent Bessard
parents:
864
diff
changeset
|
272 |
if len(extra_variables) > 0: |
235a9ec83b95
Adding support for defining specific global variables for ConfTreeNodes
Laurent Bessard
parents:
864
diff
changeset
|
273 |
if len(varlists) == 0: |
235a9ec83b95
Adding support for defining specific global variables for ConfTreeNodes
Laurent Bessard
parents:
864
diff
changeset
|
274 |
varlists = [(plcopen.interface_globalVars(), [])] |
235a9ec83b95
Adding support for defining specific global variables for ConfTreeNodes
Laurent Bessard
parents:
864
diff
changeset
|
275 |
varlists[-1][1].extend(extra_variables) |
235a9ec83b95
Adding support for defining specific global variables for ConfTreeNodes
Laurent Bessard
parents:
864
diff
changeset
|
276 |
|
814 | 277 |
# Generate any global variable in configuration |
883
235a9ec83b95
Adding support for defining specific global variables for ConfTreeNodes
Laurent Bessard
parents:
864
diff
changeset
|
278 |
for varlist, varlist_variables in varlists: |
814 | 279 |
variable_type = errorVarTypes.get("VAR_GLOBAL", "var_local") |
280 |
# Generate variable block with modifier |
|
281 |
config += [(" VAR_GLOBAL", ())] |
|
282 |
if varlist.getconstant(): |
|
283 |
config += [(" CONSTANT", (tagname, variable_type, (var_number, var_number + len(varlist.getvariable())), "constant"))] |
|
284 |
elif varlist.getretain(): |
|
285 |
config += [(" RETAIN", (tagname, variable_type, (var_number, var_number + len(varlist.getvariable())), "retain"))] |
|
286 |
elif varlist.getnonretain(): |
|
287 |
config += [(" NON_RETAIN", (tagname, variable_type, (var_number, var_number + len(varlist.getvariable())), "non_retain"))] |
|
288 |
config += [("\n", ())] |
|
289 |
# Generate any variable of this block |
|
883
235a9ec83b95
Adding support for defining specific global variables for ConfTreeNodes
Laurent Bessard
parents:
864
diff
changeset
|
290 |
for var in varlist_variables: |
814 | 291 |
vartype_content = var.gettype().getcontent() |
292 |
if vartype_content["name"] == "derived": |
|
293 |
var_type = vartype_content["value"].getname() |
|
294 |
self.GenerateDataType(var_type) |
|
295 |
else: |
|
296 |
var_type = var.gettypeAsText() |
|
297 |
||
298 |
config += [(" ", ()), |
|
299 |
(var.getname(), (tagname, variable_type, var_number, "name")), |
|
300 |
(" ", ())] |
|
301 |
# Generate variable address if exists |
|
302 |
address = var.getaddress() |
|
303 |
if address: |
|
304 |
config += [("AT ", ()), |
|
305 |
(address, (tagname, variable_type, var_number, "location")), |
|
306 |
(" ", ())] |
|
307 |
config += [(": ", ()), |
|
308 |
(var.gettypeAsText(), (tagname, variable_type, var_number, "type"))] |
|
309 |
# Generate variable initial value if exists |
|
310 |
initial = var.getinitialValue() |
|
311 |
if initial: |
|
312 |
config += [(" := ", ()), |
|
313 |
(self.ComputeValue(initial.getvalue(), var_type), (tagname, variable_type, var_number, "initial value"))] |
|
314 |
config += [(";\n", ())] |
|
315 |
var_number += 1 |
|
316 |
config += [(" END_VAR\n", ())] |
|
317 |
# Generate any resource in the configuration |
|
318 |
for resource in configuration.getresource(): |
|
319 |
config += self.GenerateResource(resource, configuration.getname()) |
|
320 |
config += [("END_CONFIGURATION\n", ())] |
|
321 |
return config |
|
322 |
||
323 |
# Generate a resource from its model |
|
324 |
def GenerateResource(self, resource, config_name): |
|
325 |
tagname = self.Controler.ComputeConfigurationResourceName(config_name, resource.getname()) |
|
326 |
resrce = [("\n RESOURCE ", ()), |
|
327 |
(resource.getname(), (tagname, "name")), |
|
328 |
(" ON PLC\n", ())] |
|
329 |
var_number = 0 |
|
330 |
# Generate any global variable in configuration |
|
331 |
for varlist in resource.getglobalVars(): |
|
332 |
variable_type = errorVarTypes.get("VAR_GLOBAL", "var_local") |
|
333 |
# Generate variable block with modifier |
|
334 |
resrce += [(" VAR_GLOBAL", ())] |
|
335 |
if varlist.getconstant(): |
|
336 |
resrce += [(" CONSTANT", (tagname, variable_type, (var_number, var_number + len(varlist.getvariable())), "constant"))] |
|
337 |
elif varlist.getretain(): |
|
338 |
resrce += [(" RETAIN", (tagname, variable_type, (var_number, var_number + len(varlist.getvariable())), "retain"))] |
|
339 |
elif varlist.getnonretain(): |
|
340 |
resrce += [(" NON_RETAIN", (tagname, variable_type, (var_number, var_number + len(varlist.getvariable())), "non_retain"))] |
|
341 |
resrce += [("\n", ())] |
|
342 |
# Generate any variable of this block |
|
343 |
for var in varlist.getvariable(): |
|
344 |
vartype_content = var.gettype().getcontent() |
|
345 |
if vartype_content["name"] == "derived": |
|
346 |
var_type = vartype_content["value"].getname() |
|
347 |
self.GenerateDataType(var_type) |
|
348 |
else: |
|
349 |
var_type = var.gettypeAsText() |
|
350 |
||
351 |
resrce += [(" ", ()), |
|
352 |
(var.getname(), (tagname, variable_type, var_number, "name")), |
|
353 |
(" ", ())] |
|
354 |
address = var.getaddress() |
|
355 |
# Generate variable address if exists |
|
356 |
if address: |
|
357 |
resrce += [("AT ", ()), |
|
358 |
(address, (tagname, variable_type, var_number, "location")), |
|
359 |
(" ", ())] |
|
360 |
resrce += [(": ", ()), |
|
361 |
(var.gettypeAsText(), (tagname, variable_type, var_number, "type"))] |
|
362 |
# Generate variable initial value if exists |
|
363 |
initial = var.getinitialValue() |
|
364 |
if initial: |
|
365 |
resrce += [(" := ", ()), |
|
366 |
(self.ComputeValue(initial.getvalue(), var_type), (tagname, variable_type, var_number, "initial value"))] |
|
367 |
resrce += [(";\n", ())] |
|
368 |
var_number += 1 |
|
369 |
resrce += [(" END_VAR\n", ())] |
|
370 |
# Generate any task in the resource |
|
371 |
tasks = resource.gettask() |
|
372 |
task_number = 0 |
|
373 |
for task in tasks: |
|
374 |
# Task declaration |
|
375 |
resrce += [(" TASK ", ()), |
|
376 |
(task.getname(), (tagname, "task", task_number, "name")), |
|
377 |
("(", ())] |
|
378 |
args = [] |
|
379 |
single = task.getsingle() |
|
380 |
# Single argument if exists |
|
381 |
if single: |
|
382 |
resrce += [("SINGLE := ", ()), |
|
383 |
(single, (tagname, "task", task_number, "single")), |
|
384 |
(",", ())] |
|
385 |
# Interval argument if exists |
|
386 |
interval = task.getinterval() |
|
387 |
if interval: |
|
388 |
resrce += [("INTERVAL := ", ()), |
|
389 |
(interval, (tagname, "task", task_number, "interval")), |
|
390 |
(",", ())] |
|
391 |
## resrce += [("INTERVAL := t#", ())] |
|
392 |
## if interval.hour != 0: |
|
393 |
## resrce += [("%dh"%interval.hour, (tagname, "task", task_number, "interval", "hour"))] |
|
394 |
## if interval.minute != 0: |
|
395 |
## resrce += [("%dm"%interval.minute, (tagname, "task", task_number, "interval", "minute"))] |
|
396 |
## if interval.second != 0: |
|
397 |
## resrce += [("%ds"%interval.second, (tagname, "task", task_number, "interval", "second"))] |
|
398 |
## if interval.microsecond != 0: |
|
399 |
## resrce += [("%dms"%(interval.microsecond / 1000), (tagname, "task", task_number, "interval", "millisecond"))] |
|
400 |
## resrce += [(",", ())] |
|
401 |
# Priority argument |
|
402 |
resrce += [("PRIORITY := ", ()), |
|
403 |
("%d"%task.getpriority(), (tagname, "task", task_number, "priority")), |
|
404 |
(");\n", ())] |
|
405 |
task_number += 1 |
|
406 |
instance_number = 0 |
|
407 |
# Generate any program assign to each task |
|
408 |
for task in tasks: |
|
409 |
for instance in task.getpouInstance(): |
|
410 |
resrce += [(" PROGRAM ", ()), |
|
411 |
(instance.getname(), (tagname, "instance", instance_number, "name")), |
|
412 |
(" WITH ", ()), |
|
413 |
(task.getname(), (tagname, "instance", instance_number, "task")), |
|
414 |
(" : ", ()), |
|
415 |
(instance.gettypeName(), (tagname, "instance", instance_number, "type")), |
|
416 |
(";\n", ())] |
|
417 |
instance_number += 1 |
|
418 |
# Generate any program assign to no task |
|
419 |
for instance in resource.getpouInstance(): |
|
420 |
resrce += [(" PROGRAM ", ()), |
|
421 |
(instance.getname(), (tagname, "instance", instance_number, "name")), |
|
422 |
(" : ", ()), |
|
423 |
(instance.gettypeName(), (tagname, "instance", instance_number, "type")), |
|
424 |
(";\n", ())] |
|
425 |
instance_number += 1 |
|
426 |
resrce += [(" END_RESOURCE\n", ())] |
|
427 |
return resrce |
|
428 |
||
429 |
# Generate the entire program for current project |
|
430 |
def GenerateProgram(self): |
|
431 |
# Find all data types defined |
|
432 |
for datatype in self.Project.getdataTypes(): |
|
433 |
self.DatatypeComputed[datatype.getname()] = False |
|
434 |
# Find all data types defined |
|
435 |
for pou in self.Project.getpous(): |
|
436 |
self.PouComputed[pou.getname()] = False |
|
437 |
# Generate data type declaration structure if there is at least one data |
|
438 |
# type defined |
|
439 |
if len(self.DatatypeComputed) > 0: |
|
440 |
self.Program += [("TYPE\n", ())] |
|
441 |
# Generate every data types defined |
|
442 |
for datatype_name in self.DatatypeComputed.keys(): |
|
443 |
self.GenerateDataType(datatype_name) |
|
444 |
self.Program += [("END_TYPE\n\n", ())] |
|
445 |
# Generate every POUs defined |
|
446 |
for pou_name in self.PouComputed.keys(): |
|
447 |
self.GeneratePouProgram(pou_name) |
|
448 |
# Generate every configurations defined |
|
449 |
for config in self.Project.getconfigurations(): |
|
450 |
self.Program += self.GenerateConfiguration(config) |
|
451 |
||
452 |
# Return generated program |
|
453 |
def GetGeneratedProgram(self): |
|
454 |
return self.Program |
|
455 |
||
456 |
||
457 |
#------------------------------------------------------------------------------- |
|
458 |
# Generator of POU programs |
|
459 |
#------------------------------------------------------------------------------- |
|
460 |
||
461 |
||
462 |
class PouProgramGenerator: |
|
463 |
||
464 |
# Create a new POU program generator |
|
465 |
def __init__(self, parent, name, type, errors, warnings): |
|
466 |
# Keep Reference to the parent generator |
|
467 |
self.ParentGenerator = parent |
|
468 |
self.Name = name |
|
469 |
self.Type = type |
|
470 |
self.TagName = self.ParentGenerator.Controler.ComputePouName(name) |
|
471 |
self.CurrentIndent = " " |
|
472 |
self.ReturnType = None |
|
473 |
self.Interface = [] |
|
474 |
self.InitialSteps = [] |
|
475 |
self.ComputedBlocks = {} |
|
476 |
self.ComputedConnectors = {} |
|
477 |
self.ConnectionTypes = {} |
|
478 |
self.RelatedConnections = [] |
|
479 |
self.SFCNetworks = {"Steps":{}, "Transitions":{}, "Actions":{}} |
|
480 |
self.SFCComputedBlocks = [] |
|
481 |
self.ActionNumber = 0 |
|
482 |
self.Program = [] |
|
483 |
self.Errors = errors |
|
484 |
self.Warnings = warnings |
|
485 |
||
486 |
def GetBlockType(self, type, inputs=None): |
|
487 |
return self.ParentGenerator.Controler.GetBlockType(type, inputs) |
|
488 |
||
489 |
def IndentLeft(self): |
|
490 |
if len(self.CurrentIndent) >= 2: |
|
491 |
self.CurrentIndent = self.CurrentIndent[:-2] |
|
492 |
||
493 |
def IndentRight(self): |
|
494 |
self.CurrentIndent += " " |
|
495 |
||
496 |
# Generator of unique ID for inline actions |
|
497 |
def GetActionNumber(self): |
|
498 |
self.ActionNumber += 1 |
|
499 |
return self.ActionNumber |
|
500 |
||
501 |
# Test if a variable has already been defined |
|
502 |
def IsAlreadyDefined(self, name): |
|
503 |
for list_type, option, located, vars in self.Interface: |
|
504 |
for var_type, var_name, var_address, var_initial in vars: |
|
505 |
if name == var_name: |
|
506 |
return True |
|
507 |
return False |
|
508 |
||
509 |
# Return the type of a variable defined in interface |
|
510 |
def GetVariableType(self, name): |
|
511 |
parts = name.split('.') |
|
512 |
current_type = None |
|
513 |
if len(parts) > 0: |
|
514 |
name = parts.pop(0) |
|
515 |
for list_type, option, located, vars in self.Interface: |
|
516 |
for var_type, var_name, var_address, var_initial in vars: |
|
517 |
if name == var_name: |
|
518 |
current_type = var_type |
|
519 |
break |
|
520 |
while current_type is not None and len(parts) > 0: |
|
883
235a9ec83b95
Adding support for defining specific global variables for ConfTreeNodes
Laurent Bessard
parents:
864
diff
changeset
|
521 |
blocktype = self.ParentGenerator.Controler.GetBlockType(current_type) |
235a9ec83b95
Adding support for defining specific global variables for ConfTreeNodes
Laurent Bessard
parents:
864
diff
changeset
|
522 |
if blocktype is not None: |
235a9ec83b95
Adding support for defining specific global variables for ConfTreeNodes
Laurent Bessard
parents:
864
diff
changeset
|
523 |
name = parts.pop(0) |
235a9ec83b95
Adding support for defining specific global variables for ConfTreeNodes
Laurent Bessard
parents:
864
diff
changeset
|
524 |
current_type = None |
235a9ec83b95
Adding support for defining specific global variables for ConfTreeNodes
Laurent Bessard
parents:
864
diff
changeset
|
525 |
for var_name, var_type, var_modifier in blocktype["inputs"] + blocktype["outputs"]: |
235a9ec83b95
Adding support for defining specific global variables for ConfTreeNodes
Laurent Bessard
parents:
864
diff
changeset
|
526 |
if var_name == name: |
235a9ec83b95
Adding support for defining specific global variables for ConfTreeNodes
Laurent Bessard
parents:
864
diff
changeset
|
527 |
current_type = var_type |
814 | 528 |
break |
883
235a9ec83b95
Adding support for defining specific global variables for ConfTreeNodes
Laurent Bessard
parents:
864
diff
changeset
|
529 |
else: |
235a9ec83b95
Adding support for defining specific global variables for ConfTreeNodes
Laurent Bessard
parents:
864
diff
changeset
|
530 |
tagname = self.ParentGenerator.Controler.ComputeDataTypeName(current_type) |
235a9ec83b95
Adding support for defining specific global variables for ConfTreeNodes
Laurent Bessard
parents:
864
diff
changeset
|
531 |
infos = self.ParentGenerator.Controler.GetDataTypeInfos(tagname) |
235a9ec83b95
Adding support for defining specific global variables for ConfTreeNodes
Laurent Bessard
parents:
864
diff
changeset
|
532 |
if infos is not None and infos["type"] == "Structure": |
235a9ec83b95
Adding support for defining specific global variables for ConfTreeNodes
Laurent Bessard
parents:
864
diff
changeset
|
533 |
name = parts.pop(0) |
235a9ec83b95
Adding support for defining specific global variables for ConfTreeNodes
Laurent Bessard
parents:
864
diff
changeset
|
534 |
current_type = None |
235a9ec83b95
Adding support for defining specific global variables for ConfTreeNodes
Laurent Bessard
parents:
864
diff
changeset
|
535 |
for element in infos["elements"]: |
235a9ec83b95
Adding support for defining specific global variables for ConfTreeNodes
Laurent Bessard
parents:
864
diff
changeset
|
536 |
if element["Name"] == name: |
235a9ec83b95
Adding support for defining specific global variables for ConfTreeNodes
Laurent Bessard
parents:
864
diff
changeset
|
537 |
current_type = element["Type"] |
235a9ec83b95
Adding support for defining specific global variables for ConfTreeNodes
Laurent Bessard
parents:
864
diff
changeset
|
538 |
break |
814 | 539 |
return current_type |
540 |
||
541 |
# Return connectors linked by a connection to the given connector |
|
542 |
def GetConnectedConnector(self, connector, body): |
|
543 |
links = connector.getconnections() |
|
544 |
if links and len(links) == 1: |
|
545 |
return self.GetLinkedConnector(links[0], body) |
|
546 |
return None |
|
547 |
||
548 |
def GetLinkedConnector(self, link, body): |
|
549 |
parameter = link.getformalParameter() |
|
550 |
instance = body.getcontentInstance(link.getrefLocalId()) |
|
551 |
if isinstance(instance, (plcopen.fbdObjects_inVariable, plcopen.fbdObjects_inOutVariable, plcopen.commonObjects_continuation, plcopen.ldObjects_contact, plcopen.ldObjects_coil)): |
|
552 |
return instance.connectionPointOut |
|
553 |
elif isinstance(instance, plcopen.fbdObjects_block): |
|
554 |
outputvariables = instance.outputVariables.getvariable() |
|
555 |
if len(outputvariables) == 1: |
|
556 |
return outputvariables[0].connectionPointOut |
|
557 |
elif parameter: |
|
558 |
for variable in outputvariables: |
|
559 |
if variable.getformalParameter() == parameter: |
|
560 |
return variable.connectionPointOut |
|
561 |
else: |
|
562 |
point = link.getposition()[-1] |
|
563 |
for variable in outputvariables: |
|
564 |
relposition = variable.connectionPointOut.getrelPositionXY() |
|
565 |
blockposition = instance.getposition() |
|
566 |
if point.x == blockposition.x + relposition[0] and point.y == blockposition.y + relposition[1]: |
|
567 |
return variable.connectionPointOut |
|
568 |
elif isinstance(instance, plcopen.ldObjects_leftPowerRail): |
|
569 |
outputconnections = instance.getconnectionPointOut() |
|
570 |
if len(outputconnections) == 1: |
|
571 |
return outputconnections[0] |
|
572 |
else: |
|
573 |
point = link.getposition()[-1] |
|
574 |
for outputconnection in outputconnections: |
|
575 |
relposition = outputconnection.getrelPositionXY() |
|
576 |
powerrailposition = instance.getposition() |
|
577 |
if point.x == powerrailposition.x + relposition[0] and point.y == powerrailposition.y + relposition[1]: |
|
578 |
return outputconnection |
|
579 |
return None |
|
580 |
||
581 |
def ExtractRelatedConnections(self, connection): |
|
582 |
for i, related in enumerate(self.RelatedConnections): |
|
583 |
if connection in related: |
|
584 |
return self.RelatedConnections.pop(i) |
|
585 |
return [connection] |
|
586 |
||
587 |
def ComputeInterface(self, pou): |
|
588 |
interface = pou.getinterface() |
|
589 |
if interface is not None: |
|
590 |
body = pou.getbody() |
|
591 |
if isinstance(body, ListType): |
|
592 |
body = body[0] |
|
593 |
body_content = body.getcontent() |
|
594 |
if self.Type == "FUNCTION": |
|
595 |
returntype_content = interface.getreturnType().getcontent() |
|
596 |
if returntype_content["name"] == "derived": |
|
597 |
self.ReturnType = returntype_content["value"].getname() |
|
598 |
elif returntype_content["name"] in ["string", "wstring"]: |
|
599 |
self.ReturnType = returntype_content["name"].upper() |
|
600 |
else: |
|
601 |
self.ReturnType = returntype_content["name"] |
|
602 |
for varlist in interface.getcontent(): |
|
603 |
variables = [] |
|
604 |
located = [] |
|
605 |
for var in varlist["value"].getvariable(): |
|
606 |
vartype_content = var.gettype().getcontent() |
|
607 |
if vartype_content["name"] == "derived": |
|
608 |
var_type = vartype_content["value"].getname() |
|
609 |
blocktype = self.GetBlockType(var_type) |
|
610 |
if blocktype is not None: |
|
611 |
self.ParentGenerator.GeneratePouProgram(var_type) |
|
612 |
if body_content["name"] in ["FBD", "LD", "SFC"]: |
|
613 |
block = pou.getinstanceByName(var.getname()) |
|
614 |
else: |
|
615 |
block = None |
|
616 |
for variable in blocktype["initialise"](var_type, var.getname(), block): |
|
617 |
if variable[2] is not None: |
|
618 |
located.append(variable) |
|
619 |
else: |
|
620 |
variables.append(variable) |
|
621 |
else: |
|
622 |
self.ParentGenerator.GenerateDataType(var_type) |
|
623 |
initial = var.getinitialValue() |
|
624 |
if initial: |
|
625 |
initial_value = initial.getvalue() |
|
626 |
else: |
|
627 |
initial_value = None |
|
628 |
address = var.getaddress() |
|
629 |
if address is not None: |
|
630 |
located.append((vartype_content["value"].getname(), var.getname(), address, initial_value)) |
|
631 |
else: |
|
632 |
variables.append((vartype_content["value"].getname(), var.getname(), None, initial_value)) |
|
633 |
else: |
|
634 |
var_type = var.gettypeAsText() |
|
635 |
initial = var.getinitialValue() |
|
636 |
if initial: |
|
637 |
initial_value = initial.getvalue() |
|
638 |
else: |
|
639 |
initial_value = None |
|
640 |
address = var.getaddress() |
|
641 |
if address is not None: |
|
642 |
located.append((var_type, var.getname(), address, initial_value)) |
|
643 |
else: |
|
644 |
variables.append((var_type, var.getname(), None, initial_value)) |
|
645 |
if varlist["value"].getconstant(): |
|
646 |
option = "CONSTANT" |
|
647 |
elif varlist["value"].getretain(): |
|
648 |
option = "RETAIN" |
|
649 |
elif varlist["value"].getnonretain(): |
|
650 |
option = "NON_RETAIN" |
|
651 |
else: |
|
652 |
option = None |
|
653 |
if len(variables) > 0: |
|
654 |
self.Interface.append((varTypeNames[varlist["name"]], option, False, variables)) |
|
655 |
if len(located) > 0: |
|
656 |
self.Interface.append((varTypeNames[varlist["name"]], option, True, located)) |
|
1181
21e6db77eb29
Fixed bug in PLC code generated with binary, octal and hexadecimal literals
Laurent Bessard
parents:
1134
diff
changeset
|
657 |
|
21e6db77eb29
Fixed bug in PLC code generated with binary, octal and hexadecimal literals
Laurent Bessard
parents:
1134
diff
changeset
|
658 |
LITERAL_TYPES = { |
21e6db77eb29
Fixed bug in PLC code generated with binary, octal and hexadecimal literals
Laurent Bessard
parents:
1134
diff
changeset
|
659 |
"T": "TIME", |
21e6db77eb29
Fixed bug in PLC code generated with binary, octal and hexadecimal literals
Laurent Bessard
parents:
1134
diff
changeset
|
660 |
"D": "DATE", |
21e6db77eb29
Fixed bug in PLC code generated with binary, octal and hexadecimal literals
Laurent Bessard
parents:
1134
diff
changeset
|
661 |
"TOD": "TIME_OF_DAY", |
21e6db77eb29
Fixed bug in PLC code generated with binary, octal and hexadecimal literals
Laurent Bessard
parents:
1134
diff
changeset
|
662 |
"DT": "DATE_AND_TIME", |
1183
a01618805821
Fixed bug in PLC code generated with binary, octal and hexadecimal literals
Laurent Bessard
parents:
1181
diff
changeset
|
663 |
"2": None, |
a01618805821
Fixed bug in PLC code generated with binary, octal and hexadecimal literals
Laurent Bessard
parents:
1181
diff
changeset
|
664 |
"8": None, |
a01618805821
Fixed bug in PLC code generated with binary, octal and hexadecimal literals
Laurent Bessard
parents:
1181
diff
changeset
|
665 |
"16": None, |
1181
21e6db77eb29
Fixed bug in PLC code generated with binary, octal and hexadecimal literals
Laurent Bessard
parents:
1134
diff
changeset
|
666 |
} |
814 | 667 |
def ComputeConnectionTypes(self, pou): |
668 |
body = pou.getbody() |
|
669 |
if isinstance(body, ListType): |
|
670 |
body = body[0] |
|
671 |
body_content = body.getcontent() |
|
672 |
body_type = body_content["name"] |
|
673 |
if body_type in ["FBD", "LD", "SFC"]: |
|
674 |
undefined_blocks = [] |
|
675 |
for instance in body.getcontentInstances(): |
|
676 |
if isinstance(instance, (plcopen.fbdObjects_inVariable, plcopen.fbdObjects_outVariable, plcopen.fbdObjects_inOutVariable)): |
|
677 |
expression = instance.getexpression() |
|
678 |
var_type = self.GetVariableType(expression) |
|
822
050045c32d98
Fix bug in PLCGenerator connection types not computed for SFC actions and transitions body
laurent
parents:
814
diff
changeset
|
679 |
if isinstance(pou, plcopen.transitions_transition) and expression == pou.getname(): |
050045c32d98
Fix bug in PLCGenerator connection types not computed for SFC actions and transitions body
laurent
parents:
814
diff
changeset
|
680 |
var_type = "BOOL" |
050045c32d98
Fix bug in PLCGenerator connection types not computed for SFC actions and transitions body
laurent
parents:
814
diff
changeset
|
681 |
elif (not isinstance(pou, (plcopen.transitions_transition, plcopen.actions_action)) and |
050045c32d98
Fix bug in PLCGenerator connection types not computed for SFC actions and transitions body
laurent
parents:
814
diff
changeset
|
682 |
pou.getpouType() == "function" and expression == pou.getname()): |
814 | 683 |
returntype_content = pou.interface.getreturnType().getcontent() |
684 |
if returntype_content["name"] == "derived": |
|
685 |
var_type = returntype_content["value"].getname() |
|
686 |
elif returntype_content["name"] in ["string", "wstring"]: |
|
687 |
var_type = returntype_content["name"].upper() |
|
688 |
else: |
|
689 |
var_type = returntype_content["name"] |
|
690 |
elif var_type is None: |
|
691 |
parts = expression.split("#") |
|
692 |
if len(parts) > 1: |
|
1181
21e6db77eb29
Fixed bug in PLC code generated with binary, octal and hexadecimal literals
Laurent Bessard
parents:
1134
diff
changeset
|
693 |
literal_prefix = parts[0].upper() |
21e6db77eb29
Fixed bug in PLC code generated with binary, octal and hexadecimal literals
Laurent Bessard
parents:
1134
diff
changeset
|
694 |
var_type = self.LITERAL_TYPES.get(literal_prefix, |
21e6db77eb29
Fixed bug in PLC code generated with binary, octal and hexadecimal literals
Laurent Bessard
parents:
1134
diff
changeset
|
695 |
literal_prefix) |
814 | 696 |
elif expression.startswith("'"): |
697 |
var_type = "STRING" |
|
698 |
elif expression.startswith('"'): |
|
699 |
var_type = "WSTRING" |
|
700 |
if var_type is not None: |
|
701 |
if isinstance(instance, (plcopen.fbdObjects_inVariable, plcopen.fbdObjects_inOutVariable)): |
|
702 |
for connection in self.ExtractRelatedConnections(instance.connectionPointOut): |
|
703 |
self.ConnectionTypes[connection] = var_type |
|
704 |
if isinstance(instance, (plcopen.fbdObjects_outVariable, plcopen.fbdObjects_inOutVariable)): |
|
705 |
self.ConnectionTypes[instance.connectionPointIn] = var_type |
|
706 |
connected = self.GetConnectedConnector(instance.connectionPointIn, body) |
|
707 |
if connected and not self.ConnectionTypes.has_key(connected): |
|
708 |
for connection in self.ExtractRelatedConnections(connected): |
|
709 |
self.ConnectionTypes[connection] = var_type |
|
710 |
elif isinstance(instance, (plcopen.ldObjects_contact, plcopen.ldObjects_coil)): |
|
711 |
for connection in self.ExtractRelatedConnections(instance.connectionPointOut): |
|
712 |
self.ConnectionTypes[connection] = "BOOL" |
|
713 |
self.ConnectionTypes[instance.connectionPointIn] = "BOOL" |
|
714 |
connected = self.GetConnectedConnector(instance.connectionPointIn, body) |
|
715 |
if connected and not self.ConnectionTypes.has_key(connected): |
|
716 |
for connection in self.ExtractRelatedConnections(connected): |
|
717 |
self.ConnectionTypes[connection] = "BOOL" |
|
718 |
elif isinstance(instance, plcopen.ldObjects_leftPowerRail): |
|
719 |
for connection in instance.getconnectionPointOut(): |
|
720 |
for related in self.ExtractRelatedConnections(connection): |
|
721 |
self.ConnectionTypes[related] = "BOOL" |
|
722 |
elif isinstance(instance, plcopen.ldObjects_rightPowerRail): |
|
723 |
for connection in instance.getconnectionPointIn(): |
|
724 |
self.ConnectionTypes[connection] = "BOOL" |
|
725 |
connected = self.GetConnectedConnector(connection, body) |
|
726 |
if connected and not self.ConnectionTypes.has_key(connected): |
|
727 |
for connection in self.ExtractRelatedConnections(connected): |
|
728 |
self.ConnectionTypes[connection] = "BOOL" |
|
729 |
elif isinstance(instance, plcopen.sfcObjects_transition): |
|
730 |
content = instance.condition.getcontent() |
|
731 |
if content["name"] == "connection" and len(content["value"]) == 1: |
|
732 |
connected = self.GetLinkedConnector(content["value"][0], body) |
|
733 |
if connected and not self.ConnectionTypes.has_key(connected): |
|
734 |
for connection in self.ExtractRelatedConnections(connected): |
|
735 |
self.ConnectionTypes[connection] = "BOOL" |
|
736 |
elif isinstance(instance, plcopen.commonObjects_continuation): |
|
737 |
name = instance.getname() |
|
738 |
connector = None |
|
739 |
var_type = "ANY" |
|
740 |
for element in body.getcontentInstances(): |
|
741 |
if isinstance(element, plcopen.commonObjects_connector) and element.getname() == name: |
|
742 |
if connector is not None: |
|
743 |
raise PLCGenException, _("More than one connector found corresponding to \"%s\" continuation in \"%s\" POU")%(name, self.Name) |
|
744 |
connector = element |
|
745 |
if connector is not None: |
|
746 |
undefined = [instance.connectionPointOut, connector.connectionPointIn] |
|
747 |
connected = self.GetConnectedConnector(connector.connectionPointIn, body) |
|
748 |
if connected: |
|
749 |
undefined.append(connected) |
|
750 |
related = [] |
|
751 |
for connection in undefined: |
|
752 |
if self.ConnectionTypes.has_key(connection): |
|
753 |
var_type = self.ConnectionTypes[connection] |
|
754 |
else: |
|
755 |
related.extend(self.ExtractRelatedConnections(connection)) |
|
756 |
if var_type.startswith("ANY") and len(related) > 0: |
|
757 |
self.RelatedConnections.append(related) |
|
758 |
else: |
|
759 |
for connection in related: |
|
760 |
self.ConnectionTypes[connection] = var_type |
|
761 |
else: |
|
762 |
raise PLCGenException, _("No connector found corresponding to \"%s\" continuation in \"%s\" POU")%(name, self.Name) |
|
763 |
elif isinstance(instance, plcopen.fbdObjects_block): |
|
764 |
block_infos = self.GetBlockType(instance.gettypeName(), "undefined") |
|
765 |
if block_infos is not None: |
|
766 |
self.ComputeBlockInputTypes(instance, block_infos, body) |
|
767 |
else: |
|
768 |
for variable in instance.inputVariables.getvariable(): |
|
769 |
connected = self.GetConnectedConnector(variable.connectionPointIn, body) |
|
770 |
if connected is not None: |
|
771 |
var_type = self.ConnectionTypes.get(connected, None) |
|
772 |
if var_type is not None: |
|
773 |
self.ConnectionTypes[variable.connectionPointIn] = var_type |
|
774 |
else: |
|
775 |
related = self.ExtractRelatedConnections(connected) |
|
776 |
related.append(variable.connectionPointIn) |
|
777 |
self.RelatedConnections.append(related) |
|
778 |
undefined_blocks.append(instance) |
|
779 |
for instance in undefined_blocks: |
|
780 |
block_infos = self.GetBlockType(instance.gettypeName(), tuple([self.ConnectionTypes.get(variable.connectionPointIn, "ANY") for variable in instance.inputVariables.getvariable() if variable.getformalParameter() != "EN"])) |
|
781 |
if block_infos is not None: |
|
782 |
self.ComputeBlockInputTypes(instance, block_infos, body) |
|
783 |
else: |
|
784 |
raise PLCGenException, _("No informations found for \"%s\" block")%(instance.gettypeName()) |
|
822
050045c32d98
Fix bug in PLCGenerator connection types not computed for SFC actions and transitions body
laurent
parents:
814
diff
changeset
|
785 |
if body_type == "SFC": |
050045c32d98
Fix bug in PLCGenerator connection types not computed for SFC actions and transitions body
laurent
parents:
814
diff
changeset
|
786 |
previous_tagname = self.TagName |
050045c32d98
Fix bug in PLCGenerator connection types not computed for SFC actions and transitions body
laurent
parents:
814
diff
changeset
|
787 |
for action in pou.getactionList(): |
050045c32d98
Fix bug in PLCGenerator connection types not computed for SFC actions and transitions body
laurent
parents:
814
diff
changeset
|
788 |
self.TagName = self.ParentGenerator.Controler.ComputePouActionName(self.Name, action.getname()) |
050045c32d98
Fix bug in PLCGenerator connection types not computed for SFC actions and transitions body
laurent
parents:
814
diff
changeset
|
789 |
self.ComputeConnectionTypes(action) |
050045c32d98
Fix bug in PLCGenerator connection types not computed for SFC actions and transitions body
laurent
parents:
814
diff
changeset
|
790 |
for transition in pou.gettransitionList(): |
050045c32d98
Fix bug in PLCGenerator connection types not computed for SFC actions and transitions body
laurent
parents:
814
diff
changeset
|
791 |
self.TagName = self.ParentGenerator.Controler.ComputePouTransitionName(self.Name, transition.getname()) |
050045c32d98
Fix bug in PLCGenerator connection types not computed for SFC actions and transitions body
laurent
parents:
814
diff
changeset
|
792 |
self.ComputeConnectionTypes(transition) |
050045c32d98
Fix bug in PLCGenerator connection types not computed for SFC actions and transitions body
laurent
parents:
814
diff
changeset
|
793 |
self.TagName = previous_tagname |
814 | 794 |
|
795 |
def ComputeBlockInputTypes(self, instance, block_infos, body): |
|
796 |
undefined = {} |
|
797 |
for variable in instance.outputVariables.getvariable(): |
|
798 |
output_name = variable.getformalParameter() |
|
799 |
if output_name == "ENO": |
|
800 |
for connection in self.ExtractRelatedConnections(variable.connectionPointOut): |
|
801 |
self.ConnectionTypes[connection] = "BOOL" |
|
802 |
else: |
|
803 |
for oname, otype, oqualifier in block_infos["outputs"]: |
|
804 |
if output_name == oname: |
|
805 |
if otype.startswith("ANY"): |
|
806 |
if not undefined.has_key(otype): |
|
807 |
undefined[otype] = [] |
|
808 |
undefined[otype].append(variable.connectionPointOut) |
|
809 |
elif not self.ConnectionTypes.has_key(variable.connectionPointOut): |
|
810 |
for connection in self.ExtractRelatedConnections(variable.connectionPointOut): |
|
811 |
self.ConnectionTypes[connection] = otype |
|
812 |
for variable in instance.inputVariables.getvariable(): |
|
813 |
input_name = variable.getformalParameter() |
|
814 |
if input_name == "EN": |
|
815 |
for connection in self.ExtractRelatedConnections(variable.connectionPointIn): |
|
816 |
self.ConnectionTypes[connection] = "BOOL" |
|
817 |
else: |
|
818 |
for iname, itype, iqualifier in block_infos["inputs"]: |
|
819 |
if input_name == iname: |
|
820 |
connected = self.GetConnectedConnector(variable.connectionPointIn, body) |
|
821 |
if itype.startswith("ANY"): |
|
822 |
if not undefined.has_key(itype): |
|
823 |
undefined[itype] = [] |
|
824 |
undefined[itype].append(variable.connectionPointIn) |
|
825 |
if connected: |
|
826 |
undefined[itype].append(connected) |
|
827 |
else: |
|
828 |
self.ConnectionTypes[variable.connectionPointIn] = itype |
|
829 |
if connected and not self.ConnectionTypes.has_key(connected): |
|
830 |
for connection in self.ExtractRelatedConnections(connected): |
|
831 |
self.ConnectionTypes[connection] = itype |
|
832 |
for var_type, connections in undefined.items(): |
|
833 |
related = [] |
|
834 |
for connection in connections: |
|
854
c10f2092c43a
Fixing bug in PLCGenerator with user defined functions and standard overloaded function
Laurent Bessard
parents:
822
diff
changeset
|
835 |
connection_type = self.ConnectionTypes.get(connection) |
c10f2092c43a
Fixing bug in PLCGenerator with user defined functions and standard overloaded function
Laurent Bessard
parents:
822
diff
changeset
|
836 |
if connection_type and not connection_type.startswith("ANY"): |
c10f2092c43a
Fixing bug in PLCGenerator with user defined functions and standard overloaded function
Laurent Bessard
parents:
822
diff
changeset
|
837 |
var_type = connection_type |
814 | 838 |
else: |
839 |
related.extend(self.ExtractRelatedConnections(connection)) |
|
840 |
if var_type.startswith("ANY") and len(related) > 0: |
|
841 |
self.RelatedConnections.append(related) |
|
842 |
else: |
|
843 |
for connection in related: |
|
844 |
self.ConnectionTypes[connection] = var_type |
|
845 |
||
846 |
def ComputeProgram(self, pou): |
|
847 |
body = pou.getbody() |
|
848 |
if isinstance(body, ListType): |
|
849 |
body = body[0] |
|
850 |
body_content = body.getcontent() |
|
851 |
body_type = body_content["name"] |
|
852 |
if body_type in ["IL","ST"]: |
|
853 |
text = body_content["value"].gettext() |
|
854 |
self.ParentGenerator.GeneratePouProgramInText(text.upper()) |
|
855 |
self.Program = [(ReIndentText(text, len(self.CurrentIndent)), |
|
856 |
(self.TagName, "body", len(self.CurrentIndent)))] |
|
857 |
elif body_type == "SFC": |
|
858 |
self.IndentRight() |
|
859 |
for instance in body.getcontentInstances(): |
|
860 |
if isinstance(instance, plcopen.sfcObjects_step): |
|
861 |
self.GenerateSFCStep(instance, pou) |
|
862 |
elif isinstance(instance, plcopen.commonObjects_actionBlock): |
|
863 |
self.GenerateSFCStepActions(instance, pou) |
|
864 |
elif isinstance(instance, plcopen.sfcObjects_transition): |
|
865 |
self.GenerateSFCTransition(instance, pou) |
|
866 |
elif isinstance(instance, plcopen.sfcObjects_jumpStep): |
|
867 |
self.GenerateSFCJump(instance, pou) |
|
868 |
if len(self.InitialSteps) > 0 and len(self.SFCComputedBlocks) > 0: |
|
869 |
action_name = "COMPUTE_FUNCTION_BLOCKS" |
|
870 |
action_infos = {"qualifier" : "S", "content" : action_name} |
|
871 |
self.SFCNetworks["Steps"][self.InitialSteps[0]]["actions"].append(action_infos) |
|
872 |
self.SFCNetworks["Actions"][action_name] = (self.SFCComputedBlocks, ()) |
|
873 |
self.Program = [] |
|
874 |
self.IndentLeft() |
|
875 |
for initialstep in self.InitialSteps: |
|
876 |
self.ComputeSFCStep(initialstep) |
|
877 |
else: |
|
878 |
otherInstances = {"outVariables&coils" : [], "blocks" : [], "connectors" : []} |
|
879 |
orderedInstances = [] |
|
880 |
for instance in body.getcontentInstances(): |
|
881 |
if isinstance(instance, (plcopen.fbdObjects_outVariable, plcopen.fbdObjects_inOutVariable, plcopen.fbdObjects_block)): |
|
882 |
executionOrderId = instance.getexecutionOrderId() |
|
883 |
if executionOrderId > 0: |
|
884 |
orderedInstances.append((executionOrderId, instance)) |
|
885 |
elif isinstance(instance, (plcopen.fbdObjects_outVariable, plcopen.fbdObjects_inOutVariable)): |
|
886 |
otherInstances["outVariables&coils"].append(instance) |
|
887 |
elif isinstance(instance, plcopen.fbdObjects_block): |
|
888 |
otherInstances["blocks"].append(instance) |
|
889 |
elif isinstance(instance, plcopen.commonObjects_connector): |
|
890 |
otherInstances["connectors"].append(instance) |
|
891 |
elif isinstance(instance, plcopen.ldObjects_coil): |
|
892 |
otherInstances["outVariables&coils"].append(instance) |
|
893 |
orderedInstances.sort() |
|
894 |
otherInstances["outVariables&coils"].sort(SortInstances) |
|
895 |
otherInstances["blocks"].sort(SortInstances) |
|
896 |
instances = [instance for (executionOrderId, instance) in orderedInstances] |
|
1048
b450202605ab
Fixed bug in program elements computation order in PLCGenerator
Laurent Bessard
parents:
1032
diff
changeset
|
897 |
instances.extend(otherInstances["outVariables&coils"] + otherInstances["blocks"] + otherInstances["connectors"]) |
814 | 898 |
for instance in instances: |
899 |
if isinstance(instance, (plcopen.fbdObjects_outVariable, plcopen.fbdObjects_inOutVariable)): |
|
900 |
connections = instance.connectionPointIn.getconnections() |
|
901 |
if connections is not None: |
|
902 |
expression = self.ComputeExpression(body, connections) |
|
903 |
self.Program += [(self.CurrentIndent, ()), |
|
904 |
(instance.getexpression(), (self.TagName, "io_variable", instance.getlocalId(), "expression")), |
|
905 |
(" := ", ())] |
|
906 |
self.Program += expression |
|
907 |
self.Program += [(";\n", ())] |
|
908 |
elif isinstance(instance, plcopen.fbdObjects_block): |
|
909 |
block_type = instance.gettypeName() |
|
910 |
self.ParentGenerator.GeneratePouProgram(block_type) |
|
911 |
block_infos = self.GetBlockType(block_type, tuple([self.ConnectionTypes.get(variable.connectionPointIn, "ANY") for variable in instance.inputVariables.getvariable() if variable.getformalParameter() != "EN"])) |
|
912 |
if block_infos is None: |
|
913 |
block_infos = self.GetBlockType(block_type) |
|
914 |
if block_infos is None: |
|
915 |
raise PLCGenException, _("Undefined block type \"%s\" in \"%s\" POU")%(block_type, self.Name) |
|
1134
1c7a4ad86aa1
Fixed PLC code generator when interface of an already used POU has changed
Laurent Bessard
parents:
1048
diff
changeset
|
916 |
try: |
1c7a4ad86aa1
Fixed PLC code generator when interface of an already used POU has changed
Laurent Bessard
parents:
1048
diff
changeset
|
917 |
block_infos["generate"](self, instance, block_infos, body, None) |
1c7a4ad86aa1
Fixed PLC code generator when interface of an already used POU has changed
Laurent Bessard
parents:
1048
diff
changeset
|
918 |
except ValueError, e: |
1c7a4ad86aa1
Fixed PLC code generator when interface of an already used POU has changed
Laurent Bessard
parents:
1048
diff
changeset
|
919 |
raise PLCGenException, e.message |
814 | 920 |
elif isinstance(instance, plcopen.commonObjects_connector): |
921 |
connector = instance.getname() |
|
922 |
if self.ComputedConnectors.get(connector, None): |
|
923 |
continue |
|
924 |
self.ComputedConnectors[connector] = self.ComputeExpression(body, instance.connectionPointIn.getconnections()) |
|
925 |
elif isinstance(instance, plcopen.ldObjects_coil): |
|
926 |
connections = instance.connectionPointIn.getconnections() |
|
927 |
if connections is not None: |
|
928 |
coil_info = (self.TagName, "coil", instance.getlocalId()) |
|
929 |
expression = self.ExtractModifier(instance, self.ComputeExpression(body, connections), coil_info) |
|
930 |
self.Program += [(self.CurrentIndent, ())] |
|
931 |
self.Program += [(instance.getvariable(), coil_info + ("reference",))] |
|
932 |
self.Program += [(" := ", ())] + expression + [(";\n", ())] |
|
933 |
||
934 |
def FactorizePaths(self, paths): |
|
935 |
same_paths = {} |
|
936 |
uncomputed_index = range(len(paths)) |
|
937 |
factorized_paths = [] |
|
938 |
for num, path in enumerate(paths): |
|
939 |
if type(path) == ListType: |
|
940 |
if len(path) > 1: |
|
941 |
str_path = str(path[-1:]) |
|
942 |
same_paths.setdefault(str_path, []) |
|
943 |
same_paths[str_path].append((path[:-1], num)) |
|
944 |
else: |
|
945 |
factorized_paths.append(path) |
|
946 |
uncomputed_index.remove(num) |
|
947 |
for same_path, elements in same_paths.items(): |
|
948 |
if len(elements) > 1: |
|
949 |
elements_paths = self.FactorizePaths([path for path, num in elements]) |
|
950 |
if len(elements_paths) > 1: |
|
951 |
factorized_paths.append([tuple(elements_paths)] + eval(same_path)) |
|
952 |
else: |
|
953 |
factorized_paths.append(elements_paths + eval(same_path)) |
|
954 |
for path, num in elements: |
|
955 |
uncomputed_index.remove(num) |
|
956 |
for num in uncomputed_index: |
|
957 |
factorized_paths.append(paths[num]) |
|
958 |
factorized_paths.sort() |
|
959 |
return factorized_paths |
|
960 |
||
961 |
def GeneratePaths(self, connections, body, order = False, to_inout = False): |
|
962 |
paths = [] |
|
963 |
for connection in connections: |
|
964 |
localId = connection.getrefLocalId() |
|
965 |
next = body.getcontentInstance(localId) |
|
966 |
if isinstance(next, plcopen.ldObjects_leftPowerRail): |
|
967 |
paths.append(None) |
|
968 |
elif isinstance(next, (plcopen.fbdObjects_inVariable, plcopen.fbdObjects_inOutVariable)): |
|
969 |
paths.append(str([(next.getexpression(), (self.TagName, "io_variable", localId, "expression"))])) |
|
970 |
elif isinstance(next, plcopen.fbdObjects_block): |
|
971 |
block_type = next.gettypeName() |
|
972 |
self.ParentGenerator.GeneratePouProgram(block_type) |
|
973 |
block_infos = self.GetBlockType(block_type, tuple([self.ConnectionTypes.get(variable.connectionPointIn, "ANY") for variable in next.inputVariables.getvariable() if variable.getformalParameter() != "EN"])) |
|
974 |
if block_infos is None: |
|
975 |
block_infos = self.GetBlockType(block_type) |
|
976 |
if block_infos is None: |
|
977 |
raise PLCGenException, _("Undefined block type \"%s\" in \"%s\" POU")%(block_type, self.Name) |
|
1134
1c7a4ad86aa1
Fixed PLC code generator when interface of an already used POU has changed
Laurent Bessard
parents:
1048
diff
changeset
|
978 |
try: |
1c7a4ad86aa1
Fixed PLC code generator when interface of an already used POU has changed
Laurent Bessard
parents:
1048
diff
changeset
|
979 |
paths.append(str(block_infos["generate"](self, next, block_infos, body, connection, order, to_inout))) |
1c7a4ad86aa1
Fixed PLC code generator when interface of an already used POU has changed
Laurent Bessard
parents:
1048
diff
changeset
|
980 |
except ValueError, e: |
1c7a4ad86aa1
Fixed PLC code generator when interface of an already used POU has changed
Laurent Bessard
parents:
1048
diff
changeset
|
981 |
raise PLCGenException, e.message |
814 | 982 |
elif isinstance(next, plcopen.commonObjects_continuation): |
983 |
name = next.getname() |
|
984 |
computed_value = self.ComputedConnectors.get(name, None) |
|
985 |
if computed_value != None: |
|
986 |
paths.append(str(computed_value)) |
|
987 |
else: |
|
988 |
connector = None |
|
989 |
for instance in body.getcontentInstances(): |
|
990 |
if isinstance(instance, plcopen.commonObjects_connector) and instance.getname() == name: |
|
991 |
if connector is not None: |
|
992 |
raise PLCGenException, _("More than one connector found corresponding to \"%s\" continuation in \"%s\" POU")%(name, self.Name) |
|
993 |
connector = instance |
|
994 |
if connector is not None: |
|
995 |
connections = connector.connectionPointIn.getconnections() |
|
996 |
if connections is not None: |
|
997 |
expression = self.ComputeExpression(body, connections, order) |
|
998 |
self.ComputedConnectors[name] = expression |
|
999 |
paths.append(str(expression)) |
|
1000 |
else: |
|
1001 |
raise PLCGenException, _("No connector found corresponding to \"%s\" continuation in \"%s\" POU")%(name, self.Name) |
|
1002 |
elif isinstance(next, plcopen.ldObjects_contact): |
|
1003 |
contact_info = (self.TagName, "contact", next.getlocalId()) |
|
1004 |
variable = str(self.ExtractModifier(next, [(next.getvariable(), contact_info + ("reference",))], contact_info)) |
|
1005 |
result = self.GeneratePaths(next.connectionPointIn.getconnections(), body, order) |
|
1006 |
if len(result) > 1: |
|
1007 |
factorized_paths = self.FactorizePaths(result) |
|
1008 |
if len(factorized_paths) > 1: |
|
1009 |
paths.append([variable, tuple(factorized_paths)]) |
|
1010 |
else: |
|
1011 |
paths.append([variable] + factorized_paths) |
|
1012 |
elif type(result[0]) == ListType: |
|
1013 |
paths.append([variable] + result[0]) |
|
1014 |
elif result[0] is not None: |
|
1015 |
paths.append([variable, result[0]]) |
|
1016 |
else: |
|
1017 |
paths.append(variable) |
|
1018 |
elif isinstance(next, plcopen.ldObjects_coil): |
|
1019 |
paths.append(str(self.GeneratePaths(next.connectionPointIn.getconnections(), body, order))) |
|
1020 |
return paths |
|
1021 |
||
1022 |
def ComputePaths(self, paths, first = False): |
|
1023 |
if type(paths) == TupleType: |
|
1024 |
if None in paths: |
|
1025 |
return [("TRUE", ())] |
|
1026 |
else: |
|
1027 |
vars = [self.ComputePaths(path) for path in paths] |
|
1028 |
if first: |
|
1029 |
return JoinList([(" OR ", ())], vars) |
|
1030 |
else: |
|
1031 |
return [("(", ())] + JoinList([(" OR ", ())], vars) + [(")", ())] |
|
1032 |
elif type(paths) == ListType: |
|
1033 |
vars = [self.ComputePaths(path) for path in paths] |
|
1034 |
return JoinList([(" AND ", ())], vars) |
|
1035 |
elif paths is None: |
|
1036 |
return [("TRUE", ())] |
|
1037 |
else: |
|
1038 |
return eval(paths) |
|
1039 |
||
1040 |
def ComputeExpression(self, body, connections, order = False, to_inout = False): |
|
1041 |
paths = self.GeneratePaths(connections, body, order, to_inout) |
|
1042 |
if len(paths) > 1: |
|
1043 |
factorized_paths = self.FactorizePaths(paths) |
|
1044 |
if len(factorized_paths) > 1: |
|
1045 |
paths = tuple(factorized_paths) |
|
1046 |
else: |
|
1047 |
paths = factorized_paths[0] |
|
1048 |
else: |
|
1049 |
paths = paths[0] |
|
1050 |
return self.ComputePaths(paths, True) |
|
1051 |
||
1052 |
def ExtractModifier(self, variable, expression, var_info): |
|
1053 |
if variable.getnegated(): |
|
1054 |
return [("NOT(", var_info + ("negated",))] + expression + [(")", ())] |
|
1055 |
else: |
|
1056 |
storage = variable.getstorage() |
|
1057 |
if storage in ["set", "reset"]: |
|
1058 |
self.Program += [(self.CurrentIndent + "IF ", var_info + (storage,))] + expression |
|
1059 |
self.Program += [(" THEN\n ", ())] |
|
1060 |
if storage == "set": |
|
1061 |
return [("TRUE; (*set*)\n" + self.CurrentIndent + "END_IF", ())] |
|
1062 |
else: |
|
1063 |
return [("FALSE; (*reset*)\n" + self.CurrentIndent + "END_IF", ())] |
|
1064 |
edge = variable.getedge() |
|
1065 |
if edge == "rising": |
|
1066 |
return self.AddTrigger("R_TRIG", expression, var_info + ("rising",)) |
|
1067 |
elif edge == "falling": |
|
1068 |
return self.AddTrigger("F_TRIG", expression, var_info + ("falling",)) |
|
1069 |
return expression |
|
1070 |
||
1071 |
def AddTrigger(self, edge, expression, var_info): |
|
1072 |
if self.Interface[-1][0] != "VAR" or self.Interface[-1][1] is not None or self.Interface[-1][2]: |
|
1073 |
self.Interface.append(("VAR", None, False, [])) |
|
1074 |
i = 1 |
|
1075 |
name = "%s%d"%(edge, i) |
|
1076 |
while self.IsAlreadyDefined(name): |
|
1077 |
i += 1 |
|
1078 |
name = "%s%d"%(edge, i) |
|
1079 |
self.Interface[-1][3].append((edge, name, None, None)) |
|
1080 |
self.Program += [(self.CurrentIndent, ()), (name, var_info), ("(CLK := ", ())] |
|
1081 |
self.Program += expression |
|
1082 |
self.Program += [(");\n", ())] |
|
1083 |
return [("%s.Q"%name, var_info)] |
|
1084 |
||
1085 |
def ExtractDivergenceInput(self, divergence, pou): |
|
1086 |
connectionPointIn = divergence.getconnectionPointIn() |
|
1087 |
if connectionPointIn: |
|
1088 |
connections = connectionPointIn.getconnections() |
|
1089 |
if connections is not None and len(connections) == 1: |
|
1090 |
instanceLocalId = connections[0].getrefLocalId() |
|
1091 |
body = pou.getbody() |
|
1092 |
if isinstance(body, ListType): |
|
1093 |
body = body[0] |
|
1094 |
return body.getcontentInstance(instanceLocalId) |
|
1095 |
return None |
|
1096 |
||
1097 |
def ExtractConvergenceInputs(self, convergence, pou): |
|
1098 |
instances = [] |
|
1099 |
for connectionPointIn in convergence.getconnectionPointIn(): |
|
1100 |
connections = connectionPointIn.getconnections() |
|
1101 |
if connections is not None and len(connections) == 1: |
|
1102 |
instanceLocalId = connections[0].getrefLocalId() |
|
1103 |
body = pou.getbody() |
|
1104 |
if isinstance(body, ListType): |
|
1105 |
body = body[0] |
|
1106 |
instances.append(body.getcontentInstance(instanceLocalId)) |
|
1107 |
return instances |
|
1108 |
||
1109 |
def GenerateSFCStep(self, step, pou): |
|
1110 |
step_name = step.getname() |
|
1111 |
if step_name not in self.SFCNetworks["Steps"].keys(): |
|
1112 |
if step.getinitialStep(): |
|
1113 |
self.InitialSteps.append(step_name) |
|
1114 |
step_infos = {"id" : step.getlocalId(), |
|
1115 |
"initial" : step.getinitialStep(), |
|
1116 |
"transitions" : [], |
|
1117 |
"actions" : []} |
|
889
ac18acb6917f
Fix bug when using feedback loop in SFC program instead of jump
Laurent Bessard
parents:
883
diff
changeset
|
1118 |
self.SFCNetworks["Steps"][step_name] = step_infos |
814 | 1119 |
if step.connectionPointIn: |
1120 |
instances = [] |
|
1121 |
connections = step.connectionPointIn.getconnections() |
|
1122 |
if connections is not None and len(connections) == 1: |
|
1123 |
instanceLocalId = connections[0].getrefLocalId() |
|
1124 |
body = pou.getbody() |
|
1125 |
if isinstance(body, ListType): |
|
1126 |
body = body[0] |
|
1127 |
instance = body.getcontentInstance(instanceLocalId) |
|
1128 |
if isinstance(instance, plcopen.sfcObjects_transition): |
|
1129 |
instances.append(instance) |
|
1130 |
elif isinstance(instance, plcopen.sfcObjects_selectionConvergence): |
|
1131 |
instances.extend(self.ExtractConvergenceInputs(instance, pou)) |
|
1132 |
elif isinstance(instance, plcopen.sfcObjects_simultaneousDivergence): |
|
1133 |
transition = self.ExtractDivergenceInput(instance, pou) |
|
1134 |
if transition: |
|
1135 |
if isinstance(transition, plcopen.sfcObjects_transition): |
|
1136 |
instances.append(transition) |
|
1137 |
elif isinstance(transition, plcopen.sfcObjects_selectionConvergence): |
|
1138 |
instances.extend(self.ExtractConvergenceInputs(transition, pou)) |
|
1139 |
for instance in instances: |
|
1140 |
self.GenerateSFCTransition(instance, pou) |
|
1141 |
if instance in self.SFCNetworks["Transitions"].keys(): |
|
1142 |
target_info = (self.TagName, "transition", instance.getlocalId(), "to", step_infos["id"]) |
|
1143 |
self.SFCNetworks["Transitions"][instance]["to"].append([(step_name, target_info)]) |
|
1144 |
||
1145 |
def GenerateSFCJump(self, jump, pou): |
|
1146 |
jump_target = jump.gettargetName() |
|
1147 |
if jump.connectionPointIn: |
|
1148 |
instances = [] |
|
1149 |
connections = jump.connectionPointIn.getconnections() |
|
1150 |
if connections is not None and len(connections) == 1: |
|
1151 |
instanceLocalId = connections[0].getrefLocalId() |
|
1152 |
body = pou.getbody() |
|
1153 |
if isinstance(body, ListType): |
|
1154 |
body = body[0] |
|
1155 |
instance = body.getcontentInstance(instanceLocalId) |
|
1156 |
if isinstance(instance, plcopen.sfcObjects_transition): |
|
1157 |
instances.append(instance) |
|
1158 |
elif isinstance(instance, plcopen.sfcObjects_selectionConvergence): |
|
1159 |
instances.extend(self.ExtractConvergenceInputs(instance, pou)) |
|
1160 |
elif isinstance(instance, plcopen.sfcObjects_simultaneousDivergence): |
|
1161 |
transition = self.ExtractDivergenceInput(instance, pou) |
|
1162 |
if transition: |
|
1163 |
if isinstance(transition, plcopen.sfcObjects_transition): |
|
1164 |
instances.append(transition) |
|
1165 |
elif isinstance(transition, plcopen.sfcObjects_selectionConvergence): |
|
1166 |
instances.extend(self.ExtractConvergenceInputs(transition, pou)) |
|
1167 |
for instance in instances: |
|
1168 |
self.GenerateSFCTransition(instance, pou) |
|
1169 |
if instance in self.SFCNetworks["Transitions"].keys(): |
|
1170 |
target_info = (self.TagName, "jump", jump.getlocalId(), "target") |
|
1171 |
self.SFCNetworks["Transitions"][instance]["to"].append([(jump_target, target_info)]) |
|
1172 |
||
1173 |
def GenerateSFCStepActions(self, actionBlock, pou): |
|
1174 |
connections = actionBlock.connectionPointIn.getconnections() |
|
1175 |
if connections is not None and len(connections) == 1: |
|
1176 |
stepLocalId = connections[0].getrefLocalId() |
|
1177 |
body = pou.getbody() |
|
1178 |
if isinstance(body, ListType): |
|
1179 |
body = body[0] |
|
1180 |
step = body.getcontentInstance(stepLocalId) |
|
1181 |
self.GenerateSFCStep(step, pou) |
|
1182 |
step_name = step.getname() |
|
1183 |
if step_name in self.SFCNetworks["Steps"].keys(): |
|
1184 |
actions = actionBlock.getactions() |
|
1185 |
for i, action in enumerate(actions): |
|
1186 |
action_infos = {"id" : actionBlock.getlocalId(), |
|
1187 |
"qualifier" : action["qualifier"], |
|
1188 |
"content" : action["value"], |
|
1189 |
"num" : i} |
|
1190 |
if "duration" in action: |
|
1191 |
action_infos["duration"] = action["duration"] |
|
1192 |
if "indicator" in action: |
|
1193 |
action_infos["indicator"] = action["indicator"] |
|
1194 |
if action["type"] == "reference": |
|
1195 |
self.GenerateSFCAction(action["value"], pou) |
|
1196 |
else: |
|
1197 |
action_name = "%s_INLINE%d"%(step_name.upper(), self.GetActionNumber()) |
|
1198 |
self.SFCNetworks["Actions"][action_name] = ([(self.CurrentIndent, ()), |
|
1199 |
(action["value"], (self.TagName, "action_block", action_infos["id"], "action", i, "inline")), |
|
1200 |
("\n", ())], ()) |
|
1201 |
action_infos["content"] = action_name |
|
1202 |
self.SFCNetworks["Steps"][step_name]["actions"].append(action_infos) |
|
1203 |
||
1204 |
def GenerateSFCAction(self, action_name, pou): |
|
1205 |
if action_name not in self.SFCNetworks["Actions"].keys(): |
|
1206 |
actionContent = pou.getaction(action_name) |
|
1207 |
if actionContent: |
|
1208 |
previous_tagname = self.TagName |
|
1209 |
self.TagName = self.ParentGenerator.Controler.ComputePouActionName(self.Name, action_name) |
|
1210 |
self.ComputeProgram(actionContent) |
|
1211 |
self.SFCNetworks["Actions"][action_name] = (self.Program, (self.TagName, "name")) |
|
1212 |
self.Program = [] |
|
1213 |
self.TagName = previous_tagname |
|
1214 |
||
1215 |
def GenerateSFCTransition(self, transition, pou): |
|
1216 |
if transition not in self.SFCNetworks["Transitions"].keys(): |
|
1217 |
steps = [] |
|
1218 |
connections = transition.connectionPointIn.getconnections() |
|
1219 |
if connections is not None and len(connections) == 1: |
|
1220 |
instanceLocalId = connections[0].getrefLocalId() |
|
1221 |
body = pou.getbody() |
|
1222 |
if isinstance(body, ListType): |
|
1223 |
body = body[0] |
|
1224 |
instance = body.getcontentInstance(instanceLocalId) |
|
1225 |
if isinstance(instance, plcopen.sfcObjects_step): |
|
1226 |
steps.append(instance) |
|
1227 |
elif isinstance(instance, plcopen.sfcObjects_selectionDivergence): |
|
1228 |
step = self.ExtractDivergenceInput(instance, pou) |
|
1229 |
if step: |
|
1230 |
if isinstance(step, plcopen.sfcObjects_step): |
|
1231 |
steps.append(step) |
|
1232 |
elif isinstance(step, plcopen.sfcObjects_simultaneousConvergence): |
|
1233 |
steps.extend(self.ExtractConvergenceInputs(step, pou)) |
|
1234 |
elif isinstance(instance, plcopen.sfcObjects_simultaneousConvergence): |
|
1235 |
steps.extend(self.ExtractConvergenceInputs(instance, pou)) |
|
1236 |
transition_infos = {"id" : transition.getlocalId(), |
|
1237 |
"priority": transition.getpriority(), |
|
1238 |
"from": [], |
|
1239 |
"to" : []} |
|
889
ac18acb6917f
Fix bug when using feedback loop in SFC program instead of jump
Laurent Bessard
parents:
883
diff
changeset
|
1240 |
self.SFCNetworks["Transitions"][transition] = transition_infos |
814 | 1241 |
transitionValues = transition.getconditionContent() |
1242 |
if transitionValues["type"] == "inline": |
|
1243 |
transition_infos["content"] = [("\n%s:= "%self.CurrentIndent, ()), |
|
1244 |
(transitionValues["value"], (self.TagName, "transition", transition.getlocalId(), "inline")), |
|
1245 |
(";\n", ())] |
|
1246 |
elif transitionValues["type"] == "reference": |
|
1247 |
transitionContent = pou.gettransition(transitionValues["value"]) |
|
1248 |
transitionType = transitionContent.getbodyType() |
|
1249 |
transitionBody = transitionContent.getbody() |
|
1250 |
previous_tagname = self.TagName |
|
1251 |
self.TagName = self.ParentGenerator.Controler.ComputePouTransitionName(self.Name, transitionValues["value"]) |
|
1252 |
if transitionType == "IL": |
|
1253 |
transition_infos["content"] = [(":\n", ()), |
|
1254 |
(ReIndentText(transitionBody.gettext(), len(self.CurrentIndent)), (self.TagName, "body", len(self.CurrentIndent)))] |
|
1255 |
elif transitionType == "ST": |
|
1256 |
transition_infos["content"] = [("\n", ()), |
|
1257 |
(ReIndentText(transitionBody.gettext(), len(self.CurrentIndent)), (self.TagName, "body", len(self.CurrentIndent)))] |
|
1258 |
else: |
|
1259 |
for instance in transitionBody.getcontentInstances(): |
|
1260 |
if isinstance(instance, plcopen.fbdObjects_outVariable) and instance.getexpression() == transitionValues["value"]\ |
|
1261 |
or isinstance(instance, plcopen.ldObjects_coil) and instance.getvariable() == transitionValues["value"]: |
|
1262 |
connections = instance.connectionPointIn.getconnections() |
|
1263 |
if connections is not None: |
|
1264 |
expression = self.ComputeExpression(transitionBody, connections) |
|
1265 |
transition_infos["content"] = [("\n%s:= "%self.CurrentIndent, ())] + expression + [(";\n", ())] |
|
1266 |
self.SFCComputedBlocks += self.Program |
|
1267 |
self.Program = [] |
|
1268 |
if not transition_infos.has_key("content"): |
|
1269 |
raise PLCGenException, _("Transition \"%s\" body must contain an output variable or coil referring to its name") % transitionValues["value"] |
|
1270 |
self.TagName = previous_tagname |
|
1271 |
elif transitionValues["type"] == "connection": |
|
1272 |
body = pou.getbody() |
|
1273 |
if isinstance(body, ListType): |
|
1274 |
body = body[0] |
|
1275 |
connections = transition.getconnections() |
|
1276 |
if connections is not None: |
|
1277 |
expression = self.ComputeExpression(body, connections) |
|
1278 |
transition_infos["content"] = [("\n%s:= "%self.CurrentIndent, ())] + expression + [(";\n", ())] |
|
1279 |
self.SFCComputedBlocks += self.Program |
|
1280 |
self.Program = [] |
|
1281 |
for step in steps: |
|
1282 |
self.GenerateSFCStep(step, pou) |
|
1283 |
step_name = step.getname() |
|
1284 |
if step_name in self.SFCNetworks["Steps"].keys(): |
|
1285 |
transition_infos["from"].append([(step_name, (self.TagName, "transition", transition.getlocalId(), "from", step.getlocalId()))]) |
|
1286 |
self.SFCNetworks["Steps"][step_name]["transitions"].append(transition) |
|
1287 |
||
1288 |
def ComputeSFCStep(self, step_name): |
|
1289 |
if step_name in self.SFCNetworks["Steps"].keys(): |
|
1290 |
step_infos = self.SFCNetworks["Steps"].pop(step_name) |
|
1291 |
self.Program += [(self.CurrentIndent, ())] |
|
1292 |
if step_infos["initial"]: |
|
1293 |
self.Program += [("INITIAL_", ())] |
|
1294 |
self.Program += [("STEP ", ()), |
|
1295 |
(step_name, (self.TagName, "step", step_infos["id"], "name")), |
|
1296 |
(":\n", ())] |
|
1297 |
actions = [] |
|
1298 |
self.IndentRight() |
|
1299 |
for action_infos in step_infos["actions"]: |
|
1300 |
if action_infos.get("id", None) is not None: |
|
1301 |
action_info = (self.TagName, "action_block", action_infos["id"], "action", action_infos["num"]) |
|
1302 |
else: |
|
1303 |
action_info = () |
|
1304 |
actions.append(action_infos["content"]) |
|
1305 |
self.Program += [(self.CurrentIndent, ()), |
|
1306 |
(action_infos["content"], action_info + ("reference",)), |
|
1307 |
("(", ()), |
|
1308 |
(action_infos["qualifier"], action_info + ("qualifier",))] |
|
1309 |
if "duration" in action_infos: |
|
1310 |
self.Program += [(", ", ()), |
|
1311 |
(action_infos["duration"], action_info + ("duration",))] |
|
1312 |
if "indicator" in action_infos: |
|
1313 |
self.Program += [(", ", ()), |
|
1314 |
(action_infos["indicator"], action_info + ("indicator",))] |
|
1315 |
self.Program += [(");\n", ())] |
|
1316 |
self.IndentLeft() |
|
1317 |
self.Program += [("%sEND_STEP\n\n"%self.CurrentIndent, ())] |
|
1318 |
for action in actions: |
|
1319 |
self.ComputeSFCAction(action) |
|
1320 |
for transition in step_infos["transitions"]: |
|
1321 |
self.ComputeSFCTransition(transition) |
|
1322 |
||
1323 |
def ComputeSFCAction(self, action_name): |
|
1324 |
if action_name in self.SFCNetworks["Actions"].keys(): |
|
1325 |
action_content, action_info = self.SFCNetworks["Actions"].pop(action_name) |
|
1326 |
self.Program += [("%sACTION "%self.CurrentIndent, ()), |
|
1327 |
(action_name, action_info), |
|
1328 |
(" :\n", ())] |
|
1329 |
self.Program += action_content |
|
1330 |
self.Program += [("%sEND_ACTION\n\n"%self.CurrentIndent, ())] |
|
1331 |
||
1332 |
def ComputeSFCTransition(self, transition): |
|
1333 |
if transition in self.SFCNetworks["Transitions"].keys(): |
|
1334 |
transition_infos = self.SFCNetworks["Transitions"].pop(transition) |
|
1335 |
self.Program += [("%sTRANSITION"%self.CurrentIndent, ())] |
|
1336 |
if transition_infos["priority"] != None: |
|
1337 |
self.Program += [(" (PRIORITY := ", ()), |
|
1338 |
("%d"%transition_infos["priority"], (self.TagName, "transition", transition_infos["id"], "priority")), |
|
1339 |
(")", ())] |
|
1340 |
self.Program += [(" FROM ", ())] |
|
1341 |
if len(transition_infos["from"]) > 1: |
|
1342 |
self.Program += [("(", ())] |
|
1343 |
self.Program += JoinList([(", ", ())], transition_infos["from"]) |
|
1344 |
self.Program += [(")", ())] |
|
1345 |
elif len(transition_infos["from"]) == 1: |
|
1346 |
self.Program += transition_infos["from"][0] |
|
1347 |
else: |
|
1348 |
raise PLCGenException, _("Transition with content \"%s\" not connected to a previous step in \"%s\" POU")%(transition_infos["content"], self.Name) |
|
1349 |
self.Program += [(" TO ", ())] |
|
1350 |
if len(transition_infos["to"]) > 1: |
|
1351 |
self.Program += [("(", ())] |
|
1352 |
self.Program += JoinList([(", ", ())], transition_infos["to"]) |
|
1353 |
self.Program += [(")", ())] |
|
1354 |
elif len(transition_infos["to"]) == 1: |
|
1355 |
self.Program += transition_infos["to"][0] |
|
1356 |
else: |
|
1357 |
raise PLCGenException, _("Transition with content \"%s\" not connected to a next step in \"%s\" POU")%(transition_infos["content"], self.Name) |
|
1358 |
self.Program += transition_infos["content"] |
|
1359 |
self.Program += [("%sEND_TRANSITION\n\n"%self.CurrentIndent, ())] |
|
1360 |
for [(step_name, step_infos)] in transition_infos["to"]: |
|
1361 |
self.ComputeSFCStep(step_name) |
|
1362 |
||
1363 |
def GenerateProgram(self, pou): |
|
1364 |
self.ComputeInterface(pou) |
|
1365 |
self.ComputeConnectionTypes(pou) |
|
1366 |
self.ComputeProgram(pou) |
|
1367 |
||
1368 |
program = [("%s "%self.Type, ()), |
|
1369 |
(self.Name, (self.TagName, "name"))] |
|
1370 |
if self.ReturnType: |
|
1371 |
program += [(" : ", ()), |
|
1372 |
(self.ReturnType, (self.TagName, "return"))] |
|
1373 |
program += [("\n", ())] |
|
1374 |
if len(self.Interface) == 0: |
|
1375 |
raise PLCGenException, _("No variable defined in \"%s\" POU")%self.Name |
|
1376 |
if len(self.Program) == 0 : |
|
1377 |
raise PLCGenException, _("No body defined in \"%s\" POU")%self.Name |
|
1378 |
var_number = 0 |
|
1379 |
for list_type, option, located, variables in self.Interface: |
|
1380 |
variable_type = errorVarTypes.get(list_type, "var_local") |
|
1381 |
program += [(" %s"%list_type, ())] |
|
1382 |
if option is not None: |
|
1383 |
program += [(" %s"%option, (self.TagName, variable_type, (var_number, var_number + len(variables)), option.lower()))] |
|
1384 |
program += [("\n", ())] |
|
1385 |
for var_type, var_name, var_address, var_initial in variables: |
|
1386 |
program += [(" ", ())] |
|
1387 |
if var_name: |
|
1388 |
program += [(var_name, (self.TagName, variable_type, var_number, "name")), |
|
1389 |
(" ", ())] |
|
1390 |
if var_address != None: |
|
1391 |
program += [("AT ", ()), |
|
1392 |
(var_address, (self.TagName, variable_type, var_number, "location")), |
|
1393 |
(" ", ())] |
|
1394 |
program += [(": ", ()), |
|
1395 |
(var_type, (self.TagName, variable_type, var_number, "type"))] |
|
1396 |
if var_initial != None: |
|
1397 |
program += [(" := ", ()), |
|
1398 |
(self.ParentGenerator.ComputeValue(var_initial, var_type), (self.TagName, variable_type, var_number, "initial value"))] |
|
1399 |
program += [(";\n", ())] |
|
1400 |
var_number += 1 |
|
1401 |
program += [(" END_VAR\n", ())] |
|
1402 |
program += [("\n", ())] |
|
1403 |
program += self.Program |
|
1404 |
program += [("END_%s\n\n"%self.Type, ())] |
|
1405 |
return program |
|
1406 |
||
1407 |
def GenerateCurrentProgram(controler, project, errors, warnings): |
|
1408 |
generator = ProgramGenerator(controler, project, errors, warnings) |
|
1409 |
generator.GenerateProgram() |
|
1410 |
return generator.GetGeneratedProgram() |
|
1411 |