DebugSessionManager.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187
  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. // 相机曝光:operate 进程相机是空壳,调试页设曝光改走 control 借用的真相机(Task3.4b)。
  92. case "SetExposure":
  93. {
  94. var cam = s.Lease.Camera;
  95. if (cam == null) return DebugCommandResult.Fail("NO_HANDLE", "借用相机句柄为空");
  96. int e = args?["value"] != null ? args["value"].Value<int>() : 0;
  97. return DebugCommandResult.Okay(cam.SetExposure(e));
  98. }
  99. case "ReadTemp": return DebugCommandResult.Okay(ser.TemperatureWait());
  100. case "ReadPressure": return DebugCommandResult.Okay(ser.PressureWait());
  101. case "ReadDoor": return DebugCommandResult.Okay(ser.DoorStatusWait().ToString());
  102. case "ReadVentTime": return DebugCommandResult.Okay(ser.ReadOpenVentTimeWait());
  103. case "ShakeHands": return DebugCommandResult.Okay(ser.ShakeHandsWait());
  104. case "OpenLed": return DebugCommandResult.Okay(ser.OpenLedWait());
  105. case "CloseLed": return DebugCommandResult.Okay(ser.CloseLedWait());
  106. case "OpenIntake": return DebugCommandResult.Okay(ser.OpenIntakeValveWait());
  107. case "CloseIntake": return DebugCommandResult.Okay(ser.CloseIntakeValveWait());
  108. case "OpenExhaust": return DebugCommandResult.Okay(ser.OpenExhaustValveWait());
  109. case "CloseExhaust": return DebugCommandResult.Okay(ser.CloseExhaustValveWait());
  110. case "HouseAeration": return DebugCommandResult.Okay(ser.HouseAerationWait());
  111. case "HouseVent": return DebugCommandResult.Okay(ser.HouseVentWait());
  112. case "BufferState":
  113. {
  114. var (pressure, t1, t2) = ser.BufferBottleStateWait();
  115. return DebugCommandResult.Okay(new { pressure, t1, t2 });
  116. }
  117. case "BufferAeration": return DebugCommandResult.Okay(ser.BufferBottleAerationWait());
  118. case "ReadLight": return DebugCommandResult.Okay(ser.ReadLightBrightnessWait());
  119. case "WriteLight":
  120. {
  121. int v = args?["value"] != null ? args["value"].Value<int>() : 0;
  122. return DebugCommandResult.Okay(ser.WriteLightBrightnessWait(v));
  123. }
  124. case "WriteOpenIntakeTimeBuffer":
  125. {
  126. int v = args?["value"] != null ? args["value"].Value<int>() : 0;
  127. return DebugCommandResult.Okay(ser.WriteOpenIntakeTimeWait(v, isBuffer: true));
  128. }
  129. default:
  130. return ExecuteMotorOrEeprom(s, ser, op, args);
  131. }
  132. }
  133. catch (Exception ex) { return DebugCommandResult.Fail("HARDWARE_ERROR", ex.Message); }
  134. }
  135. // Task7 先占位:返回 BAD_OP,让"未知 op"测试通过;Task7 替换为真实电机/EEPROM 分发。
  136. private DebugCommandResult ExecuteMotorOrEeprom(DebugSession s, IvfTl.Hardware.ISerialChannel ser, string op, JObject args)
  137. {
  138. int Arg(string k, int def = 0) => args?[k] != null ? args[k].Value<int>() : def;
  139. int delay = Arg("motorDelay", -1);
  140. switch (op)
  141. {
  142. case "VerticalReset": { bool ok = ser.VerticalResetWait(delay); if (ok) s.CurrentVer = 0; return DebugCommandResult.Okay(ok); }
  143. case "VerticalMoveTo":
  144. {
  145. int pos = Arg("pos");
  146. if (!MotorClamp.IsVerticalInRange(pos)) return DebugCommandResult.Fail("OUT_OF_RANGE", $"垂直目标{pos}越界[0,{MotorClamp.VerMax}]");
  147. bool ok = ser.VerticalMoveToWait(pos, delay); if (ok) s.CurrentVer = pos; return DebugCommandResult.Okay(ok);
  148. }
  149. case "VerticalForward":
  150. case "VerticalBackward":
  151. {
  152. // 红线钳位必须基于回读的真实物理位,不信任会话跟踪位(防真机已在高位时相对运动越红线)。
  153. int basePos = ser.ReadVerticalPositionWait();
  154. int delta = Arg("value") * (op == "VerticalBackward" ? -1 : 1);
  155. int target = MotorClamp.RelativeTarget(basePos, delta);
  156. if (!MotorClamp.IsVerticalInRange(target)) return DebugCommandResult.Fail("OUT_OF_RANGE", $"垂直目标{target}越界");
  157. bool ok = op == "VerticalBackward" ? ser.VerticalBackwardWait(Arg("value"), delay) : ser.VerticalForwardWait(Arg("value"), delay);
  158. if (ok) s.CurrentVer = ser.ReadVerticalPositionWait(); return DebugCommandResult.Okay(ok);
  159. }
  160. case "HorizontalReset": { bool ok = ser.HorizontalResetWait(delay); if (ok) s.CurrentHor = 0; return DebugCommandResult.Okay(ok); }
  161. case "HorizontalMoveTo":
  162. {
  163. int pos = Arg("pos");
  164. if (!MotorClamp.IsHorizontalInRange(pos)) return DebugCommandResult.Fail("OUT_OF_RANGE", $"水平目标{pos}越界[0,{MotorClamp.HorMax}]");
  165. bool ok = ser.HorizontalMoveToWait(pos, delay); if (ok) s.CurrentHor = pos; return DebugCommandResult.Okay(ok);
  166. }
  167. case "HorizontalForward":
  168. case "HorizontalBackward":
  169. {
  170. // 红线钳位必须基于回读的真实物理位,不信任会话跟踪位。
  171. int basePos = ser.ReadHorizontalPositionWait();
  172. int delta = Arg("value") * (op == "HorizontalBackward" ? -1 : 1);
  173. int target = MotorClamp.RelativeTarget(basePos, delta);
  174. if (!MotorClamp.IsHorizontalInRange(target)) return DebugCommandResult.Fail("OUT_OF_RANGE", $"水平目标{target}越界");
  175. bool ok = op == "HorizontalBackward" ? ser.HorizontalBackwardWait(Arg("value"), delay) : ser.HorizontalForwardWait(Arg("value"), delay);
  176. if (ok) s.CurrentHor = ser.ReadHorizontalPositionWait(); return DebugCommandResult.Okay(ok);
  177. }
  178. case "WriteScanStep": return DebugCommandResult.Okay(ser.WriteScanStepWait(Arg("value")));
  179. case "WriteOpenIntakeTime": return DebugCommandResult.Okay(ser.WriteOpenIntakeTimeWait(Arg("value")));
  180. case "WriteOpenVentTime": return DebugCommandResult.Okay(ser.WriteOpenVentTimeWait(Arg("value")));
  181. case "WriteWellHorizontalPos": return DebugCommandResult.Okay(ser.WriteWellHorizontalPosWait(Arg("well"), Arg("hor")));
  182. default: return DebugCommandResult.Fail("BAD_OP", $"未知 op: {op}");
  183. }
  184. }
  185. }
  186. }