zhuhao 3 лет назад
Родитель
Сommit
a77db59142

+ 2 - 5
IMCS_CCS/CCS.csproj

@@ -36,15 +36,12 @@
     <Reference Include="S7.Net">
       <HintPath>bin\Debug\netcoreapp3.1\S7.Net.dll</HintPath>
     </Reference>
-    <Reference Include="SinumerikOpcUaAPI">
-      <HintPath>bin\Debug\netcoreapp3.1\SinumerikOpcUaAPI.dll</HintPath>
+    <Reference Include="Siemens.OpcUA">
+      <HintPath>bin\Debug\netcoreapp3.1\Siemens.OpcUA.dll</HintPath>
     </Reference>
     <Reference Include="StackExchange.Redis">
       <HintPath>bin\Debug\netcoreapp3.1\StackExchange.Redis.dll</HintPath>
     </Reference>
-    <Reference Include="UAClientHelperAPI">
-      <HintPath>bin\Debug\netcoreapp3.1\UAClientHelperAPI.dll</HintPath>
-    </Reference>
     <Reference Include="WinSCPnet">
       <HintPath>bin\Debug\netcoreapp3.1\WinSCPnet.dll</HintPath>
     </Reference>

+ 2 - 1
IMCS_CCS/Entitys/CcsTagValue.cs

@@ -56,6 +56,7 @@ namespace IMCS.CCS.Entitys
     {
         BOOL,
         SHORT,
-        String, 
+        String,
+        Double
     }
 }

+ 44 - 0
IMCS_CCS/Model/vo/RequestOpcUaData.cs

@@ -0,0 +1,44 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Threading.Tasks;
+
+namespace IMCS_CCS.Model.vo
+{
+    public class RequestOpcUaData
+    {
+        public string UserName
+        { get; set; }
+
+        public string Password
+        { get; set; }
+
+        public string ServerUrl
+        { get; set; }
+
+        public string Type
+        { get; set; }
+
+        public string Path
+        { get; set; }
+
+        public List<string> Addresses
+        { get; set; }
+
+        public List<string> Values
+        { get; set; }
+    }
+
+    /// <summary>
+    /// 类型名称
+    /// </summary>
+    public enum OpcUaActionTypeEnum
+    {
+        Connect,
+        Write,
+        Read,
+        Upload,
+        SelectNc,
+        StartNcProgram
+    }
+}

+ 24 - 0
IMCS_CCS/Model/vo/ResponseOpcUaData .cs

@@ -0,0 +1,24 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Threading.Tasks;
+
+namespace IMCS_CCS.Model.vo
+{
+    public class ResponseOpcUaData
+    {
+        public int code
+        { get; set; }
+
+        public bool result
+        { get; set; } = true;
+
+        public string msg
+        { get; set; } = "调用成功";
+
+        public int statusCode { get; set; } = 200;
+
+        public List<string> values
+        { get; set; }
+    }
+}

+ 61 - 20
IMCS_CCS/Service/Impl/TaskJobService.cs

@@ -40,6 +40,8 @@ namespace IMCS.CCS.Service.Impl
 
         private string fanucUrlContext;
 
+        private string opcuacUrlContext;
+
         private string LOG_TITLE_OPCUA = "OPCUA采集";
 
         private string LOG_TITLE_S7 = "S7采集";
@@ -68,7 +70,7 @@ namespace IMCS.CCS.Service.Impl
             Configuration = configuration;
             ecsUrlContext = Configuration.GetConnectionString("ecsUrlContext");
             fanucUrlContext = Configuration.GetConnectionString("fanucUrlContext");
-
+            opcuacUrlContext = Configuration.GetConnectionString("opcuacUrlContext");
         }
 
         /// <summary>
@@ -109,25 +111,39 @@ namespace IMCS.CCS.Service.Impl
                     {
                         List<CcsTagValue> changTagValues = new List<CcsTagValue>();
 
-                        DeviceOPCUat deviceOPCUat = new DeviceOPCUat(device.ServerUrl, device.UserName, device.Password);
-                        if (!deviceOPCUat.IsConnection)
+                        List<string> addresses = new List<string>();
+                        foreach (CcsTagValue tagValue in tagValues)
+                        {
+                            addresses.Add(tagValue.Address);
+                        }
+                        //调用opcua是否连接接口
+                        RequestOpcUaData opcUaReq = new RequestOpcUaData();
+                        opcUaReq.ServerUrl = device.ServerUrl;
+                        opcUaReq.UserName = device.UserName;
+                        opcUaReq.Password = device.Password;
+                        opcUaReq.Type = OpcUaActionTypeEnum.Read.ToString();
+                        opcUaReq.Addresses = addresses;
+                        var Result = await _apiRequestService.RequestAsync(RequsetModeEnum.Post, opcuacUrlContext, opcUaReq, null);
+                        ResponseOpcUaData responseOpcUaData = JsonConvert.DeserializeObject<ResponseOpcUaData>(Result.Message);
+                        if (!Result.IsSuccess || !responseOpcUaData.result)
                         {
                             device.State = false;
                             await _deviceService.UpdateDevice(device);
                             Log.Instance.WriteLogAdd("OpcUA采集异常,连不上设备", LOG_TITLE_OPCUA);
                             return "采集失败,连不上设备";
                         }
-                        else
+                        List<string> values = responseOpcUaData.values;
+                        if (values != null)
                         {
-                            List<string> addresses = new List<string>();
-                            foreach (CcsTagValue tagValue in tagValues)
-                            {
-                                addresses.Add(tagValue.Address);
-                            }
-                            List<string> values = deviceOPCUat.OpcUa_Read(addresses);
                             for (int i = 0; i < tagValues.Count; i++)
                             {
                                 CcsTagValue tagValueData = (CcsTagValue)tagValues[i];
+                                //科学计数法转换
+                                if (values[i].Contains("E") && tagValueData.Type == TagValueReadTypeEnum.Double.ToString())
+                                {
+                                    Decimal d = ChangeToDecimal(values[i]);
+                                    values[i] = d.ToString();
+                                }
                                 if (tagValueData.TagValue != values[i])
                                 {
                                     tagValueData.TagValue = values[i];
@@ -138,13 +154,14 @@ namespace IMCS.CCS.Service.Impl
                                     await _ccsTagValueService.Update(tagValueData);
                                 }
                             }
-                            deviceOPCUat.OpcUa_Close();
-                            //值有变化,重新设置一次redis
-                            if (changTagValues != null && changTagValues.Count > 0)
-                            {
-                                await _redisService.Database.StringSetAsync(redis_key, JsonConvert.SerializeObject(tagValues));
-                            }
                         }
+
+                        //值有变化,重新设置一次redis
+                        if (changTagValues != null && changTagValues.Count > 0)
+                        {
+                            await _redisService.Database.StringSetAsync(redis_key, JsonConvert.SerializeObject(tagValues));
+                        }
+
                     }
                     else
                     {
@@ -999,9 +1016,15 @@ namespace IMCS.CCS.Service.Impl
                     {
                         try
                         {
-
-                            DeviceOPCUat deviceOPCUat = new DeviceOPCUat(device.ServerUrl, device.UserName, device.Password);
-                            if (!deviceOPCUat.IsConnection)
+                            //调用opcua是否连接接口
+                            RequestOpcUaData opcUaReq = new RequestOpcUaData();
+                            opcUaReq.ServerUrl = device.ServerUrl;
+                            opcUaReq.UserName = device.UserName;
+                            opcUaReq.Password = device.Password;
+                            opcUaReq.Type = OpcUaActionTypeEnum.Connect.ToString();
+                            var Result = await _apiRequestService.RequestAsync(RequsetModeEnum.Post, opcuacUrlContext, opcUaReq, null);
+                            ResponseOpcUaData responseOpcUaData = JsonConvert.DeserializeObject<ResponseOpcUaData>(Result.Message);
+                            if (!Result.IsSuccess || !responseOpcUaData.result)
                             {
                                 device.State = false;
                                 Device oldDevice = await _deviceService.GetDeviceById(device.Id);
@@ -1017,7 +1040,6 @@ namespace IMCS.CCS.Service.Impl
                             {
                                 device.State = true;
                                 await _deviceService.UpdateDevice(device);
-                                deviceOPCUat.disConnect();
                                 Log.Instance.WriteLogAdd("OPCUA连接成功,ip:" + device.Ip + ",协议类型:" + device.ProtocolType, LOG_TITLE_DEVICE);
                                 continue;
                             }
@@ -1112,5 +1134,24 @@ namespace IMCS.CCS.Service.Impl
 
         }
 
+        /// <summary>
+        /// 数字科学计数法处理
+        /// </summary>
+        /// <param name="strData"></param>
+        /// <returns></returns>
+        private Decimal ChangeToDecimal(string strData)
+        {
+            Decimal dData = 0.0M;
+            if (strData.Contains("E"))
+            {
+                dData = Convert.ToDecimal(Decimal.Parse(strData.ToString(), System.Globalization.NumberStyles.Float));
+            }
+            else
+            {
+                dData = Convert.ToDecimal(strData);
+            }
+            return dData;
+        }
+
     }
 }

+ 85 - 0
IMCS_CCS/Utils/DeviceProtocol/AProtocolBase.cs

@@ -0,0 +1,85 @@
+using Opc.Ua.Client;
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Threading;
+using System.Threading.Tasks;
+
+namespace IMCS_CCS.Utils.DeviceProtocol
+{
+    public abstract class AProtocolBase
+    {
+        public abstract void ConnectAsync();
+        public abstract void CloseConnect();
+        public abstract object ReadData(int dataType, object dataParameter);
+        public abstract bool WriteData(object obj);
+        public abstract event MonitoredItemNotificationEventHandler OpcUaAlarmNotificationHandle;
+        public string UserName { get; set; }
+        public string UserPassword { get; set; }
+        public abstract bool IsConnected { get; set; }
+        private TaskCompletionSource<bool> mConnectTaskSource;
+        private TaskCompletionSource<bool> mCloseTaskSource;
+
+        public TaskCompletionSource<bool> MConnectTaskSource
+        {
+            get => mConnectTaskSource;
+            set => mConnectTaskSource = value;
+        }
+
+        public TaskCompletionSource<bool> MCloseTaskSource
+        {
+            get => mCloseTaskSource;
+            set => mCloseTaskSource = value;
+        }
+
+        public string IpEndPort { get; set; }
+
+        public bool FinishConnectTask(bool result)
+        {
+            TaskCompletionSource<bool> connectTaskSource = this.mConnectTaskSource;
+            if (connectTaskSource == null || Interlocked.CompareExchange<TaskCompletionSource<bool>>(ref this.mConnectTaskSource, (TaskCompletionSource<bool>)null, connectTaskSource) != connectTaskSource)
+                return false;
+            connectTaskSource.SetResult(result);
+            return true;
+        }
+
+        public bool FinishCloseTask(bool result)
+        {
+            TaskCompletionSource<bool> closeTaskSource = this.mCloseTaskSource;
+            if (closeTaskSource == null || Interlocked.CompareExchange<TaskCompletionSource<bool>>(ref this.mCloseTaskSource, (TaskCompletionSource<bool>)null, closeTaskSource) != closeTaskSource)
+                return false;
+            closeTaskSource.SetResult(result);
+            return true;
+        }
+
+        public event EventHandler Connected;
+        public event EventHandler Error;
+        public event EventHandler Closed;
+
+        protected virtual void OnConnected()
+        {
+            Connected?.Invoke(this, EventArgs.Empty);
+        }
+
+        protected virtual void OnErrorProtocol(ErrorEventArgs ags)
+        {
+            Error?.Invoke(this, ags);
+        }
+
+
+        protected virtual void OnClosed()
+        {
+            Closed?.Invoke(this, EventArgs.Empty);
+        }
+    }
+
+    public class ErrorEventArgs : EventArgs
+    {
+        public Exception Exception { get; private set; }
+
+        public ErrorEventArgs(Exception exception)
+        {
+            this.Exception = exception;
+        }
+    }
+}

+ 26 - 461
IMCS_CCS/Utils/DeviceProtocol/DeviceOPCUat.cs

@@ -1,7 +1,6 @@
 using IMCS.CCS.Utils;
 using Opc.Ua;
-using Opc.Ua.Client;
-using SinumerikOpcUaAPI;
+using Opc.Ua.Client; 
 using System;
 using System.Collections.Generic;
 using System.Linq;
@@ -11,38 +10,20 @@ using System.Threading.Tasks;
 namespace IMCS.CCS.DeviceProtocol
 {
     public class DeviceOPCUat 
-    { 
-        Server opcserver;
+    {  
         EndpointDescription endpointDescription;
         public bool IsOn { get; set; } = false;
 
         public DeviceOPCUat(string url, string username = "OpcUaClient", string pwd = "12345678")
         {
-            if (opcserver == null || !opcserver.Session.Connected)
-            {
-                IsOn = OpcUa_Connection(url, username, pwd);
-                IMCS.CCS.Log.Instance.WriteLogAdd("OPCUA 连接是否成功===>>"+ IsOn);
-            } 
+            
         } 
         
         public bool IsConnection { get; set; } = false;
 
         private void Notification_KeepAlive(Session sender, KeepAliveEventArgs e)
         {
-            try
-            {
-                if (sender != this.opcserver.Session || !ServiceResult.IsBad(e.Status))
-                    return;
-                this.opcserver.Session.Reconnect();
-                IMCS.CCS.Log.Instance.WriteLogAdd($"35----->>----->>----->>----->>----->>----->>----->>----->>----->>----->>----->>Notification_KeepAlive");
-                IsConnection = true;
-            }
-            catch (Exception ex)
-            {
-                IsConnection = false;
-                IMCS.CCS.Log.Instance.WriteLogAdd($"41-->>{ex.Message}"); 
-
-            }
+           
         }
         /// <summary>
         /// 获取NC下边的文件列表
@@ -50,27 +31,16 @@ namespace IMCS.CCS.DeviceProtocol
         /// <returns></returns>
         public ReferenceDescriptionCollection OpcUa_BrowseNode()
         {
-            return opcserver.BrowseNode(new NodeId("Sinumerik/FileSystem/NCExtend/webApiMESFILE/", (ushort)2).ToString());
+            return null;
         }
         #region 终止连接
         public void OpcUa_Close()
         {
-            if (OpcUa_ConState())
-            {
-                opcserver.Disconnect();
-            }
+            
         }
         private bool OpcUa_ConState()
         {
-            if (opcserver != null && opcserver.Session.Connected)
-            {
-                return true;
-            }
-            else
-            {
-                IMCS.CCS.Log.Instance.WriteLogAdd("OPC没有连接"); 
-            }
-            return false;
+           return false;
         }
        
         #endregion
@@ -78,57 +48,18 @@ namespace IMCS.CCS.DeviceProtocol
         #region 写入
         public bool OpcUa_Write(string address, object value)
         {
-            try
-            {  
-                if (OpcUa_ConState())
-                {
-                    opcserver.WriteValues(new List<string>() { value.ToString() }, new List<string>() { address });
-                    return true;
-                }
-                return false;
-            }
-            catch (Exception ex)
-            {
-                IMCS.CCS.Log.Instance.WriteLogAdd($"92-->{ex.Message}"); 
-                return false;
-            }
+            return false;
         }
         public bool OpcUa_WriteValue(string address, object value)
         {
-            try
-            {
-                string str = new NodeId(address, (ushort)2).ToString();
-
-                if (OpcUa_ConState())
-                {
-                    opcserver.WriteValues(new List<string>() { value.ToString() }, new List<string>() { str });
-                    return true;
-                }
-                return false;
-            }
-            catch (Exception ex)
-            {
-                IMCS.CCS.Log.Instance.WriteLogAdd($"110->{ex.Message}"); 
+           
                 return false;
-            }
+            
         }
 
         public bool OpcUa_WriteValue(List<string> addresses, List<string> values)
         {
-            try
-            {  
-                if (OpcUa_ConState())
-                {
-                    opcserver.WriteValues(addresses, values);
-                    return true;
-                }
-                return false;
-            }
-            catch (Exception ex)
-            {
-                IMCS.CCS.Log.Instance.WriteLogAdd($"110->{ex.Message}");
-                return false;
-            }
+            return false;
         }
         #endregion
 
@@ -136,196 +67,37 @@ namespace IMCS.CCS.DeviceProtocol
         public bool OpcUa_Select(string filename)
         {
             bool result = false;
-            try
-            {
-                if (OpcUa_ConState())
-                {
-                    string extension = System.IO.Path.GetExtension(filename);
-                    if (string.IsNullOrWhiteSpace(extension) || !extension.ToUpper().Equals(".MPF"))
-                    {
-                       // System.Windows.Forms.MessageBox.Show("请选择要上传的文件");
-                        return false;
-                    }
-                    try
-                    {
-                        string value = opcserver.MethodCallSelectProgram(filename, Convert.ToUInt32(1)).status;
-                        if (value.Equals("Good"))
-                        {
-                            result = true;
-                        }
-
-                    }
-                    catch (Exception ex)
-                    {
-                        IMCS.CCS.Log.Instance.WriteLogAdd($"{ex.Message}");
-                        //System.Windows.Forms.MessageBox.Show($"{ex.Message}");
-
-                    }
-                }
+            
                 return result;
 
-            }
-            catch (Exception ex)
-            {
-                IMCS.CCS.Log.Instance.WriteLogAdd($"154--->{ex.Message}");
-                return false;
-            }
+            
         }
         public bool OpcUa_Select(string path, string filename)
         {
             bool result = false;
-            try
-            {
-                if (OpcUa_ConState())
-                {
-                    string extension = System.IO.Path.GetExtension(filename);
-                    if (string.IsNullOrWhiteSpace(extension) || !extension.ToUpper().Equals(".MPF"))
-                    {
-                        //System.Windows.Forms.MessageBox.Show("请选择要上传的文件");
-                        return false;
-                    }
-                    try
-                    {
-                        string value = opcserver.MethodCallSelectProgram(path + filename, Convert.ToUInt32(1)).status;
-                        if (value.Equals("Good"))
-                        {
-                            result = true;
-                        }
-
-                    }
-                    catch (Exception ex)
-                    {
-                        IMCS.CCS.Log.Instance.WriteLogAdd($"182-->{ex.Message}");
-                        //System.Windows.Forms.MessageBox.Show($"{ex.Message}");
-
-                    }
-                }
-                return result;
-
-            }
-            catch (Exception ex)
-            {
-                IMCS.CCS.Log.Instance.WriteLogAdd($"192-->{ex.Message}");
+          
                 return false;
-            }
+             
         }
         #endregion
 
-        #region 读取
-        public bool OpcUa_Read(string address, out string value)
-        {
-            bool result = false;
-            value = "";
-            if (OpcUa_ConState())
-            {
-                try
-                {
-                    string itemaddress = $"/Plc/{address}";
-                    string str = new NodeId(itemaddress, (ushort)2).ToString();
-
-                    if (opcserver != null && opcserver.Session.Connected)
-                    {
-                        value = opcserver.ReadValues(new List<string>() { str })[0];
-                    }
-                    result = true;
-                }
-                catch (Exception ex)
-                {
-                    IMCS.CCS.Log.Instance.WriteLogAdd($"{ex.Message}");
-                    //System.Windows.Forms.MessageBox.Show($"{ex.Message}");
-
-                }
-            }
-            return result;
-        }
+      
         /// <summary>
         /// 
         /// </summary>
         /// <param name="address">list里边的地址格式为I2.0,I2.1,DB2.DBX35.0等格式</param>
         /// <param name="value">查询出来的值和上面的值是一一对应的关系</param>
         /// <returns></returns>
-        public bool OpcUa_Read(List<string> address, out List<string> value)
-        {
-            value = new List<string>();
-            try
-            {
-                List<string> nodeIdStrings = new List<string>();
-                foreach (string s in address)
-                {
-                    nodeIdStrings.Add(new NodeId($"/Plc/{s}", (ushort)2).ToString());
-                }
-                if (opcserver != null && opcserver.Session.Connected)
-                {
-                    value = opcserver.ReadValues(nodeIdStrings);
-                }
-                return true;
-            }
-            catch (Exception ex)
-            {
-                IMCS.CCS.Log.Instance.WriteLogAdd($"{ex.Message}");
-                //System.Windows.Forms.MessageBox.Show($"{ex.Message}");
-                return false;
-            }
-        }
+        
         public List<string> OpcUa_Read(List<string> address)
         {
             List<string> value = new List<string>();
-            try
-            {
-                List<string> nodeIdStrings = new List<string>();
-                
-                if (opcserver != null && opcserver.Session != null && opcserver.Session.Connected)
-                {
-                    value = opcserver.ReadValues(nodeIdStrings);
-                }
-                return value;
-            }
-            catch (Exception ex)
-            {
-
-                try
-                {
-                    OpcUa_Connection(opcserver.Session.ConfiguredEndpoint.ToString());
-                }
-                catch (Exception esx)
-                {
-                    IMCS.CCS.Log.Instance.WriteLogAdd($"284------->>esx---->{esx.Message} {ex.Message}--->>>");
-                }
+             
                 return value;
-            }
+            
         }
 
-        public bool OpcUa_Read(List<string> address, out Dictionary<string, string> value)
-        {
-            value = new Dictionary<string, string>();
-            try
-            {
-                List<string> nodeIdStrings = new List<string>();
-                foreach (string s in address)
-                {
-                    nodeIdStrings.Add(new NodeId($"/Plc/{s}", (ushort)2).ToString());
-                    value.Add(s, "");
-                }
-                if (opcserver != null && opcserver.Session.Connected)
-                {
-                    List<string> Keys = value.Keys.ToList();
-                    List<string> items = opcserver.ReadValues(nodeIdStrings);
-                    for (int i = 0; i < items.Count; i++)
-                    {
-                        value[Keys[i]] = items[i];
-                    }
-                }
-                return true;
-
-            }
-            catch (Exception ex)
-            {
-                IMCS.CCS.Log.Instance.WriteLogAdd($"{ex.Message}");
-                //System.Windows.Forms.MessageBox.Show($"{ex.Message}");
-                return false;
-            }
-        }
-        #endregion
+         
 
         #region OPCUA连接
         /// <summary>
@@ -337,56 +109,7 @@ namespace IMCS.CCS.DeviceProtocol
         public bool OpcUa_Connection(string url, string username = "OpcUaClient", string pwd = "12345678")
         {
             bool result = false;
-            try
-            {
-                opcserver = new Server();
-                ApplicationDescriptionCollection applicationDescriptions = opcserver.FindServers(url);
-                if (applicationDescriptions.Count == 0)
-                {
-                    IMCS.CCS.Log.Instance.WriteLogAdd("没有找到服务!");
-                }
-                else if (applicationDescriptions.Count == 1)
-                { 
-                    applicationDescriptions[0].DiscoveryUrls.Where(m => m.Equals(url)).FirstOrDefault().FirstOrDefaultYG(
-                        (t) =>
-                        {
-                            try
-                            {
-                                var cc = opcserver.GetEndpoints(t);
-                               
-                                opcserver.GetEndpoints(t).Where(n => n.EndpointUrl.Equals(url)).FirstOrDefault().FirstOrDefaultYG((tt) =>
-                                {
-                                    try
-                                    {
-                                        endpointDescription = tt;
-                                        opcserver.KeepAliveNotification += new KeepAliveEventHandler(this.Notification_KeepAlive);
-                                        opcserver.Connect(tt, true, username, pwd);
-                                        if (opcserver.Session.Connected)
-                                        {
-                                            IsConnection = true;
-                                            result = true;
-                                        }
-                                        else
-                                        {
-                                            result = false;
-                                        }
-                                    }
-                                    catch (Exception ex)
-                                    {
-                                        IMCS.CCS.Log.Instance.WriteLogAdd($"355-->{ex.Message}");
-                                        result = false;
-                                    }
-
-                                });
-                            }
-                            catch (Exception ext)
-                            {
-                                IMCS.CCS.Log.Instance.WriteLogAdd($"362-->{ext.Message}");
-                            }
-                        });
-                }
-            }
-            catch (Exception eex) { IMCS.CCS.Log.Instance.WriteLogAdd($"368-->{eex.Message}-->{url}"); }
+           
             return result;
         }
         #endregion
@@ -398,37 +121,7 @@ namespace IMCS.CCS.DeviceProtocol
         public bool OpcUa_Access(string username = "OpcUaClient")
         {
             bool resultb = true;
-            if (OpcUa_ConState())
-            {
-                try
-                {
-                    string result = "";
-                    string strValue = "StateRead,StateWrite,FrameRead,FrameWrite,SeaRead,SeaWrite,TeaRead,TeaWrite,ToolRead,ToolWrite,DriveRead,DriveWrite,GudRead,GudWrite,PlcRead,PlcWrite,AlarmRead,FsRead,FsWrite,ApWrite,CsomReadx,CsomWritex,PlcReadDBx,PlcWriteDBx,SinuReadAll,SinuWriteAll";
-                    {
-                        string[] vs = strValue.Split(new string[] { "," }, StringSplitOptions.None);
-                        foreach (string s in vs)
-                        {
-                            Server.MethodCallResult methodCallResult = opcserver.MethodCall("/Methods/GiveUserAccess", username, s);
-                            if (methodCallResult != null && !methodCallResult.status.Equals("Good"))
-                            {
-                                result += s + methodCallResult.status;
-                            }
-                        }
-
-
-                    }
-                    if (result.Length > 0)
-                    {
-                        resultb = false;
-                        IMCS.CCS.Log.Instance.WriteLogAdd($"执行权限添加是出现异常:{result}");
-                    }
-                }
-                catch (Exception ex)
-                {
-                    resultb = false;
-                    IMCS.CCS.Log.Instance.WriteLogAdd($"409-->{ex.Message}");
-                }
-            }
+            
             return resultb;
         }
         #endregion
@@ -439,79 +132,7 @@ namespace IMCS.CCS.DeviceProtocol
         /// <param name="file">需要上传的文件的名字,这个名字是有后缀的,</param>
         public void OpcUa_UpLoadFile(string file)
         {
-            try
-            {
-
-                string extension = System.IO.Path.GetExtension(file);
-                if (string.IsNullOrWhiteSpace(extension))
-                {
-                    //System.Windows.Forms.MessageBox.Show("请选择要上传的文件");
-                    return;
-                }
-                try
-                {
-                    opcserver.MethodCallCreateNewFile("Sinumerik/FileSystem/NCExtend/webApiMESFILE/", System.IO.Path.GetFileName(file), true);
-                    byte[] data = opcserver.ReadFile(file);
-                    int copylen = 5000;
-                    bool isover = true;
-                    byte[] bt = new byte[copylen];
-                    if (data.Length > copylen)
-                    {
-
-                        int runcount = data.Length / copylen;
-                        for (int i = 0; i < runcount; i++)
-                        {
-                            Array.Copy(data, i * copylen, bt, 0, copylen);
-                            if (i > 0)
-                            {
-                                isover = false;
-                            }
-                            var cc = opcserver.MethodCallCopyFileToServer($"/Methods/CopyFileToServer", $"Sinumerik/FileSystem/NCExtend/webApiMESFILE/{System.IO.Path.GetFileName(file)}", data, isover);
-                            System.Console.WriteLine($"当前循环到的位置:{i}-->>{cc.status}");
-                        }
-                        int lastleng = data.Length % copylen;
-                        bt = new byte[lastleng];
-                        Array.Copy(data, runcount * copylen, bt, 0, lastleng);
-                        Server.MethodCallResult methodCallResult = opcserver.MethodCallCopyFileToServer($"/Methods/CopyFileToServer", $"Sinumerik/FileSystem/NCExtend/webApiMESFILE/{System.IO.Path.GetFileName(file)}", data, isover);
-
-                        if (methodCallResult.status.ToUpper().Equals("GOOD"))
-                        {
-                            IMCS.CCS.Log.Instance.WriteLogAdd("上传文件成功");
-                        }
-                        else
-                        {
-                            IMCS.CCS.Log.Instance.WriteLogAdd("上传文件失败");
-                        }
-                    }
-                    else
-                    {
-                        Server.MethodCallResult methodCallResult = opcserver.MethodCallCopyFileToServer($"/Methods/CopyFileToServer", $"Sinumerik/FileSystem/NCExtend/webApiMESFILE/{System.IO.Path.GetFileName(file)}", data, isover);
-
-                        if (methodCallResult.status.ToUpper().Equals("GOOD"))
-                        {
-                            IMCS.CCS.Log.Instance.WriteLogAdd("上传文件成功");
-                        }
-                        else
-                        {
-                            IMCS.CCS.Log.Instance.WriteLogAdd("上传文件失败");
-                        }
-                    }
-
-
-
-                }
-                catch (Exception ex)
-                {
-                    IMCS.CCS.Log.Instance.WriteLogAdd($"{ex.Message}");
-                    //System.Windows.Forms.MessageBox.Show($"{ex.Message}");
-                }
-
-
-            }
-            catch (Exception ex)
-            {
-                IMCS.CCS.Log.Instance.WriteLogAdd($"493-->{ex.Message}");
-            }
+          
         }
         #endregion
         #region 删除文件
@@ -520,45 +141,7 @@ namespace IMCS.CCS.DeviceProtocol
         /// </summary>
         /// <param name="file">需要删除的文件的名字,这个名字是有后缀的</param>
         public void OpcUa_DeleteFile(string file)
-        {
-            try
-            {
-
-                Server.MethodCallResult methodCallResult = opcserver.MethodCallDeleteFile($"Sinumerik/FileSystem/NCExtend/webApiMESFILE/{file}");
-                if (methodCallResult.status.ToUpper().Equals("GOOD"))
-                {
-                    IMCS.CCS.Log.Instance.WriteLogAdd("删除文件成功");
-                }
-                else
-                {
-                    IMCS.CCS.Log.Instance.WriteLogAdd("删除文件失败");
-                }
-            }
-            catch (Exception ex)
-            {
-                IMCS.CCS.Log.Instance.WriteLogAdd($"519-->{ex.Message}");
-            }
-        }
-        public string OpcUa_DeleteFile(string path, string file)
-        {
-            string status = "";
-            try
-            {
-                status = opcserver.MethodCallDeleteFile(path + file).status;
-                if (status.ToUpper().Equals("GOOD"))
-                {
-                    IMCS.CCS.Log.Instance.WriteLogAdd("删除文件成功");
-                }
-                else
-                {
-                    IMCS.CCS.Log.Instance.WriteLogAdd("删除文件失败");
-                }
-            }
-            catch (Exception ex)
-            {
-                IMCS.CCS.Log.Instance.WriteLogAdd($"539-->{ex.Message}");
-            }
-            return status;
+        { 
         }
         #endregion
         #region 创建文件目录
@@ -568,31 +151,13 @@ namespace IMCS.CCS.DeviceProtocol
         /// <param name="file">类似于文件夹名称</param>
         public void OpcUa_CreateNewFile(string file = "webApiMESFILE")
         {
-            try
-            {
-                Server.MethodCallResult methodCallResult = opcserver.MethodCallCreateNewDir($"Sinumerik/FileSystem/NCExtend", file);
-                if (methodCallResult.status.ToUpper().Equals("GOOD"))
-                {
-                    IMCS.CCS.Log.Instance.WriteLogAdd("删除文件成功");
-                }
-                else
-                {
-                    IMCS.CCS.Log.Instance.WriteLogAdd("删除文件失败");
-                }
-            }
-            catch (Exception ex)
-            {
-                IMCS.CCS.Log.Instance.WriteLogAdd($"565-->{ex.Message}");
-            }
+           
         }
         #endregion
 
        public void disConnect()
         {
-            if (opcserver.Session.Connected)
-            {
-                opcserver.Disconnect();
-            }
+           
         }
     }
 }

+ 422 - 0
IMCS_CCS/Utils/DeviceProtocol/FilterDefinition.cs

@@ -0,0 +1,422 @@
+using System;
+using System.Collections;
+using System.Collections.Generic;
+using Opc.Ua;
+using Opc.Ua.Client;
+
+
+namespace IMCS_CCS.Utils.DeviceProtocol
+{
+    public class FilterDefinition
+    {
+        public NodeId AreaId;
+        public EventSeverity Severity;
+        public IList<NodeId> EventTypes;
+        public bool IgnoreSuppressedOrShelved;
+        public SimpleAttributeOperandCollection SelectClauses;
+
+        public MonitoredItem CreateMonitoredItem(Session session)
+        {
+            if (this.AreaId == (object)null)
+                this.AreaId = ObjectIds.Server;
+            return new MonitoredItem()
+            {
+                DisplayName = (string)null,
+                StartNodeId = this.AreaId,
+                RelativePath = (string)null,
+                NodeClass = NodeClass.Object,
+                AttributeId = 12,
+                IndexRange = (string)null,
+                Encoding = (QualifiedName)null,
+                MonitoringMode = MonitoringMode.Reporting,
+                SamplingInterval = 0,
+                QueueSize = uint.MaxValue,
+                DiscardOldest = true,
+                Filter = (MonitoringFilter)this.ConstructFilter(session),
+                Handle = (object)this
+            };
+        }
+
+        public SimpleAttributeOperandCollection ConstructSelectClauses(
+          Session session,
+          params NodeId[] eventTypeIds)
+        {
+            SimpleAttributeOperandCollection eventFields = new SimpleAttributeOperandCollection();
+            eventFields.Add(new SimpleAttributeOperand()
+            {
+                TypeDefinitionId = ObjectTypeIds.BaseEventType,
+                AttributeId = 1U,
+                BrowsePath = new QualifiedNameCollection()
+            });
+            if (eventTypeIds != null)
+            {
+                for (int index = 0; index < eventTypeIds.Length; ++index)
+                    this.CollectFields(session, eventTypeIds[index], eventFields);
+            }
+            else
+                this.CollectFields(session, ObjectTypeIds.BaseEventType, eventFields);
+            return eventFields;
+        }
+
+        public EventFilter ConstructFilter(Session session)
+        {
+            EventFilter eventFilter = new EventFilter();
+            eventFilter.SelectClauses = this.SelectClauses;
+            ContentFilter contentFilter = new ContentFilter();
+            ContentFilterElement contentFilterElement1 = (ContentFilterElement)null;
+            if (this.Severity > EventSeverity.Min)
+            {
+                SimpleAttributeOperand attributeOperand = new SimpleAttributeOperand();
+                attributeOperand.TypeDefinitionId = ObjectTypeIds.BaseEventType;
+                attributeOperand.BrowsePath.Add((QualifiedName)"Severity");
+                attributeOperand.AttributeId = 13U;
+                contentFilterElement1 = contentFilter.Push(FilterOperator.GreaterThanOrEqual, (object)attributeOperand, (object)new LiteralOperand()
+                {
+                    Value = new Variant((ushort)this.Severity)
+                });
+            }
+            if (!this.IgnoreSuppressedOrShelved)
+            {
+                SimpleAttributeOperand attributeOperand = new SimpleAttributeOperand();
+                attributeOperand.TypeDefinitionId = ObjectTypeIds.BaseEventType;
+                attributeOperand.BrowsePath.Add((QualifiedName)"SuppressedOrShelved");
+                attributeOperand.AttributeId = 13U;
+                ContentFilterElement contentFilterElement2 = contentFilter.Push(FilterOperator.Equals, (object)attributeOperand, (object)new LiteralOperand()
+                {
+                    Value = new Variant(false)
+                });
+                if (contentFilterElement1 != null)
+                    contentFilterElement1 = contentFilter.Push(FilterOperator.And, (object)contentFilterElement1, (object)contentFilterElement2);
+                else
+                    contentFilterElement1 = contentFilterElement2;
+            }
+            if (this.EventTypes != null && this.EventTypes.Count > 0)
+            {
+                ContentFilterElement contentFilterElement2 = (ContentFilterElement)null;
+                for (int index = 0; index < this.EventTypes.Count; ++index)
+                {
+                    ContentFilterElement contentFilterElement3 = contentFilter.Push(FilterOperator.OfType, (object)new LiteralOperand()
+                    {
+                        Value = new Variant(this.EventTypes[index])
+                    });
+                    if (contentFilterElement2 != null)
+                        contentFilterElement2 = contentFilter.Push(FilterOperator.Or, (object)contentFilterElement2, (object)contentFilterElement3);
+                    else
+                        contentFilterElement2 = contentFilterElement3;
+                }
+                if (contentFilterElement1 != null)
+                    contentFilter.Push(FilterOperator.And, (object)contentFilterElement1, (object)contentFilterElement2);
+            }
+            eventFilter.WhereClause = contentFilter;
+            return eventFilter;
+        }
+
+        private void CollectFields(
+          Session session,
+          NodeId eventTypeId,
+          SimpleAttributeOperandCollection eventFields)
+        {
+            ReferenceDescriptionCollection descriptionCollection = FormUtils.BrowseSuperTypes(session, eventTypeId, false);
+            if (descriptionCollection == null)
+                return;
+            Dictionary<NodeId, QualifiedNameCollection> foundNodes = new Dictionary<NodeId, QualifiedNameCollection>();
+            QualifiedNameCollection parentPath = new QualifiedNameCollection();
+            for (int index = descriptionCollection.Count - 1; index >= 0; --index)
+                this.CollectFields(session, (NodeId)descriptionCollection[index].NodeId, parentPath, eventFields, foundNodes);
+            this.CollectFields(session, eventTypeId, parentPath, eventFields, foundNodes);
+        }
+
+        private void CollectFields(
+          Session session,
+          NodeId nodeId,
+          QualifiedNameCollection parentPath,
+          SimpleAttributeOperandCollection eventFields,
+          Dictionary<NodeId, QualifiedNameCollection> foundNodes)
+        {
+            ReferenceDescriptionCollection descriptionCollection = FormUtils.Browse(session, new BrowseDescription()
+            {
+                NodeId = nodeId,
+                BrowseDirection = BrowseDirection.Forward,
+                ReferenceTypeId = ReferenceTypeIds.Aggregates,
+                IncludeSubtypes = true,
+                NodeClassMask = 3U,
+                ResultMask = 63U
+            }, false);
+            if (descriptionCollection == null)
+                return;
+            for (int index = 0; index < descriptionCollection.Count; ++index)
+            {
+                ReferenceDescription referenceDescription = descriptionCollection[index];
+                if (!referenceDescription.NodeId.IsAbsolute)
+                {
+                    QualifiedNameCollection qualifiedNameCollection = new QualifiedNameCollection((IEnumerable<QualifiedName>)parentPath);
+                    qualifiedNameCollection.Add(referenceDescription.BrowseName);
+                    if (!this.ContainsPath(eventFields, qualifiedNameCollection))
+                        eventFields.Add(new SimpleAttributeOperand()
+                        {
+                            TypeDefinitionId = ObjectTypeIds.BaseEventType,
+                            BrowsePath = qualifiedNameCollection,
+                            AttributeId = referenceDescription.NodeClass == NodeClass.Variable ? 13U : 1U
+                        });
+                    NodeId nodeId1 = (NodeId)referenceDescription.NodeId;
+                    if (!foundNodes.ContainsKey(nodeId1))
+                    {
+                        foundNodes.Add(nodeId1, qualifiedNameCollection);
+                        this.CollectFields(session, (NodeId)referenceDescription.NodeId, qualifiedNameCollection, eventFields, foundNodes);
+                    }
+                }
+            }
+        }
+
+        private bool ContainsPath(
+          SimpleAttributeOperandCollection selectClause,
+          QualifiedNameCollection browsePath)
+        {
+            for (int index1 = 0; index1 < selectClause.Count; ++index1)
+            {
+                SimpleAttributeOperand attributeOperand = selectClause[index1];
+                if (attributeOperand.BrowsePath.Count == browsePath.Count)
+                {
+                    bool flag = true;
+                    for (int index2 = 0; index2 < attributeOperand.BrowsePath.Count; ++index2)
+                    {
+                        if (attributeOperand.BrowsePath[index2] != browsePath[index2])
+                        {
+                            flag = false;
+                            break;
+                        }
+                    }
+                    if (flag)
+                        return true;
+                }
+            }
+            return false;
+        }
+    }
+
+
+    public static class FormUtils
+    {
+        public static NodeId[] KnownEventTypes = new NodeId[8]
+        {
+      ObjectTypeIds.BaseEventType,
+      ObjectTypeIds.ConditionType,
+      ObjectTypeIds.DialogConditionType,
+      ObjectTypeIds.AlarmConditionType,
+      ObjectTypeIds.ExclusiveLimitAlarmType,
+      ObjectTypeIds.NonExclusiveLimitAlarmType,
+      ObjectTypeIds.AuditEventType,
+      ObjectTypeIds.AuditUpdateMethodEventType
+        };
+
+        public static EndpointDescription SelectEndpoint(
+          string discoveryUrl,
+          bool useSecurity)
+        {
+            if (!discoveryUrl.StartsWith("opc.tcp") && !discoveryUrl.EndsWith("/discovery"))
+                discoveryUrl += "/discovery";
+            Uri discoveryUrl1 = new Uri(discoveryUrl);
+            EndpointConfiguration configuration = EndpointConfiguration.Create();
+            configuration.OperationTimeout = 5000;
+            EndpointDescription endpointDescription1 = (EndpointDescription)null;
+            using (DiscoveryClient discoveryClient = DiscoveryClient.Create(discoveryUrl1, configuration))
+            {
+                EndpointDescriptionCollection endpoints = discoveryClient.GetEndpoints((StringCollection)null);
+                for (int index = 0; index < endpoints.Count; ++index)
+                {
+                    EndpointDescription endpointDescription2 = endpoints[index];
+                    if (endpointDescription2.EndpointUrl.StartsWith(discoveryUrl1.Scheme))
+                    {
+                        if (endpointDescription1 == null)
+                            endpointDescription1 = endpointDescription2;
+                        if (useSecurity)
+                        {
+                            if (endpointDescription2.SecurityMode != MessageSecurityMode.None && (int)endpointDescription2.SecurityLevel > (int)endpointDescription1.SecurityLevel)
+                                endpointDescription1 = endpointDescription2;
+                        }
+                        else if (endpointDescription2.SecurityMode == MessageSecurityMode.None)
+                            endpointDescription1 = endpointDescription2;
+                    }
+                    if (endpointDescription1 == null && endpoints.Count > 0)
+                        endpointDescription1 = endpoints[0];
+                }
+            }
+            Uri uri = Opc.Ua.Utils.ParseUri(endpointDescription1.EndpointUrl);
+            if (uri != (Uri)null && uri.Scheme == discoveryUrl1.Scheme)
+                endpointDescription1.EndpointUrl = new UriBuilder(uri)
+                {
+                    Host = discoveryUrl1.DnsSafeHost,
+                    Port = discoveryUrl1.Port
+                }.ToString();
+            return endpointDescription1;
+        }
+
+        public static NodeId FindEventType(
+          MonitoredItem monitoredItem,
+          EventFieldList notification)
+        {
+            EventFilter filter = monitoredItem.Status.Filter as EventFilter;
+            if (filter != null)
+            {
+                for (int index = 0; index < filter.SelectClauses.Count; ++index)
+                {
+                    SimpleAttributeOperand selectClause = filter.SelectClauses[index];
+                    if (selectClause.BrowsePath.Count == 1 && selectClause.BrowsePath[0] == (QualifiedName)"EventType")
+                        return notification.EventFields[index].Value as NodeId;
+                }
+            }
+            return (NodeId)null;
+        }
+
+        public static BaseEventState ConstructEvent(
+          Session session,
+          MonitoredItem monitoredItem,
+          EventFieldList notification,
+          Dictionary<NodeId, NodeId> eventTypeMappings)
+        {
+            NodeId eventType = FormUtils.FindEventType(monitoredItem, notification);
+            if (eventType == (object)null)
+                return (BaseEventState)null;
+            NodeId nodeId = (NodeId)null;
+            if (!eventTypeMappings.TryGetValue(eventType, out nodeId))
+            {
+                for (int index = 0; index < FormUtils.KnownEventTypes.Length; ++index)
+                {
+                    if (FormUtils.KnownEventTypes[index] == (object)eventType)
+                    {
+                        nodeId = eventType;
+                        eventTypeMappings.Add(eventType, eventType);
+                        break;
+                    }
+                }
+                if (nodeId == (object)null)
+                {
+                    ReferenceDescriptionCollection descriptionCollection = FormUtils.BrowseSuperTypes(session, eventType, false);
+                    if (descriptionCollection == null)
+                        return (BaseEventState)null;
+                    for (int index1 = 0; index1 < descriptionCollection.Count; ++index1)
+                    {
+                        for (int index2 = 0; index2 < FormUtils.KnownEventTypes.Length; ++index2)
+                        {
+                            if (FormUtils.KnownEventTypes[index2] == (object)descriptionCollection[index1].NodeId)
+                            {
+                                nodeId = FormUtils.KnownEventTypes[index2];
+                                eventTypeMappings.Add(eventType, nodeId);
+                                break;
+                            }
+                        }
+                        if (nodeId != (object)null)
+                            break;
+                    }
+                }
+            }
+            if (nodeId == (object)null)
+                return (BaseEventState)null;
+            uint? identifier = nodeId.Identifier as uint?;
+            if (!identifier.HasValue)
+                return (BaseEventState)null;
+            BaseEventState baseEventState;
+            switch (identifier.Value)
+            {
+                case 2052:
+                    baseEventState = (BaseEventState)new AuditEventState((NodeState)null);
+                    break;
+                case 2127:
+                    baseEventState = (BaseEventState)new AuditUpdateMethodEventState((NodeState)null);
+                    break;
+                case 2782:
+                    baseEventState = (BaseEventState)new ConditionState((NodeState)null);
+                    break;
+                case 2830:
+                    baseEventState = (BaseEventState)new DialogConditionState((NodeState)null);
+                    break;
+                case 2915:
+                    baseEventState = (BaseEventState)new AlarmConditionState((NodeState)null);
+                    break;
+                case 9341:
+                    baseEventState = (BaseEventState)new ExclusiveLimitAlarmState((NodeState)null);
+                    break;
+                case 9906:
+                    baseEventState = (BaseEventState)new NonExclusiveLimitAlarmState((NodeState)null);
+                    break;
+                default:
+                    baseEventState = new BaseEventState((NodeState)null);
+                    break;
+            }
+            EventFilter filter = monitoredItem.Status.Filter as EventFilter;
+            baseEventState.Update(session.SystemContext, filter.SelectClauses, notification);
+            baseEventState.Handle = (object)notification;
+            return baseEventState;
+        }
+
+        public static ReferenceDescriptionCollection Browse(
+          Session session,
+          BrowseDescription nodeToBrowse,
+          bool throwOnError)
+        {
+            try
+            {
+                ReferenceDescriptionCollection descriptionCollection = new ReferenceDescriptionCollection();
+                BrowseDescriptionCollection nodesToBrowse = new BrowseDescriptionCollection();
+                nodesToBrowse.Add(nodeToBrowse);
+                BrowseResultCollection results = (BrowseResultCollection)null;
+                DiagnosticInfoCollection diagnosticInfos = (DiagnosticInfoCollection)null;
+                session.Browse((RequestHeader)null, (ViewDescription)null, 0U, nodesToBrowse, out results, out diagnosticInfos);
+                ClientBase.ValidateResponse((IList)results, (IList)nodesToBrowse);
+                ClientBase.ValidateDiagnosticInfos(diagnosticInfos, (IList)nodesToBrowse);
+                while (!StatusCode.IsBad(results[0].StatusCode))
+                {
+                    for (int index = 0; index < results[0].References.Count; ++index)
+                        descriptionCollection.Add(results[0].References[index]);
+                    if (results[0].References.Count == 0 || results[0].ContinuationPoint == null)
+                        return descriptionCollection;
+                    ByteStringCollection continuationPoints = new ByteStringCollection();
+                    continuationPoints.Add(results[0].ContinuationPoint);
+                    session.BrowseNext((RequestHeader)null, false, continuationPoints, out results, out diagnosticInfos);
+                    ClientBase.ValidateResponse((IList)results, (IList)continuationPoints);
+                    ClientBase.ValidateDiagnosticInfos(diagnosticInfos, (IList)continuationPoints);
+                }
+                throw new ServiceResultException((ServiceResult)results[0].StatusCode);
+            }
+            catch (Exception ex)
+            {
+                if (throwOnError)
+                    throw new ServiceResultException(ex, 2147549184U);
+                return (ReferenceDescriptionCollection)null;
+            }
+        }
+
+        public static ReferenceDescriptionCollection BrowseSuperTypes(
+          Session session,
+          NodeId typeId,
+          bool throwOnError)
+        {
+            ReferenceDescriptionCollection descriptionCollection1 = new ReferenceDescriptionCollection();
+            try
+            {
+                BrowseDescription nodeToBrowse = new BrowseDescription();
+                nodeToBrowse.NodeId = typeId;
+                nodeToBrowse.BrowseDirection = BrowseDirection.Inverse;
+                nodeToBrowse.ReferenceTypeId = ReferenceTypeIds.HasSubtype;
+                nodeToBrowse.IncludeSubtypes = false;
+                nodeToBrowse.NodeClassMask = 0U;
+                nodeToBrowse.ResultMask = 63U;
+                for (ReferenceDescriptionCollection descriptionCollection2 = FormUtils.Browse(session, nodeToBrowse, throwOnError); descriptionCollection2 != null && descriptionCollection2.Count > 0; descriptionCollection2 = FormUtils.Browse(session, nodeToBrowse, throwOnError))
+                {
+                    descriptionCollection1.Add(descriptionCollection2[0]);
+                    if (!descriptionCollection2[0].NodeId.IsAbsolute)
+                        nodeToBrowse.NodeId = (NodeId)descriptionCollection2[0].NodeId;
+                    else
+                        break;
+                }
+                return descriptionCollection1;
+            }
+            catch (Exception ex)
+            {
+                if (throwOnError)
+                    throw new ServiceResultException(ex, 2147549184U);
+                return (ReferenceDescriptionCollection)null;
+            }
+        }
+    }
+}

+ 290 - 0
IMCS_CCS/Utils/DeviceProtocol/OpcUaClient.cs

@@ -0,0 +1,290 @@
+using System;
+using System.Collections.Generic;
+using System.Globalization;
+using System.Linq;
+using System.Net;
+using System.Text;
+using System.Threading.Tasks; 
+using Opc.Ua;
+using Opc.Ua.Client;
+using Siemens.OpcUA;
+using Subscription = Opc.Ua.Client.Subscription;
+
+namespace IMCS_CCS.Utils.DeviceProtocol
+{
+    public class OpcUaClient : AProtocolBase
+    {
+        public OpcUaClient(ushort index)
+        {
+            mServer = new Server();
+            namespaceIndex = index;
+            mServer.CertificateEvent += m_Server_CertificateEvent;
+            mServer.serverMessage += m_Server_serverMessage;
+        }
+
+        public override void ConnectAsync()
+        {
+            try
+            {
+                var task = Task.Run(() =>
+                {
+                    if (string.IsNullOrEmpty(UserName) || string.IsNullOrEmpty(UserPassword))
+                        mServer.Connect(IpEndPort);
+                    else
+                        mServer.Connect(IpEndPort, UserName, UserPassword);
+                });
+                IsConnected = task.Wait(5000); 
+            }
+            catch (Exception ex)
+            {
+                IsConnected = false; 
+            }
+            finally
+            {
+                if (IsConnected)
+                {
+                    mSession = mServer.Session;
+                    StartAlarmMonitor();
+                }
+                else
+                    mSession = null;
+            }
+        }
+
+        public override void CloseConnect()
+        {
+            try
+            {
+                if (mAlarmMonitorItem == null)
+                {
+                    mServer?.Disconnect();
+                    mSession = this.mServer?.Session;
+                    IsConnected = false;
+                    return;
+                }
+                this.mAlarmSubscription?.RemoveItem(this.mAlarmMonitorItem);
+                this.mAlarmSubscription?.Delete(true);
+                mAlarmSubscription?.Dispose();
+                this.mAlarmSubscription = (Subscription)null;
+                this.mAlarmMonitorItem = (MonitoredItem)null;
+                mFilter = null;
+                this.eventMonitorStart = false;
+                mServer?.Disconnect();
+                mSession = this.mServer?.Session;
+                IsConnected = false; 
+            }
+            catch (Exception ex)
+            {
+                IsConnected = false; 
+            }
+        }
+
+        public override object ReadData(int dataType, object dataParameter)
+        {
+           
+            try
+            {
+                List<object> resultList = new List<object>();
+                var dataAddress = dataParameter as List<string>;
+                NodeIdCollection nodesToRead = new NodeIdCollection();
+                if (dataAddress != null)
+                    foreach (var item in dataAddress)
+                    {
+                        var nodeId = new NodeId(item, namespaceIndex);
+                        nodesToRead.Add(nodeId);
+                    }
+                mServer.ReadValues(nodesToRead, out var results);
+                if (results.Any())
+                {
+                    foreach (var value in results)
+                    {
+                        if (typeof(int[]) == value.Value.GetType())
+                        {
+                            resultList.Add(((int[])(value.Value))[1]);
+                            continue;
+                        }
+                        if (typeof(double[]) == value.Value.GetType())
+                        {
+                            resultList.Add(((double[])value.Value)[0]);
+                            continue;
+                        }
+                        if (typeof(UInt16[]) == value.Value.GetType())
+                        {
+                            resultList.Add(value.Value);
+                            continue;
+                        }
+                        resultList.Add(value?.Value);
+                    }
+                } 
+                return resultList;
+            }
+            catch (Exception ex)
+            {
+                CloseConnect(); 
+                return null;
+            }
+        }
+
+        public override bool WriteData(object obj)
+        {
+            return false;
+        }
+
+
+        private string ReadFilesData(string valueStr)
+        {
+            string ncFileStream = "";
+            if (mServer == null) return ncFileStream;
+            try
+            {
+                DiagnosticInfoCollection diagnosticInfos = (DiagnosticInfoCollection)null;
+                CallMethodRequestCollection methodsToCall = new CallMethodRequestCollection();
+                CallMethodResultCollection results = new CallMethodResultCollection();
+                CallMethodRequest callMethodRequest = new CallMethodRequest();
+                callMethodRequest.MethodId = new NodeId("/Methods/CopyFileFromServer", 2);
+                callMethodRequest.ObjectId = new NodeId("/Methods", 2);
+                callMethodRequest.InputArguments.Add((Opc.Ua.Variant)valueStr);
+                methodsToCall.Add(callMethodRequest);
+                RequestHeader requestHeader = new RequestHeader();
+                mServer.Session.Call((RequestHeader)null, methodsToCall, out results, out diagnosticInfos);
+                if (results.Count > 0) ncFileStream = Encoding.Default.GetString((byte[])results[0].OutputArguments[0].Value);
+                return ncFileStream;
+            }
+            catch (Exception ex)
+            {
+                CloseConnect(); 
+                return ncFileStream;
+            }
+        }
+
+        #region Alarm Event
+
+        private bool eventMonitorStart = false;
+        private Subscription mAlarmSubscription;
+        private Session mSession;
+        private FilterDefinition mFilter;
+        private MonitoredItem mAlarmMonitorItem;
+        public override event MonitoredItemNotificationEventHandler OpcUaAlarmNotificationHandle;
+        private void StartAlarmMonitor()
+        {
+            if (!this.eventMonitorStart)
+            {
+                try
+                {
+                    if (this.mAlarmSubscription == null)
+                    {
+                        this.mAlarmSubscription = new Subscription
+                        {
+                            DisplayName = "AlarmSubscription",
+                            PublishingInterval = 1000,
+                            KeepAliveCount = 10U,
+                            LifetimeCount = 100U,
+                            MaxNotificationsPerPublish = 1000U,
+                            PublishingEnabled = true,
+                            TimestampsToReturn = TimestampsToReturn.Server
+                        };
+                        this.mSession?.AddSubscription(this.mAlarmSubscription);
+                        this.mFilter = new FilterDefinition
+                        {
+                            AreaId = new NodeId("Sinumerik", (ushort)2),
+                            Severity = EventSeverity.Min,
+                            IgnoreSuppressedOrShelved = true,
+                            EventTypes = (IList<NodeId>)new NodeId[1] { ObjectTypeIds.ConditionType }
+                        };
+                        this.mFilter.SelectClauses = this.mFilter.ConstructSelectClauses(this.mSession, ObjectTypeIds.ConditionType);
+                    }
+                    if (!mAlarmSubscription.Created) this.mAlarmSubscription.Create();
+                    this.mAlarmMonitorItem = this.mFilter.CreateMonitoredItem(this.mSession);
+                    this.mAlarmMonitorItem.DisplayName = "AlarmMonitorItem";
+                    this.mAlarmMonitorItem.Notification += new MonitoredItemNotificationEventHandler(this.Notification_MonitoredAlarm);
+                    this.mAlarmSubscription?.AddItem(this.mAlarmMonitorItem);
+                    this.mAlarmSubscription?.ApplyChanges();
+                    this.RefreshAlarmCall();
+                    this.eventMonitorStart = true; 
+                }
+                catch (Exception ex)
+                { 
+                }
+            }
+        }
+
+        private void RefreshAlarmCall()
+        {
+            CallMethodRequestCollection methodsToCall = new CallMethodRequestCollection(1);
+            CallMethodRequest callMethodRequest = new CallMethodRequest
+            {
+                ObjectId = new NodeId(ObjectTypeIds.ConditionType),
+                MethodId = new NodeId(MethodIds.ConditionType_ConditionRefresh)
+            };
+            callMethodRequest.InputArguments.Add((Opc.Ua.Variant)this.mAlarmSubscription.Id);
+            methodsToCall.Add(callMethodRequest);
+            this.mSession.Call((RequestHeader)null, methodsToCall, out _, out _);
+        }
+
+
+
+        private void Notification_MonitoredAlarm(
+            MonitoredItem monitoredItem,
+            MonitoredItemNotificationEventArgs e)
+        {
+            try
+            {
+                EventFieldList notificationValue = e.NotificationValue as EventFieldList;
+                if (notificationValue == null)
+                    return;
+                lock (this)
+                    OpcUaAlarmNotificationHandle?.Invoke(monitoredItem, e);
+                this.eventMonitorStart = true;
+            }
+            catch (Exception ex)
+            { 
+            }
+        }
+
+        #endregion
+
+        #region Props
+
+        public override bool IsConnected { get; set; } = false;
+        private readonly Server mServer;
+        private readonly ushort namespaceIndex;
+
+        public void Dispose()
+        {
+            Dispose(true);
+            GC.SuppressFinalize(this);
+        }
+
+        private void m_Server_CertificateEvent(
+            CertificateValidator validator,
+            CertificateValidationEventArgs e)
+        {
+            e.Accept = true;
+        }
+
+        private void m_Server_serverMessage(string message)
+        {
+        }
+
+        private void ReleaseUnmanagedResources()
+        {
+            CloseConnect();
+            // TODO release unmanaged resources here
+        }
+
+        protected virtual void Dispose(bool disposing)
+        {
+            ReleaseUnmanagedResources();
+            if (disposing)
+            {
+            }
+        }
+
+        ~OpcUaClient()
+        {
+            Dispose(false);
+        }
+
+        #endregion
+    }
+}

+ 2 - 1
IMCS_CCS/appsettings.json

@@ -32,6 +32,7 @@
     "FTPServer": "192.168.170.25",
     "FTPUser": "PROG",
     "FTPPwd": "abc.1234",
-    "fanucUrlContext": "http://localhost:5100/fanuc/"
+    "fanucUrlContext": "http://localhost:5100/fanuc/",
+    "opcuacUrlContext": "http://localhost:8010/opcua/"
   }
 }

BIN
IMCS_CCS/bin/Debug/netcoreapp3.1/Opc.Ua.Client.dll


BIN
IMCS_CCS/bin/Debug/netcoreapp3.1/Opc.Ua.Core.dll


BIN
IMCS_CCS/bin/Debug/netcoreapp3.1/Siemens.OpcUA.dll


+ 1 - 1
IMCS_CCS/obj/Debug/netcoreapp3.1/CCS.csproj.CoreCompileInputs.cache

@@ -1 +1 @@
-cc42678967412c1241fa0caab19fcd28047ffdcc
+8e95d899bbd490476278a84ddd2e4a698f1fc726