I'm not a C# programmer, but for necessity I'm trying to create a client opc-ua using C#. Searching on the web i found some examples but I could not get the client to work. Can anyone expert help me out?
I attach the complete code below:
using System;
using Opc.UaFx;
using Opc.UaFx.Client;
using System.Collections.Generic;
// using System.IO.Compression;
// using System.Linq;
namespace Client
{
public class Program
{
static void Main(string[] args)
{
using (var client = new OpcClient("opc.tcp://127.0.0.1:62541/"))
{
try
{
client.Connect(); // connection
}
catch
{
Console.WriteLine("I Can't Connect");
}
finally
{
// node list
string[] nodeIds = {
"ns=1;s=[Simulatore OPC Server]ST20543",
"ns=1;s=[Simulatore OPC Server]ST1",
"ns=1;s=[Simulatore OPC Server]ST2",
"ns=1;s=[Simulatore OPC Server]ST3",
"ns=1;s=[Simulatore OPC Server]ST4",
"ns=1;s=[Simulatore OPC Server]ST5",
"ns=1;s=[Simulatore OPC Server]ST6",
"ns=1;s=[Simulatore OPC Server]ST7",
"ns=1;s=[Simulatore OPC Server]ST8",
"ns=1;s=[Simulatore OPC Server]ST9",
"ns=1;s=[Simulatore OPC Server]ST10"
};
// Create an (empty) subscription to which we will addd OpcMonitoredItems.
OpcSubscription subscription = client.SubscribeNodes();
for (int index = 0; index < nodeIds.Length; index++)
{
// Monitored Items
var item = new OpcMonitoredItem(nodeIds[index], OpcAttribute.Value);
item.DataChangeReceived += HandleDataChanged;
item.Tag = index;
item.SamplingInterval = 200;
// Add element to subscription
subscription.AddMonitoredItem(item);
Console.WriteLine("{\"Timestamp\":", "\"", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fffffffK"), "\",\"", "Data Change from NodeId '{0}': {1}", item.DisplayName, item.LastDataChange);
}
// Apply Changes
subscription.ApplyChanges();
}
}
}
// class BROWSE
private void Browse(OpcNodeInfo node, int level = 0)
{
Console.WriteLine("{0}{1}({2})",
new string('.', level * 4),
node.Attribute(OpcAttribute.DisplayName).Value,
node.NodeId);
level++;
foreach (var childNode in node.Children())
Browse(childNode, level);
}
// class HANDLER
private static void HandleDataChanged(object sender, OpcDataChangeReceivedEventArgs e)
{
// Code to be executed
// 'sender' contains MonitoredItem
OpcMonitoredItem item = (OpcMonitoredItem)sender;
// Output
Console.WriteLine("{\"Timestamp\":", "\"", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fffffffK"), "\",\"", "Data Change from NodeId '{0}': {1}", item.DisplayName, e.Item.Value);
}
}
}
The goal is to create a client that subscribes to the server and prints an output (console.writeline) in the format specified in the Handler class at every nodes value change.