C # Create OPC client to access OPC server

Source: Internet
Author: User

A recent project that needs to communicate with the PLC, so the test uses OPC server. The main record is the client routines written in C #, which are not described in detail elsewhere.

In the first step, OPC server uses the Kepserver 5 version, a lot of information on the web. After the installation is complete, its configuration page is as follows. Configuration, I have configured and Omron PLC connected to project, creating dozens of variables to access the PLC's area address. The specific configuration according to different plc information corresponding configuration on the line.

The second step is to start writing a C # program. Because my code is nested on an existing project, a class is created to implement it. The approximate process is to create a client thread for the OPC server communication with software on. The thread method is a loop to determine if the communication has dropped, and if the drop is disconnected, reconnect. First, add the OPC DLL reference to the project Interop.OPCAutomation.dll

1. Creating Threads

        #region OPC communication thread            try            {                opcclient opcclient = new opcclient ();                Thread thropc = new thread (opcclient.opcclientoperate);                Thropc.isbackground = True;                Thropc.start ();            }            Catch {}            #endregion        

2. Create a class

Using system;using system.collections.generic;using system.io;using system.linq;using  System.text;using opcautomation;using model;using system.threading;namespace bll{public class  opcclient {#region Global variables///<summary>//OPC corresponding PLC location///</summary> public static dictionary<string, OPCI temparameter> DTOPCTOPLC = new dictionary<string, opcitemparameter>();///<summary>//OPC server information// /</summary> public static opcinformation opcinformation = new opcinformation (); #endregion///<summary> ; Initialize              ///</summary> Public

The DTOPCTOPLC in the above is a background configuration for configuring the name and corresponding properties of the variable that you want to get in the OPC server, because the project implementation can be changed, and the information can only be obtained in the form of configuration.

Opcinformation is an instance of information created with OPC communication.

Two examples are as follows

<summary>//OPC parameter information///</summary> public classOpcitemparameter {publicOpcitemparameter () {this. Changetime =DateTime.Now; }///<summary>//Initialize///</summary>//<param name= "PName" &GT;OPC Item name &LT;/PA ram>//<param name= "Plcname" &GT;PLC naming </param>///<param name= "handle" > Client handle &LT;/PARAM&G        T <param name= "Value" > Value </param> public opcitemparameter (String pName, string plcname, int handle, intValue) {this. ParameterName =PName; This. Plcname =Plcname; This. Itemhandle = handle; Value =  value; Changetime =  DateTime.Now; Iswriteok = False ;}///<summary>//client parameter handle///</summary> public int Itemhandle {get; set ;} <summary>////For the parameter name of the PLC value (OPC server naming)///</summary> public string ParameterName {get; set ;}// /<summary>///PLC Location name///</summary> public string Plcname {get; set ;}//<summary>///Parameter value/ </summary> public int Value {get; set ;}///<summary>//quality//</summary> public string Qua lities {get; set ;}//<summary>//time stamp///</summary> public string timestamps {get; set ;}/ <summary>////value change time for post-task priority///</summary> public DateTime changetime {get; set ;}//<summ Ary>///Whether the write succeeds//</summary> public bool Iswriteok {get; set ;}}      
#region OPC Server class information///<summary>///OPC server parameter information///</summary> public classopcinformation {publicOpcinformation () {this. Ip = string.            Empty; This. HostName = string.            Empty; This. Connectstate = False; This. Groupsstate = False; This. connectcontents = "Opc Failed"; }///<summary>///IP address///</summary> public string IP {get; set; }///<summary>/////</summary> public string HostName {get; set; }///<summary>//OPC server name///</summary> public string ServerName {get; set;} <summary>///server handle///</summary> public int Itmhandleserver {get; set ;}//<summary>// OPC server object///</summary> public opcserver kepserver {get; set ;}///<summary>//OPC Group collection Object///</SU Mmary> public opcgroups kepgroups {get; set ;}//<summary>//OPC Group object///</summary> public OPCGR OUP Kepgroup {get; set ;}///<summary>//OPC Item collection object///</summary> public opcitems kepitems {get; set ;} <summary>///OPC Item Object///</summary> public opcitem Kepitem {get; set ;}//<summary>///Connector State//</summary> public bool Connectstate {get; set ;}///<summary>//connection Contents//</summary> Publ IC string connectcontents {get; set ;}//<summary>//Create Group succeeded///</summary> public bool Groupsstat e {get; set ;}} #endregion          

3, the following for the creation of communication and loop to determine whether to drop the line, the main purpose is to create a new connection and drop line is able to quickly respond to the reconnection

<summary>////For business processing of OPC-acquired data///</summary> public voidOpcclientoperate () {int lineoffcount = 0;//drop judgment count while (true) {Try {if (!                         Opcinformation.connectstate) {//connection unsuccessful, attempt to reconnect if  (Getlocalserver ()) {//Get OPC Server information successfully if  (Connectremoteserver ()) {//Connect OPC successfully opcinformation.conn Ectstate = True ; Recurbrowse (OpcInformation.KepServer.CreateBrowser ()); }} else  {Thread.Sleep ;}} else  {if (!  Opcinformation.groupsstate) {//Create Group collection failed, attempt to recreate opcinformation.groupsstate =  creategroup ();} else  {// Determine status in time to re-connect }}} catch  (Exception ex) {opcinformation.connectstate = False ; Opcinformation.connectconten TS = "OPC disconnected" ; opcinformation.groupsstate = False ; try  { OpcInformation.KepServer.Disconnect (); } catch  {}}//thread.sleep (100); }}                /span>   

4, when the connection, OPC DLL control has a data change response event creation call on the line

<summary>///events that are executed whenever the item data changes///</summary>//<param name= "TransactionID" > Handling I d</param>//<param name= "NumItems" > Number of items </param>//<param name= "Clienthandles" > Customer End handle </param>///<param name= "itemvalues" >tag value </param>//<param name= "qualities" > Quality </param>//<param name= "timestamps" > Timestamp </param> private void kepgroup_datachange (int Tra Nsactionid, int numitems, ref array clienthandles, ref array itemvalues, ref array qualities, refArray Timestamps)                    {for (int i = 1; I <= NumItems; i++) {try { int index = int. Parse (Clienthandles.getvalue (i).                    ToString ()); String key = Dtopctoplc.firstordefault (o = O.value.itemhandle = = index). Key; if (!string. IsNullOrEmpty (key)) {//need to determine type, is int or boolean int value = int. Parse (Itemvalues.getvalue (i). ToString ()); if (Value! = Dtopctoplc[key]. Value) {Dtopctoplc[key]. Value = value; Dtopctoplc[key]. Changetime = DateTime.Now;} Dtopctoplc[key]. qualities = Qualities.getvalue (i). ToString (); Dtopctoplc[key]. timestamps = Timestamps.getvalue (i). ToString (); }} catch {}             }}

5. Write data to OPC server variables

<summary>///To OPC counterpart write value///</summary>//<param name= "value" > Value to write </para        m>//<param name= "Opcitemparameter" >item address </param>///<returns></returns> public static bool Writeopc (intValue, Opcitemparameter opcitem) {try{String key = Dtopctoplc.first (o = O.value.itemhandle = = opcitem.itemhandle).                Key; Dtopctoplc[key].                Iswriteok = False;                Opcitem Bitem = OpcInformation.KepItems.Item (opcitem.parametername); Opcinformation.itmhandleserver = bitem.serverhandle; int[] temp = new Int[2] {0, bitem.serverhandle}; Array serverhandles = (array) temp; object[] valuetemp = new Object[2] {"", value. ToString ()}; Array values = (array) valuetemp; Array Errors; int cancelid; OpcInformation.KepGroup.AsyncWrite (1, ref serverhandles, ref values, out Errors, N, out Canceli D); Kepitem.write (Txtwritetagvalue.text);//This sentence can also be written, but does not trigger the Write event GC. Collect (); return true;} catch {return false;}}            

Very simple, just call the corresponding function to do it.

6. Write Successful response

When the write succeeds, the corresponding response function responds

private void Kepgroup_asyncwritecomplete (int transactionid, int numitems, ref array clienthandles, ref array Errors) c1/>{            try            {for                (int i = 1; I <= NumItems; i++)                {                    int error = int. Parse (Errors.getvalue (i). ToString ());                    int handle = int. Parse (Clienthandles.getvalue (i). ToString ());                    String key = Dtopctoplc.first (o = O.value.itemhandle = = handle). Key; if (Error = = 0) {Dtopctoplc[key]. Iswriteok = True;}} } catch {}}        

Some other basic connection methods (Connectremoteserver, Getlocalserver, Recurbrowse, Setgroupproperty, etc.), is quoted Baidu on other users of the case, do not describe each.

7. Summary

OPC DLL provides a lot of interfaces, relatively simple to call, only need to make simple changes according to the project. For off-line abnormal re-connection, it needs to be handled according to the actual debug case, which takes some time to test.

This case only tested the communication connection of Omron PLC, the other PLC has not been tested in practice.

  

C # Create OPC client to access OPC server

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.