瀏覽代碼

先提交

djs 3 月之前
父節點
當前提交
9096a3f3d9

+ 23 - 0
MV485/Dlg/waitUpgradeWindow.xaml

@@ -0,0 +1,23 @@
+<Window x:Class="MV485.Dlg.WaitUpgradeWindow"
+        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
+        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
+        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
+        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
+        xmlns:local="clr-namespace:MV485.Dlg"
+        mc:Ignorable="d"
+        Title="请稍候" WindowStartupLocation="CenterScreen" ResizeMode="NoResize" SizeToContent="WidthAndHeight"
+        WindowStyle="None" AllowsTransparency="True" Background="Transparent">
+    <Grid>
+        <Border Background="White" CornerRadius="10" Padding="20" BorderBrush="Gray" BorderThickness="1">
+            <StackPanel HorizontalAlignment="Center" VerticalAlignment="Center">
+                <!--<TextBlock Text="正在删除,请稍候..." FontSize="16" Margin="0,10" TextAlignment="Center"/>-->
+                <TextBlock Text="{Binding TitleInfo}" FontSize="16" Margin="0,10" TextAlignment="Center"/>
+                <!--<TextBlock x:Name="txtProgress" Visibility="Collapsed"  FontSize="16" TextAlignment="Center" Margin="0,10"/>-->
+                <ProgressBar IsIndeterminate="True" Width="200" Height="10" />
+
+                <Button x:Name="btnStop" Click="BtnStop_Click"
+                        Content="中止升级" FontSize="14"  Width="80" Margin="0 10 0 10" Padding="5" />
+            </StackPanel>
+        </Border>
+    </Grid>
+</Window>

+ 62 - 0
MV485/Dlg/waitUpgradeWindow.xaml.cs

@@ -0,0 +1,62 @@
+using System;
+using System.Collections.Generic;
+using System.ComponentModel;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+using System.Windows;
+using System.Windows.Controls;
+using System.Windows.Data;
+using System.Windows.Documents;
+using System.Windows.Input;
+using System.Windows.Media;
+using System.Windows.Media.Imaging;
+using System.Windows.Shapes;
+
+namespace MV485.Dlg
+{
+    /// <summary>
+    /// waitUpgradeWindow.xaml 的交互逻辑
+    /// </summary>
+    public partial class WaitUpgradeWindow : Window, INotifyPropertyChanged
+    {
+        public event PropertyChangedEventHandler PropertyChanged;
+
+        protected void OnPropertyChanged(string propertyName)
+        {
+            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
+        }
+
+        public event Action StopUpgrade;
+
+        private string _titleInfo;
+        public string TitleInfo
+        {
+            get => _titleInfo;
+            set
+            {
+                if (_titleInfo != value)
+                {
+                    _titleInfo = value;
+                    OnPropertyChanged(nameof(TitleInfo));
+                }
+            }
+        }
+
+        public WaitUpgradeWindow(string titleInfo)
+        {
+            InitializeComponent();
+
+
+            TitleInfo = titleInfo;
+
+            this.DataContext = this;
+        }
+
+        private void BtnStop_Click(object sender, RoutedEventArgs e)
+        {
+            StopUpgrade?.Invoke();
+        }
+        //------------------------------------------------------------
+    }
+}

+ 7 - 0
MV485/MV485.csproj

@@ -139,6 +139,9 @@
     <Compile Include="Dlg\RegisterDlg.xaml.cs">
       <DependentUpon>RegisterDlg.xaml</DependentUpon>
     </Compile>
+    <Compile Include="Dlg\waitUpgradeWindow.xaml.cs">
+      <DependentUpon>waitUpgradeWindow.xaml</DependentUpon>
+    </Compile>
     <Compile Include="Dlg\WaitWindow.xaml.cs">
       <DependentUpon>WaitWindow.xaml</DependentUpon>
     </Compile>
@@ -254,6 +257,10 @@
       <SubType>Designer</SubType>
       <Generator>MSBuild:Compile</Generator>
     </Page>
+    <Page Include="Dlg\waitUpgradeWindow.xaml">
+      <SubType>Designer</SubType>
+      <Generator>MSBuild:Compile</Generator>
+    </Page>
     <Page Include="Dlg\WaitWindow.xaml">
       <SubType>Designer</SubType>
       <Generator>MSBuild:Compile</Generator>

+ 33 - 1
MV485/db/DBUpgradeHis.cs

@@ -220,7 +220,39 @@ namespace MV485.db
                 return false;
             }
         }
-        //
+
+        public static bool UpdateUpgradeResult(TUpgradeHis his)
+        {
+            // 定义更新的 SQL 语句
+            string sql = @"
+                UPDATE t_upgrade_his 
+                SET 
+                    upgrade_result = @UpgradeResult
+                WHERE his_id = @HisId";
+
+            // 创建 SQL 参数
+            SQLiteParameter[] parameters = new SQLiteParameter[]
+            {
+                new SQLiteParameter("@HisId", his.HisId),
+                new SQLiteParameter("@UpgradeResult", his.UpgradeResult)
+            };
+
+            try
+            {
+                // 调用 SQLiteHelper 执行更新操作
+                int rowsAffected = SQLiteHelper.ExecuteSql(sql, parameters);
+
+                // 如果更新成功,返回 true,否则返回 false
+                return rowsAffected > 0;
+            }
+            catch (Exception ex)
+            {
+                // 处理异常(如果有的话)
+                Console.WriteLine("Error updating data: " + ex.Message);
+                return false;
+            }
+        }
+        //----------------------------------------------------------------------------------
     }
 
 }

+ 14 - 5
MV485/helper/DeviceUpgrade.cs

@@ -88,6 +88,11 @@ namespace MV485.helper
             }
         }
 
+        public async Task StopSendFileAsync()
+        {
+            _cancellationToken?.c
+        }
+
         //开始异步发送升级包文件
 
         public async Task<bool> StartSendFileAsync(IProgress<string> progress, string portName,int baudRate,byte[] fileData)
@@ -196,8 +201,8 @@ namespace MV485.helper
                 }
             }
 
-            _serialPort.Write(new[] { EOT }, 0, 1);
-            progress.Report("发送 EOT,等待 ACK...");
+            //_serialPort.Write(new[] { EOT }, 0, 1);
+            //progress.Report("发送 EOT,等待 ACK...");
             if (!await SendEotWithRetryAsync(cancellationToken))
             {
                 progress.Report("未收到 EOT 的 ACK,升级失败。发送 CAN 通知设备...");
@@ -211,14 +216,18 @@ namespace MV485.helper
 
         private async Task<bool> SendEotWithRetryAsync(CancellationToken token)
         {
-            for (int attempt = 0; attempt < 3; attempt++)
+            //等待10秒
+            for (int attempt = 0; attempt < _maxRetry; attempt++)
             {
                 _serialPort.Write(new[] { EOT }, 0, 1);
-                await Task.Delay(100, token);
-
+                //await Task.Delay(100, token);
+                _progress.Report("发送 EOT,等待 ACK...");
                 var result = await WaitForByteAsync(token, ACK);
                 if (result == ACK)
+                {
+                    _progress.Report("收到EOT的ACK");
                     return true;
+                }
             }
             return false;
         }

+ 70 - 26
MV485/uc/UCDeviceUpgrade.xaml.cs

@@ -386,13 +386,13 @@ namespace MV485.uc
             //开始升级
             //1.先向设备写入(通知)升级包文件的长度及CRC32的值
             string titleInfo = "开始写入升级包的信息";
-            WaitWindow waitWindow = new WaitWindow(titleInfo)
+            WaitUpgradeWindow waitWindow = new WaitUpgradeWindow(titleInfo)
             {
                 Owner = Application.Current.MainWindow,
                 WindowStartupLocation = WindowStartupLocation.CenterOwner
-            };
+            };            
             waitWindow.Show();
-
+            Application.Current.MainWindow.IsEnabled = false;
             try
             {
                 //开始先设备写入文件信息
@@ -407,6 +407,21 @@ namespace MV485.uc
                     return;
                 }
 
+                //记录开始升级的信息
+                TUpgradeHis upgradeHis = new TUpgradeHis()
+                {
+                    HisId = Guid.NewGuid().ToString().Replace("-", ""),
+                    DeviceSn = txtDeviceSn.Text,
+                    PortName = portName,
+                    BaudRate = baudrate,
+                    Address = devId,
+                    OldFireware = txtOldFireware.Text,
+                    UpgradeTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
+                    NewFireware = txtNewFireware.Text,
+                    UpgradeResult = 0
+                };
+                await AddUpgradeItem(upgradeHis);
+
                 //开始通信
                 DeviceUpgrade deviceUpgrade = new DeviceUpgrade();
                 Progress<string> progress = new Progress<string>(msg =>
@@ -420,7 +435,7 @@ namespace MV485.uc
                     waitWindow.Dispatcher.BeginInvoke(new Action(() =>
                     {
                         //percentText = $"已发送:{packNum}/{totalPacks}({(double)packNum / totalPacks:P1})";
-                        percentText = $"已下载:{(double)packNum / totalPacks:P2}";
+                        percentText = $"已下载:{(double)packNum / totalPacks:P1}";
                         waitWindow.TitleInfo = percentText;
                         //$"已发送{packNum}/{totalPacks}";
                     }));
@@ -430,17 +445,24 @@ namespace MV485.uc
                     //});
                 };
 
+                waitWindow.StopUpgrade += () =>
+                {
+
+                };
+
                 bool blSend = await deviceUpgrade.StartSendFileAsync(progress, portName, baudrate, fileData);
 
                 if (blSend)
                 {
+                    upgradeHis.UpgradeResult = 1;  //升级失败
+                    await UpdateUpgradeResult(upgradeHis);
                     //提示继续等待设备重启,并验证升级是否成功
                     //MessageBox.Show(Application.Current.MainWindow,"向设备写入新固件成功,")
 
                     MessageBoxResult result = MessageBox.Show("向设备写入新固件成功,设备即将重启。\n是否等待自动验证重启后的版本是否正确", 
                         "确认", MessageBoxButton.YesNo, MessageBoxImage.Question);
 
-                    if (result != MessageBoxResult.No) return;
+                    if (result == MessageBoxResult.No) return;
 
                     //继续等待失败是否成功
                     titleInfo = $"正在等待验证重启后版本是否正确(1~2分钟)";
@@ -483,6 +505,8 @@ namespace MV485.uc
                 }
                 else
                 {
+                    upgradeHis.UpgradeResult = -1;  //升级失败
+                    await UpdateUpgradeResult(upgradeHis);
                     MessageBox.Show(Application.Current.MainWindow, "向设备写入新固件时失败", "错误",
                         MessageBoxButton.OK, MessageBoxImage.Error);
                 }
@@ -491,6 +515,7 @@ namespace MV485.uc
             finally
             {
                 waitWindow.Close();
+                Application.Current.MainWindow.IsEnabled = true;
             }
 
         }
@@ -671,32 +696,51 @@ namespace MV485.uc
         {
             if (his == null) return;
 
-            bool blInsert = await Task.Run(() =>
+            try
             {
-                return DBUpgradeHis.InsertUpgradeHis(his);
-            });
+                bool blInsert = await Task.Run(() =>
+                {
+                    return DBUpgradeHis.InsertUpgradeHis(his);
+                });
 
-            if (!blInsert) return;
+                if (!blInsert) return;
+
+                await Dispatcher.InvokeAsync(() =>
+               {
+                   _hisList.Insert(0, his);
+                   HisRecords++;
+                   DetailPage.PageCount = (int)Math.Ceiling(((double)HisRecords / DetailPage.PageSize));
+
+                   if (_hisList.Count > DetailPage.PageSize)
+                   {
+                       for (int i = _hisList.Count - 1; i >= DetailPage.PageSize; i--)
+                       {
+                           _hisList.Remove(_hisList[i]);
+                       }
+                   }
+
+                   for (int i = 0; i < _hisList.Count; i++)
+                   {
+                       _hisList[i].Index = i + 1;
+                   }
+               });
+                AppendLog("新增升级条目");
+            }
+            catch { }
+        }
 
-            await Dispatcher.InvokeAsync( ()=>
+        private async Task UpdateUpgradeResult(TUpgradeHis his)
+        {
+            if (his == null) return;
+            try
             {
-                _hisList.Insert(0, his);
-                HisRecords++;
-                DetailPage.PageCount = (int)Math.Ceiling(((double)HisRecords / DetailPage.PageSize));
-
-                if (_hisList.Count > DetailPage.PageSize)
-                {
-                    for (int i = _hisList.Count - 1; i >= DetailPage.PageSize; i--)
-                    {
-                        _hisList.Remove(_hisList[i]);
-                    }
-                }
-
-                for (int i = 0; i < _hisList.Count; i++)
+                bool blUpdate = await Task.Run(() =>
                 {
-                    _hisList[i].Index = i + 1;
-                }
-            });
+                    return DBUpgradeHis.UpdateUpgradeResult(his);
+                });
+                AppendLog("更新条目的升级结果");
+            }
+            catch { }
         }
 
         private async void BtnClearDataA_Click(object sender, RoutedEventArgs e)

+ 4 - 1
MV485/uc/UCRunConfig.xaml.cs

@@ -314,11 +314,14 @@ namespace MV485.uc
             waitWindow.Show();
 
             XModemReceiver receiver = new XModemReceiver();
+            string percentText = "";
             receiver.OnProgress += (receiveSize, fileSize) =>
             {
                 waitWindow.Dispatcher.Invoke(() =>
                 {
-                    waitWindow.TitleInfo = $"已接受{receiveSize}/{fileSize}";
+                    percentText = $"已读取:{(double)receiveSize / fileSize:P1}";
+                    waitWindow.TitleInfo = percentText;
+                    //waitWindow.TitleInfo = $"已接受{receiveSize}/{fileSize}";
                 });
             };
             receiver.RWLog += message =>