This commit is contained in:
ldh
2026-11-17 16:28:24 +08:00
parent b30d9f92ce
commit 19b7b10e97
28 changed files with 3891 additions and 46 deletions
@@ -0,0 +1,141 @@
using HardwareControl.Core.HardwareServiceImpl.HardwareService;
using HardwareControl.Core.SampleAnalysis;
using HardwareControl.Core.SystemSetting;
using HardwareControl.Core.UsbCamera;
using Microsoft.Extensions.Logging;
namespace HardwareControl.Core.HardwareServiceImpl
{
/// <summary>
/// 采集基准画面 / 靶样画面并调用 ONNX 模型分析。
/// 作为单例使用,保存本次检测的画面。
/// </summary>
public sealed class SampleAnalysisService : ISampleAnalysisService
{
private const string SamplingPointConfigName = "camera_sampling_point";
private const int DefaultSamplingPointCount = 5;
private const int MaxSamplingPointCount = 100;
private readonly IUsbCameraService _camera;
private readonly ISystemConfigService _systemConfig;
private readonly TargetOutlineAnalyzer _analyzer;
private readonly ILogger<SampleAnalysisService> _logger;
private readonly object _gate = new();
private IReadOnlyList<CameraFrameSnapshot>? _baseline;
private CameraFrameSnapshot? _target;
public SampleAnalysisService(
IUsbCameraService camera,
ISystemConfigService systemConfig,
TargetOutlineAnalyzer analyzer,
ILogger<SampleAnalysisService> logger)
{
_camera = camera;
_systemConfig = systemConfig;
_analyzer = analyzer;
_logger = logger;
}
public Task<SampleBaselineInfo> CaptureBaselineAsync(
CancellationToken ct = default)
{
ct.ThrowIfCancellationRequested();
var frame = CaptureLatestFrame();
lock (_gate)
{
_baseline = new[] { frame };
_target = null;
}
_logger.LogInformation(
"基准画面已采集:{Width}x{Height}", frame.Width, frame.Height);
return Task.FromResult(
new SampleBaselineInfo(frame.Width, frame.Height, frame.CapturedAt));
}
public SampleTargetInfo CaptureTarget()
{
var frame = CaptureLatestFrame();
lock (_gate)
{
if (_baseline is null || _baseline.Count == 0)
{
throw new HardwareException(
HardwareErrorKind.InvalidState,
"尚未采集基准画面,请等待相机画面稳定后再试");
}
_target = frame;
}
_logger.LogInformation(
"靶样画面已采集:{Width}x{Height}", frame.Width, frame.Height);
return new SampleTargetInfo(frame.Width, frame.Height, frame.CapturedAt);
}
public SampleAnalysisResult Analyze()
{
IReadOnlyList<CameraFrameSnapshot> baseline;
CameraFrameSnapshot target;
lock (_gate)
{
baseline = _baseline ?? throw new HardwareException(
HardwareErrorKind.InvalidState,
"尚未采集基准画面,请返回样品放置界面重新检测");
target = _target ?? throw new HardwareException(
HardwareErrorKind.InvalidState,
"尚未采集靶样画面,请返回样品放置界面重新检测");
}
var pointCount = GetSamplingPointCount();
_logger.LogInformation("开始靶样轮廓分析,采样点数:{PointCount}", pointCount);
var result = _analyzer.Analyze(baseline, target, pointCount);
_logger.LogInformation(
"靶样轮廓分析完成:{Width}x{Height},采样点 {PointCount} 个",
result.Width,
result.Height,
result.SamplingPointCount);
return result;
}
private CameraFrameSnapshot CaptureLatestFrame() =>
_camera.GetLatestFrame() ?? throw new HardwareException(
HardwareErrorKind.NotConnected,
"相机尚未产生画面,请确认相机已连接");
private int GetSamplingPointCount()
{
try
{
var config = _systemConfig
.GetAll()
.FirstOrDefault(c => string.Equals(
c.ConfigName, SamplingPointConfigName, StringComparison.OrdinalIgnoreCase));
if (int.TryParse(config?.ConfigValue, out var count) && count > 0)
{
return Math.Min(count, MaxSamplingPointCount);
}
}
catch (Exception ex)
{
_logger.LogWarning(
ex, "读取系统参数 {ConfigName} 失败,使用默认采样点数",
SamplingPointConfigName);
}
return DefaultSamplingPointCount;
}
}
}
@@ -8,8 +8,12 @@ namespace HardwareControl.Core.HardwareServiceImpl
{
public class UsbCameraService : IUsbCameraService
{
// 系统参数中保存相机硬件 ID 的配置名称
private const string CameraVidConfigName = "camera_vid";
private readonly UsbCameraOptions _options;
private readonly ILogger<UsbCameraService> _logger;
private readonly ISystemConfigService? _systemConfig;
// 串行化所有对 FlashCap 设备对象的访问
private readonly SemaphoreSlim _gate = new(1, 1);
@@ -23,6 +27,7 @@ namespace HardwareControl.Core.HardwareServiceImpl
private long _lastFrameAtTicks;
private long _framesReceived;
private long _connectedAtTicks;
private volatile CameraFrameSnapshot? _latestFrame;
public bool IsConnected => _connected;
@@ -41,15 +46,57 @@ namespace HardwareControl.Core.HardwareServiceImpl
public long FramesReceived => Interlocked.Read(ref _framesReceived);
public CameraFrameSnapshot? GetLatestFrame() => _latestFrame;
public event EventHandler<UsbCameraStatusChangedEventArgs>? StatusChanged;
public event EventHandler<FrameArrivedEventArgs>? FrameArrived;
public UsbCameraService(
IOptions<UsbCameraOptions> options,
ILogger<UsbCameraService> logger)
ILogger<UsbCameraService> logger,
ISystemConfigService? systemConfig = null)
{
_options = options.Value;
_logger = logger;
_systemConfig = systemConfig;
RefreshCameraVid();
}
/// <summary>
/// 从系统参数读取 camera_vid 并写入 <see cref="UsbCameraOptions"/>。
/// 读取失败时保留原有配置,不影响相机连接流程。
/// </summary>
private void RefreshCameraVid()
{
if (_systemConfig is null)
{
return;
}
try
{
var config = _systemConfig
.GetAll()
.FirstOrDefault(c => string.Equals(
c.ConfigName, CameraVidConfigName, StringComparison.OrdinalIgnoreCase));
var value = config?.ConfigValue?.Trim();
if (string.IsNullOrWhiteSpace(value) ||
string.Equals(_options.CameraVid, value, StringComparison.Ordinal))
{
return;
}
_options.CameraVid = value;
_logger.LogInformation(
"相机选择使用系统参数 {ConfigName}={CameraVid}",
CameraVidConfigName,
value);
}
catch (Exception ex)
{
_logger.LogWarning(ex, "读取系统参数 {ConfigName} 失败", CameraVidConfigName);
}
}
// ---------- 连接 ----------
@@ -72,6 +119,11 @@ namespace HardwareControl.Core.HardwareServiceImpl
{
try
{
// 每次连接前重新读取系统参数,管理界面修改 camera_vid 后重连即可生效
RefreshCameraVid();
_latestFrame = null;
var devices = new CaptureDevices();
var descriptors = devices.EnumerateDescriptors().ToList();
@@ -117,6 +169,15 @@ namespace HardwareControl.Core.HardwareServiceImpl
Interlocked.Increment(ref _framesReceived);
Interlocked.Exchange(ref _lastFrameAtTicks, capturedAt.UtcTicks);
// 缓存独立副本,供后台按需抓帧(事件回调仍使用同一份数据)
_latestFrame = new CameraFrameSnapshot(
image,
format.Width,
format.Height,
format.MimeType,
capturedAt,
frameIndex);
FrameArrived?.Invoke(
this,
new FrameArrivedEventArgs(
@@ -144,6 +205,7 @@ namespace HardwareControl.Core.HardwareServiceImpl
_connected = false;
_frameFormat = null;
_deviceName = null;
_latestFrame = null;
_device?.Dispose();
_device = null;
throw;
@@ -153,6 +215,7 @@ namespace HardwareControl.Core.HardwareServiceImpl
_connected = false;
_frameFormat = null;
_deviceName = null;
_latestFrame = null;
_device?.Dispose();
_device = null;
@@ -165,6 +228,26 @@ namespace HardwareControl.Core.HardwareServiceImpl
private CaptureDeviceDescriptor SelectDescriptor(
List<CaptureDeviceDescriptor> descriptors)
{
// 优先按系统参数 camera_vid 匹配设备的 Identity。
// Identity 在不同设备/平台上大小写不一致,统一转大写后比较。
var cameraVid = _options.CameraVid?.Trim();
if (!string.IsNullOrWhiteSpace(cameraVid))
{
var target = cameraVid.ToUpperInvariant();
var matched = descriptors.FirstOrDefault(d =>
{
var identity = d.Identity?.ToString();
return identity is not null &&
identity.ToUpperInvariant().Contains(target);
});
if (matched != null) return matched;
_logger.LogWarning(
"未找到 Identity 包含 {CameraVid} 的相机,回退到名称关键词选择",
cameraVid);
}
if (!string.IsNullOrWhiteSpace(_options.DeviceNameKeyword))
{
var matched = descriptors.FirstOrDefault(
@@ -221,6 +304,7 @@ namespace HardwareControl.Core.HardwareServiceImpl
{
CancelReconnectWatcher();
await StopDeviceAsync();
_latestFrame = null;
if (_connected)
{
@@ -385,6 +469,7 @@ namespace HardwareControl.Core.HardwareServiceImpl
_connected = false;
Interlocked.Exchange(ref _connectedAtTicks, 0);
_latestFrame = null;
await StopDeviceAsync();
StatusChanged?.Invoke(this, new(false, message));
}