TS6120 | TwinCAT OPC Server

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

static void Main( string [] args)
{
// Create a server object and connect to the TwinCATOpcServer
Opc. URL url = new Opc. URL ( "opcda://localhost/BECKHOFF.TwinCATOpcServerDA" );
Opc.Da.
Server server = null ;
OpcCom.
Factory fact = new OpcCom. Factory ();
server =
new Opc.Da. Server (fact, null );
server.Connect(url,
new Opc. ConnectData ( new System.Net. NetworkCredential ()));

// Create a group
Opc.Da. Subscription group;
Opc.Da.
SubscriptionState groupState = new Opc.Da. SubscriptionState ();
groupState.Name =
"Group" ;
groupState.Active =
false ;
group = (Opc.Da.
Subscription )server.CreateSubscription(groupState);

// add items to the group
Opc.Da. Item [] items = new Opc.Da. Item [3];
items[0] =
new Opc.Da. Item ();
items[0].ItemName =
"PLC1.Value1" ;
items[1] =
new Opc.Da. Item ();
items[1].ItemName =
"PLC1.Value2" ;
items[2] =
new Opc.Da. Item ();
items[2].ItemName =
"PLC1.Value3" ;
items = group.AddItems(items);

// write items
Opc.Da. ItemValue [] writeValues = new Opc.Da. ItemValue [3];
writeValues[0] =
new Opc.Da. ItemValue ();
writeValues[1] =
new Opc.Da. ItemValue ();
writeValues[2] =
new Opc.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.
IRequest req;
group.Write(writeValues, 321,
new Opc.Da. WriteCompleteEventHandler (WriteCompleteCallback), out req);

// and now read the items again
group.Read(group.Items, 123, new Opc.Da. ReadCompleteEventHandler (ReadCompleteCallback), out req);
Console .ReadLine();
}

static void WriteCompleteCallback( object clientHandle, Opc. IdentifiedResult [] results)
{
Console .WriteLine( "Write completed" );
foreach (Opc. IdentifiedResult writeResult in results)
{
Console .WriteLine( "\t{0} write result: {1}" , writeResult.ItemName, writeResult.ResultID);
}
Console .WriteLine();
}

static void ReadCompleteCallback( object clientHandle, Opc.Da. ItemValueResult [] results)
{
Console .WriteLine( "Read completed" );
foreach (Opc.Da. ItemValueResult readResult in results)
{
Console .WriteLine( "\t{0}\tval:{1}" , readResult.ItemName, readResult.Value);
}
Console .WriteLine();
}