DebugSessionManager.cs 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153
  1. using System;
  2. using System.Collections.Concurrent;
  3. using IvfTl.Hardware;
  4. using Newtonsoft.Json.Linq;
  5. namespace IvfTl.ControlHost.Debug
  6. {
  7. /// <summary>
  8. /// control 端调试会话后端:会话表 + 借用/归还 + 心跳续约 + 超时自动回收 + 命令分发。
  9. /// 安全地基(spec §5):绝不指望 operate 主动还,SweepExpired 超时回收兜底。
  10. /// </summary>
  11. public sealed class DebugSessionManager
  12. {
  13. private readonly Func<int, IHouseGate> _gateOf;
  14. private readonly Func<DateTime> _clock;
  15. private readonly int _ttlMs;
  16. private readonly Action<string> _log;
  17. private readonly ConcurrentDictionary<string, DebugSession> _sessions = new ConcurrentDictionary<string, DebugSession>();
  18. public DebugSessionManager(Func<int, IHouseGate> gateOf, Func<DateTime> clock, int ttlMs, Action<string> log)
  19. {
  20. _gateOf = gateOf; _clock = clock; _ttlMs = ttlMs; _log = log ?? (_ => { });
  21. }
  22. public DebugCommandResult Acquire(int houseSn)
  23. {
  24. var gate = _gateOf(houseSn);
  25. if (gate == null) return DebugCommandResult.Fail("NO_HANDLE", $"舱{houseSn}无闸门");
  26. var lease = gate.Acquire(HardwareUser.OperateDebug);
  27. if (lease == null) return DebugCommandResult.Fail("BUSY", $"舱{houseSn}被占用,借用超时");
  28. string sid = Guid.NewGuid().ToString("N");
  29. _sessions[sid] = new DebugSession(sid, houseSn, lease, _clock());
  30. _log($"[debug] acquire 舱{houseSn} sid={sid}");
  31. return DebugCommandResult.Okay(sid);
  32. }
  33. public DebugCommandResult Heartbeat(string sid)
  34. {
  35. if (sid != null && _sessions.TryGetValue(sid, out var s)) { s.LastSeen = _clock(); return DebugCommandResult.Okay(); }
  36. return DebugCommandResult.Fail("SESSION_EXPIRED", "会话不存在或已过期");
  37. }
  38. /// <summary>只读取会话(供推流端点校验 sid)。不刷新 LastSeen、不改状态。</summary>
  39. public bool TryGet(string sid, out DebugSession session)
  40. {
  41. if (sid != null) return _sessions.TryGetValue(sid, out session);
  42. session = null; return false;
  43. }
  44. public DebugCommandResult Release(string sid)
  45. {
  46. if (sid != null && _sessions.TryRemove(sid, out var s))
  47. {
  48. try { s.Lease.Dispose(); } catch (Exception ex) { _log($"[debug] dispose 异常 sid={sid} 舱{s.HouseSn}: {ex.Message}"); }
  49. _log($"[debug] release sid={sid} 舱{s.HouseSn}");
  50. }
  51. return DebugCommandResult.Okay();
  52. }
  53. /// <summary>超时回收:LastSeen + ttl < now 的会话自动归还(spec §5.1)。</summary>
  54. public int SweepExpired()
  55. {
  56. int n = 0; var now = _clock();
  57. foreach (var kv in _sessions)
  58. {
  59. if ((now - kv.Value.LastSeen).TotalMilliseconds > _ttlMs)
  60. {
  61. if (_sessions.TryRemove(kv.Key, out var s))
  62. {
  63. try { s.Lease.Dispose(); } catch (Exception ex) { _log($"[debug] dispose 异常 sid={kv.Key} 舱{s.HouseSn}: {ex.Message}"); }
  64. _log($"[debug] 会话超时自动回收 sid={kv.Key} 舱{s.HouseSn}");
  65. n++;
  66. }
  67. }
  68. }
  69. return n;
  70. }
  71. public DebugCommandResult Execute(string sid, string op, JObject args)
  72. {
  73. if (sid == null || !_sessions.TryGetValue(sid, out var s))
  74. return DebugCommandResult.Fail("SESSION_EXPIRED", "会话不存在或已过期");
  75. s.LastSeen = _clock();
  76. var ser = s.Lease.Serial;
  77. if (ser == null) return DebugCommandResult.Fail("NO_HANDLE", "借用串口句柄为空");
  78. try
  79. {
  80. switch (op)
  81. {
  82. case "ReadTemp": return DebugCommandResult.Okay(ser.TemperatureWait());
  83. case "ReadPressure": return DebugCommandResult.Okay(ser.PressureWait());
  84. case "ReadDoor": return DebugCommandResult.Okay(ser.DoorStatusWait().ToString());
  85. case "ReadVentTime": return DebugCommandResult.Okay(ser.ReadOpenVentTimeWait());
  86. case "ShakeHands": return DebugCommandResult.Okay(ser.ShakeHandsWait());
  87. case "OpenLed": return DebugCommandResult.Okay(ser.OpenLedWait());
  88. case "CloseLed": return DebugCommandResult.Okay(ser.CloseLedWait());
  89. case "OpenIntake": return DebugCommandResult.Okay(ser.OpenIntakeValveWait());
  90. case "CloseIntake": return DebugCommandResult.Okay(ser.CloseIntakeValveWait());
  91. case "OpenExhaust": return DebugCommandResult.Okay(ser.OpenExhaustValveWait());
  92. case "CloseExhaust": return DebugCommandResult.Okay(ser.CloseExhaustValveWait());
  93. case "HouseAeration": return DebugCommandResult.Okay(ser.HouseAerationWait());
  94. case "HouseVent": return DebugCommandResult.Okay(ser.HouseVentWait());
  95. default:
  96. return ExecuteMotorOrEeprom(s, ser, op, args);
  97. }
  98. }
  99. catch (Exception ex) { return DebugCommandResult.Fail("HARDWARE_ERROR", ex.Message); }
  100. }
  101. // Task7 先占位:返回 BAD_OP,让"未知 op"测试通过;Task7 替换为真实电机/EEPROM 分发。
  102. private DebugCommandResult ExecuteMotorOrEeprom(DebugSession s, IvfTl.Hardware.ISerialChannel ser, string op, JObject args)
  103. {
  104. int Arg(string k, int def = 0) => args?[k] != null ? args[k].Value<int>() : def;
  105. int delay = Arg("motorDelay", -1);
  106. switch (op)
  107. {
  108. case "VerticalReset": { bool ok = ser.VerticalResetWait(delay); if (ok) s.CurrentVer = 0; return DebugCommandResult.Okay(ok); }
  109. case "VerticalMoveTo":
  110. {
  111. int pos = Arg("pos");
  112. if (!MotorClamp.IsVerticalInRange(pos)) return DebugCommandResult.Fail("OUT_OF_RANGE", $"垂直目标{pos}越界[0,{MotorClamp.VerMax}]");
  113. bool ok = ser.VerticalMoveToWait(pos, delay); if (ok) s.CurrentVer = pos; return DebugCommandResult.Okay(ok);
  114. }
  115. case "VerticalForward":
  116. case "VerticalBackward":
  117. {
  118. // 红线钳位必须基于回读的真实物理位,不信任会话跟踪位(防真机已在高位时相对运动越红线)。
  119. int basePos = ser.ReadVerticalPositionWait();
  120. int delta = Arg("value") * (op == "VerticalBackward" ? -1 : 1);
  121. int target = MotorClamp.RelativeTarget(basePos, delta);
  122. if (!MotorClamp.IsVerticalInRange(target)) return DebugCommandResult.Fail("OUT_OF_RANGE", $"垂直目标{target}越界");
  123. bool ok = op == "VerticalBackward" ? ser.VerticalBackwardWait(Arg("value"), delay) : ser.VerticalForwardWait(Arg("value"), delay);
  124. if (ok) s.CurrentVer = ser.ReadVerticalPositionWait(); return DebugCommandResult.Okay(ok);
  125. }
  126. case "HorizontalReset": { bool ok = ser.HorizontalResetWait(delay); if (ok) s.CurrentHor = 0; return DebugCommandResult.Okay(ok); }
  127. case "HorizontalMoveTo":
  128. {
  129. int pos = Arg("pos");
  130. if (!MotorClamp.IsHorizontalInRange(pos)) return DebugCommandResult.Fail("OUT_OF_RANGE", $"水平目标{pos}越界[0,{MotorClamp.HorMax}]");
  131. bool ok = ser.HorizontalMoveToWait(pos, delay); if (ok) s.CurrentHor = pos; return DebugCommandResult.Okay(ok);
  132. }
  133. case "HorizontalForward":
  134. case "HorizontalBackward":
  135. {
  136. // 红线钳位必须基于回读的真实物理位,不信任会话跟踪位。
  137. int basePos = ser.ReadHorizontalPositionWait();
  138. int delta = Arg("value") * (op == "HorizontalBackward" ? -1 : 1);
  139. int target = MotorClamp.RelativeTarget(basePos, delta);
  140. if (!MotorClamp.IsHorizontalInRange(target)) return DebugCommandResult.Fail("OUT_OF_RANGE", $"水平目标{target}越界");
  141. bool ok = op == "HorizontalBackward" ? ser.HorizontalBackwardWait(Arg("value"), delay) : ser.HorizontalForwardWait(Arg("value"), delay);
  142. if (ok) s.CurrentHor = ser.ReadHorizontalPositionWait(); return DebugCommandResult.Okay(ok);
  143. }
  144. case "WriteScanStep": return DebugCommandResult.Okay(ser.WriteScanStepWait(Arg("value")));
  145. case "WriteOpenIntakeTime": return DebugCommandResult.Okay(ser.WriteOpenIntakeTimeWait(Arg("value")));
  146. case "WriteOpenVentTime": return DebugCommandResult.Okay(ser.WriteOpenVentTimeWait(Arg("value")));
  147. case "WriteWellHorizontalPos": return DebugCommandResult.Okay(ser.WriteWellHorizontalPosWait(Arg("well"), Arg("hor")));
  148. default: return DebugCommandResult.Fail("BAD_OP", $"未知 op: {op}");
  149. }
  150. }
  151. }
  152. }