Simple OPC client subscribing to an item using OPC .NET API
This is a simple OPC Classic client using OPC .NET API subscribing to an item.Step 1.
Create a .NET console application as outlined in Sample OPC client using OPC .Net APIStep 2. Replace C# console code as shown below
Notes:Replace Hostname with the machine name of the OPC server
Replace "TEST1/SGGN1/OUT.CV" with the item to subscribe.
using System;
using Opc;
using Opc.Da;
using OpcCom;
namespace oClientNet
{
class Program
{
private const string Hostname = "M6"; // machine name or IP
private const string OpcItemId = "TEST1/SGGN1/OUT.CV";
private const int UpdateRateMs = 1000;
static void Main(string[] args)
{
try
{
RunOpcClient();
}
catch (Exception ex)
{
Console.WriteLine($"An error occurred: {ex}");
}
Console.WriteLine("This should close the connection to the server, key to continue");
Console.ReadKey(true);
}
private static void RunOpcClient()
{
string urlString = $"opcda://{Hostname}/OPC.DeltaV.1";
Opc.URL url = new Opc.URL(urlString);
using (Opc.Da.Server server = new Opc.Da.Server(new OpcCom.Factory(), url))
{
server.Connect(new Opc.ConnectData(null, null));
Console.WriteLine("Connected to OPC server.");
// Create subscription state
SubscriptionState state = new SubscriptionState
{
Name = "MySubscription",
UpdateRate = UpdateRateMs,
Active = true
};
using (Subscription subscription = (Subscription)server.CreateSubscription(state))
{
Item opc_item = new Item { ItemName = OpcItemId };
Item[] items = new Item[] { opc_item };
ItemResult[] results = subscription.AddItems(items);
subscription.DataChanged += OnDataChanged;
Console.WriteLine("Subscription created. Press Esc key to exit.");
while (Console.ReadKey(true).Key != ConsoleKey.Escape)
{
}
}
server.Disconnect();
}
}
private static void OnDataChanged(object subscriptionHandle, object requestHandle, ItemValueResult[] values)
{
foreach (ItemValueResult itemValue in values)
{
if (itemValue.Quality == Quality.Good)
{
Console.WriteLine($"{itemValue.ItemName}:{itemValue.Value}");
}
else
{
Console.WriteLine($"Error for {itemValue.ItemName}: Quality={itemValue.Quality}");
}
}
}
}
}
No comments:
Post a Comment