231 lines
8.2 KiB
C#
231 lines
8.2 KiB
C#
using System.Globalization;
|
||
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 string SamplingRadiusConfigName = "camera_sampling_radius";
|
||
private const string CameraScaleConfigName = "camera_scale";
|
||
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;
|
||
private SampleAnalysisResult? _lastAnalysis;
|
||
|
||
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;
|
||
_lastAnalysis = null;
|
||
}
|
||
|
||
_logger.LogInformation(
|
||
"基准画面已采集:{Width}x{Height}", frame.Width, frame.Height);
|
||
|
||
return Task.FromResult(
|
||
new SampleBaselineInfo(frame.Width, frame.Height, frame.CapturedAt));
|
||
}
|
||
|
||
public Task<SampleTargetInfo> CaptureTargetAsync(
|
||
CancellationToken ct = default)
|
||
{
|
||
ct.ThrowIfCancellationRequested();
|
||
|
||
var frame = CaptureLatestFrame();
|
||
|
||
lock (_gate)
|
||
{
|
||
if (_baseline is null || _baseline.Count == 0)
|
||
{
|
||
throw new HardwareException(
|
||
HardwareErrorKind.InvalidState,
|
||
"尚未采集基准画面,请等待相机画面稳定后再试");
|
||
}
|
||
|
||
_target = frame;
|
||
_lastAnalysis = null;
|
||
}
|
||
|
||
_logger.LogInformation(
|
||
"靶样画面已采集:{Width}x{Height}", frame.Width, frame.Height);
|
||
|
||
return Task.FromResult(
|
||
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,
|
||
"尚未采集靶样画面,请返回样品放置界面重新检测");
|
||
|
||
// 同一组画面重复调用 Analyze 时直接返回缓存,避免重复执行 ONNX 推理。
|
||
if (_lastAnalysis is not null)
|
||
{
|
||
return _lastAnalysis;
|
||
}
|
||
}
|
||
|
||
var pointCount = GetSamplingPointCount();
|
||
var samplingRadiusPixels = GetSamplingRadiusPixels();
|
||
|
||
_logger.LogInformation(
|
||
"开始靶样轮廓分析,采样点数:{PointCount},采样半径:{Radius}",
|
||
pointCount,
|
||
samplingRadiusPixels is > 0
|
||
? $"{samplingRadiusPixels.Value:F1}px"
|
||
: "不限制");
|
||
|
||
var result = _analyzer.Analyze(
|
||
baseline, target, pointCount, samplingRadiusPixels);
|
||
|
||
_logger.LogInformation(
|
||
"靶样轮廓分析完成:{Width}x{Height},采样点 {PointCount} 个",
|
||
result.Width,
|
||
result.Height,
|
||
result.SamplingPointCount);
|
||
|
||
lock (_gate)
|
||
{
|
||
// 分析期间如果靶样画面已被重新采集,则不缓存本次结果。
|
||
if (ReferenceEquals(_target, target))
|
||
{
|
||
_lastAnalysis = result;
|
||
}
|
||
}
|
||
|
||
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;
|
||
}
|
||
|
||
/// <summary>
|
||
/// 读取系统参数 camera_sampling_radius(mm),按 camera_scale(px/mm)
|
||
/// 换算成像素半径;未配置或无效时返回 null,表示不限制采样区域。
|
||
/// </summary>
|
||
private double? GetSamplingRadiusPixels()
|
||
{
|
||
try
|
||
{
|
||
var values = _systemConfig
|
||
.GetAll()
|
||
.Where(c => !string.IsNullOrWhiteSpace(c.ConfigName))
|
||
.GroupBy(c => c.ConfigName.Trim(), StringComparer.OrdinalIgnoreCase)
|
||
.ToDictionary(
|
||
g => g.Key,
|
||
g => g.Last().ConfigValue?.Trim() ?? string.Empty,
|
||
StringComparer.OrdinalIgnoreCase);
|
||
|
||
var radiusMm = ReadDouble(values, SamplingRadiusConfigName);
|
||
if (radiusMm is null || radiusMm <= 0)
|
||
{
|
||
return null;
|
||
}
|
||
|
||
var scale = ReadDouble(values, CameraScaleConfigName);
|
||
if (scale is null || scale <= 0)
|
||
{
|
||
_logger.LogWarning(
|
||
"系统参数 {RadiusName} 已配置,但 {ScaleName} 无效," +
|
||
"跳过采样点半径限制",
|
||
SamplingRadiusConfigName,
|
||
CameraScaleConfigName);
|
||
return null;
|
||
}
|
||
|
||
return radiusMm.Value * scale.Value;
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
_logger.LogWarning(
|
||
ex, "读取系统参数 {ConfigName} 失败,跳过采样点半径限制",
|
||
SamplingRadiusConfigName);
|
||
return null;
|
||
}
|
||
}
|
||
|
||
private static double? ReadDouble(
|
||
IReadOnlyDictionary<string, string> values, string name) =>
|
||
values.TryGetValue(name, out var raw) &&
|
||
double.TryParse(
|
||
raw,
|
||
NumberStyles.Float,
|
||
CultureInfo.InvariantCulture,
|
||
out var value)
|
||
? value
|
||
: null;
|
||
}
|
||
}
|