1.使用OpcUaHelper类https://github.com/dathlin/OpcUaHelper
2.自建变量基恩士节点:ns=4;s="变量名"
using Newtonsoft.Json.Linq;
using Opc.Ua;
using Opc.Ua.Client;
using OpcUaHelper;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Reflection.Emit;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
//实例化操作
OpcUaClient m_OpcUaClient = new OpcUaClient();
private async void button1_Click(object sender, EventArgs e)
{
if (this.button1.Text == "连接")
{
// 连接服务器
try
{
string ip = "opc.tcp://" + this.textBox1.Text + ":" + this.textBox2.Text;
//设置匿名连接
m_OpcUaClient.UserIdentity = new UserIdentity(new AnonymousIdentityToken());
await m_OpcUaClient.ConnectServer("opc.tcp://192.168.0.10:4840");
}
catch (Exception ex)
{
ClientUtils.HandleException("连接失败!", ex);
return;
}
MessageBox.Show("连接成功");
this.button1.Text = "断开";
}
else
{
try
{
m_OpcUaClient.Disconnect();
}
catch (Exception ex)
{
ClientUtils.HandleException("关闭连接失败!", ex);
}
MessageBox.Show("连接已断开");
this.button1.Text = "连接";
}
}
private void button2_Click(object sender, EventArgs e)
{
//同步单节点数据读取
try
{
this.label3.Text = "SigRun[1].MainStep";
//UInt16 value = m_OpcUaClient.ReadNode<UInt16>("ns=4;s="+ label3.Text);//
m_OpcUaClient.AddSubscription("A", "ns=4;s=" + this.label3.Text, SubCallback);
//this.textBox3.Text = value.ToString();
}
catch (Exception ex)
{
ClientUtils.HandleException("读取失败!", ex);
}
}
private void button3_Click(object sender, EventArgs e)
{
bool success = false;
this.label4.Text = this.label3.Text;
string nodeId = "ns=4;s=" + this.label4.Text;
if (m_OpcUaClient != null && m_OpcUaClient.Connected)
{
if (!string.IsNullOrEmpty(nodeId) && this.textBox4.Text != null)
{
try
{
success = m_OpcUaClient.WriteNode(nodeId, ushort.Parse(textBox4.Text));
}
catch (Exception ex)
{
string str = "当前节点:" + nodeId + " 写入失败";
ClientUtils.HandleException(str, ex);
}
}
}
}
//单节点数据订阅的回调函数
private void SubCallback(string key, MonitoredItem monitoredItem, MonitoredItemNotificationEventArgs args)
{
if (InvokeRequired)
{
Invoke(new Action<string, MonitoredItem, MonitoredItemNotificationEventArgs>(SubCallback), key, monitoredItem, args);
return;
}
if (key == "A")
{
//如果有多个的订阅值都关联了当前的方法,可以通过key和monitoredItem来区分
MonitoredItemNotification notification = args.NotificationValue as MonitoredItemNotification;
if (notification != null)
{
this.textBox3.Text=notification.Value.WrappedValue.Value.ToString();
}
}
}
}
}