This tutorial explains how to run Linux commands from Codesys. There is a library in Codesys available that allows to manage processes on the target system. The target system needs to support this.

To test the functionality a Turck TX707 HMI with Codesys runtime v3.5.16.30 is used.

CodesysLinux

Configure PLC

First enable SSH access in the system settings of the TX707. This is explained in the manual in chapter 8. In the system settings, navigate to Service settings, then enable SSH Server. Now a program like Putty can be used to access the HMI via SSH.

Login via SSH and navigate to the codesys folder with the following command: (the folder might be different on another PLC)

cd /mnt/data/hmi/cds3/deploy

The location may differ on different PLC’s. Sometimtes the SysProcess information should be added in a seperate CODESYSControl_User.cfg file. See also the Codesys FAQ

Now open the Codesys config file with the following command:

sudo nano CODESYSControl.cfg

Add the following line (in the middle of the file) to give Codesys permission to execute commands:

[SysProcess]
BasePriority=Realtime
Command=AllowAll

The result should look like this:

CodesysSysProcessNano

Press Ctrl+X to exit the file editor and choose Y to save the file. Then press Enter to confirm. Now the correct file is created to allow Codesys to execute processes and commands. If only a specific program or command is needed, then this is also possible by writing the following in the file (for example):

[SysProcess]
Command.0=echo
Command.1=tar

Now only the echo and tar command can be executed by Codesys.

After changing the config file, reboot the PLC.

Execute command from Codesys

In Codesys add the SysProcess Implementation library in the library manager.

CodesysSysProcessLibrary

Now write a small program that executes a Linux command based on a test variable. For example:

Declaration:

PROGRAM PLC_PRG
VAR
	bTest : BOOL;
	testTrigger : Standard.R_TRIG;
	
	sCommand : STRING;
	refCommand : REFERENCE TO STRING;
	sOutput : STRING;
	refOutput : REFERENCE TO STRING;
	
	result : RTS_IEC_RESULT;
END_VAR

Implementation:

testTrigger(CLK:= bTest, Q=> );

sCommand:= 'echo "Hello world!"';

refCommand REF= sCommand;
refOutput REF= sOutput;

IF testTrigger.Q THEN
	SysProcessExecuteCommand2(pszCommand:= refCommand, pszStdOut:= refOutput, udiStdOutLen:= SIZEOF(sOutput), pResult:= ADR(result));
	
	bTest:= FALSE;
END_IF

When going online with Codesys the result should look like this:

CodesysEchoHelloWorld

The command succesfully executed, the result is visible in the sOutput string.

With the same library it’s also possible to create or terminate processes. It’s also possible to execute Python scripts, bash scripts or gzipping files. Everything that’s possible with a command via SSH is now possible to do dynamically with Codesys.