Execute Python Script during CodeSys # RunTime

This time I would like to write how to execute Python Script with RunTime of Pi4 with CodeSys installed.

Library installation

To run Python Script automatically on Pi4, you need to install the system library. https://help.codesys.com/webapp/idx-SysProcess%20Implementation-lib;product=SysProcess%20Implementation;version=3.5.16.0

SysFile Library to handle File

SysTypes File, the structure used when executing commands

SysProcess Library to execute commands

check

Now let's check if those libraries are in CodeSys. Click Library Repository and press Find. Enter SysFile in Search. If there is, it is already installed. image.png

When you press Open, SysFile and its version are also displayed in “Installed libraries”. image.png

Import After confirming that it is installed, you can import it into your own project. Click Library Manager> Add Library. image.png Click Advanced .. image.png The Add Library Popup will appear. Enter Sysfile, select SysFile, 3.5.15.0 and click OK. image.png

Then you will be able to use this library for your own projects. image.png Insert SysProcess in the same way. image.png SysTypes too. image.png Occasionally, when CodeSys is restarted, the message "Project Environment is not up to date" appears, but I think "Set All to Newest" is fine. image.png

External file To add a Python Script, you will use an Object called “External file”. Online Help is here: https://help.codesys.com/webapp/_cds_obj_external_file;product=codesys;version=3.5.16.0

An External File is any file that you add to the project in the POUs view or Devices view. Click Project ‣ Add Object to open the Add External File dialog and define how the file belongs to the project. An external file which was inserted in the POUs view is never downloaded to the controller. An external file which was added in the Devices view is always downloaded to the controller when an online change or a download is performed due to an IEC code change. When an external file is downloaded to the controller, it is not updated in the project

External File is an Object that allows you to add any File to POUs View or Devices View. Project> Add Object will bring up a Pop-up of the External file, which will define where the File is.

--If the External File is added in POUs, it will not be downloaded by the Controller. --If the External File is added to Devices, the File will be downloaded to the Controller by Online Change / IEC code Change.

And even if the External File is downloaded to the Controller, it will not be updated to the Project.

Add Python Script

Click Add Object> External File. image.png

Define File Path and Name here. After setting, click “Add”. image.png

You can also redo the File Handling, update timing, etc. that were set in advance with Edit Object. image.png

Login and download the External File. Let's check if it is inside the Controller properly. Double-click on Device. Click ahead of File. Path is PlcLogic / Application. Yeah, Hello.py is included.

image.png

Script It just takes the current time and logs as it is.

import datetime
print('Hello,CodeSys')
d=datetime.datetime.now()

path='log.txt'

f=open(path,"a")
f.write(str(d)+'\n')
f.close()

PI4 fix

First, here's how to use Vi: https://prev.net-newbie.com/linux/commands/vi.html https://jsapachehtml.hatenablog.com/entry/2014/11/23/124350

[SysProcess]
Command=AllowAll

To add. image.png

program

Initialization program

Create a program that runs when Controller goes to Stop> Run. This is to ensure the execution authority of Script and the latest File every time. It will be used by System Events. Click here for Online Help: https://help.codesys.com/api-content/2/codesys/3.5.13.0/en/_cds_obj_task_config_sys_event/#e5ddda49857aab52c0a8640e01f6cda7-id-8eb22e41857aab52c0a8640e009f5f0b

Click Task Configuration. Open the System Events Tab. Add a new event with the Add Event Handler. image.png

ScreenShot of Online Help, but I use its PrepareStart. Call before starting the application, that is, when the Controller is Stop> Run. image.png When you press Add Event Handler, the following Popup will appear. Here you decide what event to run and what program to run. image.png Select Prepare Start for Event. image.png Set the program to run when the Event is triggered by Function Call. Just enter the name here and press OK to create the Function without permission. image.png Create a Global variable in GVL. image.png Then False the initial value. image.png

Execution program

Create a POU for _PythonExecute. image.png

Function to use

Remember to import the library first? You will be using two Functions in that library. Select Library Manager> Library> Select Function> The description of the Function is written in the 4th place.

image.png

SysProcessExecuteCommand2 https://help.codesys.com/webapp/SysProcessExecuteCommand2;product=SysProcess%20Implementation;version=3.5.16.0 image.png

Function to execute system commands. Note that the output of the command depends on the OS.

SysFileCopy https://help.codesys.com/webapp/SysFileCopy;product=SysFile;version=3.5.9.0 image.png

--Return: RTS_IEC_RESULT, Runtime system error code --szDestFileName: Copy destination Path --szSourceFileName: Copy source Path --pulCopied: Number of copied bytes

Implementation

Interface

PROGRAM _PythonExecute
VAR
	dwCopySize: DWORD;
	dutResult : RTS_IEC_RESULT;
	szCommand : STRING(200);
	fbTimer : TON;
	szStdOout : STRING(1000);
	fbTimer1 : TON;
	Command : STRING(200);
END_VAR

Program

(*
   /etc/CODESYSControl.cfg:
   [SysProcess]
   Command=AllowAll 
*)

IF NOT GVL.init THEN
	
	//Copy the scripts to local
	SysFile.SysFileCopy('/var/opt/codesys/hello.py'
						,'/var/opt/codesys/PlcLogic/Application/hello.py'
						,ADR(dwCopySize));
	
	
	//Change the permission that can execute
	SysProcess_Implementation.SysProcessExecuteCommand2(pszCommand:='chmod +x *.py'
														, pszStdOut:=szStdOout
														, udiStdOutLen:= SIZEOF(szStdOout)
														, pResult := ADR(dutResult));
	
	//Init is finished
	GVL.init:=TRUE;
	
END_IF

//Flash Timer
fbTimer1(IN:= TRUE, PT:=T#1S); 

//Command 
Command:= 'sudo python hello.py';

//Timer is ON
IF fbTimer1.Q  THEN
		//Reset it and flash again
		fbTimer1(IN:= FALSE);
		//Execute
		SysProcess.SysProcessExecuteCommand2(pszCommand:=Command
											, pszStdOut:=szStdOout
											, udiStdOutLen:= SIZEOF(szStdOout)
											, pResult := ADR(dutResult));
END_IF

When you run it, you will first see that the Script is copied to /var/opt/codesys/hello.py. image.png

Then log.txt is created. image.png

The middle time of Log is recorded. image.png

Yes, thank you for your hard work.

Recommended Posts

Execute Python Script during CodeSys # RunTime
Execute Python script with cron of TS-220
Script python file
python script skeleton
Import python script
Periodically execute Python Script on AWS Data Pipeline
Periodically execute python script with cron in venv environment
UnicodeEncodeError:'cp932' during python scraping
Automatically execute python file
Execute command from Python
DynamoDB Script Memo (Python)
Execute command from python
POST json with Python3 script
[Python] Execute unix command (subprocess)
Bitcoin price monitor python script
Execute external command in python
Run illustrator script from python
Receive runtime arguments in Python 2.7
[Python] Passing values during multiprocessing
Python runtime customization [sitecustomize, usercustomize]
Python eval can execute statements.