feat(plc): a CODESYS script that exports PLCopen XML for Prüfwerk (#165) (#829)
CI / Check (push) Skipped
CI / Agent integration (push) Skipped
CI / Detect Changes (push) Successful in 5s
CI / Deploy Dashboard (push) Skipped
CI / Deploy MCP (push) Skipped
CI / Deploy Docs (push) Successful in 1m10s
CI / Deploy Agent (push) Successful in 6m30s
CI / Check (push) Skipped
CI / Agent integration (push) Skipped
CI / Detect Changes (push) Successful in 5s
CI / Deploy Dashboard (push) Skipped
CI / Deploy MCP (push) Skipped
CI / Deploy Docs (push) Successful in 1m10s
CI / Deploy Agent (push) Successful in 6m30s
This commit was merged in pull request #829.
This commit is contained in:
1 parent
c16e91f981
commit
e911e75c09
5 files changed
+273
-1
No files matched your search
@@ -113,6 +113,15 @@ jobs:
|
||||
env:
|
||||
RUSTC_WRAPPER: ""
|
||||
|
||||
# The repository's Python scripts (the EOL table check, the CODESYS
|
||||
# export script customers download) have offline tests.
|
||||
- name: Script tests
|
||||
run: |
|
||||
command -v python3 >/dev/null || { apt-get update -qq && apt-get install -y -qq --no-install-recommends python3; }
|
||||
python3 -B -I -m unittest discover -s scripts -p "test_*.py"
|
||||
env:
|
||||
RUSTC_WRAPPER: ""
|
||||
|
||||
# Clippy (compiles once, sccache reuses across feature sets). --all-targets
|
||||
# lints test code too; tests may unwrap (clippy.toml), production may not.
|
||||
- name: Clippy (core)
|
||||
|
||||
@@ -100,6 +100,36 @@ project** artifact and pick its format:
|
||||
Attach a **Git repository** artifact to the PLC/SPS target. Prüfwerk clones it and
|
||||
runs the control-logic scan over the exported source in the repo.
|
||||
|
||||
## Exporting PLCopen XML automatically
|
||||
|
||||
Prüfwerk reads the control logic from the PLCopen XML export, never from the
|
||||
binary `.project`. Instead of exporting by hand before every upload or commit,
|
||||
let CODESYS do it with the script
|
||||
[codesys-export-plcopen.py](/downloads/codesys-export-plcopen.py){target="_self" download} (CODESYS
|
||||
Script Engine, no extra packages). It exports every object of the project into
|
||||
one PLCopen XML file, ST as well as graphical FBD/LD/SFC/CFC POUs, and exits with
|
||||
an error if the export holds no POU.
|
||||
|
||||
- **In CODESYS:** open the project, then *Tools → Scripting → Execute Script
|
||||
File* and pick the script. The export is written next to the project as
|
||||
`<project>.plcopen.xml`.
|
||||
- **Without a window**, for example in a build pipeline before the commit or
|
||||
upload:
|
||||
|
||||
```bat
|
||||
"C:\Program Files\CODESYS 3.5.19.50\CODESYS\Common\CODESYS.exe" ^
|
||||
--profile="CODESYS V3.5 SP19 Patch 5" --noUI ^
|
||||
--runscript="C:\tools\codesys-export-plcopen.py" ^
|
||||
--scriptargs:"C:\src\Line.project C:\src\export\Line.plcopen.xml"
|
||||
```
|
||||
|
||||
Use the path and profile name of your CODESYS installation. The first script
|
||||
argument is the project, the second the export file (optional).
|
||||
|
||||
A `.projectarchive` has to be extracted first (*File → Project Archive →
|
||||
Extract Archive*). Commit or upload the export next to the `.projectarchive`:
|
||||
the export carries the control logic, the archive the library SBOM.
|
||||
|
||||
## Best-case git repository layout
|
||||
|
||||
Because the binary `.project` does not diff or merge in git, commit **textual
|
||||
|
||||
@@ -168,7 +168,7 @@ as a clean result: the CRA requirements it checks show as **Nicht geprüft**.
|
||||
| **Abhängigkeiten (SBOM)** | *(manifest)* ohne Lockfile: Die Versionen der Abhängigkeiten und ihre CVEs sind nicht bekannt. | Commit the lockfile (see below). |
|
||||
| e.g. **Firmware-Binäranalyse**, **Container-Analyse**, **Mobile-App-Analyse** | e.g. Firmware-Images werden noch nicht entpackt … | Nothing analyses these files yet; scan the source code instead. |
|
||||
| **SPS-Bibliotheken (SBOM)** | *(file)* ist kein lesbares CODESYS-Projektarchiv. | Export the archive again with *File → Project Archive*, with the referenced libraries ticked. |
|
||||
| **SPS-Projekt (natives Format)** | CODESYS-Projekt im nativen Format, Steuerungslogik nicht geprüft: *(files)* … | Export the POUs as PLCopen XML (*Project → Export PLCopenXML*) and add the export to the target; see [PLC / SPS](/guide/plc). |
|
||||
| **SPS-Projekt (natives Format)** | CODESYS-Projekt im nativen Format, Steuerungslogik nicht geprüft: *(files)* … | Export the POUs as PLCopen XML (*Project → Export PLCopenXML*) and add the export to the target; see [PLC / SPS](/guide/plc), which also has a script that exports it automatically. |
|
||||
| **Einlesen der Dateien** | *(file)* konnte nicht gelesen werden. | Check the file and upload it again under **Bearbeiten**. |
|
||||
| **Archiv-Passwort fehlt (beim Prüfobjekt unter „Bearbeiten“ eingeben)** | *(file)* ist passwortgeschützt. | Enter the password under **Bearbeiten**. |
|
||||
| **Archiv-Passwort falsch (beim Prüfobjekt unter „Bearbeiten“ ändern)** | Das gespeicherte Passwort öffnet *(file)* nicht. | Change the password under **Bearbeiten**. |
|
||||
|
||||
@@ -0,0 +1,109 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""Export a CODESYS project as PLCopen XML for Prüfwerk.
|
||||
|
||||
Prüfwerk reads the control logic of a CODESYS project from its PLCopen XML
|
||||
export, not from the native, binary .project file. This script writes that
|
||||
export with the CODESYS Script Engine, so it can run in a build pipeline
|
||||
instead of by hand (Project > Export PLCopenXML).
|
||||
|
||||
Run it inside the CODESYS development system:
|
||||
|
||||
* interactively: Tools > Scripting > Execute Script File, with the project
|
||||
open; the export is written next to the project;
|
||||
* without a window, for example in CI:
|
||||
|
||||
CODESYS.exe --profile="CODESYS V3.5 SP19 Patch 5" --noUI
|
||||
--runscript="codesys-export-plcopen.py"
|
||||
--scriptargs:"C:\\src\\Line.project C:\\src\\export\\Line.plcopen.xml"
|
||||
|
||||
The first argument is the project, the second the export file (optional:
|
||||
"<project>.plcopen.xml" next to the project).
|
||||
|
||||
A .projectarchive has to be extracted first (File > Project Archive >
|
||||
Extract Archive). The script exports every object of the project with its
|
||||
children into one file; objects CODESYS cannot write as PLCopen XML (devices,
|
||||
for instance) are left out by CODESYS itself. It exits with status 1 when the
|
||||
project cannot be opened or the export holds no POU.
|
||||
|
||||
Runs on the Script Engine's IronPython 2.7 and on Python 3.
|
||||
"""
|
||||
|
||||
from __future__ import print_function
|
||||
|
||||
import os
|
||||
import sys
|
||||
|
||||
# Provided by the CODESYS Script Engine; absent anywhere else.
|
||||
try:
|
||||
projects # noqa: F821 (a Script Engine global)
|
||||
except NameError:
|
||||
projects = None
|
||||
|
||||
|
||||
def fail(message):
|
||||
"""Print `message` and stop with exit status 1."""
|
||||
print("codesys-export-plcopen: " + message)
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
def arguments(argv):
|
||||
"""The project path and the export path from `argv` (both optional)."""
|
||||
args = [a for a in argv[1:] if a.strip()]
|
||||
project = args[0] if args else None
|
||||
export = args[1] if len(args) > 1 else None
|
||||
return project, export
|
||||
|
||||
|
||||
def default_export(project_path):
|
||||
"""`<project>.plcopen.xml` next to the project."""
|
||||
base, _ = os.path.splitext(project_path)
|
||||
return base + ".plcopen.xml"
|
||||
|
||||
|
||||
def pou_count(path):
|
||||
"""How many POUs the export at `path` holds (0 when it cannot be read)."""
|
||||
try:
|
||||
with open(path, "rb") as handle:
|
||||
return handle.read().count(b"<pou ")
|
||||
except (IOError, OSError):
|
||||
return 0
|
||||
|
||||
|
||||
def main(argv):
|
||||
"""Open or take the project, export it, and check the result."""
|
||||
if projects is None:
|
||||
fail("run this script inside CODESYS (Script Engine), not with a plain Python")
|
||||
project_path, export_path = arguments(argv)
|
||||
|
||||
opened_here = False
|
||||
if project_path:
|
||||
if not os.path.isfile(project_path):
|
||||
fail("project not found: " + project_path)
|
||||
project = projects.open(project_path)
|
||||
opened_here = True
|
||||
else:
|
||||
project = projects.primary
|
||||
if project is None:
|
||||
fail("no project given and none open")
|
||||
project_path = project.path
|
||||
|
||||
export_path = export_path or default_export(project_path)
|
||||
folder = os.path.dirname(os.path.abspath(export_path))
|
||||
if not os.path.isdir(folder):
|
||||
os.makedirs(folder)
|
||||
|
||||
try:
|
||||
objects = project.get_children(False)
|
||||
# Every top-level object with its children, into one PLCopen XML file.
|
||||
project.export_xml(objects, export_path, True)
|
||||
finally:
|
||||
if opened_here:
|
||||
project.close()
|
||||
|
||||
pous = pou_count(export_path)
|
||||
if pous == 0:
|
||||
fail("the export holds no POU: " + export_path)
|
||||
print("codesys-export-plcopen: %d POU(s) written to %s" % (pous, export_path))
|
||||
|
||||
|
||||
main(sys.argv)
|
||||
@@ -0,0 +1,124 @@
|
||||
"""Offline tests of docs/public/downloads/codesys-export-plcopen.py.
|
||||
|
||||
The script runs inside the CODESYS Script Engine, which provides the global
|
||||
`projects`. Here it runs with a stand-in that records what the script asks of
|
||||
it and writes a fake export, so the script's own logic is checked: arguments,
|
||||
the default export path, opening and closing, and the POU check.
|
||||
Run: python3 -I -m unittest discover -s scripts -p "test_*.py"
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
SCRIPT = (Path(__file__).resolve().parent.parent
|
||||
/ "docs" / "public" / "downloads" / "codesys-export-plcopen.py")
|
||||
|
||||
|
||||
class FakeProject:
|
||||
"""A ScriptProject that writes `body` as its PLCopen XML export."""
|
||||
|
||||
def __init__(self, path: str, body: bytes) -> None:
|
||||
self.path = path
|
||||
self.body = body
|
||||
self.calls: list[tuple[object, ...]] = []
|
||||
|
||||
def get_children(self, recursive: bool) -> list[str]:
|
||||
self.calls.append(("get_children", recursive))
|
||||
return ["Device", "Application"]
|
||||
|
||||
def export_xml(self, objects: list[str], path: str, recursive: bool) -> None:
|
||||
self.calls.append(("export_xml", tuple(objects), path, recursive))
|
||||
Path(path).write_bytes(self.body)
|
||||
|
||||
def close(self) -> None:
|
||||
self.calls.append(("close",))
|
||||
|
||||
|
||||
class FakeProjects:
|
||||
"""The Script Engine's `projects`: one primary project, or one to open."""
|
||||
|
||||
def __init__(self, project: FakeProject, primary: bool) -> None:
|
||||
self.project = project
|
||||
self.primary = project if primary else None
|
||||
self.opened: list[str] = []
|
||||
|
||||
def open(self, path: str) -> FakeProject:
|
||||
self.opened.append(path)
|
||||
return self.project
|
||||
|
||||
|
||||
def run(argv: list[str], projects: FakeProjects | None) -> int:
|
||||
"""Run the script with `argv`; its exit status (0 when it returns)."""
|
||||
source = SCRIPT.read_text(encoding="utf-8")
|
||||
scope: dict[str, object] = {"__name__": "__main__", "__file__": str(SCRIPT)}
|
||||
if projects is not None:
|
||||
scope["projects"] = projects
|
||||
import sys
|
||||
|
||||
saved = sys.argv
|
||||
sys.argv = argv
|
||||
try:
|
||||
exec(compile(source, str(SCRIPT), "exec"), scope)
|
||||
except SystemExit as stop:
|
||||
return int(stop.code or 0)
|
||||
finally:
|
||||
sys.argv = saved
|
||||
return 0
|
||||
|
||||
|
||||
POUS = b'<?xml version="1.0"?><project><pou name="A"/><pou name="B"/></project>'
|
||||
|
||||
|
||||
class ExportTests(unittest.TestCase):
|
||||
def setUp(self) -> None:
|
||||
self.dir = tempfile.TemporaryDirectory()
|
||||
self.root = Path(self.dir.name)
|
||||
self.project_file = self.root / "Line.project"
|
||||
self.project_file.write_bytes(b"\x00native")
|
||||
|
||||
def tearDown(self) -> None:
|
||||
self.dir.cleanup()
|
||||
|
||||
def test_a_named_project_is_opened_exported_and_closed(self) -> None:
|
||||
out = self.root / "export" / "Line.xml"
|
||||
project = FakeProject(str(self.project_file), POUS)
|
||||
engine = FakeProjects(project, primary=False)
|
||||
|
||||
status = run(["x", str(self.project_file), str(out)], engine)
|
||||
|
||||
self.assertEqual(status, 0)
|
||||
self.assertEqual(engine.opened, [str(self.project_file)])
|
||||
self.assertIn(("export_xml", ("Device", "Application"), str(out), True), project.calls)
|
||||
self.assertEqual(project.calls[-1], ("close",))
|
||||
self.assertTrue(out.is_file(), "the export folder is created")
|
||||
|
||||
def test_the_open_project_is_exported_next_to_itself_and_left_open(self) -> None:
|
||||
project = FakeProject(str(self.project_file), POUS)
|
||||
|
||||
status = run(["x"], FakeProjects(project, primary=True))
|
||||
|
||||
self.assertEqual(status, 0)
|
||||
self.assertTrue((self.root / "Line.plcopen.xml").is_file())
|
||||
self.assertNotIn(("close",), project.calls)
|
||||
|
||||
def test_an_export_without_a_pou_fails(self) -> None:
|
||||
project = FakeProject(str(self.project_file), b"<project/>")
|
||||
status = run(["x", str(self.project_file)], FakeProjects(project, primary=False))
|
||||
self.assertEqual(status, 1)
|
||||
|
||||
def test_a_missing_project_or_none_open_fails(self) -> None:
|
||||
project = FakeProject(str(self.project_file), POUS)
|
||||
missing = os.path.join(self.dir.name, "Missing.project")
|
||||
self.assertEqual(run(["x", missing], FakeProjects(project, primary=False)), 1)
|
||||
self.assertEqual(run(["x"], FakeProjects(project, primary=False)), 1)
|
||||
|
||||
def test_outside_codesys_it_says_so(self) -> None:
|
||||
self.assertEqual(run(["x"], None), 1)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in new issue
Block a user