提交代码

This commit is contained in:
ldh
2026-11-19 16:42:26 +08:00
parent c5908eff03
commit 9d06abe41c
209 changed files with 158631 additions and 1311 deletions
File diff suppressed because it is too large Load Diff
@@ -213,6 +213,52 @@ namespace HardwareControl.Core.HardwareServiceImpl
public Task StartSingleFocusAsync(CancellationToken ct = default) =>
ExecuteAsync(FocusSystemNative.focus_single_focus, "单次对焦", ct);
public async Task<FocusSingleResult> FocusSingleAndWaitAsync(
TimeSpan timeout,
CancellationToken ct = default)
{
var limit = timeout > TimeSpan.Zero ? timeout : TimeSpan.FromSeconds(10);
var startedAt = DateTimeOffset.UtcNow;
// 动态库内部完成测距光源开关与对焦动作,并阻塞到运行结果返回;
// 这里只在外部加一个等待上限,避免界面长时间无响应。
var command = ExecuteRawAsync(
FocusSystemNative.focus_single_focus,
"单次对焦",
ct);
int code;
try
{
code = await command.WaitAsync(limit, ct).ConfigureAwait(false);
}
catch (TimeoutException)
{
_logger.LogWarning(
"单次对焦在 {Timeout}s 内未返回结果,判定为失败",
limit.TotalSeconds);
return new FocusSingleResult(
FocusSingleOutcome.WaitTimeout,
null,
DateTimeOffset.UtcNow - startedAt);
}
var outcome = code switch
{
FocusSystemNative.Ok => FocusSingleOutcome.Completed,
FocusSystemNative.ErrNullPtr => FocusSingleOutcome.NullHandle,
FocusSystemNative.ErrComNotOpen => FocusSingleOutcome.ComNotOpen,
FocusSystemNative.ErrComSendFailed => FocusSingleOutcome.DeviceFailed,
FocusSystemNative.ErrTimeout => FocusSingleOutcome.DeviceTimeout,
_ => FocusSingleOutcome.Unknown,
};
return new FocusSingleResult(
outcome,
code,
DateTimeOffset.UtcNow - startedAt);
}
public Task StartContinuousFocusAsync(CancellationToken ct = default) =>
ExecuteAsync(FocusSystemNative.focus_continuous_focus, "连续对焦", ct);
@@ -338,7 +384,53 @@ namespace HardwareControl.Core.HardwareServiceImpl
.ConfigureAwait(false);
EnsureSuccess(handle, result, operation);
_logger.LogInformation("对焦系统:{Operation}完成", operation);
_logger.LogInformation("对焦系统:{Operation}命令已下发", operation);
}
finally
{
_gate.Release();
}
}
/// <summary>
/// 执行原生命令并返回动态库原始结果码,非 0 时不抛异常,
/// 由调用方按业务语义处理。
/// </summary>
private async Task<int> ExecuteRawAsync(
Func<IntPtr, int> command,
string operation,
CancellationToken ct)
{
await _gate.WaitAsync(ct).ConfigureAwait(false);
try
{
ThrowIfDisposed();
var handle = RequireHandle();
ct.ThrowIfCancellationRequested();
var result = await Task.Run(
() => command(handle),
CancellationToken.None)
.ConfigureAwait(false);
if (result >= 0)
{
_logger.LogInformation(
"对焦系统:{Operation}命令已返回,结果码 {Code}",
operation,
result);
}
else
{
var detail = FocusSystemNative.GetError(handle);
_logger.LogWarning(
"对焦系统:{Operation}命令返回错误码 {Code}{Detail}",
operation,
result,
string.IsNullOrWhiteSpace(detail) ? string.Empty : $":{detail}");
}
return result;
}
finally
{
@@ -459,17 +551,20 @@ namespace HardwareControl.Core.HardwareServiceImpl
return MapResult(response);
}
// 非阻塞查询,未找到结果帧时继续轮询
if (result != FocusSystemNative.ErrTimeout)
// 未找到完整结果帧时继续轮询:底层在无数据时返回 ErrTimeout,
// 缓冲区只有半帧时返回 ErrParseFailed,两者都视为“结果尚未就绪”。
if (result is not (FocusSystemNative.ErrTimeout
or FocusSystemNative.ErrParseFailed))
{
throw MapNativeError(handle, result, "查询对焦系统结果");
}
if (Environment.TickCount64 >= deadline)
{
throw new HardwareException(
return MapResult(response);
/*throw new HardwareException(
HardwareErrorKind.Timeout,
$"查询对焦系统结果超时({timeoutMs}ms):未找到结果帧");
$"查询对焦系统结果超时({timeoutMs}ms):未找到结果帧");*/
}
Thread.Sleep(retryInterval);
@@ -1,3 +1,4 @@
using System.Globalization;
using HardwareControl.Core.HardwareServiceImpl.HardwareService;
using HardwareControl.Core.SampleAnalysis;
using HardwareControl.Core.SystemSetting;
@@ -13,6 +14,8 @@ namespace HardwareControl.Core.HardwareServiceImpl
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;
@@ -24,6 +27,7 @@ namespace HardwareControl.Core.HardwareServiceImpl
private readonly object _gate = new();
private IReadOnlyList<CameraFrameSnapshot>? _baseline;
private CameraFrameSnapshot? _target;
private SampleAnalysisResult? _lastAnalysis;
public SampleAnalysisService(
IUsbCameraService camera,
@@ -48,6 +52,7 @@ namespace HardwareControl.Core.HardwareServiceImpl
{
_baseline = new[] { frame };
_target = null;
_lastAnalysis = null;
}
_logger.LogInformation(
@@ -57,8 +62,11 @@ namespace HardwareControl.Core.HardwareServiceImpl
new SampleBaselineInfo(frame.Width, frame.Height, frame.CapturedAt));
}
public SampleTargetInfo CaptureTarget()
public Task<SampleTargetInfo> CaptureTargetAsync(
CancellationToken ct = default)
{
ct.ThrowIfCancellationRequested();
var frame = CaptureLatestFrame();
lock (_gate)
@@ -71,12 +79,14 @@ namespace HardwareControl.Core.HardwareServiceImpl
}
_target = frame;
_lastAnalysis = null;
}
_logger.LogInformation(
"靶样画面已采集:{Width}x{Height}", frame.Width, frame.Height);
return new SampleTargetInfo(frame.Width, frame.Height, frame.CapturedAt);
return Task.FromResult(
new SampleTargetInfo(frame.Width, frame.Height, frame.CapturedAt));
}
public SampleAnalysisResult Analyze()
@@ -93,12 +103,26 @@ namespace HardwareControl.Core.HardwareServiceImpl
target = _target ?? throw new HardwareException(
HardwareErrorKind.InvalidState,
"尚未采集靶样画面,请返回样品放置界面重新检测");
// 同一组画面重复调用 Analyze 时直接返回缓存,避免重复执行 ONNX 推理。
if (_lastAnalysis is not null)
{
return _lastAnalysis;
}
}
var pointCount = GetSamplingPointCount();
_logger.LogInformation("开始靶样轮廓分析,采样点数:{PointCount}", pointCount);
var samplingRadiusPixels = GetSamplingRadiusPixels();
var result = _analyzer.Analyze(baseline, target, pointCount);
_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} 个",
@@ -106,6 +130,15 @@ namespace HardwareControl.Core.HardwareServiceImpl
result.Height,
result.SamplingPointCount);
lock (_gate)
{
// 分析期间如果靶样画面已被重新采集,则不缓存本次结果。
if (ReferenceEquals(_target, target))
{
_lastAnalysis = result;
}
}
return result;
}
@@ -137,5 +170,61 @@ namespace HardwareControl.Core.HardwareServiceImpl
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;
}
}