author | Laurent Bessard |
Wed, 08 May 2013 23:31:12 +0200 | |
changeset 1101 | 5a0b439cf576 |
parent 1048 | b450202605ab |
child 1134 | 1c7a4ad86aa1 |
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)) |
|
657 |
||
658 |
def ComputeConnectionTypes(self, pou): |
|
659 |
body = pou.getbody() |
|
660 |
if isinstance(body, ListType): |
|
661 |
body = body[0] |
|
662 |
body_content = body.getcontent() |
|
663 |
body_type = body_content["name"] |
|
664 |
if body_type in ["FBD", "LD", "SFC"]: |
|
665 |
undefined_blocks = [] |
|
666 |
for instance in body.getcontentInstances(): |
|
667 |
if isinstance(instance, (plcopen.fbdObjects_inVariable, plcopen.fbdObjects_outVariable, plcopen.fbdObjects_inOutVariable)): |
|
668 |
expression = instance.getexpression() |
|
669 |
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
|
670 |
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
|
671 |
var_type = "BOOL" |
050045c32d98
Fix bug in PLCGenerator connection types not computed for SFC actions and transitions body
laurent
parents:
814
diff
changeset
|
672 |
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
|
673 |
pou.getpouType() == "function" and expression == pou.getname()): |
814 | 674 |
returntype_content = pou.interface.getreturnType().getcontent() |
675 |
if returntype_content["name"] == "derived": |
|
676 |
var_type = returntype_content["value"].getname() |
|
677 |
elif returntype_content["name"] in ["string", "wstring"]: |
|
678 |
var_type = returntype_content["name"].upper() |
|
679 |
else: |
|
680 |
var_type = returntype_content["name"] |
|
681 |
elif var_type is None: |
|
682 |
parts = expression.split("#") |
|
683 |
if len(parts) > 1: |
|
684 |
var_type = parts[0] |
|
685 |
elif expression.startswith("'"): |
|
686 |
var_type = "STRING" |
|
687 |
elif expression.startswith('"'): |
|
688 |
var_type = "WSTRING" |
|
689 |
if var_type is not None: |
|
690 |
if isinstance(instance, (plcopen.fbdObjects_inVariable, plcopen.fbdObjects_inOutVariable)): |
|
691 |
for connection in self.ExtractRelatedConnections(instance.connectionPointOut): |
|
692 |
self.ConnectionTypes[connection] = var_type |
|
693 |
if isinstance(instance, (plcopen.fbdObjects_outVariable, plcopen.fbdObjects_inOutVariable)): |
|
694 |
self.ConnectionTypes[instance.connectionPointIn] = var_type |
|
695 |
connected = self.GetConnectedConnector(instance.connectionPointIn, body) |
|
696 |
if connected and not self.ConnectionTypes.has_key(connected): |
|
697 |
for connection in self.ExtractRelatedConnections(connected): |
|
698 |
self.ConnectionTypes[connection] = var_type |
|
699 |
elif isinstance(instance, (plcopen.ldObjects_contact, plcopen.ldObjects_coil)): |
|
700 |
for connection in self.ExtractRelatedConnections(instance.connectionPointOut): |
|
701 |
self.ConnectionTypes[connection] = "BOOL" |
|
702 |
self.ConnectionTypes[instance.connectionPointIn] = "BOOL" |
|
703 |
connected = self.GetConnectedConnector(instance.connectionPointIn, body) |
|
704 |
if connected and not self.ConnectionTypes.has_key(connected): |
|
705 |
for connection in self.ExtractRelatedConnections(connected): |
|
706 |
self.ConnectionTypes[connection] = "BOOL" |
|
707 |
elif isinstance(instance, plcopen.ldObjects_leftPowerRail): |
|
708 |
for connection in instance.getconnectionPointOut(): |
|
709 |
for related in self.ExtractRelatedConnections(connection): |
|
710 |
self.ConnectionTypes[related] = "BOOL" |
|
711 |
elif isinstance(instance, plcopen.ldObjects_rightPowerRail): |
|
712 |
for connection in instance.getconnectionPointIn(): |
|
713 |
self.ConnectionTypes[connection] = "BOOL" |
|
714 |
connected = self.GetConnectedConnector(connection, 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.sfcObjects_transition): |
|
719 |
content = instance.condition.getcontent() |
|
720 |
if content["name"] == "connection" and len(content["value"]) == 1: |
|
721 |
connected = self.GetLinkedConnector(content["value"][0], body) |
|
722 |
if connected and not self.ConnectionTypes.has_key(connected): |
|
723 |
for connection in self.ExtractRelatedConnections(connected): |
|
724 |
self.ConnectionTypes[connection] = "BOOL" |
|
725 |
elif isinstance(instance, plcopen.commonObjects_continuation): |
|
726 |
name = instance.getname() |
|
727 |
connector = None |
|
728 |
var_type = "ANY" |
|
729 |
for element in body.getcontentInstances(): |
|
730 |
if isinstance(element, plcopen.commonObjects_connector) and element.getname() == name: |
|
731 |
if connector is not None: |
|
732 |
raise PLCGenException, _("More than one connector found corresponding to \"%s\" continuation in \"%s\" POU")%(name, self.Name) |
|
733 |
connector = element |
|
734 |
if connector is not None: |
|
735 |
undefined = [instance.connectionPointOut, connector.connectionPointIn] |
|
736 |
connected = self.GetConnectedConnector(connector.connectionPointIn, body) |
|
737 |
if connected: |
|
738 |
undefined.append(connected) |
|
739 |
related = [] |
|
740 |
for connection in undefined: |
|
741 |
if self.ConnectionTypes.has_key(connection): |
|
742 |
var_type = self.ConnectionTypes[connection] |
|
743 |
else: |
|
744 |
related.extend(self.ExtractRelatedConnections(connection)) |
|
745 |
if var_type.startswith("ANY") and len(related) > 0: |
|
746 |
self.RelatedConnections.append(related) |
|
747 |
else: |
|
748 |
for connection in related: |
|
749 |
self.ConnectionTypes[connection] = var_type |
|
750 |
else: |
|
751 |
raise PLCGenException, _("No connector found corresponding to \"%s\" continuation in \"%s\" POU")%(name, self.Name) |
|
752 |
elif isinstance(instance, plcopen.fbdObjects_block): |
|
753 |
block_infos = self.GetBlockType(instance.gettypeName(), "undefined") |
|
754 |
if block_infos is not None: |
|
755 |
self.ComputeBlockInputTypes(instance, block_infos, body) |
|
756 |
else: |
|
757 |
for variable in instance.inputVariables.getvariable(): |
|
758 |
connected = self.GetConnectedConnector(variable.connectionPointIn, body) |
|
759 |
if connected is not None: |
|
760 |
var_type = self.ConnectionTypes.get(connected, None) |
|
761 |
if var_type is not None: |
|
762 |
self.ConnectionTypes[variable.connectionPointIn] = var_type |
|
763 |
else: |
|
764 |
related = self.ExtractRelatedConnections(connected) |
|
765 |
related.append(variable.connectionPointIn) |
|
766 |
self.RelatedConnections.append(related) |
|
767 |
undefined_blocks.append(instance) |
|
768 |
for instance in undefined_blocks: |
|
769 |
block_infos = self.GetBlockType(instance.gettypeName(), tuple([self.ConnectionTypes.get(variable.connectionPointIn, "ANY") for variable in instance.inputVariables.getvariable() if variable.getformalParameter() != "EN"])) |
|
770 |
if block_infos is not None: |
|
771 |
self.ComputeBlockInputTypes(instance, block_infos, body) |
|
772 |
else: |
|
773 |
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
|
774 |
if body_type == "SFC": |
050045c32d98
Fix bug in PLCGenerator connection types not computed for SFC actions and transitions body
laurent
parents:
814
diff
changeset
|
775 |
previous_tagname = self.TagName |
050045c32d98
Fix bug in PLCGenerator connection types not computed for SFC actions and transitions body
laurent
parents:
814
diff
changeset
|
776 |
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
|
777 |
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
|
778 |
self.ComputeConnectionTypes(action) |
050045c32d98
Fix bug in PLCGenerator connection types not computed for SFC actions and transitions body
laurent
parents:
814
diff
changeset
|
779 |
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
|
780 |
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
|
781 |
self.ComputeConnectionTypes(transition) |
050045c32d98
Fix bug in PLCGenerator connection types not computed for SFC actions and transitions body
laurent
parents:
814
diff
changeset
|
782 |
self.TagName = previous_tagname |
814 | 783 |
|
784 |
def ComputeBlockInputTypes(self, instance, block_infos, body): |
|
785 |
undefined = {} |
|
786 |
for variable in instance.outputVariables.getvariable(): |
|
787 |
output_name = variable.getformalParameter() |
|
788 |
if output_name == "ENO": |
|
789 |
for connection in self.ExtractRelatedConnections(variable.connectionPointOut): |
|
790 |
self.ConnectionTypes[connection] = "BOOL" |
|
791 |
else: |
|
792 |
for oname, otype, oqualifier in block_infos["outputs"]: |
|
793 |
if output_name == oname: |
|
794 |
if otype.startswith("ANY"): |
|
795 |
if not undefined.has_key(otype): |
|
796 |
undefined[otype] = [] |
|
797 |
undefined[otype].append(variable.connectionPointOut) |
|
798 |
elif not self.ConnectionTypes.has_key(variable.connectionPointOut): |
|
799 |
for connection in self.ExtractRelatedConnections(variable.connectionPointOut): |
|
800 |
self.ConnectionTypes[connection] = otype |
|
801 |
for variable in instance.inputVariables.getvariable(): |
|
802 |
input_name = variable.getformalParameter() |
|
803 |
if input_name == "EN": |
|
804 |
for connection in self.ExtractRelatedConnections(variable.connectionPointIn): |
|
805 |
self.ConnectionTypes[connection] = "BOOL" |
|
806 |
else: |
|
807 |
for iname, itype, iqualifier in block_infos["inputs"]: |
|
808 |
if input_name == iname: |
|
809 |
connected = self.GetConnectedConnector(variable.connectionPointIn, body) |
|
810 |
if itype.startswith("ANY"): |
|
811 |
if not undefined.has_key(itype): |
|
812 |
undefined[itype] = [] |
|
813 |
undefined[itype].append(variable.connectionPointIn) |
|
814 |
if connected: |
|
815 |
undefined[itype].append(connected) |
|
816 |
else: |
|
817 |
self.ConnectionTypes[variable.connectionPointIn] = itype |
|
818 |
if connected and not self.ConnectionTypes.has_key(connected): |
|
819 |
for connection in self.ExtractRelatedConnections(connected): |
|
820 |
self.ConnectionTypes[connection] = itype |
|
821 |
for var_type, connections in undefined.items(): |
|
822 |
related = [] |
|
823 |
for connection in connections: |
|
854
c10f2092c43a
Fixing bug in PLCGenerator with user defined functions and standard overloaded function
Laurent Bessard
parents:
822
diff
changeset
|
824 |
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
|
825 |
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
|
826 |
var_type = connection_type |
814 | 827 |
else: |
828 |
related.extend(self.ExtractRelatedConnections(connection)) |
|
829 |
if var_type.startswith("ANY") and len(related) > 0: |
|
830 |
self.RelatedConnections.append(related) |
|
831 |
else: |
|
832 |
for connection in related: |
|
833 |
self.ConnectionTypes[connection] = var_type |
|
834 |
||
835 |
def ComputeProgram(self, pou): |
|
836 |
body = pou.getbody() |
|
837 |
if isinstance(body, ListType): |
|
838 |
body = body[0] |
|
839 |
body_content = body.getcontent() |
|
840 |
body_type = body_content["name"] |
|
841 |
if body_type in ["IL","ST"]: |
|
842 |
text = body_content["value"].gettext() |
|
843 |
self.ParentGenerator.GeneratePouProgramInText(text.upper()) |
|
844 |
self.Program = [(ReIndentText(text, len(self.CurrentIndent)), |
|
845 |
(self.TagName, "body", len(self.CurrentIndent)))] |
|
846 |
elif body_type == "SFC": |
|
847 |
self.IndentRight() |
|
848 |
for instance in body.getcontentInstances(): |
|
849 |
if isinstance(instance, plcopen.sfcObjects_step): |
|
850 |
self.GenerateSFCStep(instance, pou) |
|
851 |
elif isinstance(instance, plcopen.commonObjects_actionBlock): |
|
852 |
self.GenerateSFCStepActions(instance, pou) |
|
853 |
elif isinstance(instance, plcopen.sfcObjects_transition): |
|
854 |
self.GenerateSFCTransition(instance, pou) |
|
855 |
elif isinstance(instance, plcopen.sfcObjects_jumpStep): |
|
856 |
self.GenerateSFCJump(instance, pou) |
|
857 |
if len(self.InitialSteps) > 0 and len(self.SFCComputedBlocks) > 0: |
|
858 |
action_name = "COMPUTE_FUNCTION_BLOCKS" |
|
859 |
action_infos = {"qualifier" : "S", "content" : action_name} |
|
860 |
self.SFCNetworks["Steps"][self.InitialSteps[0]]["actions"].append(action_infos) |
|
861 |
self.SFCNetworks["Actions"][action_name] = (self.SFCComputedBlocks, ()) |
|
862 |
self.Program = [] |
|
863 |
self.IndentLeft() |
|
864 |
for initialstep in self.InitialSteps: |
|
865 |
self.ComputeSFCStep(initialstep) |
|
866 |
else: |
|
867 |
otherInstances = {"outVariables&coils" : [], "blocks" : [], "connectors" : []} |
|
868 |
orderedInstances = [] |
|
869 |
for instance in body.getcontentInstances(): |
|
870 |
if isinstance(instance, (plcopen.fbdObjects_outVariable, plcopen.fbdObjects_inOutVariable, plcopen.fbdObjects_block)): |
|
871 |
executionOrderId = instance.getexecutionOrderId() |
|
872 |
if executionOrderId > 0: |
|
873 |
orderedInstances.append((executionOrderId, instance)) |
|
874 |
elif isinstance(instance, (plcopen.fbdObjects_outVariable, plcopen.fbdObjects_inOutVariable)): |
|
875 |
otherInstances["outVariables&coils"].append(instance) |
|
876 |
elif isinstance(instance, plcopen.fbdObjects_block): |
|
877 |
otherInstances["blocks"].append(instance) |
|
878 |
elif isinstance(instance, plcopen.commonObjects_connector): |
|
879 |
otherInstances["connectors"].append(instance) |
|
880 |
elif isinstance(instance, plcopen.ldObjects_coil): |
|
881 |
otherInstances["outVariables&coils"].append(instance) |
|
882 |
orderedInstances.sort() |
|
883 |
otherInstances["outVariables&coils"].sort(SortInstances) |
|
884 |
otherInstances["blocks"].sort(SortInstances) |
|
885 |
instances = [instance for (executionOrderId, instance) in orderedInstances] |
|
1048
b450202605ab
Fixed bug in program elements computation order in PLCGenerator
Laurent Bessard
parents:
1032
diff
changeset
|
886 |
instances.extend(otherInstances["outVariables&coils"] + otherInstances["blocks"] + otherInstances["connectors"]) |
814 | 887 |
for instance in instances: |
888 |
if isinstance(instance, (plcopen.fbdObjects_outVariable, plcopen.fbdObjects_inOutVariable)): |
|
889 |
connections = instance.connectionPointIn.getconnections() |
|
890 |
if connections is not None: |
|
891 |
expression = self.ComputeExpression(body, connections) |
|
892 |
self.Program += [(self.CurrentIndent, ()), |
|
893 |
(instance.getexpression(), (self.TagName, "io_variable", instance.getlocalId(), "expression")), |
|
894 |
(" := ", ())] |
|
895 |
self.Program += expression |
|
896 |
self.Program += [(";\n", ())] |
|
897 |
elif isinstance(instance, plcopen.fbdObjects_block): |
|
898 |
block_type = instance.gettypeName() |
|
899 |
self.ParentGenerator.GeneratePouProgram(block_type) |
|
900 |
block_infos = self.GetBlockType(block_type, tuple([self.ConnectionTypes.get(variable.connectionPointIn, "ANY") for variable in instance.inputVariables.getvariable() if variable.getformalParameter() != "EN"])) |
|
901 |
if block_infos is None: |
|
902 |
block_infos = self.GetBlockType(block_type) |
|
903 |
if block_infos is None: |
|
904 |
raise PLCGenException, _("Undefined block type \"%s\" in \"%s\" POU")%(block_type, self.Name) |
|
905 |
block_infos["generate"](self, instance, block_infos, body, None) |
|
906 |
elif isinstance(instance, plcopen.commonObjects_connector): |
|
907 |
connector = instance.getname() |
|
908 |
if self.ComputedConnectors.get(connector, None): |
|
909 |
continue |
|
910 |
self.ComputedConnectors[connector] = self.ComputeExpression(body, instance.connectionPointIn.getconnections()) |
|
911 |
elif isinstance(instance, plcopen.ldObjects_coil): |
|
912 |
connections = instance.connectionPointIn.getconnections() |
|
913 |
if connections is not None: |
|
914 |
coil_info = (self.TagName, "coil", instance.getlocalId()) |
|
915 |
expression = self.ExtractModifier(instance, self.ComputeExpression(body, connections), coil_info) |
|
916 |
self.Program += [(self.CurrentIndent, ())] |
|
917 |
self.Program += [(instance.getvariable(), coil_info + ("reference",))] |
|
918 |
self.Program += [(" := ", ())] + expression + [(";\n", ())] |
|
919 |
||
920 |
def FactorizePaths(self, paths): |
|
921 |
same_paths = {} |
|
922 |
uncomputed_index = range(len(paths)) |
|
923 |
factorized_paths = [] |
|
924 |
for num, path in enumerate(paths): |
|
925 |
if type(path) == ListType: |
|
926 |
if len(path) > 1: |
|
927 |
str_path = str(path[-1:]) |
|
928 |
same_paths.setdefault(str_path, []) |
|
929 |
same_paths[str_path].append((path[:-1], num)) |
|
930 |
else: |
|
931 |
factorized_paths.append(path) |
|
932 |
uncomputed_index.remove(num) |
|
933 |
for same_path, elements in same_paths.items(): |
|
934 |
if len(elements) > 1: |
|
935 |
elements_paths = self.FactorizePaths([path for path, num in elements]) |
|
936 |
if len(elements_paths) > 1: |
|
937 |
factorized_paths.append([tuple(elements_paths)] + eval(same_path)) |
|
938 |
else: |
|
939 |
factorized_paths.append(elements_paths + eval(same_path)) |
|
940 |
for path, num in elements: |
|
941 |
uncomputed_index.remove(num) |
|
942 |
for num in uncomputed_index: |
|
943 |
factorized_paths.append(paths[num]) |
|
944 |
factorized_paths.sort() |
|
945 |
return factorized_paths |
|
946 |
||
947 |
def GeneratePaths(self, connections, body, order = False, to_inout = False): |
|
948 |
paths = [] |
|
949 |
for connection in connections: |
|
950 |
localId = connection.getrefLocalId() |
|
951 |
next = body.getcontentInstance(localId) |
|
952 |
if isinstance(next, plcopen.ldObjects_leftPowerRail): |
|
953 |
paths.append(None) |
|
954 |
elif isinstance(next, (plcopen.fbdObjects_inVariable, plcopen.fbdObjects_inOutVariable)): |
|
955 |
paths.append(str([(next.getexpression(), (self.TagName, "io_variable", localId, "expression"))])) |
|
956 |
elif isinstance(next, plcopen.fbdObjects_block): |
|
957 |
block_type = next.gettypeName() |
|
958 |
self.ParentGenerator.GeneratePouProgram(block_type) |
|
959 |
block_infos = self.GetBlockType(block_type, tuple([self.ConnectionTypes.get(variable.connectionPointIn, "ANY") for variable in next.inputVariables.getvariable() if variable.getformalParameter() != "EN"])) |
|
960 |
if block_infos is None: |
|
961 |
block_infos = self.GetBlockType(block_type) |
|
962 |
if block_infos is None: |
|
963 |
raise PLCGenException, _("Undefined block type \"%s\" in \"%s\" POU")%(block_type, self.Name) |
|
964 |
paths.append(str(block_infos["generate"](self, next, block_infos, body, connection, order, to_inout))) |
|
965 |
elif isinstance(next, plcopen.commonObjects_continuation): |
|
966 |
name = next.getname() |
|
967 |
computed_value = self.ComputedConnectors.get(name, None) |
|
968 |
if computed_value != None: |
|
969 |
paths.append(str(computed_value)) |
|
970 |
else: |
|
971 |
connector = None |
|
972 |
for instance in body.getcontentInstances(): |
|
973 |
if isinstance(instance, plcopen.commonObjects_connector) and instance.getname() == name: |
|
974 |
if connector is not None: |
|
975 |
raise PLCGenException, _("More than one connector found corresponding to \"%s\" continuation in \"%s\" POU")%(name, self.Name) |
|
976 |
connector = instance |
|
977 |
if connector is not None: |
|
978 |
connections = connector.connectionPointIn.getconnections() |
|
979 |
if connections is not None: |
|
980 |
expression = self.ComputeExpression(body, connections, order) |
|
981 |
self.ComputedConnectors[name] = expression |
|
982 |
paths.append(str(expression)) |
|
983 |
else: |
|
984 |
raise PLCGenException, _("No connector found corresponding to \"%s\" continuation in \"%s\" POU")%(name, self.Name) |
|
985 |
elif isinstance(next, plcopen.ldObjects_contact): |
|
986 |
contact_info = (self.TagName, "contact", next.getlocalId()) |
|
987 |
variable = str(self.ExtractModifier(next, [(next.getvariable(), contact_info + ("reference",))], contact_info)) |
|
988 |
result = self.GeneratePaths(next.connectionPointIn.getconnections(), body, order) |
|
989 |
if len(result) > 1: |
|
990 |
factorized_paths = self.FactorizePaths(result) |
|
991 |
if len(factorized_paths) > 1: |
|
992 |
paths.append([variable, tuple(factorized_paths)]) |
|
993 |
else: |
|
994 |
paths.append([variable] + factorized_paths) |
|
995 |
elif type(result[0]) == ListType: |
|
996 |
paths.append([variable] + result[0]) |
|
997 |
elif result[0] is not None: |
|
998 |
paths.append([variable, result[0]]) |
|
999 |
else: |
|
1000 |
paths.append(variable) |
|
1001 |
elif isinstance(next, plcopen.ldObjects_coil): |
|
1002 |
paths.append(str(self.GeneratePaths(next.connectionPointIn.getconnections(), body, order))) |
|
1003 |
return paths |
|
1004 |
||
1005 |
def ComputePaths(self, paths, first = False): |
|
1006 |
if type(paths) == TupleType: |
|
1007 |
if None in paths: |
|
1008 |
return [("TRUE", ())] |
|
1009 |
else: |
|
1010 |
vars = [self.ComputePaths(path) for path in paths] |
|
1011 |
if first: |
|
1012 |
return JoinList([(" OR ", ())], vars) |
|
1013 |
else: |
|
1014 |
return [("(", ())] + JoinList([(" OR ", ())], vars) + [(")", ())] |
|
1015 |
elif type(paths) == ListType: |
|
1016 |
vars = [self.ComputePaths(path) for path in paths] |
|
1017 |
return JoinList([(" AND ", ())], vars) |
|
1018 |
elif paths is None: |
|
1019 |
return [("TRUE", ())] |
|
1020 |
else: |
|
1021 |
return eval(paths) |
|
1022 |
||
1023 |
def ComputeExpression(self, body, connections, order = False, to_inout = False): |
|
1024 |
paths = self.GeneratePaths(connections, body, order, to_inout) |
|
1025 |
if len(paths) > 1: |
|
1026 |
factorized_paths = self.FactorizePaths(paths) |
|
1027 |
if len(factorized_paths) > 1: |
|
1028 |
paths = tuple(factorized_paths) |
|
1029 |
else: |
|
1030 |
paths = factorized_paths[0] |
|
1031 |
else: |
|
1032 |
paths = paths[0] |
|
1033 |
return self.ComputePaths(paths, True) |
|
1034 |
||
1035 |
def ExtractModifier(self, variable, expression, var_info): |
|
1036 |
if variable.getnegated(): |
|
1037 |
return [("NOT(", var_info + ("negated",))] + expression + [(")", ())] |
|
1038 |
else: |
|
1039 |
storage = variable.getstorage() |
|
1040 |
if storage in ["set", "reset"]: |
|
1041 |
self.Program += [(self.CurrentIndent + "IF ", var_info + (storage,))] + expression |
|
1042 |
self.Program += [(" THEN\n ", ())] |
|
1043 |
if storage == "set": |
|
1044 |
return [("TRUE; (*set*)\n" + self.CurrentIndent + "END_IF", ())] |
|
1045 |
else: |
|
1046 |
return [("FALSE; (*reset*)\n" + self.CurrentIndent + "END_IF", ())] |
|
1047 |
edge = variable.getedge() |
|
1048 |
if edge == "rising": |
|
1049 |
return self.AddTrigger("R_TRIG", expression, var_info + ("rising",)) |
|
1050 |
elif edge == "falling": |
|
1051 |
return self.AddTrigger("F_TRIG", expression, var_info + ("falling",)) |
|
1052 |
return expression |
|
1053 |
||
1054 |
def AddTrigger(self, edge, expression, var_info): |
|
1055 |
if self.Interface[-1][0] != "VAR" or self.Interface[-1][1] is not None or self.Interface[-1][2]: |
|
1056 |
self.Interface.append(("VAR", None, False, [])) |
|
1057 |
i = 1 |
|
1058 |
name = "%s%d"%(edge, i) |
|
1059 |
while self.IsAlreadyDefined(name): |
|
1060 |
i += 1 |
|
1061 |
name = "%s%d"%(edge, i) |
|
1062 |
self.Interface[-1][3].append((edge, name, None, None)) |
|
1063 |
self.Program += [(self.CurrentIndent, ()), (name, var_info), ("(CLK := ", ())] |
|
1064 |
self.Program += expression |
|
1065 |
self.Program += [(");\n", ())] |
|
1066 |
return [("%s.Q"%name, var_info)] |
|
1067 |
||
1068 |
def ExtractDivergenceInput(self, divergence, pou): |
|
1069 |
connectionPointIn = divergence.getconnectionPointIn() |
|
1070 |
if connectionPointIn: |
|
1071 |
connections = connectionPointIn.getconnections() |
|
1072 |
if connections is not None and len(connections) == 1: |
|
1073 |
instanceLocalId = connections[0].getrefLocalId() |
|
1074 |
body = pou.getbody() |
|
1075 |
if isinstance(body, ListType): |
|
1076 |
body = body[0] |
|
1077 |
return body.getcontentInstance(instanceLocalId) |
|
1078 |
return None |
|
1079 |
||
1080 |
def ExtractConvergenceInputs(self, convergence, pou): |
|
1081 |
instances = [] |
|
1082 |
for connectionPointIn in convergence.getconnectionPointIn(): |
|
1083 |
connections = connectionPointIn.getconnections() |
|
1084 |
if connections is not None and len(connections) == 1: |
|
1085 |
instanceLocalId = connections[0].getrefLocalId() |
|
1086 |
body = pou.getbody() |
|
1087 |
if isinstance(body, ListType): |
|
1088 |
body = body[0] |
|
1089 |
instances.append(body.getcontentInstance(instanceLocalId)) |
|
1090 |
return instances |
|
1091 |
||
1092 |
def GenerateSFCStep(self, step, pou): |
|
1093 |
step_name = step.getname() |
|
1094 |
if step_name not in self.SFCNetworks["Steps"].keys(): |
|
1095 |
if step.getinitialStep(): |
|
1096 |
self.InitialSteps.append(step_name) |
|
1097 |
step_infos = {"id" : step.getlocalId(), |
|
1098 |
"initial" : step.getinitialStep(), |
|
1099 |
"transitions" : [], |
|
1100 |
"actions" : []} |
|
889
ac18acb6917f
Fix bug when using feedback loop in SFC program instead of jump
Laurent Bessard
parents:
883
diff
changeset
|
1101 |
self.SFCNetworks["Steps"][step_name] = step_infos |
814 | 1102 |
if step.connectionPointIn: |
1103 |
instances = [] |
|
1104 |
connections = step.connectionPointIn.getconnections() |
|
1105 |
if connections is not None and len(connections) == 1: |
|
1106 |
instanceLocalId = connections[0].getrefLocalId() |
|
1107 |
body = pou.getbody() |
|
1108 |
if isinstance(body, ListType): |
|
1109 |
body = body[0] |
|
1110 |
instance = body.getcontentInstance(instanceLocalId) |
|
1111 |
if isinstance(instance, plcopen.sfcObjects_transition): |
|
1112 |
instances.append(instance) |
|
1113 |
elif isinstance(instance, plcopen.sfcObjects_selectionConvergence): |
|
1114 |
instances.extend(self.ExtractConvergenceInputs(instance, pou)) |
|
1115 |
elif isinstance(instance, plcopen.sfcObjects_simultaneousDivergence): |
|
1116 |
transition = self.ExtractDivergenceInput(instance, pou) |
|
1117 |
if transition: |
|
1118 |
if isinstance(transition, plcopen.sfcObjects_transition): |
|
1119 |
instances.append(transition) |
|
1120 |
elif isinstance(transition, plcopen.sfcObjects_selectionConvergence): |
|
1121 |
instances.extend(self.ExtractConvergenceInputs(transition, pou)) |
|
1122 |
for instance in instances: |
|
1123 |
self.GenerateSFCTransition(instance, pou) |
|
1124 |
if instance in self.SFCNetworks["Transitions"].keys(): |
|
1125 |
target_info = (self.TagName, "transition", instance.getlocalId(), "to", step_infos["id"]) |
|
1126 |
self.SFCNetworks["Transitions"][instance]["to"].append([(step_name, target_info)]) |
|
1127 |
||
1128 |
def GenerateSFCJump(self, jump, pou): |
|
1129 |
jump_target = jump.gettargetName() |
|
1130 |
if jump.connectionPointIn: |
|
1131 |
instances = [] |
|
1132 |
connections = jump.connectionPointIn.getconnections() |
|
1133 |
if connections is not None and len(connections) == 1: |
|
1134 |
instanceLocalId = connections[0].getrefLocalId() |
|
1135 |
body = pou.getbody() |
|
1136 |
if isinstance(body, ListType): |
|
1137 |
body = body[0] |
|
1138 |
instance = body.getcontentInstance(instanceLocalId) |
|
1139 |
if isinstance(instance, plcopen.sfcObjects_transition): |
|
1140 |
instances.append(instance) |
|
1141 |
elif isinstance(instance, plcopen.sfcObjects_selectionConvergence): |
|
1142 |
instances.extend(self.ExtractConvergenceInputs(instance, pou)) |
|
1143 |
elif isinstance(instance, plcopen.sfcObjects_simultaneousDivergence): |
|
1144 |
transition = self.ExtractDivergenceInput(instance, pou) |
|
1145 |
if transition: |
|
1146 |
if isinstance(transition, plcopen.sfcObjects_transition): |
|
1147 |
instances.append(transition) |
|
1148 |
elif isinstance(transition, plcopen.sfcObjects_selectionConvergence): |
|
1149 |
instances.extend(self.ExtractConvergenceInputs(transition, pou)) |
|
1150 |
for instance in instances: |
|
1151 |
self.GenerateSFCTransition(instance, pou) |
|
1152 |
if instance in self.SFCNetworks["Transitions"].keys(): |
|
1153 |
target_info = (self.TagName, "jump", jump.getlocalId(), "target") |
|
1154 |
self.SFCNetworks["Transitions"][instance]["to"].append([(jump_target, target_info)]) |
|
1155 |
||
1156 |
def GenerateSFCStepActions(self, actionBlock, pou): |
|
1157 |
connections = actionBlock.connectionPointIn.getconnections() |
|
1158 |
if connections is not None and len(connections) == 1: |
|
1159 |
stepLocalId = connections[0].getrefLocalId() |
|
1160 |
body = pou.getbody() |
|
1161 |
if isinstance(body, ListType): |
|
1162 |
body = body[0] |
|
1163 |
step = body.getcontentInstance(stepLocalId) |
|
1164 |
self.GenerateSFCStep(step, pou) |
|
1165 |
step_name = step.getname() |
|
1166 |
if step_name in self.SFCNetworks["Steps"].keys(): |
|
1167 |
actions = actionBlock.getactions() |
|
1168 |
for i, action in enumerate(actions): |
|
1169 |
action_infos = {"id" : actionBlock.getlocalId(), |
|
1170 |
"qualifier" : action["qualifier"], |
|
1171 |
"content" : action["value"], |
|
1172 |
"num" : i} |
|
1173 |
if "duration" in action: |
|
1174 |
action_infos["duration"] = action["duration"] |
|
1175 |
if "indicator" in action: |
|
1176 |
action_infos["indicator"] = action["indicator"] |
|
1177 |
if action["type"] == "reference": |
|
1178 |
self.GenerateSFCAction(action["value"], pou) |
|
1179 |
else: |
|
1180 |
action_name = "%s_INLINE%d"%(step_name.upper(), self.GetActionNumber()) |
|
1181 |
self.SFCNetworks["Actions"][action_name] = ([(self.CurrentIndent, ()), |
|
1182 |
(action["value"], (self.TagName, "action_block", action_infos["id"], "action", i, "inline")), |
|
1183 |
("\n", ())], ()) |
|
1184 |
action_infos["content"] = action_name |
|
1185 |
self.SFCNetworks["Steps"][step_name]["actions"].append(action_infos) |
|
1186 |
||
1187 |
def GenerateSFCAction(self, action_name, pou): |
|
1188 |
if action_name not in self.SFCNetworks["Actions"].keys(): |
|
1189 |
actionContent = pou.getaction(action_name) |
|
1190 |
if actionContent: |
|
1191 |
previous_tagname = self.TagName |
|
1192 |
self.TagName = self.ParentGenerator.Controler.ComputePouActionName(self.Name, action_name) |
|
1193 |
self.ComputeProgram(actionContent) |
|
1194 |
self.SFCNetworks["Actions"][action_name] = (self.Program, (self.TagName, "name")) |
|
1195 |
self.Program = [] |
|
1196 |
self.TagName = previous_tagname |
|
1197 |
||
1198 |
def GenerateSFCTransition(self, transition, pou): |
|
1199 |
if transition not in self.SFCNetworks["Transitions"].keys(): |
|
1200 |
steps = [] |
|
1201 |
connections = transition.connectionPointIn.getconnections() |
|
1202 |
if connections is not None and len(connections) == 1: |
|
1203 |
instanceLocalId = connections[0].getrefLocalId() |
|
1204 |
body = pou.getbody() |
|
1205 |
if isinstance(body, ListType): |
|
1206 |
body = body[0] |
|
1207 |
instance = body.getcontentInstance(instanceLocalId) |
|
1208 |
if isinstance(instance, plcopen.sfcObjects_step): |
|
1209 |
steps.append(instance) |
|
1210 |
elif isinstance(instance, plcopen.sfcObjects_selectionDivergence): |
|
1211 |
step = self.ExtractDivergenceInput(instance, pou) |
|
1212 |
if step: |
|
1213 |
if isinstance(step, plcopen.sfcObjects_step): |
|
1214 |
steps.append(step) |
|
1215 |
elif isinstance(step, plcopen.sfcObjects_simultaneousConvergence): |
|
1216 |
steps.extend(self.ExtractConvergenceInputs(step, pou)) |
|
1217 |
elif isinstance(instance, plcopen.sfcObjects_simultaneousConvergence): |
|
1218 |
steps.extend(self.ExtractConvergenceInputs(instance, pou)) |
|
1219 |
transition_infos = {"id" : transition.getlocalId(), |
|
1220 |
"priority": transition.getpriority(), |
|
1221 |
"from": [], |
|
1222 |
"to" : []} |
|
889
ac18acb6917f
Fix bug when using feedback loop in SFC program instead of jump
Laurent Bessard
parents:
883
diff
changeset
|
1223 |
self.SFCNetworks["Transitions"][transition] = transition_infos |
814 | 1224 |
transitionValues = transition.getconditionContent() |
1225 |
if transitionValues["type"] == "inline": |
|
1226 |
transition_infos["content"] = [("\n%s:= "%self.CurrentIndent, ()), |
|
1227 |
(transitionValues["value"], (self.TagName, "transition", transition.getlocalId(), "inline")), |
|
1228 |
(";\n", ())] |
|
1229 |
elif transitionValues["type"] == "reference": |
|
1230 |
transitionContent = pou.gettransition(transitionValues["value"]) |
|
1231 |
transitionType = transitionContent.getbodyType() |
|
1232 |
transitionBody = transitionContent.getbody() |
|
1233 |
previous_tagname = self.TagName |
|
1234 |
self.TagName = self.ParentGenerator.Controler.ComputePouTransitionName(self.Name, transitionValues["value"]) |
|
1235 |
if transitionType == "IL": |
|
1236 |
transition_infos["content"] = [(":\n", ()), |
|
1237 |
(ReIndentText(transitionBody.gettext(), len(self.CurrentIndent)), (self.TagName, "body", len(self.CurrentIndent)))] |
|
1238 |
elif transitionType == "ST": |
|
1239 |
transition_infos["content"] = [("\n", ()), |
|
1240 |
(ReIndentText(transitionBody.gettext(), len(self.CurrentIndent)), (self.TagName, "body", len(self.CurrentIndent)))] |
|
1241 |
else: |
|
1242 |
for instance in transitionBody.getcontentInstances(): |
|
1243 |
if isinstance(instance, plcopen.fbdObjects_outVariable) and instance.getexpression() == transitionValues["value"]\ |
|
1244 |
or isinstance(instance, plcopen.ldObjects_coil) and instance.getvariable() == transitionValues["value"]: |
|
1245 |
connections = instance.connectionPointIn.getconnections() |
|
1246 |
if connections is not None: |
|
1247 |
expression = self.ComputeExpression(transitionBody, connections) |
|
1248 |
transition_infos["content"] = [("\n%s:= "%self.CurrentIndent, ())] + expression + [(";\n", ())] |
|
1249 |
self.SFCComputedBlocks += self.Program |
|
1250 |
self.Program = [] |
|
1251 |
if not transition_infos.has_key("content"): |
|
1252 |
raise PLCGenException, _("Transition \"%s\" body must contain an output variable or coil referring to its name") % transitionValues["value"] |
|
1253 |
self.TagName = previous_tagname |
|
1254 |
elif transitionValues["type"] == "connection": |
|
1255 |
body = pou.getbody() |
|
1256 |
if isinstance(body, ListType): |
|
1257 |
body = body[0] |
|
1258 |
connections = transition.getconnections() |
|
1259 |
if connections is not None: |
|
1260 |
expression = self.ComputeExpression(body, connections) |
|
1261 |
transition_infos["content"] = [("\n%s:= "%self.CurrentIndent, ())] + expression + [(";\n", ())] |
|
1262 |
self.SFCComputedBlocks += self.Program |
|
1263 |
self.Program = [] |
|
1264 |
for step in steps: |
|
1265 |
self.GenerateSFCStep(step, pou) |
|
1266 |
step_name = step.getname() |
|
1267 |
if step_name in self.SFCNetworks["Steps"].keys(): |
|
1268 |
transition_infos["from"].append([(step_name, (self.TagName, "transition", transition.getlocalId(), "from", step.getlocalId()))]) |
|
1269 |
self.SFCNetworks["Steps"][step_name]["transitions"].append(transition) |
|
1270 |
||
1271 |
def ComputeSFCStep(self, step_name): |
|
1272 |
if step_name in self.SFCNetworks["Steps"].keys(): |
|
1273 |
step_infos = self.SFCNetworks["Steps"].pop(step_name) |
|
1274 |
self.Program += [(self.CurrentIndent, ())] |
|
1275 |
if step_infos["initial"]: |
|
1276 |
self.Program += [("INITIAL_", ())] |
|
1277 |
self.Program += [("STEP ", ()), |
|
1278 |
(step_name, (self.TagName, "step", step_infos["id"], "name")), |
|
1279 |
(":\n", ())] |
|
1280 |
actions = [] |
|
1281 |
self.IndentRight() |
|
1282 |
for action_infos in step_infos["actions"]: |
|
1283 |
if action_infos.get("id", None) is not None: |
|
1284 |
action_info = (self.TagName, "action_block", action_infos["id"], "action", action_infos["num"]) |
|
1285 |
else: |
|
1286 |
action_info = () |
|
1287 |
actions.append(action_infos["content"]) |
|
1288 |
self.Program += [(self.CurrentIndent, ()), |
|
1289 |
(action_infos["content"], action_info + ("reference",)), |
|
1290 |
("(", ()), |
|
1291 |
(action_infos["qualifier"], action_info + ("qualifier",))] |
|
1292 |
if "duration" in action_infos: |
|
1293 |
self.Program += [(", ", ()), |
|
1294 |
(action_infos["duration"], action_info + ("duration",))] |
|
1295 |
if "indicator" in action_infos: |
|
1296 |
self.Program += [(", ", ()), |
|
1297 |
(action_infos["indicator"], action_info + ("indicator",))] |
|
1298 |
self.Program += [(");\n", ())] |
|
1299 |
self.IndentLeft() |
|
1300 |
self.Program += [("%sEND_STEP\n\n"%self.CurrentIndent, ())] |
|
1301 |
for action in actions: |
|
1302 |
self.ComputeSFCAction(action) |
|
1303 |
for transition in step_infos["transitions"]: |
|
1304 |
self.ComputeSFCTransition(transition) |
|
1305 |
||
1306 |
def ComputeSFCAction(self, action_name): |
|
1307 |
if action_name in self.SFCNetworks["Actions"].keys(): |
|
1308 |
action_content, action_info = self.SFCNetworks["Actions"].pop(action_name) |
|
1309 |
self.Program += [("%sACTION "%self.CurrentIndent, ()), |
|
1310 |
(action_name, action_info), |
|
1311 |
(" :\n", ())] |
|
1312 |
self.Program += action_content |
|
1313 |
self.Program += [("%sEND_ACTION\n\n"%self.CurrentIndent, ())] |
|
1314 |
||
1315 |
def ComputeSFCTransition(self, transition): |
|
1316 |
if transition in self.SFCNetworks["Transitions"].keys(): |
|
1317 |
transition_infos = self.SFCNetworks["Transitions"].pop(transition) |
|
1318 |
self.Program += [("%sTRANSITION"%self.CurrentIndent, ())] |
|
1319 |
if transition_infos["priority"] != None: |
|
1320 |
self.Program += [(" (PRIORITY := ", ()), |
|
1321 |
("%d"%transition_infos["priority"], (self.TagName, "transition", transition_infos["id"], "priority")), |
|
1322 |
(")", ())] |
|
1323 |
self.Program += [(" FROM ", ())] |
|
1324 |
if len(transition_infos["from"]) > 1: |
|
1325 |
self.Program += [("(", ())] |
|
1326 |
self.Program += JoinList([(", ", ())], transition_infos["from"]) |
|
1327 |
self.Program += [(")", ())] |
|
1328 |
elif len(transition_infos["from"]) == 1: |
|
1329 |
self.Program += transition_infos["from"][0] |
|
1330 |
else: |
|
1331 |
raise PLCGenException, _("Transition with content \"%s\" not connected to a previous step in \"%s\" POU")%(transition_infos["content"], self.Name) |
|
1332 |
self.Program += [(" TO ", ())] |
|
1333 |
if len(transition_infos["to"]) > 1: |
|
1334 |
self.Program += [("(", ())] |
|
1335 |
self.Program += JoinList([(", ", ())], transition_infos["to"]) |
|
1336 |
self.Program += [(")", ())] |
|
1337 |
elif len(transition_infos["to"]) == 1: |
|
1338 |
self.Program += transition_infos["to"][0] |
|
1339 |
else: |
|
1340 |
raise PLCGenException, _("Transition with content \"%s\" not connected to a next step in \"%s\" POU")%(transition_infos["content"], self.Name) |
|
1341 |
self.Program += transition_infos["content"] |
|
1342 |
self.Program += [("%sEND_TRANSITION\n\n"%self.CurrentIndent, ())] |
|
1343 |
for [(step_name, step_infos)] in transition_infos["to"]: |
|
1344 |
self.ComputeSFCStep(step_name) |
|
1345 |
||
1346 |
def GenerateProgram(self, pou): |
|
1347 |
self.ComputeInterface(pou) |
|
1348 |
self.ComputeConnectionTypes(pou) |
|
1349 |
self.ComputeProgram(pou) |
|
1350 |
||
1351 |
program = [("%s "%self.Type, ()), |
|
1352 |
(self.Name, (self.TagName, "name"))] |
|
1353 |
if self.ReturnType: |
|
1354 |
program += [(" : ", ()), |
|
1355 |
(self.ReturnType, (self.TagName, "return"))] |
|
1356 |
program += [("\n", ())] |
|
1357 |
if len(self.Interface) == 0: |
|
1358 |
raise PLCGenException, _("No variable defined in \"%s\" POU")%self.Name |
|
1359 |
if len(self.Program) == 0 : |
|
1360 |
raise PLCGenException, _("No body defined in \"%s\" POU")%self.Name |
|
1361 |
var_number = 0 |
|
1362 |
for list_type, option, located, variables in self.Interface: |
|
1363 |
variable_type = errorVarTypes.get(list_type, "var_local") |
|
1364 |
program += [(" %s"%list_type, ())] |
|
1365 |
if option is not None: |
|
1366 |
program += [(" %s"%option, (self.TagName, variable_type, (var_number, var_number + len(variables)), option.lower()))] |
|
1367 |
program += [("\n", ())] |
|
1368 |
for var_type, var_name, var_address, var_initial in variables: |
|
1369 |
program += [(" ", ())] |
|
1370 |
if var_name: |
|
1371 |
program += [(var_name, (self.TagName, variable_type, var_number, "name")), |
|
1372 |
(" ", ())] |
|
1373 |
if var_address != None: |
|
1374 |
program += [("AT ", ()), |
|
1375 |
(var_address, (self.TagName, variable_type, var_number, "location")), |
|
1376 |
(" ", ())] |
|
1377 |
program += [(": ", ()), |
|
1378 |
(var_type, (self.TagName, variable_type, var_number, "type"))] |
|
1379 |
if var_initial != None: |
|
1380 |
program += [(" := ", ()), |
|
1381 |
(self.ParentGenerator.ComputeValue(var_initial, var_type), (self.TagName, variable_type, var_number, "initial value"))] |
|
1382 |
program += [(";\n", ())] |
|
1383 |
var_number += 1 |
|
1384 |
program += [(" END_VAR\n", ())] |
|
1385 |
program += [("\n", ())] |
|
1386 |
program += self.Program |
|
1387 |
program += [("END_%s\n\n"%self.Type, ())] |
|
1388 |
return program |
|
1389 |
||
1390 |
def GenerateCurrentProgram(controler, project, errors, warnings): |
|
1391 |
generator = ProgramGenerator(controler, project, errors, warnings) |
|
1392 |
generator.GenerateProgram() |
|
1393 |
return generator.GetGeneratedProgram() |
|
1394 |