浏览代码

对接opcua

wzx 4 天之前
父节点
当前提交
efd495ba14

+ 3 - 3
HEIDENHAIN/Form1.cs

@@ -184,7 +184,7 @@ namespace HEIDENHAIN
                                 }
 
 
-                                if (hdhBody.Type == ActionTypeEnum.Collect.ToString())
+                                if (hdhBody.Type == ActionTypeEnum.Collect.ToString()) //数据采集
                                 {
 
                                     JHAutomatic m_Automatic = Machine.GetInterface(DNC_INTERFACE_OBJECT.DNC_INTERFACE_JHAUTOMATIC);
@@ -223,7 +223,7 @@ namespace HEIDENHAIN
 
 
                                 }
-                                else if (hdhBody.Type == ActionTypeEnum.Upload.ToString())
+                                else if (hdhBody.Type == ActionTypeEnum.Upload.ToString()) //文件上传
                                 {
 
                                     JHFileSystem m_FileSystem = Machine.GetInterface(DNC_INTERFACE_OBJECT.DNC_INTERFACE_JHFILESYSTEM);
@@ -254,7 +254,7 @@ namespace HEIDENHAIN
                                     //设当前上传程序为主程序
                                     m_Automatic.SelectProgram(iChannel, dncPath);
                                 }
-                                else if (hdhBody.Type == ActionTypeEnum.DeleteNc.ToString())
+                                else if (hdhBody.Type == ActionTypeEnum.DeleteNc.ToString()) 
                                 {
 
                                     JHFileSystem m_FileSystem = Machine.GetInterface(DNC_INTERFACE_OBJECT.DNC_INTERFACE_JHFILESYSTEM);

二进制
HEIDENHAIN/HEIDENHAIN_TemporaryKey.pfx


+ 16 - 2
HEIDENHAIN/Heidenhain.csproj

@@ -13,7 +13,7 @@
     <AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
     <Deterministic>true</Deterministic>
     <IsWebBootstrapper>false</IsWebBootstrapper>
-    <PublishUrl>publish\</PublishUrl>
+    <PublishUrl>E:\workspace\code\produce_code\</PublishUrl>
     <Install>true</Install>
     <InstallFrom>Disk</InstallFrom>
     <UpdateEnabled>false</UpdateEnabled>
@@ -23,9 +23,10 @@
     <UpdatePeriodically>false</UpdatePeriodically>
     <UpdateRequired>false</UpdateRequired>
     <MapFileExtensions>true</MapFileExtensions>
-    <ApplicationRevision>0</ApplicationRevision>
+    <ApplicationRevision>1</ApplicationRevision>
     <ApplicationVersion>1.0.0.%2a</ApplicationVersion>
     <UseApplicationTrust>false</UseApplicationTrust>
+    <PublishWizardCompleted>true</PublishWizardCompleted>
     <BootstrapperEnabled>true</BootstrapperEnabled>
   </PropertyGroup>
   <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
@@ -47,6 +48,18 @@
     <ErrorReport>prompt</ErrorReport>
     <WarningLevel>4</WarningLevel>
   </PropertyGroup>
+  <PropertyGroup>
+    <ManifestCertificateThumbprint>C73FAD937CD287F8536C97EF5D03532843D59051</ManifestCertificateThumbprint>
+  </PropertyGroup>
+  <PropertyGroup>
+    <ManifestKeyFile>HEIDENHAIN_TemporaryKey.pfx</ManifestKeyFile>
+  </PropertyGroup>
+  <PropertyGroup>
+    <GenerateManifests>true</GenerateManifests>
+  </PropertyGroup>
+  <PropertyGroup>
+    <SignManifests>true</SignManifests>
+  </PropertyGroup>
   <ItemGroup>
     <Reference Include="Interop.HeidenhainDNCLib, Version=1.5.0.0, Culture=neutral, processorArchitecture=x86">
       <SpecificVersion>False</SpecificVersion>
@@ -95,6 +108,7 @@
       <AutoGen>True</AutoGen>
       <DependentUpon>Resources.resx</DependentUpon>
     </Compile>
+    <None Include="HEIDENHAIN_TemporaryKey.pfx" />
     <None Include="Properties\Settings.settings">
       <Generator>SettingsSingleFileGenerator</Generator>
       <LastGenOutput>Settings.Designer.cs</LastGenOutput>

+ 1 - 1
opcua/App.config

@@ -55,7 +55,7 @@
 			</dependentAssembly>
 			<dependentAssembly>
 				<assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
-				<bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" />
+				<bindingRedirect oldVersion="0.0.0.0-13.0.1.0" newVersion="13.0.1.0" />
 			</dependentAssembly>
 			<dependentAssembly>
 				<assemblyIdentity name="System.Runtime.CompilerServices.Unsafe" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />

+ 3 - 2
opcua/Device/DeviceOPCUat.cs

@@ -333,7 +333,7 @@ namespace YG.Device
         /// <param name="url"></param>
         /// <param name="username"></param>
         /// <param name="pwd"></param>
-        public bool OpcUa_Connection(string url, string username = "OpcUaClient", string pwd = "12345678")
+        public  bool OpcUa_Connection(string url, string username = "OpcUaClient", string pwd = "12345678")
         {
             bool result = false;
             try
@@ -397,7 +397,8 @@ namespace YG.Device
         /// <param name="pwd"></param>
         public static Server OpcUa_Connection1(string url, string username = "OpcUaClient", string pwd = "12345678")
         {
-            Server serverOpcUa = new Server();
+            //OpcUaClient   IGT12345
+           Server serverOpcUa = new Server();
             try
             {
 

+ 3 - 0
opcua/Device/body/RequestBody.cs

@@ -24,6 +24,9 @@ namespace IMCS.Device
 
         public List<string> Values
         { get; set; }
+
+        public string Ip 
+        { get; set; }
     }
 
     /// <summary>

+ 90 - 17
opcua/Form_Main.cs

@@ -13,6 +13,7 @@ using System.Drawing;
 using System.IO;
 using System.Linq;
 using System.Net;
+using System.Net.NetworkInformation;
 using System.Text;
 using System.Threading;
 using System.Threading.Tasks;
@@ -23,13 +24,22 @@ namespace IMCS
 {
     public partial class Form_Main : Form
     {
-        public string UPLOAD_NC_PATH = "Sinumerik/FileSystem/Work Pieces/TEST1/";
+        //public string UPLOAD_NC_PATH = "Sinumerik/FileSystem/NCExtend/wks.dir/nc_program/";
+        public string UPLOAD_NC_PATH = "Sinumerik/FileSystem/Work Pieces/TEST/";
         //public string UPLOAD_NC_PATH = "Sinumerik/FileSystem/NCExtend/";
         public string CHANNEL_NO = "1";
-        public string TEMP_NC_NAME = "7999.MPF";
+        public string TEMP_NC_NAME = "TEMP1.MPF"; //临时程序
         private uint currentToolArea = 1;
+
+        string Listener_URL = "http://20.20.47.107:8010/opcua/";  
         Server opcServer = null;
-        public Dictionary<string, Server> deviceList { get; set; } = new Dictionary<string, Server>();
+        //public Dictionary<string, Server> deviceList { get; set; } = new Dictionary<string, Server>();
+
+        // 作为长连接进行bean的存储, key使用ip,
+        Dictionary<string, Server> opcServerMap = new Dictionary<string, Server>();
+
+
+
 
         public Form_Main()
         {
@@ -41,9 +51,9 @@ namespace IMCS
             HttpListener httpListenner;
             httpListenner = new HttpListener();
             httpListenner.AuthenticationSchemes = AuthenticationSchemes.Anonymous;
-            httpListenner.Prefixes.Add("http://127.0.0.1:8010/opcua/");
+            httpListenner.Prefixes.Add(Listener_URL);
             httpListenner.Start();
-            label1.Text = "HttpServer已开启:http://127.0.0.1:8010/opcua/";
+            label1.Text = "HttpServer已开启:" + Listener_URL;
             new Thread(new ThreadStart(delegate
             {
                 try
@@ -81,6 +91,11 @@ namespace IMCS
                 {
                     if (!request.Url.ToString().Contains("favicon"))
                     {
+
+                        RequestBody opcBody = null;
+                        ResponseBody responseBody = new ResponseBody();
+                        Server opcServer = null;
+
                         try
                         {
                             Stream stream = context.Request.InputStream;
@@ -88,13 +103,15 @@ namespace IMCS
                             string body = reader.ReadToEnd();
 
                             YG.Log.Instance.WriteLogAdd(">>>===收到POST数据 : >>>>===" + body);
-                            ResponseBody responseBody = new ResponseBody();
+                            responseBody = new ResponseBody();
 
-                            RequestBody opcBody = JsonConvert.DeserializeObject<RequestBody>(body);
+
+                            opcBody = JsonConvert.DeserializeObject<RequestBody>(body);
 
                             AddList(DateTime.Now.ToString(), "POST", opcBody.ServerUrl + opcBody.Type, "OK");
 
-                            if (deviceList == null || (deviceList.Where(m => m.Key.Equals(opcBody.ServerUrl)).Count() == 0))
+                            /*
+                             * if (deviceList == null || (deviceList.Where(m => m.Key.Equals(opcBody.ServerUrl)).Count() == 0))
                             {
                                 opcServer = DeviceOPCUat.OpcUa_Connection1(opcBody.ServerUrl, opcBody.UserName, opcBody.Password);
                                 if (opcServer.Session != null)
@@ -110,18 +127,42 @@ namespace IMCS
                             {
                                 opcServer = DeviceOPCUat.OpcUa_Connection1(opcBody.ServerUrl, opcBody.UserName, opcBody.Password);
                             }
+                            */
                             //else
                             //{
                             //    opcServer.Session.Reconnect();
                             //}
 
-                            if (opcServer.Session.Connected)
+                            // 从map中取出opcServer 判断是否存在,以及是否可用
+                            opcServerMap.TryGetValue(opcBody.ServerUrl, out opcServer);
+
+                            // 如果key不存在,或者存在单连接不上,则需要重新创建连接
+                            if (!opcServerMap.ContainsKey(opcBody.ServerUrl) || !opcServer.Session.Connected)
+                            {
+                                Ping pingSender = new Ping();
+                                PingReply reply = pingSender.Send(opcBody.Ip);
+                                if (reply.Status == IPStatus.Success)
+                                {
+                                    opcServer = DeviceOPCUat.OpcUa_Connection1(opcBody.ServerUrl, opcBody.UserName, opcBody.Password);
+                                }
+
+                                if (opcServer != null && opcServer.Session != null && opcServer.Session.Connected)
+                                {
+                                    // 存储Server bean
+                                    opcServerMap.Add(opcBody.ServerUrl, opcServer);
+                                }
+
+                            }
+
+
+
+                            if (opcServer != null && opcServer.Session != null && opcServer.Session.Connected)
                             {
                                 if (opcBody.Type == ActionTypeEnum.Connect.ToString()) //连接状态
                                 {
                                     responseBody.result = true;
                                 }
-                                else if (opcBody.Type == ActionTypeEnum.Collect.ToString()) //采集
+                                else if (opcBody.Type == ActionTypeEnum.Collect.ToString()) //数据采集
                                 {
                                     //ETH_S7Simens s7 = new ETH_S7Simens("192.168.11.164");
 
@@ -203,27 +244,29 @@ namespace IMCS
                                 {
                                     opcServer.WriteValues(opcBody.Values, opcBody.Addresses);
                                 }
-                                else if (opcBody.Type == ActionTypeEnum.SelectNc.ToString())
+                                else if (opcBody.Type == ActionTypeEnum.SelectNc.ToString()) // 选中程序
                                 {
                                     string sSelectedFileName = Path.GetFileName(opcBody.Path);
                                     string status = opcServer.MethodCallSelectProgram(UPLOAD_NC_PATH + sSelectedFileName, Convert.ToUInt32(CHANNEL_NO)).status;
                                     if (status == "Good")
                                     {
-                                        responseBody.msg = "选择成功";
+                                        responseBody.msg = "选择程序成功";
                                     }
                                     else
                                     {
-                                        responseBody.msg = "选择失败";
+                                        responseBody.msg = "选择程序失败";
                                     }
                                 }
-                                else if (opcBody.Type == ActionTypeEnum.Upload.ToString())
+                                else if (opcBody.Type == ActionTypeEnum.Upload.ToString())  //上传文件
                                 {
                                     string file = opcBody.Path;
                                     string serverPath = "";
                                     //选择临时文件
-                                    string status = opcServer.MethodCallSelectProgram(UPLOAD_NC_PATH + TEMP_NC_NAME, Convert.ToUInt32(CHANNEL_NO)).status;
+                                    
                                     try
                                     {
+                                        string status = opcServer.MethodCallSelectProgram(UPLOAD_NC_PATH + TEMP_NC_NAME, Convert.ToUInt32(CHANNEL_NO)).status;
+                                        
                                         string extension = Path.GetExtension(file);
                                         if (string.IsNullOrWhiteSpace(extension))
                                         {
@@ -252,6 +295,8 @@ namespace IMCS
                                         catch (Exception ex)
                                         {
                                             responseBody.msg = "上传文件失败===>" + ex.Message;
+                                            responseBody.code = 0;
+                                            responseBody.result = false;
                                             YG.Log.Instance.WriteLogAdd($"{ex.Message}");
                                         }
 
@@ -262,9 +307,37 @@ namespace IMCS
                                         responseBody.msg = "上传文件失败===>" + ex.Message;
                                         YG.Log.Instance.WriteLogAdd($"493-->{ex.Message}");
                                     }
-                                    //设位主程序
-                                    status = opcServer.MethodCallSelectProgram(serverPath, Convert.ToUInt32(CHANNEL_NO)).status;
+
+                                    //设为主程序
+                                    try
+                                    {
+
+                                        Server.MethodCallResult methodCallResult = opcServer.MethodCallSelectProgram(serverPath, Convert.ToUInt32(CHANNEL_NO));
+
+                                        if (methodCallResult.status.ToUpper().Equals("GOOD"))
+                                        {
+                                            responseBody.msg += "==设为主程序成功";
+                                            YG.Log.Instance.WriteLogAdd(serverPath + "设为主程序成功");
+                                        }
+                                        else
+                                        {
+                                            responseBody.code = 0;
+                                            responseBody.result = false;
+                                            responseBody.msg += "==设为主程序失败";
+                                            YG.Log.Instance.WriteLogAdd(serverPath + "设为主程序失败");
+                                        }
+                                    }
+                                    catch (Exception ex)
+                                    {
+                                        responseBody.code = 0;
+                                        responseBody.result = false;
+                                        responseBody.msg = "设为主程序失败";
+                                        YG.Log.Instance.WriteLogAdd($"设为主程序失败-->{ex.Message}");
+                                    }
+
+                                    
                                 }
+                                
 
                             }
                             else

+ 28 - 6
opcua/OpcUA.csproj

@@ -1,5 +1,6 @@
 <?xml version="1.0" encoding="utf-8"?>
 <Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <Import Project="..\packages\Costura.Fody.6.0.0\build\Costura.Fody.props" Condition="Exists('..\packages\Costura.Fody.6.0.0\build\Costura.Fody.props')" />
   <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
   <PropertyGroup>
     <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
@@ -12,7 +13,10 @@
     <FileAlignment>512</FileAlignment>
     <AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
     <Deterministic>true</Deterministic>
-    <PublishUrl>publish\</PublishUrl>
+    <IsWebBootstrapper>false</IsWebBootstrapper>
+    <NuGetPackageImportStamp>
+    </NuGetPackageImportStamp>
+    <PublishUrl>E:\workspace\code\produce_code\</PublishUrl>
     <Install>true</Install>
     <InstallFrom>Disk</InstallFrom>
     <UpdateEnabled>false</UpdateEnabled>
@@ -22,13 +26,12 @@
     <UpdatePeriodically>false</UpdatePeriodically>
     <UpdateRequired>false</UpdateRequired>
     <MapFileExtensions>true</MapFileExtensions>
-    <ApplicationRevision>0</ApplicationRevision>
+    <AutorunEnabled>true</AutorunEnabled>
+    <ApplicationRevision>3</ApplicationRevision>
     <ApplicationVersion>1.0.0.%2a</ApplicationVersion>
-    <IsWebBootstrapper>false</IsWebBootstrapper>
     <UseApplicationTrust>false</UseApplicationTrust>
+    <PublishWizardCompleted>true</PublishWizardCompleted>
     <BootstrapperEnabled>true</BootstrapperEnabled>
-    <NuGetPackageImportStamp>
-    </NuGetPackageImportStamp>
   </PropertyGroup>
   <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
     <PlatformTarget>AnyCPU</PlatformTarget>
@@ -53,11 +56,20 @@
     <TargetZone>LocalIntranet</TargetZone>
   </PropertyGroup>
   <PropertyGroup>
-    <GenerateManifests>false</GenerateManifests>
+    <GenerateManifests>true</GenerateManifests>
   </PropertyGroup>
   <PropertyGroup>
     <ApplicationManifest>Properties\app.manifest</ApplicationManifest>
   </PropertyGroup>
+  <PropertyGroup>
+    <ManifestCertificateThumbprint>DADD0BD8AE106476B836918B27A1B9AB85099F74</ManifestCertificateThumbprint>
+  </PropertyGroup>
+  <PropertyGroup>
+    <ManifestKeyFile>OpcUA_TemporaryKey.pfx</ManifestKeyFile>
+  </PropertyGroup>
+  <PropertyGroup>
+    <SignManifests>false</SignManifests>
+  </PropertyGroup>
   <ItemGroup>
     <Reference Include="HslCommunication">
       <HintPath>..\软件\UV胶揭钢片V1.21.3.08\UV胶揭钢片V1.21.3.08\DKUV\bin\Debug\HslCommunication.dll</HintPath>
@@ -148,6 +160,8 @@
       <AutoGen>True</AutoGen>
       <DependentUpon>Resources.resx</DependentUpon>
     </Compile>
+    <None Include="OpcUA_TemporaryKey.pfx" />
+    <None Include="packages.config" />
     <None Include="Properties\app.manifest" />
     <None Include="Properties\Settings.settings">
       <Generator>SettingsSingleFileGenerator</Generator>
@@ -185,4 +199,12 @@
     <Content Include="dll\UAClientHelperAPI.dll" />
   </ItemGroup>
   <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
+  <Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
+    <PropertyGroup>
+      <ErrorText>这台计算机上缺少此项目引用的 NuGet 程序包。使用“NuGet 程序包还原”可下载这些程序包。有关更多信息,请参见 http://go.microsoft.com/fwlink/?LinkID=322105。缺少的文件是 {0}。</ErrorText>
+    </PropertyGroup>
+    <Error Condition="!Exists('..\packages\Costura.Fody.6.0.0\build\Costura.Fody.props')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\Costura.Fody.6.0.0\build\Costura.Fody.props'))" />
+    <Error Condition="!Exists('..\packages\Costura.Fody.6.0.0\build\Costura.Fody.targets')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\Costura.Fody.6.0.0\build\Costura.Fody.targets'))" />
+  </Target>
+  <Import Project="..\packages\Costura.Fody.6.0.0\build\Costura.Fody.targets" Condition="Exists('..\packages\Costura.Fody.6.0.0\build\Costura.Fody.targets')" />
 </Project>

二进制
opcua/OpcUA_TemporaryKey.pfx


+ 8 - 3
opcua/Properties/app.manifest

@@ -15,11 +15,16 @@
             如果你的应用程序需要此虚拟化来实现向后兼容性,则删除此
             元素。
         -->
-        <requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
-      </requestedPrivileges>
+        <!-- <requestedExecutionLevel level="requireAdministrator" uiAccess="false" />     
+		 <requestedExecutionLevel level="asInvoker" uiAccess="false" /> 
+		-->
+		  <requestedExecutionLevel level="asInvoker" uiAccess="false" />
+
+
+	  </requestedPrivileges>
       <applicationRequestMinimum>
         <defaultAssemblyRequest permissionSetReference="Custom" />
-        <PermissionSet class="System.Security.PermissionSet" version="1" ID="Custom" SameSite="site" Unrestricted="true" />
+        <PermissionSet class="System.Security.PermissionSet" version="1" ID="Custom" SameSite="site" />
       </applicationRequestMinimum>
     </security>
   </trustInfo>

+ 4 - 0
opcua/packages.config

@@ -0,0 +1,4 @@
+<?xml version="1.0" encoding="utf-8"?>
+<packages>
+  <package id="Costura.Fody" version="6.0.0" targetFramework="net46" developmentDependency="true" />
+</packages>