# -*- 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"