Saturday, March 28, 2009

Connecting to a Kepware OPC server

I’m investigating the retrieval of status information from my company production machines querying the PLC’s using OPC. This week I downloaded a promising OPC server from Kepware. The product came with samples, but none in a .Net C# version. Browsing the internet didn’t help much. so I decided to just give it a go based on the other language samples and the opcnet API. I installed the Kepware EX trial version. The install went very smoothly, whithout any problems. For coding I used the Visual Studio Express IDE with SP1 installed.

My first piece of code to connect to the server looked like:

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));
}
 
            static void Main(string[] args)
{
Tester tst = new Tester();
tst.Initialize();
Console.ReadLine();
}
}

It all was fairly simple. I discovered that it’s possible to query for the available OPC servers using the ServerEnumerator routine. Below the code to query the available servers and if any is available, connecting to the first one.

class Tester
{
private Opc.Da.Server m_server = null;
private Opc.IDiscovery m_discovery = new OpcCom.ServerEnumerator();

public void Initialize()
{
Opc.Server[] m_servers = m_discovery.GetAvailableServers(Specification.COM_DA_20, "localhost", null);
foreach (Opc.Da.Server server in m_servers)
{
Console.WriteLine(String.Format("server : {0}", server.Name));
}
if (m_servers != null)
m_server[0].Connect();
}
catch (Opc.ConnectFailedException connectionFailure)
{
Console.WriteLine("Connection failure : " + connectionFailure.Message);
}
Console.WriteLine(String.Format("Connection with {0} successfull", m_server.Name));
}
         }

In my next post I’ll try to connect to the server and retrieve some “tag” data from the PLC’s.

No comments:

Post a Comment