using OBMAPI.PublicFunction;
using Opc.Ua;
using OpcUaHelper;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace opcuatest
{
/*
* 注意事项:
* 1.由于与ads通信相兼容 所以读写数据名称,方法传参都用老的ads通讯名称
* 所以有的方法传参对于opcua可能无意义,写空或0即可。
* 2.plc real 对应 C# double
* 3.plc int16 对应 C# short
* 4.需要知道GVL父节点的id
* 5. .net framework 4.6.1以上
* 6 NuGet包搜索OPCUAHELPER 安装
*/
class opcuahelpMethod
{
private OpcUaClient opcUaClient = null;
string ipaddr=null;
Dictionary<string, string> dicNodeNameAndId = new Dictionary<string, string>();
/// <summary>
/// GVL父节点的id
/// </summary>
string parentnodeid = "ns=4;i=1";
#region 连接,断开连接,检查连接状态
/// <summary>
/// IPAddr格式= ip:netid:port
/// netid没有可以为空,这是为了与ads通信格式一致而设计
/// </summary>
/// <param name="IPAddr"></param>
/// <returns></returns>
public int ConnectDev(string IPAddr)
{
if (IPAddr == null)
return 0;
ipaddr = IPAddr;
string[] strNetIDPort = IPAddr.Split(':');
try
{
if (!PingOC(strNetIDPort[0]))
{
Log.WriteLog("<ConnectDev> " + " Fail");
return 0;
}
}
catch (Exception e)
{
return 0;
}
string opcstr = "opc.tcp://" + strNetIDPort[0] + ":" + strNetIDPort[2];
//opcstr = "opc.tcp://118.24.36.220:62547/DataAccessServer";
try
{
if (opcUaClient == null)
{
opcUaClient = new OpcUaClient();
opcUaClient.ConnectServer(opcstr);
getNodeid();
}
if (opcUaClient.Connected)
{
return -1;
}
else
{
DisconnectDev();
Log.WriteLog("<ConnectDev> " + " opcUaClient.Connected: " + opcUaClient.Connected);
return 0;
}
}
catch (Exception err)
{
Log.WriteLog("<ConnectDev> " + err.Message.ToString());
DisconnectDev();
return 0;
}
}
public void DisconnectDev()
{
try
{
if (opcUaClient != null)
{
opcUaClient.Disconnect();
}
opcUaClient = null;
dicNodeNameAndId = null;
}
catch (Exception ex)
{
Log.WriteLog("<DisconnectDev>失败" + ex.Message);
}
}
public bool CheckConnected()
{
int ret = -1;
if (opcUaClient == null)
{
ret = ConnectDev(ipaddr);
}
else
{
try
{
if (opcUaClient.Connected)
{
return true;
}
else
{
Log.WriteLog("<CheckConnected> " + " opcUaClient.Connected: " + opcUaClient.Connected);
return false;
}
}
catch (Exception e)
{
Log.WriteLog("<CheckConnected> " + e.Message.ToString());
DisconnectDev();
return false;
}
}
if (ret == 0)
{
Log.WriteLog("<CheckConnected> ret==0");
DisconnectDev();
return false;
}
return true;
}
public bool PingOC(String ips)//2020.04.23 by Irving
{
bool ret;
Process p = new Process();
p.StartInfo.FileName = "cmd.exe";
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardInput = true;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardError = true;
p.StartInfo.CreateNoWindow = true;
int i = 0;
p.Start();
p.StandardInput.WriteLine("ping -n 1 " + ips);
p.StandardInput.WriteLine("exit");
string strRst = p.StandardOutput.ReadToEnd();
if (strRst.IndexOf("(100%") == -1)
{
ret = true;
}
else
{
ret = false;
}
p.Close();
return ret;
}
#endregion
#region 根据GVL父节点获取GVL所有子节点,组成键值对
private void getNodeid()
{
#region 获取opcua根目录所有节点,目前不用
//ReferenceDescriptionCollection referenceDescriptionCollection;
//byte[] continuationPoint;
//opcUaClient.Session.Browse(null, null, ObjectIds.RootFolder, 0u, BrowseDirection.Forward, ReferenceTypeIds.HierarchicalReferences, true, (uint)NodeClass.Variable | (uint)NodeClass.Object | (uint)NodeClass.Method, out continuationPoint, out referenceDescriptionCollection);
#endregion
ReferenceDescription[] references = opcUaClient.BrowseNodeReference(parentnodeid);
foreach (var item in references)
{
if ("GVL".Equals(item.DisplayName.ToString().ToUpper()))
{
ReferenceDescription[] refer = opcUaClient.BrowseNodeReference(item.NodeId.ToString());
foreach (var items in refer)
{
ReferenceDescription[] re = opcUaClient.BrowseNodeReference(items.NodeId.ToString());
if (re.Length!=0)
{
foreach (var it in re)
{
if (it.DisplayName.ToString().Contains("[")&& it.DisplayName.ToString().Contains("]"))
dicNodeNameAndId.Add("GVL." + items.DisplayName.ToString() + it.DisplayName.ToString(), it.NodeId.ToString());
else
dicNodeNameAndId.Add("GVL." + items.DisplayName.ToString() +"."+it.DisplayName.ToString(), it.NodeId.ToString());
}
}
else
dicNodeNameAndId.Add("GVL." + items.DisplayName.ToString(), items.NodeId.ToString());
}
}
}
}
#endregion
#region opcua读写数据基方法
/// <summary>
/// opc ua不需要指定长度 nLength为0即可
/// </summary>
/// <param name="strVName"></param>
/// <param name="nLength"></param>
/// <returns></returns>
public String adsReadString(String strVName, int nLength)
{
String strRet = null;
try
{
strRet = opcUaClient.ReadNode<string>(dicNodeNameAndId[strVName]);
}
catch (Exception ex)
{
Log.WriteLog(Log.LogLevel.EXCEPTION, ex.Message.ToString(), MethodBase.GetCurrentMethod().DeclaringType.Name + "." + MethodBase.GetCurrentMethod().Name);
}
Log.WriteLog(Log.LogLevel.INFO, "adsReadString " + strVName + " " + strRet, MethodBase.GetCurrentMethod().DeclaringType.Name + "." + MethodBase.GetCurrentMethod().Name);
return strRet;
}
public bool adsWriteString(String strVName, String strBuffer, int nLength)
{
bool bRet = false;
try
{
bRet = opcUaClient.WriteNode(dicNodeNameAndId[strVName], strBuffer);
}
catch (Exception err)
{
Log.WriteLog(Log.LogLevel.EXCEPTION, err.Message.ToString(), MethodBase.GetCurrentMethod().DeclaringType.Name + "." + MethodBase.GetCurrentMethod().Name);
bRet = false;
}
Log.WriteLog(Log.LogLevel.INFO, "WriteString " + strVName + " " + strBuffer + " " + bRet, MethodBase.GetCurrentMethod().DeclaringType.Name + "." + MethodBase.GetCurrentMethod().Name);
return bRet;
}
public int adsReadnCommand(String strVName)//2019.09.02 by sim
{
//return 1;
short ret = -1;
bool bRead = false;
for (int i = 0; i < 2; i++)
{
try
{
bRead = adsReadBool(strVName);
if (bRead)
ret = 0;
break;
}
catch (Exception e)
{
bRead = false;
}
}
return (int)ret;
}
public int adsReadInt(String strVName)
{
//return 1;
short ret = 0;
bool bRead = false;
for (int i = 0; i < 2; i++)
{
try
{
ret = opcUaClient.ReadNode<Int16>(dicNodeNameAndId[strVName]);
bRead = true;
break;
}
catch (Exception e)
{
Log.WriteLog("\t adsReadInt " + strVName.ToString() + " " + e.Message.ToString());
bRead = false;
Thread.Sleep(1000);
}
}
Log.WriteLog(Log.LogLevel.INFO, "ReadInt " + strVName + " " + ret.ToString() + " " + bRead, MethodBase.GetCurrentMethod().DeclaringType.Name + "." + MethodBase.GetCurrentMethod().Name);
return (int)ret;
}
public bool adsWriteInt(String strVName, int nValue)
{
//return true;
bool ret = false;
for (int i = 0; i < 2; i++)
{
try
{
ret = opcUaClient.WriteNode(dicNodeNameAndId[strVName], (short)nValue);
Log.WriteLog(Log.LogLevel.INFO, "adsWriteInt " + strVName + " " + nValue + " " + ret, MethodBase.GetCurrentMethod().DeclaringType.Name + "." + MethodBase.GetCurrentMethod().Name);
break;
}
catch (Exception e)
{
Log.WriteLog(Log.LogLevel.INFO, "adsWriteInt " + strVName + " " + nValue + " " + ret + " " + e.Message, MethodBase.GetCurrentMethod().DeclaringType.Name + "." + MethodBase.GetCurrentMethod().Name);
ret = false;
}
}
return ret;
}
public bool adsReadBool(String strVName)
{
bool ret = false;
for (int i = 0; i < 2; i++)
{
try
{
ret = opcUaClient.ReadNode<bool>(dicNodeNameAndId[strVName]);
Log.WriteLog(Log.LogLevel.INFO, "adsReadBool " + strVName + " " + ret, MethodBase.GetCurrentMethod().DeclaringType.Name + "." + MethodBase.GetCurrentMethod().Name);
}
catch (Exception e)
{
Log.WriteLog(Log.LogLevel.INFO, "adsReadBool " + strVName + " " + e.Message, MethodBase.GetCurrentMethod().DeclaringType.Name + "." + MethodBase.GetCurrentMethod().Name);
Thread.Sleep(1000);
}
}
return ret;
}
public bool adsWriteBool(String strVName, bool bValue)
{
//return true;
bool ret = false;
for (int i = 0; i < 2; i++)
{
try
{
ret = opcUaClient.WriteNode(dicNodeNameAndId[strVName], bValue);
Log.WriteLog(Log.LogLevel.INFO, "adsWriteBool " + strVName + " " + bValue + " " + ret, MethodBase.GetCurrentMethod().DeclaringType.Name + "." + MethodBase.GetCurrentMethod().Name);
}
catch (Exception e)
{
//contiue;
Log.WriteLog(Log.LogLevel.INFO, "adsWriteBool " + strVName + " " + e.Message, MethodBase.GetCurrentMethod().DeclaringType.Name + "." + MethodBase.GetCurrentMethod().Name);
Thread.Sleep(1000);
}
}
return ret;
}
public double adsReadRReal(String strVName)
{
//return 1.0d;
int hander;
double ret = 0;
for (int i = 0; i < 2; i++)
{
try
{
ret = opcUaClient.ReadNode<double>(dicNodeNameAndId[strVName]);
Log.WriteLog(Log.LogLevel.INFO, "adsReadRReal " + strVName + " " + ret, MethodBase.GetCurrentMethod().DeclaringType.Name + "." + MethodBase.GetCurrentMethod().Name);
}
catch (Exception e)
{
Log.WriteLog(Log.LogLevel.INFO, "adsReadRReal " + strVName + " " + e.Message, MethodBase.GetCurrentMethod().DeclaringType.Name + "." + MethodBase.GetCurrentMethod().Name);
Thread.Sleep(1000);
}
}
return ret;
}
public bool adsWriteReal(String strVName, double dValue)
{
bool ret = false;
for (int i = 0; i < 2; i++)
{
try
{
ret = opcUaClient.WriteNode(dicNodeNameAndId[strVName], dValue);
Log.WriteLog(Log.LogLevel.INFO, "adsWriteReal " + strVName + " " + dValue + " " + ret, MethodBase.GetCurrentMethod().DeclaringType.Name + "." + MethodBase.GetCurrentMethod().Name);
}
catch (Exception e)
{
Log.WriteLog(Log.LogLevel.INFO, "adsWriteReal " + strVName + " " + e.Message, MethodBase.GetCurrentMethod().DeclaringType.Name + "." + MethodBase.GetCurrentMethod().Name);
Thread.Sleep(1000);
}
}
return ret;
}
#endregion
}
}