7Creating function blocks and functions with C#

The Visual Studio® extension is an extension for the integrated development environment Microsoft® Visual Studio®. The extension allows for using Visual Studio® for the develop­ment of eCLR firmware libraries in C# and implementing them on PLCnext Technology de­vices. Furthermore, you can debug the C# code on PLCnext Technology devices.

ProConOS embedded CLR is the open IEC 61131 control runtime system for different au­tomation tasks. The eCLR programming system is structured as follows:

eCLR_IEC61131_DevTools.PNG

Figure 7-1 Structure of the eCLR programming system

Additional information

In addition to the information in the following sections, further information is available in the online help “eCLR Programming Reference” and the “Readme.txt” text file. Both the online help and the text file are available in every eCLR project in Visual Studio®.

PLCnext_VS_SolutionExplorer_CHM_Readme.PNG

Figure 7-2 “eCLR-Programming-Reference.chm” and “Readme.txt”

The eCLR programming system consists of the following components:

CIL compiler

The CIL compiler is responsible for translating the CIL code (CIL = Common Intermediate Language). The eCLR CIL compiler is an ahead-of-time compiler. This means that the CIL code has been fully translated for the platform before being transferred to the controller (more importantly, before execution). This fulfills an essential requirement for the real-time capability of the system. The functional scope of the CIL compiler enables the use of many C # language elements and namespaces of the Base Class Library, which are listed in Sec­tion C# language functions.

eCLR core libraries

The core libraries consist of eCLR base class libraries (mscorlib.dll, System.dll, Sys­tem.Core.dll) and some eCLR-specific libraries (eclrlib.dll, pcoslib.dll). The eCLR base class libraries implement the .NET Framework class libraries. An overview of the supported functions is available in Section “eCLR Base Class Libraries Reference” of the “eCLR Pro­gramming Reference” online help (see Additional information).

eCLR runtime

The eCLR runtime executes the compiled IL code on the controller. The runtime is respon­sible for object and memory management, metadata processing (e.g., for debugging), as well as for the transition of managed API calls to native implementation specific to the oper­ating system. An overview of the eCLR runtime is available in Section eCLR runtime functions.

7.1Installing the Visual Studio® extension

7.1.1System requirements

Before starting the installation, ensure that the system requirements are met and down­load the necessary software.

Operating system

Microsoft® Windows® 7

Microsoft® Windows® 8.1

Microsoft® Windows® 10

Phoenix Contact software

PLCnext Engineer (Order No. 1046008):

To use the libraries created with C# for PLCnext Technology devices, you need the engi­neering software platform for automation controllers.

PLCnext Technology controller with eCLR as of version 2019.0 LTS (e.g., AXC F 2152)

Visual Studio® extension installer

The Visual Studio® extension (tools for Visual Studio 2015 for PLCnext Technology C# pro­gramming) are available in the download area of your controller or the PLCnext Engineer software (Order No. 1046008) at phoenixcontact.net/products.

C# development environment

Microsoft® Visual Studio® 2015 and 2017
Versions: Enterprise, Pro, Community

7.1.2Installation

You need the Microsoft® Visual Studio® development environment for programming in C#. The Phoenix Contact extension available for Visual Studio® makes it easy to use C# pro­grams in the PLCnext Technology context.

Installing the
Visual Studio® extension

To install the Visual Studio® extension, run the Windows installation program of the Visual Studio® extension.
This adds the project and element templates and the debug module to Visual Studio®.

Check if installation was successful by opening the “Tools, Extensions and Updates” menu in the Visual Studio® development environment.

If the extensions have been successfully installed, they are displayed as shown in Figure 7-3:

PLCnext_Visual_Studio_Extensions_and_Updates.PNG

Figure 7-3 “Extensions and Updates” menu

Uninstalling the Visual Studio® extension

If you want to uninstall the Visual Studio® extension, proceed as follows:

Run the Windows installation program of the Visual Studio® extension.

In the next dialog, select “Remove”.

You can also use the Windows® “Programs and Features” menu to uninstall the Visual Studio® extension.

Select the extension from the list.

Click on “Uninstall”.

7.2Creating a firmware library

With Visual Studio® you can create functions and function blocks in C#, which you can sub­sequently import using the PLCnext Engineer software, and use on a PLCnext Technology device. You first have to create a new project. To do this, proceed as follows:

In Visual Studio®, open the “File, New, Project...” menu.

In the dialog that opens, select “Installed, Templates, Visual C#, PLCnext”.

Select the “Firmware Library” eCLR template from the list.

Select a storage path and click on “OK”.

A new, empty eCLR library project is created.

PLCnext_VS_New_Project.PNG

 

Figure 7-4 Creating a new PLCnext library project

 

Open the “Project, Add New Item” menu.

In the dialog that opens, select “Installed, Visual C# Items, eCLR”.

Select the “Function Block” or “Function” element from the list.

Click on “Add”.

By doing so you create a new template for a function or a function block.

PLCnext_VS_Add_FB.PNG

Figure 7-5 Adding a “Function Block”

When you create a function, select a return value in the following dialog.

PLCnext_Debugging_Function_Wizard.png

Figure 7-6 Adding a new “Function” element: selecting a return value

“Kind of Return Value”:
“By Reference” is recommended for complex data types, and is mandatory for generic data types (ANY).

Create your function block or function in the template.

Observe the comments in the template.

Create the entire project by pressing <F6>. Depending on your configuration, a *.pcwlx library is created in the release or debug directory of the project.

PLCnext_Visual_Studio_FB_template.PNG

Figure 7-7 Example: eCLR function block template

Also observe the information in the “Known Issues and Constraints” section of the on­line help (see Additional information).

7.3Remote debugging of C# code with Visual Studio®

inset_34.jpg 

 

NOTE: Risk of damage to equipment

If safety functions are switched off, the controller must not be used for live operation.

Using the debugging function can result in an unsafe process interruption.

Ensure that there is no risk of damage to the equipment or personal injury.

Because PLCnext Technology includes an implementation of eCLR, you have the option to establish a C# remote session. The following sections describe the basic steps needed for setting up a remote debug session and establishing a direct connection to a running appli­cation by means of Visual Studio®.

Software used

PuTTY

WinSCP

Microsoft® Visual Studio® 2015 and 2017

Visual Studio® extension

inset_28.jpg 

 

Please note:

The following description is based on the default settings. Consider all changes made by the user.

7.3.1Disabling user authentication

inset_27.jpg 

 

NOTE: Risk of damage to equipment

If safety functions are switched off, the controller must not be used for live operation.

Currently, the C# debugging function does not feature an interface for logging on to the con­troller. To debug the C# code, you have to deactivate the user authentication in WBM (web-based management) of the controller.

For additional information, please refer to Section “User Authentication” page.

Deactivate user authentication of your controller via WBM.

PLCnext_Debugging_WBM_Benutzerauthentifizierung.png

Figure 7-8 Example WBM for AXC F 2152: Deactivating user authentication

7.3.2Opening a port and deactivating TLS (Transport Layer Se­curity)

Currently, C# debugging via a secure communication connection is not supported. For this reason, another port has to be opened for communication with the controller. TLS (Trans­port Layer Security) has to be deactivated on this port.

Open WinSCP.

Establish a connection to the IP address of the controller and a user with root rights (see Section 2.15.7, “Root rights”).

PLCnext_Debugging_WINscp_Verbindung_herstellen.png

 

Figure 7-9 Establishing a connection

Open the /etc/plcnext/device/System/RscGateway/ folder.

Open the “RscGateway.settings” file.

PLCnext_Debugging_WINscp_Verzeichnis_RscGateway.png

Figure 7-10 “RscGateway” directory with “RscGateway.settings” file

Scroll to the line with the “TcpGatewaySettings”.

Insert the line
<TcpGatewaySettings gatewayId=”0” tcpPort="41101” sessionTimeout="300000” encrypted="false” /> 
as shown in the figure below:

PLCnext_Debugging_RscGateway.settings_ergaenzen.png

Figure 7-11 “RscGateway.settings”

Save and close the file.

Restart the controller.

7.3.3Debug mode

Creating/opening a proj­ect

Create a new project in Visual Studio®. Set it up.

Follow the operating instructions in Section Creating a firmware library
Or

Open an existing project

Importing a library in PLCnext Engineer

Import the library in PLCnext Engineer (see Section Importing libraries into PLCnext Engineer).

Activating debug mode

To activate debug mode, proceed as follows:

Connect PLCnext Engineer to the controller. Additional information on PLCnext Engineer is available in the online help and in the quick start guide. The quick start guide can be downloaded at phoenixcontact.net/products.

In the “PLANT” area, right-click on the controller.

In the context menu, select “Debug On/Off”.

PLCnext_Debugging_Debug_OnOff.png

Figure 7-12 Activating debug mode in PLCnext Engineer

Attaching Visual Studio® 
to the process

In Visual Studio® open the “Debug, Attach to Process...” menu.

From the “Transport” drop-down list, select the “eCLR Device” entry.

Click on the “Find...” button.

In the “Attach to eCLR” dialog that opens, enter the IP address of the controller (e.g., 192.168.1.10:41101) and port number 41101.

Select the image under the following path:
“c:\users\Public\Documents\PLCnext Engineer\Version\Binaries\PROJECT1@binary\eCLR\”.

A shortcut to this path is available in the “Select Image File” dialog. It can be found under “Microsoft Visual Studio 2015”, “Binaries”.

PLCnext_Debugging_VS_Einstellungen.png

Figure 7-13 Attaching Visual Studio® to the process

Select the image currently running on the controller.

Confirm your selection with “OK”.

Click on the “Attach” button.

Then add breakpoints in Visual Studio.

Execution of the code is stopped at the breakpoint. You can now evaluate the current vari­able values.

CSharp_Debugging_Breakpoint.PNG

Figure 7-14 Setting breakpoints in Visual Studio

Use the functions in Visual Studio to jump to the next breakpoint or continue processing of the code.

CSharp_Breakpoint_continue.PNG

Figure 7-15 Continuing code processing or jumping to the next breakpoint

If you want to make changes to the code within the framework of debugging, you have to disconnect the process connection (“Detach“):

In Visual Studio, select the “Debug, Detach All” menu.

CSharp_Debugging_Detach_All.PNG

Figure 7-16 Visual Studio® - “Detach All”

Make changes to the code and save them.

Recompile the project. To do so, open the “Build, Rebuild Project name” menu.

Then, switch to PLCnext Engineer.

PLCnext Engineer recognizes the change. Save the change.

inset_35.jpg 

 

If the inputs/outputs have been changed, errors might occur in PLCnext Engineer. If necessary, correct them in PLCnext Engineer.

 

Transfer the project to the controller.

Then, reconnect Visual Studio to the process (see Attaching Visual Studio® to the process).

For information on the debug functions in PLCnext Engineer and in Microsoft Visual Studio®, please refer to the associated documentation.

7.4Supported functions of the PLCnext Technology C# programming system

7.4.1C# language functions

Types

All the integrated types are supported with the exception of decimal.

Type system

Namespaces, structs, classes, interfaces, enumerations, nested types

Indexers, properties, operations

Events, delegates, MultiCastDelegates

Arrays

Constructors, static constructors, destructors (finalizers)

Boxing, unboxing, static casts

Nullable

Polymorphy

Virtual mechanism (virtual, overwrite, abstract)

Dynamic casts (as)

Modifiers and keywords

public, internal, protected, private

readonly, const, sealed, unsafe

params, ref, out

base, this

explicit, implicit, operator

Operators

new, sizeof, typeof, as, is

All unary operators

All binary operators

Prefix, postfix and conditional operator

Cast and index operator

Control structures and statements

if, else

switch, case, default (also on strings)

for, do, while, foreach, break, continue

goto, return

using, fixed

lock

Exceptions

throw

try, catch, finally

For additional information, please refer to Section Known issues and constraints.

7.4.2Base class libraries

Below you will find a list of the most important classes that have been implemented in the eCLR base class library, separated by namespaces. A complete list of the implemented classes with additional information is available in Section “eCLR Base Class Libraries Ref­erence” of the “eCLR-Programming-Reference.chm” online help (see Additional information).

System

All integrated types, as well as the following:

Char, Boolean, Int32, Single, etc., with the exception of decimal

All common exception types

Common interfaces such as:
IDisposable, IComparable, ICloneable, IFormatProvider, IFormattable

String, array, object, valuetype

Version, DateTime, TimeSpan, TimeZone

BitConverter, Convert

GC

Console

Uri, UriBuilder

System.Collections

IEnumerator, IEnumerable, ICollection, IList, IDictionary, IComparer

ArrayList, Hashtable, Queue

Comparer, DictionaryEntry

System.Collections.Generic

IEnumerator<T>, IEnumerable<T>, ICollection<T>, ICollection<T>, IList<T>,
IDictionary<TKey,TValue>, IComparer<T>

Dictionary<TKey,TValue>, List<T>, Queue<T>

Comparer<T>, KeyValuePair<TKey,TValue>

System.Globalization

Calendar, CalendarWeekRule

CultureInfo
Supported cultures: de-DE, en-US, en-GB, Invariant
Types that support the localized formatting/parsing: all number types, DateTime, Time­Span

DateTimeFormatInfo, NumberFormatInfo, NumberStyles, DateTimeStyles

System.IO

Path, File

Stream, FileStream, MemoryStream

BinaryReader, BinaryWriter

TextReader, TextWriter, StreamReader, StreamWriter, StringReader, StringWriter

System.Security.Cryptography

CryptoConfig

HashAlgorithm, MD5, MD5CryptoServiceProvider

System.Text

StringBuilder

Encoding, ASCIIEncoding, UTF8Encoding, UnicodeEncoding (big endian and little en­dian)

System.Threading

Thread, ThreadPool, ThreadStart, ThreadState

Monitor (lock)

WaitHandle, EventWaitHandle, AutoResetEvent, ManualResetEvent, WaitCallback

Timer, TimerCallback

System.Net

IPAdress, IPEndpoint, Endpoint, SocketAddress

WebClient, HttpWebRequest, HttpWebResponse

System.Net.Sockets

NetworkStream

AddressFamily, ProtocolType

Socket, SocketType

7.4.3eCLR runtime functions

Garbage collection

Memory management is performed by the eCLR. The garbage collector should explicitly only be called at a specific point in time (application of GC.Collect).

Implicit finalization

The finalizer of each applicable .NET class (implementing ~T()) is called when teh garbage collector releases the instance. The garbage collector collect function is called automati­cally. The time of the implicit call cannot be predicted.

Implicit initialization

All the integrated types and value types (struct) are implicitly initialized with their default val­ues. Reference type instances are implicitly initialized with the value “zero”.

Debug support

Defining breakpoints

Evaluation of instance values and local variables, as well as arguments from the current method

Providing call stack information

Known issues and constraints

For detailed information, please refer to Section “Known Issues and Constraints” of the Visual Studio® extension online help (see Additional information).

7.5Supported data types

The following table illustrates how the IEC 61131-3 data types are linked to the .Net Frame­work and C#. Variables of data types that are marked with a “+” in the “Attribute data type” column must have the optional “DataType” attribute for unique assignment.

Table 7-1Supported IEC 61131-3, .Net Framework, and C# data types

IEC 61131-3

.Net Framework

C#

Attribute data type

BOOL

System.Boolean

bool

-

SINT

System.SByte

sbyte

-

INT

System.Int16

short

-

DINT

System.Int32

int

-

LINT

System.Int64

long

-

USINT

System.Byte

byte

-

UINT

System.UInt16

ushort

-

UDINT

System.UInt32

uint

-

ULINT

System.UInt64

ulong

-

REAL

System.Single

float

-

LREAL

System.Double

double

-

TIME

System.UInt32

uint

+

LTIME

System.Int64

long

+

LDATE

System.Int64

long

+

LTOD

System.Int64

long

+

LDT

System.Int64

long

+

BYTE

System.Byte

byte

+

WORD

System.UInt16

ushort

+

DWORD

System.UInt32

uint

+

LWORD

System.UInt64

ulong

+

STRING

System.Iec61131Lib.
IecStringEx

 

-

ANY

System.Iec61131Lib.Any

 

+

ANY_MAGNITUDE

System.Iec61131Lib.Any

 

+

ANY_NUM

System.Iec61131Lib.Any

 

+

ANY_INT

System.Iec61131Lib.Any

 

+

ANY_SIGNED

System.Iec61131Lib.Any

 

+

ANY_UNSIGNED

System.Iec61131Lib.Any

 

+

ANY_REAL

System.Iec61131Lib.Any

 

+

ANY_BIT

System.Iec61131Lib.Any

 

+

ANY_ELEMENTARY

System.Iec61131Lib.Any

 

+