移除海康工业相机及MVS依赖仅保留USB采集

This commit is contained in:
tfarcraw 2026-11-19 23:21:56 +08:00
parent 74898e27d3
commit d1fb13f5fe
26 changed files with 102 additions and 827 deletions

3
.gitignore vendored
View File

@ -387,10 +387,7 @@ FodyWeavers.xsd
/AGENTS.md
*.onnx
# 海康 MVS 托管 SDK 随项目提供;原生运行时由现场安装。
!/libs/
!/libs/MvCameraControl.Net.dll
!/libs/mvs/linux-x64/MvCameraControl.Net.dll
/libs/cuda/
/models

View File

@ -19,8 +19,8 @@ pwsh -File tools/Start-HandAiD3.ps1
## 操作流程
1. 在“运行设置”中选择 UVC 或海康相机,新建或选择配方。抽帧、完成后自动复位和复位延时保存在独立的 `workspace/runtime-settings.json`,下次开始运行时生效,切换配方不会覆盖。
2. 配方编辑器包含“步骤、SOP流程视频、Agent助手”三页。区域导航和参数位于步骤页播放器下方,暂停视频后可直接拖动画框;相机设置独立于配方,在“运行设置”中点击相机后面的“配置”按钮打开专用窗口。USB 分辨率、目标帧率、视频格式和自动曝光使用下拉菜单选择,关闭自动曝光后可填写以毫秒为单位的手动曝光时间(留空保留当前时间);海康相机可设置曝光时间。USB 采集统一使用 OpenCV:Windows 自动使用设备可用的兼容接口(DirectShow/MSMF),枚举结果记录内部接口标记,保证连接时沿用同一设备索引体系;Linux 使用 V4L2,无需选择采集方式。曝光控制分别适配 Windows 的对数档位及 V4L2 的原始控制值,Windows 会匹配最接近的曝光档位;设备不支持或控制失败时静默跳过。已移除 Windows 专属驱动属性页,旧设置中的采集方式及补偿字段会被忽略。设置按设备保存在 workspace/camera-device-settings.json,保存后下次开启采集、取图或录像预览时生效。SOP 日志显示驱动回读采集模式,状态栏分别显示 USB 实测采集和渲染 fps。
1. 在“运行设置”中选择 USB(UVC)相机,新建或选择配方。抽帧、完成后自动复位和复位延时保存在独立的 `workspace/runtime-settings.json`,下次开始运行时生效,切换配方不会覆盖。
2. 配方编辑器包含“步骤、SOP流程视频、Agent助手”三页。区域导航和参数位于步骤页播放器下方,暂停视频后可直接拖动画框;相机设置独立于配方,在“运行设置”中点击相机后面的“配置”按钮打开专用窗口。USB 分辨率、目标帧率、视频格式和自动曝光使用下拉菜单选择,关闭自动曝光后可填写以毫秒为单位的手动曝光时间(留空保留当前时间)。USB 采集统一使用 OpenCV:Windows 自动使用设备可用的兼容接口(DirectShow/MSMF),枚举结果记录内部接口标记,保证连接时沿用同一设备索引体系;Linux 使用 V4L2,无需选择采集方式。曝光控制分别适配 Windows 的对数档位及 V4L2 的原始控制值,Windows 会匹配最接近的曝光档位;设备不支持或控制失败时静默跳过。已移除 Windows 专属驱动属性页,旧设置中的采集方式及补偿字段会被忽略。设置按设备保存在 workspace/camera-device-settings.json,保存后下次开启采集、取图或录像预览时生效。SOP 日志显示驱动回读采集模式,状态栏分别显示 USB 实测采集和渲染 fps。
3. 步骤名描述操作,“说明”填写送检单帧能看到的静态完成状态,AI 用说明判断图片。触发规则支持手在区域内、手进入后离开区域、A→B 移动和持续计时。
4. 送检可选整张画面、固定区域或跟随手部;跟随手部可以设置扩展距离、最小范围和位置保留时间。
5. 保存、应用后开始采集。规则满足只触发送图;AI 确认且完成概率达标后才推进。步骤说明为空、接口失败或证据不足时不会按规则直接完成。
@ -47,13 +47,13 @@ Agent 助手右侧可聊天,要求拆分、合并或修改步骤,并保留
- `configs/sop/`:初始配方模板;已有同名配方不覆盖。
- `recipes/配方名/`:配方、过程图、录像及保留的历史数据,不入 Git。
- `models/`:当前打包使用的通用手部 ONNX 模型。
- `libs/`:海康绑定和平台原生运行库。
- `libs/`:平台原生运行库。
```powershell
pwsh -File tools/Publish-Avalonia.ps1
```
发布目录为 `artifacts/avalonia/win-x64` 和 `artifacts/avalonia/linux-x64`。默认构建及发布不再携带训练用 Python、SAM2 或 YOLO 权重;D3 服务使用自己的独立环境。海康相机的系统驱动仍需在目标机器安装。
发布目录为 `artifacts/avalonia/win-x64` 和 `artifacts/avalonia/linux-x64`。默认构建及发布不再携带训练用 Python、SAM2 或 YOLO 权重;D3 服务使用自己的独立环境。相机仅支持 USB(UVC),不依赖工业相机 SDK。
`--import-recipes 原数据根目录` 可以导入已有配方,`--check-standalone` / `--check-runtime` 检查本地手部模型和使用模拟 AI 的步骤门控,`--check-gpu` 额外要求手部推理使用 GPU;这些本地诊断不代表真实 D3 接口联调成功。
@ -70,4 +70,4 @@ dotnet run --project tests/TensorPreprocessing.Smoke
界面检查使用假相机,覆盖新设置入口、手部触发、区域取图和实际送检图保存。D3 的工位误判率及间歇请求延迟仍需现场验证,当前不承诺每次请求都低于 200ms。
Agent 助手的“生成步骤”和“回测并修订”独立运行:生成只产出草稿,普通对话只修改草稿,不自动回测;草稿可直接编辑或添加到配方。点击“回测并修订”后才启用标准视频验证与按证据修订,显式回测未通过或已验证草稿发生变化时需重新回测才能应用。旧设置中的 autoVerify 字段不再生效。
Agent 助手生成步骤草稿,支持编辑、对话修订和添加到配方;已移除 djev 回测入口及应用前回测限制。旧设置中的 autoVerify 字段不再生效。

Binary file not shown.

File diff suppressed because one or more lines are too long

View File

@ -1,15 +0,0 @@
# Linux MVS managed binding
`MvCameraControl.Net.dll` is the vendor's x64/netstandard2.0 binding shipped with
Linux MVS 4.9.0.3, obtained from the user's installed SDK at
`/opt/MVS/Samples/64/C#/Dotnet/x64/netstandard2.0/MvCameraControl.Net.dll`.
SHA256: `952CB2ECABF397A117DB3E108DDAEEBB0E018B42B26265A3D1E33EE6B17E5912`.
The Windows binding in `libs/MvCameraControl.Net.dll` must not be reused on Linux:
its frame structure layout produces zero dimensions and an invalid buffer length
with Linux MVS 4.9. Both targets retain the same application/camera service source;
only the vendor SDK binding and native runtime differ.
Verified on 2026-11-08: LH-GC10-HS500, BayerRG8, 2448×2048; acquisition, BGR conversion,
buffer release and reopening the device passed against the installed Linux runtime.

View File

@ -8,13 +8,10 @@ namespace SopHelper.Models;
public sealed record CameraDeviceSettings
{
public UvcCaptureOptions UsbCapture { get; set; } = new();
public double? ExposureTimeUs { get; set; }
public void Validate()
{
UsbCapture.Validate();
if (ExposureTimeUs is { } exposure && (!double.IsFinite(exposure) || exposure <= 0))
throw new ArgumentException("曝光时间必须大于 0(微秒),或留空使用相机默认值");
}
}
@ -23,8 +20,7 @@ public sealed class CameraSettingsStore(string root)
{
public string FilePath => Path.Combine(root, "workspace", "camera-device-settings.json");
public static CameraSettingsStore Current => new(DesktopPlatform.WorkspaceRoot);
private static string Key(CameraInfo camera) => camera.Kind == CameraKind.Hikvision
? $"Hikvision:{camera.SerialNumber}" : $"Uvc:{camera.Index}";
private static string Key(CameraInfo camera) => $"Uvc:{camera.Index}";
private Dictionary<string, CameraDeviceSettings> Read()
{
// 旧路径也用于录像目录;只迁移设备项,避免把 directory 字符串读成设备设置。
@ -36,8 +32,7 @@ public sealed class CameraSettingsStore(string root)
var settings = new Dictionary<string, CameraDeviceSettings>();
foreach (var property in json.RootElement.EnumerateObject())
{
if (!property.Name.StartsWith("Uvc:", StringComparison.Ordinal) &&
!property.Name.StartsWith("Hikvision:", StringComparison.Ordinal)) continue;
if (!property.Name.StartsWith("Uvc:", StringComparison.Ordinal)) continue;
settings[property.Name] = property.Value.Deserialize<CameraDeviceSettings>()
?? throw new InvalidDataException("相机设备设置内容为空:" + property.Name);
}
@ -68,9 +63,6 @@ public sealed class CameraSettingsStore(string root)
{
var settings = Load(camera);
settings.Validate();
var description = camera.Kind == CameraKind.Uvc
? await service.ConfigureUvcAsync(settings.UsbCapture) : "";
if (settings.ExposureTimeUs is { } exposure) await service.SetExposureTimeAsync(exposure);
return description;
return await service.ConfigureUvcAsync(settings.UsbCapture);
}
}

View File

@ -15,7 +15,6 @@
<NativePlatform Condition="'$(NativePlatform)' == ''">Linux</NativePlatform>
<ApplicationIcon>BWS.ico</ApplicationIcon>
<BundlePythonRuntime Condition="'$(BundlePythonRuntime)' == ''">false</BundlePythonRuntime>
<MvsRuntimeDirectory Condition="'$(MvsRuntimeDirectory)' == ''">$(MSBuildProgramFiles32)/Common Files/MVS/Runtime/Win64_x64</MvsRuntimeDirectory>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="../SopHelper.CrossPlatform.Engine/SopHelper.CrossPlatform.Engine.csproj" />
@ -30,10 +29,4 @@
<Content Include="BWS.ico" />
<Content Include="../../python/**/*" Exclude="../../python/**/__pycache__/**;../../python/**/*.pyc;../../python/**/*.lnk" Link="python/%(RecursiveDir)%(Filename)%(Extension)" CopyToOutputDirectory="PreserveNewest" CopyToPublishDirectory="Never" Condition="'$(NativePlatform)' == 'Windows' and '$(BundlePythonRuntime)' == 'true'" />
</ItemGroup>
<Target Name="BundleMvsRuntime" AfterTargets="Build" Condition="'$(NativePlatform)' == 'Windows' and Exists('$(MvsRuntimeDirectory)')">
<ItemGroup>
<LocalMvs Include="$(MvsRuntimeDirectory)/**/*" />
</ItemGroup>
<Copy SourceFiles="@(LocalMvs)" DestinationFiles="@(LocalMvs->'$(TargetDir)%(RecursiveDir)%(Filename)%(Extension)')" SkipUnchangedFiles="true" />
</Target>
</Project>

View File

@ -32,8 +32,6 @@ public sealed class CameraSettingsViewModel : BindableBase
public bool IsManualExposure => SelectedAutoExposure.Enabled == false;
public decimal? UsbExposureTimeMs { get; set; }
public string CameraName => _camera.Name;
public bool IsUsb => _camera.Kind == CameraKind.Uvc;
public bool IsIndustrial => !IsUsb;
public ObservableCollection<ResolutionPreset> Resolutions { get; } = new([
new(null,null), new(640,480), new(800,600), new(1280,720), new(1280,960),
new(1920,1080), new(1920,1200), new(2560,1440), new(2592,1944),
@ -44,7 +42,6 @@ public sealed class CameraSettingsViewModel : BindableBase
public ResolutionPreset SelectedResolution { get; set; }
public FrameRatePreset SelectedFrameRate { get; set; }
public string SelectedFormat { get; set; } = "驱动默认";
public double? ExposureTimeUs { get; set; }
public string Error { get => _error; private set => SetProperty(ref _error, value); }
public bool CanSave { get; private set; } = true;
@ -66,7 +63,6 @@ public sealed class CameraSettingsViewModel : BindableBase
SelectedFormat = string.IsNullOrWhiteSpace(settings.UsbCapture.Format) ? Formats[0] : settings.UsbCapture.Format.Trim().ToUpperInvariant();
SelectedAutoExposure = ExposureModes.Single(p => p.Enabled == settings.UsbCapture.AutoExposure);
UsbExposureTimeMs = settings.UsbCapture.ExposureTimeMs is { } ms ? (decimal)ms : null;
ExposureTimeUs = settings.ExposureTimeUs;
}
catch (Exception ex) { Error = "读取相机设置失败:" + ex.Message; CanSave = false; }
}
@ -77,14 +73,13 @@ public sealed class CameraSettingsViewModel : BindableBase
{
_store.Save(_camera, new CameraDeviceSettings
{
UsbCapture = IsUsb ? new UvcCaptureOptions
UsbCapture = new UvcCaptureOptions
{
Width = SelectedResolution.Width, Height = SelectedResolution.Height,
Fps = SelectedFrameRate.Fps, Format = SelectedFormat == Formats[0] ? null : SelectedFormat,
AutoExposure = SelectedAutoExposure.Enabled,
ExposureTimeMs = IsManualExposure && UsbExposureTimeMs is { } ms ? (double)ms : null
} : new(),
ExposureTimeUs = IsIndustrial ? ExposureTimeUs : null
}
});
Error = ""; return true;
}

View File

@ -8,7 +8,7 @@
</StackPanel>
<ScrollViewer Grid.Row="1" Margin="0,20,0,16" HorizontalScrollBarVisibility="Disabled">
<StackPanel Spacing="14">
<StackPanel IsVisible="{Binding IsUsb}" Spacing="12">
<StackPanel Spacing="12">
<Grid ColumnDefinitions="100,*">
<TextBlock Text="分辨率" VerticalAlignment="Center" />
<ComboBox x:Name="ResolutionPicker" Grid.Column="1" ItemsSource="{Binding Resolutions}" SelectedItem="{Binding SelectedResolution, Mode=TwoWay}" HorizontalAlignment="Stretch" />
@ -32,10 +32,6 @@
<TextBlock Text="关闭自动曝光后可调整时间,值越小通常越暗;留空只关闭自动曝光并保留当前曝光时间。Windows 会匹配最接近的设备曝光档位。" TextWrapping="Wrap" Foreground="{StaticResource FgDim}" FontSize="12" />
<TextBlock Text="列表为常用配置,不代表当前相机均支持。选择“驱动默认”可保留默认模式;实际协商结果见运行日志。" TextWrapping="Wrap" Foreground="{StaticResource FgDim}" FontSize="12" />
</StackPanel>
<StackPanel IsVisible="{Binding IsIndustrial}" Spacing="8">
<TextBlock Text="曝光时间(μs)" />
<TextBox x:Name="ExposureInput" Text="{Binding ExposureTimeUs, Mode=TwoWay}" PlaceholderText="留空使用相机默认值" />
</StackPanel>
<TextBlock Text="设置按相机独立保存,切换配方不会改变;下次开启采集、取图或录像预览时生效。" TextWrapping="Wrap" Foreground="{StaticResource FgDim}" FontSize="12" />
<TextBlock Text="{Binding Error}" Foreground="{StaticResource Ng}" TextWrapping="Wrap" />
</StackPanel>

View File

@ -14,7 +14,7 @@
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<TextBlock Text="相机" Width="40" />
<ComboBox Grid.Column="1" Height="26" VerticalContentAlignment="Center" ItemsSource="{Binding Cameras}" IsEnabled="{Binding CanSelectCamera}" SelectedItem="{Binding SelectedCamera, Converter={StaticResource SelectionConverter}}" ToolTip.Tip="支持 UVC 和海康 GigE/USB 工业相机">
<ComboBox Grid.Column="1" Height="26" VerticalContentAlignment="Center" ItemsSource="{Binding Cameras}" IsEnabled="{Binding CanSelectCamera}" SelectedItem="{Binding SelectedCamera, Converter={StaticResource SelectionConverter}}" ToolTip.Tip="支持 USB(UVC)相机">
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Name}" />

View File

@ -667,7 +667,10 @@ public class SopPageViewModel : ViewModelBase
try
{
if (File.Exists(LastCameraPath))
{
_lastUsedCamera = JsonSerializer.Deserialize<CameraInfo>(File.ReadAllText(LastCameraPath));
if (_lastUsedCamera?.Kind != CameraKind.Uvc) _lastUsedCamera = null;
}
}
catch (Exception ex)
{
@ -706,13 +709,12 @@ public class SopPageViewModel : ViewModelBase
if (Cameras.Count == 0)
{
Log("warn", "没有枚举到相机(支持 UVC、海康 GigE/USB 工业相机)");
Log("warn", "没有枚举到 USB(UVC)相机");
if (_camera.IsConnected) await Task.Run(_camera.Disconnect);
return;
}
SelectedCamera = previous is null ? Cameras[0] : Cameras.FirstOrDefault(c => c.Kind == previous.Kind &&
(c.Kind == CameraKind.Hikvision ? c.SerialNumber == previous.SerialNumber : c.Index == previous.Index));
SelectedCamera = previous is null ? Cameras[0] : Cameras.FirstOrDefault(c => c.IsSameDevice(previous));
if (previous is not null && SelectedCamera is null)
{
if (_camera.IsConnected) await Task.Run(_camera.Disconnect);

View File

@ -1,10 +1,9 @@
namespace SopHelper.Engine.Camera;
/// <summary>统一枚举、按设备类型切换采集后端,推理管线始终订阅同一个服务。</summary>
/// <summary>USB 相机连接与采集生命周期管理,推理管线始终订阅同一个服务。</summary>
public sealed class CameraService : ICameraService
{
private readonly ICameraService _uvc;
private readonly ICameraService _hik;
private ICameraService? _active;
private readonly SemaphoreSlim _operations = new(1, 1);
private bool _disposed;
@ -12,16 +11,12 @@ public sealed class CameraService : ICameraService
private UvcCaptureOptions? _configuredUsbOptions;
private string _modeDescription = "";
public CameraService(ICameraService? uvc = null, ICameraService? hik = null)
public CameraService(ICameraService? uvc = null)
{
_uvc = uvc ?? new UvcCameraService();
_hik = hik ?? new HikvisionCameraService();
foreach (var service in new[] { _uvc, _hik })
{
service.FrameArrived += frame => FrameArrived?.Invoke(frame);
service.ConnectionChanged += connected => ConnectionChanged?.Invoke(connected);
service.Error += message => Error?.Invoke(message);
}
_uvc.FrameArrived += frame => FrameArrived?.Invoke(frame);
_uvc.ConnectionChanged += connected => ConnectionChanged?.Invoke(connected);
_uvc.Error += message => Error?.Invoke(message);
}
public bool IsConnected => _active?.IsConnected == true;
@ -37,10 +32,7 @@ public sealed class CameraService : ICameraService
try
{
ObjectDisposedException.ThrowIf(_disposed, this);
// 优先展示海康;没有安装 MVS 时仍可使用 UVC。
var cameras = await _hik.EnumerateAsync().ConfigureAwait(false);
cameras.AddRange(await _uvc.EnumerateAsync().ConfigureAwait(false));
return cameras;
return await _uvc.EnumerateAsync().ConfigureAwait(false);
}
finally { _operations.Release(); }
}
@ -51,33 +43,22 @@ public sealed class CameraService : ICameraService
try
{
ObjectDisposedException.ThrowIf(_disposed, this);
if (camera.Kind != CameraKind.Uvc) throw new ArgumentException("仅支持 USB(UVC)相机", nameof(camera));
if (_active?.IsConnected == true && camera.IsSameDevice(_connectedCamera)
&& (camera.Kind != CameraKind.Uvc || camera.UseCompatibilityBackend == _connectedCamera!.UseCompatibilityBackend))
&& camera.UseCompatibilityBackend == _connectedCamera!.UseCompatibilityBackend)
return true;
_connectedCamera = null; _configuredUsbOptions = null;
if (_active is not null) await Task.Run(_active.Disconnect).ConfigureAwait(false);
_active = camera.Kind == CameraKind.Hikvision ? _hik : _uvc;
_active = _uvc;
var connected = await _active.ConnectAsync(camera).ConfigureAwait(false);
if (connected)
_connectedCamera = new CameraInfo {Kind=camera.Kind,Index=camera.Index,SerialNumber=camera.SerialNumber,
_connectedCamera = new CameraInfo {Kind=camera.Kind,Index=camera.Index,
UseCompatibilityBackend=camera.UseCompatibilityBackend};
return connected;
}
finally { _operations.Release(); }
}
public async Task SetExposureTimeAsync(double microseconds)
{
await _operations.WaitAsync().ConfigureAwait(false);
try
{
ObjectDisposedException.ThrowIf(_disposed, this);
if (_active is null || !_active.IsConnected) throw new InvalidOperationException("请先连接相机");
await _active.SetExposureTimeAsync(microseconds).ConfigureAwait(false);
}
finally { _operations.Release(); }
}
public async Task<string> ConfigureUvcAsync(UvcCaptureOptions options)
{
await _operations.WaitAsync().ConfigureAwait(false);
@ -134,11 +115,7 @@ public sealed class CameraService : ICameraService
if (_disposed) return;
_disposed = true;
try { _uvc.Dispose(); }
finally
{
try { _hik.Dispose(); }
finally { _active = null; }
}
finally { _active = null; }
}
finally { _operations.Release(); }
}

View File

@ -1,264 +0,0 @@
using MvCameraControl;
using OpenCvSharp;
namespace SopHelper.Engine.Camera;
/// <summary>海康 MVS 连续视频采集(GigE / USB),参考 plcsharp 的 SDK 接入方式。</summary>
public sealed class HikvisionCameraService : ICameraService
{
private readonly object _gate = new();
private IDevice? _device;
private CancellationTokenSource? _cts;
private Task? _grabTask;
private bool _initialized;
private bool _disposed;
private volatile bool _connected;
private volatile bool _grabbing;
private long _frameId;
public bool IsConnected => _connected;
public bool IsGrabbing => _grabbing;
public event Action<CameraFrame>? FrameArrived;
public event Action<bool>? ConnectionChanged;
public event Action<string>? Error;
private void EnsureInitialized()
{
ObjectDisposedException.ThrowIf(_disposed, this);
if (_initialized) return;
Check(SDKSystem.Initialize(), "初始化 MVS");
_initialized = true;
}
private static List<IDeviceInfo> EnumerateDevices()
{
Check(DeviceEnumerator.EnumDevices(
DeviceTLayerType.MvGigEDevice | DeviceTLayerType.MvUsbDevice, out var devices), "枚举海康相机");
return devices;
}
public Task<List<CameraInfo>> EnumerateAsync() => Task.Run(() =>
{
lock (_gate)
{
try
{
EnsureInitialized();
return EnumerateDevices().Select((device, index) => new CameraInfo
{
Kind = CameraKind.Hikvision,
Index = index,
SerialNumber = device.SerialNumber,
Name = $"海康 {device.ModelName} / {device.SerialNumber}" +
(string.IsNullOrWhiteSpace(device.UserDefinedName) ? "" : $"({device.UserDefinedName})"),
}).ToList();
}
catch (Exception ex)
{
Report(ex);
return new List<CameraInfo>();
}
}
});
public Task<bool> ConnectAsync(CameraInfo camera) => Task.Run(() =>
{
lock (_gate)
{
try
{
DisconnectCore();
EnsureInitialized();
if (camera.Kind != CameraKind.Hikvision || string.IsNullOrWhiteSpace(camera.SerialNumber))
throw new InvalidOperationException("请选择有效的海康相机");
var info = EnumerateDevices().FirstOrDefault(d => d.SerialNumber == camera.SerialNumber)
?? throw new InvalidOperationException($"海康相机 {camera.SerialNumber} 已离线,请刷新列表");
_device = DeviceFactory.CreateDevice(info);
Check(_device.Open(), "打开海康相机");
if (_device is IGigEDevice gigE)
{
var result = gigE.GetOptimalPacketSize(out var packetSize);
if (result == MvError.MV_OK)
result = _device.Parameters.SetIntValue("GevSCPSPacketSize", packetSize);
if (result != MvError.MV_OK)
Error?.Invoke($"海康网络包大小优化失败(0x{result:X8}),继续使用默认值");
}
// 视频必须关闭触发,避免相机上一次留下的软触发/硬触发模式导致无图。
Check(_device.Parameters.SetEnumValueByString("AcquisitionMode", "Continuous"), "设置连续采集");
Check(_device.Parameters.SetEnumValueByString("TriggerMode", "Off"), "关闭触发模式");
_connected = true;
ConnectionChanged?.Invoke(true);
return true;
}
catch (Exception ex)
{
DisconnectCore();
Report(ex);
return false;
}
}
});
public Task SetExposureTimeAsync(double microseconds) => Task.Run(() =>
{
lock (_gate)
{
if (!double.IsFinite(microseconds) || microseconds <= 0 || microseconds > float.MaxValue)
throw new ArgumentOutOfRangeException(nameof(microseconds), "相机曝光必须是大于 0 的有限数值(微秒)");
if (!_connected || _device is null || _disposed) throw new InvalidOperationException("请先连接海康相机");
if (_grabbing) throw new InvalidOperationException("请停止采集后再设置曝光");
Check(_device.Parameters.SetEnumValueByString("ExposureAuto", "Off"), "关闭自动曝光");
Check(_device.Parameters.SetFloatValue("ExposureTime", (float)microseconds), "设置曝光时间,请确认数值在相机支持范围内");
}
});
public Task<bool> StartAsync() => Task.Run(() =>
{
lock (_gate)
{
if (_grabbing) return true;
if (!_connected || _device is null || _disposed) return false;
try
{
StopCore();
Check(_device.StreamGrabber.StartGrabbing(), "启动海康取流");
_cts = new CancellationTokenSource();
var token = _cts.Token;
var device = _device;
_grabbing = true;
_grabTask = Task.Run(() => GrabLoop(device, token));
return true;
}
catch (Exception ex)
{
Report(ex);
return false;
}
}
});
private void GrabLoop(IDevice device, CancellationToken token)
{
try
{
while (!token.IsCancellationRequested)
{
var result = device.StreamGrabber.GetImageBuffer(500, out var buffer);
if (result == MvError.MV_E_NODATA) continue; // 有限超时,允许安全停止。
Check(result, "海康取帧");
Mat bgr;
try
{
bgr = CopyBgr(device, buffer.Image);
}
finally
{
// 转换失败也必须归还 SDK 缓冲,防止缓冲池耗尽。
device.StreamGrabber.FreeImageBuffer(buffer);
}
using var frame = new CameraFrame
{
FrameId = Interlocked.Increment(ref _frameId),
Timestamp = DateTime.Now,
Bgr = bgr,
};
if (token.IsCancellationRequested) break;
try { FrameArrived?.Invoke(frame); }
catch (Exception ex) { Error?.Invoke($"海康帧回调异常:{ex.Message}"); }
}
}
catch (Exception ex)
{
if (!token.IsCancellationRequested)
{
_connected = false;
ConnectionChanged?.Invoke(false);
Report(ex);
}
}
finally { _grabbing = false; }
}
private static Mat CopyBgr(IDevice device, IImage image)
{
if (image.Width == 0 || image.Height == 0 || image.Width > int.MaxValue || image.Height > int.MaxValue || image.PixelDataPtr == IntPtr.Zero)
throw new InvalidDataException($"海康返回无效帧尺寸 {image.Width}×{image.Height},请检查当前平台的托管 SDK 与原生运行库是否配套");
if (image.PixelType == MvGvspPixelType.PixelType_Gvsp_BGR8_Packed)
{
using var view = Mat.FromPixelData((int)image.Height, (int)image.Width, MatType.CV_8UC3, image.PixelDataPtr);
return view.Clone();
}
if (image.PixelType == MvGvspPixelType.PixelType_Gvsp_Mono8)
{
using var view = Mat.FromPixelData((int)image.Height, (int)image.Width, MatType.CV_8UC1, image.PixelDataPtr);
var bgr = new Mat();
try { Cv2.CvtColor(view, bgr, ColorConversionCodes.GRAY2BGR); return bgr; }
catch { bgr.Dispose(); throw; }
}
// Bayer、RGB、YUV、高位深格式由 SDK 转换,不能当三通道直接读取。
var result = device.PixelTypeConverter.ConvertPixelType(image, out var converted, MvGvspPixelType.PixelType_Gvsp_BGR8_Packed);
using (converted)
{
Check(result, $"转换海康像素格式({image.Width}×{image.Height},{image.PixelType})");
if (converted is null) throw new InvalidOperationException("海康像素转换未返回图像");
using var view = Mat.FromPixelData((int)converted.Height, (int)converted.Width, MatType.CV_8UC3, converted.PixelDataPtr);
return view.Clone(); // 深拷贝后才能释放 SDK 图像。
}
}
public void Stop() { lock (_gate) StopCore(); }
private void StopCore()
{
_cts?.Cancel();
// 等采集线程归还最后一个缓冲后,再停止/关闭设备;不在超时后强行释放句柄。
_grabTask?.GetAwaiter().GetResult();
_grabTask = null;
_cts?.Dispose();
_cts = null;
if (_device is not null) _device.StreamGrabber.StopGrabbing();
_grabbing = false;
}
public void Disconnect() { lock (_gate) DisconnectCore(); }
private void DisconnectCore()
{
StopCore();
if (_device is not null)
{
try { _device.Close(); }
finally { _device.Dispose(); _device = null; }
}
var wasConnected = _connected;
_connected = false;
if (wasConnected) ConnectionChanged?.Invoke(false);
}
public void Dispose()
{
lock (_gate)
{
if (_disposed) return;
DisconnectCore();
if (_initialized) SDKSystem.Finalize();
_initialized = false;
_disposed = true;
}
}
private static void Check(int result, string operation)
{
if (result != MvError.MV_OK) throw new InvalidOperationException($"{operation}失败(0x{result:X8})");
}
private void Report(Exception ex)
{
var detail = ex is DllNotFoundException or BadImageFormatException or EntryPointNotFoundException
? "请检查 MVS 原生运行库、架构和 SDK 版本是否匹配。"
: "请根据上面的具体错误检查相机连接、占用状态及 SDK 兼容性。";
var message = $"海康相机:{ex.Message}。{detail}";
Console.Error.WriteLine(message);
Error?.Invoke(message);
}
}

View File

@ -2,7 +2,7 @@ using OpenCvSharp;
namespace SopHelper.Engine.Camera;
public enum CameraKind { Uvc, Hikvision }
public enum CameraKind { Uvc }
/// <summary>
/// 相机信息
@ -11,18 +11,14 @@ public class CameraInfo
{
public CameraKind Kind { get; set; }
/// <summary>海康设备序列号,重新枚举后仍可稳定定位设备</summary>
public string SerialNumber { get; set; } = "";
/// <summary>索引(UVC 设备号)</summary>
public int Index { get; set; }
/// <summary>Windows 内部兼容采集标记;由枚举结果决定,不作为用户设置。</summary>
public bool UseCompatibilityBackend { get; set; }
public bool IsSameDevice(CameraInfo? other) => other is not null && Kind == other.Kind &&
(Kind == CameraKind.Hikvision && (!string.IsNullOrWhiteSpace(SerialNumber) || !string.IsNullOrWhiteSpace(other.SerialNumber))
? !string.IsNullOrWhiteSpace(SerialNumber) && SerialNumber == other.SerialNumber : Index == other.Index);
public bool IsSameDevice(CameraInfo? other) => other is not null && Kind == CameraKind.Uvc
&& other.Kind == CameraKind.Uvc && Index == other.Index;
/// <summary>名称</summary>
public string Name { get; set; } = "";
@ -52,7 +48,7 @@ public class CameraFrame : IDisposable
}
/// <summary>
/// 单相机采集服务:一个采集线程 + 帧事件,支持 UVC 和海康工业相机。
/// 单相机采集服务:一个采集线程 + 帧事件,支持 USB(UVC)相机。
/// </summary>
public interface ICameraService : IDisposable
{
@ -80,10 +76,6 @@ public interface ICameraService : IDisposable
/// <summary>连接相机</summary>
Task<bool> ConnectAsync(CameraInfo camera);
/// <summary>连接后、采集前设置手动曝光,单位微秒。不支持时明确报错。</summary>
Task SetExposureTimeAsync(double microseconds) =>
Task.FromException(new NotSupportedException("当前相机不支持以微秒设置曝光,请将配方的相机曝光留空"));
/// <summary>连接后、采集前配置 USB 模式,返回驱动回读参数。</summary>
Task<string> ConfigureUvcAsync(UvcCaptureOptions options) => options.IsDefault
? Task.FromResult("")

View File

@ -88,6 +88,7 @@ public class UvcCameraService : ICameraService
/// <inheritdoc />
public Task<bool> ConnectAsync(CameraInfo camera)
{
if (camera.Kind != CameraKind.Uvc) throw new ArgumentException("仅支持 USB(UVC)相机", nameof(camera));
return Task.Run(() =>
{
lock (CameraBackendLock)

View File

@ -1,28 +0,0 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using MvCameraControl;
namespace SopHelper.Engine.Camera;
internal static class MvsNativeBindings
{
// The managed SDK's acquisition APIs import MvCameraControl.dll by name. On
// Linux bind those same calls to the MVS C runtime; no application/UI fork.
[ModuleInitializer]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Usage","CA2255",Justification="This application-owned adapter must install the SDK resolver before its first P/Invoke.")]
internal static void Initialize()
{
if(!OperatingSystem.IsWindows())NativeLibrary.SetDllImportResolver(typeof(SDKSystem).Assembly,Resolve);
}
private static IntPtr Resolve(string name,Assembly assembly,DllImportSearchPath? searchPath)
{
if(name!="MvCameraControl.dll"&&name!="MvCameraControl"&&name!="libMvCameraControl.so")return IntPtr.Zero;
var configured=Environment.GetEnvironmentVariable("MVS_LIB_DIR");
var candidates=new List<string>();
if(!string.IsNullOrWhiteSpace(configured))candidates.Add(Path.Combine(configured,"libMvCameraControl.so"));
candidates.AddRange(["/opt/MVS/lib/64/libMvCameraControl.so","/opt/MVS/lib/aarch64/libMvCameraControl.so","libMvCameraControl.so"]);
foreach(var candidate in candidates)if(NativeLibrary.TryLoad(candidate,out var handle))return handle;
throw new DllNotFoundException("未找到 Linux MVS 原生运行库。请安装与托管 SDK 匹配的 MVS,并设置 MVS_LIB_DIR 及 LD_LIBRARY_PATH。");
}
}

View File

@ -8,11 +8,8 @@
<NativePlatform Condition="$([System.String]::Copy('$(RuntimeIdentifier)').StartsWith('win'))">Windows</NativePlatform>
<NativePlatform Condition="'$(NativePlatform)' == '' and '$(OS)' == 'Windows_NT'">Windows</NativePlatform>
<NativePlatform Condition="'$(NativePlatform)' == ''">Linux</NativePlatform>
<MvsManagedSdk Condition="'$(NativePlatform)' == 'Linux'">../../libs/mvs/linux-x64/MvCameraControl.Net.dll</MvsManagedSdk>
<MvsManagedSdk Condition="'$(MvsManagedSdk)' == ''">../../libs/MvCameraControl.Net.dll</MvsManagedSdk>
</PropertyGroup>
<ItemGroup>
<Reference Include="MvCameraControl.Net"><HintPath>$(MvsManagedSdk)</HintPath><Private>true</Private></Reference>
<PackageReference Include="OpenCvSharp5" Version="5.0.0.20261107" />
<PackageReference Include="OpenCvSharp5.runtime.win" Version="5.0.0.20261107" Condition="'$(NativePlatform)' == 'Windows'" />
<PackageReference Include="OpenCvSharp5.official.runtime.linux-x64" Version="5.0.0.20261107" Condition="'$(NativePlatform)' == 'Linux'" />

View File

@ -181,7 +181,7 @@ internal static class Smoke
Check(model.Logs.Any(l=>l.Message.Contains("推理设备:")&&l.Message.Contains("步骤确认=")),"Inference backend diagnostics remain available in the runtime log");
_exit=0;return;
}
if(Environment.GetCommandLineArgs().Contains("--camera-lifecycle-only")) { await CheckCameraLifecycle(app,window); _exit=0; return; }
if(Environment.GetCommandLineArgs().Contains("--camera-lifecycle-only")) { CheckCameraPreferences(app); await CheckCameraLifecycle(app,window); _exit=0; return; }
if(Environment.GetCommandLineArgs().Contains("--usb-capture-only")) { await CheckUsbCapture(app); _exit=0; return; }
CheckCameraPreferences(app);
CheckRecipePreferences(app);
@ -503,7 +503,7 @@ internal static class Smoke
var path=Path.Combine(Environment.GetEnvironmentVariable("SOPHELPER_WORKSPACE_ROOT")!,"workspace","last-camera.json");
var before=File.Exists(path)?File.ReadAllBytes(path):null;
var first=new CameraInfo {Index=0,Name="测试相机"};
var preferred=new CameraInfo {Kind=CameraKind.Hikvision,SerialNumber="camera-preferred",Index=1,Name="首选相机"};
var preferred=new CameraInfo {Kind=CameraKind.Uvc,Index=1,Name="首选相机"};
void WithCameras(List<CameraInfo> devices,Action<SopPageViewModel,FakeCamera> check)
{
using var camera=new FakeCamera {Devices=devices};
@ -517,10 +517,10 @@ internal static class Smoke
WithCameras([first,preferred],(vm,_)=>
{
vm.SelectedCamera=preferred;
Check(!vm.IsRunning&&JsonSerializer.Deserialize<CameraInfo>(File.ReadAllText(path))!.SerialNumber==preferred.SerialNumber,"Changing camera saves immediately without starting acquisition");
Check(!vm.IsRunning&&JsonSerializer.Deserialize<CameraInfo>(File.ReadAllText(path))!.Index==preferred.Index,"Changing camera saves immediately without starting acquisition");
});
var reindexed=new CameraInfo {Kind=preferred.Kind,SerialNumber=preferred.SerialNumber,Index=7,Name=preferred.Name};
WithCameras([reindexed,first],(vm,_)=>Check(ReferenceEquals(vm.SelectedCamera,reindexed),"Restart restores the selected camera by serial number despite enumeration order/index changes"));
var reindexed=new CameraInfo {Kind=preferred.Kind,Index=preferred.Index,Name=preferred.Name};
WithCameras([reindexed,first],(vm,_)=>Check(ReferenceEquals(vm.SelectedCamera,reindexed),"Restart restores the selected USB camera by index despite enumeration order changes"));
var saved=File.ReadAllText(path);
WithCameras([first],(vm,camera)=>
{
@ -532,6 +532,8 @@ internal static class Smoke
vm.SelectedCamera=first;
});
WithCameras([reindexed,first],(vm,_)=>Check(ReferenceEquals(vm.SelectedCamera,first),"Switching camera without starting is restored on the next launch"));
File.WriteAllText(path,"{\"Kind\":1,\"Index\":9,\"Name\":\"旧设备\"}");
WithCameras([first,reindexed],(vm,_)=>Check(ReferenceEquals(vm.SelectedCamera,first),"A retired camera preference falls back to the first USB camera"));
}
finally
{
@ -659,8 +661,8 @@ internal static class Smoke
private static async Task CheckCameraLifecycle(App app,Window window)
{
var uvc=new FakeCamera();var hik=new FakeCamera();
var service=new CameraService(uvc,hik);
var uvc=new FakeCamera();
var service=new CameraService(uvc);
var camera=new CameraInfo {Index=0,UseCompatibilityBackend=true};
var mode=new UvcCaptureOptions {Width=1280,Height=720,Fps=30};
await service.ConnectAsync(camera);await service.ConfigureUvcAsync(mode);await service.StartAsync();service.Stop();
@ -673,14 +675,15 @@ internal static class Smoke
await service.ConnectAsync(new CameraInfo {Index=1,UseCompatibilityBackend=true});
await service.ConfigureUvcAsync(mode);
Check(uvc.DisconnectCount==1&&uvc.ConnectCount==2&&uvc.ConfigureCount==3,"Switching USB cameras releases the previous device and invalidates mode cache");
await service.ConnectAsync(new CameraInfo {Kind=CameraKind.Hikvision,SerialNumber="test-serial",Index=2});
await service.ConnectAsync(new CameraInfo {Kind=CameraKind.Hikvision,SerialNumber="test-serial",Index=9});
Check(uvc.DisconnectCount==2&&hik.ConnectCount==1,"Industrial cameras also reuse their connection by serial number");
service.Disconnect();var released=hik.DisconnectCount;
await service.ConnectAsync(new CameraInfo {Kind=CameraKind.Hikvision,SerialNumber="test-serial",Index=9});
Check(hik.DisconnectCount==released&&hik.ConnectCount==2,"Reconnecting an explicitly released device does not release it a second time");
var unsupported=false;
try { await service.ConnectAsync(new CameraInfo {Kind=(CameraKind)1,Index=9}); }
catch(ArgumentException) { unsupported=true; }
Check(unsupported&&uvc.ConnectCount==2&&uvc.IsConnected,"Retired camera kinds cannot open or replace the USB connection");
service.Disconnect();var released=uvc.DisconnectCount;
await service.ConnectAsync(new CameraInfo {Index=1});
Check(uvc.DisconnectCount==released&&uvc.ConnectCount==3,"Reconnecting an explicitly released USB device does not release it a second time");
service.Dispose();service.Dispose();
Check(uvc.DisposeCount==1&&hik.DisposeCount==1&&!hik.IsConnected,"Exit disposes each camera service once");
Check(uvc.DisposeCount==1&&!uvc.IsConnected,"Exit disposes the USB camera service once");
var rejected=false;try{await service.ConnectAsync(camera);}catch(ObjectDisposedException){rejected=true;}
Check(rejected,"Disposed services cannot reopen a camera");
@ -759,8 +762,9 @@ internal static class Smoke
var dialog=lifetime.Windows.OfType<SopHelper.VVMs.CameraSettings.CameraSettingsWindow>().Single();
try
{
Check(dialog.FindControl<Button>("DriverPropertiesButton") is null&&dialog.FindControl<ComboBox>("CaptureBackendPicker") is null,
"Camera configuration has no platform-specific driver dialog or backend selector");
Check(dialog.FindControl<Button>("DriverPropertiesButton") is null&&dialog.FindControl<ComboBox>("CaptureBackendPicker") is null
&&dialog.FindControl<TextBox>("ExposureInput") is null,
"Camera configuration contains only USB controls without industrial exposure or backend selection");
dialog.FindControl<ComboBox>("ResolutionPicker")!.SelectedItem=dialog.Model.Resolutions.Single(r=>r.Width==1920&&r.Height==1080);
dialog.FindControl<ComboBox>("FrameRatePicker")!.SelectedItem=dialog.Model.FrameRates.Single(r=>r.Fps==30);
dialog.FindControl<ComboBox>("FormatPicker")!.SelectedItem="MJPG";

View File

@ -13,15 +13,25 @@ try
var usb=new CameraInfo {Index=0};
if(!store.Load(usb).UsbCapture.IsDefault)throw new Exception("旧录像目录应使用默认相机参数");
Console.WriteLine("PASS: 旧录像目录文件不再阻止读取相机参数");
File.WriteAllText(legacy,"{\"Uvc:0\":{\"UsbCapture\":{\"Width\":640,\"Height\":480}},\"Uvc:2\":{\"ExposureTimeUs\":1000}}");
File.WriteAllText(legacy,"{\"Uvc:0\":{\"UsbCapture\":{\"Width\":640,\"Height\":480}},\"Uvc:2\":{\"UsbCapture\":{\"Fps\":15}}}");
if(store.Load(usb).UsbCapture.Width!=640)throw new Exception("现有设备参数没有迁移");
var settings=new CameraDeviceSettings {UsbCapture=new() {Width=1280,Height=720,Format="MJPG",Fps=30}};
store.Save(usb,settings);
if(store.Load(usb).UsbCapture.Width!=1280||store.Load(new CameraInfo {Index=2}).ExposureTimeUs!=1000)throw new Exception("保存时丢失设备参数");
if(store.Load(usb).UsbCapture.Width!=1280||store.Load(new CameraInfo {Index=2}).UsbCapture.Fps!=15)throw new Exception("保存时丢失设备参数");
File.WriteAllText(legacy,original);
if(store.Load(usb).UsbCapture.Width!=1280)throw new Exception("录像目录覆盖了设备参数");
store.Save(usb,settings);
if(File.ReadAllText(legacy)!=original)throw new Exception("保存相机参数改写了录像目录");
File.WriteAllText(store.FilePath,"{\"Uvc:0\":{\"UsbCapture\":{\"Fps\":30},\"ExposureTimeUs\":1000},\"Hikvision:old\":\"unused legacy data\"}");
if(store.Load(usb).UsbCapture.Fps!=30)throw new Exception("旧工业相机参数影响 USB 参数读取");
using(var camera=new SettingsProbe())
{
await store.ApplyAsync(camera,usb);
if(camera.Options?.Fps!=30)throw new Exception("USB 配置没有传递给采集后端");
}
if(Enum.GetValues<CameraKind>().Length!=1||Enum.GetValues<CameraKind>()[0]!=CameraKind.Uvc)throw new Exception("仍暴露非 USB 相机类型");
if(typeof(CameraService).Assembly.GetReferencedAssemblies().Any(a=>a.Name?.Contains("MvCamera",StringComparison.OrdinalIgnoreCase)==true))throw new Exception("仍依赖工业相机 SDK");
Console.WriteLine("PASS: 仅保留 USB 类型与采集配置,旧工业相机参数不会参与配置,运行时无工业 SDK 依赖");
Console.WriteLine("PASS: 旧设备参数可迁移;录像目录与设备参数互不覆盖");
}
finally {Directory.Delete(root,true);}
@ -44,3 +54,20 @@ if(args.Contains("--hardware"))
if(frames<10)throw new Exception("相机未持续输出图像,帧数="+frames);
Console.WriteLine(JsonSerializer.Serialize(new {passed=true,camera=selected.Name,frames,width,height}));
}
sealed class SettingsProbe : ICameraService
{
public UvcCaptureOptions? Options;
public bool IsConnected=>true;
public bool IsGrabbing=>false;
public event Action<CameraFrame>? FrameArrived {add{} remove{}}
public event Action<bool>? ConnectionChanged {add{} remove{}}
public event Action<string>? Error {add{} remove{}}
public Task<List<CameraInfo>> EnumerateAsync()=>Task.FromResult(new List<CameraInfo>());
public Task<bool> ConnectAsync(CameraInfo camera)=>Task.FromResult(true);
public Task<string> ConfigureUvcAsync(UvcCaptureOptions options) {Options=options;return Task.FromResult("USB");}
public Task<bool> StartAsync()=>Task.FromResult(true);
public void Stop(){}
public void Disconnect(){}
public void Dispose(){}
}

View File

@ -1,10 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup><OutputType>Exe</OutputType><TargetFramework>net8.0</TargetFramework><Nullable>enable</Nullable><ImplicitUsings>enable</ImplicitUsings></PropertyGroup>
<ItemGroup>
<ProjectReference Include="../../src/SopHelper.CrossPlatform.Engine/SopHelper.CrossPlatform.Engine.csproj" />
<Reference Include="MvCameraControl.Net">
<HintPath Condition="'$(NativePlatform)' == 'Linux'">../../libs/mvs/linux-x64/MvCameraControl.Net.dll</HintPath>
<HintPath Condition="'$(NativePlatform)' != 'Linux'">../../libs/MvCameraControl.Net.dll</HintPath>
</Reference>
</ItemGroup>
</Project>

View File

@ -1,163 +0,0 @@
using MvCameraControl;
using SopHelper.Engine.Camera;
using OpenCvSharp;
using System.Diagnostics;
using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;
try
{
using var camera=new HikvisionCameraService();
var errors=new List<string>();
camera.Error+=message=>{errors.Add(message);Console.Error.WriteLine(message);};
Console.WriteLine("SDK: "+SDKSystem.GetSDKVersion());
var cameras=await camera.EnumerateAsync();
foreach(var device in cameras)Console.WriteLine($"DEVICE: {device.Name}");
if(errors.Count>0)throw new Exception("Camera enumeration reported an error");
Console.WriteLine($"PASS: SDK initialized and enumerated {cameras.Count} camera(s)");
var d3BenchmarkIndex = Array.IndexOf(args, "--d3-benchmark");
var benchmarkIndex = d3BenchmarkIndex >= 0 ? d3BenchmarkIndex : Array.IndexOf(args, "--imajev-benchmark");
if (benchmarkIndex >= 0)
{
if (benchmarkIndex + 1 >= args.Length) throw new ArgumentException("AI benchmark requires an output directory");
var directory = Path.GetFullPath(args[benchmarkIndex + 1]);
Directory.CreateDirectory(directory);
var device = cameras.FirstOrDefault() ?? throw new Exception("No Hikvision camera found");
TaskCompletionSource<(Mat Image, long Started)>? requested = null;
var seen = 0;
camera.FrameArrived += frame =>
{
if (Interlocked.Increment(ref seen) < 5) return;
var pending = Interlocked.Exchange(ref requested, null);
if (pending is not null)
{
var started = Stopwatch.GetTimestamp();
pending.TrySetResult((frame.Bgr.Clone(), started));
}
};
if (!await camera.ConnectAsync(device) || !await camera.StartAsync()) throw new Exception("Open/start failed");
using var http = new HttpClient { Timeout = TimeSpan.FromSeconds(30) };
var runs = new List<object>();
for (var index = 0; index <= 20; index++)
{
var next = new TaskCompletionSource<(Mat Image, long Started)>(TaskCreationOptions.RunContinuationsAsynchronously);
Interlocked.Exchange(ref requested, next);
var captured = await next.Task.WaitAsync(TimeSpan.FromSeconds(10));
using var image = captured.Image;
using var resized = new Mat();
var scale = 512.0 / Math.Max(image.Width, image.Height);
Cv2.Resize(image, resized, new Size((int)Math.Round(image.Width * scale), (int)Math.Round(image.Height * scale)), 0, 0, InterpolationFlags.Area);
if (!Cv2.ImEncode(".jpg", resized, out var jpeg)) throw new IOException("JPEG encode failed");
var preparedMs = Stopwatch.GetElapsedTime(captured.Started).TotalMilliseconds;
using HttpContent body = d3BenchmarkIndex >= 0
? new StringContent(JsonSerializer.Serialize(new { state = "", images = new[] { "data:image/jpeg;base64," + Convert.ToBase64String(jpeg) }, questions = new { empty = new { type = "noul", instructions = "盒子空了没?" } } }), Encoding.UTF8, "application/json")
: new MultipartFormDataContent();
if (body is MultipartFormDataContent form)
{
form.Add(new StringContent(JsonSerializer.Serialize(new { state = new { }, questions = new { empty = new { type = "noul", instructions = "Is the open cardboard box empty inside? Empty means there are no objects inside the box. Ignore objects outside the box." } } }), Encoding.UTF8), "request");
var content = new ByteArrayContent(jpeg);
content.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");
form.Add(content, "image", "camera.jpg");
}
var endpoint = d3BenchmarkIndex >= 0 ? "http://127.0.0.1:8766/v1/systemone" : "http://127.0.0.1:8765/v1/systemone";
using var response = await http.PostAsync(endpoint, body);
response.EnsureSuccessStatusCode();
var json = await response.Content.ReadAsStringAsync();
using var result = JsonDocument.Parse(json);
if (d3BenchmarkIndex >= 0)
{
var digest = Convert.ToHexString(System.Security.Cryptography.SHA256.HashData(jpeg)).ToLowerInvariant();
if (result.RootElement.GetProperty("usage").GetProperty("image_sha256")[0].GetString() != digest)
throw new InvalidOperationException("D3 server received a different image");
}
var totalMs = Stopwatch.GetElapsedTime(captured.Started).TotalMilliseconds;
if (index == 0) File.WriteAllBytes(Path.Combine(directory, "fresh-camera-input.jpg"), jpeg);
var entry = new { index, warmup = index == 0, preprocess_ms = preparedMs, frame_to_result_ms = totalMs, response = result.RootElement.Clone() };
runs.Add(entry);
File.WriteAllText(Path.Combine(directory, "camera-e2e.json"), JsonSerializer.Serialize(new { camera = device.Name, scope = "From decoded BGR frame callback before clone, resize and JPEG encode through HTTP response parsing; excludes exposure, sensor readout, camera transport and camera startup", runs }, new JsonSerializerOptions { WriteIndented = true }));
Console.WriteLine($"CAMERA AI: {index}, preprocess={preparedMs:F1}ms, frame_to_result={totalMs:F1}ms");
}
camera.Disconnect();
return 0;
}
var snapshotIndex = Array.IndexOf(args, "--snapshot");
if (snapshotIndex >= 0)
{
if (snapshotIndex + 1 >= args.Length) throw new ArgumentException("--snapshot requires an output path");
var path = Path.GetFullPath(args[snapshotIndex + 1]);
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
var device = cameras.FirstOrDefault() ?? throw new Exception("No Hikvision camera found");
var ready = new TaskCompletionSource<Mat>(TaskCreationOptions.RunContinuationsAsynchronously);
var frames = 0;
camera.FrameArrived += frame =>
{
if (Interlocked.Increment(ref frames) == 5) ready.TrySetResult(frame.Bgr.Clone());
};
var watch = System.Diagnostics.Stopwatch.StartNew();
if (!await camera.ConnectAsync(device) || !await camera.StartAsync()) throw new Exception("Open/start failed");
using var captured = await ready.Task.WaitAsync(TimeSpan.FromSeconds(15));
watch.Stop();
camera.Disconnect();
if (!Cv2.ImWrite(path, captured)) throw new IOException("Snapshot write failed");
Console.WriteLine($"SNAPSHOT: {path}; {captured.Width}x{captured.Height}; camera={device.Name}; open/start/5 frames={watch.Elapsed.TotalMilliseconds:F1}ms");
return 0;
}
if(args.Contains("--inspect-timing"))
{
var result=DeviceEnumerator.EnumDevices(DeviceTLayerType.MvGigEDevice|DeviceTLayerType.MvUsbDevice,out var infos);
if(result!=MvError.MV_OK||infos.Count==0)throw new Exception("Enumeration failed");
using var device=DeviceFactory.CreateDevice(infos[0]);
if(device.Open()!=MvError.MV_OK)throw new Exception("Open failed");
try
{
foreach(var node in new[]{"ExposureTime","AcquisitionFrameRate","ResultingFrameRate"})
if(device.Parameters.GetFloatValue(node,out var value)==MvError.MV_OK)
Console.WriteLine($"TIMING: {node}={value.CurValue} (max={value.Max})");
foreach(var node in new[]{"PayloadSize","DeviceLinkThroughputLimit","GevSCPSPacketSize","GevSCPD"})
if(device.Parameters.GetIntValue(node,out var value)==MvError.MV_OK)
Console.WriteLine($"TRANSPORT: {node}={value.CurValue}");
}
finally { device.Close(); }
}
if(args.Contains("--inspect-frame"))
{
var result=DeviceEnumerator.EnumDevices(DeviceTLayerType.MvGigEDevice|DeviceTLayerType.MvUsbDevice,out var infos);
if(result!=MvError.MV_OK||infos.Count==0)throw new Exception("Enumeration failed");
using var device=DeviceFactory.CreateDevice(infos[0]);
Console.WriteLine($"OPEN: 0x{device.Open():X8}");
device.Parameters.SetEnumValueByString("TriggerMode","Off");
try
{
Console.WriteLine($"START: 0x{device.StreamGrabber.StartGrabbing():X8}");
result=device.StreamGrabber.GetImageBuffer(3000,out var buffer);
Console.WriteLine($"GET: 0x{result:X8}");
if(result==MvError.MV_OK)
{
try
{
foreach(var p in typeof(IImage).GetProperties().Where(p=>p.Name!="PixelData"))Console.WriteLine($"IMAGE {p.Name}: {p.GetValue(buffer.Image)}");
result=device.PixelTypeConverter.ConvertPixelType(buffer.Image,out var converted,MvGvspPixelType.PixelType_Gvsp_BGR8_Packed);
using(converted)Console.WriteLine($"CONVERT: 0x{result:X8}");
}
finally{device.StreamGrabber.FreeImageBuffer(buffer);}
}
}
finally{device.StreamGrabber.StopGrabbing();device.Close();}
}
if(args.Contains("--hardware"))
{
var device=cameras.FirstOrDefault()??throw new Exception("No camera found");
var ready=new TaskCompletionSource<(int W,int H)>(TaskCreationOptions.RunContinuationsAsynchronously);
var frames=0;
camera.FrameArrived+=frame=>{if(Interlocked.Increment(ref frames)>=5)ready.TrySetResult((frame.Bgr.Width,frame.Bgr.Height));};
if(!await camera.ConnectAsync(device)||!await camera.StartAsync())throw new Exception("Open/start failed");
var frame=await ready.Task.WaitAsync(TimeSpan.FromSeconds(10));
camera.Disconnect();
Console.WriteLine($"PASS: acquired {frames} {frame.W}x{frame.H} BGR frames and released camera");
if(!await camera.ConnectAsync(device))throw new Exception("Camera could not reopen after disconnect");
camera.Disconnect();Console.WriteLine("PASS: camera reopened after release");
}
return 0;
}
catch(Exception error){Console.Error.WriteLine(error);return 1;}

View File

@ -23,7 +23,7 @@ internal static class PreviewSmoke
[STAThread]
public static int Main(string[] args)
{
Camera = args.Contains("--hardware") ? new HikvisionCameraService() : new SyntheticCamera();
Camera = args.Contains("--hardware") ? new UvcCameraService() : new SyntheticCamera();
Camera.FrameArrived += _ => Interlocked.Increment(ref _acquired);
Camera.Error += Console.Error.WriteLine;
var cameraPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "SopHelper", "last-camera.json");
@ -61,7 +61,7 @@ internal static class PreviewSmoke
probeWindow.Close();
var sop = ((App)Application.Current!).Container.Resolve<SopPageViewModel>();
for (var i = 0; i < 100 && sop.Cameras.Count == 0; i++) await Task.Delay(20);
sop.SelectedCamera = sop.Cameras.Single();
sop.SelectedCamera = sop.SelectedCamera ?? sop.Cameras.FirstOrDefault() ?? throw new Exception("未枚举到 USB 相机");
sop.StartStopCommand.Execute();
for (var i = 0; i < 100 && !sop.IsRunning; i++) await Task.Delay(50);
if (!sop.IsRunning) throw new Exception("Synthetic camera failed to start");
@ -78,7 +78,7 @@ internal static class PreviewSmoke
var fps = changes / seconds;
var pipeline = ((App)Application.Current!).Container.Resolve<DetectionPipeline>();
sop.PropertyChanged -= changed;
Console.WriteLine(JsonSerializer.Serialize(new { renderer, camera = Camera is SyntheticCamera ? "synthetic" : "hikvision",
Console.WriteLine(JsonSerializer.Serialize(new { renderer, camera = Camera is SyntheticCamera ? "synthetic" : "usb",
width = sop.FrameWidth, height = sop.FrameHeight,
previewUpdatesPerSecond = fps, acquisitionFps = (Interlocked.Read(ref _acquired) - produced) / seconds, status = sop.FpsText,
handBackend = pipeline.HandBackend, inferenceMs = pipeline.AvgInferenceMs }));

View File

@ -21,7 +21,7 @@ using Point = Avalonia.Point;
internal static class Program
{
[STAThread]
public static void Main()
public static void Main(string[] args)
{
var root = Path.Combine(Path.GetTempPath(), "recording-limit-smoke-" + Guid.NewGuid().ToString("N"));
var previousRoot = Environment.GetEnvironmentVariable("SOPHELPER_WORKSPACE_ROOT");
@ -31,8 +31,7 @@ internal static class Program
AppBuilder.Configure<Application>().UseSkia().UseHeadless(new AvaloniaHeadlessPlatformOptions { UseHeadlessDrawing = false }).SetupWithoutStarting();
Application.Current!.Styles.Add(new FluentTheme());
Application.Current.Styles.Add(new StyleInclude(new Uri("avares://SopHelper.Avalonia/")) { Source = new Uri("avares://SopHelper.Avalonia/Themes/Styles.axaml") });
CheckRunStatistics();
CheckStandardDuration(root);
if (!args.Contains("--usb-camera-only")) { CheckRunStatistics(); CheckStandardDuration(root); }
Check(VideoRecorder.MaximumDuration == TimeSpan.FromMinutes(5), "Production recording limit is five minutes");
var clock = new ManualClock();
using var camera = new FakeCamera();
@ -44,12 +43,23 @@ internal static class Program
CheckRecordingButtons(window, model, false, false);
Check(!model.PreviewCommand.CanExecute() && model.SelectedCameraName.Contains("运行设置"), "Recording requires the camera selected in runtime settings");
Check(!window.GetVisualDescendants().OfType<ComboBox>().Any() && !window.GetVisualDescendants().OfType<Button>().Any(b => b.Content?.ToString() == "刷新相机"), "Recording window has no camera selector or refresh button");
selected = new CameraInfo { Kind = CameraKind.Hikvision, Index = 7, SerialNumber = "GLOBAL-CAMERA", Name = "运行设置中的相机" };
selected = new CameraInfo { Kind = CameraKind.Uvc, Index = 7, Name = "运行设置中的相机" };
Tick(model); model.PreviewCommand.Execute();
Check(ReferenceEquals(camera.ConnectedCamera, selected) && camera.EnumerationCount == 0, "Recording uses the exact global camera without enumerating devices");
Thread.Sleep(75); camera.Emit(); Dispatcher.UIThread.RunJobs();
Check(model.StartRecordingCommand.CanExecute(), "Preview is ready for recording");
CheckRecordingButtons(window, model, true, false);
if (args.Contains("--usb-camera-only"))
{
model.StartRecordingCommand.Execute();
clock.Advance(TimeSpan.FromSeconds(1));camera.Emit();Tick(model);
model.StopRecordingCommand.Execute();
Check(!model.IsRecording&&model.IsPreviewing,"USB recording saves while keeping preview active");
CheckVideo(model.LastRecording,1);
Pump(model.ShutdownAsync());window.Close();
Check(!camera.IsConnected&&!camera.IsGrabbing,"Closing USB recording releases the camera");
return;
}
var notices = 0;
model.RecordingLimitReached += message => { notices++; Check(message.Contains("5分钟") && message.Contains(model.LastRecording), "Timeout notice contains the limit and saved path"); };
model.StartRecordingCommand.Execute();
@ -253,9 +263,9 @@ internal static class Program
Pump(other.ShutdownAsync());
var fresh = new RecipeEditorViewModel(); var newConfig = new SopConfig(); newConfig.Sop.Name = "新配方";
fresh.OnDialogOpened(new DialogParameters { { "directory", store.RecipesDirectory }, { "config", newConfig }, { "new", true } });
Check(!fresh.HasSopRecording && fresh.TrainingView is null, "Unsaved recipes cannot record or train into an ambiguous directory");
Check(!fresh.HasSopRecording, "Unsaved recipes cannot record into an ambiguous directory");
fresh.SaveCommand.Execute(); Check(fresh.HasSopRecording, "Saving a new recipe enables its SOP recording page");
Check(fresh.TrainingView?.Model.RecipeName == "新配方", "Saving a new recipe creates training bound to that recipe");
Check(fresh.SopRecording?.StandardVideoPath == Path.Combine(store.DirectoryFor("新配方"), "sop_stand", "sop.avi"), "Saving a new recipe binds SOP recording to its own directory");
Pump(fresh.ShutdownSopRecordingAsync()); fresh.OnDialogClosed();
}
private static Window FindSopDialog(RecipeEditor editor)

View File

@ -5,13 +5,9 @@ $ErrorActionPreference = 'Stop'
if ($Target -notmatch '^[a-zA-Z0-9_.-]+@[a-zA-Z0-9_.-]+$') { throw 'Target must be user@host' }
$repo = Split-Path $PSScriptRoot -Parent
$release = 'avalonia-' + (Get-Date -Format 'yyyyMMdd-HHmmss')
$output = Join-Path $repo "artifacts/$release"
$output = Join-Path $repo 'artifacts/avalonia/linux-x64'
& dotnet publish (Join-Path $repo 'src/SopHelper.Avalonia') -c Release -r linux-x64 --self-contained true -p:PublishSingleFile=false -p:NativePlatform=Linux -o $output --nologo
if ($LASTEXITCODE) { throw 'Publish failed' }
$sdkExpected=Join-Path $repo 'libs/mvs/linux-x64/MvCameraControl.Net.dll'
if ((Get-FileHash $sdkExpected).Hash -ne (Get-FileHash (Join-Path $output 'MvCameraControl.Net.dll')).Hash) {
throw 'Linux package contains the wrong MVS managed binding'
}
$archive = Join-Path $repo "artifacts/$release.tar.gz"
& tar -czf $archive -C $output .
if ($LASTEXITCODE) { throw 'Packaging failed' }

View File

@ -20,18 +20,7 @@ foreach ($rid in $RuntimeIdentifiers) {
$nativePlatform=if($rid -eq 'win-x64'){'Windows'}else{'Linux'}
& dotnet publish $project -c Release -r $rid --self-contained true -p:PublishSingleFile=false -p:BundlePythonRuntime=false "-p:NativePlatform=$nativePlatform" -o $destination --nologo
if ($LASTEXITCODE) { throw "Publish failed: $rid" }
$sdkSource=if($rid -eq 'linux-x64'){'libs/mvs/linux-x64/MvCameraControl.Net.dll'}else{'libs/MvCameraControl.Net.dll'}
if ((Get-FileHash (Join-Path $repo $sdkSource)).Hash -ne (Get-FileHash (Join-Path $destination 'MvCameraControl.Net.dll')).Hash) {
throw "Wrong vendor MVS binding in $rid package"
}
[IO.File]::WriteAllText((Join-Path $destination 'source-manifest.json'),$sourceJson,[Text.UTF8Encoding]::new($false))
if ($rid -eq 'win-x64') {
$mvs=Join-Path ${env:ProgramFiles(x86)} 'Common Files/MVS/Runtime/Win64_x64'
if(Test-Path -LiteralPath $mvs) {
& robocopy $mvs $destination /E /NFL /NDL /NJH /NJS /NP
if($LASTEXITCODE -ge 8){throw 'MVS runtime copy failed'}
}
}
}
$hashes=@($RuntimeIdentifiers | ForEach-Object { (Get-FileHash (Join-Path $OutputRoot "$_/source-manifest.json")).Hash } | Select-Object -Unique)
if ($hashes.Count -ne 1) { throw 'Published source manifests differ.' }