Shun 2 лет назад
Родитель
Сommit
7f6a814d05

+ 2 - 56
src/YSAI.DAQ/YSAI.Core/reflection/ReflectionOperate.cs

@@ -54,60 +54,6 @@ namespace YSAI.Core.reflection
                 {
                     return JsonTool.StringToJsonEntity<Basics>(FileTool.FileToString(ConfigFile));
                 }
-                else
-                {
-                    //创建配置
-                    Basics basics = new Basics()
-                    {
-                        DllDatas = new List<Basics.DllData>()
-                                    {
-                                        new Basics.DllData()
-                                        {
-                                            DllPath="YSAI.RelayManage.dll",
-                                            IsAbsolutePath=false,
-                                            NamespaceDatas=new List<Basics.DllData.NamespaceData>()
-                                            {
-                                                new Basics.DllData.NamespaceData()
-                                                {
-                                                    Namespace="YSAI.RelayManage",
-                                                    ClassDatas=new List<Basics.DllData.NamespaceData.ClassData>()
-                                                    {
-                                                        new Basics.DllData.NamespaceData.ClassData()
-                                                        {
-                                                            ClassName="RelayManageOperate",
-                                                            ConstructorParam=null,
-                                                            SN="YSAI.RelayManage.RelayManageOperate[Instance]",
-                                                            MethodDatas=new List<Basics.DllData.NamespaceData.ClassData.MethodData>()
-                                                            {
-                                                                new Basics.DllData.NamespaceData.ClassData.MethodData()
-                                                                {
-                                                                    MethodName="Produce",
-                                                                    SN="[Produce]"
-                                                                },
-                                                                 new Basics.DllData.NamespaceData.ClassData.MethodData()
-                                                                {
-                                                                    MethodName="Dispose",
-                                                                    SN="[Dispose]"
-                                                                }
-                                                            },
-                                                            EventDatas=new List<ClassData.EventData>()
-                                                            {
-                                                                new ClassData.EventData()
-                                                                {
-                                                                    EventName="OnEvent",
-                                                                    SN="[OnEvent]"
-                                                                }
-                                                            }
-                                                        }
-                                                    }
-                                                }
-                                            }
-                                        }
-                                    }
-                    };
-                    FileTool.StringToFile(ConfigFile, basics.ToJson().JsonFormatting());
-                    return GetConfig();
-                }
             }
             catch (Exception ex)
             {
@@ -153,12 +99,12 @@ namespace YSAI.Core.reflection
                 OperateResult operateResult = Init();
                 if (!operateResult.State)
                 {
-                    throw new Exception("反射初始化异常:" + operateResult.Message);
+                    LogHelper.Error("反射初始化异常:" + operateResult.Message, $"{ClassName}.log");
                 }
             }
             else
             {
-                throw new Exception("请设置反射DLL配置");
+                LogHelper.Error($"反射配置不存在",$"{ClassName}.log");
             }
         }
 

+ 79 - 73
src/YSAI.DAQ/YSAI.Opc/ua/client/OpcUaClientOperate.cs

@@ -1,4 +1,5 @@
 using Microsoft.AspNetCore.DataProtection.KeyManagement;
+using Microsoft.AspNetCore.Mvc.ApplicationParts;
 using Newtonsoft.Json.Linq;
 using Opc.Ua;
 using Opc.Ua.Client;
@@ -974,92 +975,97 @@ namespace YSAI.Opc.ua.client
             Depart("On");
             try
             {
-                if (AC != null)
+                if (IsConnected)
                 {
-                    if (IsConnected)
+                    return Break("On", false, "已连接");
+                }
+                //实例化对象
+                allSubscriptions = new ConcurrentDictionary<string, Subscription>();
+                //OPCUA证书验证
+                CertificateValidator certificateValidator = new CertificateValidator();
+                //当发生证书验证错误时引发
+                certificateValidator.CertificateValidation += (sender, eventArgs) =>
+                {
+                    if (ServiceResult.IsGood(eventArgs.Error)) //验证状态码是否正常
                     {
-                        return Break("On", false, "已连接");
+                        eventArgs.Accept = true;
                     }
-                    //实例化对象
-                    allSubscriptions = new ConcurrentDictionary<string, Subscription>();
-                    //OPCUA证书验证
-                    CertificateValidator certificateValidator = new CertificateValidator();
-                    //当发生证书验证错误时引发
-                    certificateValidator.CertificateValidation += (sender, eventArgs) =>
+                    else if (eventArgs.Error.StatusCode.Code == StatusCodes.BadCertificateUntrusted)  //验证证书状态
                     {
-                        if (ServiceResult.IsGood(eventArgs.Error)) //验证状态码是否正常
-                        {
-                            eventArgs.Accept = true;
-                        }
-                        else if (eventArgs.Error.StatusCode.Code == StatusCodes.BadCertificateUntrusted)  //验证证书状态
-                        {
-                            eventArgs.Accept = true;
-                        }
-                        else
-                        {
-                            throw new Exception(string.Format("证书验证错误:{0},{1}", eventArgs.Error.Code, eventArgs.Error.AdditionalInfo));
-                        }
-                    };
-                    //用配置的当前状态更新验证器。
-                    certificateValidator.Update(new SecurityConfiguration
-                    {
-                        //获取或设置一个值,该值指示是否应自动接受不受信任的证书
-                        AutoAcceptUntrustedCertificates = true,
-                        //获取或设置一个值,该值指示是否接受SHA-1签名的证书
-                        RejectSHA1SignedCertificates = false,
-                        //获取或设置一个值,该值指示接受的最小证书密钥强度
-                        MinimumCertificateKeySize = 1024
-                    }).Wait();
-                    //实例化
-                    if (AI == null)
-                    {
-                        AI = new ApplicationInstance();
+                        eventArgs.Accept = true;
                     }
-                    //初始化配置
-                    AI.ApplicationType = ApplicationType.Client;
-                    //配置文件的名称
-                    AI.ConfigSectionName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Opc.Ua.Client");
-                    //加载应用程序配置
-                    AC = AI.LoadApplicationConfiguration(false).Result;
-                    AC.ApplicationName = basics.Name;
-                    AC.ApplicationType = ApplicationType.Client;
-                    AC.CertificateValidator = certificateValidator;
-
-                    //查找与当前设置最匹配的端点
-                    EndpointDescription endpointDescription = CoreClientUtils.SelectEndpoint(basics.ServerUrl, false);
-                    //使用合理的默认值创建配置的实例
-                    EndpointConfiguration endpointConfiguration = EndpointConfiguration.Create(AC);
-                    //配置终端
-                    ConfiguredEndpoint endpoint = new ConfiguredEndpoint(null, endpointDescription, endpointConfiguration);
-
-                    //证书跟密钥的设置,首选证书设置,如两个都为空则是匿名访问
-                    if (!basics.Cer.IsEmpty() && !basics.SecreKey.IsEmpty())//设置证书
+                    else
                     {
-                        X509Certificate2 certificate = new X509Certificate2(basics.Cer, basics.SecreKey, X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.Exportable);
-                        UserIdentity = new UserIdentity(certificate);
+                        throw new Exception(string.Format("证书验证错误:{0},{1}", eventArgs.Error.Code, eventArgs.Error.AdditionalInfo));
                     }
-                    else if (!basics.UserName.IsEmpty() && !basics.Password.IsEmpty())//设置账户密码
+                };
+                //用配置的当前状态更新验证器。
+                certificateValidator.Update(new SecurityConfiguration
+                {
+                    //获取或设置一个值,该值指示是否应自动接受不受信任的证书
+                    AutoAcceptUntrustedCertificates = true,
+                    //获取或设置一个值,该值指示是否接受SHA-1签名的证书
+                    RejectSHA1SignedCertificates = false,
+                    //获取或设置一个值,该值指示接受的最小证书密钥强度
+                    MinimumCertificateKeySize = 1024
+                }).Wait();
+                //实例化
+                if (AI == null)
+                {
+                    AI = new ApplicationInstance();
+                }
+                //初始化配置
+                AI.ApplicationType = ApplicationType.Client;
+
+                string ConfigName = "Opc.Ua.Client";
+                string ConfigPath = string.Empty;
+                foreach (var item in Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory, "*.Config.xml", SearchOption.AllDirectories))
+                {
+                    if (item.Contains(ConfigName))
                     {
-                        UserIdentity = new UserIdentity(basics.UserName, basics.Password);
+                        ConfigPath = Path.Combine(FileTool.GetFolderPath(item), ConfigName);
+                        break;
                     }
-                    //通过调用CreateSession服务创建与服务器的新通信会话
-                    clientSession = Session.Create(AC, endpoint, false, false, AC.ApplicationName, 60000, UserIdentity, null).Result;
-
-                    //当会话关闭,则关闭订阅
-                    clientSession.DeleteSubscriptionsOnClose = true;
-
-                    //当从服务器到达一个存活状态或检测到一个错误时将被引发
-                    clientSession.KeepAlive += new KeepAliveEventHandler(Session_KeepAlive);
-
-                    //设置连接状态
-                    IsConnected = true;
+                }
 
-                    return Break("On", true);
+                //配置文件的名称
+                AI.ConfigSectionName = ConfigPath;
+                //加载应用程序配置
+                AC = AI.LoadApplicationConfiguration(false).Result;
+                AC.ApplicationName = basics.Name;
+                AC.ApplicationType = ApplicationType.Client;
+                AC.CertificateValidator = certificateValidator;
+
+                //查找与当前设置最匹配的端点
+                EndpointDescription endpointDescription = CoreClientUtils.SelectEndpoint(basics.ServerUrl, false);
+                //使用合理的默认值创建配置的实例
+                EndpointConfiguration endpointConfiguration = EndpointConfiguration.Create(AC);
+                //配置终端
+                ConfiguredEndpoint endpoint = new ConfiguredEndpoint(null, endpointDescription, endpointConfiguration);
+
+                //证书跟密钥的设置,首选证书设置,如两个都为空则是匿名访问
+                if (!basics.Cer.IsEmpty() && !basics.SecreKey.IsEmpty())//设置证书
+                {
+                    X509Certificate2 certificate = new X509Certificate2(basics.Cer, basics.SecreKey, X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.Exportable);
+                    UserIdentity = new UserIdentity(certificate);
                 }
-                else
+                else if (!basics.UserName.IsEmpty() && !basics.Password.IsEmpty())//设置账户密码
                 {
-                    return Break("On", false, "OpcUa 配置为空,有可能初始化失败或未初始化");
+                    UserIdentity = new UserIdentity(basics.UserName, basics.Password);
                 }
+                //通过调用CreateSession服务创建与服务器的新通信会话
+                clientSession = Session.Create(AC, endpoint, false, false, AC.ApplicationName, 60000, UserIdentity, null).Result;
+
+                //当会话关闭,则关闭订阅
+                clientSession.DeleteSubscriptionsOnClose = true;
+
+                //当从服务器到达一个存活状态或检测到一个错误时将被引发
+                clientSession.KeepAlive += new KeepAliveEventHandler(Session_KeepAlive);
+
+                //设置连接状态
+                IsConnected = true;
+
+                return Break("On", true);
             }
             catch (Exception ex)
             {

+ 13 - 1
src/YSAI.DAQ/YSAI.Opc/ua/service/OpcUaServiceOperate.cs

@@ -224,8 +224,20 @@ namespace YSAI.Opc.ua.service
                 AI = new ApplicationInstance();
                 //设置类型
                 AI.ApplicationType = ApplicationType.Server;
+
+                string ConfigName = "Opc.Ua.Service";
+                string ConfigPath = string.Empty;
+                foreach (var item in Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory, "*.Config.xml", SearchOption.AllDirectories))
+                {
+                    if (item.Contains(ConfigName))
+                    {
+                        ConfigPath = Path.Combine(FileTool.GetFolderPath(item), ConfigName);
+                        break;
+                    }
+                }
+
                 //获取或设置包含应用程序配置文件路径的配置节的名称(也就是通过配置文件来进行配置)
-                AI.ConfigSectionName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Opc.Ua.Service");
+                AI.ConfigSectionName = ConfigPath;
 
                 //加载应用程序配置
                 ApplicationConfiguration config = AI.LoadApplicationConfiguration(false).Result;

+ 130 - 110
src/YSAI.DAQ/YSAI.Test.Console/Program.cs

@@ -6,123 +6,143 @@ using YSAI.Core.script;
 using YSAI.DaqManage;
 using YSAI.Mqtt.client;
 using YSAI.Mqtt.service.websocket;
+using YSAI.Opc.ua.client;
 using YSAI.RelayManage;
 using YSAI.Unility;
 
-int[] ints = { 8881, 8882 };
-foreach (var item in ints)
+
+OpcUaClientData.Basics opcUaClientData = new OpcUaClientData.Basics() 
 {
-    MqttWebSocketServiceOperate mqttWebSocketServiceOperate = MqttWebSocketServiceOperate.Instance(new MqttWebSocketServiceData.Basics()
-    {
-        Port = item,
-        HttpPort = ($"1{item.ToString()}").ToInt(),
-        LoginID = "ysai",
-        LoginPassword = "ysai",
-        Uri = "ysai"
-    });
-    mqttWebSocketServiceOperate.On();
-}
+    Name="ysai",
+    Password="ysai",
+    ServerUrl= "opc.tcp://127.0.0.1:8866/Opc.Ua.Service",
+    SN="OPCUA1",
+    UserName="ysai"
+};
 
+OpcUaClientOperate opcUaClientOperate = OpcUaClientOperate.Instance(opcUaClientData);
 
-DaqManageOperate manageOperate = new DaqManageOperate();
-manageOperate.OnEvent += DaqEvent;
+OperateResult operateResult = opcUaClientOperate.On();
 
-AddressHandler.RelayEventRegister(RelayEvent);
 
-while (manageOperate != null)
-{
-    Console.Read();
-    //添加订阅
-    Address address = new Address();
-    address.AddressArray = new List<AddressDetails>()
-            {
-                new AddressDetails()
-                {
-                    AddressName = "a.a.a",
-                    AddressDataType = DataType.Bool,
-                    AddressDescribe = "一个动态的布尔类型",
-                    AddressAnotherName = "test",
-                    AddressPropertyName = "aaa",
-                    AddressType = AddressType.Reality
-                },
-                new AddressDetails()
-                {
-                    AddressName = "a.a.h",
-                    AddressDataType = DataType.String,
-                    AddressDescribe = "一个动态的字符串类型",
-                    AddressAnotherName = "test",
-                    AddressPropertyName = "aah",
-                    AddressType = AddressType.Reality,
-                    AddressParseParam = new AddressParse()
-                    {
-                        ParseType = ParseType.ScriptAnalysis,
-                        Script = new ScriptData.Basics()
-                        {
-                            ScriptCode = @"function Convert(value) 
-                                            {
-                                                return '这是脚本测试,传入的参数是:' + value;
-                                            }",
-                            ScriptFunction = "Convert",
-                            ScriptType = ScriptData.ScriptType.JavaScript
-                        }
-                    }
-                },
-                new AddressDetails()
-                 {
-                     AddressName = "a.a.g",
-                     AddressDataType = DataType.Double,
-                     AddressDescribe = "一个动态的浮点类型",
-                     AddressAnotherName = "test",
-                     AddressPropertyName = "aag",
-                     AddressType = AddressType.Reality,
-                     AddressParseParam = new AddressParse()
-                     {
-                         ParseType = ParseType.ScriptAnalysis,
-                         Script = new ScriptData.Basics()
-                         {
-                             ScriptCode = @"function Convert(value) 
-                                            {
-                                                return value*1000;
-                                            }",
-                             ScriptFunction = "Convert",
-                             ScriptType = ScriptData.ScriptType.JavaScript
-                         }
-                     }
-                 },
-                new AddressDetails()
-                 {
-                     AddressName = "OPCDA_VirtualAddress",
-                     AddressDataType =DataType.String,
-                     AddressDescribe = "虚拟地址",
-                     AddressAnotherName = "test",
-                     AddressPropertyName = "OPCDA_VirtualAddress",
-                     AddressType = AddressType.Virtual
-                 },
-                new AddressDetails()
-                  {
-                      AddressName = "OPCDA_VirtualDynamicAddress",
-                      AddressDataType = DataType.String,
-                      AddressDescribe = "虚拟动态地址",
-                      AddressAnotherName = "test",
-                      AddressPropertyName = "OPCDA_VirtualDynamicAddress",
-                      AddressType =AddressType.VirtualDynamic
-                  }
-            };
-    OperateResult operateResult = manageOperate.Subscribe(address, $"YSAI.Opc.da.client.OpcDaClientOperate.OPCDA1");
-    Console.WriteLine(operateResult.Message);
-}
+//FileTool.StringToFile("config/YSAI.Opc.ua.client.OpcUaClientReadController.OPCUA1.Daq.Config.json", opcUaClientData.ToJson().JsonFormatting());
 
+Console.WriteLine();
 
-void RelayEvent(object? sender, object e)
-{
-    EventResult? result = JsonTool.StringToJsonEntity<EventResult>(e.ToJson());
-    Console.ForegroundColor = ConsoleColor.Red;
-    Console.WriteLine(result.Message);
-}
-void DaqEvent(object? sender, YSAI.Core.data.EventResult e)
-{
-    if (e.Message == "点位数据更新")
-        return;
-    Console.ForegroundColor = ConsoleColor.Green;
-    Console.WriteLine(e.Message);
-}
+//int[] ints = { 8881, 8882 };
+//foreach (var item in ints)
+//{
+//    MqttWebSocketServiceOperate mqttWebSocketServiceOperate = MqttWebSocketServiceOperate.Instance(new MqttWebSocketServiceData.Basics()
+//    {
+//        Port = item,
+//        HttpPort = ($"1{item.ToString()}").ToInt(),
+//        LoginID = "ysai",
+//        LoginPassword = "ysai",
+//        Uri = "ysai"
+//    });
+//    mqttWebSocketServiceOperate.On();
+//}
+
+
+//DaqManageOperate manageOperate = new DaqManageOperate();
+//manageOperate.OnEvent += DaqEvent;
+
+//AddressHandler.RelayEventRegister(RelayEvent);
+
+//while (manageOperate != null)
+//{
+//    Console.Read();
+//    //添加订阅
+//    Address address = new Address();
+//    address.AddressArray = new List<AddressDetails>()
+//            {
+//                new AddressDetails()
+//                {
+//                    AddressName = "a.a.a",
+//                    AddressDataType = DataType.Bool,
+//                    AddressDescribe = "一个动态的布尔类型",
+//                    AddressAnotherName = "test",
+//                    AddressPropertyName = "aaa",
+//                    AddressType = AddressType.Reality
+//                },
+//                new AddressDetails()
+//                {
+//                    AddressName = "a.a.h",
+//                    AddressDataType = DataType.String,
+//                    AddressDescribe = "一个动态的字符串类型",
+//                    AddressAnotherName = "test",
+//                    AddressPropertyName = "aah",
+//                    AddressType = AddressType.Reality,
+//                    AddressParseParam = new AddressParse()
+//                    {
+//                        ParseType = ParseType.ScriptAnalysis,
+//                        Script = new ScriptData.Basics()
+//                        {
+//                            ScriptCode = @"function Convert(value) 
+//                                            {
+//                                                return '这是脚本测试,传入的参数是:' + value;
+//                                            }",
+//                            ScriptFunction = "Convert",
+//                            ScriptType = ScriptData.ScriptType.JavaScript
+//                        }
+//                    }
+//                },
+//                new AddressDetails()
+//                 {
+//                     AddressName = "a.a.g",
+//                     AddressDataType = DataType.Double,
+//                     AddressDescribe = "一个动态的浮点类型",
+//                     AddressAnotherName = "test",
+//                     AddressPropertyName = "aag",
+//                     AddressType = AddressType.Reality,
+//                     AddressParseParam = new AddressParse()
+//                     {
+//                         ParseType = ParseType.ScriptAnalysis,
+//                         Script = new ScriptData.Basics()
+//                         {
+//                             ScriptCode = @"function Convert(value) 
+//                                            {
+//                                                return value*1000;
+//                                            }",
+//                             ScriptFunction = "Convert",
+//                             ScriptType = ScriptData.ScriptType.JavaScript
+//                         }
+//                     }
+//                 },
+//                new AddressDetails()
+//                 {
+//                     AddressName = "OPCDA_VirtualAddress",
+//                     AddressDataType =DataType.String,
+//                     AddressDescribe = "虚拟地址",
+//                     AddressAnotherName = "test",
+//                     AddressPropertyName = "OPCDA_VirtualAddress",
+//                     AddressType = AddressType.Virtual
+//                 },
+//                new AddressDetails()
+//                  {
+//                      AddressName = "OPCDA_VirtualDynamicAddress",
+//                      AddressDataType = DataType.String,
+//                      AddressDescribe = "虚拟动态地址",
+//                      AddressAnotherName = "test",
+//                      AddressPropertyName = "OPCDA_VirtualDynamicAddress",
+//                      AddressType =AddressType.VirtualDynamic
+//                  }
+//            };
+//    OperateResult operateResult = manageOperate.Subscribe(address, $"YSAI.Opc.da.client.OpcDaClientOperate.OPCDA1");
+//    Console.WriteLine(operateResult.Message);
+//}
+
+
+//void RelayEvent(object? sender, object e)
+//{
+//    EventResult? result = JsonTool.StringToJsonEntity<EventResult>(e.ToJson());
+//    Console.ForegroundColor = ConsoleColor.Red;
+//    Console.WriteLine(result.Message);
+//}
+//void DaqEvent(object? sender, YSAI.Core.data.EventResult e)
+//{
+//    if (e.Message == "点位数据更新")
+//        return;
+//    Console.ForegroundColor = ConsoleColor.Green;
+//    Console.WriteLine(e.Message);
+//}

+ 8 - 24
src/YSAI.DAQ/YSAI.Unility/FileTool.cs

@@ -19,35 +19,20 @@ namespace YSAI.Unility
         /// <param name="Path">路径</param>
         /// <param name="Create">是否创建</param>
         /// <returns></returns>
-        public static string GetFolderPath(string Path,bool Create=true)
+        public static string GetFolderPath(string Path, bool Create = true)
         {
-           string[] paths= Path.Replace("//", "◆").Replace("\\", "◆").Replace("/", "◆").Split('◆');
-            paths[paths.Length-1] = string.Empty;
-            StringBuilder folders = new StringBuilder();
-            int index = 0;
-            foreach (string path in paths)
+            string? path = System.IO.Path.GetDirectoryName(Path);
+            if (!string.IsNullOrWhiteSpace(path))
             {
-                if (!string.IsNullOrEmpty(path))
+                if (Create)
                 {
-                    if ((paths.Length - 2).Equals(index))
+                    if (!Directory.Exists(path))
                     {
-                        folders.Append(path);
+                        Directory.CreateDirectory(path);
                     }
-                    else
-                    {
-                        folders.Append($"{path}//");
-                    }
-                }
-                index++;
-            }
-            if (Create)
-            {
-                if (!Directory.Exists(folders.ToString()))
-                {
-                    Directory.CreateDirectory(folders.ToString());
                 }
             }
-            return folders.ToString();
+            return path;
         }
         /// <summary>
         /// 获取文件名称
@@ -56,8 +41,7 @@ namespace YSAI.Unility
         /// <returns></returns>
         public static string GetFileName(string Path)
         {
-            string[] paths = Path.Replace("//", "◆").Replace("\\", "◆").Replace("/", "◆").Split('◆');
-            return paths[paths.Length - 1];
+            return System.IO.Path.GetFileName(Path);
         }
         
         /// <summary>