CalibrationManager.cs 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131
  1. using System;
  2. using System.Collections.Concurrent;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using IvfTl.AutoFocus.Calib;
  6. using ivf_tl_Com;
  7. namespace IvfTl.ControlHost.Debug
  8. {
  9. /// <summary>
  10. /// 调试页"16 孔标定协作"管理器(D2-02 Task3.2a)。按 sid 持有每个调试会话的 CalibrationCoordinator,
  11. /// 把 Task3.1 的纯逻辑协作器接到真实硬件/引擎/落库:
  12. /// · 标定全程复用 operate 那个 DebugSession 借到的 lease(HardwareUser.OperateDebug)——control 采集该舱已暂停,
  13. /// 这里【绝不再 Acquire/Release lease】,只读 s.Lease.Serial / s.Lease.Camera;
  14. /// · 逐 well 注入 per-well 范围(HouseBin.ReadWellFocusRange) + 中心(DB优先,缺失回退硬件EEPROM),
  15. /// 调 CalibrationEngine.CalibrateWell,结果落 scene=0(调试页=出厂基准)。
  16. /// 线程安全:_byS id 用 ConcurrentDictionary;单次标定的并发由 CalibrationCoordinator 内部 _lock 保证。
  17. /// </summary>
  18. public sealed class CalibrationManager
  19. {
  20. private readonly DebugSessionManager _debug;
  21. // 按 houseSn 取该舱 HouseBin 的注入委托(Program.cs 传 sn => AppData.Instance.GetHouseBin(sn))。
  22. // 用委托而非直接静态依赖,便于单测注入假对象;真实 HouseBin 提供 ReadWellFocusRange/阈值/tlSn/AutofocusStore。
  23. private readonly Func<int, HouseBin> _houseBinOf;
  24. private readonly Action<string> _log;
  25. // 按 sid 管协作器:一个调试会话一份。Stop 后从字典移除。
  26. private readonly ConcurrentDictionary<string, CalibrationCoordinator> _bySid
  27. = new ConcurrentDictionary<string, CalibrationCoordinator>();
  28. public CalibrationManager(DebugSessionManager debug, Func<int, HouseBin> houseBinOf, Action<string> log = null)
  29. {
  30. _debug = debug ?? throw new ArgumentNullException(nameof(debug));
  31. _houseBinOf = houseBinOf ?? throw new ArgumentNullException(nameof(houseBinOf));
  32. _log = log ?? (_ => { });
  33. }
  34. /// <summary>
  35. /// 起一次 16 孔标定。校验 sid → 取该舱 HouseBin/阈值 → 构造协作器(calibrateOne 闭包接真实引擎) → Start。
  36. /// wells 为空默认 1..16。返回 Okay(无 result) / Fail(SESSION_EXPIRED|NO_HANDLE|BUSY)。
  37. /// </summary>
  38. public DebugCommandResult StartCalibrate(string sid, IReadOnlyList<int> wells)
  39. {
  40. if (!_debug.TryGet(sid, out var s))
  41. return DebugCommandResult.Fail("SESSION_EXPIRED", "会话不存在或已过期");
  42. if (s.Lease?.Serial == null || s.Lease?.Camera == null)
  43. return DebugCommandResult.Fail("NO_HANDLE", "借用串口/相机句柄为空");
  44. var houseBin = _houseBinOf(s.HouseSn);
  45. if (houseBin == null)
  46. return DebugCommandResult.Fail("NO_HANDLE", $"舱{s.HouseSn}无 HouseBin");
  47. // 合格阈值:tl_setting.focusPeakRatioThreshold ?? 1.2(与现网 CalibrationEngine 弱峰判定一致)。
  48. double peakThreshold = (double)(houseBin.FocusPeakRatioThreshold ?? 1.2m);
  49. string tlSn = houseBin.CalibTlSn;
  50. string port = houseBin.House?.housePort;
  51. string ccdSn = houseBin.House?.ccdSn;
  52. var targets = (wells != null && wells.Count > 0)
  53. ? wells.ToList()
  54. : Enumerable.Range(1, 16).ToList();
  55. // calibrateOne 闭包(逐 well 在协作器后台线程跑):范围注入 + 中心兜底 + CalibrateWell + 落 scene=0。
  56. Func<int, WellCalib> calibrateOne = well =>
  57. {
  58. var range = houseBin.ReadWellFocusRange(well);
  59. // DB优先 + 硬件兜底:DB 中心缺失(≤0)时回读硬件 EEPROM,避免中心=0 致 Z 粗扫错过真实焦面(沿用采集对焦 path B 范式)。
  60. int hCenter = range.HCenter > 0 ? range.HCenter : Math.Max(0, s.Lease.Serial.ReadWellHorizontalPosWait(well));
  61. int vCenter = range.VCenter > 0 ? range.VCenter : Math.Max(0, s.Lease.Serial.ReadWellFocusZeroWait(well));
  62. var engine = new CalibrationEngine(s.Lease.Serial, s.Lease.Camera)
  63. {
  64. Log = msg => _log($"[calib][舱{s.HouseSn}][well{well}]{msg}"),
  65. HFineRange = range.HHalf, // 水平微调半幅(围绕 HCenter)
  66. ZCoarseCenter = vCenter, // Z 粗扫中心=该 well 清晰位(取代引擎固定 90000)
  67. ZCoarseHalf = range.VHalf, // Z 粗扫半幅
  68. ExpLo = range.ExpLo, // 曝光二分下限
  69. ExpHi = range.ExpHi, // 曝光二分上限
  70. };
  71. var wc = engine.CalibrateWell(well, hCenter, vCenter);
  72. // 调试页一键标定 = 出厂基准 → scene=0(upsert)。存储失败不崩标定(CalibrationStore 内部已吞异常)。
  73. try
  74. {
  75. houseBin.AutofocusStore?.SaveCalibration(wc, tlSn, s.HouseSn, well, scene: 0,
  76. port: port, ccdSn: ccdSn);
  77. }
  78. catch (Exception ex) { _log($"[calib][舱{s.HouseSn}][well{well}] 落库失败(已忽略): {ex.Message}"); }
  79. return wc;
  80. };
  81. var coordinator = new CalibrationCoordinator(calibrateOne, peakThreshold,
  82. msg => _log($"[calib][舱{s.HouseSn}]{msg}"));
  83. _bySid[sid] = coordinator;
  84. coordinator.Start(targets);
  85. _log($"[calib] 起标定 sid={sid} 舱{s.HouseSn} wells=[{string.Join(",", targets)}] 阈值={peakThreshold:F2}");
  86. return DebugCommandResult.Okay();
  87. }
  88. /// <summary>轮询进度:返回 CalibProgress 快照(无对应 sid → SESSION_EXPIRED)。</summary>
  89. public DebugCommandResult GetProgress(string sid)
  90. {
  91. if (sid != null && _bySid.TryGetValue(sid, out var c))
  92. return DebugCommandResult.Okay(c.GetProgress());
  93. return DebugCommandResult.Fail("SESSION_EXPIRED", "无对应标定任务(会话不存在或未起标定)");
  94. }
  95. /// <summary>单孔重标(转调协作器 Recalibrate)。无对应 sid → SESSION_EXPIRED;批量跑中协作器自身忽略。</summary>
  96. public DebugCommandResult Recalibrate(string sid, int wellSn)
  97. {
  98. if (sid != null && _bySid.TryGetValue(sid, out var c))
  99. {
  100. bool ok = c.Recalibrate(wellSn);
  101. return DebugCommandResult.Okay(ok);
  102. }
  103. return DebugCommandResult.Fail("SESSION_EXPIRED", "无对应标定任务(会话不存在或未起标定)");
  104. }
  105. /// <summary>中止标定并从字典移除该 sid 的协作器(lease 仍由 operate 的 DebugSession 持有,这里不还)。</summary>
  106. public DebugCommandResult Stop(string sid)
  107. {
  108. if (sid != null && _bySid.TryRemove(sid, out var c))
  109. {
  110. c.Stop();
  111. _log($"[calib] 停标定 sid={sid}");
  112. }
  113. return DebugCommandResult.Okay();
  114. }
  115. }
  116. }