From 89db34bc189c0e667cf81687cee711829fb79492 Mon Sep 17 00:00:00 2001 From: tfarcraw <123211521@163.com> Date: Wed, 18 Nov 2026 17:26:25 +0800 Subject: [PATCH] =?UTF-8?q?=E9=9B=86=E6=88=90USB=E7=9B=B8=E6=9C=BA?= =?UTF-8?q?=E4=BD=8E=E4=BA=AE=E5=BA=A6=E8=A1=A5=E5=81=BF=E5=BC=80=E5=85=B3?= =?UTF-8?q?=E5=B9=B6=E6=94=AF=E6=8C=81=E9=9D=99=E9=BB=98=E5=9B=9E=E9=80=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 2 +- .../CameraSettings/CameraSettingsViewModel.cs | 11 +++- .../CameraSettings/CameraSettingsWindow.axaml | 7 ++- .../Camera/UvcCameraService.cs | 10 ++- .../Camera/UvcCaptureOptions.cs | 3 +- ...eCompensation.cs => WindowsUvcControls.cs} | 62 ++++++++++++++++++- tests/Avalonia.Smoke/Program.cs | 35 +++++++++-- 7 files changed, 117 insertions(+), 13 deletions(-) rename src/SopHelper.CrossPlatform.Engine/Camera/{WindowsExposureCompensation.cs => WindowsUvcControls.cs} (74%) diff --git a/README.md b/README.md index 321b13a..fa012f0 100644 --- a/README.md +++ b/README.md @@ -20,7 +20,7 @@ pwsh -File tools/Start-HandAiD3.ps1 ## 操作流程 1. 在“运行设置”中选择 UVC 或海康相机,新建或选择配方。设置页保留相机、配方和抽帧参数。 -2. 配方编辑器包含“步骤、区域、全局设置、SOP流程视频、Agent助手”五页。在原始相机画面上绘制区域;相机设置独立于配方,在“运行设置”中点击相机后面的“配置”按钮打开专用窗口。USB 分辨率、目标帧率、视频格式和曝光补偿使用下拉菜单选择,列表提供常用配置,不代表设备均支持;海康相机可设置曝光时间。设置按设备保存在 workspace/camera-settings.json,保存后下次开启采集、取图或录像预览时生效。SOP 日志显示驱动回读模式,状态栏分别显示 USB 实测采集和渲染 fps。曝光补偿以 EV 为单位,负值压低自动曝光;选择“不修改”保留当前值,0 EV 清除补偿。当前通过 Windows MSMF 对应设备的 KS 扩展接口写入并回读确认,不支持的设备、步长或平台,以及曝光补偿设置失败时,均静默跳过,不提示、不阻断采集。 +2. 配方编辑器包含“步骤、区域、全局设置、SOP流程视频、Agent助手”五页。在原始相机画面上绘制区域;相机设置独立于配方,在“运行设置”中点击相机后面的“配置”按钮打开专用窗口。USB 分辨率、目标帧率、视频格式、曝光补偿和低亮度补偿使用下拉菜单选择,列表提供常用配置,不代表设备均支持;海康相机可设置曝光时间。设置按设备保存在 workspace/camera-settings.json,保存后下次开启采集、取图或录像预览时生效。SOP 日志显示驱动回读模式,状态栏分别显示 USB 实测采集和渲染 fps。曝光补偿以 EV 为单位,负值压低自动曝光;选择“不修改”保留当前值,0 EV 清除补偿。当前通过 Windows MSMF 对应设备的 KS 扩展接口写入并回读确认,不支持的设备、步长或平台,以及曝光补偿设置失败时,均静默跳过,不提示、不阻断采集。低亮度补偿提供“不修改/关闭/开启”,对应 UVC 属性页同名开关(自动曝光优先级),按设备保存,并在采集、取图、录像预览启动前应用;不支持或设置失败时同样静默跳过,成功回读后记录运行日志。 3. 步骤名描述操作,“说明”填写送检单帧能看到的静态完成状态,AI 用说明判断图片。触发规则支持手在区域内、手进入后离开区域、A→B 移动和持续计时。 4. 送检可选整张画面、固定区域或跟随手部;跟随手部可以设置扩展距离、最小范围和位置保留时间。 5. 保存、应用后开始采集。规则满足只触发送图;AI 确认且完成概率达标后才推进。步骤说明为空、接口失败或证据不足时不会按规则直接完成。 diff --git a/src/SopHelper.Avalonia/VVMs/CameraSettings/CameraSettingsViewModel.cs b/src/SopHelper.Avalonia/VVMs/CameraSettings/CameraSettingsViewModel.cs index 7101261..2055682 100644 --- a/src/SopHelper.Avalonia/VVMs/CameraSettings/CameraSettingsViewModel.cs +++ b/src/SopHelper.Avalonia/VVMs/CameraSettings/CameraSettingsViewModel.cs @@ -17,6 +17,10 @@ public sealed record ExposureCompensationPreset(double? Ev) { public override string ToString() => Ev is null ? "不修改" : $"{Ev:+0.##;-0.##;0} EV"; } +public sealed record LowLightCompensationPreset(bool? Enabled) +{ + public override string ToString() => Enabled switch { true => "开启", false => "关闭", null => "不修改" }; +} public sealed class CameraSettingsViewModel : BindableBase { private readonly CameraInfo _camera; @@ -35,6 +39,8 @@ public sealed class CameraSettingsViewModel : BindableBase new(null), new(-3), new(-2), new(-5d/3), new(-4d/3), new(-1), new(-2d/3), new(-1d/3), new(0), new(1d/3), new(2d/3), new(1), new(2), new(3)]); public ExposureCompensationPreset SelectedExposureCompensation { get; set; } + public LowLightCompensationPreset[] LowLightCompensations { get; } = [new(null), new(false), new(true)]; + public LowLightCompensationPreset SelectedLowLightCompensation { get; set; } public string[] Formats { get; } = ["驱动默认", "MJPG", "YUY2"]; public ResolutionPreset SelectedResolution { get; set; } public FrameRatePreset SelectedFrameRate { get; set; } @@ -48,6 +54,7 @@ public sealed class CameraSettingsViewModel : BindableBase _camera = camera; _store = store; SelectedResolution = Resolutions[0]; SelectedFrameRate = FrameRates[0]; SelectedExposureCompensation = ExposureCompensations[0]; + SelectedLowLightCompensation = LowLightCompensations[0]; try { var settings = store.Load(camera); @@ -62,6 +69,7 @@ public sealed class CameraSettingsViewModel : BindableBase var compensation = new ExposureCompensationPreset(settings.UsbCapture.ExposureCompensationEv); if (!ExposureCompensations.Contains(compensation)) ExposureCompensations.Add(compensation); SelectedExposureCompensation = ExposureCompensations.First(c => c == compensation); + SelectedLowLightCompensation = LowLightCompensations.Single(p => p.Enabled == settings.UsbCapture.LowLightCompensation); ExposureTimeUs = settings.ExposureTimeUs; } catch (Exception ex) { Error = "读取相机设置失败:" + ex.Message; CanSave = false; } @@ -77,7 +85,8 @@ public sealed class CameraSettingsViewModel : BindableBase { Width = SelectedResolution.Width, Height = SelectedResolution.Height, Fps = SelectedFrameRate.Fps, Format = SelectedFormat == Formats[0] ? null : SelectedFormat, - ExposureCompensationEv = SelectedExposureCompensation.Ev + ExposureCompensationEv = SelectedExposureCompensation.Ev, + LowLightCompensation = SelectedLowLightCompensation.Enabled } : new(), ExposureTimeUs = IsIndustrial ? ExposureTimeUs : null }); diff --git a/src/SopHelper.Avalonia/VVMs/CameraSettings/CameraSettingsWindow.axaml b/src/SopHelper.Avalonia/VVMs/CameraSettings/CameraSettingsWindow.axaml index e85b2c7..5554b61 100644 --- a/src/SopHelper.Avalonia/VVMs/CameraSettings/CameraSettingsWindow.axaml +++ b/src/SopHelper.Avalonia/VVMs/CameraSettings/CameraSettingsWindow.axaml @@ -1,6 +1,6 @@ + Width="520" Height="600" MinWidth="440" MinHeight="400" Background="{StaticResource Bg}" WindowStartupLocation="CenterOwner"> @@ -26,6 +26,11 @@ + + + + + diff --git a/src/SopHelper.CrossPlatform.Engine/Camera/UvcCameraService.cs b/src/SopHelper.CrossPlatform.Engine/Camera/UvcCameraService.cs index 1b2bee6..d4280d7 100644 --- a/src/SopHelper.CrossPlatform.Engine/Camera/UvcCameraService.cs +++ b/src/SopHelper.CrossPlatform.Engine/Camera/UvcCameraService.cs @@ -149,8 +149,14 @@ public class UvcCameraService : ICameraService if (options.ExposureCompensationEv is { } ev && OperatingSystem.IsWindows() && capture.Get(VideoCaptureProperties.Backend) == (double)VideoCaptureAPIs.MSMF && Current is { } current - && WindowsExposureCompensation.TrySet(current.Index, ev) is { } actualEv) + && WindowsUvcControls.TrySet(current.Index, ev) is { } actualEv) exposureDescription = $";曝光补偿回读 {actualEv:+0.##;-0.##;0} EV"; + var lowLightDescription = ""; + if (options.LowLightCompensation is { } lowLight && OperatingSystem.IsWindows() + && capture.Get(VideoCaptureProperties.Backend) == (double)VideoCaptureAPIs.MSMF + && Current is { } lowLightCamera + && WindowsUvcControls.TrySetLowLightCompensation(lowLightCamera.Index, lowLight) is { } actualLowLight) + lowLightDescription = actualLowLight ? ";低亮度补偿已开启" : ";低亮度补偿已关闭"; var actualWidth = capture.Get(VideoCaptureProperties.FrameWidth); var actualHeight = capture.Get(VideoCaptureProperties.FrameHeight); var actualFps = capture.Get(VideoCaptureProperties.Fps); @@ -162,7 +168,7 @@ public class UvcCameraService : ICameraService || !string.IsNullOrWhiteSpace(options.Format) && actualFormat != options.Format.Trim().ToUpperInvariant(); ActualFps = 0; return $"USB 驱动回读:{actualWidth:F0}×{actualHeight:F0},{actualFps:F1} fps,格式 {actualFormat}(非实测帧率)" - + (mismatch ? ";与请求不一致,请调整到相机支持的模式" : "") + exposureDescription; + + (mismatch ? ";与请求不一致,请调整到相机支持的模式" : "") + exposureDescription + lowLightDescription; } }); diff --git a/src/SopHelper.CrossPlatform.Engine/Camera/UvcCaptureOptions.cs b/src/SopHelper.CrossPlatform.Engine/Camera/UvcCaptureOptions.cs index e672a24..4b0a394 100644 --- a/src/SopHelper.CrossPlatform.Engine/Camera/UvcCaptureOptions.cs +++ b/src/SopHelper.CrossPlatform.Engine/Camera/UvcCaptureOptions.cs @@ -8,8 +8,9 @@ public sealed record UvcCaptureOptions public double? Fps { get; set; } public string? Format { get; set; } public double? ExposureCompensationEv { get; set; } + public bool? LowLightCompensation { get; set; } [YamlDotNet.Serialization.YamlIgnore, System.Text.Json.Serialization.JsonIgnore] - public bool IsDefault => Width is null && Height is null && Fps is null && string.IsNullOrWhiteSpace(Format) && ExposureCompensationEv is null; + public bool IsDefault => Width is null && Height is null && Fps is null && string.IsNullOrWhiteSpace(Format) && ExposureCompensationEv is null && LowLightCompensation is null; public void Validate() { diff --git a/src/SopHelper.CrossPlatform.Engine/Camera/WindowsExposureCompensation.cs b/src/SopHelper.CrossPlatform.Engine/Camera/WindowsUvcControls.cs similarity index 74% rename from src/SopHelper.CrossPlatform.Engine/Camera/WindowsExposureCompensation.cs rename to src/SopHelper.CrossPlatform.Engine/Camera/WindowsUvcControls.cs index 647217d..c427f5c 100644 --- a/src/SopHelper.CrossPlatform.Engine/Camera/WindowsExposureCompensation.cs +++ b/src/SopHelper.CrossPlatform.Engine/Camera/WindowsUvcControls.cs @@ -4,11 +4,12 @@ using Microsoft.Win32.SafeHandles; namespace SopHelper.Engine.Camera; -/// Windows KS EV 补偿接口。只打开控制句柄,不创建第二条视频采集流。 -internal static unsafe class WindowsExposureCompensation +/// Windows KS 相机控制接口。只打开控制句柄,不创建第二条视频采集流。 +internal static unsafe class WindowsUvcControls { private const uint IoctlKsProperty = 0x002f0003; private static readonly Guid ExtendedControl = new("1CB79112-C0D2-4213-9CA6-CD4FDB927972"); + private static readonly Guid CameraControlSet = new("C6E13370-30AC-11D0-A18C-00A0C9118956"); private static readonly Guid SourceType = new("C60AC5FE-252A-478F-A0EF-BC8FA5F7CAD3"); private static readonly Guid VideoCapture = new("8AC3587A-4AE7-42D8-99E0-0A6013EEF90F"); private static readonly Guid SymbolicLink = new("58F0AAD8-22BF-4F8A-BB3D-D2C4978C6E2F"); @@ -20,6 +21,51 @@ internal static unsafe class WindowsExposureCompensation catch (Exception) { return null; } } + // KSPROPERTY_CAMERACONTROL_AUTO_EXPOSURE_PRIORITY(19)即 UVC 属性页的低亮度补偿。 + // https://learn.microsoft.com/windows-hardware/drivers/stream/ksproperty-cameracontrol-auto-exposure-priority + public static bool? TrySetLowLightCompensation(int index, bool enabled) + { + try + { + if (!OperatingSystem.IsWindows()) return null; + using var device = OpenDevice(index); + var current = ReadLowLightCompensation(device); + if ((current.Value != 0) == enabled) return enabled; + var request = new CameraControlProperty + { + Property = new KsProperty { Set = CameraControlSet, Id = 19, Flags = 2 }, + Value = enabled ? 1 : 0, Flags = 2 + }; + var response = request; + if (!CameraControlIoctl(device, IoctlKsProperty, ref request, 40, ref response, 40, out _, IntPtr.Zero)) + return null; + var actual = ReadLowLightCompensation(device); + return (actual.Value != 0) == enabled ? enabled : null; + } + catch (Exception) { return null; } + } + + public static bool? QueryLowLightCompensation(int index) + { + if (!OperatingSystem.IsWindows()) return null; + using var device = OpenDevice(index); + return ReadLowLightCompensation(device).Value != 0; + } + + private static CameraControlProperty ReadLowLightCompensation(SafeFileHandle device) + { + var request = new CameraControlProperty + { + Property = new KsProperty { Set = CameraControlSet, Id = 19, Flags = 1 } + }; + var response = request; + if (!CameraControlIoctl(device, IoctlKsProperty, ref request, 40, ref response, 40, out var count, IntPtr.Zero)) + throw Failure("无法读取相机低亮度补偿"); + if (count < 40 || response.Value is not (0 or 1)) + throw new NotSupportedException($"低亮度补偿返回值无效:长度 {count},值 {response.Value}"); + return response; + } + private static double Set(int index, double ev) { if (!OperatingSystem.IsWindows()) throw new NotSupportedException("当前平台尚不支持 USB 曝光补偿"); @@ -114,6 +160,18 @@ internal static unsafe class WindowsExposureCompensation [StructLayout(LayoutKind.Sequential)] private struct KsProperty { public Guid Set; public uint Id, Flags; } + // KSIDENTIFIER 包含 LONGLONG 对齐成员,原生相机控制结构尾部需补齐到 40 字节。 + [StructLayout(LayoutKind.Sequential, Size = 40)] + private struct CameraControlProperty + { + public KsProperty Property; + public int Value; + public uint Flags, Capabilities; + } + [DllImport("kernel32.dll", SetLastError = true, EntryPoint = "DeviceIoControl")] + [return: MarshalAs(UnmanagedType.Bool)] + private static extern bool CameraControlIoctl(SafeFileHandle device, uint code, ref CameraControlProperty input, + uint inputSize, ref CameraControlProperty output, uint outputSize, out uint returned, IntPtr overlapped); [StructLayout(LayoutKind.Sequential)] private struct EvPayload { diff --git a/tests/Avalonia.Smoke/Program.cs b/tests/Avalonia.Smoke/Program.cs index 6ca9d9f..9dc49a7 100644 --- a/tests/Avalonia.Smoke/Program.cs +++ b/tests/Avalonia.Smoke/Program.cs @@ -37,12 +37,23 @@ internal static class Smoke { try { - var type=typeof(UvcCameraService).Assembly.GetType("SopHelper.Engine.Camera.WindowsExposureCompensation")!; + var type=typeof(UvcCameraService).Assembly.GetType("SopHelper.Engine.Camera.WindowsUvcControls")!; var range=type.GetMethod("Query")!.Invoke(null,[int.Parse(args[1])]); Console.WriteLine("USB EV capability (read only): "+range);return 0; } catch(Exception ex) { Console.WriteLine("USB EV probe: "+(ex.InnerException?.Message??ex.Message));return 2; } } + if(args.Length==2&&args[0]=="--probe-usb-low-light") + { + try + { + var type=typeof(UvcCameraService).Assembly.GetType("SopHelper.Engine.Camera.WindowsUvcControls")!; + var value=type.GetMethod("QueryLowLightCompensation")!.Invoke(null,[int.Parse(args[1])]); + Console.WriteLine("USB low-light compensation (read only): "+(value is bool enabled ? (enabled ? "on" : "off") : "unavailable")); + } + catch(Exception ex){Console.WriteLine("USB low-light probe: "+(ex.InnerException?.Message??ex.Message));} + return 0; + } _visionOnly=args.Contains("--vision-only"); _processImagesOnly=args.Contains("--process-images-only"); _recipeSelectionOnly=args.Contains("--recipe-selection-only"); @@ -596,9 +607,15 @@ internal static class Smoke Check(rejectedFraction&&wholeOnly.Encode(-1)==(16UL,-1),"Unsupported fractional EV is rejected rather than silently rounded"); var rejectedRange=false;try{thirds.Encode(-3);}catch(ArgumentOutOfRangeException){rejectedRange=true;} Check(rejectedRange,"Requested EV is checked against the actual device range"); - var native=typeof(UvcCameraService).Assembly.GetType("SopHelper.Engine.Camera.WindowsExposureCompensation")!; + var native=typeof(UvcCameraService).Assembly.GetType("SopHelper.Engine.Camera.WindowsUvcControls")!; Check(native.GetMethod("TrySet")!.Invoke(null,[-1,-1d]) is null, "Unavailable exposure compensation silently returns without throwing or writing to a camera"); + Check(native.GetMethod("TrySetLowLightCompensation")!.Invoke(null,[-1,false]) is null, + "Unavailable low-light compensation is silently skipped"); + Check(System.Runtime.InteropServices.Marshal.SizeOf(native.GetNestedType("CameraControlProperty",System.Reflection.BindingFlags.NonPublic)!)==40, + "Low-light control layout matches the Windows SDK"); + Check(!new UvcCaptureOptions {LowLightCompensation=false}.IsDefault, + "Explicitly disabling low-light compensation is distinct from leaving the camera unchanged"); Check(System.Runtime.InteropServices.Marshal.SizeOf(native.GetNestedType("EvPayload",System.Reflection.BindingFlags.NonPublic)!)==56, "Native EV payload layout matches the Windows SDK"); var lifetime=(IClassicDesktopStyleApplicationLifetime)Application.Current!.ApplicationLifetime!; @@ -616,20 +633,22 @@ internal static class Smoke var rate=dialog.FindControl("FrameRatePicker")!; var format=dialog.FindControl("FormatPicker")!; var compensation=dialog.FindControl("ExposureCompensationPicker")!; + var lowLight=dialog.FindControl("LowLightCompensationPicker")!; Check(dialog.Model.Resolutions.Any(r=>r.Width==4608)&&dialog.Model.FrameRates.Any(r=>r.Fps==30),"Resolution and frame rate dropdowns contain common presets including 16 MP and 30 fps"); resolution.SelectedItem=dialog.Model.Resolutions.Single(r=>r.Width==1920&&r.Height==1080); rate.SelectedItem=dialog.Model.FrameRates.Single(r=>r.Fps==30); format.SelectedItem="MJPG"; compensation.SelectedItem=dialog.Model.ExposureCompensations.Single(c=>c.Ev==-2d/3); + lowLight.SelectedItem=dialog.Model.LowLightCompensations.Single(p=>p.Enabled==false); await Task.Delay(60); Save(dialog,"camera-settings"); dialog.FindControl