فهرست منبع

因應ftp server 只開放ftps 連線使用
調整FW 放到 ftp server 服務功能
替換設定檔 https & ftps

Jessica Tseng 2 سال پیش
والد
کامیت
43243b00bf

+ 1 - 1
EVCB_OCPP.WSServer/Properties/AssemblyInfo.cs

@@ -35,4 +35,4 @@ using System.Runtime.InteropServices;
 [assembly: AssemblyVersion("1.2.1.0")]
 [assembly: AssemblyFileVersion("1.2.1.0")]
 
-[assembly: AssemblyInformationalVersion("2d3a9cd")]
+[assembly: AssemblyInformationalVersion("2624426")]

BIN
SuperWebSocket/bin/Debug/SuperWebSocket.dll


BIN
SuperWebSocket/bin/Debug/SuperWebSocket.pdb


+ 4 - 4
TestTool.RemoteTriggerAPP/App.config

@@ -35,16 +35,16 @@
   <applicationSettings>
     <TestTool.RemoteTriggerAPP.Properties.Settings>
       <setting name="UpdateFWPreUrl" serializeAs="String">
-        <value>http://ocpp.phihong.com.tw:5000/</value>
+        <value>https://ocpp.phihong.com.tw:5011/</value>
       </setting>
       <setting name="FTPUpdateFWPreUrl" serializeAs="String">
-        <value>ftp://testocpp:testocpp@ocpp.phihong.com.tw/</value>
+        <value>ftps://testocpp:testocpp@ocpp.phihong.com.tw:5002/</value>
       </setting>
       <setting name="GetDiagnosticsPreUrl" serializeAs="String">
-        <value>http://ocpp.phihong.com.tw:5000/api/v1/file/</value>
+        <value>https://ocpp.phihong.com.tw:5011/api/v1/file/</value>
       </setting>
       <setting name="FTPGetDiagnosticsPreUrl" serializeAs="String">
-        <value>ftp://evseocpp:evseocpp@ocpp.phihong.com.tw/</value>
+        <value>ftps://evseocpp:evseocpp@ocpp.phihong.com.tw:5002/</value>
       </setting>
     </TestTool.RemoteTriggerAPP.Properties.Settings>
   </applicationSettings>

+ 7 - 1
TestTool.RemoteTriggerAPP/FTPClient.cs

@@ -129,6 +129,9 @@ namespace TestTool.RemoteTriggerAPP
             reqFTP.UseBinary = true;
             // 上传文件时通知服务器文件的大小 
             reqFTP.ContentLength = fileInf.Length;
+            reqFTP.EnableSsl = true;
+    
+
             int buffLength = 2048000;// 缓冲大小设置为200kb 
             byte[] buff = new byte[buffLength];
             // 打开一个文件流 (System.IO.FileStream) 去读上传的文件 
@@ -191,7 +194,9 @@ namespace TestTool.RemoteTriggerAPP
             long filesize = 0;
             try
             {
+                ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
                 FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(remoteFilepath);
+                reqFTP.EnableSsl = true;
                 reqFTP.KeepAlive = false;
                 reqFTP.UseBinary = true;
                 reqFTP.Credentials = new NetworkCredential(UesrName, Password);//用户,密码
@@ -200,7 +205,7 @@ namespace TestTool.RemoteTriggerAPP
                 filesize = response.ContentLength;
                 return filesize;
             }
-            catch
+            catch(Exception ex)
             {
                 return 0;
             }
@@ -220,6 +225,7 @@ namespace TestTool.RemoteTriggerAPP
             FtpWebRequest request = (FtpWebRequest)WebRequest.Create(target);
             request.Method = WebRequestMethods.Ftp.UploadFile;
             request.Credentials = new NetworkCredential(UesrName, Password);
+           
             state.Request = request;
             state.FileName = uploadFilePath;
 

+ 161 - 0
TestTool.RemoteTriggerAPP/FluentFTPClient.cs

@@ -0,0 +1,161 @@
+using FluentFTP;
+using System;
+using System.Collections.Generic;
+using System.IO;
+using System.Linq;
+using System.Security.Authentication;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace TestTool.RemoteTriggerAPP
+{
+    internal class FluentFTPClient
+    {
+        #region 属性与构造函数
+
+        /// <summary>
+        /// IP地址
+        /// </summary>
+        public string IpAddr { get; set; }
+
+        /// <summary>
+        /// 相对路径
+        /// </summary>
+        public string RelatePath { get; set; }
+
+        /// <summary>
+        /// 端口号
+        /// </summary>
+        public int Port { get; set; }
+
+        /// <summary>
+        /// 用户名
+        /// </summary>
+        public string UserName { get; set; }
+
+        /// <summary>
+        /// 密码
+        /// </summary>
+        public string Password { get; set; }
+
+       
+
+        public FluentFTPClient(string ipAddr, int port, string userName, string password, string relatePath)
+        {
+            this.IpAddr = ipAddr;
+            this.Port = port;
+            this.UserName = userName;
+            this.Password = password;
+            this.RelatePath = relatePath;
+        }
+
+        #endregion
+
+        #region 方法
+
+        public FtpListItem[] ListDir()
+        {
+            FtpListItem[] lists;
+            using (var client = new FtpClient(this.IpAddr, this.UserName, this.Password, this.Port))
+            {
+                client.Config.EncryptionMode = FtpEncryptionMode.Explicit;
+                client.Config.SslProtocols = SslProtocols.Tls12;
+                client.ValidateCertificate += Client_ValidateCertificate;
+                client.Connect();
+
+                client.SetWorkingDirectory(this.RelatePath);
+                lists = client.GetListing();
+            }
+            return lists;
+        }
+
+        private void Client_ValidateCertificate(FluentFTP.Client.BaseClient.BaseFtpClient control, FtpSslValidationEventArgs e)
+        {
+            if (e.PolicyErrors != System.Net.Security.SslPolicyErrors.None)
+            {
+                e.Accept = false;
+            }
+            else
+            {
+                e.Accept = true;
+            }
+        }
+
+        async internal Task<bool> UploadFileAsync(string localFilePath, string remoteFilePath)
+        {
+            bool isOk = false;
+            using (var client = new AsyncFtpClient(this.IpAddr, this.UserName, this.Password, this.Port))
+            {
+                client.Config.EncryptionMode = FtpEncryptionMode.Implicit;
+                client.Config.SslProtocols = SslProtocols.Tls12;
+                client.ValidateCertificate += Client_ValidateCertificate;
+                await client.SetWorkingDirectory(this.RelatePath);
+                await client.Connect();
+
+
+                var status = await client.UploadFile(localFilePath, "/" + remoteFilePath, FtpRemoteExists.Overwrite, false, FtpVerify.Retry);
+                isOk = status == FtpStatus.Success;
+
+            }
+
+            return isOk;
+
+
+        }
+
+
+
+        public bool Upload(string dir, string file)
+        {
+            bool isOk = false;
+            FileInfo fi = new FileInfo(Path.Combine(dir, file));
+            using (FileStream fs = fi.OpenRead())
+            {
+                //long length = fs.Length;
+                using (var client = new FtpClient(this.IpAddr, this.UserName, this.Password, this.Port))
+                {
+                    client.Config.EncryptionMode = FtpEncryptionMode.Implicit;
+                    client.Config.SslProtocols = SslProtocols.Tls12;
+                    client.ValidateCertificate += Client_ValidateCertificate;
+                    client.Connect();
+                    client.SetWorkingDirectory(this.RelatePath);
+                    string remotePath = Path.GetFileName(file);
+                    FtpStatus status = client.UploadStream(fs, remotePath, FtpRemoteExists.Overwrite, true);
+                    isOk = status == FtpStatus.Success;
+
+                }
+            }
+
+            return isOk;
+        }
+
+
+
+
+        /// <summary>
+        /// 下载ftp
+        /// </summary>
+        /// <param name="localAddress"></param>
+        /// <param name="remoteAddress"></param>
+        /// <returns></returns>
+        public bool DownloadFile(string localAddress, string remoteAddress)
+        {
+            using (var client = new FtpClient(this.IpAddr, this.UserName, this.Password, this.Port))
+            {
+                client.Config.EncryptionMode = FtpEncryptionMode.Explicit;
+                client.Config.SslProtocols = SslProtocols.Tls12;
+                client.ValidateCertificate += Client_ValidateCertificate;
+
+                client.SetWorkingDirectory("/");
+                client.Connect();
+                if (client.DownloadFile(localAddress, remoteAddress) == FtpStatus.Success)
+                {
+                    return true;
+                }
+                return false;
+            }
+        }
+
+        #endregion
+    }
+}

+ 1 - 1
TestTool.RemoteTriggerAPP/MainWindow.xaml

@@ -5,7 +5,7 @@
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
         xmlns:local="clr-namespace:TestTool.RemoteTriggerAPP"      
         mc:Ignorable="d"
-        Title="下發測試用工具(公司內網) V1.1.38 (20220622)" Height="481" Width="652">
+        Title="下發測試用工具(公司內網) V1.1.39 (20230223)" Height="481" Width="652">
     <Viewbox>
         <Grid Margin="0,2,2,0">
             <Grid.ColumnDefinitions>

+ 66 - 85
TestTool.RemoteTriggerAPP/MainWindow.xaml.cs

@@ -43,31 +43,22 @@ namespace TestTool.RemoteTriggerAPP
     public partial class MainWindow : Window
     {
 
+
+
+
         string action = "";
         List<UploadFile> publishes = new List<UploadFile>();
-        FTPClient UploadClient = new FTPClient(@"ftp://test.evsocket.phihong.com.cn", "testocpp", "testocpp");
+
         string chargingProfilePath = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "SetChargingProfile.json");
         string dataTransferPath = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "DataTransfer.json");
         int selectedPublish = -1;
         bool isDestroyMode = false;
         public MainWindow()
         {
-            var oo = new { idToken = "3345678", price = "Connection Fee: $2.11 NTD/time; Current Rate: $2.22 NTD/kWh;Occupancy Fee: $2.33 NTD/hr; Account Balance: $2444 NTD" };
-
-
-            var tt = new DataTransferRequest()
-            {
-                vendorId = "Phihong Technology",
-                messageId = "SetUserPrice",
-                data = JsonConvert.SerializeObject(oo)
-            };
-
-            var ttt = JsonConvert.SerializeObject(tt);
-
 
             InitializeComponent();
             Loaded += MainWindow_Loaded;
-            UploadClient.OnUploadProgress += UploadClient_OnUploadProgress;
+
 
         }
 
@@ -98,7 +89,7 @@ namespace TestTool.RemoteTriggerAPP
             {
                 switch (action)
                 {
-                   
+
                     #region Core Profile
                     case "ChangeAvailability_Inoperative":
                         {
@@ -598,9 +589,9 @@ namespace TestTool.RemoteTriggerAPP
                 //        status = AuthorizationStatus.ConcurrentTx
                 //    }
                 //});
-             
 
-                for (int i = 0; i < size ; i++)
+
+                for (int i = 0; i < size; i++)
                 {
                     request.localAuthorizationList.Add(new AuthorizationData()
                     {
@@ -940,96 +931,86 @@ namespace TestTool.RemoteTriggerAPP
                 uxMsgTb.Text = "Please select upload file!";
                 return;
             }
+            string filePath = uxUploadFileTb.Text;
 
-            FileInfo f = new FileInfo(uxUploadFileTb.Text);
-
-            int size = (int)f.Length;
-            string md5 = "";
-            string filePreUrl = ConfigurationManager.AppSettings["UpdateFWPreUrl"];
-            using (WebClient client = new WebClient())
-            {
-                client.UseDefaultCredentials = false;
-                client.Headers.Add("Content-Type", "application/octet-stream");
-                using (Stream fileStream = File.OpenRead(uxUploadFileTb.Text))
-                {
-                    var _md5 = MD5.Create();
-                    var hash = _md5.ComputeHash(fileStream);
-                    md5 = BitConverter.ToString(hash).Replace("-", String.Empty).ToLowerInvariant();
-
-                }
-            }
-
-            UploadFile ufObj = new UploadFile();
-            ufObj.CreatedOn = DateTime.Now.ToUniversalTime();
-            ufObj.FileExtensionName = System.IO.Path.GetExtension(uxUploadFileTb.Text);
-            ufObj.Id = Guid.NewGuid().ToString();
-            ufObj.FileName = md5 + ufObj.FileExtensionName;
-            ufObj.FilePath = "~/UploadFiles/Fw/" + ufObj.FileName;
-            ufObj.FileSize = size;
-            ufObj.FileMD5 = md5;
-            ufObj.OriginName = System.IO.Path.GetFileName(uxUploadFileTb.Text);
-            ufObj.FileUrl = new Uri(Properties.Settings.Default.UpdateFWPreUrl + ufObj.FilePath.Replace("~/", "")).ToString();
-            ufObj.VendorId = "TestTool";
-            ufObj.ModelName = "TestTool";
-            ufObj.ModuleId = 0;
-
-            using (var db = new MainDBContext())
-            {
-                db.UploadFile.Add(ufObj);
-                db.SaveChanges();
-
-            }
 
-            string filePath = uxUploadFileTb.Text;
-            uxMsgTb.Text = "Uploading........";
 
             Task.Run(async () =>
             {
-                await UploadTask(filePath, ufObj.FileName);
-            });
-
-
-
-
-
-
-
-
-
 
+                await UploadTask(filePath, false);
+            });
         }
 
-        private async Task UploadTask(string filePath, string fileName)
+        private async Task UploadTask(string filepath, bool isFTP)
         {
+            try
+            {
+                await Dispatcher.BeginInvoke(new Action(() =>
+                {
+                    uxMsgTb.Text = "Uploading........";
 
-            bool uploadResult = UploadClient.FtpUploadBroken(filePath, @"ftp://ocpp.phihong.com.tw/" + fileName);
+                }));
 
-            await Dispatcher.BeginInvoke(new Action(() =>
-            {
-                if (uploadResult)
+                FileInfo f = new FileInfo(filepath);
+                int size = (int)f.Length;
+                string fileMD5 = "";  //get file md5
+                using (var md5 = MD5.Create())
                 {
-                    uxMsgTb.Text = "Current Progress :100 %";
-                    Thread.CurrentThread.Join(100);
+                    using (var stream = File.OpenRead(filepath))
+                    {
+                        fileMD5 = BitConverter.ToString(md5.ComputeHash(stream)).Replace("-", String.Empty).ToLower();
+                    }
                 }
-                uxMsgTb.Text = "Upload File Result :" + (uploadResult ? "Success" : "Fail");
-
+                string filePreUrl = isFTP ? Properties.Settings.Default.FTPUpdateFWPreUrl : Properties.Settings.Default.UpdateFWPreUrl;
+
+                UploadFile ufObj = new UploadFile();
+                ufObj.CreatedOn = DateTime.Now.ToUniversalTime();
+                ufObj.FileExtensionName = System.IO.Path.GetExtension(filepath);
+                ufObj.Id = Guid.NewGuid().ToString();
+                ufObj.FileName = fileMD5 + System.IO.Path.GetExtension(filepath);
+                ufObj.FilePath = isFTP ? "~/" + ufObj.FileName : "~/UploadFiles/FW/" + ufObj.FileName;
+                ufObj.FileSize = size;
+                ufObj.FileMD5 = fileMD5;
+                ufObj.OriginName = System.IO.Path.GetFileName(filepath);
+                ufObj.FileUrl = new Uri(filePreUrl + ufObj.FilePath.Replace("~/", "")).ToString();
+                ufObj.VendorId = "TestTool";
+                ufObj.ModelName = "TestTool";
+                ufObj.ModuleId = 0;
+
+                using (var db = new MainDBContext())
+                {
+                    db.UploadFile.Add(ufObj);
+                    await db.SaveChangesAsync();
 
-            }));
+                }
 
+                FluentFTPClient ftpClient = new FluentFTPClient("ocpp.phihong.com.tw", 5002, "testocpp", "testocpp", "/");
+                //Properties.Settings.Default.UpdateFWPreUrl
+                bool uploadResult = await ftpClient.UploadFileAsync(filepath, ufObj.FileName);
 
+                await Dispatcher.BeginInvoke(new Action(() =>
+                {
+                    if (uploadResult)
+                    {
+                        uxMsgTb.Text = "Current Progress :100 %";
+                        Thread.CurrentThread.Join(100);
+                    }
+                    uxMsgTb.Text = "Upload File Result :" + (uploadResult ? "Success" : "Fail");
 
 
-        }
+                }));
 
-        private void UploadClient_OnUploadProgress(double percent)
-        {
-            Dispatcher.BeginInvoke(new Action(() =>
+            }
+            catch (Exception ex)
             {
-                uxMsgTb.Text = "Current Progress :" + (int)percent + " %";
 
-            }));
+            }
+
         }
 
+
+
         private void uxFTPUploadBtn_Click(object sender, RoutedEventArgs e)
         {
             if (string.IsNullOrEmpty(uxUploadFileTb.Text))
@@ -1084,7 +1065,7 @@ namespace TestTool.RemoteTriggerAPP
 
             Task.Run(async () =>
             {
-                await UploadTask(filePath, ufObj.FileName);
+                await UploadTask(filePath, true);
             });
 
 

+ 4 - 0
TestTool.RemoteTriggerAPP/TestTool.RemoteTriggerAPP.csproj

@@ -62,6 +62,9 @@
     <Reference Include="EVCB_OCPP.Packet">
       <HintPath>DLL\EVCB_OCPP.Packet.dll</HintPath>
     </Reference>
+    <Reference Include="FluentFTP, Version=45.1.0.0, Culture=neutral, PublicKeyToken=f4af092b1d8df44f, processorArchitecture=MSIL">
+      <HintPath>..\packages\FluentFTP.45.1.0\lib\net462\FluentFTP.dll</HintPath>
+    </Reference>
     <Reference Include="Newtonsoft.Json, Version=12.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL">
       <HintPath>..\packages\Newtonsoft.Json.12.0.2\lib\net45\Newtonsoft.Json.dll</HintPath>
     </Reference>
@@ -95,6 +98,7 @@
       <DependentUpon>App.xaml</DependentUpon>
       <SubType>Code</SubType>
     </Compile>
+    <Compile Include="FluentFTPClient.cs" />
     <Compile Include="FTPClient.cs" />
     <Compile Include="MainWindow.xaml.cs">
       <DependentUpon>MainWindow.xaml</DependentUpon>

+ 1 - 0
TestTool.RemoteTriggerAPP/packages.config

@@ -1,5 +1,6 @@
 <?xml version="1.0" encoding="utf-8"?>
 <packages>
   <package id="EntityFramework" version="6.2.0" targetFramework="net471" />
+  <package id="FluentFTP" version="45.1.0" targetFramework="net471" />
   <package id="Newtonsoft.Json" version="12.0.2" targetFramework="net471" />
 </packages>