EcoStruxure Machine Expert version 1.1 does not support the M258, LMC058 and LMC078 controllers.

Project

Overview

Since the examples for this namespace are relatively short and self-explanatory, their meaning is not explained in detail. Complete examples are provided, where appropriate.

New Project

This method creates a new project.

It consists of 2 parameters:

oa string specifying the location where the project will be stored

oa boolean parameter: If TRUE, the project will be the new primary project. This parameter is optional, the default value is TRUE.

The method returns the IProject instance (refer to the specification in the document Automation Platform SDK) which can be used for further steps.

import os
 
try:
    # Clean up any open project
    if projects.primary:
        projects.primary.close()
 
    # Define the new file name for the project
    project_name = "Example.project"
 
    # Define the new path where the new project should be stored
    project_path = r"C:\Python"
 
    # Create the new project
    proj = projects.create(os.path.join(project_path, project_name), True)
 
    # Save the project to the specified path
    proj.save()
except Exception as exception:
    print("Error: " + str(exception))
    if not system.trace:
       print("Please turn on the 'Script Tracing' function to get detailed information about the script execution.")

Load Project

This method loads a project. Any open projects will not be closed.

The first parameter specifies the path of the project that will be loaded.

import os
 
try:
    # Clean up any open project
    if projects.primary:
        projects.primary.close()
 
    # Define the file name for the project
    project_name = "Example.project"
 
    # Define the path where the project is stored
    project_path = r"C:\Python"
 
    # Load the existing project
    proj = projects.open(os.path.join(project_path, project_name))
except Exception as exception:
    print("Error: " + str(exception))
    if not system.trace:
       print("Please turn on the 'Script Tracing' function to get detailed information about the script execution.")

Save Project

This method saves the project at its physical location.

# Save project
projects.primary.save()

Save Archive

This method saves the project as an archive. The additional categories which are selected by default are included, but no extra files.

The first parameter specifies the path where the archive will be saved.

import os
 
# Define the new file name for the archive
archive_name = "Example.archive"
 
# Define the new path where the archive should be stored
archive_path = r"C:\Python"
 
# Save archive with the default values
projects.primary.save_archive(os.path.join(archive_path, archive_name))

Close Project

This method closes the project. If there are unsaved changes in this project, these changes will be discarded.

# Clean up any open project:
if projects.primary:
    projects.primary.close()

Find Objects

This method finds objects matching the given name.

It consists of 2 parameters:

oThe first parameter is the name of the object that is searched.

oThe second parameter specifies whether a recursive search is performed. This parameter is optional, the default value is FALSE. This method returns a collection of objects.

# Search for
result_list = projects.primary.find('MyController', True)
 
for result in result_list:
    print("Object " + result.get_name() + " found with Guid " + str(result.guid))

Names are not unique in the tree. This has the effect that several objects can be found. The search is against the nonlocalized name.

Native Import

This method imports the specified files in the native XML format in the top level of this project.

import os
 
# Specify the project file name
project_name = "NativeImport.project"
 
# Define the path where the project should be/is stored
project_path = r"C:\Python"
 
# Define the path where the exported objects are be stored
object_path = os.path.join(project_path, "Objects")
 
# Create the import reporter
class Handler(NativeImportHandler):
    def conflict(self, name, obj, guid):
        print("Object already exists: " + name)
        return NativeImportResolve.skip
 
    def progress(self, name, obj, exception):
        print("in progess: " + name)
 
    def skipped(self, list):
        return
 
def import_filter(name, guid, type, path):
    # Workaround, skip the project settings object because we cant import it
    if(type == "_3S.CoDeSys.Engine.WorkspaceObject"):
        return False
    return True
 
try:
    # Clean up any open project
    if projects.primary:
        projects.primary.close()
 
    # Create the new project
    project_reference = projects.create(os.path.join(project_path, project_name), True)
 
    files = os.listdir(object_path)
 
    # Create the importer instance.
    handler = Handler()
 
    for file in files:
        file_path = os.path.join(object_path, file)
        project_reference.import_native(file_path, import_filter, handler)
 
    project_reference.save()
 
except Exception as exception:
    print("Error: " + str(exception))
    if not system.trace:
       print("Please turn on the 'Script Tracing' function to get detailed information about the script execution.")

PLCOpenXML Import

This method imports the contents of the specified PLCopenXML file into the top level of the project.

import os
 
# Specify the project file name
project_name = "PLCOpenXMLImport.project"
 
# Define the path where the project should be/is storedproject_path = r"C:\Python"
 
# Define the file where the exported object is stored
file_name = os.path.join(project_path, r"Objects\MyController.xml")
 
# Create the import reporter
class Reporter(ImportReporter):
    def error(self, message):
        system.write_message(Severity.Error, message)
    def warning(self, message):
        system.write_message(Severity.Warning, message)
    def resolve_conflict(self, obj):
        return ConflictResolve.Copy
    def added(self, obj):
        print("added: ", obj)
    def replaced(self, obj):
        print("replaced: ", obj)
    def skipped(self, obj):
        print("skipped: ", obj)
    @property
    def aborting(self):
        return False
 
try:
    # Clean up any open project
    if projects.primary:
        projects.primary.close()
 
    # Create the reporter instance
    reporter = Reporter()
 
    # Create the new project
    project_reference = projects.create(os.path.join(project_path, project_name), True)
 
    # Import the data into the project
    project_reference.import_xml(reporter, file_name)
 
    # Save the project to the specified path
    project_reference.save()
except Exception as exception:
    print("Error: " + str(exception))
    if not system.trace:
       print("Please turn on the 'Script Tracing' function to get detailed information about the script execution.")

Native Export

This method exports the given objects in native format into a string, or a file at the given path. The non-exportable objects are detected as an error, but the export continues.

import sys,io,os
 
# Specify the project file name
project_name = "Example.project"
 
# Define the path where the project should be/is stored
project_path = r"C:\Python"
 
# Define the path where the exported objects should be stored
object_path = os.path.join(project_path, "Objects")
 
def collect_objects(project_reference):
    # List that stores all POU nodes
    project_objects = []
 
    # Collect all the leaf nodes.
    for node in project_reference.get_children(True):
        project_objects.append(node)
 
    for i in project_objects:
        print("Found: ", i.type, i.guid, i.get_name())
    return project_objects
 
def export_objects(collected_objects, project_reference):
    if not os.path.exists(object_path):
        os.makedirs(object_path)
 
    # Export the files.
    for candidate in collected_objects:
        # Create a list of objects to export:
        # The object itself
        objects = [candidate]
 
        # And sub-objects (POUs can have actions, properties, ...)
        objects.extend(candidate.get_children(True))
 
        # And the parent folders.
        parent = candidate.parent
        while ((not parent.is_root) and parent.is_folder):
            objects.append(parent)
            parent = parent.parent
 
        # Create a unique file name
        filename = os.path.join(object_path, "%s__%s.export" % (candidate.get_name(), candidate.guid))
 
        # Print some user information
        print("Exporting " + str(len(objects)) + " objects to: " + filename)
 
        # And actually export the project
        project_reference.export_native(objects, filename)

try:
    # Clean up any open project
    if projects.primary:
        projects.primary.close()
 
    # Open a project first
    project_reference = projects.open(os.path.join(project_path, project_name))
 
    # Collect the objects
    collected_objects = collect_objects(project_reference)
 
    export_objects(collected_objects, project_reference)
except Exception as exception:
    print("Error: " + str(exception))
    if not system.trace:
       print("Please turn on the 'Script Tracing' function to get detailed information about the script execution.")

PLCOpenXML Export

This method exports the given objects in PLCopenXML format into a string, or a file at the given path. The non-exportable objects are detected as an error, but the export continues.

import os
 
# Specify the object which should be exported
object_name = "MyController"
 
# Define the path where the exported objects should be stored
object_path = r"C:\Python\Objects"
 
# Define the printing function
def print_tree(treeobj, depth=0):
    name = treeobj.get_name(False)
    if treeobj.is_device:
        deviceid = treeobj.get_device_identification()
        print("{0} - {1} {2}".format(" "*depth, name, deviceid))
 
    for child in treeobj.get_children(False):
        print_tree(child, depth+1)
 
# Create the export reporter
class Reporter(ExportReporter):
    def error(self, message):
        system.write_message(Severity.Error, message)
    def warning(self, message):
        system.write_message(Severity.Warning, message)
    def nonexportable(self, message):
        print(message)
    @property
    def aborting(self):
        return False
 
try:
    # Get the project reference of the currently opened project
    project_reference = projects.primary
 
    # Get a reporter instance
    reporter = Reporter()
 
    # Print all devices in the project
    for obj in project_reference.get_children():
        print_tree(obj)
 
    # Finds the object in the project, and return the first result
    device = project_reference.find(object_name, True)
 
    if device != None:
        filename = os.path.join(object_path, device[0].get_name() + ".xml")
 
        # Exports the object to the hard drive
        project_reference.export_xml(reporter, device, filename, True, True)
 
except Exception as exception:
    print("Error: " + str(exception))
    if not system.trace:
       print("Please turn on the 'Script Tracing' function to get detailed information about the script execution.")