1、Opc 基金会git地址:OPC Foundation · GitHub
其中:UA-.NETStandard 、UA-.NETStandard-Samples比价有参考价值
2、参数传递方式:ns=2;s=参数名(ns表示命名空间索引,一般为2)
特殊情况可以查看所有命名空间:ns=0;i=2255,也可以用(OpcUaHelper.Tool)工具查看
下载地址:C#opc学习资源代码-其它文档类资源-CSDN下载
3、根据opc基金会提供方法整理出调用代码:OPCUAC#控制类库-制造文档类资源-CSDN下载
using Opc.Ua;
using Opc.Ua.Client;
using Opc.Ua.Configuration;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
namespace OPCUALink
{
///
/// OPC UA Client with examples of basic functionality.
///
public class UAClient
{
#region Constructors
public UAClient(bool isdebug = false)
{
if (isdebug)
{
return;
}
ApplicationInstance application = new ApplicationInstance();
application.ApplicationName = SessionName;
application.ApplicationType = ApplicationType.Client;
//加载配置文件
application.LoadApplicationConfiguration(ConfigPath, silent: false).Wait();
// check the application certificate.
//application.CheckApplicationInstanceCertificate(silent: false, minimumKeySize: 0).Wait();
m_validateResponse = ClientBase.ValidateResponse;
m_configuration = application.ApplicationConfiguration;
m_configuration.CertificateValidator.CertificateValidation += CertificateValidation;
ReceiveMsg += Msg;
}
#endregion
#region Public Properties
///
/// session.
///
public Session Session => m_session;
public static string conStr = "ns=3;s=";
///
/// session名称
///
public string SessionName { get; set; } = "DefaultSession";
///
/// opcua服务地址
///
public string ServerUrl { get; set; } = "opc.tcp://192.168.0.1/";
///
/// 配置文件
///
public string ConfigPath { get; set; } = "ConsoleReferenceClient.Config.xml";
///
/// 日志委托
///
public Action LogAction { get; set; } = t => { Console.Write(t); };
///
/// 订阅委托
///
///
///
public delegate void ShowMonitoredItemNotification(string DisplayName, string Value);
public ShowMonitoredItemNotification ReceiveMsg;
#endregion
#region Public Methods
///
/// 连接服务器
///
public async Task ConnectAsync()
{
try
{
//if (m_session != null && m_session.Connected && m_session.SessionId.ToString() == null)
//{
// LogAction?.Invoke("Session already connected!");
//}
//else
//{
// LogAction?.Invoke("Connecting...");
// EndpointDescription endpointDescription = CoreClientUtils.SelectEndpoint(ServerUrl, false);
// EndpointConfiguration endpointConfiguration = EndpointConfiguration.Create(m_configuration);
// Session session = await Session.Create(endpoint: new ConfiguredEndpoint(null, endpointDescription, endpointConfiguration), configuration: m_configuration, updateBeforeConnect: false, checkDomain: false, sessionName: m_configuration.ApplicationName, sessionTimeout: 1800000u, identity: new UserIdentity(), preferredLocales: null);
// if (session?.Connected ?? false)
// {
// m_session = session;
// }
// LogAction?.Invoke("New Session Created with SessionName = " + m_session.SessionName);
// WriteLogWorkDate_n("OpcUa", "连接成功:" + ServerUrl);
//}
if (m_session != null && m_session.Connected == true && m_session.SessionId.ToString() == null)
{
LogAction?.Invoke("Session already connected!");
}
else
{
//Conect();
LogAction?.Invoke("Connecting...");
// Get the endpoint by connecting to server's discovery endpoint.
// Try to find the first endopint without security.
EndpointDescription endpointDescription = CoreClientUtils.SelectEndpoint(ServerUrl, false);
EndpointConfiguration endpointConfiguration = EndpointConfiguration.Create(m_configuration);
ConfiguredEndpoint endpoint = new ConfiguredEndpoint(null, endpointDescription, endpointConfiguration);
// Create the session
Session session = await Session.Create(
m_configuration,
endpoint,
false,
false,
m_configuration.ApplicationName,
30 * 60 * 1000,//30 * 60 * 10,//
new UserIdentity(),
null
);
// Assign the created session
if (session != null && session.Connected)
{
m_session = session;
}
// Session created successfully.
LogAction?.Invoke($"New Session Created with SessionName = {m_session.SessionName}");
WriteLogWorkDate_n("OpcUa", "连接成功:" + ServerUrl);
}
return true;
}
catch (Exception ex)
{
// Log Error
LogAction?.Invoke($"Create Session Error : {ex.Message}");
WriteLogWorkDate_n("OpcUa", "连接失败:" + ServerUrl + ":" + ex.Message);
ConnectAsync().Wait();
return false;
}
}
private async void Conect()
{
LogAction?.Invoke("Connecting...");
// Get the endpoint by connecting to server's discovery endpoint.
// Try to find the first endopint without security.
EndpointDescription endpointDescription = CoreClientUtils.SelectEndpoint(ServerUrl, false);
EndpointConfiguration endpointConfiguration = EndpointConfiguration.Create(m_configuration);
ConfiguredEndpoint endpoint = new ConfiguredEndpoint(null, endpointDescription, endpointConfiguration);
// Create the session
Session session = await Session.Create(
m_configuration,
endpoint,
false,
false,
m_configuration.ApplicationName,
30 * 60 * 10,//30 * 60 * 1000,
new UserIdentity(),
null
);
// Assign the created session
if (session != null && session.Connected)
{
m_session = session;
}
// Session created successfully.
LogAction?.Invoke($"New Session Created with SessionName = {m_session.SessionName}");
}
///
/// 断开链接
///
public void Disconnect()
{
try
{
WriteLogWorkDate_n("OpcUa", "断开连接:" + ServerUrl);
if (m_session != null)
{
LogAction?.Invoke("Disconnecting...");
m_session.Close();
m_session.Dispose();
m_session = null;
// Log Session Disconnected event
LogAction?.Invoke("Session Disconnected.");
}
else
{
LogAction?.Invoke("Session not created!");
}
}
catch (Exception ex)
{
// Log Error
LogAction?.Invoke($"Disconnect Error : {ex.Message}");
}
}
string oldword = "";
///
/// 读单个节点
///
///
/// ns=4;s=A_AGV到周转桶
/// ns=0;i=2255 查看所有命名空间
public T ReadNode(string location)
{
#region
//DataValue dataValue = null;
//if (m_session == null || !m_session.Connected)
//{
// ConnectAsync();
//}
//try
//{
// dataValue = m_session.ReadValue(conStr + location);
//}
//catch
//{
// ConnectAsync();
// dataValue = m_session.ReadValue(conStr + location);
//}
//return (T)dataValue.Value;
#endregion
if (m_session == null || m_session.Connected == false)
{
ConnectAsync().Wait();
}
DataValue value = null;
try
{
value = m_session.ReadValue(conStr + location);
}
catch (Exception)
{
ConnectAsync().Wait();
value = m_session.ReadValue(conStr + location);
}
string newword = "读单个节点:" + location + ":" + value.Value;
if (newword != oldword)
{
WriteLogWorkDate_n("OpcUa", newword);
oldword = newword;
}
return (T)value.Value;
}
///
/// 读多个节点
///
///
///
///
public List ReadNodes(List locations)
{
for (int i = 0; i < locations.Count; i++)
{
locations[i] = conStr + locations[i];
}
if (m_session == null || m_session.Connected == false)
{
ConnectAsync().Wait();
}
var typeList = new List();
foreach (var location in locations)
{
typeList.Add(typeof(T));
}
var nodeIds = locations.Select(t => new NodeId(t)).ToList();
List