using System;
using System.Diagnostics;
using System.IO.Ports;
using System.Threading;
namespace AutoFocusTool.Serial
{
///
/// 单舱室串口控制器(马达 + LED)。自包含,无外部实体依赖。
/// 采用同步请求-响应:写命令帧 → 按该命令固定回复长度阻塞读 → 校验。
/// 比原工程的事件+环形缓冲简单,适合调试台单线程操作。
/// 串口参数固定:9600 8N1,读写超时 3000ms。
///
public class SerialMotor : IDisposable
{
private readonly SerialPort _port;
private readonly object _ioLock = new object();
/// 日志回调(发送/接收/错误)
public Action Log;
public string PortName { get; }
public bool IsOpen => _port != null && _port.IsOpen;
// ───────────────────────── 读超时策略(方案甲:按命令类型动态超时)─────────────────────────
// 背景/根因:下位机的“移动命令”是开环阻塞式——它在机械真正转到位之后才回复
// (回复即“到位确认”)。因此回复耗时 ∝ 移动距离。大行程移动(如水平从 206150
// 转到 71500,跨 ~13.5 万脉冲)实测需 6 秒以上。
// 旧实现把读超时写死 3000ms:大行程移动还没等到回复就被判“接收超时”→ 返回 null →
// 上层误判“移动失败”并重试,且后续步骤在电机尚未稳定到位时就抓图,导致粗对焦
// 整段检不出 well 圆、对焦退回边界。(详见 well1 标定日志:仅 2 次超时,均为本 well
// 首次大行程移动,后续 166 次小步移动 0 超时。)
// 方案甲:把“移动类命令”与“查询类命令”分开给超时——
// · 移动类(电机绝对/相对/复位,命令码 CMD_MOTOR=0x05):长超时,覆盖最大行程移动耗时。
// · 查询类(握手/读EEPROM/读电机位置/设IO等):下位机立即回复,保持短超时即可。
/// 移动类命令(电机运动,命令码0x05)的读超时(ms)。需覆盖最大行程移动耗时,默认12000。
public int MoveReadTimeoutMs { get; set; } = 12000;
/// 查询类命令(握手/读EEPROM/读位置/设IO)的读超时(ms)。下位机立即回复,默认3000。
public int QueryReadTimeoutMs { get; set; } = 3000;
public SerialMotor(string portName)
{
PortName = portName;
_port = new SerialPort
{
PortName = portName,
BaudRate = 9600,
DataBits = 8,
StopBits = StopBits.One,
Parity = Parity.None,
// SerialPort.ReadTimeout 取两者较大值:实际每次读用的超时由 Send() 按命令类型
// 再细分(见 ReadTimeoutForCmd)。这里设为大值,避免底层 Read 提前抛 TimeoutException。
ReadTimeout = 12000,
WriteTimeout = 3000,
};
}
public bool Open()
{
try
{
if (!_port.IsOpen) _port.Open();
_port.DiscardInBuffer();
_port.DiscardOutBuffer();
return true;
}
catch (Exception ex)
{
Log?.Invoke($"[{PortName}] 打开串口失败: {ex.Message}");
return false;
}
}
public void Close()
{
try { if (_port.IsOpen) _port.Close(); } catch { }
}
///
/// 发送命令帧并读取固定长度回复。返回回复字节(失败返回 null)。
///
/// 完整命令帧(含校验)
/// 读到回复后额外等待(电机到位延时)
public byte[] Send(byte[] frame, int extraWaitMs = 0)
{
if (!IsOpen && !Open()) return null;
int replyLen = Protocol.ReplyLength(frame[1]);
lock (_ioLock)
{
try
{
_port.DiscardInBuffer();
_port.Write(frame, 0, frame.Length);
Log?.Invoke($"[{PortName}] 发送: {ToHex(frame)}");
// 方案甲:按命令类型选读超时。移动类命令要等机械到位才回复,耗时随行程增长,
// 必须给足超时;查询类命令下位机立即回复,短超时即可(快速失败、不空等)。
int readTimeout = ReadTimeoutForCmd(frame[1]);
byte[] reply = ReadFixed(replyLen, readTimeout);
if (reply == null)
{
Log?.Invoke($"[{PortName}] 接收超时(期望{replyLen}字节,超时{readTimeout}ms)");
return null;
}
Log?.Invoke($"[{PortName}] 接收: {ToHex(reply)}{(Protocol.CheckChecksum(reply) ? "" : " [校验失败]")}");
// 回复 [n-2] 为下位机结果位,非0视为失败(返回null表示操作失败)
if (replyLen >= 2 && reply[replyLen - 2] != 0)
{
Log?.Invoke($"[{PortName}] 下位机结果位非0(操作失败)");
return null;
}
if (extraWaitMs > 0) Thread.Sleep(extraWaitMs);
return reply;
}
catch (Exception ex)
{
Log?.Invoke($"[{PortName}] 收发异常: {ex.Message}");
return null;
}
}
}
///
/// 按命令码返回该命令的读超时(ms)。方案甲核心:
/// 移动类命令(CMD_MOTOR=0x05,含绝对/相对/复位运动)要等机械到位才回复,
/// 回复耗时随移动行程增长(大行程实测 >6 秒),给 MoveReadTimeoutMs(默认12秒);
/// 其余查询/设置类命令(握手0x01/读EEPROM0x11/读位置0x18/设IO0x09等)下位机立即回复,
/// 给 QueryReadTimeoutMs(默认3秒),快速失败不空等。
///
private int ReadTimeoutForCmd(byte cmd)
=> cmd == Protocol.CMD_MOTOR ? MoveReadTimeoutMs : QueryReadTimeoutMs;
/// 阻塞读取指定字节数,超时返回 null。
private byte[] ReadFixed(int count, int timeoutMs)
{
byte[] buf = new byte[count];
int got = 0;
var sw = Stopwatch.StartNew();
while (got < count)
{
if (sw.ElapsedMilliseconds > timeoutMs) return null;
try
{
int n = _port.Read(buf, got, count - got);
got += n;
}
catch (TimeoutException)
{
if (sw.ElapsedMilliseconds > timeoutMs) return null;
}
}
return buf;
}
private static string ToHex(byte[] b)
{
if (b == null) return "(null)";
var sb = new System.Text.StringBuilder(b.Length * 3);
foreach (var x in b) sb.Append(x.ToString("X2")).Append(' ');
return sb.ToString().TrimEnd();
}
public void Dispose()
{
Close();
_port?.Dispose();
}
}
}