Ticket #5: Export as PLCOpen XML
Scripting
snippets
(Ticket)
class ER(ExportReporter): def error(self, object, message): system.write_message(Severity.Error, "Error exporting %s: %s" % (object, message)) def warning(self, object, message): system.write_message(Severity.Warning, "Warning exporting %s: %s" % (object, message)) def nonexportable(self, object): system.write_message(Severity.Information, "Object not exportable: %s" % object) @property def aborting(self): return False; reporter = ER() proj = projects.open(filename) proj.export_xml(reporter, proj.get_children(False), tempname, recursive = True) proj.close() Export as PLCOpen XML Scripting 0 snippets Ticket tickets Export as PLCOpen XML 2020-02-08 02:18:39.201000 Unlicense False 0 ingo Ticket #5: Export as PLCOpen XML 0 False /tol/scripting/snippets/5/ None 2020-02-07 22:40:17.745000 None 5 scripting class ER(ExportReporter): def error(self, object, message): system.write_message(Severity.Error, "Error exporting %s: %s" % (object, message)) def warning(self, object, message): system.write_message(Severity.Warning, "Warning exporting %s: %s" % (object, message)) def nonexportable(self, object): system.write_message(Severity.Information, "Object not exportable: %s" % object) @property def aborting(self): return False; reporter = ER() proj = projects.open(filename) proj.export_xml(reporter, proj.get_children(False), tempname, recursive = True) proj.close() False False 2
Last updated: 2020-02-08
Ticket #6: Modify Properties / Compiler defines
Scripting
snippets
(Ticket)
# Find Object VICTIM in projecttree victim = projects.primary.find("VICTIM", True)[0] props = victim.build_properties props.external = not props.external props.enable_system_call = not props.enable_system_call props.link_always = not props.link_always props.exclude_from_build = not props.exclude_from_build if ";FOOBAR" in props.compiler_defines: props.compiler_defines = props.compiler_defines.replace(";FOOBAR","") else: props.compiler_defines = props.compiler_defines + ";FOOBAR" Modify Properties / Compiler defines Scripting 0 snippets Ticket tickets Modify Properties / Compiler defines 2020-02-08 02:18:39.206000 Unlicense False 0 ingo Ticket #6: Modify Properties / Compiler defines 0 False /tol/scripting/snippets/6/ None 2020-02-08 01:44:18.785000 None 6 scripting # Find Object VICTIM in projecttree victim = projects.primary.find("VICTIM", True)[0] props = victim.build_properties props.external = not props.external props.enable_system_call = not props.enable_system_call props.link_always = not props.link_always props.exclude_from_build = not props.exclude_from_build if ";FOOBAR" in props.compiler_defines: props.compiler_defines = props.compiler_defines.replace(";FOOBAR","") else: props.compiler_defines = props.compiler_defines + ";FOOBAR" False False 2
Last updated: 2020-02-08
Ticket #7: SVN checkout
Scripting
snippets
(Ticket)
def set_username(req): req.username = username req.password = password req.save = True # Optional svn.auth_username_password += set_username svn.checkout(url, dir, filename) proj = projects.primary proj.save_as(filename) SVN checkout Scripting 0 snippets Ticket tickets SVN checkout 2020-02-08 02:18:39.205000 Unlicense False 0 ingo Ticket #7: SVN checkout 0 False /tol/scripting/snippets/7/ None 2020-02-08 01:46:04.388000 None 7 scripting def set_username(req): req.username = username req.password = password req.save = True # Optional svn.auth_username_password += set_username svn.checkout(url, dir, filename) proj = projects.primary proj.save_as(filename) False False 2
Last updated: 2020-02-08
Ticket #8: SVN commit
Scripting
snippets
(Ticket)
def set_username(req): req.username = username req.password = password req.save = True # Optional svn.auth_username_password += set_username svn.commit(message) SVN commit Scripting 0 snippets Ticket tickets SVN commit 2020-02-08 02:18:39.200000 Unlicense False 0 ingo Ticket #8: SVN commit 0 False /tol/scripting/snippets/8/ None 2020-02-08 01:47:04.102000 None 8 scripting def set_username(req): req.username = username req.password = password req.save = True # Optional svn.auth_username_password += set_username svn.commit(message) False False 2
Last updated: 2020-02-08
Ticket #9: SVN update
Scripting
snippets
(Ticket)
def set_username(req): req.username = username req.password = password req.save = True # Optional svn.auth_username_password += set_username svn.update() SVN update Scripting 0 snippets Ticket tickets SVN update 2020-02-08 02:18:39.202000 Unlicense False 0 ingo Ticket #9: SVN update 0 False /tol/scripting/snippets/9/ None 2020-02-08 01:48:24.555000 None 9 scripting def set_username(req): req.username = username req.password = password req.save = True # Optional svn.auth_username_password += set_username svn.update() False False 2
Last updated: 2020-02-08
Ticket #10: Add Device with Task Configuration
Scripting
snippets
(Ticket)
# add device proj.add('PLC', devId) apps = proj.find('Application', True) if len(apps) > 0: tc = apps[0].create_task_configuration() # add task task = tc.create_task('Task') task.pous.add('PLC_PRG') Add Device with Task Configuration Scripting 0 snippets Ticket tickets Add Device with Task Configuration 2020-02-08 02:18:39.205000 Unlicense False 0 ingo Ticket #10: Add Device with Task Configuration 0 False /tol/scripting/snippets/10/ None 2020-02-08 01:49:48.651000 None 10 scripting # add device proj.add('PLC', devId) apps = proj.find('Application', True) if len(apps) > 0: tc = apps[0].create_task_configuration() # add task task = tc.create_task('Task') task.pous.add('PLC_PRG') False False 1
Last updated: 2020-02-08
Ticket #11: Check compile errors of libraries
Scripting
snippets
(Ticket)
CompileCategory = Guid("{97F48D64-A2A3-4856-B640-75C046E37EA9}") # Clear messages from Build category system.clear_messages(CompileCategory) projects.primary.check_all_pool_objects() # Get message objects which contain all the data severities = { Severity.FatalError : "Fatal error", Severity.Error : "Error", Severity.Warning : "Warning", Severity.Information : "Information", Severity.Text : "Text" } msgs = system.get_message_objects(CompileCategory, Severity.FatalError|Severity.Error) for msg in msgs: sev = severities[msg.severity] print("{} {}{}: {}".format(sev, msg.prefix, msg.number, msg.text) Check compile errors of libraries Scripting 0 snippets Ticket tickets Check compile errors of libraries 2020-02-08 02:18:39.204000 Unlicense False 0 ingo Ticket #11: Check compile errors of libraries 0 False /tol/scripting/snippets/11/ None 2020-02-08 01:50:49.600000 None 11 scripting CompileCategory = Guid("{97F48D64-A2A3-4856-B640-75C046E37EA9}") # Clear messages from Build category system.clear_messages(CompileCategory) projects.primary.check_all_pool_objects() # Get message objects which contain all the data severities = { Severity.FatalError : "Fatal error", Severity.Error : "Error", Severity.Warning : "Warning", Severity.Information : "Information", Severity.Text : "Text" } msgs = system.get_message_objects(CompileCategory, Severity.FatalError|Severity.Error) for msg in msgs: sev = severities[msg.severity] print("{} {}{}: {}".format(sev, msg.prefix, msg.number, msg.text) False False 2
Last updated: 2020-02-08
Ticket #13: Add device to project
Scripting
snippets
(Ticket)
devId = None devices = device_repository.get_all_devices("CODESYS Control Win V3") for device in devices: devId = device.device_id proj = projects.primary # delete existing testdev device existing = proj.find('testdev') if len(existing) > 0: existing[0].remove() # add device proj.add('testdev', devId) apps = proj.find('Application', True) if len(apps) > 0: app = apps[0] tc = app.create_task_configuration() Add device to project Scripting 0 snippets Ticket tickets Add device to project 2020-02-08 16:01:54.247000 Unlicense False 0 ingo Ticket #13: Add device to project 0 False /tol/scripting/snippets/13/ None 2020-02-08 16:01:54.134000 None 13 scripting devId = None devices = device_repository.get_all_devices("CODESYS Control Win V3") for device in devices: devId = device.device_id proj = projects.primary # delete existing testdev device existing = proj.find('testdev') if len(existing) > 0: existing[0].remove() # add device proj.add('testdev', devId) apps = proj.find('Application', True) if len(apps) > 0: app = apps[0] tc = app.create_task_configuration() False False 1
Last updated: 2020-02-08
Ticket #14: Login and monitor variable
Scripting
snippets
(Ticket)
# login onlineapp = online.create_online_application(app) try: onlineapp.login(OnlineChangeOption.Try, True) except: print("Error: compile error") return False # run program onlineapp.start() # wait until project finishes for timeout in range(10): system.delay(1000) xready = onlineapp.read_value("PRG_RUNTEST.xReady") if str(xready) == "TRUE": break # check for error xerror = onlineapp.read_value("PRG_RUNTEST.xError") ~~~Login and monitor variable Scripting 0 snippets Ticket tickets Login and monitor variable 2020-02-08 16:04:51.316000 Unlicense False 0 ingo Ticket #14: Login and monitor variable 0 False /tol/scripting/snippets/14/ None 2020-02-08 16:04:51.212000 None 14 scripting ~~~python # login onlineapp = online.create_online_application(app) try: onlineapp.login(OnlineChangeOption.Try, True) except: print("Error: compile error") return False # run program onlineapp.start() # wait until project finishes for timeout in range(10): system.delay(1000) xready = onlineapp.read_value("PRG_RUNTEST.xReady") if str(xready) == "TRUE": break # check for error xerror = onlineapp.read_value("PRG_RUNTEST.xError") False False 1
Last updated: 2020-02-08
Ticket #15: Searching for an object example
Scripting
snippets
(Ticket)
# Search recursivly for 'TheObjectIWantToSearchFor' Recursive = True result_list = projects.primary.find('TheObjectIWantToSearchFor', Recursive) for result in result_list: print("Object " + result.get_name() + " found with Guid " + str(result.guid)) ~~~Searching for an object example Scripting 0 snippets Ticket tickets Searching for an object example 2020-02-24 20:59:08.832000 Unlicense False 0 aliazzz Ticket #15: Searching for an object example 0 False /tol/scripting/snippets/15/ None 2020-02-08 18:33:58.464000 None 15 scripting Search recursivly for 'TheObjectIWantToSearchFor' Recursive = True result_list = projects.primary.find('TheObjectIWantToSearchFor', Recursive) for result in result_list: print("Object " + result.get_name() + " found with Guid " + str(result.guid)) ~~~ False False 2
Last updated: 2020-02-24
Ticket #16: Disable System Prompts and Dialogs
Scripting
snippets
(Ticket)
Disable prompts, as those are enabled in UI mode by default: system.prompt_handling = PromptHandling.None ~~~Disable System Prompts and Dialogs Scripting 0 snippets Ticket tickets Disable System Prompts and Dialogs 2020-04-21 07:28:02.722000 Unlicense False 0 ingo Ticket #16: Disable System Prompts and Dialogs 0 False /tol/scripting/snippets/16/ None 2020-04-21 07:27:37.613000 None 16 scripting Disable prompts, as those are enabled in UI mode by default: system.prompt_handling = PromptHandling.None ~~~ False False 2
Last updated: 2020-04-21
Ticket #17: Handle Answers of Dialogs
Scripting
snippets
(Ticket)
Log Message Keys: system.prompt_handling |= PromptHandling.LogMessageKeys Define Reaction for specific messages: system.prompt_answers["EnterDebugMode_Prompt"]=PromptResult.OK ~~~Handle Answers of Dialogs Scripting 0 snippets Ticket tickets Handle Answers of Dialogs 2020-04-21 07:31:44.928000 Unlicense False 0 ingo Ticket #17: Handle Answers of Dialogs 0 False /tol/scripting/snippets/17/ None 2020-04-21 07:31:37.976000 None 17 scripting Log Message Keys: system.prompt_handling |= PromptHandling.LogMessageKeys Define Reaction for specific messages: system.prompt_answers["EnterDebugMode_Prompt"]=PromptResult.OK ~~~ False False 2
Last updated: 2020-04-21
Ticket #18: Installation of missing libraries
Scripting
snippets
(Ticket)
Script that lists all the library dependencies: proj = projects.open(projectPath) objects = proj.get_children(recursive=True) for candidate in objects: if candidate.is_libman: for libref in iter(candidate): if libref.is_placeholder: if libref.effective_resolution is not None: libInfo = str(libref.effective_resolution) libMissing = False elif libref.default_resolution is not None: libInfo = str(libref.default_resolution) libMissing = True elif libref.is_managed: libInfo = str(libref.managed_library) else: libInfo = str(libref.name) Script that downloads the libraries: libraryServers = ["https://store.codesys.com/CODESYSLibs/"] for server in libraryServers: libraryFileName = None url = str("%s%s/%s/%s/" % (server, data['supplier'], data['name'], data['version'])) response = requests.get(url + "index") fileUrl = str("%s%s" % (url, libraryFileName)).rstrip() response = requests.get(fileUrl) f.write(response.content) Script that installs the downloaded libraries: repo = librarymanager.repositories[0] librarymanager.install_library(absLibPath, repo, overwrite=True) Installation of missing libraries Scripting 0 snippets Ticket tickets Installation of missing libraries 2020-07-14 11:16:24.475000 Unlicense False 0 jelle Ticket #18: Installation of missing libraries 0 False /tol/scripting/snippets/18/ None 2020-07-14 10:04:51.779000 None 18 libraries missing download install scripting Script that lists all the library dependencies: proj = projects.open(projectPath) objects = proj.get_children(recursive=True) for candidate in objects: if candidate.is_libman: for libref in iter(candidate): if libref.is_placeholder: if libref.effective_resolution is not None: libInfo = str(libref.effective_resolution) libMissing = False elif libref.default_resolution is not None: libInfo = str(libref.default_resolution) libMissing = True elif libref.is_managed: libInfo = str(libref.managed_library) else: libInfo = str(libref.name) Script that downloads the libraries: libraryServers = ["https://store.codesys.com/CODESYSLibs/"] for server in libraryServers: libraryFileName = None url = str("%s%s/%s/%s/" % (server, data['supplier'], data['name'], data['version'])) response = requests.get(url + "index") fileUrl = str("%s%s" % (url, libraryFileName)).rstrip() response = requests.get(fileUrl) f.write(response.content) Script that installs the downloaded libraries: repo = librarymanager.repositories[0] librarymanager.install_library(absLibPath, repo, overwrite=True) False False 2
Last updated: 2020-07-14
IndexMain 2020-02-08 02:22:13.048833
Scripting
home
(WikiPage)
Home Snippets
Last updated: 2020-02-08
Snippets 2020-02-08 02:21:37.805218
Scripting
home
(WikiPage)
[[include IndexMain (not found)]] Editing of Python scripts Help.codesys.com Project Importing the CODESYS scripting objects into python Open project Iterate Device Tree Create an FB Create a DUT Export as PLCOpen XML Modify Properties / Compiler defines Autogenerate Devices SVN checkout SVN commit SVN update Add Device with Task Configuration Compiler Check compile errors of libraries External Tools Excel Editing of Python scripts CODESYS does not posses an internal Python script editor. To edit python scripts there are more then enough alternatives available. Offcourse you are free to use any tool that you wish, but we can give some suggestions (not exhaustive): Notepad++ 1. + Very small but variable installation footprint (dependent on extension choices) 2. - Only provides intellisense help on standard libraries 3. + Syntax highlighting 4. + Indentation help 5. + Quickly edit single files 6. - Less suited for larger projects VS.Net Select the "Visual Studio IDE Community" version, install IronPython support via the installation proces. 1. - Large but variable installation footprint (heavily dependent on installation/extension choices) 2. + Provides very good intellisense help 3. + Syntax highlighting 4. + Indentation help 5. - Not well suited to edit single files 6. + Suited for large projects PyCharm 1. + Medium but variable sized installation footprint (dependent on installation/extension choices) 2. + Provides very good intellisense 3. + Syntax highlighting 4. + Indentation help 5. - Not well suited to edit single files 6. + Suited for larger projects TIP: you can opt to install notepad++ and VS.NET in tandem as they complement each other well *Visual Studio Code can be an alternative, however, the CFORGE tool is developped using VS.NET, so your mileage may vary. Help.codesys.com As of CODESYS version 3.5.14.0, https://help.codesys.com/webapp/idx-scriptingengine;product=ScriptEngine;version=3.5.14.0 offers an exthaustive overview of the various available scripting objects and their possibilities. Project The provided codesnippets are conceptual examples without any liability. Importing the CODESYS scripting objects into python // Simple all-everything import: from scriptengine import * // Import only the needed objects: from scriptengine import ImportReporter, OnlineChangeOption // Import only the module itself: import scriptengine // and then later in the code somewhere: class Reporter(scriptengine.ImportReporter): Open project proj = projects.open(filepath) Iterate Device Tree def printtree_rec(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): printtree_rec(child, depth+1) def printTree(proj): for obj in proj.get_children(): printtree_rec(obj) Create an FB Only Structured Text can be edited directly! For the graphical languages you have to import the POU from PLCopenXML or the codesys native format. See IScriptTextualObjectMarker, IScriptObjectWithTextualDeclaration, IScriptObjectWithTextualImplementation and IScriptTextDocument for the textual language and the methods importxml() and importnative() from IScriptObject2 and IScriptProject2 for the import. Find the Scripting object, for example withfind(), and use the method remove() to delete an object. proj = projects.primary found = proj.find("Application", True) app = found[0] # Create FB mypou = app.create_pou("MyPou") # Change declaration of the FB implementation = mypou.textual_declaration.replace("""FUNCTION_BLOCK MyPou VAR_INPUT iValue : INT; END_VAR VAR_OUTPUT END_VAR VAR END_VAR""") # Change implementation of the FB mypou.textual_implementation.replace("""iValue := iValue + 1;""") # Add method to FB dosomething = mypou.create_method("DoSomething", "INT") # Change declaration of the method dosomething.textual_declaration.replace("""METHOD DoSomething : INT VAR_INPUT iVal1 : INT; iVal2 : INT; END_VAR""") # Change implementation of the method dosomething.textual_implementation.replace("""DoSomething := iVal1 + iVal2;""") # Find the pou and delete it found = app.find("MyPou") if found and len(found) == 1: found[0].remove() else: print("POU 'MyPou' was not found" Create a DUT proj = projects.primary found = proj.find("Application", True) app = found[0] myDUT = app.create_dut("STATE", DutType.Enumeration) # add declaration of the ENUM # here parameter "DutType" can be DutType.Structure(default), DutType.Enumeration , DutType.Alias, DutType.Union . implementation = myDUT.textual_declaration.replace("""TYPE STATE : ( Examples_INT := 0, (* *) SEND, (* Send messages *) READ, (* Receive messages *) ERROR (* error single *) ); END_TYPE""") Export as PLCOpen XML class ER(ExportReporter): def error(self, object, message): system.write_message(Severity.Error, "Error exporting %s: %s" % (object, message)) def warning(self, object, message): system.write_message(Severity.Warning, "Warning exporting %s: %s" % (object, message)) def nonexportable(self, object): system.write_message(Severity.Information, "Object not exportable: %s" % object) @property def aborting(self): return False; reporter = ER() proj = projects.open(filename) proj.export_xml(reporter, proj.get_children(False), tempname, recursive = True) proj.close() Modify Properties / Compiler defines # Find Object VICTIM in projecttree victim = projects.primary.find("VICTIM", True)[0] props = victim.build_properties props.external = not props.external props.enable_system_call = not props.enable_system_call props.link_always = not props.link_always props.exclude_from_build = not props.exclude_from_build if ";FOOBAR" in props.compiler_defines: props.compiler_defines = props.compiler_defines.replace(";FOOBAR","") else: props.compiler_defines = props.compiler_defines + ";FOOBAR" Autogenerate Devices Example of generating a modbus configuration from a configuration file: print "Current project." proj = projects.primary # Search for all top-level devices in project for dev in proj.get_children(): if dev.is_device: f = open("C:\_d\Python\ModbusImport\ModbusConfiguratie.txt", "r") for line in f: tok = line.split(' ') print tok[1], tok[0] if "(COM)" in tok[1]: dev.add(tok[0], DeviceID(92, "0000 0001", "3.4.0.0")) subnodes = dev.get_children() master = subnodes[len(subnodes) - 1] elif "(ModbusMaster)" in tok[1]: master.add(tok[0], DeviceID(90, "0000 0002", "3.4.3.0")) subnodes = master.get_children() coupler = subnodes[len(subnodes) - 1] elif "(ModbusSlave)" in tok[1]: coupler.add(tok[0], DeviceID(91, "0000 0001", "3.4.0.0")) print "script finished." SVN checkout def set_username(req): req.username = username req.password = password req.save = True # Optional svn.auth_username_password += set_username svn.checkout(url, dir, filename) proj = projects.primary proj.save_as(filename) SVN commit def set_username(req): req.username = username req.password = password req.save = True # Optional svn.auth_username_password += set_username svn.commit(message) SVN update def set_username(req): req.username = username req.password = password req.save = True # Optional svn.auth_username_password += set_username svn.update() Add Device with Task Configuration # add device proj.add('PLC', devId) apps = proj.find('Application', True) if len(apps) > 0: tc = apps[0].create_task_configuration() # add task task = tc.create_task('Task') task.pous.add('PLC_PRG') Compiler Check compile errors of libraries CompileCategory = Guid("{97F48D64-A2A3-4856-B640-75C046E37EA9}") # Clear messages from Build category system.clear_messages(CompileCategory) projects.primary.check_all_pool_objects() # Get message objects which contain all the data severities = { Severity.FatalError : "Fatal error", Severity.Error : "Error", Severity.Warning : "Warning", Severity.Information : "Information", Severity.Text : "Text" } msgs = system.get_message_objects(CompileCategory, Severity.FatalError|Severity.Error) for msg in msgs: sev = severities[msg.severity] print("{} {}{}: {}".format(sev, msg.prefix, msg.number, msg.text) External Tools Excel Frame for interworking with excel: # load relevant clr import clr clr.AddReferenceByName("Microsoft.Office.Interop.Excel, Version=11.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c") clr.AddReference("System") # import garbage collector from System import GC # import .NET library for Excel from Microsoft.Office.Interop import Excel excel = Excel.ApplicationClass() excel.Visible = False # makes the Excel application visible to the user excel.DisplayAlerts = False from System.Runtime.InteropServices import Marshal #excel = Marshal.GetActiveObject("Excel.Application") # <-- not sure about that one # finding a workbook that's already open workbooks = [wb for wb in excel.Workbooks if wb.FullName == filepath] if workbooks: workbook = workbooks[0] else: workbooks = excel.Workbooks workbook = workbooks.Open(filepath,False,True) workbook.Saved = True # select work sheet worksheets = workbook.Worksheets(sheetname) worksheet = worksheets.Range(worksheets.Cells(1,1),worksheets.Cells(maxRow,maxCol)) worksheetDict = worksheet.Value2 ... # Close workbook after readout workbook.Close(False) excel.Application.Quit() excel.Quit() Marshal.ReleaseComObject(worksheet) Marshal.ReleaseComObject(worksheets) Marshal.ReleaseComObject(workbook) Marshal.ReleaseComObject(workbooks) Marshal.ReleaseComObject(excel) workbook = None workbooks = None worksheet = None worksheets = None excel = None GC.Collect(); GC.WaitForPendingFinalizers();
Last updated: 2020-02-08
Home (version 2) discussion
Scripting
home
(Thread)
Home (version 2) discussion
Last updated: 2018-10-29
(no subject)
Scripting
snippets
(Thread)
Last updated: 2020-07-14
Snippets (version 54) discussion
Scripting
home
(Thread)
Snippets (version 54) discussion
Last updated: 2020-01-06
(no subject)
Scripting
snippets
(Thread)
Last updated: 2020-02-08
(no subject)
Scripting
snippets
(Thread)
Last updated: 2020-02-08
(no subject)
Scripting
snippets
(Thread)
Last updated: 2020-02-08
(no subject)
Scripting
snippets
(Thread)
Last updated: 2020-02-08
(no subject)
Scripting
snippets
(Thread)
Last updated: 2020-02-08
Home (version 7) discussion
Scripting
home
(Thread)
Home (version 7) discussion
Last updated: 2018-12-07