Programming An OPC UA Client With C# For The SIMATIC NET . - Siemens

Transcription

Programming an OPCUA .NET Client withC# for the SIMATICNET OPC UA ServerSIMATIC NET OPC UA n/view/42014088SiemensIndustryOnlineSupport

Warranty and LiabilityWarranty and Liability Siemens AG Table 3-6 All rights reservedNoteThe Application Examples are not binding and do not claim to be complete regarding thecircuits shown, equipping and any eventuality. The Application Examples do not representcustomer-specific solutions. They are only intended to provide support for typicalapplications. You are responsible for ensuring that the described products are usedcorrectly. These Application Examples do not relieve you of the responsibility to use safepractices in application, installation, operation and maintenance. When using theseApplication Examples, you recognize that we cannot be made liable for anydamage/claims beyond the liability clause described. We reserve the right to makechanges to these Application Examples at any time without prior notice.If there are any deviations between the recommendations provided in these ApplicationExamples and other Siemens publications – e.g. Catalogs – the contents of the otherdocuments have priority.We do not accept any liability for the information contained in this document.Any claims against us – based on whatever legal reason – resulting from the use ofthe examples, information, programs, engineering and performance data etc.,described in this Application Example shall be excluded. Such an exclusion shallnot apply in the case of mandatory liability, e.g. under the German Product LiabilityAct (“Produkthaftungsgesetz”), in case of intent, gross negligence, or injury of life,body or health, guarantee for the quality of a product, fraudulent concealment of adeficiency or breach of a condition which goes to the root of the contract(“wesentliche Vertragspflichten”). The damages for a breach of a substantialcontractual obligation are, however, limited to the foreseeable damage, typical forthe type of contract, except in the event of intent or gross negligence or injury tolife, body or health. The above provisions do not imply a change of the burden ofproof to your detriment.Any form of duplication or distribution of these Application Examples or excerptshereof is prohibited without the expressed consent of the Siemens AG.SecurityinformationSiemens provides products and solutions with industrial security functions that support thesecure operation of plants, systems, machines and networks.In order to protect plants, systems, machines and networks against cyber threats, it isnecessary to implement – and continuously maintain – a holistic, state-of-the-art industrialsecurity concept. Siemens’ products and solutions only form one element of such aconcept.Customer is responsible to prevent unauthorized access to its plants, systems, machinesand networks. Systems, machines and components should only be connected to theenterprise network or the internet if and to the extent necessary and with appropriatesecurity measures (e.g. use of firewalls and network segmentation) in place.Additionally, Siemens’ guidance on appropriate security measures should be taken intoaccount. For more information about industrial security, please mens’ products and solutions undergo continuous development to make them moresecure. Siemens strongly recommends to apply product updates as soon as available andto always use the latest product versions. Use of product versions that are no longersupported, and failure to apply latest updates may increase customer’s exposure to cyberthreats.To stay informed about product updates, subscribe to the Siemens Industrial SecurityRSS Feed under http://www.siemens.com/industrialsecurity.NET OPC UA-ClientEntry-ID: 42014088, V1.2,12/20172

Table of ContentsTable of ContentsWarranty and Liability . 21Automation Task . 41.11.22Automation Solution . 82.12.22.32.4 Siemens AG 2017 All rights reserved3Basics on OPC . 15Basics on OPC Unified Architecture . 17OPC UA specifications . 17Structure of the OPC UA Server address space . 19Interface for access to the OPC UA Server address space . 23Protocols and security mechanisms . 26Delimitation and comparison with OPC Data Access . 30Basics on S7 communication . 31General . 31Optimized S7 communication . 34Functional Mechanisms of this Application . 364.14.24.34.3.14.3.24.3.34.45Solution overview . 8Description of the core functionality . 9Topics not covered by this application . 13Hardware and software components used. 13Alternative solutions . 14Basics . rview. 5Requirements . 6OPC UA Client Helper API . 39Simple OPC UA Client . 41Convenient OPC UA Client . 44Interface. 44Class diagram . 45Sequence diagrams . 47S7 program . 52Configuration and Settings. 565.15.25.35.3.15.3.25.3.3Configuring the SIMATIC S7 stations . 56Configuration of the OPC server station . 58Configuration of OPC UA Security . 62OPC UA remote communication . 62Certificate storage . 63Authentication, SecurityPolicy and MessageSecurityMode . 686Installation . 707Commissioning the Application . 728Operating the Application . 768.18.2Operating the Simple Client . 76Operating the convenient OPC UA client . 789Further Notes, Tips & Tricks, etc. . 8410Reference List . 8511History. 86.NET OPC UA-ClientEntry-ID: 42014088, V1.2,12/20173

1 Automation Task1Automation TaskReasonThe OPC Unified Architecture (UA) provides an additional, convenient andperformant option of process coupling for PC systems with SIMATIC S7 now existsin SIMATIC NET OPC Server, which will successively replace the existing OPCData Access (DA) and Alarms & Events (A&E) functions.The main advantages of OPC UA over conventional OPC interfaces are: Communication over the Internet and across firewalls. Optimized, robust and fault-tolerant protocol with integrated securitymechanisms. OPC UA can be directly integrated into applications on different operatingsystems with different programming languages. All OPC information, such as data or alarms, is integrated in a namespace. Information can be described using object-oriented means.Copyright Siemens AG 2017 All rights reservedTarget groupThis application is designed for end users who need a comprehensive introductionto this technology and who want to acquire experience with the professionalcreation of OPC UA clients in C# under .NETContentThis is where you get an overview of the use of the OPC UA communicationinterface which offers the data, alarms and diagnostic information from theSIMATIC S7 controllers. You will learn about the components used, standardhardware and software components and the specially created user software.The user software offers examples for the creation of OPC UA clients with C#under .NET. Included are a simplified, reusable API, a simple example and acomplex example with a convenient user interface. The example also providesnotes on the optimization and expansion of the application.NET OPC UA-ClientEntry-ID: 42014088, V1.2,12/20174

1 Automation Task1.1OverviewIntroductionIn order to realize a data link, it is nowadays preferred to use standardizedmechanisms in order to ensure that such a data exchange remains independent ofthe used bus system or protocol or even manufacturer. For the exchange of eventand alarm messages, a standardized mechanism for connecting differentsubsystems will also be used. OPC UA combines this functionality and additionallyoffers authentication and encrypted data transmission as well as advanceddiagnostic information.Overview of the automation taskThe following figure provides an overview of the automation task.Figure 1-1Copyright Siemens AG 2017 All rights reservedPC StationVisualizationData nformation ServerOPC Unified ArchitectureInformation ServerOPC Unified ArchitectureProcess / Production plantProcess / Production plantDescription of the automation taskIn the automation system the OPC UA server shall be considered the informationserver, which can display and describe individual components but also the entiresystem. Due to the encrypted access, which is checked and secured withcertificates, a link to other locations is also possible.The core task of this example is access to process data with the OPC UA interface.This is explained by creating a simple, individually created visualization on thebasis of the new OPC UA standard which is nevertheless suitable for real-lifesituations.NET OPC UA-ClientEntry-ID: 42014088, V1.2,12/20175

1 Automation TaskThe application is to contain the following functionalities: Server selection including security settings. Navigation through the OPC UA namespace of the server and selection ofprocess variables. Reading of attributes including the values of the selected process variables. Monitoring of the value of the selected process variables. Writing the value of the selected process variables. Using block services via OPC UA.Further data processing (e.g. saving in database or similar) is not discussed here.1.2RequirementsRequirements for the automation taskCopyright Siemens AG 2017 All rights reservedThe sample application has been created in C# and uses the interfaces of .NETAPI of the OPC Foundation.The user is explained the handling of the OPC UA interface under .NET in a reallife situation. The basic interface is the .NET Client SDK of the OPC Foundationincluded in delivery on the SIMATIC NET installation.This interface offers the full functional scope of OPC UA. To simplify the interface,a reduction to the functionality required for this example is performed. An efficientinstruction which is suitable for real-life situations for the OPC UA services isdeveloped.The design of a simple GUI interface demonstrates the basic functionality of OPCUA. The entire functional chain between S7 variable(s), OPC UA namespace andaccess from the client in C# is shown: Logging in, logging out and authentication on the server Searching the namespace for variables Reading, writing and monitoring variables Simple error handlingThe example describes the symbolic and absolute addressing and the use of thevariable services “read, write and monitor” for the S7 basic types as well as the useof the block-oriented services (receiving and sending of large data blocks).The different diagnostics options and the processing of error scenarios by theprogram are explained. The errors can also be triggered by simulatingdisconnections between the different components.NET OPC UA-ClientEntry-ID: 42014088, V1.2,12/20176

1 Automation TaskRequirement for data storageThe controller is to be able to offer the necessary data structures and data volumesand simulate value changes. There is no concrete control task, only the access tothe data is to be illustrated. The data areas and the interaction with othercomponents is displayed in the figure below.Figure 1-2PLCVariablesProductiondataCopyright Siemens AG 2017 All rights reservedRecipeOPC ribeStorageRPBRECVThe STEP7 program in the S7-CPU simulates the individual values which are to bereceived and displayed by the client (variable services). Different data types areused as individual variables.The PLC program simulates and generates the necessary structures and values forthe bi-directional transmission of larger data volumes and calls the block-orientedservices accordingly (BSEND, BRECV). This is used for STRUCT or ARRAYvariables with a total of several 100 bytes (recipe data, production data blocks orsimilar.).To send data, PLC actively triggers the transmission of a block-oriented productiondata record to the OPC UA server. The PLC receives a block-oriented data set(e.g. recipe) sent by an OPC UA client and stores it in the respective structure in adata block.The necessary variable tables are furthermore provided in STEP 7 for testpurposes.Requirement for the PC stationThe PC station must have the necessary physical connection to the respectivehardware and software for the communication with the controller. The applicationfor the visualization and control should only use the OPC UA interface to be able touse any OPC UA servers.The application example is to show what has to be generally projected on theserver/client PC station and the S7 controllers in order to solve the communicationtask.In STEP 7 the SIMATIC NET OPC server is configured for the task (protocol,security settings, certificates, etc.) in the configuration console for the PC stationand in the respective configuration files.The underlying S7 protocol and the necessary connections to the controllers areconfigured, including all corresponding steps which are to be projected andconfigured on the server PC for the OPC UA operation.Under Windows a secure communication between client PC and server PC iscreated by OPC UA means.NET OPC UA-ClientEntry-ID: 42014088, V1.2,12/20177

2 Automation Solution2Automation Solution2.1Solution overviewOverviewThe figure below shows a schematic overview of the most important components ofthe solution:Figure 2-1SIMATIC PC stationCopyright Siemens AG 2017 All rights reservedOPC UA Client-simple-advancedS7-1500 stationCPU 1516-2 PN/DPStd. Ethernet CardSIMATIC NET CD V14SOFTNET S7 IE/LeanSTEP 7 V14Visual Studio 2013(C#)S7-300 stationCPU 315-2 PN/DPS7-400 stationCPU 416-3 PN/DPCP443-1Adv.ConfigurationA PC station is connected to a CPU 315-2 PN and a CPU 414-2 via Ethernet. Astandard Ethernet card is used in the PC.OPC-UA Client softwareThe OPC-UA client in the PC station is realized at two levels of complexity. A verysimply designed client (Simple OPC UA Client) shows you all basic functions forgetting started in OPC UA. A more complex client (OPC UA .NET Client) with aconvenient interface will demonstrate professional handling with reusable classes.The functionality of these sample clients will be explained in the next section.NET OPC UA-ClientEntry-ID: 42014088, V1.2,12/20178

2 Automation Solution2.2Description of the core functionalityOverviewSIMATIC NET OPC UA Server forms the main functionality part of this example. Itsimplifies the functions and information of the classic OPC server for data accessand alarm & events in one single namespace and permits access to information viaa service-oriented architecture. Communication via the Internet and acrossfirewalls is secure and performant.This figure below shows the functional chain for a data access:Figure 2-2OPC UA ClientDisplayOPC UA ClientDisplay3StorageCopyright Siemens AG 2017 All rights reservedInternetind. EthernetUA TCPOPC UA Server2S7 ProtocolS7 connectionind. EthernetBSENDBRECVIn / OutPut1CP 443-1CPU 414-2DPGetS7 VariablesData blocksTable 2-1No.ComponentDescription1.S7 stationThe S7 CPU provides S7 variables for data areas such asflags or data blocks.Via the block-oriented services BSEND and BRECV, largerdata blocks can also be actively sent and received from theuser program.2.OPC UA serverThe OPC UA server transposes the S7 variables and theblock services to the OPC UA variables and provides OPCservices such as browse, read, write and data monitoring.3.OPC UA clientThe OPC UA Client can establish a secure connection to theserver, navigate through the namespace of the server andread, write and monitor selected variables.NET OPC UA-ClientEntry-ID: 42014088, V1.2,12/20179

2 Automation SolutionSoftware components of the application (OPC UA .NET client)The figure below shows the software components used for the more complexapplication (OPC UA .NET client). The OPC UA server and the basic libraries forthe OPC UA communication on the client side are from the SIMATIC NET CD.The software components created in C# for the application can be divided inreusable modules and sample code.Figure 2-3ExampleSimpleClientUAClientReusableSIMATIC NET CDBrowse ControlAttribute List ControlMonitored Items ControlCopyright Siemens AG 2017 All rights reservedClientAPIDiscoverySessionSubscriptionOPC UAClientExampleOPC UA .NET Client SDK (OPC Foundation)OPC UA .NET Stack (OPC Foundation)SIMATIC NET S7 OPC UA ServerOPC UAServerTable 2-2ModuleDescriptionOPC UA .NET stackThe .NET OPC UA stack from the OPC Foundation for the realization of thenetwork communication.NET Client SDKThe .NET OPC UA client SDK of the OPC foundation. The two DLLs of theOPC foundation are part of the delivery of the SIMATIC NET CD.Client APIReusable, simplified and tailored to this .NET Client API task. It offers reusableC# classes for discovery, session and subscription handling.Simple ClientSimple user interface for the use of the Client API with connect, disconnect,read, write and data monitoring functions. This example also shows directaddressing and the handling of namespaces.UA ClientConvenient OPC UA client with the functions: discovery, connect, disconnect,browse, read of all attributes, write and data monitoring.General functions such as browse, listing attributes and monitoring of datavariables are encapsulated in reusable controls.In this example the symbolic variables can be browsed and can be useddirectly from the browser.S7 OPC UA serverThe SIMATIC NET OPC UA server implements the necessary server logic forsessions and subscriptions and the data connection to the S7 stations.NET OPC UA-ClientEntry-ID: 42014088, V1.2,12/201710

2 Automation SolutionUser interface of the simple example (Simple OPC UA Client)The user interface of the Simple OPC UA Client is operated via buttons for theindividual functions. The simple example shows the use of the direct addressing ofS7 variables.Figure 2-43142567Copyright Siemens AG 2017 All rights reserved8Table 2-3No.Description1.The server URL can be specified in the text box for the Server URL. For the SIMATIC NET OPCserver it is made up of opc.tcp:// name of computer :4845.In the Namespace URI text box the namespace used is indicated. This is S7: for directaddressing, S7COM: for direct addressing via the OPC DA compatible Syntax and SYM: forsymbolic addressing.2.In the text boxes for the Variable Identifier the identification code of the NodeID is indicated. Fornamespace S7: it is made up of S7Connection . Data area . Offset , Data type The NodeID for reading and writing is made up of identification and namespace.3.Via the Connect and Disconnect buttons, the connection to the OPC server can be establishedor disconnected. The connection is only established without security. Secure connectionestablishment is explained in the next example.4.A subscription is created via the Monitor button and two Monitored Items are created in theSubscription with both NodeIds. The data changes are displayed in the text boxes next to thebutton. Errors are displayed instead of the values.5.The Read button reads the values (attribute value) of both variables with the specified NodeIDsand displays them in the text boxes next to the button.6.The Write button writes the value from the text box next to the button onto the variable identifiedby the NodeID.In order to write, “read” has to be called first since the text from the text box has to be convertedin the data type suitable for the variable. The conversion is on the basis of the data type which issupplied at “read”.7.In the "Block Read" group, data can be received which is actively sent by the S7 with theBSEND block service. This can be, for example, used for the sending of result data from the S7to a PC application.8.In the "Block Write" group, data blocks can be sent to the S7 which are there received by theBRECV block service. Two blocks with different contents can be sent. This can be used, forexample, for the download of recipe data for the S7.NET OPC UA-ClientEntry-ID: 42014088, V1.2,12/201711

2 Automation SolutionOverview and description of the convenient user interface (OPC UA .NET Client)The figure and table below describe the interface of the generic OPC UA clientexample with which the information of the namespace of an OPC UA server can beconveniently accessed.The interface also permits browsing the symbolic S7 variables.Figure 2-56213Copyright Siemens AG 2017 All rights reserved45Table 2-4No.Description1.The server can be selected via the Endpoints selection list. For this purpose the list of theavailable OPC UA servers from the corresponding network node is determined. The computer,from which the list is to be prompted, can be entered in the Node text field. If the field is empty,the list will be determined on the local computer.The URL of the OPC UA server can also be entered manually. The URL for the SIMATIC NETOPC UA server it is made up of opc.tcp:// name of computer :55101.2.The connection to the server can be established or terminated via the Connect button.3.In Browse Control the entire address space of the connected server is shown in a hierarchicaltree view. Only hierarchical references are displayed.4.For the selected nodes the attributes are read in Browse Control and they are displayed in thiscontrol.5.With drag-and-drop the variables can be dragged from Browse Control to the monitoring window.For the variable, the NodeID, the sampling interval, the value, the time stamp and the status codeis displayed.6.The properties of the subscription and monitored items can be changed via the context menu inthe monitoring window or via the application menu. This is how e.g. the sampling interval can bechanged.The dialog for writing can also be opened. Doing this, accepts the variables marked in themonitoring window in the dialog.NET OPC UA-ClientEntry-ID: 42014088, V1.2,12/201712

2 Automation SolutionAdvantages of this solutionThe solution presented here offers the following advantages: Easy introduction to OPC UA technology Programming in C# for .NET Easy expandability of the example Reusable program components Access possible via internet and across firewalls Access rights can be assigned individually for users Handling with certificates, encryption and authentication Demonstration of S7 communicationTopics not covered by this applicationThis application does not contain a description for processing or saving data in theOPC UA client e.g. in databases.Copyright Siemens AG 2017 All rights reservedAssumed knowledgeBasic knowledge of the handling of the SIMATIC configuration and programmingtool STEP7 as well as of the Microsoft Visual Studio 2008 developmentenvironment and the programming language C# and object-orientatedprogramming is assumed.2.3Hardware and software components usedThe application was created using the following components:Hardware componentsTable 2-5ComponentQty.Article numberNoteS7-400 CPU 416-3PN/DP16ES7416-3XR05-0AB0Alternatively, any other S7400 with PNIO interfacecan also be used.CP 443-1 Advanced16GK7443-1GX20-0XE0(Optional) Alternatively, anyother S7-capable EthernetCP can also be used.S7-300 CPU 315-2PN/DP16ES7 315-2EH14-0AB0Alternatively, any other S7300 with PNIO interfacecan also be used.CP 343-1 AdvancedIT16GK7 343-1GX31-0XE0(Optional) Alternatively, anyother S7-capable EthernetCP can also be used.S7-1500 CPU 1516-3PN/DP16ES7 516-3AN00-0AB0Alternatively, any other S71500 can be used.Standard PC as OPCUA server1Standard PC as OPCUA client1.NET OPC UA-ClientEntry-ID: 42014088, V1.2,12/2017-Standard-PC (e.g. PGs)with Windows 7/8/10.-Alternatively, the client canalso be operated locally onthe PC.13

2 Automation SolutionSoftware componentsTable 2-6ComponentQty.SIMATIC NET DVDV141STEP 7 ProfessionalV14 SP11Microsoft VisualStudio 20101.NET Framework 4.51Article rnatively, later versionsof VS are also possible.--Example files and projectsThe following list includes all files and projects that are used in this example.Table 2-7Copyright Siemens AG 2017 All rights reservedComponent2.4Note42014088 OPC UAClient DOKU V12 en.pdfThis document.42014088 OPC UAClient CODE V12.zipThis zip file contains the OPC UA clientwith sources and the related STEP 7V14 project.Alternative solutionsOPC Data Access on the basis of COMToday, this automation task is typically solved with the COM based classic OPCData Access interface.Advantages of the solution with COM OPC Data Access: Wide distribution of the interface. Many applications for different tasks support the interface. Easy access for local applications.Disadvantages of the solution with COM OPC Data Access: Complicated DCOM configuration for remote access. No communication possible across firewall or internet boundaries. OPC clients can only be operated on Windows PC systems. Restricted security mechanisms and user authentication only within theframework of the DCOM configuration. No user-defined access rights possible.NET OPC UA-ClientEntry-ID: 42014088, V1.2,12/201714

3 Basics3Basics3.1Basics on OPCOverviewCopyright Siemens AG 2017 All rights reservedIn recent years, the OPC Foundation (an interest group of well-knownmanufacturers for the definition of standard interfaces) has defined a large numberof software interfaces to standardize the information flow from the process level tothe management level. According to the different requirements within an industrialapplication, different OPC specifications have been developed in the past: DataAccess (DA), Alarm & Events (A&E), Historical Data Access (HDA) and DataeXchange (DX). Access to process data is described in the DA specification, A&Edescribes an interface for event-based information, including acknowledgement,HDA describes functions for archived data and DX defines a lateral server to servercommunication.Based on the experience with these classic OPC interfaces, the OPC Foundationdefined a new platform, called OPC Unified Architecture (UA). The aim of this newstandard is the generic description and uniform access to all information which is tobe exchanged between systems or applications. This includes the functionality ofall previous OPC interfaces. Furthermore, it is to generate the possibility of nativelyintegrating the interface in the respective system, irrespective of which operatingsystem the system is operated on and irrespective of the programming language inwhich the system was created.This example discusses the OPC Unified Architecture interface. A detaileddocumentation is available on the SIMATIC NET CD. For more information, pleasego to www.opcfoundation.org.What is OPC?In the past, OPC was a collection of software interfaces for data exchange betweenPC applications and process devices. These software interfaces have been definedaccording to the rules of Microsoft COM (Component Object Model) and cantherefore be easily integrated into Microsoft operating systems. COM or DCOM(Distributed COM) provides the functionality of inter process communication andorganizes the information exchange between applications, even across networkboundaries (DCOM). Using mechanisms of the Microsoft operating system, anOPC client (COM client) can use it to exchange information with an

in SIMATIC NET OPC Server, which will successively replace the existing OPC Data Access (DA) and Alarms & Events (A&E) functions. The main advantages of OPC UA over conventional OPC interfaces are: Communication over the Internet and across firewalls. Optimized, robust and fault-tolerant protocol with integrated security mechanisms.