OPC .NET client : API sample for read / write
Download complete VS2005 Solution
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)
{
Console.WriteLine("Read completed");
foreach(Opc.Da.ItemValueResultreadResultinresults)
{
Console.WriteLine("\t{0}\tval:{1}", readResult.ItemName, readResult.Value);
}
Console.WriteLine();
}