219 lines
7.9 KiB
C#
219 lines
7.9 KiB
C#
using System.Diagnostics;
|
||
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 string IdentificationTimeoutConfigName = "camera_Identification_outtime";
|
||
private const int DefaultSamplingPointCount = 5;
|
||
private const int MaxSamplingPointCount = 100;
|
||
private const int DefaultIdentificationTimeoutSeconds = 60;
|
||
private const int MinIdentificationTimeoutSeconds = 5;
|
||
private const int MaxIdentificationTimeoutSeconds = 300;
|
||
|
||
private readonly IUsbCameraService _camera;
|
||
private readonly ISystemConfigService _systemConfig;
|
||
private readonly TargetOutlineAnalyzer _analyzer;
|
||
private readonly ILogger<SampleAnalysisService> _logger;
|
||
|
||
private readonly object _gate = new();
|
||
private SampleAnalysisResult? _lastAnalysis;
|
||
|
||
public SampleAnalysisService(
|
||
IUsbCameraService camera,
|
||
ISystemConfigService systemConfig,
|
||
TargetOutlineAnalyzer analyzer,
|
||
ILogger<SampleAnalysisService> logger)
|
||
{
|
||
_camera = camera;
|
||
_systemConfig = systemConfig;
|
||
_analyzer = analyzer;
|
||
_logger = logger;
|
||
}
|
||
|
||
public SampleAnalysisResult Analyze()
|
||
{
|
||
var target = CaptureLatestFrame();
|
||
|
||
var pointCount = GetSamplingPointCount();
|
||
var samplingRadiusPixels = GetSamplingRadiusPixels();
|
||
|
||
_logger.LogInformation(
|
||
"开始靶样轮廓分析,采样点数:{PointCount},采样半径:{Radius}",
|
||
pointCount,
|
||
samplingRadiusPixels is > 0
|
||
? $"{samplingRadiusPixels.Value:F1}px"
|
||
: "不限制");
|
||
|
||
var watch = Stopwatch.StartNew();
|
||
var result = _analyzer.Analyze(
|
||
target, pointCount, samplingRadiusPixels);
|
||
watch.Stop();
|
||
|
||
_logger.LogInformation(
|
||
"靶样轮廓分析完成:{Width}x{Height},采样点 {PointCount} 个,总耗时 {Elapsed} ms",
|
||
result.Width,
|
||
result.Height,
|
||
result.SamplingPointCount,
|
||
watch.ElapsedMilliseconds);
|
||
|
||
lock (_gate)
|
||
{
|
||
_lastAnalysis = result;
|
||
}
|
||
|
||
return result;
|
||
}
|
||
|
||
public SampleAnalysisResult GetLatestAnalysis()
|
||
{
|
||
lock (_gate)
|
||
{
|
||
if (_lastAnalysis is not null)
|
||
{
|
||
return _lastAnalysis;
|
||
}
|
||
}
|
||
|
||
return Analyze();
|
||
}
|
||
|
||
private CameraFrameSnapshot CaptureLatestFrame() =>
|
||
_camera.GetLatestFrame() ?? throw new HardwareException(
|
||
HardwareErrorKind.NotConnected,
|
||
"相机尚未产生画面,请确认相机已连接");
|
||
|
||
/// <summary>
|
||
/// 读取系统参数 camera_Identification_outtime(秒),
|
||
/// 作为前端等待轮廓识别结果的超时时间;未配置或无效时使用默认值。
|
||
/// </summary>
|
||
public int GetIdentificationTimeoutSeconds()
|
||
{
|
||
try
|
||
{
|
||
var config = _systemConfig
|
||
.GetAll()
|
||
.FirstOrDefault(c => string.Equals(
|
||
c.ConfigName,
|
||
IdentificationTimeoutConfigName,
|
||
StringComparison.OrdinalIgnoreCase));
|
||
|
||
if (double.TryParse(
|
||
config?.ConfigValue,
|
||
NumberStyles.Float,
|
||
CultureInfo.InvariantCulture,
|
||
out var seconds) &&
|
||
seconds > 0)
|
||
{
|
||
return (int)Math.Clamp(
|
||
Math.Round(seconds),
|
||
MinIdentificationTimeoutSeconds,
|
||
MaxIdentificationTimeoutSeconds);
|
||
}
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
_logger.LogWarning(
|
||
ex,
|
||
"读取系统参数 {ConfigName} 失败,使用默认识别超时时间",
|
||
IdentificationTimeoutConfigName);
|
||
}
|
||
|
||
return DefaultIdentificationTimeoutSeconds;
|
||
}
|
||
|
||
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;
|
||
}
|
||
}
|