From e911e75c09b38c1780a9d1fa07fb8fbeaa621730 Mon Sep 17 00:00:00 2001 From: Sharang Parnerkar Date: Wed, 4 Nov 2026 11:10:09 +0000 Subject: [PATCH] =?UTF-8?q?feat(plc):=20a=20CODESYS=20script=20that=20expo?= =?UTF-8?q?rts=20PLCopen=20XML=20for=20Pr=C3=BCfwerk=20(#165)=20(#829)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .gitea/workflows/ci.yml | 9 ++ docs/guide/plc.md | 30 +++++ docs/guide/scanning.md | 2 +- .../downloads/codesys-export-plcopen.py | 109 +++++++++++++++ scripts/test_codesys_export.py | 124 ++++++++++++++++++ 5 files changed, 273 insertions(+), 1 deletion(-) create mode 100644 docs/public/downloads/codesys-export-plcopen.py create mode 100644 scripts/test_codesys_export.py diff --git a/.gitea/workflows/ci.yml b/.gitea/workflows/ci.yml index ab228bd..b762865 100644 --- a/.gitea/workflows/ci.yml +++ b/.gitea/workflows/ci.yml @@ -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) diff --git a/docs/guide/plc.md b/docs/guide/plc.md index a97d5d4..39e7ab7 100644 --- a/docs/guide/plc.md +++ b/docs/guide/plc.md @@ -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 + `.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 diff --git a/docs/guide/scanning.md b/docs/guide/scanning.md index a0bb427..cc1457a 100644 --- a/docs/guide/scanning.md +++ b/docs/guide/scanning.md @@ -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**. | diff --git a/docs/public/downloads/codesys-export-plcopen.py b/docs/public/downloads/codesys-export-plcopen.py new file mode 100644 index 0000000..b80df2b --- /dev/null +++ b/docs/public/downloads/codesys-export-plcopen.py @@ -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: + ".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): + """`.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" 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'' + + +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"") + 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()