5Creating function blocks and functions with C#

The Visual Studio® extension is an extension for the integrated development environment Microsoft® Visual Studio®. The extension makes it possible to use Visual Studio® for the development of eCLR firmware libraries in C# and to implement these on PLCnext Technology devices. 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 5-1 Structure of the 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 to be found in every eCLR project in Visual Studio®.

PLCnext_VS_SolutionExplorer_CHM_Readme.png

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

The eCLR programming system consists of the following components:

CIL compiler

The CIL compiler is responsible for translating the CIL code (Common Intermediate Lan­guage). 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 target system (more importantly, before execution). This fulfills an essential requirement for the real-time capa­bility 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 Chapter C# language functions.

eCLR core libraries

The core libraries consists 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 target system. The runtime is re­sponsible for the object and memory management, metadata processing (e.g. for debug­ging), as well as for the transition of managed API call ups to operating-system-specific na­tive implementation. An overview of the eCLR runtime is available in section eCLR runtime functions.

5.1Installing the Visual Studio® extension

5.1.1Requirements

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

Operating system

Windows® 7

Windows® 8.1

Windows® 10

Phoenix Contact software

PC Worx Engineer (at least Version 7.2.2, Order No.: 1046008):

You need the engineering software platform for automation controllers to use the libraries created with C# for PLCnext Technology devices.

PLCnext Technology target with eCLR, at least Version 3.1 (e.g. AXC F 2152)

Visual Studio® extension installer

The extension is to be found in the download area of the AXC F 2152 controller (Order No.: 2404267) or the PC Worx Engineer software (Order No.: 1046008) under the address phoenixcontact.net/products (PLCnext Technology Development Tools for Visual Studio).

C# development environment

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

5.1.2Installation

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

Installing Visual Studio®

Install the Microsoft® Visual Studio® 2015 development environment.

Follow the instructions of the installation wizard.

Installing the
Visual Studio® extension

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®.

To ensure that the installation has been completed correctly, open the Visual Studio® development environment.

Open the “Tools, Extensions and Updates” menu.

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

PLCnext_Visual_Studio_Extensions_and_Updates.png

Figure 5-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® menu “Programs and Features” to uninstall the Visual Studio® extension.

Select the extension from the list.

Click on “Uninstall”.

5.2Creating a firmware library

With Visual Studio® you can create functions and function blocks in C# that you can subse­quently import using the PC Worx Engineer software and which you can use on a PLCnext Technology device. You first have to create a new project. Proceed as follows:

Open the “File, New, Project...” menu in Visual Studio®.

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

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

Select a storage path and click on “OK”.

This creates a new, empty eCLR library project.

PLCnext_Visual_Studio_neues_Projekt_generieren.png

 

Figure 5-4 Creating a new, empty eCLR 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 an eCLR function or a func­tion block.

PLCnext_Visual_Studio_Add_New_Item.png

Figure 5-5 Adding a new “Function Block” element

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

PLCnext_Debugging_Function_Wizard.png

Figure 5-6 Adding a new “Function” element: Selecting a return value

“Kind of Return Value”:
“By Reference” is recommended for complex data types, and must be used 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 5-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).

5.3Importing the C# library in PC Worx Engineer

inset_27.png 

 

Additional information on PC Worx Engineer is available in the online help and the quick start guide. This is available for downloading at phoenixcontact.net/products (PC WORX ENGINEER 7, Order No.: 1046008).

Once you have generated a *.pcwlx library from a C# library, import this library into the PC Worx Engineer software. In PC Worx Engineer, imported libraries are treated as func­tions or function blocks in accordance with IEC 61131-3, and are processed in tasks.

To import a library into PC Worx Engineer, proceed as follows:

Open your PC Worx Engineer project or create a new AXC F 2152 template.

Save the project by selecting the “File, Save Project As...” menu.

Select a path.

In the “COMPONENTS” section, click on “References”.

Right-click on “Libraries”.

Adding a library

Right-click to open the “Add Library” context menu.

PLCnext_PCWE_Add_Library.png

Figure 5-8 “Add library” context menu

In the dialog that opens, select the desired *.pcwlx library. You will find this in the folder of your C# firmware project, in the subfolder bin/Debug or bin/Release (depending on the setting in Visual Studio®).

Click on “Open”.

PLCnext_Visual_Studio_PCWE_pcwlx_öffnen.png

Figure 5-9 Example: Opening a pcwlx library

The library is now a part of the PC Worx Engineer project. The POUs contained therein (Pro­gram Organization Unit) can be used in the project, for example in the FBD (Function Block Diagram).

Open the “Main” code worksheet via the “COMPONENTS” area.

Open the “Code” program editor.

Add the new C# function block by dragging it from the “COMPONENTS” area under “References” to your code worksheet.

PLCnext_Visual_Studio_PCWE_neuen_FB_einfügen.png

Figure 5-10 Inserting a function block

Assigning inputs/outputs

Additional information is to be found in the Readme.txt file (see Additional information).

5.4Root rights

PLCnext Technology controllers are supplied with a preset admin user. This enables ac­cess to the most important functions. To configure settings for remote debugging of C# code, you need advanced rights. To this end, first create a user with root rights.

inset_28.png 

 

NOTE: Risk of damage to equipment

If safety functions are switched off, using the controller for live operation is not permitted.
Ensure that there is no risk of equipment damage or personal injury.

Software used

WinSCP

Configure the connection settings in WinSCP.

Connect with the controller by entering the IP address of the controller and the pass­word for the admin user.

Click “Login”.

PLCnext_Visual_Studio_WinSCP_verbinden.png

 

Figure 5-11 Connecting WinSCP with the controller (1)   

PLCnext_Visual_Studio_WinSCP_verbinden2.png

 

Figure 5-12 Connecting WinSCP with the controller (2)

Subsequently, open the console by clicking the “Open in PuTTY” button.

PLCnext_Visual_Studio_WinSCP_PuTTY_öffnen.png

Figure 5-13 Opening PuTTY

Log in with the “admin” user name and the controller password. The default password of the controller is printed on the housing.

PLCnext_Visual_Studio_Konsole1.png

Figure 5-14 Logging in as admin user

Enter the “sudo passwd root” command.

Enter the admin password.

Enter a new password for the root user.

Confirm this by entering it again.

PLCnext_Visual_Studio_Konsole2.png

Figure 5-15 Creating a new root user

To end the connection, enter the “exit” command.

5.5Remote debugging of C# code with Visual Studio®

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

Software used

PuTTY

WinSCP

Microsoft® Visual Studio® 2015

Visual Studio® extension

inset_34.png 

 

Please note:

The following description is based on the default settings. Take all changes made by the user into account.

Do not use the controller in live operation when safety functions have been disabled.

Using the debugging functionality can result in an unsafe process interruption. Ensure that there is no risk of equipment damage or personal injury.

5.5.1Opening a port and deactivating TLS

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. Transport Layer Security (TLS) has to be deactivated on this port.

Open WinSCP.

Establish a connection using the IP address of the controller and the user with root rights.

PLCnext_Debugging_WINscp_Verbindung_herstellen.png

 

Figure 5-16 Establishing a connection

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

Open the “RscGateway.settings” file.

PLCnext_Debugging_WINscp_Verzeichnis_RscGateway.png

Figure 5-17 “RscGateway” directory with “RscGateway.settings” file

Insert the line <TcpGatewaySettings gatewayId="0" tcpPort="41101" sessionTime­out="300000" encrypted="false" /> as shown in the figure below.

PLCnext_Debugging_RscGateway.settings_ergaenzen.png

Figure 5-18 “RscGateway.settings”

Save the file.

Restart the controller.

5.5.2Disabling user authentication

inset_35.png 

 

NOTE: Risk of damage to equipment

If safety functions are switched off, using the controller for live operation is not permitted.

The C# debugging function does not currently have an interface for logging on to the con­troller. To debug the C# code, you have to deactivate the user authentication in the WBM of the controller.

For information on the WBM (Web-Based Management) of your controller, please refer to the corresponding user manual.

Deactivate the user authentication of your controller via the WBM.

PLCnext_Debugging_WBM_Benutzerauthentifizierung.png

Figure 5-19 Example WBM AXC F 2152: Deactivating the user authentication

5.5.3Debug mode

Creating/opening a
project

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

Follow the operating instructions in section Creating a firmware library,
or

Open an existing project.

Importing a library into PC Worx Engineer

Import the project into PC Worx Engineer.

Follow the operating instructions in section Importing the C# library in PC&nbsp;Worx&nbsp;Engineer.

Activating debug mode

Connect PC Worx Engineer with the controller. Additional information on PC Worx Engineer is available in the online help and in the quick start guide. This is available for downloading at phoenixcontact.net/products.

Activate the debug mode by right-clicking on the controller in the “PLANT” area.

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

PLCnext_Debugging_Debug_OnOff.png

Figure 5-20 Activating debug mode in PC Worx Engineer.

Attaching Visual Studio® 
to the process

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

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

Click on the “Find...” button.

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

Select the image under the following path: “C:\Users\Public\Documents\PC Worx En­gineer\Binaries\PROJECT1@binary\eCLR\”. A shortcut to this path is available in the “Select Image File” dialog. This is available under “Microsoft Visual Studio 2015”, “Bi­naries”.

PLCnext_Debugging_VS_Einstellungen.png

Figure 5-21 Attaching Visual Studio® to the process

Confirm your selection with “OK”.

Click on the “Attach” button.

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

5.6Supported functions of the eCLR programming systems

5.6.1C# language functions

Types

All 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 further information, see section Known issues and constraints.

5.6.2Base class libraries

The following table contains a list of the most important classes that have been imple­mented in the eCLR base class library, separated by namespaces. A complete list of the im­plemented classes with additional information is available in the section “eCLR Base Class Libraries Reference” of the “eCLR Programming Reference” online help (see Additional information).

System

All integrated system types, as well as the following:

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

All standard 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

5.6.3eCLR runtime functions

Garbage Collection

The memory management is performed via eCLR. The Garbage Collector should explicitly only be called up at a specific point in time (application of GC.Collect).

Implicit Finalization

The Finalizer of each applicable .NET class (implementing ~T()) is called up when the in­stance is released by the Garbage Collector. The Garbage Collector collect function is called up automatically. The time of the implicit call up cannot be predicted.

Implicit initialization

All integrated types and value types (struct) are implicitly initialized with their default values. 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

Detailed information is to be found in the identically named online help section of the Visual Studio® extension (see Additional information).

5.7Supported data types

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

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

IEC 61131-3

.Net Framework

C#

Attribut DataType

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.Iec­StringEx

 

-

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_ELEMEN­TARY

System.Iec61131Lib.Any

 

+