DebugSessionManager.cs 11 KB

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