ClientAce: Creating A Simple Windows Form Application

2y ago
137 Views
2 Downloads
220.46 KB
15 Pages
Last View : 1m ago
Last Download : 3m ago
Upload by : Rafael Ruffin
Transcription

Kepware TechnologiesClientAce: Creating a SimpleWindows Form ApplicationJuly, 2013Ref. 1.03 Kepware Technologies

Table of Contents1.Overview. 11.12.Requirements . 1Creating a Windows Form Application . 12.1Adding Controls to the Form . 12.2Initializing Global Variables. 22.2.12.3Examples . 2Adding the Form Load Actions. 32.3.1Advising the Server Management Object for Callbacks . 52.4Subscribing for Data . 52.5Setting Items Active for Polling . 92.6Handling DataChanged Events . 92.7Handling Changes to the Server State. 123.Testing the Project . 134.Summary . 13www.kepware.comiClientAce: Creating a Simple Windows FormApplication

1. OverviewThis document intends to demonstrate the basic steps needed to create a SimpleWindows Form application in Visual Basic .NET (VB .NET) and C-Sharp (C#).Note: The coding practices used in the following examples are the preference of thedeveloper. The project code was developed in Visual Studio 2010 using ClientAce 4.0.Unless noted otherwise, the same steps and procedures can also be used with ClientAce3.5.1.1Requirements Visual Studio 2008 SP1 or higher. ClientAce 3.5 or 4.0. An OPC Server (like KEPServerEX version 5.x).2. Creating a Windows Form Application1.2.3.4.To start, create a new VB .NET or C# project by clicking File New Project.In the list of project templates, locate and select Windows Forms Application.Name the project “MyFormApp” and then click OK.Next, use the Toolbox to drag several controls to the form. In the VB .NET examplebelow, two checkboxes, two textboxes, one progress bar, and a Third-Party gaugecontrol were added.5. Once finished, add a button that will be used to subscribe to the server’s data items.To do so, drag the control from the toolbox to the form.Note: Code must be added in order to perform the OPC processes.2.1Adding Controls to the Form1. In Solution Explorer, right-click on the Main.vb or Main.cs form. Then, selectView Designer.Note: The new form will be named “Form1” by default, but can be renamed ifdesired.www.kepware.com1ClientAce: Creating a Simple Windows FormApplication

2. Next, add the controls to the form that will be used to display the OPC data (ifthey haven’t been added already). Then, right-click the Main.vb or Main.csform and select View Code.2.2Initializing Global VariablesGlobal variables can be used by all methods and functions in the project. Thefollowing objects should be added and initialized: A Server Management Object. This establishes the OPC DA connection to theserver. A Connection Information Collection Object. This specifies the connectionparameters for the Server Management Object connection. A Boolean variable. This tests whether the connection to the serversucceeded. A Server Subscription Handle. This modifies or cancels an active datasubscription. More than one handle will be needed when more than onesubscription is being performed in the same server connection. The handlewill be returned to the application from the server. A Client Subscription Handle. This identifies the data change callbacks sentby the server to the application for each subscription. It is specified by theuser, and must be unique to each subscription. An array of item identifier collection objects. These specify the properties foreach item that is added to a particular subscription.2.2.1 ExamplesThe VB .NET code is displayed below.Public Class MainDim WithEvents daServerMgt As New Kepware.ClientAce.OpcDaClient.DaServerMgtDim connectInfo As New Kepware.ClientAce.OpcDaClient.ConnectInfoDim connectFailed As BooleanDim activeServerSubscriptionHandle As IntegerDim itemIdentifiers(4) As Kepware.ClientAce.OpcDaClient.ItemIdentifierDim clientSubscriptionHandle As IntegerThe C# code is displayed below.public partial class Main : Form{Kepware.ClientAce.OpcDaClient.DaServerMgt DAserver ware.ClientAce.OpcDaClient.ConnectInfo connectInfo l connectFailed;int activeServerSubscriptionHandle;int clientSubscriptionHandle;ItemIdentifier[] itemIdentifiers new ItemIdentifier[5];www.kepware.com2ClientAce: Creating a Simple Windows FormApplication

2.3Adding the Form Load ActionsIn this example, a connection to the OPC Server will be established when theform loads.1. In the project, double-click on the Windows Form. The shell code for FormLoad Events will be added automatically by Visual Studio Intellisense.2. Next, add the code needed to initialize the objects for connection to theserver. URL. This string object specifies the type of OPC Connection, the locationof the server, and the Server ID. OPC Connection options include DA,XML-DA, and UA.oExample OPC DA URL: The OPC DA URL for connection F6-4C0C4804-A122-6F3B160F4397}. The Class ID included in the URL isoptional.oExample OPD UA URL: The OPC UA Endpoint URL (with security)for connection is opc.tcp://127.0.0.1:49320. The UA server that isbeing connected must allow connections that have not beensecured; however, users can create secure connections throughadditional coding.ConnectionInfo. This object specifies the following parameters:oLocaleID: This parameter specifies the client application’s language,number, and date format preferences.oKeepAliveTime: This parameter specifies the interval at which theserver status will be checked.oRetryAfterConnectionError: This parameter specifies whether theserver object will attempt to reconnect to the server if the connectionfails after the initial connection.oRetryInitialConnection: This parameter specifies whether theserver object will retry a connection attempt if the initial attempt fails.oClientName: This parameter allows the client application to provideadditional identity information for the client connection in the form ofa plain language identifier. This parameter is new in ClientAce version4.0.ServerHandle. This unique identifier is assigned by the client applicationfor each server object with which it initializes and establishes aconnection to the server.3. Once finished, set the Connection Failed variable to False.www.kepware.com3ClientAce: Creating a Simple Windows FormApplication

Note: The VB .NET code is displayed below.' Define the server connection URLDim url As String 6-4C0C-4804-A1226F3B160F4397}"' Initialize the connect info object dataconnectInfo.LocalId "en"connectInfo.KeepAliveTime 1000connectInfo.RetryAfterConnectionError TrueconnectInfo.RetryInitialConnection FalseconnectInfo.ClientName "Simple VB Form Example"connectFailed False'define a client handle for the connectionDim ServerHandle As Integer 1Note: The C# code is displayed below.// Define the server connection URLstring url 6-4C0C-4804-A1226F3B160F4397}";// Initialize the connect info object dataconnectInfo.LocalId "en";connectInfo.KeepAliveTime 1000;connectInfo.RetryAfterConnectionError true;connectinfo.RetryInitialConnection false;connectInfo.ClientName "CS Simple Client";connectFailed false;///define a client handle for the connection/int clientHandle 1;4. Next, add the code needed to manage the OPC DA connection to the server.5. Then, set a Try Catch Block to catch and handle any exceptions that areencountered during the connection attempt.Note: The VB .NET code is displayed below.‘Call the API connect method:Try'Try to connectdaServerMgt.Connect(url, ServerHandle, connectInfo, connectFailed)' Handle result:If connectFailed Then' Tell user connection attempt failed:MsgBox("Connect failed")End IfCatch ex As ExceptionMsgBox("Handled Connect exception. Reason: " & ex.Message)' Make sure following code knows connection failed:connectFailed True'Stop processingExit SubEnd Trywww.kepware.com4ClientAce: Creating a Simple Windows FormApplication

Note: The C# code is displayed below.//Try to connect with the API connect method:try{DAserver.Connect (url, clientHandle, ref connectInfo, out connectFailed);}catch (Exception ex){MessageBox.Show ("Handled Connect exception. Reason: " ex.Message);// Make sure following code knows connection failed:connectFailed true;}// Handle result:if (connectFailed){// Tell user connection attempt failed:MessageBox.Show ("Connect failed");}//Subscribe to eventsSubscribeToOPCDAServerEvents();2.3.1 Advising the Server Management Object for CallbacksThe C# code has an additional process that it calls to advise the server orobject for callbacks. The OPC DA specification allows users to acquire datathrough three methods: Synchronous, Asynchronous, and UnsolicitedAsynchronous. The Asynchronous methods require that the ServerManagement Object advise or subscribe for change events.Applications created using C# do this separately from the ServerManagement Object declaration. A separate function is used to subscribe toevents.//Subscribe to server eventsprivate void leted newDaServerMgt.ReadCompletedEventHandler(DAserver ReadCompleted);//DAServer.WriteCompleted newDaServerMgt.WriteCompletedEventHandler(DAserver WriteCompleted);DAserver.DataChanged new DaServerMgt.DataChangedEventHandler(DAserver DataChanged);DAserver.ServerStateChanged rver ServerStateChanged);}Note: Applications created with VB .NET do this when declaring the object.The “WithEvents” keyword specifies that the named object instance can raiseevents. The example below was done in the form declarations.Dim WithEvents daServerMgt As New ibing for DataItems must be added through a subscription in order to get data in anUnsolicited Asynchronous callback event (or a DataChanged Event) in ClientAce.The examples below use a button to initiate the subscription. The button makestwo calls. The first call is to the Subscribe2Data function, where items aresubscribed but inactive. The second call is to the ModifySubscription function,which sets the subscription active.www.kepware.com5ClientAce: Creating a Simple Windows FormApplication

Note: The VB .NET code is displayed below.Private Sub Button1 Click(sender As System.Object, e As System.EventArgs) HandlesButton1.Click'Subscribe to the opc data itemsSubscibe2Data()SubscriptionModify(True)End SubNote: The C# code is displayed below.private void button1 Click(object sender, EventArgs e){//Call the method for subscribing to dataSubscribe2Data();ModifySubscription(true);}The Subscribe2Data function does the following: Initializes the ClientSubscription handle variable. This identifies data in theDataChanged Event that is specific to this subscription. Each subscriptionshould have a unique handle. Initializes the Active variable to False. This specifies whether the subscribeditems will be actively polled from the server. Initializes the UpdateRate variable. This specifies the rate at which thesubscribed items will be polled. Initializes the Deadband variable. This specifies the amount of change that isrequired before a DataChange Event is sent to the client. To disableDeadband, enter zero. Initializes the RevisedUpdateRate variable. This value is returned from theserver to indicate the update rate that the server will support. For example,although a client might request a rate of 1024 milliseconds, the server mightrevise it to 1030 milliseconds. Initializes each element of the ItemIdentifiers array as the ClientAceItemIdentifier and its attributes are initialized. The following four items willbe added to the subscription (indexes 0-4):oItemName: This attribute is the fully-qualified OPC Item Name for thedesired item in the server.oClientHandle: This attribute is a unique number that identifies the itemin callbacks from the server.oDataType: This attribute specifies the item’s data type. Users can additems with or without specifying the data type. In both cases, the serverwill return a RevisedDataType for each item: this attribute is also partof the ItemIdentifier object.Once all the variables and array elements have been initialized, users cansubscribe to the server for data using a Try Catch so that any exceptionerrors will be caught and handled.Once the subscription is complete, the ResultID for the first item will be checkedto see whether it subscribed successfully. If it was, the application will move on.In a live production application, every item that is subscribed should be checkedfor success.www.kepware.com6ClientAce: Creating a Simple Windows FormApplication

Note: The VB .NET code is displayed below.Sub Subscibe2Data()'initialize the client subscription handleclientSubscriptionHandle 1'Parameter to specify if the subscription will be added as active or notDim active As Boolean False' The updateRate parameter is used to tell the server how fast we' would like to see data updates.Dim updateRate As Integer 1000' The deadband parameter specifies the minimum deviation needed' to be considered a change of value. 0 is disabledDim deadBand As Single 0' The revisedUpdateRate parameter is the actual update rate that the' server will be using.Dim revisedUpdateRate As Integer'initialize the itemIdentifier valuesitemIdentifiers(0) New entifiers(0).ItemName andle 0itemIdentifiers(0).DataType NothingitemIdentifiers(1) New entifiers(1).ItemName andle 1itemIdentifiers(1).DataType NothingitemIdentifiers(2) New entifiers(2).ItemName Handle 2itemIdentifiers(2).DataType NothingitemIdentifiers(3) New entifiers(3).ItemName Handle 3itemIdentifiers(3).DataType NothingitemIdentifiers(4) New entifiers(4).ItemName andle 4itemIdentifiers(4).DataType Nothing'Call the Subscribe API Handle, active, updateRate,revisedUpdateRate, deadBand, itemIdentifiers, activeServerSubscriptionHandle)' Check item result ID:If itemIdentifiers(0).ResultID.Succeeded False Then' Show a message box if an item could not be added to subscription.' You would probably use some other means to alert' the user to failed item enrollments in an actual application.MsgBox("Failed to add item " & itemIdentifiers(0).ItemName & " tosubscription")End IfCatch ex As ExceptionMsgBox("Handled Subscribe exception. Reason: " & ex.Message)End TryEnd Subwww.kepware.com7ClientAce: Creating a Simple Windows FormApplication

Note: The C# code is displayed below.private void Subscribe2Data(){// Define parameters for Subscribe method:int itemIndex;//initialize the client subscription handleclientSubscriptionHandle 1;//Parameter to specify if the subscription will be added as active or notbool active false;// The updateRate parameter is used to tell the server how fast we// would like to see data updates.int updateRate 1000;// The deadband parameter specifies the minimum deviation needed// to be considered a change of value. 0 is disabledSingle deadBand 0;// The revisedUpdateRate parameter is the actual update rate that the// server will be using.int revisedUpdateRate;//Initialize the item identifier valuesitemIdentifiers[0] new ItemIdentifier();itemIdentifiers[0].ClientHandle 0;itemIdentifiers[0].DataType ItemName "Channel1.Device1.Bool1";itemIdentifiers[1] new ItemIdentifier();itemIdentifiers[1].ClientHandle 1;itemIdentifiers[1].DataType ItemName "Channel1.Device1.Bool2";itemIdentifiers[2] new ItemIdentifier();itemIdentifiers[2].ClientHandle 2;itemIdentifiers[2].DataType emName "Channel1.Device1.Short1";itemIdentifiers[3] new ItemIdentifier();itemIdentifiers[3].ClientHandle 3;itemIdentifiers[3].DataType emName "Channel1.Device1.Short2";itemIdentifiers[4] new ItemIdentifier();itemIdentifiers[4].ClientHandle 4;itemIdentifiers[4].DataType emName ientSubscriptionHandle, active, updateRate, outrevisedUpdateRate, deadBand, ref itemIdentifiers, out activeServerSubscriptionHandle);for (itemIndex 0; itemIndex 4; itemIndex ){if (itemIdentifiers[itemIndex].ResultID.Succeeded false){MessageBox.Show("Failed to add item " itemIdentifiers[itemIndex].ItemName " to subscription");}}}catch (Exception ex){MessageBox.Show("Handled Subscribe exception. Reason: " ex.Message);}}www.kepware.com8ClientAce: Creating a Simple Windows FormApplication

2.5Setting Items Active for PollingItems may be set active for polling after they have been added with asubscription modification function, which is called from the button click aftersubscribing to the server for items. The function is passed, and the Booleanvalue that is used is the SubscriptionModify Method of the Server ManagementObject. This method uses the ActiveServerSubscription Handle (which wasreturned from the server in the data subscription) and the Action value that wassent when it was called. In this case, the Action value is True.Note: The VB .NET code is displayed below.Sub SubscriptionModify(ByVal action As Boolean)'Set the subscription active or rSubscriptionHandle, action)End SubNote: The C# code is displayed below.private void ModifySubscription(bool action){//Modify the Subscription to set it criptionHandle, action);}2.6Handling DataChanged EventsIf all the items were successfully subscribed, the server should now be pollingthe device at the update rate specified in the subscription. Any of the subscribeditems that change in value or quality will be sent to the client application in aDataChanged Event. In the code examples below, the events are received andthen processed through an event handler on a new thread through theBeginInvoke() Method.Note: The VB .NET code is displayed below.Private Sub daServerMgt DataChanged(clientSubscription As Integer, allQualitiesGood As Boolean,noErrors As Boolean, itemValues() As Kepware.ClientAce.OpcDaClient.ItemValueCallback) HandlesdaServerMgt.DataChangedBeginInvoke(New gedEventHandler(AddressOfDataChanged), New Object() {clientSubscription, allQualitiesGood, noErrors, itemValues})End SubNote: The C# code is displayed below.public void DAserver DataChanged(int clientSubscription, bool all

Application 2.3 Adding the Form Load Actions In this example, a connection to the OPC Server will be established when the form loads. 1. In the project, double-click on the Windows Form. The shell code for Form Load Events will

Related Documents:

The Windows The Windows Universe Universe Windows 3.1 Windows for Workgroups Windows 95 Windows 98 Windows 2000 1990 Today Business Consumer Windows Me Windows NT 3.51 Windows NT 4 Windows XP Pro/Home. 8 Windows XP Flavors Windows XP Professional Windows XP Home Windows 2003 Server

AutoCAD 2000 HDI 1.x.x Windows 95, 98, Me Windows NT4 Windows 2000 AutoCAD 2000i HDI 2.x.x Windows 95, 98, Me Windows NT4 Windows 2000 AutoCAD 2002 HDI 3.x.x Windows 98, Me Windows NT4 Windows 2000 Windows XP (with Autodesk update) AutoCAD 2004 HDI 4.x.x Windows NT4 Windows 2000 Windows XP AutoCAD 2005 HDI 5.x.x Windows 2000 Windows XP

A computer with at least a 450MHz Pentium CPU with 128 MB of RAM, running Windows 2000, Windows XP, Windows Server 2003, Windows Vista, Windows Server 2008, Windows 7, Windows 8/8.1, Windows 10, Windows Server 2012, Windows Server 2016 or Windows Server 2019 platforms. Instal

Windows 8.1 *6 Windows Server 2003 *7 Windows Server 2008 *8 Windows Server 2012 *9 Mac OS X *10: Supported *1 Printer drivers support both 32-bit and 64-bit Windows. *2 Microsoft Windows XP Professional Edition/Microsoft Windows XP Home Edition *3 Microsoft Windows Vista Ultimate/Microsoft Windows Vista Enterprise/Microsoft Windows Vista Business/

Microsoft Windows 7, 32-bit and 64-bit Microsoft Windows 8 & 8.1, 32-bit and 64-bit Microsoft Windows 10, 32-bit and 64-bit Microsoft Windows Server 2008 R2 Microsoft Windows Server 2012, 64-bit only RAM: Minimum 2 GB for the 32-bit versions of Microsoft Windows 7, Windows 8, Windows 8.1, and Windows 10.

Machine Edition Product Windows 7SP1 Windows 8 and 8.1 Windows 10 QP View Developer - QP Logic Developer – PC - o Windows 7 Ultimate, Windows 7 Enterprise, Windows 7 Professional and Windows 10. Notes The above versions of Windows are supported in both 32-bit and 64-bit. Windows regional settings must be set to English.

- 32 & 64 bit Windows 7, Windows 8 & Windows 10 - 32 & 64 bit Windows 2008 Server - Windows 2008 Server R2 - Windows Server 2012 - Windows Server 2012 R2 - Windows Server 2016 NOTE: Microsoft .Net Framework 4.5 is required on all o

ANsi A300 (Part 9) and isA bMP as they outline how risk tolerance affects risk rating, from fieldwork to legal defense, and we wanted to take that into account for the Unitil specification. The definitions and applications of the following items were detailed: