Saturday, March 28, 2009

Retrieving information from a “tag” using C# and Kepware OPC server

As promised on my previous post this post will show you how to connect and retrieve some data from a PLC connect through the Kepware EX server. The picture  shows the main screen of the  Kepware KEPServerEX

server. The structure is “channel”, “device” , “tag”. On the screen e.g. “Channel_0_User_Defined”, “Ramp”, “Ramp4”. For each tag the name, address, data type, scan rate, scaling and description are shown.

My first attempt will be to query just 2 tags on different channels and devices.

class Tester
{
private Opc.Da.Server m_server = null;

public void Initialize()
{
Opc.URL m_url = new Opc.URL("opcda://localhost/KEPware.KEPServerEx.V4");
m_server = new Opc.Da.Server(new OpcCom.Factory(), m_url) ;
try
{
if (m_server != null)
m_server.Connect();
}
catch (Opc.ConnectFailedException connectionFailure)
{
Console.WriteLine("Connection failure : " + connectionFailure.Message);
}
Console.WriteLine(String.Format("Connection with {0} successfull", m_server.Name));
}

public void QueryOPCTags()
{
Opc.Da.Item item = new Item();
Opc.Da.Item[] m_items = new Item[2]; // Define two elements
item.ItemName = "Channel_0_User_Defined.Ramp.Ramp4";
m_items[0] = item;
item = new Item();
item.ItemName = "Channel_1.Device_1.Tag_2";
m_items[1] = item;
ItemValueResult[] itemValues = null;
try
{
itemValues = m_server.Read(m_items);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
if (itemValues.Length > 0)
{
foreach (ItemValueResult value in itemValues)
{
Console.WriteLine("Item name:{0},value:{1},quality:{2}", value.ItemName, value.Value, value.Quality);
}
}
}


            static void Main(string[] args)
{
Tester tst = new Tester();
tst.Initialize();
tst.QueryOPCTags();


                Console.ReadLine();
}
}
}





The routine QueryOpcTags creates 2 tags and adds them to the tag array (m_items). It will then query the server to read the information from the defined tags and store the retrieved information in the ItemValueResult collection.



The result of running this piece of code will look like..



OPCTestOutputScreen



Although that the program is not very useful due to the static nature, it at least shows that we can get some information out of the “machine” using some C# code. In my next post I’ll extend the sample to retrieve information whenever a observed tag changes.

No comments:

Post a Comment