OPC Client sample code 7 OPC Client sample code 7.1 OPC .NET client :
API sample for read / write https://infosys.beckhoff.com/content/1033/tcopcserver/Resources/12162184203/.zip To read or write variables from Beckhoffs TwinCAT OPC-DA-Server via an C# application perform the following simple steps Download and install the Opc.NET Api from the OPC Foundation website Start VisualStudio 2005 and create a new C# console application Go to the Solution Explorer, and add references to OpcNetApi.dllOpcNetApi.Com.dll Use the following code to read and write variables staticvoidMain(string[] args) { // Create a server object and connect to the TwinCATOpcServer Opc.URLurl =newOpc.URL("opcda://localhost/BECKHOFF.TwinCATOpcServerDA"); Opc.Da.Serverserver =null; OpcCom.Factoryfact =newOpcCom.Factory(); server =newOpc.Da.Server(fact,null); server.Connect(url,newOpc.ConnectData(newSystem.Net.NetworkCredential())); // Create a group Opc.Da.Subscriptiongroup; Opc.Da.SubscriptionStategroupState =newOpc.Da.SubscriptionState(); groupState.Name ="Group"; groupState.Active =false; group = (Opc.Da.Subscription)server.CreateSubscription(groupState); // add items to the group Opc.Da.Item[] items =newOpc.Da.Item[3]; items[0] =newOpc.Da.Item(); items[0].ItemName ="PLC1.Value1"; items[1] =newOpc.Da.Item(); items[1].ItemName ="PLC1.Value2"; items[2] =newOpc.Da.Item(); items[2].ItemName ="PLC1.Value3"; items = group.AddItems(items); // write items Opc.Da.ItemValue[] writeValues =newOpc.Da.ItemValue[3]; writeValues[0] =newOpc.Da.ItemValue(); writeValues[1] =newOpc.Da.ItemValue(); writeValues[2] =newOpc.Da.ItemValue(); writeValues[0].ServerHandle = group.Items[0].ServerHandle; writeValues[0].Value = 0; writeValues[1].ServerHandle = group.Items[1].ServerHandle; writeValues[1].Value = 0; writeValues[2].ServerHandle = group.Items[2].ServerHandle; writeValues[2].Value = 0; Opc.IRequestreq; group.Write(writeValues, 321,newOpc.Da.WriteCompleteEventHandler(WriteCompleteCallback),outreq); // and now read the items again group.Read(group.Items, 123,newOpc.Da.ReadCompleteEventHandler(ReadCompleteCallback),outreq); Console.ReadLine(); } staticvoidWriteCompleteCallback(objectclientHandle, Opc.IdentifiedResult[] results) { Console.WriteLine("Write completed"); foreach(Opc.IdentifiedResultwriteResultinresults) { Console.WriteLine("\t{0} write result:
{1}", writeResult.ItemName, writeResult.ResultID); } Console.WriteLine(); } staticvoidReadCompleteCallback(objectclientHandle, Opc.Da.ItemValueResult[] results) TS6120 61 Version: 1.2.0