plcdiff 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- plcdiff/__init__.py +21 -0
- plcdiff/__main__.py +3 -0
- plcdiff/_xml.py +41 -0
- plcdiff/cli.py +158 -0
- plcdiff/diff.py +172 -0
- plcdiff/gitutil.py +130 -0
- plcdiff/l5x.py +286 -0
- plcdiff/loader.py +43 -0
- plcdiff/model.py +64 -0
- plcdiff/plcopen.py +291 -0
- plcdiff/py.typed +0 -0
- plcdiff/render.py +36 -0
- plcdiff/report.py +128 -0
- plcdiff-0.1.0.dist-info/METADATA +180 -0
- plcdiff-0.1.0.dist-info/RECORD +18 -0
- plcdiff-0.1.0.dist-info/WHEEL +4 -0
- plcdiff-0.1.0.dist-info/entry_points.txt +2 -0
- plcdiff-0.1.0.dist-info/licenses/LICENSE +21 -0
plcdiff/l5x.py
ADDED
|
@@ -0,0 +1,286 @@
|
|
|
1
|
+
"""Rockwell Automation Studio 5000 / RSLogix 5000 ``.L5X`` exports."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import xml.etree.ElementTree as ET
|
|
6
|
+
|
|
7
|
+
from plcdiff._xml import child, children, local, oneline, text
|
|
8
|
+
from plcdiff.model import Block, Document, Entry
|
|
9
|
+
|
|
10
|
+
ROOT = "RSLogix5000Content"
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def description(el: ET.Element) -> str:
|
|
14
|
+
"""Description of a tag/member/routine, plain or localized."""
|
|
15
|
+
desc = child(el, "Description")
|
|
16
|
+
if desc is None:
|
|
17
|
+
return ""
|
|
18
|
+
localized = child(desc, "LocalizedDescription")
|
|
19
|
+
return text(localized if localized is not None else desc)
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def comment(el: ET.Element) -> str:
|
|
23
|
+
com = child(el, "Comment")
|
|
24
|
+
if com is not None:
|
|
25
|
+
localized = child(com, "LocalizedComment")
|
|
26
|
+
return text(localized if localized is not None else com)
|
|
27
|
+
comments = child(el, "Comments")
|
|
28
|
+
if comments is not None:
|
|
29
|
+
return "\n".join(text(c) for c in comments)
|
|
30
|
+
return ""
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def parse(root: ET.Element, include_values: bool = True) -> Document:
|
|
34
|
+
controller = child(root, "Controller")
|
|
35
|
+
if controller is None:
|
|
36
|
+
raise ValueError("L5X file has no <Controller> element")
|
|
37
|
+
name = controller.get("Name", root.get("TargetName", "controller"))
|
|
38
|
+
doc = Document(format="L5X", name=name)
|
|
39
|
+
doc.info = {
|
|
40
|
+
"target": f"{root.get('TargetType', 'Controller')} {root.get('TargetName', name)}",
|
|
41
|
+
"software": root.get("SoftwareRevision", ""),
|
|
42
|
+
"processor": controller.get("ProcessorType", ""),
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
ctl = doc.block("Controller", kind="keyed", unit="Property")
|
|
46
|
+
for attr in ("ProcessorType", "MajorRev", "MinorRev", "CommPath"):
|
|
47
|
+
if controller.get(attr):
|
|
48
|
+
ctl.add(f"{attr} = {controller.get(attr)}", key=attr)
|
|
49
|
+
if description(controller):
|
|
50
|
+
ctl.add("Description", key="Description", note=description(controller))
|
|
51
|
+
if not ctl.entries:
|
|
52
|
+
doc.blocks.remove(ctl)
|
|
53
|
+
|
|
54
|
+
_datatypes(doc, controller)
|
|
55
|
+
_modules(doc, controller)
|
|
56
|
+
_aois(doc, controller, include_values)
|
|
57
|
+
_tags(doc, child(controller, "Tags"), ("Controller Tags",), include_values)
|
|
58
|
+
_programs(doc, controller, include_values)
|
|
59
|
+
_tasks(doc, controller)
|
|
60
|
+
return doc
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _datatypes(doc: Document, controller: ET.Element) -> None:
|
|
64
|
+
for dt in children(child(controller, "DataTypes"), "DataType"):
|
|
65
|
+
block = doc.block("DataType " + dt.get("Name", "?"), kind="keyed", unit="Member")
|
|
66
|
+
if description(dt):
|
|
67
|
+
block.add("Description", key="", note=description(dt))
|
|
68
|
+
for m in children(child(dt, "Members"), "Member"):
|
|
69
|
+
if m.get("Hidden") == "true":
|
|
70
|
+
continue # backing SINT for packed BOOLs: noise
|
|
71
|
+
dtype = m.get("DataType", "?")
|
|
72
|
+
if dtype == "BIT":
|
|
73
|
+
dtype = "BOOL"
|
|
74
|
+
dim = m.get("Dimension", "0")
|
|
75
|
+
decl = f"{m.get('Name')} : {dtype}" + (f"[{dim}]" if dim not in ("", "0") else "")
|
|
76
|
+
block.add(decl, key=m.get("Name"), note=description(m))
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def _modules(doc: Document, controller: ET.Element) -> None:
|
|
80
|
+
modules = child(controller, "Modules")
|
|
81
|
+
if modules is None:
|
|
82
|
+
return
|
|
83
|
+
block = doc.block("Modules", kind="keyed", unit="Module")
|
|
84
|
+
for mod in children(modules, "Module"):
|
|
85
|
+
parts = [f"{mod.get('Name')} : {mod.get('CatalogNumber', '?')}"]
|
|
86
|
+
if mod.get("Major"):
|
|
87
|
+
parts.append(f"rev {mod.get('Major')}.{mod.get('Minor', '0')}")
|
|
88
|
+
parent = mod.get("ParentModule")
|
|
89
|
+
if parent and parent != mod.get("Name"):
|
|
90
|
+
parts.append(f"parent {parent}")
|
|
91
|
+
addresses = [p.get("Address", "") for p in children(child(mod, "Ports"), "Port")]
|
|
92
|
+
addresses = [a for a in addresses if a]
|
|
93
|
+
if addresses:
|
|
94
|
+
parts.append("address " + ",".join(addresses))
|
|
95
|
+
if mod.get("Inhibited") == "true":
|
|
96
|
+
parts.append("INHIBITED")
|
|
97
|
+
block.add(", ".join(parts), key=mod.get("Name"), note=description(mod))
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def _aois(doc: Document, controller: ET.Element, include_values: bool) -> None:
|
|
101
|
+
aois = child(controller, "AddOnInstructionDefinitions")
|
|
102
|
+
if aois is None:
|
|
103
|
+
return
|
|
104
|
+
for aoi in children(aois, "AddOnInstructionDefinition"):
|
|
105
|
+
name = aoi.get("Name", "?")
|
|
106
|
+
head = ("AOI " + name,)
|
|
107
|
+
block = doc.block(*head, "Parameters", kind="keyed", unit="Parameter")
|
|
108
|
+
block.add(f"Revision {aoi.get('Revision', '?')}", key="Revision", note=description(aoi))
|
|
109
|
+
for p in children(child(aoi, "Parameters"), "Parameter"):
|
|
110
|
+
decl = f"{p.get('Name')} : {p.get('DataType')} ({p.get('Usage', '?')})"
|
|
111
|
+
if p.get("Required") == "true":
|
|
112
|
+
decl += " required"
|
|
113
|
+
block.add(decl, key=p.get("Name"), note=description(p))
|
|
114
|
+
local_tags = child(aoi, "LocalTags")
|
|
115
|
+
if local_tags is not None:
|
|
116
|
+
_tags(doc, local_tags, (*head, "Local Tags"), include_values, tag="LocalTag")
|
|
117
|
+
_routines(doc, aoi, head)
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def _decl(tag: ET.Element) -> str:
|
|
121
|
+
decl = f"{tag.get('Name')} : {tag.get('DataType', '?')}"
|
|
122
|
+
dim = tag.get("Dimensions") or tag.get("Dimension")
|
|
123
|
+
if dim and dim != "0":
|
|
124
|
+
decl += f"[{dim.replace(' ', ',')}]"
|
|
125
|
+
if tag.get("TagType") == "Alias":
|
|
126
|
+
decl = f"{tag.get('Name')} alias for {tag.get('AliasFor', '?')}"
|
|
127
|
+
elif tag.get("TagType") == "Produced":
|
|
128
|
+
decl += " produced"
|
|
129
|
+
elif tag.get("TagType") == "Consumed":
|
|
130
|
+
decl += " consumed"
|
|
131
|
+
if tag.get("Usage") and tag.get("Usage") not in ("Local", "Public"):
|
|
132
|
+
decl += f" ({tag.get('Usage')})"
|
|
133
|
+
if tag.get("Constant") == "true":
|
|
134
|
+
decl += " constant"
|
|
135
|
+
access = tag.get("ExternalAccess")
|
|
136
|
+
if access and access != "Read/Write":
|
|
137
|
+
decl += f" access={access}"
|
|
138
|
+
return decl
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def _tags(
|
|
142
|
+
doc: Document,
|
|
143
|
+
tags: ET.Element | None,
|
|
144
|
+
path: tuple[str, ...],
|
|
145
|
+
include_values: bool,
|
|
146
|
+
tag: str = "Tag",
|
|
147
|
+
) -> None:
|
|
148
|
+
if tags is None:
|
|
149
|
+
return
|
|
150
|
+
block = doc.block(*path, kind="keyed", unit="Tag")
|
|
151
|
+
values: Block | None = None
|
|
152
|
+
if include_values:
|
|
153
|
+
values = doc.block(*path[:-1], path[-1] + " (values)", kind="keyed", unit="Value")
|
|
154
|
+
for t in children(tags, tag):
|
|
155
|
+
name = t.get("Name", "?")
|
|
156
|
+
block.add(_decl(t), key=name, note=description(t))
|
|
157
|
+
if values is None:
|
|
158
|
+
continue
|
|
159
|
+
for member_name, value in tag_values(t):
|
|
160
|
+
values.add(f"{member_name} = {value}", key=member_name)
|
|
161
|
+
if values is not None and not values.entries:
|
|
162
|
+
doc.blocks.remove(values)
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def tag_values(tag: ET.Element) -> list[tuple[str, str]]:
|
|
166
|
+
"""Flatten a tag's ``Decorated`` (or ``String``) data into name/value pairs."""
|
|
167
|
+
name = tag.get("Name", "?")
|
|
168
|
+
datas = list(children(tag, "Data")) + list(children(tag, "DefaultData"))
|
|
169
|
+
for data in datas:
|
|
170
|
+
if data.get("Format") == "Decorated":
|
|
171
|
+
out: list[tuple[str, str]] = []
|
|
172
|
+
for item in data:
|
|
173
|
+
_flatten(item, name, out)
|
|
174
|
+
return out
|
|
175
|
+
for data in datas:
|
|
176
|
+
if data.get("Format") == "String":
|
|
177
|
+
return [(name, text(data))]
|
|
178
|
+
return []
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
def _flatten(el: ET.Element, prefix: str, out: list[tuple[str, str]]) -> None:
|
|
182
|
+
kind = local(el.tag)
|
|
183
|
+
if kind in ("DataValue", "DataValueMember"):
|
|
184
|
+
here = prefix if kind == "DataValue" else f"{prefix}.{el.get('Name')}"
|
|
185
|
+
value = el.get("Value")
|
|
186
|
+
out.append((here, value if value is not None else text(el)))
|
|
187
|
+
elif kind in ("Structure", "Array"):
|
|
188
|
+
for sub in el:
|
|
189
|
+
_flatten(sub, prefix, out)
|
|
190
|
+
elif kind in ("StructureMember", "ArrayMember"):
|
|
191
|
+
here = f"{prefix}.{el.get('Name')}"
|
|
192
|
+
for sub in el:
|
|
193
|
+
_flatten(sub, here, out)
|
|
194
|
+
elif kind == "Element":
|
|
195
|
+
here = prefix + el.get("Index", "[?]")
|
|
196
|
+
if el.get("Value") is not None:
|
|
197
|
+
out.append((here, el.get("Value", "")))
|
|
198
|
+
for sub in el:
|
|
199
|
+
_flatten(sub, here, out)
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
def _programs(doc: Document, controller: ET.Element, include_values: bool) -> None:
|
|
203
|
+
programs = child(controller, "Programs")
|
|
204
|
+
if programs is None:
|
|
205
|
+
return
|
|
206
|
+
summary = doc.block("Programs", kind="keyed", unit="Program")
|
|
207
|
+
for prog in children(programs, "Program"):
|
|
208
|
+
name = prog.get("Name", "?")
|
|
209
|
+
line = f"{name} main={prog.get('MainRoutineName', '-')}"
|
|
210
|
+
if prog.get("FaultRoutineName"):
|
|
211
|
+
line += f" fault={prog.get('FaultRoutineName')}"
|
|
212
|
+
if prog.get("Disabled") == "true":
|
|
213
|
+
line += " DISABLED"
|
|
214
|
+
summary.add(line, key=name, note=description(prog))
|
|
215
|
+
head = ("Program " + name,)
|
|
216
|
+
_tags(doc, child(prog, "Tags"), (*head, "Tags"), include_values)
|
|
217
|
+
_routines(doc, prog, head)
|
|
218
|
+
|
|
219
|
+
|
|
220
|
+
def _routines(doc: Document, owner: ET.Element, head: tuple[str, ...]) -> None:
|
|
221
|
+
routines = child(owner, "Routines")
|
|
222
|
+
if routines is None:
|
|
223
|
+
return
|
|
224
|
+
for r in children(routines, "Routine"):
|
|
225
|
+
rtype = r.get("Type", "?")
|
|
226
|
+
title = f"Routine {r.get('Name')} ({rtype})"
|
|
227
|
+
rll = child(r, "RLLContent")
|
|
228
|
+
st = child(r, "STContent")
|
|
229
|
+
if rll is not None:
|
|
230
|
+
block = doc.block(*head, title, kind="sequence", unit="Rung")
|
|
231
|
+
for rung in children(rll, "Rung"):
|
|
232
|
+
logic = oneline(text(child(rung, "Text")))
|
|
233
|
+
rung_type = rung.get("Type", "N")
|
|
234
|
+
if rung_type not in ("N", ""):
|
|
235
|
+
logic = f"[{rung_type}] {logic}"
|
|
236
|
+
block.add(logic, note=comment(rung))
|
|
237
|
+
elif st is not None:
|
|
238
|
+
block = doc.block(*head, title, kind="sequence", unit="Line")
|
|
239
|
+
for line in children(st, "Line"):
|
|
240
|
+
block.add("".join(line.itertext()).strip("\r\n").rstrip())
|
|
241
|
+
elif child(r, "EncodedData") is not None or child(r, "EncryptedContent") is not None:
|
|
242
|
+
block = doc.block(*head, title, kind="sequence", unit="Line")
|
|
243
|
+
block.add("(source protected)")
|
|
244
|
+
else:
|
|
245
|
+
block = doc.block(*head, title, kind="sequence", unit="Element")
|
|
246
|
+
for content in r:
|
|
247
|
+
if local(content.tag) == "Description":
|
|
248
|
+
continue
|
|
249
|
+
_generic(content, block)
|
|
250
|
+
if description(r):
|
|
251
|
+
block.entries.insert(0, Entry("Description", note=description(r)))
|
|
252
|
+
|
|
253
|
+
|
|
254
|
+
def _generic(el: ET.Element, block: Block, depth: int = 0) -> None:
|
|
255
|
+
"""Graphical content (FBD, SFC): one line per element with its attributes."""
|
|
256
|
+
attrs = " ".join(f'{k}="{v}"' for k, v in sorted(el.attrib.items()))
|
|
257
|
+
body = oneline(el.text or "") if len(el) == 0 else ""
|
|
258
|
+
line = " " * depth + local(el.tag) + (f" {attrs}" if attrs else "")
|
|
259
|
+
if body:
|
|
260
|
+
line += f": {body}"
|
|
261
|
+
block.add(line)
|
|
262
|
+
for sub in el:
|
|
263
|
+
_generic(sub, block, depth + 1)
|
|
264
|
+
|
|
265
|
+
|
|
266
|
+
def _tasks(doc: Document, controller: ET.Element) -> None:
|
|
267
|
+
tasks = child(controller, "Tasks")
|
|
268
|
+
if tasks is None:
|
|
269
|
+
return
|
|
270
|
+
block = doc.block("Tasks", kind="keyed", unit="Task")
|
|
271
|
+
for task in children(tasks, "Task"):
|
|
272
|
+
parts = [f"{task.get('Name')} : {task.get('Type', '?')}"]
|
|
273
|
+
if task.get("Rate"):
|
|
274
|
+
parts.append(f"rate {task.get('Rate')} ms")
|
|
275
|
+
if task.get("Priority"):
|
|
276
|
+
parts.append(f"priority {task.get('Priority')}")
|
|
277
|
+
if task.get("Watchdog"):
|
|
278
|
+
parts.append(f"watchdog {task.get('Watchdog')} ms")
|
|
279
|
+
if task.get("InhibitTask") == "true":
|
|
280
|
+
parts.append("INHIBITED")
|
|
281
|
+
progs = [
|
|
282
|
+
p.get("Name", "?")
|
|
283
|
+
for p in children(child(task, "ScheduledPrograms"), "ScheduledProgram")
|
|
284
|
+
]
|
|
285
|
+
parts.append("programs " + (", ".join(progs) if progs else "-"))
|
|
286
|
+
block.add(", ".join(parts), key=task.get("Name"), note=description(task))
|
plcdiff/loader.py
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
"""Detect the export format and parse it into a :class:`~plcdiff.model.Document`."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import xml.etree.ElementTree as ET
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
|
|
8
|
+
from plcdiff import l5x, plcopen
|
|
9
|
+
from plcdiff._xml import local
|
|
10
|
+
from plcdiff.model import Document
|
|
11
|
+
|
|
12
|
+
SUFFIXES = (".l5x", ".xml", ".plcopen")
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class UnsupportedFormat(ValueError):
|
|
16
|
+
"""The file is not a PLC export plcdiff understands."""
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def loads(data: bytes | str, name: str = "<data>", include_values: bool = True) -> Document:
|
|
20
|
+
"""Parse export content. Raises :class:`UnsupportedFormat` for anything else."""
|
|
21
|
+
if isinstance(data, str):
|
|
22
|
+
data = data.encode("utf-8")
|
|
23
|
+
if not data.strip():
|
|
24
|
+
return Document(format="empty", name=name)
|
|
25
|
+
try:
|
|
26
|
+
root = ET.fromstring(data)
|
|
27
|
+
except ET.ParseError as exc:
|
|
28
|
+
raise UnsupportedFormat(f"{name}: not well-formed XML ({exc})") from exc
|
|
29
|
+
if local(root.tag) == l5x.ROOT:
|
|
30
|
+
return l5x.parse(root, include_values)
|
|
31
|
+
if plcopen.is_plcopen(root):
|
|
32
|
+
return plcopen.parse(root, include_values)
|
|
33
|
+
raise UnsupportedFormat(f"{name}: unknown root element <{local(root.tag)}>")
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def load(path: str | Path, include_values: bool = True) -> Document:
|
|
37
|
+
"""Parse an export file from disk."""
|
|
38
|
+
p = Path(path)
|
|
39
|
+
return loads(p.read_bytes(), name=str(p), include_values=include_values)
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def looks_supported(path: str) -> bool:
|
|
43
|
+
return path.lower().endswith(SUFFIXES)
|
plcdiff/model.py
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
"""The normalized, vendor-neutral view of a PLC project.
|
|
2
|
+
|
|
3
|
+
Every supported export format is parsed into a :class:`Document`: an ordered
|
|
4
|
+
list of :class:`Block` objects. A block is one logical part of the project
|
|
5
|
+
(the controller tags, one routine, one data type, ...). It holds entries that
|
|
6
|
+
are either *keyed* (tags, members, parameters: compared by name, order does not
|
|
7
|
+
matter) or *sequential* (rungs, Structured Text lines: compared by position).
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
from dataclasses import dataclass, field
|
|
13
|
+
from typing import Literal
|
|
14
|
+
|
|
15
|
+
BlockKind = Literal["keyed", "sequence"]
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
@dataclass(frozen=True)
|
|
19
|
+
class Entry:
|
|
20
|
+
"""One line of meaning: a tag declaration, a rung, a line of code."""
|
|
21
|
+
|
|
22
|
+
text: str
|
|
23
|
+
key: str | None = None
|
|
24
|
+
note: str = ""
|
|
25
|
+
"""Comment or description attached to the entry (may span lines)."""
|
|
26
|
+
|
|
27
|
+
def same_as(self, other: Entry) -> bool:
|
|
28
|
+
return self.text == other.text and self.note == other.note
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
@dataclass
|
|
32
|
+
class Block:
|
|
33
|
+
"""A titled group of entries, e.g. ``Program MainProgram / Routine Main``."""
|
|
34
|
+
|
|
35
|
+
path: tuple[str, ...]
|
|
36
|
+
kind: BlockKind
|
|
37
|
+
entries: list[Entry] = field(default_factory=list)
|
|
38
|
+
unit: str = "Entry"
|
|
39
|
+
"""What a single entry is called in reports: Rung, Line, Tag, Member, ..."""
|
|
40
|
+
|
|
41
|
+
@property
|
|
42
|
+
def title(self) -> str:
|
|
43
|
+
return " / ".join(self.path)
|
|
44
|
+
|
|
45
|
+
def add(self, text: str, key: str | None = None, note: str = "") -> None:
|
|
46
|
+
self.entries.append(Entry(text=text, key=key, note=note.strip()))
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
@dataclass
|
|
50
|
+
class Document:
|
|
51
|
+
"""A parsed PLC export."""
|
|
52
|
+
|
|
53
|
+
format: str
|
|
54
|
+
name: str
|
|
55
|
+
blocks: list[Block] = field(default_factory=list)
|
|
56
|
+
info: dict[str, str] = field(default_factory=dict)
|
|
57
|
+
|
|
58
|
+
def block(self, *path: str, kind: BlockKind = "keyed", unit: str = "Entry") -> Block:
|
|
59
|
+
b = Block(path=tuple(path), kind=kind, unit=unit)
|
|
60
|
+
self.blocks.append(b)
|
|
61
|
+
return b
|
|
62
|
+
|
|
63
|
+
def by_title(self) -> dict[str, Block]:
|
|
64
|
+
return {b.title: b for b in self.blocks}
|
plcdiff/plcopen.py
ADDED
|
@@ -0,0 +1,291 @@
|
|
|
1
|
+
"""PLCopen TC6 XML (IEC 61131-3) exports: CODESYS, TwinCAT, Beremiz, Machine Expert, ..."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import xml.etree.ElementTree as ET
|
|
6
|
+
|
|
7
|
+
from plcdiff._xml import child, children, local, oneline, text
|
|
8
|
+
from plcdiff.model import Block, Document
|
|
9
|
+
|
|
10
|
+
ROOT = "project"
|
|
11
|
+
NAMESPACE_HINT = "plcopen.org/xml/tc6"
|
|
12
|
+
|
|
13
|
+
VAR_SECTIONS = {
|
|
14
|
+
"inputVars": "VAR_INPUT",
|
|
15
|
+
"outputVars": "VAR_OUTPUT",
|
|
16
|
+
"inOutVars": "VAR_IN_OUT",
|
|
17
|
+
"localVars": "VAR",
|
|
18
|
+
"tempVars": "VAR_TEMP",
|
|
19
|
+
"externalVars": "VAR_EXTERNAL",
|
|
20
|
+
"globalVars": "VAR_GLOBAL",
|
|
21
|
+
"accessVars": "VAR_ACCESS",
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
# Layout-only elements of graphical languages: they change when someone drags a
|
|
25
|
+
# box around, not when the logic changes.
|
|
26
|
+
LAYOUT = {"position", "relPosition", "connectionPointIn", "connectionPointOut", "addData"}
|
|
27
|
+
LAYOUT_ATTRS = {"localId", "height", "width", "executionOrderId", "refLocalId"}
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def is_plcopen(root: ET.Element) -> bool:
|
|
31
|
+
return local(root.tag) == ROOT and NAMESPACE_HINT in root.tag
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def documentation(el: ET.Element) -> str:
|
|
35
|
+
return text(child(el, "documentation"))
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def type_str(type_el: ET.Element | None) -> str:
|
|
39
|
+
"""Render a ``<type>``/``<baseType>`` element as IEC 61131-3 text."""
|
|
40
|
+
if type_el is None:
|
|
41
|
+
return "?"
|
|
42
|
+
inner = next(iter(type_el), None)
|
|
43
|
+
if inner is None:
|
|
44
|
+
return "?"
|
|
45
|
+
kind = local(inner.tag)
|
|
46
|
+
if kind == "derived":
|
|
47
|
+
return inner.get("name", "?")
|
|
48
|
+
if kind in ("string", "wstring"):
|
|
49
|
+
length = inner.get("length")
|
|
50
|
+
return kind.upper() + (f"({length})" if length else "")
|
|
51
|
+
if kind == "array":
|
|
52
|
+
dims = ",".join(
|
|
53
|
+
f"{d.get('lower', '?')}..{d.get('upper', '?')}" for d in children(inner, "dimension")
|
|
54
|
+
)
|
|
55
|
+
return f"ARRAY[{dims}] OF {type_str(child(inner, 'baseType'))}"
|
|
56
|
+
if kind == "pointer":
|
|
57
|
+
return f"POINTER TO {type_str(child(inner, 'baseType'))}"
|
|
58
|
+
if kind in ("subrangeSigned", "subrangeUnsigned"):
|
|
59
|
+
rng = child(inner, "range")
|
|
60
|
+
bounds = f"{rng.get('lower')}..{rng.get('upper')}" if rng is not None else "?"
|
|
61
|
+
return f"{type_str(child(inner, 'baseType'))}({bounds})"
|
|
62
|
+
if kind == "enum":
|
|
63
|
+
names = [v.get("name", "?") for v in children(child(inner, "values"), "value")]
|
|
64
|
+
return "(" + ", ".join(names) + ")"
|
|
65
|
+
if kind == "struct":
|
|
66
|
+
return "STRUCT"
|
|
67
|
+
return kind.upper()
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def value_str(el: ET.Element | None) -> str:
|
|
71
|
+
"""Render an ``<initialValue>`` element."""
|
|
72
|
+
if el is None:
|
|
73
|
+
return ""
|
|
74
|
+
inner = next(iter(el), None)
|
|
75
|
+
if inner is None:
|
|
76
|
+
return ""
|
|
77
|
+
kind = local(inner.tag)
|
|
78
|
+
if kind == "simpleValue":
|
|
79
|
+
return inner.get("value", "")
|
|
80
|
+
if kind == "arrayValue":
|
|
81
|
+
parts = []
|
|
82
|
+
for v in children(inner, "value"):
|
|
83
|
+
item = value_str(v)
|
|
84
|
+
if v.get("repetitionValue"):
|
|
85
|
+
item = f"{v.get('repetitionValue')}({item})"
|
|
86
|
+
parts.append(item)
|
|
87
|
+
return "[" + ", ".join(parts) + "]"
|
|
88
|
+
if kind == "structValue":
|
|
89
|
+
return (
|
|
90
|
+
"("
|
|
91
|
+
+ ", ".join(f"{v.get('member')} := {value_str(v)}" for v in children(inner, "value"))
|
|
92
|
+
+ ")"
|
|
93
|
+
)
|
|
94
|
+
return oneline(text(inner))
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def variable_decl(var: ET.Element) -> str:
|
|
98
|
+
decl = f"{var.get('name')} : {type_str(child(var, 'type'))}"
|
|
99
|
+
if var.get("address"):
|
|
100
|
+
decl = f"{var.get('name')} AT {var.get('address')} : {type_str(child(var, 'type'))}"
|
|
101
|
+
init = value_str(child(var, "initialValue"))
|
|
102
|
+
if init:
|
|
103
|
+
decl += f" := {init}"
|
|
104
|
+
return decl
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def parse(root: ET.Element, include_values: bool = True) -> Document:
|
|
108
|
+
header = child(root, "contentHeader")
|
|
109
|
+
file_header = child(root, "fileHeader")
|
|
110
|
+
name = header.get("name", "project") if header is not None else "project"
|
|
111
|
+
doc = Document(format="PLCopen XML", name=name)
|
|
112
|
+
if file_header is not None:
|
|
113
|
+
doc.info = {
|
|
114
|
+
"product": " ".join(
|
|
115
|
+
x for x in (file_header.get("productName"), file_header.get("productVersion")) if x
|
|
116
|
+
),
|
|
117
|
+
"company": file_header.get("companyName", ""),
|
|
118
|
+
}
|
|
119
|
+
types = child(root, "types")
|
|
120
|
+
if types is not None:
|
|
121
|
+
_datatypes(doc, child(types, "dataTypes"))
|
|
122
|
+
_pous(doc, child(types, "pous"))
|
|
123
|
+
_instances(doc, child(root, "instances", "configurations"))
|
|
124
|
+
# CODESYS keeps global variable lists in vendor data, not in a configuration.
|
|
125
|
+
for gvl in _in_add_data(root, "globalVars"):
|
|
126
|
+
_var_list(doc, gvl, (f"GVL {gvl.get('name', '?')}",))
|
|
127
|
+
doc.blocks = [b for b in doc.blocks if b.entries]
|
|
128
|
+
return doc
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def _in_add_data(el: ET.Element, name: str) -> list[ET.Element]:
|
|
132
|
+
"""Elements called ``name`` inside an element's own ``<addData>``."""
|
|
133
|
+
found: list[ET.Element] = []
|
|
134
|
+
for add in children(el, "addData"):
|
|
135
|
+
found += [d for d in add.iter() if local(d.tag) == name]
|
|
136
|
+
return found
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def _var_list(doc: Document, var_list: ET.Element, path: tuple[str, ...]) -> None:
|
|
140
|
+
block = doc.block(*path, kind="keyed", unit="Variable")
|
|
141
|
+
flags = [f.upper() for f in ("constant", "retain", "persistent") if var_list.get(f) == "true"]
|
|
142
|
+
label = " ".join(["VAR_GLOBAL", *flags])
|
|
143
|
+
for var in children(var_list, "variable"):
|
|
144
|
+
block.add(f"{label} {variable_decl(var)}", key=var.get("name"), note=documentation(var))
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def _datatypes(doc: Document, datatypes: ET.Element | None) -> None:
|
|
148
|
+
if datatypes is None:
|
|
149
|
+
return
|
|
150
|
+
for dt in children(datatypes, "dataType"):
|
|
151
|
+
name = dt.get("name", "?")
|
|
152
|
+
base = child(dt, "baseType")
|
|
153
|
+
inner = next(iter(base), None) if base is not None else None
|
|
154
|
+
block = doc.block("DataType " + name, kind="keyed", unit="Member")
|
|
155
|
+
if documentation(dt):
|
|
156
|
+
block.add("Description", key="", note=documentation(dt))
|
|
157
|
+
if inner is not None and local(inner.tag) == "struct":
|
|
158
|
+
for var in children(inner, "variable"):
|
|
159
|
+
block.add(variable_decl(var), key=var.get("name"), note=documentation(var))
|
|
160
|
+
elif inner is not None and local(inner.tag) == "enum":
|
|
161
|
+
for v in children(child(inner, "values"), "value"):
|
|
162
|
+
val = f" := {v.get('value')}" if v.get("value") else ""
|
|
163
|
+
block.add(f"{v.get('name')}{val}", key=v.get("name"))
|
|
164
|
+
else:
|
|
165
|
+
init = value_str(child(dt, "initialValue"))
|
|
166
|
+
block.add(f"{name} : {type_str(base)}" + (f" := {init}" if init else ""), key="(type)")
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
def _var_sections(doc: Document, iface: ET.Element | None, path: tuple[str, ...]) -> None:
|
|
170
|
+
if iface is None:
|
|
171
|
+
return
|
|
172
|
+
block = doc.block(*path, "Interface", kind="keyed", unit="Variable")
|
|
173
|
+
ret = child(iface, "returnType")
|
|
174
|
+
if ret is not None:
|
|
175
|
+
block.add(f"RETURN : {type_str(ret)}", key="(return)")
|
|
176
|
+
for section in iface:
|
|
177
|
+
kind = VAR_SECTIONS.get(local(section.tag))
|
|
178
|
+
if kind is None:
|
|
179
|
+
continue
|
|
180
|
+
flags = [f for f in ("constant", "retain", "persistent") if section.get(f) == "true"]
|
|
181
|
+
label = " ".join([kind, *(f.upper() for f in flags)])
|
|
182
|
+
for var in children(section, "variable"):
|
|
183
|
+
block.add(f"{label} {variable_decl(var)}", key=var.get("name"), note=documentation(var))
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
def _body(doc: Document, body: ET.Element | None, path: tuple[str, ...]) -> None:
|
|
187
|
+
if body is None:
|
|
188
|
+
return
|
|
189
|
+
lang_el = next((el for el in body if local(el.tag) != "documentation"), None)
|
|
190
|
+
if lang_el is None:
|
|
191
|
+
return
|
|
192
|
+
lang = local(lang_el.tag)
|
|
193
|
+
title = (*path[:-1], f"{path[-1]} ({lang})")
|
|
194
|
+
if lang in ("ST", "IL"):
|
|
195
|
+
block = doc.block(*title, kind="sequence", unit="Line")
|
|
196
|
+
holder = child(lang_el, "xhtml")
|
|
197
|
+
source = "".join((holder if holder is not None else lang_el).itertext())
|
|
198
|
+
source = source.strip("\r\n")
|
|
199
|
+
for line in source.splitlines():
|
|
200
|
+
block.add(line.rstrip())
|
|
201
|
+
else:
|
|
202
|
+
block = doc.block(*title, kind="sequence", unit="Element")
|
|
203
|
+
_graphical(lang_el, block)
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
def _graphical(lang_el: ET.Element, block: Block) -> None:
|
|
207
|
+
"""LD / FBD / SFC: one line per element, without layout noise."""
|
|
208
|
+
for el in lang_el:
|
|
209
|
+
kind = local(el.tag)
|
|
210
|
+
if kind in LAYOUT:
|
|
211
|
+
continue
|
|
212
|
+
attrs = " ".join(
|
|
213
|
+
f'{k}="{v}"' for k, v in sorted(el.attrib.items()) if k not in LAYOUT_ATTRS
|
|
214
|
+
)
|
|
215
|
+
parts = [kind + (f" {attrs}" if attrs else "")]
|
|
216
|
+
var = child(el, "variable")
|
|
217
|
+
expr = child(el, "expression")
|
|
218
|
+
if var is not None:
|
|
219
|
+
parts.append(oneline(text(var)))
|
|
220
|
+
elif expr is not None:
|
|
221
|
+
parts.append(oneline(text(expr)))
|
|
222
|
+
elif kind == "comment":
|
|
223
|
+
parts.append(oneline(text(child(el, "content"))))
|
|
224
|
+
elif kind == "block":
|
|
225
|
+
for section in ("inputVariables", "inOutVariables", "outputVariables"):
|
|
226
|
+
names = [
|
|
227
|
+
v.get("formalParameter", "?") for v in children(child(el, section), "variable")
|
|
228
|
+
]
|
|
229
|
+
if names:
|
|
230
|
+
parts.append(f"{section[:-9]}({', '.join(names)})")
|
|
231
|
+
elif kind in ("step", "transition", "jumpStep", "actionBlock"):
|
|
232
|
+
cond = child(el, "condition")
|
|
233
|
+
if cond is not None:
|
|
234
|
+
parts.append(oneline(text(cond)))
|
|
235
|
+
for action in children(el, "action"):
|
|
236
|
+
ref = child(action, "reference")
|
|
237
|
+
parts.append(
|
|
238
|
+
f"{action.get('qualifier', 'N')} "
|
|
239
|
+
+ (ref.get("name", "?") if ref is not None else oneline(text(action)))
|
|
240
|
+
)
|
|
241
|
+
block.add(": ".join(parts) if len(parts) == 2 else " ".join(parts))
|
|
242
|
+
|
|
243
|
+
|
|
244
|
+
def _pous(doc: Document, pous: ET.Element | None) -> None:
|
|
245
|
+
if pous is None:
|
|
246
|
+
return
|
|
247
|
+
summary = doc.block("POUs", kind="keyed", unit="POU")
|
|
248
|
+
for pou in children(pous, "pou"):
|
|
249
|
+
name = pou.get("name", "?")
|
|
250
|
+
ptype = pou.get("pouType", "?")
|
|
251
|
+
summary.add(f"{name} : {ptype}", key=name, note=documentation(pou))
|
|
252
|
+
head = (f"POU {name}",)
|
|
253
|
+
_var_sections(doc, child(pou, "interface"), head)
|
|
254
|
+
_body(doc, child(pou, "body"), (*head, "Body"))
|
|
255
|
+
for action in children(child(pou, "actions"), "action"):
|
|
256
|
+
_body(doc, child(action, "body"), (*head, f"Action {action.get('name')}"))
|
|
257
|
+
for trans in children(child(pou, "transitions"), "transition"):
|
|
258
|
+
_body(doc, child(trans, "body"), (*head, f"Transition {trans.get('name')}"))
|
|
259
|
+
for method in _in_add_data(pou, "method"):
|
|
260
|
+
mhead = (*head, f"Method {method.get('name')}")
|
|
261
|
+
_var_sections(doc, child(method, "interface"), mhead)
|
|
262
|
+
_body(doc, child(method, "body"), (*mhead, "Body"))
|
|
263
|
+
|
|
264
|
+
|
|
265
|
+
def _instances(doc: Document, configurations: ET.Element | None) -> None:
|
|
266
|
+
if configurations is None:
|
|
267
|
+
return
|
|
268
|
+
for conf in children(configurations, "configuration"):
|
|
269
|
+
head = (f"Configuration {conf.get('name')}",)
|
|
270
|
+
_var_sections(doc, conf, head)
|
|
271
|
+
for res in children(conf, "resource"):
|
|
272
|
+
rhead = (*head, f"Resource {res.get('name')}")
|
|
273
|
+
_var_sections(doc, res, rhead)
|
|
274
|
+
block = doc.block(*rhead, "Tasks", kind="keyed", unit="Task")
|
|
275
|
+
for task in children(res, "task"):
|
|
276
|
+
parts = [f"{task.get('name')}"]
|
|
277
|
+
for attr in ("interval", "priority", "single"):
|
|
278
|
+
if task.get(attr):
|
|
279
|
+
parts.append(f"{attr} {task.get(attr)}")
|
|
280
|
+
instances = [
|
|
281
|
+
f"{i.get('name')}:{i.get('typeName')}" for i in children(task, "pouInstance")
|
|
282
|
+
]
|
|
283
|
+
parts.append("runs " + (", ".join(instances) if instances else "-"))
|
|
284
|
+
block.add(", ".join(parts), key=task.get("name"))
|
|
285
|
+
for inst in children(res, "pouInstance"):
|
|
286
|
+
block.add(
|
|
287
|
+
f"{inst.get('name')} : {inst.get('typeName')} (no task)",
|
|
288
|
+
key="inst:" + inst.get("name", "?"),
|
|
289
|
+
)
|
|
290
|
+
if not block.entries:
|
|
291
|
+
doc.blocks.remove(block)
|