From d0ded5cd9bf5070a120bad58b5be21fe2ac6a4ff Mon Sep 17 00:00:00 2001
From: C3032 <C3032@BC3032>
Date: 星期六, 20 十二月 2025 16:41:09 +0800
Subject: [PATCH] test

---
 IDViewer_2D/MainWindow.xaml.cs | 3494 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
 1 files changed, 3,494 insertions(+), 0 deletions(-)

diff --git a/IDViewer_2D/MainWindow.xaml.cs b/IDViewer_2D/MainWindow.xaml.cs
new file mode 100644
index 0000000..debfd97
--- /dev/null
+++ b/IDViewer_2D/MainWindow.xaml.cs
@@ -0,0 +1,3494 @@
+锘�
+using System;
+using System.Runtime.InteropServices;
+using System.Windows;
+using System.Windows.Controls;
+using System.Windows.Media;
+using System.Windows.Threading;
+using static SmartScanner.IDViewerDefines;
+using static SmartScanner.IDViewerSDK;
+using static SmartScanner.IDViewerSDK2;
+using System.Drawing;
+using System.Drawing.Imaging;
+using System.Windows.Media.Imaging;
+using System.IO;
+using System.Runtime;
+using OpenCvSharp;
+using System.Windows.Media.Media3D;
+using System.Collections.Generic;
+using System.Threading;
+using System.Net.Sockets;
+using System.Text;
+using static System.Net.Mime.MediaTypeNames;
+using System.Net;
+using System.Threading.Tasks;
+using static OpenCvSharp.XImgProc.CvXImgProc;
+using System.Diagnostics;
+using System.Linq;
+using System.Text.RegularExpressions;
+using Newtonsoft.Json;
+using SmartScanner.ViewModel;
+using SmartScanner.OperateLog;
+using System.Windows.Input;
+using System.Timers;
+using System.Net.NetworkInformation;
+
+namespace SmartScanner
+{
+    /// <summary>
+    /// MainWindow.xaml 鐨勪氦浜掗�昏緫
+    /// </summary>
+    /// 
+    public partial class MainWindow : System.Windows.Window
+    {
+        //璁惧鐨勫彞鏌�
+        private readonly Dictionary<int, IntPtr> _deviceHandles = new Dictionary<int, IntPtr>();
+
+        //鍥惧儚鍙ユ焺
+        private readonly Dictionary<int, IntPtr> _imagePtr = new Dictionary<int, IntPtr>();
+
+        //妯″瀷鍖归厤
+        private readonly Dictionary<int, IntPtr> _DetectorSelect = new Dictionary<int, IntPtr>();
+
+        //閫夋嫨鐨勮澶�
+        public int selectedIndex;
+
+        //璁惧缂栧彿
+        public int[] deviceIndex = new int[100];
+
+        //杩炴帴璁惧涓暟
+        int IsConnected = 0;
+
+        public IntPtr devicesListHandle;
+
+        //鑰楁椂璁$畻
+        Stopwatch stopwatch = new Stopwatch();
+
+        ModbusTCPClient modbusTCPClient = new ModbusTCPClient();
+
+        //瀹炰緥鍖杔og绫�
+        //EnhancedLogViewModel EnhancedLogViewModel.Instance = new EnhancedLogViewModel();
+
+        //璁惧淇℃伅缁撴瀯浣撳彞鏌�
+        IDDeviceInfo[] deviceInfo = new IDDeviceInfo[100];
+
+        delegate void IDViewerCallBack(IntPtr device, IntPtr image);
+        delegate void IDViewerCallBack1(IntPtr device, IntPtr image);
+
+        //妫�娴嬭繛鎺ョ姸鎬佸畾鏃跺櫒
+        private System.Threading.Timer deviceStatusTimer;
+        private int deviceStatusInterval = 3000; // 3绉�
+
+        //鍥炶皟濮旀墭
+        static IDViewerCallBack[] callbackDelegate;
+
+        IDNodeParam iDNodeParam;
+
+        //鍒涘缓妫�娴嬪櫒
+        public IntPtr detector = new IntPtr();
+        public static string filePath = ".\\detector.txt";
+        string Detector_Device = File.ReadAllText(filePath);
+
+        //淇″彿淇濇寔鏃堕棿
+        public static string holdtime = ".\\HoldTime.txt";
+        public string Hold_Time = File.ReadAllText(holdtime);
+
+        //淇″彿淇濇寔鏃堕棿
+        public static string selflockingtime = ".\\SelflockingTime.txt";
+        public string Selflocking_Time = File.ReadAllText(holdtime);
+        //string Detector_Device = "CPU";
+        //string modelPath = ".\\model\\best.onnx";
+
+        //TCP閫氳鍙傛暟
+        //private TcpListener _server;
+        //private TcpClient _client;
+        //private NetworkStream _stream;
+        private TcpServerManager _tcpServerManager;
+
+        //鍥惧儚瀛楄妭鏁扮粍
+        int batchSize = 2;
+        byte[] imgBatch1 = null;
+        byte[] imgBatch2 = null;
+
+        //杈撳嚭缁撴灉鏁扮粍
+        public bool[] outputs = new bool[20];
+        private TextBlock[] cameraAliasLabels;
+        private TextBlock[] deviceNames;
+
+        //NG鍥剧墖璺緞闆嗗悎
+        public List<string> Image_NG = new List<string>();
+
+        //瀵勫瓨鍣ㄦ帶鍒跺彉閲�
+        public int[] usOutput = new int[16];
+        public int[] usOutput2 = new int[4];
+        public bool USOUT = true;
+        public int[] usOutput_tcp;
+        //杈撳嚭妯″紡鎺у埗
+        bool IsSignleOutput = false;
+
+        //鏂规閰嶇疆鍙傛暟
+        public string json;
+        public ResultJudge.JudgmentConfiguration config = new ResultJudge.JudgmentConfiguration();
+
+        //ModBus蹇冭烦瀹氭椂鍣�
+        private System.Threading.Timer heartbeatTimer;
+        private int heartbeatInterval = 30000; // 30绉�
+
+        //Modbus閲嶈繛鍙傛暟
+        private int _reconnectAttempts = 0;//閲嶈繛灏濊瘯娆℃暟
+        private const int MAX_RECONNECT_ATTEMPTS = 5; //鏈�澶ч噸杩炲皾璇曟鏁�
+        private bool _isReconnecting = false;//鏄惁姝e湪閲嶈繛
+        private System.Threading.Timer _reconnectTimer;//閲嶈繛瀹氭椂鍣�
+        private const int RECONNECT_INTERVAL = 2000; // 閲嶈繛闂撮殧鏃堕棿(姣)
+        private string _lastIpAddress = ""; // 鏈�鍚庤繛鎺ョ殑IP鍦板潃
+        private int _lastPort = 502; // 鏈�鍚庤繛鎺ョ殑绔彛
+
+        //缁撴灉淇″彿瀹氭椂鍣�
+        private System.Timers.Timer OutputTimer;
+
+        //瀹氭湡鍒犻櫎鍥惧儚
+        private ImageCleanupService _cleanupService;
+
+        public MainWindow()
+        {
+            if (!LBProtect.ValidateFingerprint())
+            {
+                MessageBox.Show("杞欢鏈巿鏉冨湪姝ょ‖浠朵笂杩愯锛�");
+                Close();
+                return;
+            }
+            InitializeComponent();
+            DataContext = EnhancedLogViewModel.Instance;
+            // 瀹氭湡娓呭浘鏈嶅姟鍒濆鍖�
+            InitializeCleanupService();
+
+            LoadDataAsync();
+            // SDK鍒濆鍖�
+            InitSDK();
+            // 缁撴灉鏄剧ず鐣岄潰鍒濆鍖�
+            InitUI();
+            // 鐢ㄦ埛鍋忓ソ璁剧疆鍒濆鍖�
+            InitUserConfig();
+            for (int i = 0; i < outputs.Length; i++)
+            {
+                outputs[i] = false;
+            }
+            // 榛樿鍔犺浇涓婃妫�娴嬫柟妗�
+            LoadLastUsedConfiguration(true);
+            this.Closing += MainWindow_Closing;
+            // 鑾峰彇ListView涓殑ScrollViewer寮曠敤
+            // 鑾峰彇ScrollViewer寮曠敤骞朵紶閫掔粰ViewModel
+            Loaded += (sender, e) =>
+            {
+                if (FindVisualChild<ScrollViewer>(LogListView) is ScrollViewer scrollViewer)
+                {
+                    EnhancedLogViewModel.Instance.LogScrollViewer = scrollViewer;
+                }
+            };
+            this.WindowState = WindowState.Maximized;
+            Loaded += (s, e) => RefreshIpButton_Click(null, null); // 鑷姩鍔犺浇IP
+            RefreshModelList(); // 鑷姩鍔犺浇妯″瀷鍒楄〃
+            RefreshDetectionPlanList(); // 鑷姩鍔犺浇妫�娴嬫柟妗堝垪琛�
+            RefreshProjectList(); // 鑷姩鍔犺浇宸ョ▼鏂囦欢鍒楄〃
+        }
+        private async void LoadDataAsync()
+        {
+            LoadingWindow loadingWindow = new LoadingWindow();
+            loadingWindow.Show();
+            await Task.Delay(2000);
+            loadingWindow.Close();
+        }
+
+        #region 鍒濆鍖�
+        //SDK鍒濆鍖�
+        private void InitSDK()
+        {
+            try
+            {
+                long result = IDVIEWER_Init_();
+                if (result != 0)
+                {
+                    MessageBox.Show("SDK鍒濆鍖栧け璐ワ紝閿欒鐮侊細" + result);
+                }
+            }
+            catch (Exception ex)
+            {
+                Console.WriteLine(ex.Message);
+            }
+        }
+        //鐣岄潰鍒濆鍖�
+        private void InitUI()
+        {
+            cameraAliasLabels = new TextBlock[30];
+            //deviceNames = new TextBlock[30];
+            cameraAliasLabels[0] = cameraAlias0;
+            cameraAliasLabels[1] = cameraAlias1;
+            cameraAliasLabels[2] = cameraAlias2;
+            cameraAliasLabels[3] = cameraAlias3;
+            cameraAliasLabels[4] = cameraAlias4;
+            cameraAliasLabels[5] = cameraAlias5;
+            cameraAliasLabels[6] = cameraAlias6;
+            cameraAliasLabels[7] = cameraAlias7;
+            cameraAliasLabels[8] = cameraAlias8;
+            cameraAliasLabels[9] = cameraAlias9;
+            cameraAliasLabels[10] = cameraAlias10;
+            cameraAliasLabels[11] = cameraAlias11;
+            cameraAliasLabels[12] = cameraAlias12;
+            cameraAliasLabels[13] = cameraAlias13;
+            cameraAliasLabels[14] = cameraAlias14;
+            cameraAliasLabels[15] = cameraAlias15;
+            cameraAliasLabels[16] = cameraAlias16;
+            cameraAliasLabels[17] = cameraAlias17;
+            cameraAliasLabels[18] = cameraAlias18;
+            cameraAliasLabels[19] = cameraAlias19;
+            cameraAliasLabels[20] = cameraAlias20;
+            cameraAliasLabels[21] = cameraAlias21;
+            cameraAliasLabels[22] = cameraAlias22;
+            cameraAliasLabels[23] = cameraAlias23;
+            //deviceNames[0] = deviceName0;
+            //deviceNames[1] = deviceName1;
+            //deviceNames[2] = deviceName2;
+            //deviceNames[3] = deviceName3;
+            //deviceNames[4] = deviceName4;
+            //deviceNames[5] = deviceName5;
+            //deviceNames[6] = deviceName6;
+            //deviceNames[7] = deviceName7;
+            //deviceNames[8] = deviceName8;
+            //deviceNames[9] = deviceName9;
+            //deviceNames[10] = deviceName10;
+            //deviceNames[11] = deviceName11;
+            //deviceNames[12] = deviceName12;
+            //deviceNames[13] = deviceName13;
+            //deviceNames[14] = deviceName14;
+            //deviceNames[15] = deviceName15;
+            //deviceNames[16] = deviceName16;
+            //deviceNames[17] = deviceName17;
+            //deviceNames[18] = deviceName18;
+            //deviceNames[19] = deviceName19;
+            //deviceNames[20] = deviceName20;
+            //deviceNames[21] = deviceName21;
+            //deviceNames[22] = deviceName22;
+            //deviceNames[23] = deviceName23;
+        }
+        //鐢ㄦ埛閰嶇疆鍒濆鍖�
+        private void InitUserConfig()
+        {
+            DownloadData downloadData = new DownloadData();
+            downloadData.Init();
+            if (DownloadData.MemoryAlarm_main)
+            {
+                downloadData.CheckStorage();
+            }
+            IsSignleOutput = (bool)OutputCheckBox.IsChecked;
+            //TCP绔彛鍒濆鍖�
+            // 濡傛灉浠庢湭璁剧疆杩囷紝浣跨敤榛樿鍊�
+            if (string.IsNullOrEmpty(Properties.Settings.Default.DefaultPort))
+            {
+                Properties.Settings.Default.DefaultPort = "8080";
+                Properties.Settings.Default.SelectedPort = 8080;
+            }
+
+            // 纭繚绔彛鍦ㄥ悎娉曡寖鍥村唴
+            if (Properties.Settings.Default.SelectedPort < 1 ||
+                Properties.Settings.Default.SelectedPort > 65535)
+            {
+                Properties.Settings.Default.SelectedPort = 8080;
+            }
+
+            // 灏濊瘯閫変腑宸蹭繚瀛樼殑绔彛
+            foreach (ComboBoxItem item in TCPServer_PortComboBox.Items)
+            {
+                if (int.TryParse(item.Content.ToString(), out int port) &&
+                    port == Properties.Settings.Default.SelectedPort)
+                {
+                    TCPServer_PortComboBox.SelectedItem = item;
+                    return;
+                }
+            }
+
+            // 濡傛灉淇濆瓨鐨勭鍙d笉鍦ㄩ璁惧垪琛ㄤ腑锛屾樉绀哄湪缂栬緫妗�
+            TCPServer_PortComboBox.Text = Properties.Settings.Default.SelectedPort.ToString();
+        }
+        //瀹氭湡娓呭浘鏈嶅姟鍒濆鍖�
+        private void InitializeCleanupService()
+        {
+            // 浠庤缃腑鑾峰彇鍙傛暟
+            string imageDir = Properties.Settings.Default.DataSavingRoad;
+            int retentionDays = Properties.Settings.Default.DeleteImageDays;
+            bool isEnabled = Properties.Settings.Default.ImageDeleteEnabled;
+
+            if (isEnabled && !string.IsNullOrWhiteSpace(imageDir))
+            {
+                _cleanupService = new ImageCleanupService(imageDir, retentionDays);
+                _cleanupService.Start();
+            }
+        }
+        protected override void OnClosed(EventArgs e)
+        {
+            _cleanupService?.Stop();
+            ExcelResultRecorder.FlushRecords();
+            base.OnClosed(e);
+        }
+        private void MainWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e)
+        {
+            DownloadData.isOP = false; // 绐楀彛鍏抽棴鏃舵墽琛屾搷浣�
+                                       // 鍙�夛細鍙栨秷鍏抽棴锛堥�氳繃 e.Cancel = true锛�
+            deviceStatusTimer?.Dispose();
+            deviceStatusTimer = null;
+
+            // 娓呯悊Modbus鐩稿叧瀹氭椂鍣�
+            heartbeatTimer?.Dispose();
+            heartbeatTimer = null;
+            _reconnectTimer?.Dispose();
+            _reconnectTimer = null;
+
+            // 鍋滄鏃ュ織鑷姩淇濆瓨鏈嶅姟
+            EnhancedLogViewModel.Instance?.StopAutoSaveService();
+
+            DisposeDetector_CPU(detector);
+            if (devicesListHandle != IntPtr.Zero)
+            {
+                long result = IDVIEWER_UnInit_(devicesListHandle);
+            }
+            //TCP绔彛閰嶇疆
+            // 楠岃瘉褰撳墠绔彛鍊�
+            if (int.TryParse(TCPServer_PortComboBox.Text, out int port) &&
+                port >= 1 && port <= 65535)
+            {
+                Properties.Settings.Default.SelectedPort = port;
+                Properties.Settings.Default.DefaultPort = port.ToString();
+            }
+            else
+            {
+                // 鎭㈠涓洪粯璁ゅ��
+                Properties.Settings.Default.SelectedPort = 8080;
+                Properties.Settings.Default.DefaultPort = "8080";
+            }
+
+            Properties.Settings.Default.Save();
+            foreach (System.Windows.Window window in System.Windows.Application.Current.Windows.OfType<DownloadData>().ToList())
+            {
+                window.Close();
+            }
+            Process.GetCurrentProcess().Kill();
+        }
+        // 褰撹缃彉鏇存椂閲嶆柊鍒濆鍖栨湇鍔�
+        private void OnSettingsChanged(object sender, EventArgs e)
+        {
+            _cleanupService?.Stop();
+            InitializeCleanupService();
+        }
+        // 杈呭姪鏂规硶锛氭煡鎵捐瑙夋爲涓殑瀛愬厓绱�
+        private static T FindVisualChild<T>(DependencyObject obj) where T : DependencyObject
+        {
+            for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
+            {
+                DependencyObject child = VisualTreeHelper.GetChild(obj, i);
+                if (child is T result)
+                    return result;
+
+                var childResult = FindVisualChild<T>(child);
+                if (childResult != null)
+                    return childResult;
+            }
+            return null;
+        }
+
+        #endregion
+        #region 璁惧鍒锋柊涓庤繛鎺�
+        private async void Refresh_Btn_Click(object sender, RoutedEventArgs e)
+        {
+            try
+            {
+                Refresh_Btn.IsEnabled = false;
+                IsConnected = 0;
+                // 鍔犺浇鐩告満杩炴帴椤哄簭鏄犲皠琛�
+                var productManager = new ProductManager();
+                var mapping = productManager.LoadConfig();
+                bool Bl = true;
+
+                if (mapping.Count == 0)
+                {
+                    MessageBox.Show("鏄犲皠琛ㄤ负绌猴紝璇峰厛閰嶇疆椤哄簭鍜孖P", "鎻愮ず", MessageBoxButton.OK, MessageBoxImage.Warning);
+                    return;
+                }
+                LoadingWindow loadingWindow = new LoadingWindow();
+                loadingWindow.Show();
+                loadingWindow.Loading.Text = "璁惧杩炴帴涓紝璇风◢鍊�";
+
+                await Task.Run(() =>
+                {
+                    // 鍒锋柊鐩告満鍒楄〃
+                    RefreshDeviceList();
+
+                    // 鎸夌収鏄犲皠琛ㄩ『搴忚繛鎺ョ浉鏈�
+                    foreach (var item in mapping.OrderBy(x => x.Key))
+                    {
+                        int sequence = item.Key;
+                        string ip = item.Value;
+                        ConnectDeviceByIP(sequence, ip);
+                    }
+                    Bl = false;
+                });
+                await Task.Run(() =>
+                    {
+                        while (true)
+                        {
+                            if (!Bl)
+                            {
+                                this.Dispatcher.Invoke(new Action(() =>
+                            {
+                                Refresh_Btn.IsEnabled = true;
+                            }));
+                                break;
+                            }
+                        }
+                    });
+
+                loadingWindow.Close();
+                // 鍒涘缓瀹氭椂鍣紝瀹氭椂妫�娴嬭澶囪繛鎺ョ姸鎬�
+                deviceStatusTimer = new System.Threading.Timer(DeviceConnectbeatCallback, null, Timeout.Infinite, deviceStatusInterval);
+                // 鍚姩瀹氭椂鍣紝绔嬪嵆寮�濮嬪苟姣忛殧MemoryAlarmInterval姣鎵ц涓�娆�
+                deviceStatusTimer.Change(0, deviceStatusInterval);
+                GetMessage($"璁惧宸插叏閮ㄨ繛鎺ュ畬鎴怽n杩炴帴鍙版暟锛歿IsConnected}");
+            }
+            catch (Exception ex)
+            {
+                MessageBox.Show($"璇峰厛閰嶇疆鐩告満杩炴帴椤哄簭锛歿ex.Message}", "閿欒", MessageBoxButton.OK, MessageBoxImage.Error);
+            }
+        }
+        // 鍒锋柊鐩告満鍒楄〃
+        private void RefreshDeviceList()
+        {
+            try
+            {
+                this.Dispatcher.BeginInvoke(new Action(() =>
+                {
+                    DeviceListBox.Items.Clear();
+
+                }));
+                // 鑾峰彇璁惧鍒楄〃鍙ユ焺
+                devicesListHandle = IDVIEWER_DiscoveryDevices_(500);
+                Console.WriteLine($"鑾峰彇璁惧鍒楄〃鍙ユ焺");
+
+                // 鑾峰彇璁惧鎬绘暟
+                int deviceCount = (int)IDVIEWER_GetDevicesLength_(devicesListHandle);
+                Console.WriteLine($"鑾峰彇璁惧鎬绘暟锛歿deviceCount}");
+                Task.Run(() => GetMessage($"妫�娴嬪埌 {deviceCount} 鍙拌澶�"));
+
+                // 鑾峰彇鐩告満IP鍒楄〃
+                for (int i = 0; i < deviceCount; i++)
+                {
+                    IDViewerSDK.IDVIEWER_SelectIDDeviceInfo_(devicesListHandle, ref deviceInfo[i], (uint)i);
+                    string deviceIP = deviceInfo[i].cameraIP.Trim();
+
+                    // 灏嗙浉鏈烘坊鍔犲埌鐣岄潰鍒楄〃
+                    this.Dispatcher.BeginInvoke(new Action(() =>
+                    {
+                        DeviceListBox.Items.Add(deviceIP);
+
+                    }));
+
+
+                }
+
+            }
+            catch (Exception ex)
+            {
+                MessageBox.Show($"璁惧妫�娴嬪け璐ワ細{ex.Message}", "閿欒", MessageBoxButton.OK, MessageBoxImage.Error);
+            }
+        }
+
+        // 閫氳繃IP杩炴帴鐩告満
+        private void ConnectDeviceByIP(int sequence, string ip)
+        {
+            IntPtr deviceHandle = IntPtr.Zero;
+            IntPtr imagePtr = IntPtr.Zero;
+            try
+            {
+                // 鍒涘缓璁惧鍙ユ焺
+                IDVIEWER_CreateDeviceByIP_(ip, ref deviceHandle);
+                if (deviceHandle == IntPtr.Zero)
+                {
+                    MessageBox.Show($"鏈悳绱㈠埌璇ヨ澶�:{ip}", "閿欒", MessageBoxButton.OK, MessageBoxImage.Error);
+                    return;
+                }
+                // 鎵撳紑璁惧
+                IDDevice_Open(deviceHandle);
+                // 璇昏澶囧綋鍓嶅悇椤瑰弬鏁�
+                double getGain = 0.0;
+                long resultGetGain_1330 = IDDevice_GetGain_1330(deviceHandle, 0, ref getGain);
+
+                IDDeviceHarewareParams iDDeviceHarewareParams;
+                iDDeviceHarewareParams = IDDevice_GetHardWareParams(deviceHandle);
+                IDNodeParam focusingLocation1 = iDDeviceHarewareParams.exposure;
+                IDNodeParam focusingLocation2 = iDDeviceHarewareParams.gamma;
+
+                float getexposure = focusingLocation1.value;
+                float getgamma = focusingLocation2.value;
+
+                Console.WriteLine($"{sequence}鍙疯澶囧綋鍓嶆洕鍏�:{getexposure}");
+                Console.WriteLine($"{sequence}鍙疯澶囧綋鍓嶅鐩�:{getGain}");
+                Console.WriteLine($"{sequence}鍙疯澶囧綋鍓嶄冀椹�:{getgamma}");
+                Console.WriteLine($"璁惧{sequence}杩炴帴鎴愬姛");
+
+                // 妫�鏌ヨ澶囨槸鍚﹁繛鎺ユ垚鍔�
+                long isConnected = IDDevice_IsConnected(deviceHandle);
+                if (isConnected != 1)
+                {
+                    MessageBox.Show($"璁惧杩炴帴澶辫触锛歿ip}", "閿欒", MessageBoxButton.OK, MessageBoxImage.Error);
+                    this.Dispatcher.BeginInvoke(new Action(() =>
+                    {
+                        DeviceListBox.Items.Remove(ip);
+
+                    }));
+                    return;
+                }
+                // 鍒濆鍖栧浘鍍忓彞鏌�
+                long result = IDImage_Init(ref imagePtr);
+                // 瀛樺偍璁惧鍜屽浘鍍忓彞鏌�
+                _deviceHandles[sequence] = deviceHandle;
+                _imagePtr[sequence] = imagePtr;
+                this.Dispatcher.BeginInvoke(new Action(() =>
+                {
+                    cameraAliasLabels[sequence - 1].Text = sequence.ToString();
+                    //deviceNames[sequence - 1].Text = deviceInfo[sequence - 1].cameraAlias;
+                }));
+                IsConnected++;
+                // SDK瀛樺湪BUG锛岀浉鏈鸿繛鎺ュ悗鍙栫殑鍓嶅嚑寮犲浘寮傚父锛屼复鏃惰В鍐虫柟妗�
+                // 杩炴帴鍚庡彇3寮犲浘涓㈠純
+                //for (int i = 0; i <= 3; i++)
+                //{
+                //    IDDevice_CaptureImage(deviceHandle, imagePtr);
+                //}
+                Refresh_ImageParameter(deviceHandle);
+            }
+            catch (Exception ex)
+            {
+                MessageBox.Show($"杩炴帴璁惧鏃跺嚭閿欙細{ex.Message}", "閿欒", MessageBoxButton.OK, MessageBoxImage.Error);
+                this.Dispatcher.BeginInvoke(new Action(() =>
+                {
+                    DeviceListBox.Items.Remove(ip);
+
+                }));
+            }
+        }
+        static List<double> gainList = new List<double>();
+        static IDDOParamsCreate iDDOParamsCreate = new IDDOParamsCreate();
+        static IDDOParams iDDOParams = iDDOParamsCreate.create();
+        static void Refresh_ImageParameter(IntPtr device)
+        {
+            /******鑾峰彇澧炵泭******/
+            int count = 0;
+            long resultCount = IDDevice_GetGainCount(device, ref count);
+            double getAtGain = 0.0;
+            IDDevice_GetGain_1330(device, 0, ref getAtGain);
+
+            double Gain = 0.0;
+            for (int i = 0; i < count; i++)
+            {
+                IDDevice_SetGain(device, 0, i);
+                long ii = IDDevice_GetGain_1330(device, 0, ref Gain);
+                if (ii == 0)
+                {
+                    gainList.Add(Gain);
+                }
+            }
+
+            double searchValue = getAtGain;
+            // 鍦� List 涓煡鎵捐澧炵泭鍊�
+            int index = gainList.IndexOf(searchValue);
+
+            if (index >= 0)
+            {
+                IDDevice_SetGain(device, 0, index);
+            }
+
+            IDDeviceHarewareParams iDDeviceHarewareParams;
+            iDDeviceHarewareParams = IDDevice_GetHardWareParams(device);
+            IDNodeParam focusingLocation = iDDeviceHarewareParams.focusingLocation;
+            IDNodeParam focusingLocation1 = iDDeviceHarewareParams.exposure;
+            IDNodeParam focusingLocation2 = iDDeviceHarewareParams.gamma;
+
+            float maxValue = focusingLocation.maxValue;
+            float CurrentValue = focusingLocation.value;
+            float getexposure = focusingLocation1.value;
+            float getgamma = focusingLocation2.value;
+
+            //娣诲姞DO鍒版柟妗堬紝鍙渶鎵ц涓�娆°��    
+            for (int i = 0; i <= 2; i++)
+            {
+                iDDOParams.pin = (uint)i;
+                iDDOParams.status = 0;
+                iDDOParams.doModel = 0;
+                iDDOParams.durationTime = 2000;
+                iDDOParams.doSource = IDDoEventSource.EVENT_SOURCE_OFF_C;
+                long retm8 = addDOParam(device, ref iDDOParams);
+                Console.WriteLine("褰撳墠娣诲姞绗�" + i + "缁勶紝ret锛�" + retm8);
+            }
+
+            /******灏嗚幏鍙栫殑鍙傛暟璁剧疆涓�娆�******/
+            //double getexposure1 = getexposure;
+            //double getgamma1 = getgamma;
+            //int CurrentValue1 = (int)CurrentValue;
+
+            //long g1 = IDDevice_SetExposure(device, 0, getexposure1);
+            //long g3 = IDDevice_SetGamma(device, 0, getgamma1);
+            //long g4 = IDDevice_SetFocusLocation(device, 0, CurrentValue1);
+        }
+        #endregion
+        #region 璁惧淇℃伅鏄剧ず
+        private void DeviceListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
+        {
+            if (DeviceListBox.SelectedIndex != -1)
+            {
+                CameraIP.Text = deviceInfo[DeviceListBox.SelectedIndex].cameraIP.Trim();
+                CameraNetMask.Text = deviceInfo[DeviceListBox.SelectedIndex].cameraNetMask.Trim();
+                CameraGateWay.Text = deviceInfo[DeviceListBox.SelectedIndex].cameraGateWay.Trim();
+                CameraFirmwareVersion.Text = deviceInfo[DeviceListBox.SelectedIndex].cameraFirmwareVersion.Trim();
+                CameraAlias.Text = deviceInfo[DeviceListBox.SelectedIndex].cameraAlias;
+                CameraModel.Text = deviceInfo[DeviceListBox.SelectedIndex].cameraModel.Trim();
+            }
+            else { return; }
+        }
+        #endregion
+        #region 鏃ュ織鏄剧ず
+        //鏃ュ織鏄剧ず
+        private void GetMessage(string obj)
+        {
+            this.Dispatcher.BeginInvoke(new Action(() =>
+            {
+                Log.AppendText(obj + Environment.NewLine);
+                Log.ScrollToEnd();
+            }));
+        }
+        //ModBus鏃ュ織鏄剧ず
+        private void GetMessage_Modbus(string obj)
+        {
+            this.Dispatcher.BeginInvoke(new Action(() =>
+            {
+                Client_LogsTextBox.AppendText(obj + Environment.NewLine);
+                Client_LogsTextBox.ScrollToEnd();
+            }));
+        }
+        #endregion
+        //娣卞害瀛︿範妯″瀷鎺ㄧ悊妯″潡
+        private void Reasoning_AI(IntPtr detector, byte[] ImageBath, int Image_Width, int Image_Height, out int[] classIds, out int[] numBoxes, out float[] prob,
+            out float[] x1, out float[] y1, out float[] x2, out float[] y2, int sequence)
+        {
+            // 鍒濆鍖栬緭鍑哄弬鏁�
+            batchSize = 1;
+            x1 = new float[100];
+            y1 = new float[100];
+            x2 = new float[100];
+            y2 = new float[100];
+            prob = new float[100];
+            classIds = new int[100];
+            numBoxes = new int[batchSize];
+
+            try
+            {
+                // 妫�鏌� detector 鎸囬拡鏄惁鏈夋晥
+                if (detector == IntPtr.Zero)
+                {
+                    throw new ArgumentNullException(nameof(detector), "Detector pointer is null (IntPtr.Zero)");
+                }
+                // 妫�鏌� ImageBath 鏄惁涓虹┖鎴栧ぇ灏忎笉姝g‘
+                if (ImageBath == null || ImageBath.Length == 0)
+                {
+                    throw new ArgumentException("Image batch data is null or empty", nameof(ImageBath));
+                }
+                // 妫�鏌ュ浘鍍忓昂瀵告槸鍚﹀悎鐞�
+                if (Image_Width <= 0 || Image_Height <= 0)
+                {
+                    throw new ArgumentException($"Invalid image dimensions: Width={Image_Width}, Height={Image_Height}");
+                }
+                // 妫�鏌� batchSize 鏄惁鍚堢悊
+                if (batchSize <= 0)
+                {
+                    throw new InvalidOperationException($"Invalid batch size: {batchSize}");
+                }
+                // 妫�鏌ヨ緭鍑虹紦鍐插尯鏄惁瓒冲澶�
+                if (x1.Length < 100 || y1.Length < 100 || x2.Length < 100 || y2.Length < 100 || prob.Length < 100 || classIds.Length < 100)
+                {
+                    throw new InvalidOperationException("Output buffer size is too small (must be at least 100)");
+                }
+                // 璋冪敤 C++ API
+                PredictDetector_CPU(
+                    detector,
+                    ImageBath,
+                    x1, y1, x2, y2,
+                    prob,
+                    classIds,
+                    numBoxes,
+                    100,
+                    Image_Width,
+                    Image_Height,
+                    batchSize,
+                    0.25f,
+                    0.3f,
+                    1,
+                    sequence
+                );
+            }
+            catch (SEHException ex)
+            {
+                // 璁板綍璇︾粏鐨勯敊璇俊鎭�
+                Console.Error.WriteLine($"SEHException in PredictDetector_CPU: {ex.Message}");
+                Console.Error.WriteLine($"Detector: {detector}");
+                Console.Error.WriteLine($"ImageBatch Length: {ImageBath?.Length ?? 0}");
+                Console.Error.WriteLine($"Image Size: {Image_Width}x{Image_Height}");
+                Console.Error.WriteLine($"Batch Size: {batchSize}");
+
+                // 鍙互閫夋嫨閲嶆柊鎶涘嚭鎴栬繑鍥為粯璁ゅ��
+                throw new InvalidOperationException("Failed to run AI reasoning due to native code error", ex);
+            }
+            catch (Exception ex)
+            {
+                Console.Error.WriteLine($"Error in Reasoning_AI: {ex.Message}");
+                throw;
+            }
+        }
+
+
+        // 娴嬭瘯鏂规硶
+        private void Start_Detector_Btn_Click(object sender, RoutedEventArgs e)
+        {
+            string images_path = "D:\\01 LBImage\\20241010\\10_59_24_2.bmp";
+            Mat mat = Cv2.ImRead(images_path);
+            int width = mat.Width;
+            int height = mat.Height;
+            int channel = mat.Channels();
+            byte[] imgBatch = new byte[width * height * channel];
+            int batchSize = 1;
+            float[] x1 = new float[1000], y1 = new float[1000], x2 = new float[1000], y2 = new float[1000];
+            float[] prob = new float[1000];
+            int[] classIds = new int[1000];
+            int[] numBoxes = new int[batchSize];
+            Marshal.Copy(mat.Data, imgBatch, 0, imgBatch.Length);
+            PredictDetector_CPU(detector, imgBatch, x1, y1, x2, y2, prob, classIds, numBoxes, 100, width, height, batchSize, 0.25f, 0.3f, 1, 1);
+            for (int i = 0; i < batchSize; i++)
+            {
+                for (int j = 0; j < numBoxes[i]; j++)
+                {
+                    float x1Val = x1[j];
+                    float y1Val = y1[j];
+                    float x2Val = x2[j];
+                    float y2Val = y2[j];
+                    float probVal = prob[j];
+                    int classId = classIds[j];
+                }
+            }
+        }
+
+        #region ModBus閫氳璁剧疆涓庢娴嬫ā鍧�
+        #region 鍔犺浇绔彛
+        private void LoadPorts()
+        {
+            //Server_PortComboBox.ItemsSource = new[] { "8000", "8001", "8002" };
+            //Client_PortComboBox.ItemsSource = new[] { "8000", "8001", "8002" };
+            Client_PortComboBox.ItemsSource = new[] { "502" };
+        }
+        #endregion
+        #region ModBus閫氳妯″潡
+        private void Client_Connect_Click(object sender, RoutedEventArgs e)
+        {
+            try
+            {
+                if (Client_ServerIpComboBox.Text != "" && Client_PortComboBox.SelectedItem != null)
+                {
+                    string ipAddress = Client_ServerIpComboBox.Text;
+                    int port = int.Parse(Client_PortComboBox.Text);
+
+                    // 淇濆瓨杩炴帴淇℃伅鐢ㄤ簬閲嶈繛
+                    _lastIpAddress = ipAddress;
+                    _lastPort = port;
+
+                    modbusTCPClient.ModbudTCP_Connect(ipAddress, port);
+                    if (modbusTCPClient._client == null)
+                    {
+                        //MessageBox.Show("杩炴帴鍒版湇鍔″櫒澶辫触锛岃妫�鏌ヨ繛鎺ュ悗閲嶈瘯");
+                        return;
+                    }
+
+                    // 鍒濆鍖栭噸杩炲畾鏃跺櫒
+                    InitializeReconnectTimer();
+
+                    // 鍒涘缓瀹氭椂鍣紝浣滀负ModBus蹇冭烦淇″彿
+                    heartbeatTimer = new System.Threading.Timer(HeartbeatCallback, null, Timeout.Infinite, heartbeatInterval);
+                    // 鍚姩瀹氭椂鍣紝绔嬪嵆寮�濮嬪苟姣忛殧heartbeatInterval姣鎵ц涓�娆�
+                    heartbeatTimer.Change(0, heartbeatInterval);
+                    // 寮�濮嬩睛鍚鎴风瑙﹀彂淇″彿
+                    Task.Run(() => ClientListen());
+                    GetMessage_Modbus($"杩炴帴鎴愬姛 {ipAddress}:{port}\n");
+                    this.Dispatcher.BeginInvoke(new Action(() =>
+                    {
+                        LinkState.Text = "ModBus宸茶繛鎺�";
+                        LinkState.Foreground = System.Windows.Media.Brushes.LightGreen;
+                    }));
+                }
+                else
+                {
+                    MessageBox.Show("璇疯緭鍏ユ纭殑IP鍜岀鍙�");
+                    this.Dispatcher.BeginInvoke(new Action(() =>
+                    {
+                        LinkState.Text = "鏈繛鎺�";
+                        LinkState.Foreground = System.Windows.Media.Brushes.Red;
+                    }));
+                    return;
+                }
+            }
+            catch (Exception ex)
+            {
+                MessageBox.Show("鍦板潃鍜岀鍙e凡琚崰鐢�");
+                this.Dispatcher.BeginInvoke(new Action(() =>
+                {
+                    LinkState.Text = "鏈繛鎺�";
+                    LinkState.Foreground = System.Windows.Media.Brushes.Red;
+                }));
+                return;
+            }
+        }
+        //ModBus鏂紑杩炴帴
+        private void Client_Disconnect_Click(object sender, RoutedEventArgs e)
+        {
+            try
+            {
+                // 鍋滄鎵�鏈夊畾鏃跺櫒
+                heartbeatTimer?.Change(Timeout.Infinite, Timeout.Infinite);
+                _reconnectTimer?.Change(Timeout.Infinite, Timeout.Infinite);
+
+                if (modbusTCPClient._client != null && modbusTCPClient._client.Connected)
+                {
+                    modbusTCPClient._client?.Close();
+                    modbusTCPClient._client = null;
+                    GetMessage_Modbus("杩炴帴宸叉柇寮�\n");
+                    this.Dispatcher.BeginInvoke(new Action(() =>
+                    {
+                        LinkState.Text = "鏈繛鎺�";
+                        LinkState.Foreground = System.Windows.Media.Brushes.Red;
+                    }));
+                }
+
+                // 閲嶇疆閲嶈繛鐘舵��
+                _reconnectAttempts = 0;
+                _isReconnecting = false;
+            }
+            catch (Exception ex)
+            {
+                MessageBox.Show("杩炴帴鏂紑");
+                this.Dispatcher.BeginInvoke(new Action(() =>
+                {
+                    LinkState.Text = "鏈繛鎺�";
+                    LinkState.Foreground = System.Windows.Media.Brushes.Red;
+                }));
+            }
+        }
+
+        private void Client_ClearClientLogs_Click(object sender, RoutedEventArgs e)
+        {
+            Client_LogsTextBox.Clear();
+        }
+        #endregion
+        #region 鍥惧儚閲囬泦涓庡鐞嗘ā鍧�
+        //鑾峰彇鍥惧儚骞跺鐞�
+        private void GetImage()
+        {
+            this.Dispatcher.BeginInvoke(new Action(() =>
+            {
+                DetectState.Text = "姝e湪妫�娴嬩腑銆傘�傘��";
+                DetectState.Foreground = System.Windows.Media.Brushes.LightGreen;
+            }));
+            //璁℃椂鍣ㄥ惎鍔�
+            stopwatch.Reset();
+            stopwatch.Start();
+            Console.WriteLine($"璁℃椂鍣ㄥ惎鍔�!");
+            //鍔犺浇涓婃瑙e喅鏂规
+            bool isL = LoadLastUsedConfiguration(false);
+            if (!isL)
+            {
+                stopwatch.Stop();
+                long F_elapsedMilliseconds = stopwatch.ElapsedMilliseconds;
+                Console.WriteLine($"绯荤粺鍝嶅簲鏃堕棿涓猴細{F_elapsedMilliseconds}ms");
+                this.Dispatcher.BeginInvoke(new Action(() =>
+                {
+                    DetectState.Text = "鏈湪妫�娴�";
+                    DetectState.Foreground = System.Windows.Media.Brushes.Red;
+                }));
+                return;
+            }
+            for (int i = 0; i < DeviceListBox.Items.Count; i++)
+            {
+                //閲囬泦鍥惧儚
+                GetIDDevice_CaptureImage(i + 1);
+            }
+            for (int i = 0; i < DeviceListBox.Items.Count; i++)
+            {
+                //澶勭悊鍥惧儚
+                Reasoning_Image(i + 1);
+            }
+            stopwatch.Stop();
+            long elapsedMilliseconds = stopwatch.ElapsedMilliseconds;
+            Console.WriteLine($"绯荤粺鍝嶅簲鏃堕棿涓猴細{elapsedMilliseconds}ms");
+            EnhancedLogViewModel.Instance.AddLog($"绯荤粺鍝嶅簲鏃堕棿涓猴細{elapsedMilliseconds}ms");
+            this.Dispatcher.BeginInvoke(new Action(() =>
+            {
+                DetectState.Text = "鏈湪妫�娴�";
+                DetectState.Foreground = System.Windows.Media.Brushes.Red;
+            }));
+            //NG鍥惧儚寮圭獥鏄剧ず涓庝繚瀛�
+            if (Image_NG.Count != 0)
+            {
+                Task.Run(() =>
+                {
+                    List<string> Image_NG_Save = new List<string>(Image_NG);
+
+                    // NG鍥惧儚寮圭獥鏄剧ず
+                    OnDetectionCompleted(Image_NG);
+                    // NG鍥惧儚鑷姩淇濆瓨
+                    int savedCount = AutoSaveNGImages(Image_NG_Save);
+                    EnhancedLogViewModel.Instance.AddLog($"鎴愬姛淇濆瓨浜� {savedCount} 寮燦G鍥剧墖");
+                    Image_NG_Save.Clear();
+                });
+
+            }
+
+            //妫�娴嬬粨鏋滈�氳繃ModBus瀛樺叆瀵勫瓨鍣�
+            try
+            {
+                if (modbusTCPClient._client != null)
+                {
+                    if (!IsSignleOutput)
+                    {
+                        // 灏嗕簩杩涘埗鏁扮粍杞崲涓簎short
+                        ushort value = BinaryToUshort_MSBFirst(usOutput);//1鍙�-16鍙风浉鏈�
+                        ushort value2 = BinaryToUshort_MSBFirst(usOutput2);//17-20鍙风浉鏈�
+                        // 灏唘short瀛樺偍鍦╱short鏁扮粍涓�
+                        ushort[] test = new ushort[] { value };
+                        ushort[] test2 = new ushort[] { value2 };
+                        modbusTCPClient.MultipleRegistersWrite(3, test);//1鍙�-16鍙风浉鏈�
+                        modbusTCPClient.MultipleRegistersWrite(4, test2);//17-20鍙风浉鏈�
+                        EnhancedLogViewModel.Instance.AddLog($"妫�娴嬬粨鏋滀繚鎸亄Hold_Time}绉�");
+                        if (double.TryParse(Hold_Time, out double interval))
+                        {
+                            OutputTimer = new System.Timers.Timer(interval * 1000);
+                        }
+                        else
+                        {
+                            MessageBox.Show("淇濇寔鏃堕棿鏍煎紡閿欒锛岃妫�鏌ラ厤缃�", "閿欒", MessageBoxButton.OK, MessageBoxImage.Error);
+                            return;
+                        }
+
+                        OutputTimer.Elapsed += OnTimedEvent;
+                        OutputTimer.AutoReset = false; // 璁剧疆涓篺alse琛ㄧず鍙Е鍙戜竴娆�
+                        OutputTimer.Start();
+                    }
+                    else
+                    {
+                        if (USOUT)
+                        {
+                            modbusTCPClient.MultipleRegistersWrite(3, new ushort[] { 1 });
+                            EnhancedLogViewModel.Instance.AddLog($"妫�娴嬬粨鏋滀繚鎸�5绉�");
+                            OutputTimer = new System.Timers.Timer(5000);
+                            OutputTimer.Elapsed += OnTimedEvent;
+                            OutputTimer.AutoReset = false; // 璁剧疆涓篺alse琛ㄧず鍙Е鍙戜竴娆�
+                            OutputTimer.Start();
+                        }
+                        else
+                        {
+                            modbusTCPClient.MultipleRegistersWrite(3, new ushort[] { 0 });
+                        }
+
+                    }
+                }
+                else if (TcpServerManager._isRunning)
+                {
+                    //usOutput_tcp
+                }
+                else
+                {
+                    // 鑾峰彇褰撳墠鏃ユ湡
+                    DateTime currentDate = DateTime.Now;
+                    // 鏍煎紡鍖栨椂闂翠负 "HHmmss"
+                    string timeFileName = currentDate.ToString("HH:mm:ss");
+                    this.Dispatcher.BeginInvoke(new Action(() =>
+                    {
+                        LinkState.Text = "鏈繛鎺�";
+                        LinkState.Foreground = System.Windows.Media.Brushes.Red;
+                    }));
+                    //MessageBox.Show($"ModBus鏈繛鎺�", "閿欒", MessageBoxButton.OK, MessageBoxImage.Error);
+                    GetMessage_Modbus($"{timeFileName} ModBus鏈繛鎺�");
+                }
+                USOUT = true;
+            }
+            catch (NullReferenceException ex)
+            {
+                MessageBox.Show($"ModBus鏈繛鎺ワ細{ex.Message}", "閿欒", MessageBoxButton.OK, MessageBoxImage.Error);
+            }
+            USOUT = true;
+        }
+        private ImageDisplayWindow _imageDisplayWindow;
+
+        //NG鍥惧儚寮圭獥鏄剧ず
+        private void OnDetectionCompleted(List<string> imagePath)
+        {
+            if (imagePath.Count != 0)
+            {
+                // 浣跨敤Dispatcher纭繚UI绾跨▼鎿嶄綔
+                Dispatcher.Invoke(() =>
+                {
+                    // 妫�鏌ョ獥鍙f槸鍚﹀凡瀛樺湪
+                    if (_imageDisplayWindow == null || !_imageDisplayWindow.IsLoaded)
+                    {
+                        _imageDisplayWindow = new ImageDisplayWindow();
+                        _imageDisplayWindow.Closed += (s, e) => { _imageDisplayWindow = null; };
+                        _imageDisplayWindow.Show();
+                        _imageDisplayWindow.Topmost = true;
+                    }
+
+                    // 娣诲姞鍥剧墖鍒版煡鐪嬪櫒
+                    _imageDisplayWindow.AddImage(imagePath);
+                });
+                Image_NG.Clear();
+            }
+        }
+        //鍥惧儚澶勭悊
+        private void Reasoning_Image(int Sequence)
+        {
+            IntPtr deviceHandle = _deviceHandles[Sequence];
+            IntPtr imagePtr = _imagePtr[Sequence];
+
+            int[] classIds;     //鐩爣鐗╃被鍒�   
+            int[] numBoxes;     //鐩爣鐗╂暟閲�
+            float[] prob;       //鐩爣鐗╁緱鍒�
+            float[] x1 = new float[100], y1 = new float[100], x2 = new float[100], y2 = new float[100];
+            if (imagePtr == IntPtr.Zero)
+            {
+                GetMessage($"璁惧{Sequence}杩炴帴宸叉柇寮�");
+                EnhancedLogViewModel.Instance.AddLog($"璁惧{Sequence}杩炴帴宸叉柇寮�", "ERROR");
+                return;
+            }
+            long Image_Width = IDImage_Width(imagePtr);
+            long Image_Height = IDImage_Height(imagePtr);
+            long Image_Channels = IDImage_Channels(imagePtr);
+            long dataLength = Image_Width * Image_Height * Image_Channels;
+            byte[] Imagedata = new byte[dataLength];
+            byte[] bytes = new byte[Image_Width * Image_Height * 3];
+            IntPtr Image_ImageData = IDImage_ImageData(imagePtr);
+
+            if (imagePtr == IntPtr.Zero)
+            {
+                MessageBox.Show("鍥惧儚鍙ユ焺鏃犳晥");
+            }
+            if (dataLength != 0)
+            {
+                Console.WriteLine($"鑾峰彇鏃ユ湡");
+                // 鑾峰彇褰撳墠鏃ユ湡
+                DateTime currentDate = DateTime.Now;
+
+                // 鏍煎紡鍖栨棩鏈熶负 "yyyyMMdd"
+                string datePath = currentDate.ToString("yyyyMMdd");
+
+                // 鏍煎紡鍖栨椂闂翠负 "HHmmss"
+                string timeFileName = currentDate.ToString("HH_mm_ss");
+
+                // 鏋勫缓瀹屾暣璺緞
+                string folderPath = $@"{DownloadData.ImageSavingPath}\{datePath}";
+                string filePath = Path.Combine(folderPath, $"{timeFileName + "_" + Sequence + DownloadData.ImageFormat_main}");
+
+                // 妫�鏌ユ枃浠跺す鏄惁瀛樺湪锛屽鏋滀笉瀛樺湪鍒欏垱寤�
+                if (!Directory.Exists(folderPath))
+                {
+                    Directory.CreateDirectory(folderPath);
+                }
+                Console.WriteLine($"鍥惧儚鍙ユ焺杞崲涓哄瓧鑺傛暟鎹�");
+                Marshal.Copy(Image_ImageData, Imagedata, 0, (int)dataLength);           //鍥惧儚鍙ユ焺杞崲涓哄瓧鑺傛暟鎹�
+                ConvertSingletoThreeChannels(detector, Imagedata, (int)Image_Width, (int)Image_Height, bytes);
+                //鍘熷浘淇濆瓨鑷虫湰鍦�
+                if (DownloadData.ImageSave)
+                {
+                    IDImage_SaveImage(imagePtr, filePath, DownloadData.ImageCompressionRatio_main);
+                    EnhancedLogViewModel.Instance.AddLog($"璁惧{Sequence}鍥惧儚宸蹭繚瀛樿嚦{filePath}");
+                }
+                EnhancedLogViewModel.Instance.AddLog($"{DateTime.Now:HH:mm:ss:fff}锛歿Sequence}鍙疯澶囧浘鍍忛澶勭悊瀹屾垚锛屽紑濮嬭繘琛岀畻娉曟帹鐞�");
+                //娣卞害瀛︿範鎺ㄧ悊妯″瀷
+                Reasoning_AI(detector, bytes, (int)Image_Width, (int)Image_Height, out classIds, out numBoxes, out prob, out x1, out y1, out x2, out y2, Sequence);
+                EnhancedLogViewModel.Instance.AddLog($"{DateTime.Now:HH:mm:ss:fff}锛歿Sequence}鍙疯澶囩畻娉曟帹鐞嗗畬鎴愶紝寮�濮嬭繘琛岀粨鏋滃垽鏂�");
+                //缁撴灉鍒ゆ柇
+                switch (Sequence)
+                {
+                    case 1:
+                        int isPass1 = config.JudgeDetectionResult(Sequence, numBoxes, classIds, prob);
+                        usOutput[Sequence - 1] = isPass1;
+                        if (TcpServerManager._isRunning && usOutput_tcp != null) usOutput_tcp[Sequence - 1] = isPass1;
+
+                        if (isPass1 == 1)
+                        {
+                            this.Dispatcher.BeginInvoke(new Action(() =>
+                            {
+                                Finall_result0.Content = "OK";
+                                finall_result0.Background = System.Windows.Media.Brushes.Green;
+                            }));
+                            Console.WriteLine($"鐐逛綅 {Sequence} 妫�娴嬮�氳繃");
+                            EnhancedLogViewModel.Instance.AddLog($"{DateTime.Now:HH:mm:ss:fff}锛氱偣浣� {Sequence} 妫�娴嬮�氳繃");
+                            Task.Run(() =>
+                            {
+                                // 璁板綍鍒癊xcel锛堟壒閲忓啓鍏ワ級
+                                ExcelResultRecorder.RecordDetectionResult(Sequence, "OK");
+                            });
+                        }
+                        else
+                        {
+                            USOUT = false;
+                            this.Dispatcher.BeginInvoke(new Action(() =>
+                            {
+                                Finall_result0.Content = "NG";
+                                finall_result0.Background = System.Windows.Media.Brushes.Red;
+                            }));
+                            Console.WriteLine($"鐐逛綅 {Sequence} 妫�娴嬩笉閫氳繃");
+                            EnhancedLogViewModel.Instance.AddLog($"{DateTime.Now:HH:mm:ss:fff}锛氱偣浣� {Sequence} 妫�娴嬩笉閫氳繃", "ERROR");
+                            Image_NG.Add($".\\vino_res\\result_{Sequence}.jpg");
+                            Task.Run(() =>
+                            {
+                                // 璁板綍鍒癊xcel锛堟壒閲忓啓鍏ワ級
+                                ExcelResultRecorder.RecordDetectionResult(Sequence, "NG");
+                            });
+                        }
+                        break;
+                    case 2:
+                        int isPass2 = config.JudgeDetectionResult(Sequence, numBoxes, classIds, prob);
+                        usOutput[Sequence - 1] = isPass2;
+                        if (TcpServerManager._isRunning && usOutput_tcp != null) usOutput_tcp[Sequence - 1] = isPass2;
+                        if (isPass2 == 1)
+                        {
+                            this.Dispatcher.BeginInvoke(new Action(() =>
+                            {
+                                Finall_result1.Content = "OK";
+                                finall_result1.Background = System.Windows.Media.Brushes.Green;
+                            }));
+                            Console.WriteLine($"鐐逛綅 {Sequence} 妫�娴嬮�氳繃");
+                            EnhancedLogViewModel.Instance.AddLog($"{DateTime.Now:HH:mm:ss:fff}锛氱偣浣� {Sequence} 妫�娴嬮�氳繃");
+                            Task.Run(() =>
+                            {
+                                // 璁板綍鍒癊xcel锛堟壒閲忓啓鍏ワ級
+                                ExcelResultRecorder.RecordDetectionResult(Sequence, "OK");
+                            });
+                        }
+                        else
+                        {
+                            USOUT = false;
+                            this.Dispatcher.BeginInvoke(new Action(() =>
+                            {
+                                Finall_result1.Content = "NG";
+                                finall_result1.Background = System.Windows.Media.Brushes.Red;
+                            }));
+                            Console.WriteLine($"鐐逛綅 {Sequence} 妫�娴嬩笉閫氳繃");
+                            EnhancedLogViewModel.Instance.AddLog($"{DateTime.Now:HH:mm:ss:fff}锛氱偣浣� {Sequence} 妫�娴嬩笉閫氳繃", "ERROR");
+                            Image_NG.Add($".\\vino_res\\result_{Sequence}.jpg");
+                            Task.Run(() =>
+                            {
+                                // 璁板綍鍒癊xcel锛堟壒閲忓啓鍏ワ級
+                                ExcelResultRecorder.RecordDetectionResult(Sequence, "NG");
+                            });
+                        }
+                        break;
+                    case 3:
+                        int isPass3 = config.JudgeDetectionResult(Sequence, numBoxes, classIds, prob);
+                        usOutput[Sequence - 1] = isPass3;
+                        if (TcpServerManager._isRunning && usOutput_tcp != null) usOutput_tcp[Sequence - 1] = isPass3;
+                        if (isPass3 == 1)
+                        {
+                            this.Dispatcher.BeginInvoke(new Action(() =>
+                            {
+                                Finall_result2.Content = "OK";
+                                finall_result2.Background = System.Windows.Media.Brushes.Green;
+                            }));
+                            Console.WriteLine($"鐐逛綅 {Sequence} 妫�娴嬮�氳繃");
+                            EnhancedLogViewModel.Instance.AddLog($"{DateTime.Now:HH:mm:ss:fff}锛氱偣浣� {Sequence} 妫�娴嬮�氳繃");
+                            Task.Run(() =>
+                            {
+                                // 璁板綍鍒癊xcel锛堟壒閲忓啓鍏ワ級
+                                ExcelResultRecorder.RecordDetectionResult(Sequence, "OK");
+                            });
+                        }
+                        else
+                        {
+                            USOUT = false;
+                            this.Dispatcher.BeginInvoke(new Action(() =>
+                            {
+                                Finall_result2.Content = "NG";
+                                finall_result2.Background = System.Windows.Media.Brushes.Red;
+                            }));
+                            Console.WriteLine($"鐐逛綅 {Sequence} 妫�娴嬩笉閫氳繃");
+                            EnhancedLogViewModel.Instance.AddLog($"{DateTime.Now:HH:mm:ss:fff}锛氱偣浣� {Sequence} 妫�娴嬩笉閫氳繃", "ERROR");
+                            Image_NG.Add($".\\vino_res\\result_{Sequence}.jpg");
+                            Task.Run(() =>
+                            {
+                                // 璁板綍鍒癊xcel锛堟壒閲忓啓鍏ワ級
+                                ExcelResultRecorder.RecordDetectionResult(Sequence, "NG");
+                            });
+                        }
+                        break;
+                    case 4:
+                        int isPass4 = config.JudgeDetectionResult(Sequence, numBoxes, classIds, prob);
+                        usOutput[Sequence - 1] = isPass4;
+                        if (TcpServerManager._isRunning && usOutput_tcp != null) usOutput_tcp[Sequence - 1] = isPass4;
+                        if (isPass4 == 1)
+                        {
+                            this.Dispatcher.BeginInvoke(new Action(() =>
+                            {
+                                Finall_result3.Content = "OK";
+                                finall_result3.Background = System.Windows.Media.Brushes.Green;
+                            }));
+                            Console.WriteLine($"鐐逛綅 {Sequence} 妫�娴嬮�氳繃");
+                            EnhancedLogViewModel.Instance.AddLog($"{DateTime.Now:HH:mm:ss:fff}锛氱偣浣� {Sequence} 妫�娴嬮�氳繃");
+                            Task.Run(() =>
+                            {
+                                // 璁板綍鍒癊xcel锛堟壒閲忓啓鍏ワ級
+                                ExcelResultRecorder.RecordDetectionResult(Sequence, "OK");
+                            });
+                        }
+                        else
+                        {
+                            USOUT = false;
+                            this.Dispatcher.BeginInvoke(new Action(() =>
+                            {
+                                Finall_result3.Content = "NG";
+                                finall_result3.Background = System.Windows.Media.Brushes.Red;
+                            }));
+                            Console.WriteLine($"鐐逛綅 {Sequence} 妫�娴嬩笉閫氳繃");
+                            EnhancedLogViewModel.Instance.AddLog($"{DateTime.Now:HH:mm:ss:fff}锛氱偣浣� {Sequence} 妫�娴嬩笉閫氳繃", "ERROR");
+                            Image_NG.Add($".\\vino_res\\result_{Sequence}.jpg");
+                            Task.Run(() =>
+                            {
+                                // 璁板綍鍒癊xcel锛堟壒閲忓啓鍏ワ級
+                                ExcelResultRecorder.RecordDetectionResult(Sequence, "NG");
+                            });
+                        }
+                        break;
+                    case 5:
+                        int isPass5 = config.JudgeDetectionResult(Sequence, numBoxes, classIds, prob);
+                        usOutput[Sequence - 1] = isPass5;
+                        if (TcpServerManager._isRunning && usOutput_tcp != null) usOutput_tcp[Sequence - 1] = isPass5;
+                        if (isPass5 == 1)
+                        {
+                            this.Dispatcher.BeginInvoke(new Action(() =>
+                            {
+                                Finall_result4.Content = "OK";
+                                finall_result4.Background = System.Windows.Media.Brushes.Green;
+                            }));
+                            Console.WriteLine($"鐐逛綅 {Sequence} 妫�娴嬮�氳繃");
+                            EnhancedLogViewModel.Instance.AddLog($"{DateTime.Now:HH:mm:ss:fff}锛氱偣浣� {Sequence} 妫�娴嬮�氳繃");
+                            Task.Run(() =>
+                            {
+                                // 璁板綍鍒癊xcel锛堟壒閲忓啓鍏ワ級
+                                ExcelResultRecorder.RecordDetectionResult(Sequence, "OK");
+                            });
+                        }
+                        else
+                        {
+                            USOUT = false;
+                            this.Dispatcher.BeginInvoke(new Action(() =>
+                            {
+                                Finall_result4.Content = "NG";
+                                finall_result4.Background = System.Windows.Media.Brushes.Red;
+                            }));
+                            Console.WriteLine($"鐐逛綅 {Sequence} 妫�娴嬩笉閫氳繃");
+                            EnhancedLogViewModel.Instance.AddLog($"{DateTime.Now:HH:mm:ss:fff}锛氱偣浣� {Sequence} 妫�娴嬩笉閫氳繃", "ERROR");
+                            Image_NG.Add($".\\vino_res\\result_{Sequence}.jpg");
+                            Task.Run(() =>
+                            {
+                                // 璁板綍鍒癊xcel锛堟壒閲忓啓鍏ワ級
+                                ExcelResultRecorder.RecordDetectionResult(Sequence, "NG");
+                            });
+                        }
+                        break;
+                    case 6:
+                        int isPass6 = config.JudgeDetectionResult(Sequence, numBoxes, classIds, prob);
+                        usOutput[Sequence - 1] = isPass6;
+                        if (TcpServerManager._isRunning && usOutput_tcp != null) usOutput_tcp[Sequence - 1] = isPass6;
+                        if (isPass6 == 1)
+                        {
+                            this.Dispatcher.BeginInvoke(new Action(() =>
+                            {
+                                Finall_result5.Content = "OK";
+                                finall_result5.Background = System.Windows.Media.Brushes.Green;
+                            }));
+                            Console.WriteLine($"鐐逛綅 {Sequence} 妫�娴嬮�氳繃");
+                            EnhancedLogViewModel.Instance.AddLog($"{DateTime.Now:HH:mm:ss:fff}锛氱偣浣� {Sequence} 妫�娴嬮�氳繃");
+                            Task.Run(() =>
+                            {
+                                // 璁板綍鍒癊xcel锛堟壒閲忓啓鍏ワ級
+                                ExcelResultRecorder.RecordDetectionResult(Sequence, "OK");
+                            });
+                            //Image_NG.Add($".\\vino_res\\result_{Sequence}.jpg");
+                        }
+                        else
+                        {
+                            USOUT = false;
+                            this.Dispatcher.BeginInvoke(new Action(() =>
+                            {
+                                Finall_result5.Content = "NG";
+                                finall_result5.Background = System.Windows.Media.Brushes.Red;
+                            }));
+                            Console.WriteLine($"鐐逛綅 {Sequence} 妫�娴嬩笉閫氳繃");
+                            EnhancedLogViewModel.Instance.AddLog($"{DateTime.Now:HH:mm:ss:fff}锛氱偣浣� {Sequence} 妫�娴嬩笉閫氳繃", "ERROR");
+                            Image_NG.Add($".\\vino_res\\result_{Sequence}.jpg");
+                            Task.Run(() =>
+                            {
+                                // 璁板綍鍒癊xcel锛堟壒閲忓啓鍏ワ級
+                                ExcelResultRecorder.RecordDetectionResult(Sequence, "NG");
+                            });
+                        }
+                        break;
+                    case 7:
+                        int isPass7 = config.JudgeDetectionResult(Sequence, numBoxes, classIds, prob);
+                        usOutput[Sequence - 1] = isPass7;
+                        if (TcpServerManager._isRunning && usOutput_tcp != null) usOutput_tcp[Sequence - 1] = isPass7;
+                        if (isPass7 == 1)
+                        {
+                            this.Dispatcher.BeginInvoke(new Action(() =>
+                            {
+                                Finall_result6.Content = "OK";
+                                finall_result6.Background = System.Windows.Media.Brushes.Green;
+                            }));
+                            Console.WriteLine($"鐐逛綅 {Sequence} 妫�娴嬮�氳繃");
+                            EnhancedLogViewModel.Instance.AddLog($"{DateTime.Now:HH:mm:ss:fff}锛氱偣浣� {Sequence} 妫�娴嬮�氳繃");
+                            Task.Run(() =>
+                            {
+                                // 璁板綍鍒癊xcel锛堟壒閲忓啓鍏ワ級
+                                ExcelResultRecorder.RecordDetectionResult(Sequence, "OK");
+                            });
+                            //Image_NG.Add($".\\vino_res\\result_{Sequence}.jpg");
+                        }
+                        else
+                        {
+                            USOUT = false;
+                            this.Dispatcher.BeginInvoke(new Action(() =>
+                            {
+                                Finall_result6.Content = "NG";
+                                finall_result6.Background = System.Windows.Media.Brushes.Red;
+                            }));
+                            Console.WriteLine($"鐐逛綅 {Sequence} 妫�娴嬩笉閫氳繃");
+                            EnhancedLogViewModel.Instance.AddLog($"{DateTime.Now:HH:mm:ss:fff}锛氱偣浣� {Sequence} 妫�娴嬩笉閫氳繃", "ERROR");
+                            Image_NG.Add($".\\vino_res\\result_{Sequence}.jpg");
+                            Task.Run(() =>
+                            {
+                                // 璁板綍鍒癊xcel锛堟壒閲忓啓鍏ワ級
+                                ExcelResultRecorder.RecordDetectionResult(Sequence, "NG");
+                            });
+                        }
+                        break;
+                    case 8:
+                        int isPass8 = config.JudgeDetectionResult(Sequence, numBoxes, classIds, prob);
+                        usOutput[Sequence - 1] = isPass8;
+                        if (TcpServerManager._isRunning && usOutput_tcp != null) usOutput_tcp[Sequence - 1] = isPass8;
+                        if (isPass8 == 1)
+                        {
+                            this.Dispatcher.BeginInvoke(new Action(() =>
+                            {
+                                Finall_result7.Content = "OK";
+                                finall_result7.Background = System.Windows.Media.Brushes.Green;
+                            }));
+                            Console.WriteLine($"鐐逛綅 {Sequence} 妫�娴嬮�氳繃");
+                            EnhancedLogViewModel.Instance.AddLog($"{DateTime.Now:HH:mm:ss:fff}锛氱偣浣� {Sequence} 妫�娴嬮�氳繃");
+                            Task.Run(() =>
+                            {
+                                // 璁板綍鍒癊xcel锛堟壒閲忓啓鍏ワ級
+                                ExcelResultRecorder.RecordDetectionResult(Sequence, "OK");
+                            });
+                            //Image_NG.Add($".\\vino_res\\result_{Sequence}.jpg");
+                        }
+                        else
+                        {
+                            USOUT = false;
+                            this.Dispatcher.BeginInvoke(new Action(() =>
+                            {
+                                Finall_result7.Content = "NG";
+                                finall_result7.Background = System.Windows.Media.Brushes.Red;
+                            }));
+                            Console.WriteLine($"鐐逛綅 {Sequence} 妫�娴嬩笉閫氳繃");
+                            EnhancedLogViewModel.Instance.AddLog($"{DateTime.Now:HH:mm:ss:fff}锛氱偣浣� {Sequence} 妫�娴嬩笉閫氳繃", "ERROR");
+                            Image_NG.Add($".\\vino_res\\result_{Sequence}.jpg");
+                            Task.Run(() =>
+                            {
+                                // 璁板綍鍒癊xcel锛堟壒閲忓啓鍏ワ級
+                                ExcelResultRecorder.RecordDetectionResult(Sequence, "NG");
+                            });
+                        }
+                        break;
+                    case 9:
+                        int isPass9 = config.JudgeDetectionResult(Sequence, numBoxes, classIds, prob);
+                        usOutput[Sequence - 1] = isPass9;
+                        if (TcpServerManager._isRunning && usOutput_tcp != null) usOutput_tcp[Sequence - 1] = isPass9;
+                        if (isPass9 == 1)
+                        {
+                            this.Dispatcher.BeginInvoke(new Action(() =>
+                            {
+                                Finall_result8.Content = "OK";
+                                finall_result8.Background = System.Windows.Media.Brushes.Green;
+                            }));
+                            Console.WriteLine($"鐐逛綅 {Sequence} 妫�娴嬮�氳繃");
+                            EnhancedLogViewModel.Instance.AddLog($"{DateTime.Now:HH:mm:ss:fff}锛氱偣浣� {Sequence} 妫�娴嬮�氳繃");
+                            Task.Run(() =>
+                            {
+                                // 璁板綍鍒癊xcel锛堟壒閲忓啓鍏ワ級
+                                ExcelResultRecorder.RecordDetectionResult(Sequence, "OK");
+                            });
+                            //Image_NG.Add($".\\vino_res\\result_{Sequence}.jpg");
+                        }
+                        else
+                        {
+                            USOUT = false;
+                            this.Dispatcher.BeginInvoke(new Action(() =>
+                            {
+                                Finall_result8.Content = "NG";
+                                finall_result8.Background = System.Windows.Media.Brushes.Red;
+                            }));
+                            Console.WriteLine($"鐐逛綅 {Sequence} 妫�娴嬩笉閫氳繃");
+                            EnhancedLogViewModel.Instance.AddLog($"{DateTime.Now:HH:mm:ss:fff}锛氱偣浣� {Sequence} 妫�娴嬩笉閫氳繃", "ERROR");
+                            Image_NG.Add($".\\vino_res\\result_{Sequence}.jpg");
+                            Task.Run(() =>
+                            {
+                                // 璁板綍鍒癊xcel锛堟壒閲忓啓鍏ワ級
+                                ExcelResultRecorder.RecordDetectionResult(Sequence, "NG");
+                            });
+                        }
+                        break;
+                    case 10:
+                        int isPass10 = config.JudgeDetectionResult(Sequence, numBoxes, classIds, prob);
+                        usOutput[Sequence - 1] = isPass10;
+                        if (TcpServerManager._isRunning && usOutput_tcp != null) usOutput_tcp[Sequence - 1] = isPass10;
+                        if (isPass10 == 1)
+                        {
+                            this.Dispatcher.BeginInvoke(new Action(() =>
+                            {
+                                Finall_result9.Content = "OK";
+                                finall_result9.Background = System.Windows.Media.Brushes.Green;
+                            }));
+                            Console.WriteLine($"鐐逛綅 {Sequence} 妫�娴嬮�氳繃");
+                            EnhancedLogViewModel.Instance.AddLog($"{DateTime.Now:HH:mm:ss:fff}锛氱偣浣� {Sequence} 妫�娴嬮�氳繃");
+                            Task.Run(() =>
+                            {
+                                // 璁板綍鍒癊xcel锛堟壒閲忓啓鍏ワ級
+                                ExcelResultRecorder.RecordDetectionResult(Sequence, "OK");
+                            });
+                            //Image_NG.Add($".\\vino_res\\result_{Sequence}.jpg");
+                        }
+                        else
+                        {
+                            USOUT = false;
+                            this.Dispatcher.BeginInvoke(new Action(() =>
+                            {
+                                Finall_result9.Content = "NG";
+                                finall_result9.Background = System.Windows.Media.Brushes.Red;
+                            }));
+                            Console.WriteLine($"鐐逛綅 {Sequence} 妫�娴嬩笉閫氳繃");
+                            EnhancedLogViewModel.Instance.AddLog($"{DateTime.Now:HH:mm:ss:fff}锛氱偣浣� {Sequence} 妫�娴嬩笉閫氳繃", "ERROR");
+                            Image_NG.Add($".\\vino_res\\result_{Sequence}.jpg");
+                            Task.Run(() =>
+                            {
+                                // 璁板綍鍒癊xcel锛堟壒閲忓啓鍏ワ級
+                                ExcelResultRecorder.RecordDetectionResult(Sequence, "NG");
+                            });
+                        }
+                        break;
+                    case 11:
+                        int isPass11 = config.JudgeDetectionResult(Sequence, numBoxes, classIds, prob);
+                        usOutput[Sequence - 1] = isPass11;
+                        if (TcpServerManager._isRunning && usOutput_tcp != null) usOutput_tcp[Sequence - 1] = isPass11;
+                        if (isPass11 == 1)
+                        {
+                            this.Dispatcher.BeginInvoke(new Action(() =>
+                            {
+                                Finall_result10.Content = "OK";
+                                finall_result10.Background = System.Windows.Media.Brushes.Green;
+                            }));
+                            Console.WriteLine($"鐐逛綅 {Sequence} 妫�娴嬮�氳繃");
+                            EnhancedLogViewModel.Instance.AddLog($"{DateTime.Now:HH:mm:ss:fff}锛氱偣浣� {Sequence} 妫�娴嬮�氳繃");
+                            Task.Run(() =>
+                            {
+                                // 璁板綍鍒癊xcel锛堟壒閲忓啓鍏ワ級
+                                ExcelResultRecorder.RecordDetectionResult(Sequence, "OK");
+                            });
+                            //Image_NG.Add($".\\vino_res\\result_{Sequence}.jpg");
+                        }
+                        else
+                        {
+                            USOUT = false;
+                            this.Dispatcher.BeginInvoke(new Action(() =>
+                            {
+                                Finall_result10.Content = "NG";
+                                finall_result10.Background = System.Windows.Media.Brushes.Red;
+                            }));
+                            Console.WriteLine($"鐐逛綅 {Sequence} 妫�娴嬩笉閫氳繃");
+                            EnhancedLogViewModel.Instance.AddLog($"{DateTime.Now:HH:mm:ss:fff}锛氱偣浣� {Sequence} 妫�娴嬩笉閫氳繃", "ERROR");
+                            Image_NG.Add($".\\vino_res\\result_{Sequence}.jpg");
+                            Task.Run(() =>
+                            {
+                                // 璁板綍鍒癊xcel锛堟壒閲忓啓鍏ワ級
+                                ExcelResultRecorder.RecordDetectionResult(Sequence, "NG");
+                            });
+                        }
+                        break;
+                    case 12:
+                        int isPass12 = config.JudgeDetectionResult(Sequence, numBoxes, classIds, prob);
+                        usOutput[Sequence - 1] = isPass12;
+                        if (TcpServerManager._isRunning && usOutput_tcp != null) usOutput_tcp[Sequence - 1] = isPass12;
+                        if (isPass12 == 1)
+                        {
+                            this.Dispatcher.BeginInvoke(new Action(() =>
+                            {
+                                Finall_result11.Content = "OK";
+                                finall_result11.Background = System.Windows.Media.Brushes.Green;
+                            }));
+                            Console.WriteLine($"鐐逛綅 {Sequence} 妫�娴嬮�氳繃");
+                            EnhancedLogViewModel.Instance.AddLog($"{DateTime.Now:HH:mm:ss:fff}锛氱偣浣� {Sequence} 妫�娴嬮�氳繃");
+                            Task.Run(() =>
+                            {
+                                // 璁板綍鍒癊xcel锛堟壒閲忓啓鍏ワ級
+                                ExcelResultRecorder.RecordDetectionResult(Sequence, "OK");
+                            });
+                            //Image_NG.Add($".\\vino_res\\result_{Sequence}.jpg");
+                        }
+                        else
+                        {
+                            USOUT = false;
+                            this.Dispatcher.BeginInvoke(new Action(() =>
+                            {
+                                Finall_result11.Content = "NG";
+                                finall_result11.Background = System.Windows.Media.Brushes.Red;
+                            }));
+                            Console.WriteLine($"鐐逛綅 {Sequence} 妫�娴嬩笉閫氳繃");
+                            EnhancedLogViewModel.Instance.AddLog($"{DateTime.Now:HH:mm:ss:fff}锛氱偣浣� {Sequence} 妫�娴嬩笉閫氳繃", "ERROR");
+                            Image_NG.Add($".\\vino_res\\result_{Sequence}.jpg");
+                            Task.Run(() =>
+                            {
+                                // 璁板綍鍒癊xcel锛堟壒閲忓啓鍏ワ級
+                                ExcelResultRecorder.RecordDetectionResult(Sequence, "NG");
+                            });
+                        }
+                        break;
+                    case 13:
+                        int isPass13 = config.JudgeDetectionResult(Sequence, numBoxes, classIds, prob);
+                        usOutput[Sequence - 1] = isPass13;
+                        if (TcpServerManager._isRunning && usOutput_tcp != null) usOutput_tcp[Sequence - 1] = isPass13;
+                        if (isPass13 == 1)
+                        {
+                            this.Dispatcher.BeginInvoke(new Action(() =>
+                            {
+                                Finall_result12.Content = "OK";
+                                finall_result12.Background = System.Windows.Media.Brushes.Green;
+                            }));
+                            Console.WriteLine($"鐐逛綅 {Sequence} 妫�娴嬮�氳繃");
+                            EnhancedLogViewModel.Instance.AddLog($"{DateTime.Now:HH:mm:ss:fff}锛氱偣浣� {Sequence} 妫�娴嬮�氳繃");
+                            Task.Run(() =>
+                            {
+                                // 璁板綍鍒癊xcel锛堟壒閲忓啓鍏ワ級
+                                ExcelResultRecorder.RecordDetectionResult(Sequence, "OK");
+                            });
+                        }
+                        else
+                        {
+                            USOUT = false;
+                            this.Dispatcher.BeginInvoke(new Action(() =>
+                            {
+                                Finall_result12.Content = "NG";
+                                finall_result12.Background = System.Windows.Media.Brushes.Red;
+                            }));
+                            Console.WriteLine($"鐐逛綅 {Sequence} 妫�娴嬩笉閫氳繃");
+                            EnhancedLogViewModel.Instance.AddLog($"{DateTime.Now:HH:mm:ss:fff}锛氱偣浣� {Sequence} 妫�娴嬩笉閫氳繃", "ERROR");
+                            Image_NG.Add($".\\vino_res\\result_{Sequence}.jpg");
+                            Task.Run(() =>
+                            {
+                                // 璁板綍鍒癊xcel锛堟壒閲忓啓鍏ワ級
+                                ExcelResultRecorder.RecordDetectionResult(Sequence, "NG");
+                            });
+                        }
+                        break;
+                    case 14:
+                        int isPass14 = config.JudgeDetectionResult(Sequence, numBoxes, classIds, prob);
+                        usOutput[Sequence - 1] = isPass14;
+                        if (TcpServerManager._isRunning && usOutput_tcp != null) usOutput_tcp[Sequence - 1] = isPass14;
+                        if (isPass14 == 1)
+                        {
+                            this.Dispatcher.BeginInvoke(new Action(() =>
+                            {
+                                Finall_result13.Content = "OK";
+                                finall_result13.Background = System.Windows.Media.Brushes.Green;
+                            }));
+                            Console.WriteLine($"鐐逛綅 {Sequence} 妫�娴嬮�氳繃");
+                            EnhancedLogViewModel.Instance.AddLog($"{DateTime.Now:HH:mm:ss:fff}锛氱偣浣� {Sequence} 妫�娴嬮�氳繃");
+                            Task.Run(() =>
+                            {
+                                // 璁板綍鍒癊xcel锛堟壒閲忓啓鍏ワ級
+                                ExcelResultRecorder.RecordDetectionResult(Sequence, "OK");
+                            });
+                        }
+                        else
+                        {
+                            USOUT = false;
+                            this.Dispatcher.BeginInvoke(new Action(() =>
+                            {
+                                Finall_result13.Content = "NG";
+                                finall_result13.Background = System.Windows.Media.Brushes.Red;
+                            }));
+                            Console.WriteLine($"鐐逛綅 {Sequence} 妫�娴嬩笉閫氳繃");
+                            EnhancedLogViewModel.Instance.AddLog($"{DateTime.Now:HH:mm:ss:fff}锛氱偣浣� {Sequence} 妫�娴嬩笉閫氳繃", "ERROR");
+                            Image_NG.Add($".\\vino_res\\result_{Sequence}.jpg");
+                            Task.Run(() =>
+                            {
+                                // 璁板綍鍒癊xcel锛堟壒閲忓啓鍏ワ級
+                                ExcelResultRecorder.RecordDetectionResult(Sequence, "NG");
+                            });
+                        }
+                        break;
+                    case 15:
+                        int isPass15 = config.JudgeDetectionResult(Sequence, numBoxes, classIds, prob);
+                        usOutput[Sequence - 1] = isPass15;
+                        if (TcpServerManager._isRunning && usOutput_tcp != null) usOutput_tcp[Sequence - 1] = isPass15;
+                        if (isPass15 == 1)
+                        {
+                            this.Dispatcher.BeginInvoke(new Action(() =>
+                            {
+                                Finall_result14.Content = "OK";
+                                finall_result14.Background = System.Windows.Media.Brushes.Green;
+                            }));
+                            Console.WriteLine($"鐐逛綅 {Sequence} 妫�娴嬮�氳繃");
+                            EnhancedLogViewModel.Instance.AddLog($"{DateTime.Now:HH:mm:ss:fff}锛氱偣浣� {Sequence} 妫�娴嬮�氳繃");
+                            Task.Run(() =>
+                            {
+                                // 璁板綍鍒癊xcel锛堟壒閲忓啓鍏ワ級
+                                ExcelResultRecorder.RecordDetectionResult(Sequence, "OK");
+                            });
+                        }
+                        else
+                        {
+                            USOUT = false;
+                            this.Dispatcher.BeginInvoke(new Action(() =>
+                            {
+                                Finall_result14.Content = "NG";
+                                finall_result14.Background = System.Windows.Media.Brushes.Red;
+                            }));
+                            Console.WriteLine($"鐐逛綅 {Sequence} 妫�娴嬩笉閫氳繃");
+                            EnhancedLogViewModel.Instance.AddLog($"{DateTime.Now:HH:mm:ss:fff}锛氱偣浣� {Sequence} 妫�娴嬩笉閫氳繃", "ERROR");
+                            Image_NG.Add($".\\vino_res\\result_{Sequence}.jpg");
+                            Task.Run(() =>
+                            {
+                                // 璁板綍鍒癊xcel锛堟壒閲忓啓鍏ワ級
+                                ExcelResultRecorder.RecordDetectionResult(Sequence, "NG");
+                            });
+                        }
+                        break;
+                    case 16:
+                        int isPass16 = config.JudgeDetectionResult(Sequence, numBoxes, classIds, prob);
+                        usOutput[Sequence - 1] = isPass16;
+                        if (TcpServerManager._isRunning && usOutput_tcp != null) usOutput_tcp[Sequence - 1] = isPass16;
+                        if (isPass16 == 1)
+                        {
+                            this.Dispatcher.BeginInvoke(new Action(() =>
+                            {
+                                Finall_result15.Content = "OK";
+                                finall_result15.Background = System.Windows.Media.Brushes.Green;
+                            }));
+                            Console.WriteLine($"鐐逛綅 {Sequence} 妫�娴嬮�氳繃");
+                            EnhancedLogViewModel.Instance.AddLog($"{DateTime.Now:HH:mm:ss:fff}锛氱偣浣� {Sequence} 妫�娴嬮�氳繃");
+                            Task.Run(() =>
+                            {
+                                // 璁板綍鍒癊xcel锛堟壒閲忓啓鍏ワ級
+                                ExcelResultRecorder.RecordDetectionResult(Sequence, "OK");
+                            });
+                        }
+                        else
+                        {
+                            USOUT = false;
+                            this.Dispatcher.BeginInvoke(new Action(() =>
+                            {
+                                Finall_result15.Content = "NG";
+                                finall_result15.Background = System.Windows.Media.Brushes.Red;
+                            }));
+                            Console.WriteLine($"鐐逛綅 {Sequence} 妫�娴嬩笉閫氳繃");
+                            EnhancedLogViewModel.Instance.AddLog($"{DateTime.Now:HH:mm:ss:fff}锛氱偣浣� {Sequence} 妫�娴嬩笉閫氳繃", "ERROR");
+                            Image_NG.Add($".\\vino_res\\result_{Sequence}.jpg");
+                            Task.Run(() =>
+                            {
+                                // 璁板綍鍒癊xcel锛堟壒閲忓啓鍏ワ級
+                                ExcelResultRecorder.RecordDetectionResult(Sequence, "NG");
+                            });
+                        }
+                        break;
+                    case 17:
+                        int isPass17 = config.JudgeDetectionResult(Sequence, numBoxes, classIds, prob);
+                        usOutput2[Sequence - 17] = isPass17;
+                        if (TcpServerManager._isRunning && usOutput_tcp != null) usOutput_tcp[Sequence - 1] = isPass17;
+                        if (isPass17 == 1)
+                        {
+                            this.Dispatcher.BeginInvoke(new Action(() =>
+                            {
+                                Finall_result16.Content = "OK";
+                                finall_result16.Background = System.Windows.Media.Brushes.Green;
+                            }));
+                            Console.WriteLine($"鐐逛綅 {Sequence} 妫�娴嬮�氳繃");
+                            EnhancedLogViewModel.Instance.AddLog($"{DateTime.Now:HH:mm:ss:fff}锛氱偣浣� {Sequence} 妫�娴嬮�氳繃");
+                            Task.Run(() =>
+                            {
+                                // 璁板綍鍒癊xcel锛堟壒閲忓啓鍏ワ級
+                                ExcelResultRecorder.RecordDetectionResult(Sequence, "OK");
+                            });
+                        }
+                        else
+                        {
+                            USOUT = false;
+                            this.Dispatcher.BeginInvoke(new Action(() =>
+                            {
+                                Finall_result16.Content = "NG";
+                                finall_result16.Background = System.Windows.Media.Brushes.Red;
+                            }));
+                            Console.WriteLine($"鐐逛綅 {Sequence} 妫�娴嬩笉閫氳繃");
+                            EnhancedLogViewModel.Instance.AddLog($"{DateTime.Now:HH:mm:ss:fff}锛氱偣浣� {Sequence} 妫�娴嬩笉閫氳繃", "ERROR");
+                            Image_NG.Add($".\\vino_res\\result_{Sequence}.jpg");
+                            Task.Run(() =>
+                            {
+                                // 璁板綍鍒癊xcel锛堟壒閲忓啓鍏ワ級
+                                ExcelResultRecorder.RecordDetectionResult(Sequence, "NG");
+                            });
+                        }
+                        break;
+                    case 18:
+                        int isPass18 = config.JudgeDetectionResult(Sequence, numBoxes, classIds, prob);
+                        usOutput2[Sequence - 17] = isPass18;
+                        if (TcpServerManager._isRunning && usOutput_tcp != null) usOutput_tcp[Sequence - 1] = isPass18;
+                        if (isPass18 == 1)
+                        {
+                            this.Dispatcher.BeginInvoke(new Action(() =>
+                            {
+                                Finall_result17.Content = "OK";
+                                finall_result17.Background = System.Windows.Media.Brushes.Green;
+                            }));
+                            Console.WriteLine($"鐐逛綅 {Sequence} 妫�娴嬮�氳繃");
+                            EnhancedLogViewModel.Instance.AddLog($"{DateTime.Now:HH:mm:ss:fff}锛氱偣浣� {Sequence} 妫�娴嬮�氳繃");
+                            Task.Run(() =>
+                            {
+                                // 璁板綍鍒癊xcel锛堟壒閲忓啓鍏ワ級
+                                ExcelResultRecorder.RecordDetectionResult(Sequence, "OK");
+                            });
+                        }
+                        else
+                        {
+                            USOUT = false;
+                            this.Dispatcher.BeginInvoke(new Action(() =>
+                            {
+                                Finall_result17.Content = "NG";
+                                finall_result17.Background = System.Windows.Media.Brushes.Red;
+                            }));
+                            Console.WriteLine($"鐐逛綅 {Sequence} 妫�娴嬩笉閫氳繃");
+                            EnhancedLogViewModel.Instance.AddLog($"{DateTime.Now:HH:mm:ss:fff}锛氱偣浣� {Sequence} 妫�娴嬩笉閫氳繃", "ERROR");
+                            Image_NG.Add($".\\vino_res\\result_{Sequence}.jpg");
+                            Task.Run(() =>
+                            {
+                                // 璁板綍鍒癊xcel锛堟壒閲忓啓鍏ワ級
+                                ExcelResultRecorder.RecordDetectionResult(Sequence, "NG");
+                            });
+                        }
+                        break;
+                    case 19:
+                        int isPass19 = config.JudgeDetectionResult(Sequence, numBoxes, classIds, prob);
+                        usOutput2[Sequence - 17] = isPass19;
+                        if (TcpServerManager._isRunning && usOutput_tcp != null) usOutput_tcp[Sequence - 1] = isPass19;
+                        if (isPass19 == 1)
+                        {
+                            this.Dispatcher.BeginInvoke(new Action(() =>
+                            {
+                                Finall_result18.Content = "OK";
+                                finall_result18.Background = System.Windows.Media.Brushes.Green;
+                            }));
+                            Console.WriteLine($"鐐逛綅 {Sequence} 妫�娴嬮�氳繃");
+                            EnhancedLogViewModel.Instance.AddLog($"{DateTime.Now:HH:mm:ss:fff}锛氱偣浣� {Sequence} 妫�娴嬮�氳繃");
+                            Task.Run(() =>
+                            {
+                                // 璁板綍鍒癊xcel锛堟壒閲忓啓鍏ワ級
+                                ExcelResultRecorder.RecordDetectionResult(Sequence, "OK");
+                            });
+                        }
+                        else
+                        {
+                            USOUT = false;
+                            this.Dispatcher.BeginInvoke(new Action(() =>
+                            {
+                                Finall_result18.Content = "NG";
+                                finall_result18.Background = System.Windows.Media.Brushes.Red;
+                            }));
+                            Console.WriteLine($"鐐逛綅 {Sequence} 妫�娴嬩笉閫氳繃");
+                            EnhancedLogViewModel.Instance.AddLog($"{DateTime.Now:HH:mm:ss:fff}锛氱偣浣� {Sequence} 妫�娴嬩笉閫氳繃", "ERROR");
+                            Image_NG.Add($".\\vino_res\\result_{Sequence}.jpg");
+                            Task.Run(() =>
+                            {
+                                // 璁板綍鍒癊xcel锛堟壒閲忓啓鍏ワ級
+                                ExcelResultRecorder.RecordDetectionResult(Sequence, "NG");
+                            });
+                        }
+                        break;
+                    case 20:
+                        int isPass20 = config.JudgeDetectionResult(Sequence, numBoxes, classIds, prob);
+                        usOutput2[Sequence - 17] = isPass20;
+                        if (TcpServerManager._isRunning && usOutput_tcp != null) usOutput_tcp[Sequence - 1] = isPass20;
+                        if (isPass20 == 1)
+                        {
+                            this.Dispatcher.BeginInvoke(new Action(() =>
+                            {
+                                Finall_result19.Content = "OK";
+                                finall_result19.Background = System.Windows.Media.Brushes.Green;
+                            }));
+                            Console.WriteLine($"鐐逛綅 {Sequence} 妫�娴嬮�氳繃");
+                            EnhancedLogViewModel.Instance.AddLog($"{DateTime.Now:HH:mm:ss:fff}锛氱偣浣� {Sequence} 妫�娴嬮�氳繃");
+                            Task.Run(() =>
+                            {
+                                // 璁板綍鍒癊xcel锛堟壒閲忓啓鍏ワ級
+                                ExcelResultRecorder.RecordDetectionResult(Sequence, "OK");
+                            });
+                        }
+                        else
+                        {
+                            USOUT = false;
+                            this.Dispatcher.BeginInvoke(new Action(() =>
+                            {
+                                Finall_result19.Content = "NG";
+                                finall_result19.Background = System.Windows.Media.Brushes.Red;
+                            }));
+                            Console.WriteLine($"鐐逛綅 {Sequence} 妫�娴嬩笉閫氳繃");
+                            EnhancedLogViewModel.Instance.AddLog($"{DateTime.Now:HH:mm:ss:fff}锛氱偣浣� {Sequence} 妫�娴嬩笉閫氳繃", "ERROR");
+                            Image_NG.Add($".\\vino_res\\result_{Sequence}.jpg");
+                            Task.Run(() =>
+                            {
+                                // 璁板綍鍒癊xcel锛堟壒閲忓啓鍏ワ級
+                                ExcelResultRecorder.RecordDetectionResult(Sequence, "NG");
+                            });
+                        }
+                        break;
+                }
+            }
+        }
+        //鍥惧儚閲囬泦
+        private void GetIDDevice_CaptureImage(int Sequence)
+        {
+            IntPtr deviceHandle = _deviceHandles[Sequence];
+            IntPtr imagePtr = _imagePtr[Sequence];
+
+            // 寮�濮嬮噰闆嗗浘鍍�
+            Console.WriteLine($"{Sequence}鍙疯澶囧紑濮嬮噰闆嗗浘鍍�");
+            EnhancedLogViewModel.Instance.AddLog($"{DateTime.Now:HH:mm:ss:fff}锛歿Sequence}鍙疯澶囧紑濮嬮噰闆嗗浘鍍�");
+            long rel = IDDevice_IsOpen(deviceHandle);
+            if (rel == 0)
+            {
+                MessageBox.Show($"璁惧{Sequence}杩炴帴宸叉柇寮�", "閿欒", MessageBoxButton.OK, MessageBoxImage.Error);
+                EnhancedLogViewModel.Instance.AddLog($"璁惧{Sequence}杩炴帴宸叉柇寮�", "ERROR");
+                _imagePtr[Sequence] = IntPtr.Zero;
+                return;
+            }
+
+            IDDevice_CaptureImage(deviceHandle, imagePtr);
+            EnhancedLogViewModel.Instance.AddLog($"{DateTime.Now:HH:mm:ss:fff}锛歿Sequence}鍙疯澶囧浘鍍忛噰闆嗙粨鏉燂紝寮�濮嬭繘琛屽浘鍍忛澶勭悊");
+        }
+        #endregion
+        // 鏁版嵁杞崲
+        static ushort BinaryToUshort_MSBFirst(int[] binaryArray)
+        {
+            if (binaryArray.Length > 16)
+                throw new ArgumentException("Binary array cannot exceed 16 bits.");
+
+            ushort result = 0;
+            for (int i = 0; i < binaryArray.Length; i++)
+            {
+                if (binaryArray[i] == 1)
+                    result |= (ushort)(1 << i); // 浣庝綅鍦ㄥ墠
+                else if (binaryArray[i] != 0)
+                    throw new ArgumentException("Binary array can only contain 0s and 1s.");
+            }
+            return result;
+        }
+        /// <summary>
+        /// 鑷姩淇濆瓨NG鍥剧墖鍒版寚瀹氭棩鏈熺洰褰�
+        /// 淇濆瓨璺緞鏍煎紡锛欴:\01 LBImage_NG\(褰撳墠鏃ユ湡)\
+        /// 濡傛灉鐩綍涓嶅瓨鍦ㄤ細鑷姩鍒涘缓锛屾敮鎸佹壒閲忎繚瀛樻搷浣�
+        /// </summary>
+        /// <param name="ngImagePaths">NG鍥剧墖璺緞闆嗗悎</param>
+        /// <returns>鎴愬姛淇濆瓨鐨勫浘鐗囨暟閲�</returns>
+        public int AutoSaveNGImages(List<string> ngImagePaths)
+        {
+            // 鏍¢獙杈撳叆鍙傛暟
+            if (ngImagePaths == null || ngImagePaths.Count == 0)
+            {
+                EnhancedLogViewModel.Instance.AddLog($"NG鍥剧墖璺緞闆嗗悎涓虹┖锛屾棤闇�淇濆瓨鎿嶄綔銆�");
+                return 0;
+            }
+
+            int successCount = 0;  // 鎴愬姛淇濆瓨鐨勮鏁板櫒
+            string baseDirectory = @"D:\01 LBImage_NG";  // 鍩虹淇濆瓨鐩綍
+
+            try
+            {
+                // 鑾峰彇褰撳墠绯荤粺鏃ユ湡锛屾牸寮忓寲涓簓yyyMMdd
+                string dateFolderName = DateTime.Now.ToString("yyyyMMdd");
+
+                // 鏋勫缓瀹屾暣鐨勭洰鏍囩洰褰曡矾寰�
+                string targetDirectory = Path.Combine(baseDirectory, dateFolderName);
+
+                // 濡傛灉鐩爣鐩綍涓嶅瓨鍦紝鍒欏垱寤�
+                if (!Directory.Exists(targetDirectory))
+                {
+                    Directory.CreateDirectory(targetDirectory);
+                }
+
+                // 閬嶅巻鎵�鏈塏G鍥剧墖璺緞
+                foreach (string sourcePath in ngImagePaths)
+                {
+                    try
+                    {
+                        // 妫�鏌ユ簮鏂囦欢鏄惁瀛樺湪
+                        if (!File.Exists(sourcePath))
+                        {
+                            Console.WriteLine($"鏂囦欢涓嶅瓨鍦紝璺宠繃: {sourcePath}");
+                            continue;
+                        }
+
+                        // 鑾峰彇鏂囦欢鍚嶏紙鍖呭惈鎵╁睍鍚嶏級
+                        string fileName = Path.GetFileName(sourcePath);
+
+                        // 鏋勫缓鐩爣鏂囦欢瀹屾暣璺緞
+                        string destinationPath = Path.Combine(targetDirectory, fileName);
+
+                        // 濡傛灉鐩爣鏂囦欢宸插瓨鍦紝娣诲姞鏃堕棿鎴抽伩鍏嶈鐩�
+                        if (File.Exists(destinationPath))
+                        {
+                            string timeStamp = DateTime.Now.ToString("HHmmss");
+                            string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(fileName);
+                            string extension = Path.GetExtension(fileName);
+                            fileName = $"{fileNameWithoutExtension}_{timeStamp}{extension}";
+                            destinationPath = Path.Combine(targetDirectory, fileName);
+                        }
+
+                        // 澶嶅埗鏂囦欢鍒扮洰鏍囩洰褰�
+                        File.Copy(sourcePath, destinationPath, true);
+                        successCount++;
+
+                        Console.WriteLine($"鎴愬姛淇濆瓨: {sourcePath} -> {destinationPath}");
+                    }
+                    catch (Exception ex)
+                    {
+                        Console.WriteLine($"淇濆瓨鏂囦欢澶辫触 {sourcePath}: {ex.Message}");
+                    }
+                }
+
+            }
+            catch (Exception ex)
+            {
+                MessageBox.Show($"淇濆瓨杩囩▼涓彂鐢熼敊璇�: {ex.Message}", "閿欒", MessageBoxButton.OK, MessageBoxImage.Error);
+            }
+
+            return successCount;
+        }
+        //榛樿鍔犺浇涓婃妫�娴嬫柟妗�
+        public bool LoadLastUsedConfiguration(bool bl)
+        {
+            bool isLoad = true;
+            try
+            {
+                if (!string.IsNullOrEmpty(ResultJudge.AppSettings.LastConfigFilePath_Proj) && File.Exists(ResultJudge.AppSettings.LastConfigFilePath_Proj))
+                {
+                    bool isLoadModel;
+                    //json = File.ReadAllText(ResultJudge.AppSettings.LastConfigFilePath);
+                    var (modelName, configPath, configContent, message) = LBProjService.LoadLBProj(ResultJudge.AppSettings.LastConfigFilePath_Proj);
+                    config = JsonConvert.DeserializeObject<ResultJudge.JudgmentConfiguration>(configContent);
+
+                    if (bl)
+                    {
+                        if (detector != IntPtr.Zero)
+                        {
+                            DisposeDetector_CPU(detector);
+                        }
+                        Task.Run(() =>
+                        {
+                            // 妯″瀷鎺ㄧ悊寮曟搸閫夋嫨
+                            detector = CreateDetector_CPU();
+                            isLoadModel = InitializeDetector_CPU(detector, Detector_Device, $".\\model\\{modelName}");
+                            while (true)
+                            {
+                                if (isLoadModel)
+                                {
+                                    EnhancedLogViewModel.Instance.AddLog($"妯″瀷缂栬瘧鎴愬姛");
+                                    break;
+                                }
+                            }
+                        });
+                        MessageBox.Show($"宸茶嚜鍔ㄥ姞杞戒笂娆′娇鐢ㄧ殑宸ョ▼鏂囦欢: {ResultJudge.AppSettings.LastConfigFilePath_Proj}",
+                "鎴愬姛", MessageBoxButton.OK, MessageBoxImage.Information);
+                    }
+                    this.Dispatcher.BeginInvoke(new Action(() =>
+                    {
+                        ProjectState.Foreground = System.Windows.Media.Brushes.LightGreen;
+                        ModelState.Foreground = System.Windows.Media.Brushes.LightGreen;
+                        ProjectState.Text = ResultJudge.AppSettings.LastConfigFilePath_Proj;
+                        ModelState.Text = modelName;
+                    }));
+                    EnhancedLogViewModel.Instance.AddLog($"褰撳墠宸ョ▼鏂囦欢: {ResultJudge.AppSettings.LastConfigFilePath_Proj}锛屾ā鍨嬶細{modelName}");
+                    isLoad = true;
+                }
+                else
+                {
+                    if (!string.IsNullOrEmpty(ResultJudge.AppSettings.LastConfigFilePath) && File.Exists(ResultJudge.AppSettings.LastConfigFilePath))
+                    {
+                        json = File.ReadAllText(ResultJudge.AppSettings.LastConfigFilePath);
+                        config = JsonConvert.DeserializeObject<ResultJudge.JudgmentConfiguration>(json);
+                        if (bl)
+                        {
+                            MessageBox.Show($"宸茶嚜鍔ㄥ姞杞戒笂娆′娇鐢ㄧ殑妫�娴嬫柟妗�: {ResultJudge.AppSettings.LastConfigFilePath}",
+                    "鎴愬姛", MessageBoxButton.OK, MessageBoxImage.Information);
+                        }
+                        EnhancedLogViewModel.Instance.AddLog($"褰撳墠妫�娴嬫柟妗�: {ResultJudge.AppSettings.LastConfigFilePath}");
+                        isLoad = true;
+                    }
+                    else
+                    {
+                        MessageBox.Show("娌℃湁鎵惧埌涓婃浣跨敤鐨勬娴嬫柟妗堬紝璇锋墜鍔ㄥ姞杞�",
+                                    "鎻愮ず", MessageBoxButton.OK, MessageBoxImage.Information);
+                        EnhancedLogViewModel.Instance.AddLog($"娌℃湁鎵惧埌涓婃浣跨敤鐨勬娴嬫柟妗堬紝璇锋墜鍔ㄥ姞杞�", "WARN");
+                        isLoad = false;
+                    }
+                }
+            }
+            catch (Exception ex)
+            {
+                isLoad = false;
+                MessageBox.Show($"鑷姩鍔犺浇宸ョ▼鏃跺嚭閿欙紝璇锋墜鍔ㄥ姞杞�: {ex.Message}", "閿欒", MessageBoxButton.OK, MessageBoxImage.Error);
+            }
+            return isLoad;
+        }
+        #endregion
+        #region  Modbus Tcp閫氳璁剧疆
+        //璁板綍鏈�鍚庝竴娆¤Е鍙戞椂闂�
+        private DateTime _lastTriggerTime = DateTime.MinValue;
+        //瑙﹀彂淇″彿鐩戝惉
+        private void ClientListen()
+        {
+            try
+            {
+                int num = 0;
+                while (modbusTCPClient._client == null || modbusTCPClient._client.Connected == false || modbusTCPClient._master == null)
+                {
+                    if (_isReconnecting) return; // 濡傛灉姝e湪閲嶈繛锛岀洿鎺ヨ繑鍥�
+
+                    modbusTCPClient.ModbudTCP_Connect(_lastIpAddress, _lastPort);
+                    if (num++ > 3)
+                    {
+                        this.Dispatcher.BeginInvoke(new Action(() =>
+                        {
+                            MessageBox.Show("Modbus master 鏈垵濮嬪寲銆傛棤娉曡繛鎺LC");
+                        }));
+                        break;
+                    }
+                }
+
+                while (modbusTCPClient._client != null && modbusTCPClient._client.Connected) //鎸佺画鐩戞帶
+                {
+                    //modbusTCPClient.currentValus_ROIModel = modbusTCPClient.InputRegistersRead(3);
+                    while (modbusTCPClient._client != null && modbusTCPClient._client.Connected)
+                    {
+                        modbusTCPClient.currentValus_trigger = modbusTCPClient.InputRegistersRead(3);
+                        if (modbusTCPClient.previousValus_trigger[0] == 0 && modbusTCPClient.currentValus_trigger[0] == 1)
+                        {
+                            // 妫�鏌ヨ窛绂讳笂娆¤Е鍙戞槸鍚﹁秴杩�5绉�
+                            if ((DateTime.Now - _lastTriggerTime).TotalSeconds >= double.Parse(Selflocking_Time))
+                            {
+                                _lastTriggerTime = DateTime.Now;
+                                modbusTCPClient.istrigger = true;
+                                Dispatcher.Invoke(() =>
+                                {
+                                    DateTime currentDate = DateTime.Now;
+                                    string timeFileName = currentDate.ToString("HH:mm:ss");
+                                    GetMessage_Modbus($"妫�娴嬪埌瑙﹀彂淇″彿:{modbusTCPClient.currentValus_trigger[0]}");
+                                    GetMessage_Modbus($"{timeFileName}\n");
+                                });
+                                Console.WriteLine($"妫�娴嬪埌瑙﹀彂淇″彿:{modbusTCPClient.currentValus_trigger[0]}");
+                                modbusTCPClient.MultipleRegistersWrite(3, new ushort[] { 0 });
+                                Console.WriteLine($"瀵勫瓨鍣ㄧ疆0");
+                                ReSetUI();
+                                Task.Run(() => GetImage());
+                            }
+                            else
+                            {
+                                Console.WriteLine($"蹇界暐瑙﹀彂淇″彿锛岃窛绂讳笂娆¤Е鍙戜笉瓒硔Selflocking_Time}绉�");
+                                modbusTCPClient.MultipleRegistersWrite(3, new ushort[] { 0 });
+                            }
+                        }
+                        modbusTCPClient.previousValus_trigger = modbusTCPClient.currentValus_trigger;
+                        modbusTCPClient.istrigger = false;
+                        break;
+                    }
+                    modbusTCPClient.previousValus_ROIModel = modbusTCPClient.currentValus_ROIModel;
+                }
+            }
+            catch (Exception e)
+            {
+                // 濡傛灉姝e湪閲嶈繛锛屼笉鏄剧ず閿欒娑堟伅
+                if (!_isReconnecting)
+                {
+                    this.Dispatcher.BeginInvoke(new Action(() =>
+                    {
+                        // 涓嶅啀寮圭獥锛屽彧鍦ㄦ棩蹇椾腑璁板綍
+                        GetMessage_Modbus("Modbus杩炴帴鏂紑锛屽紑濮嬪皾璇曢噸杩�...\n");
+                    }));
+                }
+            }
+        }
+        //ModBus蹇冭烦淇″彿
+        private void HeartbeatCallback(object state)
+        {
+            try
+            {
+                // 璇诲彇淇濇寔瀵勫瓨鍣�1鐨勫��
+                modbusTCPClient.HoldingRegisterRead(1);
+                Console.WriteLine("蹇冭烦淇″彿鏀跺彂姝e父");
+
+                // 蹇冭烦姝e父锛岄噸缃噸杩炲皾璇曟鏁�
+                _reconnectAttempts = 0;
+            }
+            catch (Exception ex)
+            {
+                this.Dispatcher.BeginInvoke(new Action(() =>
+                {
+                    LinkState.Text = "鏈繛鎺�";
+                    LinkState.Foreground = System.Windows.Media.Brushes.Red;
+                    GetMessage_Modbus("妫�娴嬪埌Modbus杩炴帴寮傚父锛屽噯澶囬噸杩�...\n");
+                }));
+                Console.WriteLine($"Heartbeat failed: {ex.Message}");
+
+                // 绔嬪嵆鍚姩閲嶈繛鏈哄埗
+                StartReconnect();
+            }
+        }
+        // 鐢ㄦ埛鐐瑰嚮纭畾璺熻釜鏍囧織浣�
+        private bool _disconnectAlertShown = false;
+        // 璁惧杩炴帴鐘舵�佹娴�
+        private void DeviceConnectbeatCallback(object state)
+        {
+            try
+            {
+                for (int i = 0; i < DeviceListBox.Items.Count; i++)
+                {
+                    IntPtr deviceHandle = _deviceHandles[i + 1];
+                    long rel = IDDevice_IsOpen(deviceHandle);
+                    if (rel == 0)
+                    {
+                        if (!_disconnectAlertShown)
+                        {
+                            _disconnectAlertShown = true;
+                            System.Windows.Application.Current.Dispatcher.Invoke(() =>
+                            {
+                                MessageBox.Show($"璁惧{i + 1}杩炴帴鏂紑,璇烽噸鏂拌繛鎺�", "閿欒",
+                                    MessageBoxButton.OK, MessageBoxImage.Error);
+                                _disconnectAlertShown = false; // 鐢ㄦ埛鐐瑰嚮纭畾鍚庨噸缃爣蹇�
+                            });
+
+                            _imagePtr[i + 1] = IntPtr.Zero;
+                            // 褰诲簳閲婃斁瀹氭椂鍣�
+                            deviceStatusTimer?.Dispose();
+                            deviceStatusTimer = null;
+                        }
+                        return;
+                    }
+                }
+            }
+            catch (Exception ex)
+            {
+                Console.WriteLine($"璁惧鏈寜鐓ф槧灏勮〃杩炴帴: {ex.Message}");
+            }
+        }
+        #endregion
+
+        #region Modbus閲嶈繛鏈哄埗
+
+        // 鍒濆鍖栭噸杩炲畾鏃跺櫒
+        private void InitializeReconnectTimer()
+        {
+            // 濡傛灉瀹氭椂鍣ㄥ凡瀛樺湪锛屽厛閲婃斁
+            _reconnectTimer?.Dispose();
+
+            // 鍒涘缓鏂扮殑閲嶈繛瀹氭椂鍣�
+            _reconnectTimer = new System.Threading.Timer(ReconnectCallback, null, Timeout.Infinite, RECONNECT_INTERVAL);
+        }
+
+        // 鍚姩閲嶈繛
+        private void StartReconnect()
+        {
+            if (_isReconnecting) return;
+
+            // 鍋滄蹇冭烦瀹氭椂鍣�
+            heartbeatTimer?.Change(Timeout.Infinite, Timeout.Infinite);
+
+            // 鍚姩閲嶈繛瀹氭椂鍣�
+            _reconnectTimer?.Change(0, RECONNECT_INTERVAL);
+        }
+
+        // 鍋滄閲嶈繛
+        private void StopReconnect()
+        {
+            // 鍋滄閲嶈繛瀹氭椂鍣�
+            _reconnectTimer?.Change(Timeout.Infinite, Timeout.Infinite);
+
+            // 閲嶅惎蹇冭烦瀹氭椂鍣�
+            heartbeatTimer?.Change(0, heartbeatInterval);
+        }
+
+        // 閲嶈繛鍥炶皟
+        private void ReconnectCallback(object state)
+        {
+            if (_isReconnecting) return;
+
+            _isReconnecting = true;
+
+            try
+            {
+                // 妫�鏌ユ槸鍚﹁秴杩囨渶澶ч噸杩炴鏁�
+                if (_reconnectAttempts >= MAX_RECONNECT_ATTEMPTS)
+                {
+                    this.Dispatcher.BeginInvoke(new Action(() =>
+                    {
+                        GetMessage_Modbus($"閲嶈繛澶辫触锛屽凡杈惧埌鏈�澶ч噸杩炴鏁� ({MAX_RECONNECT_ATTEMPTS})\n");
+                        // 鍙湁瓒呰繃鏈�澶ч噸杩炴鏁版椂鎵嶅脊绐�
+                        MessageBox.Show("Modbus閲嶈繛澶辫触锛屽凡杈惧埌鏈�澶ч噸杩炴鏁�", "閿欒", MessageBoxButton.OK, MessageBoxImage.Error);
+                    }));
+
+                    // 鍋滄閲嶈繛瀹氭椂鍣�
+                    _reconnectTimer?.Change(Timeout.Infinite, Timeout.Infinite);
+                    return;
+                }
+
+                _reconnectAttempts++;
+
+                this.Dispatcher.BeginInvoke(new Action(() =>
+                {
+                    GetMessage_Modbus($"灏濊瘯绗� {_reconnectAttempts} 娆¢噸杩�...\n");
+                }));
+
+                // 灏濊瘯閲嶈繛
+                bool reconnectSuccess = modbusTCPClient.Reconnect(_lastIpAddress, _lastPort);
+
+                if (reconnectSuccess)
+                {
+                    // 閲嶈繛鎴愬姛
+                    _reconnectAttempts = 0;
+                    _isReconnecting = false;
+
+                    this.Dispatcher.BeginInvoke(new Action(() =>
+                    {
+                        GetMessage_Modbus("閲嶈繛鎴愬姛\n");
+                        LinkState.Text = "ModBus宸茶繛鎺�";
+                        LinkState.Foreground = System.Windows.Media.Brushes.LightGreen;
+                    }));
+
+                    // 鍋滄閲嶈繛锛屾仮澶嶅績璺�
+                    StopReconnect();
+
+                    // 閲嶆柊鍚姩鐩戝惉浠诲姟
+                    Task.Run(() => ClientListen());
+                }
+                else
+                {
+                    // 閲嶈繛澶辫触锛岀户缁皾璇曪紝涓嶅湪UI涓婂脊绐楋紝鍙湪鏃ュ織涓褰�
+                    this.Dispatcher.BeginInvoke(new Action(() =>
+                    {
+                        GetMessage_Modbus($"绗� {_reconnectAttempts} 娆¢噸杩炲け璐n");
+                    }));
+
+                    _isReconnecting = false;
+                }
+            }
+            catch (Exception ex)
+            {
+                this.Dispatcher.BeginInvoke(new Action(() =>
+                {
+                    GetMessage_Modbus($"閲嶈繛杩囩▼涓彂鐢熼敊璇�: {ex.Message}\n");
+                }));
+
+                _isReconnecting = false;
+            }
+        }
+
+        #endregion
+
+        // 閫氳娴嬭瘯锛宒ebug鐢�
+        private void Write_Click(object sender, RoutedEventArgs e)
+        {
+            EnhancedLogViewModel.Instance.AddLog("寮�濮婱odBus閫氳娴嬭瘯锛屾墍鏈夊瘎瀛樺櫒鍐欏叆楂樼數骞�2s鍚庣疆闆�", "DEBUG");
+            if (modbusTCPClient._client == null)
+            {
+                this.Dispatcher.BeginInvoke(new Action(() =>
+                {
+                    LinkState.Text = "鏈繛鎺�";
+                    LinkState.Foreground = System.Windows.Media.Brushes.Red;
+                }));
+                MessageBox.Show("杩炴帴鍒版湇鍔″櫒澶辫触锛岃妫�鏌ヨ繛鎺ュ悗閲嶈瘯");
+                return;
+            }
+            //ushort[] test = new ushort[] { 0x8001 };
+            //modbusTCPClient.MultipleRegistersWrite(3, test);
+            //outputs[0] = true;
+            //outputs[15] = true;
+            //ushort value = BoolsToUshort(outputs);
+            // 鍋囪鏈変竴涓寘鍚�16涓�0鍜�1鐨勬暟缁�
+            int[] binaryDigits = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 };
+            int[] binaryDigits2 = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 };
+
+            // 灏嗕簩杩涘埗鏁扮粍杞崲涓簎short
+            ushort value = BinaryToUshort_MSBFirst(binaryDigits);
+            ushort value2 = BinaryToUshort_MSBFirst(binaryDigits2);
+
+            // 灏唘short瀛樺偍鍦╱short鏁扮粍涓�
+            ushort[] test = new ushort[] { value };
+            ushort[] test2 = new ushort[] { value2 };
+
+            modbusTCPClient.MultipleRegistersWrite(3, test);
+            modbusTCPClient.MultipleRegistersWrite(4, test2);
+            Thread.Sleep(2000);
+            modbusTCPClient.MultipleRegistersWrite(3, new ushort[] { 0 });
+            modbusTCPClient.MultipleRegistersWrite(4, new ushort[] { 0 });
+        }
+        private void OnTimedEvent(object source, ElapsedEventArgs e)
+        {
+            // 瀹氭椂鍣ㄨЕ鍙戞椂鎵ц鐨勪唬鐮�
+            modbusTCPClient.MultipleRegistersWrite(3, new ushort[] { 0 });
+            modbusTCPClient.MultipleRegistersWrite(4, new ushort[] { 0 });
+            EnhancedLogViewModel.Instance.AddLog($"Modbus宸茬疆闆�");
+            Console.WriteLine("Modbus宸茬疆闆�");
+
+        }
+        // 鎵嬪姩閲囬泦鍥惧儚
+        private void Read_Click(object sender, RoutedEventArgs e)
+        {
+            EnhancedLogViewModel.Instance.AddLog("寮�濮嬫墜鍔ㄩ噰闆嗗浘鍍�", "DEBUG");
+            ReSetUI();
+            Task.Run(() =>
+            {
+                GetImage();
+            });
+        }
+        private void ReSetUI()
+        {
+            this.Dispatcher.BeginInvoke(new Action(() =>
+            {
+                Finall_result0.Content = "";
+                finall_result0.Background = System.Windows.Media.Brushes.Gray;
+                Finall_result1.Content = "";
+                finall_result1.Background = System.Windows.Media.Brushes.Gray;
+                Finall_result2.Content = "";
+                finall_result2.Background = System.Windows.Media.Brushes.Gray;
+                Finall_result3.Content = "";
+                finall_result3.Background = System.Windows.Media.Brushes.Gray;
+                Finall_result4.Content = "";
+                finall_result4.Background = System.Windows.Media.Brushes.Gray;
+                Finall_result5.Content = "";
+                finall_result5.Background = System.Windows.Media.Brushes.Gray;
+                Finall_result6.Content = "";
+                finall_result6.Background = System.Windows.Media.Brushes.Gray;
+                Finall_result7.Content = "";
+                finall_result7.Background = System.Windows.Media.Brushes.Gray;
+                Finall_result8.Content = "";
+                finall_result8.Background = System.Windows.Media.Brushes.Gray;
+                Finall_result9.Content = "";
+                finall_result9.Background = System.Windows.Media.Brushes.Gray;
+                Finall_result10.Content = "";
+                finall_result10.Background = System.Windows.Media.Brushes.Gray;
+                Finall_result11.Content = "";
+                finall_result11.Background = System.Windows.Media.Brushes.Gray;
+                Finall_result12.Content = "";
+                finall_result12.Background = System.Windows.Media.Brushes.Gray;
+                Finall_result13.Content = "";
+                finall_result13.Background = System.Windows.Media.Brushes.Gray;
+                Finall_result14.Content = "";
+                finall_result14.Background = System.Windows.Media.Brushes.Gray;
+                Finall_result15.Content = "";
+                finall_result15.Background = System.Windows.Media.Brushes.Gray;
+                Finall_result16.Content = "";
+                finall_result16.Background = System.Windows.Media.Brushes.Gray;
+                Finall_result17.Content = "";
+                finall_result17.Background = System.Windows.Media.Brushes.Gray;
+                Finall_result18.Content = "";
+                finall_result18.Background = System.Windows.Media.Brushes.Gray;
+                Finall_result19.Content = "";
+                finall_result19.Background = System.Windows.Media.Brushes.Gray;
+                Finall_result20.Content = "";
+                finall_result20.Background = System.Windows.Media.Brushes.Gray;
+                Finall_result21.Content = "";
+                finall_result21.Background = System.Windows.Media.Brushes.Gray;
+                Finall_result22.Content = "";
+                finall_result22.Background = System.Windows.Media.Brushes.Gray;
+                Finall_result23.Content = "";
+                finall_result23.Background = System.Windows.Media.Brushes.Gray;
+            }));
+        }
+        private void ReSet_Click(object sender, RoutedEventArgs e)
+        {
+            ReSetUI();
+        }
+        //璁惧绠$悊
+        SmartScanner.ProductManager productManager = null;
+        private void ProductMaanager_Btn_Click(object sender, RoutedEventArgs e)
+        {
+            var loginWindow = new LoginWindow();
+            if (loginWindow.ShowDialog() == true)
+            {
+                if (productManager == null || !productManager.IsLoaded)
+                {
+                    productManager = new ProductManager();
+                    productManager.Closed += (s, args) => { productManager = null; };
+                    productManager.SetControlsEnabled(UserManager.HasAdministratorPrivilege());
+                    productManager.ShowDialog();
+                }
+                else
+                {
+                    if (productManager.WindowState == WindowState.Minimized)
+                    {
+                        productManager.WindowState = WindowState.Normal; // 鎭㈠绐楀彛鐘舵��
+                    }
+                    productManager.Activate(); // 濡傛灉绐楀彛宸插瓨鍦紝鍒欐縺娲诲畠
+                }
+            }
+        }
+        //妫�娴嬫柟妗�
+        SmartScanner.ResultJudge resultJudge = null;
+        private void ResultJudge_Btn_Click(object sender, RoutedEventArgs e)
+        {
+            var loginWindow = new LoginWindow();
+            if (loginWindow.ShowDialog() == true)
+            {
+                if (resultJudge == null || !resultJudge.IsLoaded)
+                {
+                    resultJudge = new ResultJudge();
+                    resultJudge.Closed += (s, args) => { resultJudge = null; };
+                    resultJudge.SetControlsEnabled(UserManager.HasAdministratorPrivilege());
+                    resultJudge.ShowDialog();
+                }
+                else
+                {
+                    if (resultJudge.WindowState == WindowState.Minimized)
+                    {
+                        resultJudge.WindowState = WindowState.Normal; // 鎭㈠绐楀彛鐘舵��
+                    }
+                    resultJudge.Activate(); // 濡傛灉绐楀彛宸插瓨鍦紝鍒欐縺娲诲畠
+                }
+            }
+        }
+        #region 杈撳嚭妯″紡閫夋嫨
+        private void OutputCheckBox_Checked(object sender, RoutedEventArgs e)
+        {
+            IsSignleOutput = true;
+            // 璁板綍鏃ュ織
+            OperateLogService.LogOperation(
+                "缁撴灉杈撳嚭妯″紡",
+                $"淇敼涓�: 鍗曠偣杈撳嚭",
+                null);
+        }
+
+        private void OutputCheckBox_Unchecked(object sender, RoutedEventArgs e)
+        {
+            IsSignleOutput = false;
+            // 璁板綍鏃ュ織
+            OperateLogService.LogOperation(
+                "缁撴灉杈撳嚭妯″紡",
+                $"淇敼涓�: 澶氱偣杈撳嚭",
+                null);
+        }
+        #endregion
+        // 鍥惧儚淇濆瓨璁剧疆
+        SmartScanner.DownloadData downloadData = null;
+        private void ImageSetup_Btn_Click(object sender, RoutedEventArgs e)
+        {
+            var loginWindow = new LoginWindow();
+            if (loginWindow.ShowDialog() == true)
+            {
+                if (downloadData == null || !downloadData.IsLoaded)
+                {
+                    downloadData = new DownloadData();
+                    downloadData.Closed += (s, args) => { downloadData = null; };
+                    downloadData.SetControlsEnabled(UserManager.HasAdministratorPrivilege());
+                    downloadData.ShowDialog();
+                }
+                else
+                {
+                    if (downloadData.WindowState == WindowState.Minimized)
+                    {
+                        downloadData.WindowState = WindowState.Normal; // 鎭㈠绐楀彛鐘舵��
+                    }
+                    downloadData.Activate(); // 濡傛灉绐楀彛宸插瓨鍦紝鍒欐縺娲诲畠
+                }
+            }
+        }
+        private void AddTestLog_Click(object sender, RoutedEventArgs e)
+        {
+            EnhancedLogViewModel.Instance.AddLog("杩欐槸涓�鏉℃櫘閫氫俊鎭�");
+            EnhancedLogViewModel.Instance.AddLog("杩欐槸涓�鏉¤鍛婁俊鎭�", "WARN");
+            EnhancedLogViewModel.Instance.AddLog("杩欐槸涓�鏉¢敊璇俊鎭�", "ERROR");
+            EnhancedLogViewModel.Instance.AddLog("杩欐槸涓�鏉¤皟璇曚俊鎭�", "DEBUG");
+        }
+        private void TCPClient_Connect_Click(object sender, RoutedEventArgs e)
+        {
+
+        }
+
+        private void TCPClient_ClearClientLogs_Click(object sender, RoutedEventArgs e)
+        {
+
+        }
+
+        private void btnViewLogs_Click(object sender, RoutedEventArgs e)
+        {
+            var operateLogView = new OperateLogView();
+            operateLogView.ShowDialog();
+        }
+
+        private void btnViewReports_Click(object sender, RoutedEventArgs e)
+        {
+            ExcelResultRecorder.OpenReportFolder();
+        }
+
+        private async void RestartButton_Click(object sender, RoutedEventArgs e)
+        {
+            if (MessageBox.Show("纭畾瑕侀噸鍚簲鐢ㄧ▼搴忓悧锛�", "纭閲嶅惎",
+            MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes)
+            {
+                Mouse.OverrideCursor = Cursors.Wait;
+                try
+                {
+                    await AppRestartHelper.RestartAsync();
+                }
+                finally
+                {
+                    Mouse.OverrideCursor = null;
+                }
+            }
+        }
+        #region 鐣岄潰鍥剧墖鏄剧ず鎸夐挳
+        private ImageDisplayWindow displayWindow;
+
+        private void finall_result0_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
+        {
+            displayWindow = new ImageDisplayWindow();
+            bool isShow = displayWindow.ShowImage_main(".\\vino_res\\result_1.jpg");
+            if (isShow)
+            {
+                displayWindow.Show();
+            }
+            else
+            {
+                return;
+            }
+        }
+
+        private void finall_result1_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
+        {
+            displayWindow = new ImageDisplayWindow();
+            bool isShow = displayWindow.ShowImage_main(".\\vino_res\\result_2.jpg");
+            if (isShow)
+            {
+                displayWindow.Show();
+            }
+            else
+            {
+                return;
+            }
+        }
+
+        private void finall_result2_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
+        {
+            displayWindow = new ImageDisplayWindow();
+            bool isShow = displayWindow.ShowImage_main(".\\vino_res\\result_3.jpg");
+            if (isShow)
+            {
+                displayWindow.Show();
+            }
+            else
+            {
+                return;
+            }
+
+        }
+
+        private void finall_result3_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
+        {
+            displayWindow = new ImageDisplayWindow();
+            bool isShow = displayWindow.ShowImage_main(".\\vino_res\\result_4.jpg");
+            if (isShow)
+            {
+                displayWindow.Show();
+            }
+            else
+            {
+                return;
+            }
+        }
+
+        private void finall_result4_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
+        {
+            displayWindow = new ImageDisplayWindow();
+            bool isShow = displayWindow.ShowImage_main(".\\vino_res\\result_5.jpg");
+            if (isShow)
+            {
+                displayWindow.Show();
+            }
+            else
+            {
+                return;
+            }
+        }
+
+        private void finall_result5_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
+        {
+            displayWindow = new ImageDisplayWindow();
+            bool isShow = displayWindow.ShowImage_main(".\\vino_res\\result_6.jpg");
+            if (isShow)
+            {
+                displayWindow.Show();
+            }
+            else
+            {
+                return;
+            }
+        }
+
+        private void finall_result6_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
+        {
+            displayWindow = new ImageDisplayWindow();
+            bool isShow = displayWindow.ShowImage_main(".\\vino_res\\result_7.jpg");
+            if (isShow)
+            {
+                displayWindow.Show();
+            }
+            else
+            {
+                return;
+            }
+        }
+
+        private void finall_result7_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
+        {
+            displayWindow = new ImageDisplayWindow();
+            bool isShow = displayWindow.ShowImage_main(".\\vino_res\\result_8.jpg");
+            if (isShow)
+            {
+                displayWindow.Show();
+            }
+            else
+            {
+                return;
+            }
+        }
+
+        private void finall_result8_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
+        {
+            displayWindow = new ImageDisplayWindow();
+            bool isShow = displayWindow.ShowImage_main(".\\vino_res\\result_9.jpg");
+            if (isShow)
+            {
+                displayWindow.Show();
+            }
+            else
+            {
+                return;
+            }
+
+        }
+
+        private void finall_result9_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
+        {
+            displayWindow = new ImageDisplayWindow();
+            bool isShow = displayWindow.ShowImage_main(".\\vino_res\\result_10.jpg");
+            if (isShow)
+            {
+                displayWindow.Show();
+            }
+            else
+            {
+                return;
+            }
+        }
+
+        private void finall_result10_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
+        {
+            displayWindow = new ImageDisplayWindow();
+            bool isShow = displayWindow.ShowImage_main(".\\vino_res\\result_11.jpg");
+            if (isShow)
+            {
+                displayWindow.Show();
+            }
+            else
+            {
+                return;
+            }
+        }
+
+        private void finall_result11_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
+        {
+            displayWindow = new ImageDisplayWindow();
+            bool isShow = displayWindow.ShowImage_main(".\\vino_res\\result_12.jpg");
+            if (isShow)
+            {
+                displayWindow.Show();
+            }
+            else
+            {
+                return;
+            }
+        }
+
+        private void finall_result12_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
+        {
+            displayWindow = new ImageDisplayWindow();
+            bool isShow = displayWindow.ShowImage_main(".\\vino_res\\result_13.jpg");
+            if (isShow)
+            {
+                displayWindow.Show();
+            }
+            else
+            {
+                return;
+            }
+
+        }
+
+        private void finall_result13_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
+        {
+            displayWindow = new ImageDisplayWindow();
+            bool isShow = displayWindow.ShowImage_main(".\\vino_res\\result_14.jpg");
+            if (isShow)
+            {
+                displayWindow.Show();
+            }
+            else
+            {
+                return;
+            }
+
+        }
+
+        private void finall_result14_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
+        {
+            displayWindow = new ImageDisplayWindow();
+            bool isShow = displayWindow.ShowImage_main(".\\vino_res\\result_15.jpg");
+            if (isShow)
+            {
+                displayWindow.Show();
+            }
+            else
+            {
+                return;
+            }
+        }
+
+        private void finall_result15_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
+        {
+            displayWindow = new ImageDisplayWindow();
+            bool isShow = displayWindow.ShowImage_main(".\\vino_res\\result_16.jpg");
+            if (isShow)
+            {
+                displayWindow.Show();
+            }
+            else
+            {
+                return;
+            }
+
+        }
+
+        private void finall_result16_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
+        {
+            displayWindow = new ImageDisplayWindow();
+            bool isShow = displayWindow.ShowImage_main(".\\vino_res\\result_17.jpg");
+            if (isShow)
+            {
+                displayWindow.Show();
+            }
+            else
+            {
+                return;
+            }
+
+        }
+
+        private void finall_result17_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
+        {
+            displayWindow = new ImageDisplayWindow();
+            bool isShow = displayWindow.ShowImage_main(".\\vino_res\\result_18.jpg");
+            if (isShow)
+            {
+                displayWindow.Show();
+            }
+            else
+            {
+                return;
+            }
+
+        }
+
+        private void finall_result18_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
+        {
+            displayWindow = new ImageDisplayWindow();
+            bool isShow = displayWindow.ShowImage_main(".\\vino_res\\result_19.jpg");
+            if (isShow)
+            {
+                displayWindow.Show();
+            }
+            else
+            {
+                return;
+            }
+        }
+
+        private void finall_result19_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
+        {
+            displayWindow = new ImageDisplayWindow();
+            bool isShow = displayWindow.ShowImage_main(".\\vino_res\\result_20.jpg");
+            if (isShow)
+            {
+                displayWindow.Show();
+            }
+            else
+            {
+                return;
+            }
+
+        }
+
+        private void finall_result20_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
+        {
+            displayWindow = new ImageDisplayWindow();
+            bool isShow = displayWindow.ShowImage_main(".\\vino_res\\result_21.jpg");
+            if (isShow)
+            {
+                displayWindow.Show();
+            }
+            else
+            {
+                return;
+            }
+        }
+
+        private void finall_result21_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
+        {
+            displayWindow = new ImageDisplayWindow();
+            bool isShow = displayWindow.ShowImage_main(".\\vino_res\\result_22.jpg");
+            if (isShow)
+            {
+                displayWindow.Show();
+            }
+            else
+            {
+                return;
+            }
+        }
+
+        private void finall_result22_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
+        {
+            displayWindow = new ImageDisplayWindow();
+            bool isShow = displayWindow.ShowImage_main(".\\vino_res\\result_23.jpg");
+            if (isShow)
+            {
+                displayWindow.Show();
+            }
+            else
+            {
+                return;
+            }
+
+        }
+
+        private void finall_result23_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
+        {
+            displayWindow = new ImageDisplayWindow();
+            bool isShow = displayWindow.ShowImage_main(".\\vino_res\\result_24.jpg");
+            if (isShow)
+            {
+                displayWindow.Show();
+            }
+            else
+            {
+                return;
+            }
+
+        }
+        #endregion
+        #region TCP/IP閫氳妯″潡
+        private void TCPServer_Start_Click(object sender, RoutedEventArgs e)
+        {
+            try
+            {
+                var ip = GetSelectedIP();
+                var port = GetSelectedPort();
+                var enableHeartbeat = TCPServer_EnableHeartbeat.IsChecked ?? false;
+                var heartbeatCommand = TCPServer_HeartbeatCommand.Text.Trim();
+                var heartbeatInterval = int.Parse(TCPServer_HeartbeatInterval.Text);
+                var outputIOCount = DeviceListBox.Items.Count;
+
+                // 楠岃瘉蹇冭烦璁剧疆
+                if (enableHeartbeat)
+                {
+                    if (string.IsNullOrWhiteSpace(heartbeatCommand))
+                    {
+                        MessageBox.Show("璇疯緭鍏ユ湁鏁堢殑蹇冭烦鎸囦护");
+                        return;
+                    }
+
+                    if (heartbeatInterval <= 0)
+                    {
+                        MessageBox.Show("蹇冭烦闂撮殧蹇呴』澶т簬0");
+                        return;
+                    }
+                }
+
+                _tcpServerManager = new TcpServerManager(
+                    enableHeartbeat,
+                    heartbeatCommand,
+                    heartbeatInterval,
+                    GetImageAndProcess,
+                    outputIOCount);
+
+                _tcpServerManager.LogMessage += msg => Dispatcher.Invoke(() =>
+                {
+                    TCPServer_LogsTextBox.AppendText($"{DateTime.Now:HH:mm:ss:fff} {msg}\n");
+                    TCPServer_LogsTextBox.ScrollToEnd();
+                });
+
+                _ = _tcpServerManager.StartAsync(ip, port);
+
+                TCPServer_Start.IsEnabled = false;
+                TCPServer_Stop.IsEnabled = true;
+                LinkState.Text = "TCP宸插惎鍔�";
+                LinkState.Foreground = System.Windows.Media.Brushes.LightGreen;
+            }
+            catch (Exception ex)
+            {
+                MessageBox.Show($"鍚姩鏈嶅姟鍣ㄥけ璐�: {ex.Message}");
+            }
+        }
+        private async Task<int[]> GetImageAndProcess()
+        {
+            try
+            {
+                usOutput_tcp = new int[DeviceListBox.Items.Count];
+                return await Task.Run(() =>
+                {
+                    GetImage();
+                    return usOutput_tcp; // 杩斿洖缁撴灉
+                }).ConfigureAwait(false);
+            }
+            catch (Exception ex)
+            {
+                MessageBox.Show($"鍥惧儚澶勭悊寮傚父: {ex.Message}");
+                throw; // 閲嶆柊鎶涘嚭浠ヨЕ鍙慣CP灞傜殑閿欒澶勭悊
+            }
+        }
+        private void TCPServer_Stop_Click(object sender, RoutedEventArgs e)
+        {
+            _tcpServerManager?.Stop();
+            TCPServer_Start.IsEnabled = true;
+            TCPServer_Stop.IsEnabled = false;
+            LinkState.Text = "鏈繛鎺�";
+            LinkState.Foreground = System.Windows.Media.Brushes.Red;
+        }
+
+        private void TCPServer_EnableHeartbeat_Checked(object sender, RoutedEventArgs e)
+        {
+            TCPServer_HeartbeatPanel.Visibility = Visibility.Visible;
+        }
+
+        private void TCPServer_EnableHeartbeat_Unchecked(object sender, RoutedEventArgs e)
+        {
+            TCPServer_HeartbeatPanel.Visibility = Visibility.Collapsed;
+        }
+
+        private void TCPServer_ClearLogs_Click(object sender, RoutedEventArgs e)
+        {
+            Dispatcher.Invoke(() =>
+            TCPServer_LogsTextBox.Clear());
+        }
+
+
+        private void RefreshIpButton_Click(object sender, RoutedEventArgs e)
+        {
+            TCPServer_IpComboBox.Items.Clear();
+
+            // 娣诲姞榛樿閫夐」
+            TCPServer_IpComboBox.Items.Add(new ComboBoxItem
+            {
+                Content = "0.0.0.0 (All Interfaces)"
+            });
+            TCPServer_IpComboBox.Items.Add(new ComboBoxItem
+            {
+                Content = "127.0.0.1 (Loopback)"
+            });
+
+            // 娣诲姞瀹為檯IP鍦板潃
+            foreach (var ip in GetAvailableIPs())
+            {
+                var item = new ComboBoxItem
+                {
+                    Content = $"{ip} ({GetNetworkInterfaceName(ip)})",
+                    Tag = ip // 瀛樺偍瀹為檯IP瀵硅薄
+                };
+                TCPServer_IpComboBox.Items.Add(item);
+            }
+
+            TCPServer_IpComboBox.SelectedIndex = 0;
+        }
+        private string GetNetworkInterfaceName(IPAddress ip)
+        {
+            foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
+            {
+                foreach (UnicastIPAddressInformation addr in nic.GetIPProperties().UnicastAddresses)
+                {
+                    if (addr.Address.Equals(ip))
+                    {
+                        return nic.Name;
+                    }
+                }
+            }
+            return "Unknown";
+        }
+        private List<IPAddress> GetAvailableIPs()
+        {
+            var ips = new List<IPAddress>();
+
+            // 鑾峰彇鎵�鏈夋椿鍔ㄧ殑缃戠粶鎺ュ彛
+            foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
+            {
+                // 鍙幏鍙栧凡鍚敤涓旈潪铏氭嫙鐨勬帴鍙�
+                if (nic.OperationalStatus != OperationalStatus.Up ||
+                    nic.NetworkInterfaceType == NetworkInterfaceType.Loopback)
+                    continue;
+
+                // 鑾峰彇IPv4鍦板潃
+                foreach (UnicastIPAddressInformation ip in nic.GetIPProperties().UnicastAddresses)
+                {
+                    if (ip.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
+                    {
+                        ips.Add(ip.Address);
+                    }
+                }
+            }
+
+            return ips;
+        }
+        /// <summary>
+        /// 鑾峰彇褰撳墠閫夋嫨鐨処P鍦板潃瀛楃涓�
+        /// </summary>
+        /// <returns>
+        /// "0.0.0.0" - 鎵�鏈夋帴鍙�
+        /// "127.0.0.1" - 鐜洖鍦板潃
+        /// "192.168.1.100" - 鍏蜂綋IP
+        /// </returns>
+        public string GetSelectedIP()
+        {
+            // 鎯呭喌1锛氱敤鎴锋墜鍔ㄨ緭鍏ワ紙IsEditable=true鏃讹級
+            if (!string.IsNullOrWhiteSpace(TCPServer_IpComboBox.Text))
+            {
+                if (IsValidIP(TCPServer_IpComboBox.Text))
+                    return TCPServer_IpComboBox.Text.Trim();
+            }
+
+            // 鎯呭喌2锛氫粠涓嬫媺椤归�夋嫨
+            if (TCPServer_IpComboBox.SelectedItem is ComboBoxItem item)
+            {
+                // 澶勭悊鐗规畩閫夐」
+                if (item.Content.ToString().Contains("0.0.0.0"))
+                    return "0.0.0.0";
+                if (item.Content.ToString().Contains("127.0.0.1"))
+                    return "127.0.0.1";
+
+                // 浠庡唴瀹逛腑鎻愬彇IP閮ㄥ垎锛堟牸寮忥細"IP (鎻忚堪)"锛�
+                var ipPart = item.Content.ToString().Split().FirstOrDefault();
+                if (IsValidIP(ipPart))
+                    return ipPart;
+            }
+
+            // 榛樿杩斿洖"0.0.0.0"
+            return "0.0.0.0";
+        }
+
+        // IP鍦板潃楠岃瘉鏂规硶
+        private bool IsValidIP(string ipString)
+        {
+            return IPAddress.TryParse(ipString, out _);
+        }
+        /// <summary>
+        /// 瀹夊叏鑾峰彇閫夋嫨鐨勭鍙e彿
+        /// </summary>
+        /// <returns>
+        /// 鎴愬姛杩斿洖鏈夋晥绔彛(1-65535)锛屽け璐ヨ繑鍥�-1骞舵樉绀洪敊璇彁绀�
+        /// </returns>
+        public int GetSelectedPort()
+        {
+            try
+            {
+                // 鎯呭喌1锛氫粠涓嬫媺椤归�夋嫨
+                if (TCPServer_PortComboBox.SelectedItem is ComboBoxItem selectedItem)
+                {
+                    if (int.TryParse(selectedItem.Content.ToString(), out int port) && IsValidPort(port))
+                        return port;
+                }
+
+                // 鎯呭喌2锛氭墜鍔ㄨ緭鍏ユ枃鏈�
+                if (!string.IsNullOrWhiteSpace(TCPServer_PortComboBox.Text))
+                {
+                    if (int.TryParse(TCPServer_PortComboBox.Text, out int manualPort) && IsValidPort(manualPort))
+                        return manualPort;
+                }
+
+                throw new ArgumentException("鏈�夋嫨鏈夋晥绔彛");
+            }
+            catch (Exception ex)
+            {
+                ShowPortError($"绔彛鑾峰彇澶辫触: {ex.Message}");
+                return -1;
+            }
+        }
+
+        // 绔彛鑼冨洿楠岃瘉
+        private bool IsValidPort(int port) => port > 0 && port <= 65535;
+
+        // 閿欒鎻愮ず鏂规硶
+        private void ShowPortError(string message)
+        {
+            MessageBox.Show(message, "绔彛閰嶇疆閿欒",
+                          MessageBoxButton.OK,
+                          MessageBoxImage.Error);
+        }
+        #endregion
+        #region 宸ョ▼鏂规璁剧疆妯″潡鎸夐挳浜嬩欢
+        private void BtnSelectParam_Click(object sender, RoutedEventArgs e)
+        {
+            RefreshDetectionPlanList();
+            if (cmbDetectionPlans.SelectedItem == null)
+            {
+                MessageBox.Show("璇峰厛閫夋嫨妫�娴嬫柟妗�", "鎻愮ず", MessageBoxButton.OK, MessageBoxImage.Warning);
+                return;
+            }
+
+            string selectedPlan = ((dynamic)cmbDetectionPlans.SelectedItem).FileName;
+            MessageBox.Show($"宸查�夋嫨妫�娴嬫柟妗�: {selectedPlan}", "妫�娴嬫柟妗堢‘璁�",
+                           MessageBoxButton.OK, MessageBoxImage.Information);
+        }
+
+        /// <summary>
+        /// 鍔犺浇妫�娴嬫柟妗堝垪琛�
+        /// </summary>
+        private void RefreshDetectionPlanList()
+        {
+            var plans = GetAvailableDetectionPlans()
+                .Select(name => new
+                {
+                    FileName = name,
+                    FullPath = Path.Combine("DetectionPlan", name)
+                }).ToList();
+
+            cmbDetectionPlans.ItemsSource = plans;
+            if (plans.Any()) cmbDetectionPlans.SelectedIndex = 0;
+        }
+
+        /// <summary>
+        /// 鑾峰彇鎵�鏈夊彲鐢ㄦ娴嬫柟妗�
+        /// </summary>
+        private string[] GetAvailableDetectionPlans()
+        {
+            string planPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "DetectionPlan");
+
+            if (!Directory.Exists(planPath))
+            {
+                Directory.CreateDirectory(planPath);
+                return Array.Empty<string>();
+            }
+
+            return Directory.GetFiles(planPath, "*.json")
+                           .Select(Path.GetFileName)
+                           .ToArray();
+        }
+
+        private void BtnConfirmModel_Click(object sender, RoutedEventArgs e)
+        {
+            if (cmbModels.SelectedItem == null)
+            {
+                MessageBox.Show("璇峰厛閫夋嫨妯″瀷鏂囦欢", "鎻愮ず", MessageBoxButton.OK, MessageBoxImage.Warning);
+                return;
+            }
+
+            string selectedModel = ((dynamic)cmbModels.SelectedItem).FileName;
+            MessageBox.Show($"宸查�夋嫨妯″瀷: {selectedModel}", "妯″瀷纭",
+                           MessageBoxButton.OK, MessageBoxImage.Information);
+        }
+        /// <summary>
+        /// 鍔犺浇妯″瀷鍒楄〃
+        /// </summary>
+        private void RefreshModelList()
+        {
+            var models = LBProjService.GetAvailableModels()
+                .Select(name => new
+                {
+                    FileName = name,
+                    FullPath = Path.Combine("model", name)
+                }).ToList();
+
+            cmbModels.ItemsSource = models;
+            if (models.Any()) cmbModels.SelectedIndex = 0;
+        }
+
+        private void BtnExport_Click(object sender, RoutedEventArgs e)
+        {
+            if (cmbModels.SelectedItem == null)
+            {
+                MessageBox.Show("璇峰厛鐐瑰嚮銆愮‘瀹氥�戞寜閽�夋嫨妯″瀷", "璀﹀憡", MessageBoxButton.OK, MessageBoxImage.Warning);
+                return;
+            }
+
+            // 鍥哄畾瀵煎嚭璺緞
+            string projectDir = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Project");
+            if (!Directory.Exists(projectDir))
+            {
+                Directory.CreateDirectory(projectDir);
+            }
+
+            var saveDialog = new System.Windows.Forms.SaveFileDialog
+            {
+                Title = "瀵煎嚭 LBProj 宸ョ▼",
+                Filter = "LBProj鏂囦欢|*.lbproj",
+                FileName = $"project_{DateTime.Now:yyyyMMdd_HHmmss}",
+                InitialDirectory = projectDir
+            };
+
+            if (saveDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
+            {
+                string modelName = ((dynamic)cmbModels.SelectedItem).FileName;
+                // 浣跨敤鍥哄畾璺緞鐨勬娴嬫柟妗堟枃浠�
+                string detectionPlanPath = cmbDetectionPlans.SelectedItem != null ?
+                    Path.Combine("DetectionPlan", ((dynamic)cmbDetectionPlans.SelectedItem).FileName) :
+                    "";
+
+                var (success, message) = LBProjService.CreateLBProj(
+                    detectionPlanPath,
+                    modelName,
+                    saveDialog.FileName);
+
+                if (success)
+                {
+                    Properties.Settings.Default.LastConfigFilePath_Proj = saveDialog.FileName;
+                    Properties.Settings.Default.Save();
+                    MessageBox.Show($"宸ョ▼宸叉垚鍔熶繚瀛樺埌: {saveDialog.FileName}", "鎴愬姛", MessageBoxButton.OK, MessageBoxImage.Information);
+                    OperateLogService.LogOperation("宸ョ▼鏂囦欢淇敼", $"宸ョ▼鏂囦欢淇敼涓�: {saveDialog.FileName}", null);
+                    //txtExportPath.Text = saveDialog.FileName;
+                }
+                else
+                {
+                    MessageBox.Show(message, "閿欒", MessageBoxButton.OK, MessageBoxImage.Error);
+                }
+            }
+        }
+
+        private void BtnLoad_Click(object sender, RoutedEventArgs e)
+        {
+            //RefreshProjectList();
+            if (cmbProjects.SelectedItem == null)
+            {
+                MessageBox.Show("璇峰厛閫夋嫨宸ョ▼鏂囦欢", "鎻愮ず", MessageBoxButton.OK, MessageBoxImage.Warning);
+                return;
+            }
+
+            string selectedProject = ((dynamic)cmbProjects.SelectedItem).FullPath;
+            var (modelName, configPath, configContent, message) = LBProjService.LoadLBProj(selectedProject);
+            config = JsonConvert.DeserializeObject<ResultJudge.JudgmentConfiguration>(configContent);
+            if (modelName != null)
+            {
+                // 鏇存柊妯″瀷閫夋嫨
+                foreach (var item in cmbModels.Items)
+                {
+                    if (((dynamic)item).FileName == modelName)
+                    {
+                        cmbModels.SelectedItem = item;
+                        break;
+                    }
+                }
+                if (detector != IntPtr.Zero)
+                {
+                    DisposeDetector_CPU(detector);
+                }
+                Task.Run(() =>
+                {
+                    // 妯″瀷鎺ㄧ悊寮曟搸閫夋嫨
+                    detector = CreateDetector_CPU();
+                    bool isLoadModel = InitializeDetector_CPU(detector, Detector_Device, $".\\model\\{modelName}");
+                    while (true)
+                    {
+                        if (isLoadModel)
+                        {
+                            EnhancedLogViewModel.Instance.AddLog($"妯″瀷缂栬瘧鎴愬姛");
+                            break;
+                        }
+                    }
+                });
+                Properties.Settings.Default.LastConfigFilePath_Proj = selectedProject;
+                Properties.Settings.Default.Save();
+                //txtParamPath.Text = configPath;
+                //cmbModels.ItemsSource = modelName.ToString();
+                MessageBox.Show($"宸插姞杞芥ā鍨�: {modelName}\n{message}", "鎴愬姛",
+                    MessageBoxButton.OK, MessageBoxImage.Information);
+                this.Dispatcher.BeginInvoke(new Action(() =>
+                {
+                    ProjectState.Foreground = System.Windows.Media.Brushes.LightGreen;
+                    ModelState.Foreground = System.Windows.Media.Brushes.LightGreen;
+                    ProjectState.Text = selectedProject;
+                    ModelState.Text = modelName;
+                }));
+                EnhancedLogViewModel.Instance.AddLog($"宸插姞杞藉伐绋嬫枃浠�: {selectedProject}锛屾ā鍨嬶細{modelName}");
+            }
+            else
+            {
+                MessageBox.Show(message, "閿欒", MessageBoxButton.OK, MessageBoxImage.Error);
+            }
+        }
+
+        /// <summary>
+        /// 鍔犺浇宸ョ▼鏂囦欢鍒楄〃
+        /// </summary>
+        private void RefreshProjectList()
+        {
+            var projects = GetAvailableProjects()
+                .Select(name => new
+                {
+                    FileName = name,
+                    FullPath = Path.Combine("Project", name)
+                }).ToList();
+
+            cmbProjects.ItemsSource = projects;
+            if (projects.Any()) cmbProjects.SelectedIndex = 0;
+        }
+
+        /// <summary>
+        /// 鑾峰彇鎵�鏈夊彲鐢ㄥ伐绋嬫枃浠�
+        /// </summary>
+        private string[] GetAvailableProjects()
+        {
+            string projectPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Project");
+
+            if (!Directory.Exists(projectPath))
+            {
+                Directory.CreateDirectory(projectPath);
+                return Array.Empty<string>();
+            }
+
+            return Directory.GetFiles(projectPath, "*.lbproj")
+                           .Select(Path.GetFileName)
+                           .ToArray();
+        }
+
+        private void BtnRefreshModels_Click(object sender, RoutedEventArgs e)
+        {
+            RefreshModelList();
+            RefreshDetectionPlanList();
+            RefreshProjectList();
+            MessageBox.Show("妯″瀷銆佹娴嬫柟妗堝拰宸ョ▼鏂囦欢鍒楄〃宸插埛鏂�", "鎻愮ず", MessageBoxButton.OK, MessageBoxImage.Information);
+        }
+        #endregion
+        #region 鐗堟湰璇存槑鍔熻兘
+        private void VersionButton_Click(object sender, RoutedEventArgs e)
+        {
+            ShowVersionInfo();
+        }
+
+        private void ShowVersionInfo()
+        {
+            try
+            {
+                // 璇诲彇鐗堟湰璇存槑鏂囦欢
+                string versionFile = "鐗堟湰璇存槑.txt";
+                if (File.Exists(versionFile))
+                {
+                    string versionContent = File.ReadAllText(versionFile);
+
+                    // 瑙f瀽鐗堟湰璇存槑鏂囦欢锛屾彁鍙栨渶鏂扮増鏈俊鎭�
+                    var versionLines = versionContent.Split('\n');
+                    string latestVersion = "";
+                    string latestDate = "";
+                    string latestChanges = "";
+
+                    // 浠庢渶鍚庝竴琛屽悜鍓嶆煡鎵炬渶鏂扮殑鐗堟湰淇℃伅
+                    for (int i = versionLines.Length - 1; i >= 0; i--)
+                    {
+                        if (versionLines[i].Contains("v") && versionLines[i].Contains("."))
+                        {
+                            // 鎻愬彇鐗堟湰鏃ユ湡鍜岀増鏈彿
+                            var parts = versionLines[i].Trim().Split(' ');
+                            foreach (var part in parts)
+                            {
+                                if (part.Contains(".") && part.Length > 0)
+                                {
+                                    if (part.StartsWith("v") || part.Contains("v"))
+                                    {
+                                        latestVersion = part.Trim();
+                                    }
+                                    else if (char.IsDigit(part[0]))
+                                    {
+                                        latestDate = part.Trim();
+                                    }
+                                }
+                            }
+
+                            // 鏌ユ壘璇ョ増鏈殑鏇存柊鍐呭
+                            for (int j = i + 1; j < versionLines.Length; j++)
+                            {
+                                string contentLine = versionLines[j].Trim();
+
+                                // 鍋滄鏉′欢锛氱┖琛屾垨鏂扮殑鐗堟湰琛�
+                                if (string.IsNullOrEmpty(contentLine) ||
+                                    (contentLine.Contains("v") && contentLine.Contains(".") && contentLine.Length > 8))
+                                {
+                                    break;
+                                }
+
+                                // 娣诲姞鎵�鏈夐潪绌哄唴瀹硅
+                                if (contentLine.Length > 0)
+                                {
+                                    latestChanges += contentLine + "\n";
+                                }
+
+                                // 鏈�澶氳鍙�8琛屽唴瀹�
+                                if (j - i > 8)
+                                {
+                                    break;
+                                }
+                            }
+
+                            // 鏄剧ず鐗堟湰淇℃伅瀵硅瘽妗�
+                            string message = $"褰撳墠杞欢鐗堟湰: {latestVersion}\n" +
+                                           $"鍙戝竷鏃ユ湡: {latestDate}\n\n" +
+                                           $"鏈�鏂版洿鏂板唴瀹�:\n{latestChanges}\n" +
+                                           $"瀹屾暣鐗堟湰鍘嗗彶璁板綍璇锋煡鐪嬬増鏈鏄�.txt鏂囦欢";
+
+                            MessageBox.Show(message, "杞欢鐗堟湰璇存槑", MessageBoxButton.OK, MessageBoxImage.Information);
+                            return;
+                        }
+                    }
+
+                    // 濡傛灉娌℃湁鎵惧埌鐗堟湰淇℃伅锛屾樉绀洪粯璁ゆ彁绀�
+                    MessageBox.Show("鐗堟湰璇存槑鏂囦欢涓湭鎵惧埌鏈夋晥鐨勭増鏈俊鎭�", "鎻愮ず", MessageBoxButton.OK, MessageBoxImage.Information);
+                }
+                else
+                {
+                    MessageBox.Show("鐗堟湰璇存槑鏂囦欢涓嶅瓨鍦�", "閿欒", MessageBoxButton.OK, MessageBoxImage.Warning);
+                }
+            }
+            catch (Exception ex)
+            {
+                MessageBox.Show($"璇诲彇鐗堟湰淇℃伅鏃跺嚭閿�: {ex.Message}", "閿欒", MessageBoxButton.OK, MessageBoxImage.Error);
+            }
+        }
+        #endregion
+    }
+}
+
+

--
Gitblit v1.9.3