using System;
using System.IO;
namespace AutoFocusTool.Calib
{
///
/// 标定结果管理器:统一封装"优先读 JSON,降级到 EEPROM"的逻辑,
/// 确保标定结果真正被使用,而不是只存不用。
///
public class CalibrationManager
{
private CalibrationFile _cache;
private readonly string _jsonPath;
public CalibrationManager(string jsonPath = @"C:\claudeFile\TL\AutoFocusTool\calibration.json")
{
_jsonPath = jsonPath;
}
///
/// 获取指定舱室和well的标定参数。
/// 优先从 JSON 读取;若 JSON 不存在、该well标定失败或质量差,则降级到 EEPROM。
///
/// (水平脉冲, Z焦点, 曝光值); 曝光值=-1 表示未标定,需自行设置
public (int hPos, int z, int exp) GetWellParams(int house, int well, Serial.HouseMotor motor)
{
// 尝试从 JSON 加载
if (_cache == null && File.Exists(_jsonPath))
{
try { _cache = CalibrationFile.Load(_jsonPath); }
catch { _cache = null; }
}
// 检查 JSON 中的标定结果
var wc = _cache?.Find(house, well);
if (wc != null && wc.CircleFound && wc.PeakRatio > 1.2)
{
// 标定成功且质量合格,使用 JSON 参数
return (wc.HorizontalPulse, wc.FocusZ, wc.Exposure);
}
// 降级到 EEPROM
int hPos = motor.ReadWellHorizontalPos(well);
int z = motor.ReadWellFocusZero(well);
if (hPos < 0) hPos = 0;
if (z < 0) z = 0;
return (hPos, z, -1); // 曝光未标定
}
///
/// 检查某个well是否有合格的标定结果。
///
public bool HasValidCalibration(int house, int well)
{
if (_cache == null && File.Exists(_jsonPath))
{
try { _cache = CalibrationFile.Load(_jsonPath); }
catch { return false; }
}
var wc = _cache?.Find(house, well);
return wc != null && wc.CircleFound && wc.PeakRatio > 1.2;
}
///
/// 刷新缓存(当 calibration.json 被重写后调用)。
///
public void RefreshCache()
{
_cache = null;
}
}
}