C # uses OpcNetApi.dll and OpcNetApi.Com.dll to operate OPC

Source: Internet
Author: User
Tags foreach sleep thread


I learned a bit about. Net, exactly, but also with this. And many vc6,vb6,vb on the internet. NET but, few C # 's. Now look at this and give an example:



Test platform, is Vs2008,kepserver,opcnetapi.dll and OpcNetApi.Com.dll. Of course I also installed at the same time, Siemens Net2006 and STEP7, where Net2006 is responsible for OPC, may create some DLLs in the system, and so on, because my program to switch to a machine without Net2006 since there are problems, I do not know their computer problems or because they did not install Net2006. Theoretically, however, OpcNetApi.dll and OpcNetApi.Com.dll are sufficient. Also, there are write DLLs and examples under the Net2006 installation path. For example my is the default installation, C:\Program Files\siemens\simatic.net\opc2\samples under the automation, Custom, dotnet, XML four kinds of application examples, interested can study.



The following gives me the code, is based on the console, the code is not long, if you have C # experience and OPC base should not be difficult to understand, but also have comments, I hope you like:



Here is Program.cs, some of the test operations I commented out, you can also play.



Using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Text;
Using System.Threading;
Using Opc;
Using Opc.Da;
Using OpcCom;

Namespace OPCAPITest
{
Class Tester
{
Private Opc.Da.Server m_server = null; / / define the data access server
Private Opc.Da.Subscription subscription = null;//Define group object (subscriber)
Private Opc.Da.SubscriptionState state = null; / / define the group (subscriber) state, equivalent to the parameters of the group in the OPC specification
Private Opc.IDiscovery m_discovery = new OpcCom.ServerEnumerator();//Defines the enumeration of COM server-based interfaces for searching all such servers.
Public void Work()
{
/ / Query server
Opc.Server[] servers = m_discovery.GetAvailableServers(Specification.COM_DA_20,"TX1" , null);
//daver indicates the version of the data access specification, and Specification.COMDA_20 is equal to version 2.0.
//host is the computer name, and null means no network security authentication is required.
If (servers != null)
{
Foreach (Opc.Da.Server server in servers)
{
//server is the OPC data access server that needs to be connected.
If (String.Compare(server.Name,"TX1.KEPware.KEPServerEx.V4",true) == 0)// is true to ignore case
//if (String.Compare(server.Name, "localhost.KEPware.KEPServerEx.V4", true) == 0)//With no computer name local access
{
M_server = server; / / establish a connection.
Break;
}
}
}

      //connect to the server
If (m_server != null)//non-empty connection server
m_server.Connect();
Else
Return;

/ / Set the group status
State = new Opc.Da.SubscriptionState();//Group (subscriber) state, equivalent to the parameters of the group in the OPC specification
state.Name = "test"; / / group name
state.ServerHandle = null; // The handle assigned to the group by the server.
state.ClientHandle = Guid.NewGuid().ToString();//The handle that the client assigns to the group.
state.Active = true; / / activate the group.
state.UpdateRate = 100; / / refresh rate is 1 second.
state.Deadband = 0; / / Dead zone value, set to 0, the server side of the group of any data changes are notified to the group.
state.Locale = null;//Do not set the region value.

/ / Add group
Subscription = (Opc.Da.Subscription)m_server.CreateSubscription(state);//Create a group
/ / Define the Item list
//The corresponding type is: {Byte, Byte, Char, Short, String, Word, Boolean}
String[] itemName = { "BPJ.DB1.dbb0", "BPJ.DB1.dbb1", "BPJ.DB1.dbc2", "BPJ.DB1.dbi3",
"BPJ.DB1.dbs4", "BPJ.DB1.dbw5", "BPJ.DB1.dbx6" };

/ / Define the item list
Item[] items = new Item[7];//Define the data item, ie item
Int i;
For (i = 0; i < items.Length; i++)//item initial assignment
{
Items[i] = new Item();//Create an item Item object.
Items[i].ClientHandle = Guid.NewGuid().ToString();//The handle that the client assigns to this data item.
Items[i].ItemPath = null; //The path of the data item in the server.
Items[i].ItemName = itemName[i]; //The name of the data item in the server.
}

/ / Add Item
subscription.AddItems(items);

/ / Register callback event
subscription.DataChanged += new Opc.Da.DataChangedEventHandler(OnDataChange);

/ / The following test synchronous reading
/ / Read the entire group below
ItemValueResult[] values = subscription.Read(subscription.Items);
/ / The following test the quality of the item
/*if (values[0].Quality .Equals(Opc.Da.Quality.Good))
Console.WriteLine("Detection Quality Success!");*/
/ / read the following group
Item[] r_items=new Item[2];
For (i = 1; i < 3; i++)
R_items[i-1] = subscription.Items[i];
ItemValueResult[] values2 = subscription.Read(r_items);
/ / The following traversal of all the values read
/*foreach (ItemValueResult value in values2)
{
Console.WriteLine("Synchronous read: ITEM: {0}, value: {1}, quality: {2}", value.ItemName, value.Value, value.Quality);
}*/

/ / The following test asynchronous read
IRequest quest=null ;
subscription.Read(subscription.Items,1,this.OnReadComplete,out quest ) ;

/ / The following test synchronous write
/ / Write the entire group below
ItemValue[] itemvalues= new ItemValue[subscription.Items.Length];
For (i = 0; i < subscription.Items.Length; i++)
Itemvalues[i] = new ItemValue((ItemIdentifier)subscription.Items[i]);
Itemvalues[0].Value = 255;
Itemvalues[1].Value = 126;
Itemvalues[2].Value = 'A';
Itemvalues[3].Value = -128;
Itemvalues[4].Value = "Good Lucky!";
Itemvalues[5].Value = 65535;
Itemvalues[6].Value = true;
subscription.Write(itemvalues);
Thread.Sleep(500);//suspend the thread to let DataChange reflect
/ / Write the following group
ItemValue[] itemvalues2 = new ItemValue[3];
Itemvalues2[0] = new ItemValue((ItemIdentifier)subscription.Items[1]);//TItem class must be converted to ItemIdentifier before it can be converted into ItemValue
Itemvalues2[1] = new ItemValue((ItemIdentifier)subscription.Items[2]);//TItem class must be converted to ItemIdentifier before it can be converted into ItemValue
Itemvalues2[2] = new ItemValue((ItemIdentifier)subscription.Items[3]);//TItem class must be converted to ItemIdentifier before it can be converted into ItemValue
Itemvalues2[0].Value = 12;
Itemvalues2[1].Value = 112;
Itemvalues2[2].Value = 122;
subscription.Write(itemvalues2);

/ / The following test asynchronous write
Thread.Sleep(500);//suspend the thread to let DataChange reflect
subscription.Write(itemvalues, 1, this.OnWriteComplete, out quest);

//END
Console.WriteLine("************************************** hit <return> to close. ..");
Console.ReadLine();

/ / Cancel the callback event
subscription.DataChanged -= new Opc.Da.DataChangedEventHandler(this.OnDataChange);
/ / Remove the group item
subscription.RemoveItems(subscription.Items);
/ / End: release each resource
m_server.CancelSubscription(subscription);//m_server As explained earlier, the notification server asks to delete the group.
subscription.Dispose();// Forces the .NET Resource Recycle Bin to reclaim all resources for this subscription.
m_server.Disconnect();// disconnect server connection
}

//DataChange callback
Public void OnDataChange(object subscriptionHandle, object requestHandle, ItemValueResult[] values)
{
Console.WriteLine("_____________________DataChange event");
Foreach (ItemValueResult item in values)
{
Console.WriteLine("DataChange event occurred");
Console.WriteLine("ITEM:{0},value:{1}", item.ItemName, item.Value);
Console.WriteLine("ITEM:{0},value:{1}", item.Quality,item.Timestamp);
Console.WriteLine("Event signal handle is {0}", requestHandle);

}

}

//ReadComplete callback
Public void OnReadComplete(object requestHandle, Opc.Da.ItemValueResult[] values)
{
/*Console.WriteLine("Async read name: {0}, value: {1}", values[0].ItemName, values[0].Value);
If ((int)requestHandle == 1)
Console.WriteLine("Event signal handle is {0}", requestHandle); */
}

//WriteComplete callback
Public void OnWriteComplete(object requestHandle, Opc.IdentifiedResult[] values)
{
/*Console.WriteLine("Async write name: {0}, value: {1}", values[0].ItemName, values[0].GetType());
If ((int)requestHandle == 2)
Console.WriteLine("Event signal handle is {0}", requestHandle); */
}

Static void Main(string[] args)
{
Tester tst = new Tester();
tst.Work();
}
}
}


Related Article

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.