stress_test_35ptc_24h.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378
  1. #!/usr/bin/env python3
  2. """24-Hour Continuous Hardware Stress Test for Prod2U 6400 V2.0 (24 PTC / 8 fan / 3 SSR protocol).
  3. Continuously maintains all 24 physical PTC heating channels at 50% duty cycle,
  4. feeds the 30-second hardware watchdog every loop, periodically queries and verifies
  5. readback duty values and temperatures, and logs detailed statistics.
  6. Safety: Gracefully drives all 24 PTC channels to 0% upon termination (SIGINT/SIGTERM/completion).
  7. """
  8. import argparse
  9. from datetime import datetime, timezone
  10. import json
  11. import logging
  12. from pathlib import Path
  13. import signal
  14. import sys
  15. import time
  16. ROOT = Path(__file__).resolve().parents[1]
  17. if str(ROOT) not in sys.path:
  18. sys.path.insert(0, str(ROOT))
  19. from tools.stream_receiver import StreamReceiver
  20. from tools._vendor.hth_protocol import FrameType, encode_frame
  21. try:
  22. import serial
  23. except ImportError:
  24. serial = None
  25. # The historical filename is kept for existing launch commands; this tool now
  26. # targets 6400-v2 3.0: 24 PTC + 8 fan + 3 SSR (SET=35, DATA=86).
  27. # This PTC-only stress test keeps all three heater-cloth SSR outputs at zero.
  28. PTC_COUNT = 24
  29. FAN_COUNT = 8
  30. SSR_COUNT = 3
  31. def make_frame(msg_type: int, payload: bytes = b"") -> bytes:
  32. return encode_frame(msg_type, payload)
  33. class StressTester:
  34. def __init__(self, port: str, baud: int, target_hours: float, interval_s: float,
  35. ptc_duty: int, fan_duty: int, log_dir: Path, status_file: Path):
  36. self.port = port
  37. self.baud = baud
  38. self.target_seconds = target_hours * 3600.0
  39. self.interval_s = interval_s
  40. self.ptc_duty = ptc_duty
  41. self.fan_duty = fan_duty
  42. self.log_dir = log_dir
  43. self.status_file = status_file
  44. self.ser = None
  45. self.running = True
  46. self.start_time = 0.0
  47. # Statistics
  48. self.total_cycles = 0
  49. self.set_ack_success = 0
  50. self.set_ack_miss = 0
  51. self.get_success = 0
  52. self.get_miss = 0
  53. self.duty_mismatch_count = 0
  54. self.reconnect_count = 0
  55. # Last known readback
  56. self.last_ptc = []
  57. self.last_fans = []
  58. self.last_bmc = []
  59. self.last_ct = []
  60. self.last_ssr = []
  61. self.receiver = StreamReceiver("6400-v2")
  62. self.autonomous_data = 0
  63. self.rejected_frames = 0
  64. def connect(self) -> bool:
  65. if self.ser and self.ser.is_open:
  66. try:
  67. self.ser.close()
  68. except Exception:
  69. pass
  70. self.ser = None
  71. actual_port = self.port
  72. logging.info("Connecting to serial port %s at %d baud...", actual_port, self.baud)
  73. try:
  74. self.ser = serial.Serial(
  75. actual_port,
  76. baudrate=self.baud,
  77. timeout=0.2,
  78. write_timeout=1.0
  79. )
  80. self.receiver = StreamReceiver("6400-v2")
  81. logging.info("Serial port opened successfully.")
  82. return True
  83. except Exception as e:
  84. logging.error("Failed to open serial port %s: %s", actual_port, e)
  85. return False
  86. def exchange(self, request_type: int, payload: bytes = b"", timeout: float = 1.0):
  87. """One request; CRC/length checked continuously, GET requires ACK then DATA."""
  88. self.ser.write(make_frame(request_type, payload))
  89. self.ser.flush()
  90. deadline = time.monotonic() + timeout
  91. ack_seen = False
  92. while time.monotonic() < deadline:
  93. for event, frame in self.receiver.feed_bytes(self.ser.read(256)):
  94. if event == "FRAME_REJECTED":
  95. self.rejected_frames += 1
  96. logging.warning("Rejected serial frame: %s", frame["reason"])
  97. elif event == "FRAME_VALID":
  98. kind, data = frame["frame_type"], frame["payload"]
  99. if kind == FrameType.NACK and data[0] == request_type:
  100. logging.error("NACK request=0x%02X reason=0x%02X", data[0], data[1])
  101. return None
  102. if request_type == FrameType.SET_ALL and kind == FrameType.SET_ACK:
  103. return b""
  104. if request_type == FrameType.GET_ALL and kind == FrameType.GET_ACK:
  105. ack_seen = True
  106. elif kind == FrameType.GET_DATA:
  107. if request_type == FrameType.GET_ALL and ack_seen:
  108. return data
  109. self.autonomous_data += 1
  110. logging.debug("Automatic telemetry received (%d bytes)", len(data))
  111. return None
  112. def send_safe_stop(self):
  113. """Set all 24 PTC, 3 SSR, and buzzer to zero, preserving cooling at 20%."""
  114. logging.info("Stopping: setting all 24 PTC channels to 0%%...")
  115. payload = bytes([0] * PTC_COUNT + [20] * FAN_COUNT + [0] * SSR_COUNT + [0])
  116. for attempt in range(3):
  117. if not self.ser or not self.ser.is_open:
  118. self.connect()
  119. if self.ser and self.ser.is_open:
  120. try:
  121. if self.exchange(FrameType.SET_ALL, payload) is not None:
  122. logging.info("Shutdown SET_ACK received (PTC 0%% committed).")
  123. return True
  124. except Exception as e:
  125. logging.warning("Shutdown attempt %d failed: %s", attempt + 1, e)
  126. logging.warning("Could not confirm SET_ACK for shutdown.")
  127. return False
  128. def run_one_cycle(self) -> bool:
  129. """SET all duties, GET after ACK, verify PTC and both fan groups."""
  130. if not self.ser or not self.ser.is_open:
  131. if not self.connect():
  132. self.reconnect_count += 1
  133. return False
  134. try:
  135. payload = bytes([self.ptc_duty] * PTC_COUNT + [self.fan_duty] * FAN_COUNT + [0] * SSR_COUNT + [0])
  136. got_ack = self.exchange(FrameType.SET_ALL, payload) is not None
  137. if got_ack:
  138. self.set_ack_success += 1
  139. else:
  140. self.set_ack_miss += 1
  141. logging.warning("[Cycle %d] SET_ACK missing", self.total_cycles)
  142. data = self.exchange(FrameType.GET_ALL)
  143. if data is None:
  144. self.get_miss += 1
  145. logging.warning("[Cycle %d] GET_ACK + DATA missing", self.total_cycles)
  146. return False
  147. self.get_success += 1
  148. self.last_ptc = list(data[:24])
  149. self.last_fans = list(data[24:32]) # intake chamber 1..4, exhaust chamber 1..4
  150. self.last_bmc = list(data[32:56])
  151. self.last_ct = list(data[56:83])
  152. self.last_ssr = list(data[83:86])
  153. matches = len(data) in (86, 88, 90) and data[:32] + data[83:86] == payload[:35]
  154. if not matches:
  155. self.duty_mismatch_count += 1
  156. logging.error("[Cycle %d] Duty mismatch: PTC=%s intake=%s exhaust=%s",
  157. self.total_cycles, self.last_ptc, self.last_fans[:4], self.last_fans[4:])
  158. return got_ack and matches
  159. except (OSError, IOError) as e:
  160. logging.error("Serial I/O error during cycle %d: %s", self.total_cycles, e)
  161. self.reconnect_count += 1
  162. self.connect()
  163. return False
  164. def update_status_json(self, status: str = "RUNNING"):
  165. now = time.time()
  166. elapsed = now - self.start_time
  167. remaining = max(0.0, self.target_seconds - elapsed)
  168. progress = min(100.0, (elapsed / self.target_seconds) * 100.0) if self.target_seconds > 0 else 100.0
  169. bmc_valid = [t for t in self.last_bmc if t != 0xFF]
  170. ct_valid = [t for t in self.last_ct if t != 0xFF]
  171. data = {
  172. "status": status,
  173. "product": "6400-v2",
  174. "ptc_count": PTC_COUNT,
  175. "host_baud": self.baud,
  176. "port": self.port,
  177. "autonomous_data": self.autonomous_data,
  178. "rejected_frames": self.rejected_frames,
  179. "target_hours": self.target_seconds / 3600.0,
  180. "start_time_iso": datetime.fromtimestamp(self.start_time, timezone.utc).isoformat(),
  181. "last_update_iso": datetime.now(timezone.utc).isoformat(),
  182. "elapsed_seconds": round(elapsed, 1),
  183. "remaining_seconds": round(remaining, 1),
  184. "progress_percent": round(progress, 2),
  185. "total_cycles": self.total_cycles,
  186. "set_ack_success": self.set_ack_success,
  187. "set_ack_miss": self.set_ack_miss,
  188. "get_success": self.get_success,
  189. "get_miss": self.get_miss,
  190. "duty_mismatches": self.duty_mismatch_count,
  191. "reconnect_count": self.reconnect_count,
  192. "target_ptc_duty": self.ptc_duty,
  193. "target_fan_duty": self.fan_duty,
  194. "last_ptc_all_match": (len(self.last_ptc) == PTC_COUNT and all(v == self.ptc_duty for v in self.last_ptc)),
  195. "last_ptc_duties": self.last_ptc,
  196. "last_fan_duties": self.last_fans,
  197. "last_ssr_duties": self.last_ssr,
  198. "target_ssr_duties": [0, 0, 0],
  199. "intake_chambers_1_to_4": self.last_fans[:4],
  200. "exhaust_chambers_1_to_4": self.last_fans[4:],
  201. "temperatures": {
  202. "bmc_valid_channels": len(bmc_valid),
  203. "bmc_min": min(bmc_valid) if bmc_valid else None,
  204. "bmc_max": max(bmc_valid) if bmc_valid else None,
  205. "ct_valid_channels": len(ct_valid),
  206. "ct_min": min(ct_valid) if ct_valid else None,
  207. "ct_max": max(ct_valid) if ct_valid else None,
  208. }
  209. }
  210. try:
  211. tmp_file = self.status_file.with_suffix(".tmp")
  212. tmp_file.write_text(json.dumps(data, indent=2, ensure_ascii=False), encoding="utf-8")
  213. tmp_file.replace(self.status_file)
  214. except Exception as e:
  215. logging.warning("Failed to write status JSON: %s", e)
  216. def run(self):
  217. self.start_time = time.time()
  218. logging.info("=" * 70)
  219. logging.info("STARTING 24-PTC CONTINUOUS STRESS TEST")
  220. logging.info("Target duration: %.2f hours (%.0f seconds)", self.target_seconds / 3600.0, self.target_seconds)
  221. logging.info("Loop interval: %.1f seconds (feeding 30s watchdog every cycle)", self.interval_s)
  222. logging.info("Target PTC duty: %d%% across ALL 24 physical channels", self.ptc_duty)
  223. logging.info("Target Fan duty: %d%% across 8 fan channels", self.fan_duty)
  224. logging.info("Port: %s @ %d baud", self.port, self.baud)
  225. logging.info("Status JSON: %s", self.status_file)
  226. logging.info("=" * 70)
  227. if not self.connect():
  228. logging.error("Initial serial connection failed. Aborting.")
  229. return 1
  230. # Hook signal handlers
  231. def handle_signal(sig, frame):
  232. logging.info("Received signal %s! Initiating graceful stop...", sig)
  233. self.running = False
  234. signal.signal(signal.SIGINT, handle_signal)
  235. signal.signal(signal.SIGTERM, handle_signal)
  236. last_log_time = 0.0
  237. try:
  238. while self.running:
  239. now = time.time()
  240. elapsed = now - self.start_time
  241. if elapsed >= self.target_seconds:
  242. logging.info("Target duration of %.2f hours reached.", self.target_seconds / 3600.0)
  243. break
  244. self.total_cycles += 1
  245. self.run_one_cycle()
  246. self.update_status_json(status="RUNNING")
  247. # Hourly / Periodic log summary every 60s
  248. if now - last_log_time >= 60.0:
  249. last_log_time = now
  250. remaining_s = max(0.0, self.target_seconds - elapsed)
  251. h, rem = divmod(int(elapsed), 3600)
  252. m, s = divmod(rem, 60)
  253. rh, rrem = divmod(int(remaining_s), 3600)
  254. rm, rs = divmod(rrem, 60)
  255. bmc_val = [t for t in self.last_bmc if t != 0xFF]
  256. ct_val = [t for t in self.last_ct if t != 0xFF]
  257. b_str = f"min={min(bmc_val)}C max={max(bmc_val)}C" if bmc_val else "none"
  258. c_str = f"min={min(ct_val)}C max={max(ct_val)}C" if ct_val else "none"
  259. logging.info(
  260. "[Progress %5.2f%%] Elapsed: %02d:%02d:%02d | Remaining: %02d:%02d:%02d | "
  261. "Cycles: %d | ACK OK: %d (miss:%d) | Duty OK: %s | BMC: %s | CT: %s",
  262. (elapsed / self.target_seconds) * 100.0,
  263. h, m, s, rh, rm, rs,
  264. self.total_cycles,
  265. self.set_ack_success,
  266. self.set_ack_miss,
  267. f"24ch={self.ptc_duty}%" if (len(self.last_ptc) == PTC_COUNT and all(v == self.ptc_duty for v in self.last_ptc)) else "MISMATCH",
  268. b_str, c_str
  269. )
  270. time.sleep(self.interval_s)
  271. finally:
  272. shutdown_ok = self.send_safe_stop()
  273. failed = bool(self.set_ack_miss or self.get_miss or self.duty_mismatch_count
  274. or self.reconnect_count or not self.total_cycles or not shutdown_ok)
  275. completed = time.time() - self.start_time >= self.target_seconds
  276. self.update_status_json(status="FAIL" if failed else ("PASS" if completed else "STOPPED"))
  277. if self.ser and self.ser.is_open:
  278. try:
  279. self.ser.close()
  280. except Exception:
  281. pass
  282. logging.info("Stress test complete. Total cycles: %d. Summary saved to %s",
  283. self.total_cycles, self.status_file)
  284. return 1 if failed else 0
  285. def main():
  286. parser = argparse.ArgumentParser(description="24-Hour Continuous 24-PTC Stress Test")
  287. parser.add_argument("--hours", type=float, default=24.0, help="Target test duration in hours (default: 24.0)")
  288. parser.add_argument("--interval", type=float, default=5.0, help="Loop interval in seconds (default: 5.0)")
  289. parser.add_argument("--ptc-duty", type=int, default=50, help="PTC duty percent (default: 50)")
  290. parser.add_argument("--fan-duty", type=int, default=20, help="Fan duty percent (default: 20)")
  291. parser.add_argument("--port", type=str, default="/dev/ttyUSB0", help="Serial port (default: /dev/ttyUSB0)")
  292. parser.add_argument("--baud", type=int, choices=(921600, 460800, 230400, 115200), default=921600, help="Baud rate (default: 921600)")
  293. parser.add_argument("--log-dir", type=Path, default=Path("/home/user/stress_logs"), help="Log directory")
  294. parser.add_argument("--status-file", type=Path, default=Path("/home/user/stress_status.json"), help="Status JSON file")
  295. args = parser.parse_args()
  296. if serial is None:
  297. parser.error("pyserial is required; install with python -m pip install pyserial")
  298. if not 0 <= args.ptc_duty <= 100 or not 0 <= args.fan_duty <= 100:
  299. parser.error("duties must be 0..100 percent")
  300. if args.hours <= 0 or not 0 < args.interval < 25:
  301. parser.error("hours must be positive and interval must be 0..25 seconds for the 30s watchdog")
  302. args.log_dir.mkdir(parents=True, exist_ok=True)
  303. stamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  304. log_file = args.log_dir / f"stress_24ptc_{stamp}.log"
  305. latest_symlink = args.log_dir / "stress_24ptc_latest.log"
  306. # Configure logging
  307. log_format = "%(asctime)s [%(levelname)s] %(message)s"
  308. logging.basicConfig(
  309. level=logging.INFO,
  310. format=log_format,
  311. handlers=[
  312. logging.StreamHandler(sys.stdout),
  313. logging.FileHandler(str(log_file), encoding="utf-8")
  314. ]
  315. )
  316. # Update latest symlink
  317. try:
  318. if latest_symlink.is_symlink() or latest_symlink.exists():
  319. latest_symlink.unlink()
  320. latest_symlink.symlink_to(log_file.name)
  321. except Exception:
  322. pass
  323. tester = StressTester(
  324. port=args.port,
  325. baud=args.baud,
  326. target_hours=args.hours,
  327. interval_s=args.interval,
  328. ptc_duty=args.ptc_duty,
  329. fan_duty=args.fan_duty,
  330. log_dir=args.log_dir,
  331. status_file=args.status_file
  332. )
  333. return tester.run()
  334. if __name__ == "__main__":
  335. sys.exit(main())