C3204
2026-01-15 577926fdf6836eb7506d2dff189a9d18b0aeb932
LB_VisionProcesses/Cameras/LBCameras/LBCamera.cs
@@ -1,18 +1,29 @@
using LB_SmartVisionCameraDevice.PHM6000;
using LB_SmartVisionCameraSDK.PHM6000;
using LB_SmartVisionCommon;
using LB_VisionProcesses.Cameras;
using Sunny.UI.Win32;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using LB_SmartVisionCameraSDK.PHM6000;
using LB_VisionProcesses.Cameras;
using LB_SmartVisionCommon;
using LB_SmartVisionCameraDevice.PHM6000;
namespace LB_VisionProcesses.Cameras.LBCameras
{
    public class LBCameraEventArgs : CameraEventArgs
    {
        public bool IsComplete { get; set; }
        public LBCameraEventArgs(string sn, Bitmap bitmap, bool isComplete) : base(sn, bitmap)
        {
            IsComplete = isComplete;
        }
    }
    /// <summary>
    /// LB3D工业相机实现类
    /// 基于PHM6000系列封装
@@ -21,14 +32,27 @@
    {
        private IntPtr _cameraHandle = IntPtr.Zero;
        private PHM6000SensorConfig _sensorConfig;
        // 采集回调
        private AcquisitionCallbackZA _acquisitionCallback;
        private AcquisitionCompletedCallback _acquisitionCompletedCallback;
        private bool _isConnected = false;
        private int _frameCount = 0; // 采集帧计数
        // 图像缓冲
        private List<byte[]> _lineDataBuffer = new List<byte[]>();
        private readonly object _bufferLock = new object();
        private byte[] _rawPixelBuffer = null; // 用于存储整张图的像素数据 (8bpp)
        private int _currentBitmapHeight = 0;
        private int _currentBitmapWidth = 0;
        private int _currentLineCount = 0;
        private object _bufferLock = new object();
        private bool _isBufferReady = false;
        // 临时行缓冲,用于接收回调数据
        private byte[] _tempLineBuffer = null;
        private bool _isContinuous = false;
        // 新增:CollectedImages操作锁,保证线程安全
        private readonly object _collectedImagesLock = new object();
        public LBCamera()
        {
@@ -40,6 +64,12 @@
        public override bool InitDevice(string sn, object handle = null)
        {
            // 如果已连接,直接返回true
            if (_isConnected && _cameraHandle != IntPtr.Zero)
            {
                return true;
            }
            IntPtr tempHandle = IntPtr.Zero;
            try
            {
@@ -70,9 +100,8 @@
                    {
                        string currentSn = Encoding.UTF8.GetString(serialNumberBytes).TrimEnd('\0');
                        
                        // 如果传入的 sn 是 IP 地址,则直接尝试匹配 IP
                        // 或者匹配序列号
                        if (currentSn == sn || sn.Contains(currentSn)) // 简单匹配逻辑
                        // 匹配SN或IP
                        if (currentSn == sn || sn.Contains(currentSn))
                        {
                            byte[] addressBytes = new byte[64];
                            int port = 0;
@@ -87,17 +116,15 @@
                    }
                }
                // 销毁临时句柄
                PHM6000Profiler.DestroyCameraEntry(tempHandle);
                tempHandle = IntPtr.Zero;
                if (!found)
                {
                    // 如果没找到但 sn 本身看起来像 IP,尝试直接连接(兼容旧逻辑)
                    if (System.Net.IPAddress.TryParse(sn, out _))
                    {
                        targetIp = sn;
                        targetPort = 5577; // 默认端口
                        targetPort = 5577;
                    }
                    else
                    {
@@ -119,14 +146,24 @@
                    // 加载相机当前参数到 _sensorConfig
                    SyncConfigFromCamera();
                    // 初始化回调
                    _acquisitionCallback = new AcquisitionCallbackZA(OnLineReceived);
                    _acquisitionCompletedCallback = new AcquisitionCompletedCallback(OnAcquisitionCompleted);
                    // 初始化并注册采集回调 (获取数据用)
                    _acquisitionCallback = new AcquisitionCallbackZA(OnAcquisitionCallbackZA);
                    PHM6000Profiler.SetAcquisitionCallbackZA(_cameraHandle, _acquisitionCallback, IntPtr.Zero);
                    // 初始化并注册采集完成回调 (状态通知用)
                    _acquisitionCompletedCallback = new AcquisitionCompletedCallback(OnAcquisitionCompleted);
                    PHM6000Profiler.RegisterAcquisitionCompletedCallback(_cameraHandle, _acquisitionCompletedCallback, IntPtr.Zero);
                    // 强制应用当前配置(确保触发模式等参数正确,避免相机处于未知状态)
                    UpdateSensorConfig(_sensorConfig);
                    AsyncLogHelper.Info($"LBCamera[{SN}]: Connected and initialized successfully (Manual Data Mode)");
                    return true;
                }
                else
                {
                    AsyncLogHelper.Error($"LBCamera[{SN}]: ConnectToCamera failed, result={result}");
                }
            }
            catch (Exception ex) 
@@ -145,6 +182,7 @@
                PHM6000Profiler.DestroyCameraEntry(_cameraHandle);
                _cameraHandle = IntPtr.Zero;
                _isConnected = false;
                AsyncLogHelper.Info($"LBCamera[{SN}]: Closed");
            }
            return true;
        }
@@ -166,8 +204,6 @@
                        if (PHM6000Profiler.GetCameraInformation(tempHandle, i, moduleTypeBytes, serialNumberBytes) == 0)
                        {
                            string sn = Encoding.UTF8.GetString(serialNumberBytes).TrimEnd('\0');
                            string type = Encoding.UTF8.GetString(moduleTypeBytes).TrimEnd('\0');
                            // 格式参考:PHM6000[SN123456]
                            if (!string.IsNullOrEmpty(sn))
                            {
                                cameraList.Add(sn);
@@ -178,7 +214,7 @@
            }
            catch (Exception ex)
            {
                AsyncLogHelper.Error($"LBCamera: GetListEnum异常 - {ex.Message}");
                AsyncLogHelper.Error($"LBCamera: 获取设备列表异常 - {ex.Message}");
            }
            finally
            {
@@ -188,18 +224,57 @@
            return cameraList;
        }
        public override bool StartGrabbing()
        private void InitBuffer()
        {
            if (!_isConnected) return false;
            lock (_bufferLock)
            {
                _lineDataBuffer.Clear();
                _currentBitmapHeight = _sensorConfig.ScanLineCount > 0 ? _sensorConfig.ScanLineCount : 5000;
                // 宽度在第一行数据到达时确定
                _currentBitmapWidth = 0;
                _rawPixelBuffer = null;
                _currentLineCount = 0;
                _isBufferReady = false;
            }
        }
            // 设置采集模式:1=扫描模式,1=连续模式
        public override bool StartGrabbing()
        {
            // 默认连续模式
            return StartSingleGrab();
        }
        public bool StartSingleGrab()
        {
            if (!_isConnected) return false;
            _isContinuous = false;
            InitBuffer();
            AsyncLogHelper.Info($"LBCamera[{SN}]: 开始单次采集");
            // 1=扫描模式, 0=单次
            PHM6000Profiler.SetAcquisitionMode(_cameraHandle, 1, 0);
            int result = PHM6000Profiler.StartAcquisition(_cameraHandle, 0, 0, 0.0);
            if (result == 0)
            {
                isGrabbing = true;
                return true;
            }
            return false;
        }
        public override bool StartContinuousGrab()
        {
            if (!_isConnected) return false;
            _isContinuous = true;
            InitBuffer();
            AsyncLogHelper.Info($"LBCamera[{SN}]:开始连续采集");
            // 1=扫描模式, 1=连续
            PHM6000Profiler.SetAcquisitionMode(_cameraHandle, 1, 1);
            int result = PHM6000Profiler.StartAcquisition(_cameraHandle, 0, 0, 0.0);
            if (result == 0)
            {
                isGrabbing = true;
@@ -210,28 +285,62 @@
        public override bool StopGrabbing()
        {
            _isContinuous = false;
            if (!_isConnected) return true;
            PHM6000Profiler.StopAcquisition(_cameraHandle);
            // 停止时如果有未显示的缓存数据,将其显示出来(支持显示不完整的帧)
            lock (_bufferLock)
            {
                if (_currentLineCount > 0)
                {
                    AsyncLogHelper.Info($"LBCamera[{SN}]: Flushing partial buffer ({_currentLineCount} lines) on stop");
                    CreateAndFireBitmap();
                    _currentLineCount = 0;
                }
            }
            isGrabbing = false;
            return true;
        }
        public override bool SoftTrigger()
        {
            // 线扫相机通常不需要传统软触发,但在某些模式下可模拟
            return true;
        }
        public override bool StartWith_SoftTriggerModel() => StartContinuousGrab();
        public override bool StartWith_HardTriggerModel(TriggerSource hardtriggeritem = TriggerSource.Line0) => StartSingleGrab();
        public override bool SoftTrigger() => true;
        #region 参数设置映射
        public override bool SetExpouseTime(double value) => SetParam(EnumNameId.ExposureTime, (float)value);
        public override bool GetExpouseTime(out double value) { float v; bool r = GetParam(EnumNameId.ExposureTime, out v); value = v; return r; }
        public override bool SetGain(double gain) => SetParam(EnumNameId.AnalogGain, (float)gain);
        public override bool GetGain(out double gain) { float v; bool r = GetParam(EnumNameId.AnalogGain, out v); gain = v; return r; }
        public override bool SetGain(double gain) => SetParam(EnumNameId.AnalogGain, (int)gain);
        public override bool GetGain(out double gain) { int v; bool r = GetParam(EnumNameId.AnalogGain, out v); gain = v; return r; }
        // 其他接口占位实现
        public override bool SetTriggerMode(TriggerMode mode, TriggerSource triggerEnum = TriggerSource.Line0) => true;
        public override bool GetTriggerMode(out TriggerMode mode, out TriggerSource source) { mode = TriggerMode.Off; source = TriggerSource.Software; return true; }
        public override bool SetTriggerMode(TriggerMode mode, TriggerSource triggerEnum = TriggerSource.Line0)
        {
            if (!_isConnected) return false;
            if (triggerEnum == TriggerSource.Software)
            {
                _sensorConfig.LineScanTriggerSource = EnumLineScanTriggerSource.固定频率;
                _sensorConfig.DataAcquisitionTriggerSource = EnumDataAcquisitionTriggerSource.软触发;
            }
            else
            {
                _sensorConfig.LineScanTriggerSource = EnumLineScanTriggerSource.编码器;
                _sensorConfig.DataAcquisitionTriggerSource = EnumDataAcquisitionTriggerSource.外部触发;
            }
            UpdateSensorConfig(_sensorConfig);
            return true;
        }
        public override bool GetTriggerMode(out TriggerMode mode, out TriggerSource source)
        {
            mode = TriggerMode.On;
            source = _sensorConfig.DataAcquisitionTriggerSource == EnumDataAcquisitionTriggerSource.软触发 ? TriggerSource.Software : TriggerSource.Line0;
            return true;
        }
        public override bool SetTriggerPolarity(TriggerPolarity polarity) => true;
        public override bool GetTriggerPolarity(out TriggerPolarity polarity) { polarity = TriggerPolarity.RisingEdge; return true; }
        public override bool SetTriggerFliter(double flitertime) => true;
@@ -242,6 +351,64 @@
        public override bool SetLineStatus(IOLines line, LineStatus linestatus) => true;
        public override bool GetLineStatus(IOLines line, out LineStatus lineStatus) { lineStatus = LineStatus.Low; return true; }
        public override bool AutoBalanceWhite() => true;
        public override void SetCamConfig(CameraConfig config) { }
        public override void GetCamConfig(out CameraConfig config) { config = new CameraConfig(null); }
        public override bool GetImage(out Bitmap bitmap, int outtime = 3000) { bitmap = null; return false; }
        public override bool GetImageWithSoftTrigger(out Bitmap bitmap, int outtime = 3000)
        {
            // 简单实现:软触发等待
            bitmap = null;
            if(!_isConnected) return false;
            // 计算理论最小耗时 (仅当使用固定频率触发时)
            int minTime = 0;
            if (_sensorConfig.LineScanTriggerSource == EnumLineScanTriggerSource.固定频率)
            {
                float rate = _sensorConfig.SoftwareTriggerRate > 0 ? _sensorConfig.SoftwareTriggerRate : 1000f;
                int lines = _sensorConfig.ScanLineCount > 0 ? _sensorConfig.ScanLineCount : 5000;
                minTime = (int)((lines / rate) * 1000);
            }
            // 如果传入超时时间不够,自动延长
            int actualTimeout = outtime;
            if (actualTimeout < minTime + 2000)
            {
                actualTimeout = minTime + 3000; // 预留3秒余量
                AsyncLogHelper.Warn($"LBCamera: Provided timeout {outtime}ms is too short for {minTime}ms scan. Extended to {actualTimeout}ms.");
            }
            using (AutoResetEvent waitHandle = new AutoResetEvent(false))
            {
                Bitmap res = null;
                EventHandler<CameraEventArgs> handler = (s, e) => {
                    if(e.Bitmap != null) {
                         res = e.Bitmap.Clone() as Bitmap;
                         waitHandle.Set();
                    }
                };
                ImageGrabbed += handler;
                if (StartSingleGrab())
                {
                    if (!waitHandle.WaitOne(actualTimeout))
                    {
                        AsyncLogHelper.Error($"LBCamera: GetImageWithSoftTrigger timeout after {actualTimeout}ms");
                    }
                }
                else
                {
                    AsyncLogHelper.Error("LBCamera: StartSingleGrab failed");
                }
                ImageGrabbed -= handler;
                // 确保停止采集
                StopGrabbing();
                bitmap = res;
                return bitmap != null;
            }
        }
        public PHM6000SensorConfig GetSensorConfig()
        {
@@ -252,93 +419,337 @@
        public void UpdateSensorConfig(PHM6000SensorConfig config)
        {
            _sensorConfig = config;
            // 简单示例:设置曝光和增益
            SetExpouseTime(config.ExposureTime);
            SetGain((double)config.AnalogGain);
            // 更多参数同步逻辑应在此处实现
            if (!_isConnected) return;
            SetParam(EnumNameId.ExposureTime, (float)config.ExposureTime);
            SetParam(EnumNameId.AnalogGain, (float)config.AnalogGain);
            PHM6000Profiler.SetProfilerParameter(_cameraHandle, (int)EnumNameId.ScanLineCount, config.ScanLineCount, 0, 0);
            PHM6000Profiler.SetProfilerParameter(_cameraHandle, (int)EnumNameId.LineScanTriggerSource, 0, 0, (int)config.LineScanTriggerSource);
            PHM6000Profiler.SetProfilerParameter(_cameraHandle, (int)EnumNameId.DataAcquisitionTriggerSource, 0, 0, (int)config.DataAcquisitionTriggerSource);
            if (config.LineScanTriggerSource == EnumLineScanTriggerSource.固定频率)
            {
                PHM6000Profiler.SetProfilerParameter(_cameraHandle, (int)EnumNameId.SoftwareTriggerRate, 0, config.SoftwareTriggerRate, 0);
            }
            PHM6000Profiler.SaveAllParametersToDevice(_cameraHandle);
        }
        #endregion
        #endregion
        #region Private Callback & Helpers
        #region Callbacks
        private void OnLineReceived(IntPtr pInstance, IntPtr buffer, int points)
        private void OnAcquisitionCallbackZA(IntPtr pInstance, IntPtr buffer, int points)
        {
                // 实时回调处理:累积行数据
                if (!isGrabbing) return;
            if (buffer == IntPtr.Zero || points <= 0) return;
                int lineSize = points * Marshal.SizeOf(typeof(LBPointZA));
                byte[] lineData = new byte[lineSize];
                Marshal.Copy(buffer, lineData, 0, lineSize);
                lock (_bufferLock)
            lock (_bufferLock)
            {
                // 初始化缓冲区
                if (_rawPixelBuffer == null)
                {
                    _lineDataBuffer.Add(lineData);
                    _currentLineCount++;
                    _currentBitmapWidth = points;
                    if (_currentBitmapHeight <= 0) _currentBitmapHeight = 2000; // 默认防呆
                    _rawPixelBuffer = new byte[_currentBitmapWidth * _currentBitmapHeight];
                    _currentLineCount = 0;
                }
                if (_currentLineCount >= _currentBitmapHeight) return; // 缓冲区满,忽略多余数据
                // 准备临时缓冲区接收行数据 (LBPointZA = 8 bytes)
                int lineBytes = points * 8;
                if (_tempLineBuffer == null || _tempLineBuffer.Length != lineBytes)
                {
                    _tempLineBuffer = new byte[lineBytes];
                }
                // 拷贝非托管内存到托管数组
                Marshal.Copy(buffer, _tempLineBuffer, 0, lineBytes);
                // 提取灰度(Intensity/Alpha)数据填充到 _rawPixelBuffer
                // LBPointZA结构: float(4) + res(3) + alpha(1). Alpha在偏移7
                int bufferOffset = _currentLineCount * _currentBitmapWidth;
                for (int i = 0; i < points; i++)
                {
                    if (bufferOffset + i < _rawPixelBuffer.Length)
                    {
                        _rawPixelBuffer[bufferOffset + i] = _tempLineBuffer[i * 8 + 7];
                    }
                }
                _currentLineCount++;
                // 如果达到预定高度,生成图像
                if (_currentLineCount >= _currentBitmapHeight)
                {
                    CreateAndFireBitmap();
                    // 重置,准备下一帧 (如果是连续采集)
                    _currentLineCount = 0;
                    // _rawPixelBuffer 可以复用,不需要置空
                }
            }
        }
        private void OnAcquisitionCompleted(IntPtr pInstance, int nOption)
        {
                // nOption: 0=一批数据结束, 1=全部完成, 2=点云就绪
                if (nOption == 1 || nOption == 0)
            // nOption: 0=Batch End, 1=All End(Single), 2=Processing End
            // 此处主要用于日志或状态监控
            // 实际图像生成在 Data Callback 中完成
            if (nOption == 1) // 单次采集结束
            {
                if (_isContinuous && isGrabbing)
                {
                    GenerateIntensityMap();
                    // 如果在连续模式下收到结束信号,尝试自动重启采集
                    AsyncLogHelper.Info($"LBCamera[{SN}]: Continuous mode frame ended, restarting...");
                    Task.Run(() =>
                    {
                        if (_isContinuous && _isConnected)
                        {
                            PHM6000Profiler.StartAcquisition(_cameraHandle, 0, 0, 0.0);
                        }
                    });
                }
                else
                {
                    isGrabbing = false;
                    AsyncLogHelper.Info($"LBCamera[{SN}]: Single grab completed by SDK");
                    // 单次采集结束时,如果有未显示的缓冲数据,立即生成图像
                    // 防止因数据量不足(小于ScanLineCount)导致GetImageWithSoftTrigger一直等待
                    lock (_bufferLock)
                    {
                        if (_currentLineCount > 0)
                        {
                            AsyncLogHelper.Info($"LBCamera[{SN}]: Flushing partial buffer ({_currentLineCount} lines) on completion");
                            CreateAndFireBitmap();
                            _currentLineCount = 0;
                        }
                    }
                }
            }
        }
        private void GenerateIntensityMap()
        private void CreateAndFireBitmap()
        {
            if (_cameraHandle == IntPtr.Zero) return;
            int width = 0;
            int height = 0;
            // 直接从 SDK 获取合并后的强度数据指针 (unsigned char*)
            IntPtr pIntensity = PHM6000Profiler.GetIntensityData(_cameraHandle, ref width, ref height);
            if (pIntensity == IntPtr.Zero || width <= 0 || height <= 0) return;
            try
            {
                int width = _currentBitmapWidth;
                int height = _currentLineCount; // 使用实际采集到的行数
                if (width <= 0 || height <= 0 || _rawPixelBuffer == null) return;
                Bitmap bmp = new Bitmap(width, height, PixelFormat.Format8bppIndexed);
                // 设置灰度调色板
                ColorPalette palette = bmp.Palette;
                for (int i = 0; i < 256; i++) palette.Entries[i] = Color.FromArgb(i, i, i);
                for (int i = 0; i < 256; i++)
                {
                    palette.Entries[i] = Color.FromArgb(i, i, i);
                }
                bmp.Palette = palette;
                // 拷贝数据
                BitmapData bmpData = bmp.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.WriteOnly, PixelFormat.Format8bppIndexed);
                
                // 高性能内存拷贝
                int size = width * height;
                byte[] managedData = new byte[size];
                Marshal.Copy(pIntensity, managedData, 0, size);
                Marshal.Copy(managedData, 0, bmpData.Scan0, size);
                // 注意:Bitmap Stride 可能不等于 Width,需要逐行拷贝
                int stride = bmpData.Stride;
                IntPtr ptr = bmpData.Scan0;
                for (int y = 0; y < height; y++)
                {
                    // 确保不越界
                    if ((y * width) + width <= _rawPixelBuffer.Length)
                    {
                        Marshal.Copy(_rawPixelBuffer, y * width, ptr + y * stride, width);
                    }
                }
                bmp.UnlockBits(bmpData);
                // 触发事件通知 UI 更新亮度图
                ImageGrabbed?.Invoke(this, new CameraEventArgs(SN, bmp));
                _frameCount++;
                AsyncLogHelper.Info($"LBCamera[{SN}]: Frame {_frameCount} generated ({width}x{height})");
                //空值校验:转换失败则直接返回
                if (bmp == null)
                {
                    AsyncLogHelper.Warn(SN + "帧转换为Bitmap失败,跳过处理");
                    return;
                }
                // 线程安全地将Bitmap添加到CollectedImages字典
                lock (_collectedImagesLock)
                {
                    // 确保当前相机SN对应的列表存在
                    if (!CollectedImages.ContainsKey(SN))
                    {
                        CollectedImages[SN] = new List<Bitmap>();
                    }
                    CollectedImages[SN].Add(bmp);
                    AsyncLogHelper.Info(SN + $"图像已加入缓存,当前缓存数量:{CollectedImages[SN].Count}");
                }
                // 处理CollectedImages中的图像:遍历消费列表第一个元素直到为空
                ProcessCollectedImages();
                //// 异步触发事件,避免阻塞SDK回调线程
                //Task.Factory.StartNew(() =>
                //{
                //    try
                //    {
                //        ImageGrabbed?.Invoke(this, new LBCameraEventArgs(SN, bmp, true));
                //        CallBackImg = (Bitmap)bmp.Clone();
                //        if (CallBackImg == null)
                //        {
                //            return;
                //        }
                //        if (GetTriggerMode(out TriggerMode mode, out TriggerSource source))
                //        {
                //            if (mode == TriggerMode.On && source != TriggerSource.Software)
                //                TriggerRunMessageReceived?.Invoke(SN, source.ToString());  // 触发运行事件
                //        }
                //        bmp.Dispose();
                //    }
                //    catch (Exception ex)
                //    {
                //        AsyncLogHelper.Error($"LBCamera: Event Invoke error - {ex.Message}");
                //        bmp.Dispose(); // 异常时释放资源
                //    }
                //});
            }
            catch (Exception ex)
            {
                AsyncLogHelper.Error($"LBCamera: 生成亮度图异常 - {ex.Message}");
                AsyncLogHelper.Error($"LBCamera: CreateBitmap error - {ex.Message}");
            }
        }
        /// <summary>
        /// 处理CollectedImages中的缓存图像
        /// 核心逻辑:遍历取第一个图像 -> 赋值给CallBackImg -> 触发事件 -> 释放并移除
        /// </summary>
        private void ProcessCollectedImages()
        {
            Task.Factory.StartNew(() =>
            {
                // 加锁保证线程安全,防止多线程同时操作列表
                lock (_collectedImagesLock)
                {
                    // 校验当前相机的图像列表是否存在且有数据
                    if (!CollectedImages.ContainsKey(SN) || CollectedImages[SN].Count == 0)
                    {
                        AsyncLogHelper.Info(SN + "当前无缓存图像,跳过处理");
                        return;
                    }
                    // 循环处理:直到列表为空
                    while (CollectedImages[SN].Count > 0)
                    {
                        try
                        {
                            // 1 取列表第一个索引的图像赋值给CallBackImg
                            Bitmap firstBitmap = CollectedImages[SN][0];
                            ImageGrabbed?.Invoke(this, new LBCameraEventArgs(SN, firstBitmap, true));
                            CallBackImg = (Bitmap)firstBitmap.Clone(); // 克隆避免原对象被释放后引用失效
                            // 2 获取触发模式并判断是否触发运行事件
                            if (GetTriggerMode(out TriggerMode mode, out TriggerSource source))
                            {
                                // 硬触发模式下触发运行事件
                                if (mode == TriggerMode.On && source != TriggerSource.Software)
                                {
                                    AsyncLogHelper.Info(SN + $"触发硬触发事件,触发源:{source}");
                                    TriggerRunMessageReceived?.Invoke(SN, source.ToString());
                                }
                            }
                            else
                            {
                                AsyncLogHelper.Warn(SN + "获取触发模式失败,跳过事件触发");
                            }
                            // 3 释放第一个图像资源并从列表移除
                            // 先释放Bitmap内存,再移除列表元素
                            firstBitmap.Dispose();
                            CollectedImages[SN].RemoveAt(0);
                            AsyncLogHelper.Info(SN + $"已消费缓存图像,剩余缓存数量:{CollectedImages[SN].Count}");
                        }
                        catch (Exception ex)
                        {
                            AsyncLogHelper.Error(SN + $"处理缓存图像异常:{ex.Message}", ex);
                            // 单个图像处理失败时,移除该图像避免阻塞后续处理
                            if (CollectedImages[SN].Count > 0)
                            {
                                try
                                {
                                    CollectedImages[SN][0]?.Dispose(); // 尝试释放
                                    CollectedImages[SN].RemoveAt(0);
                                }
                                catch (Exception innerEx)
                                {
                                    AsyncLogHelper.Error(SN + $"清理异常图像失败:{innerEx.Message}", innerEx);
                                }
                            }
                            // 单个图像处理失败不终止循环,继续处理下一个
                            // 4. 所有图像处理完成后,清空CallBackImg
                            if (CallBackImg != null)
                            {
                                CallBackImg.Dispose();
                                CallBackImg = null;
                            }
                            continue;
                        }
                        // 4. 所有图像处理完成后,清空CallBackImg
                        if (CallBackImg != null)
                        {
                            CallBackImg.Dispose();
                            CallBackImg = null;
                        }
                    }
                }
            });
        }
        private void SyncConfigFromCamera()
        {
            // 从相机读取所有参数并填充到 _sensorConfig
            foreach (EnumNameId id in Enum.GetValues(typeof(EnumNameId)))
            try
            {
                int iVal = 0; double dVal = 0; int eVal = 0;
                if (PHM6000Profiler.GetProfilerParameter(_cameraHandle, (int)id, ref iVal, ref dVal, ref eVal) == 0)
                if (!_isConnected) return;
                PropertyInfo[] props = _sensorConfig.GetType().GetProperties();
                foreach (PropertyInfo p in props)
                {
                    // 实际项目中应使用反射将值写回 _sensorConfig
                    // 跳过自定义参数
                    var iscustomAttr = p.GetCustomAttribute<IsCustomAttribute>();
                    if (iscustomAttr != null) continue;
                    if (Enum.TryParse(typeof(EnumNameId), p.Name, out object nameIdObj))
                    {
                        EnumNameId nameId = (EnumNameId)nameIdObj;
                        int intValue = 0;
                        double doubleValue = 0;
                        int enumValue = 0;
                        if (PHM6000Profiler.GetProfilerParameter(_cameraHandle, (int)nameId, ref intValue, ref doubleValue, ref enumValue) == 0)
                        {
                            if (p.PropertyType == typeof(int))
                            {
                                p.SetValue(_sensorConfig, intValue);
                            }
                            else if (p.PropertyType == typeof(float))
                            {
                                p.SetValue(_sensorConfig, (float)doubleValue);
                            }
                            else if (p.PropertyType == typeof(double))
                            {
                                p.SetValue(_sensorConfig, doubleValue);
                            }
                            else // Enum or other types
                            {
                                p.SetValue(_sensorConfig, enumValue);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                AsyncLogHelper.Error($"LBCamera: SyncConfigFromCamera error - {ex.Message}");
            }
        }
@@ -346,6 +757,13 @@
        {
            if (!_isConnected) return false;
            return PHM6000Profiler.SetProfilerParameter(_cameraHandle, (int)id, 0, value, 0) == 0;
        }
        private bool SetParam(EnumNameId id, int value)
        {
            if (!_isConnected) return false;
            // 对于枚举类型,通常通过 enumValue (最后一个参数) 传递
            return PHM6000Profiler.SetProfilerParameter(_cameraHandle, (int)id, 0, 0, value) == 0;
        }
        private bool GetParam(EnumNameId id, out float value)
@@ -361,6 +779,18 @@
            return false;
        }
        private bool GetParam(EnumNameId id, out int value)
        {
            value = 0;
            if (!_isConnected) return false;
            int iVal = 0; double dVal = 0; int eVal = 0;
            if (PHM6000Profiler.GetProfilerParameter(_cameraHandle, (int)id, ref iVal, ref dVal, ref eVal) == 0)
            {
                value = eVal; // Assuming it returns in enumValue
                return true;
            }
            return false;
        }
        #endregion
    }
}
}