| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378 |
- #!/usr/bin/env python3
- """24-Hour Continuous Hardware Stress Test for Prod2U 6400 V2.0 (24 PTC / 8 fan / 3 SSR protocol).
- Continuously maintains all 24 physical PTC heating channels at 50% duty cycle,
- feeds the 30-second hardware watchdog every loop, periodically queries and verifies
- readback duty values and temperatures, and logs detailed statistics.
- Safety: Gracefully drives all 24 PTC channels to 0% upon termination (SIGINT/SIGTERM/completion).
- """
- import argparse
- from datetime import datetime, timezone
- import json
- import logging
- from pathlib import Path
- import signal
- import sys
- import time
- ROOT = Path(__file__).resolve().parents[1]
- if str(ROOT) not in sys.path:
- sys.path.insert(0, str(ROOT))
- from tools.stream_receiver import StreamReceiver
- from tools._vendor.hth_protocol import FrameType, encode_frame
- try:
- import serial
- except ImportError:
- serial = None
- # The historical filename is kept for existing launch commands; this tool now
- # targets 6400-v2 3.0: 24 PTC + 8 fan + 3 SSR (SET=35, DATA=86).
- # This PTC-only stress test keeps all three heater-cloth SSR outputs at zero.
- PTC_COUNT = 24
- FAN_COUNT = 8
- SSR_COUNT = 3
- def make_frame(msg_type: int, payload: bytes = b"") -> bytes:
- return encode_frame(msg_type, payload)
- class StressTester:
- def __init__(self, port: str, baud: int, target_hours: float, interval_s: float,
- ptc_duty: int, fan_duty: int, log_dir: Path, status_file: Path):
- self.port = port
- self.baud = baud
- self.target_seconds = target_hours * 3600.0
- self.interval_s = interval_s
- self.ptc_duty = ptc_duty
- self.fan_duty = fan_duty
- self.log_dir = log_dir
- self.status_file = status_file
-
- self.ser = None
- self.running = True
- self.start_time = 0.0
-
- # Statistics
- self.total_cycles = 0
- self.set_ack_success = 0
- self.set_ack_miss = 0
- self.get_success = 0
- self.get_miss = 0
- self.duty_mismatch_count = 0
- self.reconnect_count = 0
-
- # Last known readback
- self.last_ptc = []
- self.last_fans = []
- self.last_bmc = []
- self.last_ct = []
- self.last_ssr = []
- self.receiver = StreamReceiver("6400-v2")
- self.autonomous_data = 0
- self.rejected_frames = 0
- def connect(self) -> bool:
- if self.ser and self.ser.is_open:
- try:
- self.ser.close()
- except Exception:
- pass
- self.ser = None
-
- actual_port = self.port
- logging.info("Connecting to serial port %s at %d baud...", actual_port, self.baud)
- try:
- self.ser = serial.Serial(
- actual_port,
- baudrate=self.baud,
- timeout=0.2,
- write_timeout=1.0
- )
- self.receiver = StreamReceiver("6400-v2")
- logging.info("Serial port opened successfully.")
- return True
- except Exception as e:
- logging.error("Failed to open serial port %s: %s", actual_port, e)
- return False
- def exchange(self, request_type: int, payload: bytes = b"", timeout: float = 1.0):
- """One request; CRC/length checked continuously, GET requires ACK then DATA."""
- self.ser.write(make_frame(request_type, payload))
- self.ser.flush()
- deadline = time.monotonic() + timeout
- ack_seen = False
- while time.monotonic() < deadline:
- for event, frame in self.receiver.feed_bytes(self.ser.read(256)):
- if event == "FRAME_REJECTED":
- self.rejected_frames += 1
- logging.warning("Rejected serial frame: %s", frame["reason"])
- elif event == "FRAME_VALID":
- kind, data = frame["frame_type"], frame["payload"]
- if kind == FrameType.NACK and data[0] == request_type:
- logging.error("NACK request=0x%02X reason=0x%02X", data[0], data[1])
- return None
- if request_type == FrameType.SET_ALL and kind == FrameType.SET_ACK:
- return b""
- if request_type == FrameType.GET_ALL and kind == FrameType.GET_ACK:
- ack_seen = True
- elif kind == FrameType.GET_DATA:
- if request_type == FrameType.GET_ALL and ack_seen:
- return data
- self.autonomous_data += 1
- logging.debug("Automatic telemetry received (%d bytes)", len(data))
- return None
- def send_safe_stop(self):
- """Set all 24 PTC, 3 SSR, and buzzer to zero, preserving cooling at 20%."""
- logging.info("Stopping: setting all 24 PTC channels to 0%%...")
- payload = bytes([0] * PTC_COUNT + [20] * FAN_COUNT + [0] * SSR_COUNT + [0])
- for attempt in range(3):
- if not self.ser or not self.ser.is_open:
- self.connect()
- if self.ser and self.ser.is_open:
- try:
- if self.exchange(FrameType.SET_ALL, payload) is not None:
- logging.info("Shutdown SET_ACK received (PTC 0%% committed).")
- return True
- except Exception as e:
- logging.warning("Shutdown attempt %d failed: %s", attempt + 1, e)
- logging.warning("Could not confirm SET_ACK for shutdown.")
- return False
- def run_one_cycle(self) -> bool:
- """SET all duties, GET after ACK, verify PTC and both fan groups."""
- if not self.ser or not self.ser.is_open:
- if not self.connect():
- self.reconnect_count += 1
- return False
- try:
- payload = bytes([self.ptc_duty] * PTC_COUNT + [self.fan_duty] * FAN_COUNT + [0] * SSR_COUNT + [0])
- got_ack = self.exchange(FrameType.SET_ALL, payload) is not None
- if got_ack:
- self.set_ack_success += 1
- else:
- self.set_ack_miss += 1
- logging.warning("[Cycle %d] SET_ACK missing", self.total_cycles)
- data = self.exchange(FrameType.GET_ALL)
- if data is None:
- self.get_miss += 1
- logging.warning("[Cycle %d] GET_ACK + DATA missing", self.total_cycles)
- return False
- self.get_success += 1
- self.last_ptc = list(data[:24])
- self.last_fans = list(data[24:32]) # intake chamber 1..4, exhaust chamber 1..4
- self.last_bmc = list(data[32:56])
- self.last_ct = list(data[56:83])
- self.last_ssr = list(data[83:86])
- matches = len(data) in (86, 88, 90) and data[:32] + data[83:86] == payload[:35]
- if not matches:
- self.duty_mismatch_count += 1
- logging.error("[Cycle %d] Duty mismatch: PTC=%s intake=%s exhaust=%s",
- self.total_cycles, self.last_ptc, self.last_fans[:4], self.last_fans[4:])
- return got_ack and matches
- except (OSError, IOError) as e:
- logging.error("Serial I/O error during cycle %d: %s", self.total_cycles, e)
- self.reconnect_count += 1
- self.connect()
- return False
- def update_status_json(self, status: str = "RUNNING"):
- now = time.time()
- elapsed = now - self.start_time
- remaining = max(0.0, self.target_seconds - elapsed)
- progress = min(100.0, (elapsed / self.target_seconds) * 100.0) if self.target_seconds > 0 else 100.0
-
- bmc_valid = [t for t in self.last_bmc if t != 0xFF]
- ct_valid = [t for t in self.last_ct if t != 0xFF]
-
- data = {
- "status": status,
- "product": "6400-v2",
- "ptc_count": PTC_COUNT,
- "host_baud": self.baud,
- "port": self.port,
- "autonomous_data": self.autonomous_data,
- "rejected_frames": self.rejected_frames,
- "target_hours": self.target_seconds / 3600.0,
- "start_time_iso": datetime.fromtimestamp(self.start_time, timezone.utc).isoformat(),
- "last_update_iso": datetime.now(timezone.utc).isoformat(),
- "elapsed_seconds": round(elapsed, 1),
- "remaining_seconds": round(remaining, 1),
- "progress_percent": round(progress, 2),
- "total_cycles": self.total_cycles,
- "set_ack_success": self.set_ack_success,
- "set_ack_miss": self.set_ack_miss,
- "get_success": self.get_success,
- "get_miss": self.get_miss,
- "duty_mismatches": self.duty_mismatch_count,
- "reconnect_count": self.reconnect_count,
- "target_ptc_duty": self.ptc_duty,
- "target_fan_duty": self.fan_duty,
- "last_ptc_all_match": (len(self.last_ptc) == PTC_COUNT and all(v == self.ptc_duty for v in self.last_ptc)),
- "last_ptc_duties": self.last_ptc,
- "last_fan_duties": self.last_fans,
- "last_ssr_duties": self.last_ssr,
- "target_ssr_duties": [0, 0, 0],
- "intake_chambers_1_to_4": self.last_fans[:4],
- "exhaust_chambers_1_to_4": self.last_fans[4:],
- "temperatures": {
- "bmc_valid_channels": len(bmc_valid),
- "bmc_min": min(bmc_valid) if bmc_valid else None,
- "bmc_max": max(bmc_valid) if bmc_valid else None,
- "ct_valid_channels": len(ct_valid),
- "ct_min": min(ct_valid) if ct_valid else None,
- "ct_max": max(ct_valid) if ct_valid else None,
- }
- }
- try:
- tmp_file = self.status_file.with_suffix(".tmp")
- tmp_file.write_text(json.dumps(data, indent=2, ensure_ascii=False), encoding="utf-8")
- tmp_file.replace(self.status_file)
- except Exception as e:
- logging.warning("Failed to write status JSON: %s", e)
- def run(self):
- self.start_time = time.time()
- logging.info("=" * 70)
- logging.info("STARTING 24-PTC CONTINUOUS STRESS TEST")
- logging.info("Target duration: %.2f hours (%.0f seconds)", self.target_seconds / 3600.0, self.target_seconds)
- logging.info("Loop interval: %.1f seconds (feeding 30s watchdog every cycle)", self.interval_s)
- logging.info("Target PTC duty: %d%% across ALL 24 physical channels", self.ptc_duty)
- logging.info("Target Fan duty: %d%% across 8 fan channels", self.fan_duty)
- logging.info("Port: %s @ %d baud", self.port, self.baud)
- logging.info("Status JSON: %s", self.status_file)
- logging.info("=" * 70)
-
- if not self.connect():
- logging.error("Initial serial connection failed. Aborting.")
- return 1
-
- # Hook signal handlers
- def handle_signal(sig, frame):
- logging.info("Received signal %s! Initiating graceful stop...", sig)
- self.running = False
-
- signal.signal(signal.SIGINT, handle_signal)
- signal.signal(signal.SIGTERM, handle_signal)
-
- last_log_time = 0.0
-
- try:
- while self.running:
- now = time.time()
- elapsed = now - self.start_time
- if elapsed >= self.target_seconds:
- logging.info("Target duration of %.2f hours reached.", self.target_seconds / 3600.0)
- break
-
- self.total_cycles += 1
- self.run_one_cycle()
- self.update_status_json(status="RUNNING")
-
- # Hourly / Periodic log summary every 60s
- if now - last_log_time >= 60.0:
- last_log_time = now
- remaining_s = max(0.0, self.target_seconds - elapsed)
- h, rem = divmod(int(elapsed), 3600)
- m, s = divmod(rem, 60)
- rh, rrem = divmod(int(remaining_s), 3600)
- rm, rs = divmod(rrem, 60)
-
- bmc_val = [t for t in self.last_bmc if t != 0xFF]
- ct_val = [t for t in self.last_ct if t != 0xFF]
- b_str = f"min={min(bmc_val)}C max={max(bmc_val)}C" if bmc_val else "none"
- c_str = f"min={min(ct_val)}C max={max(ct_val)}C" if ct_val else "none"
-
- logging.info(
- "[Progress %5.2f%%] Elapsed: %02d:%02d:%02d | Remaining: %02d:%02d:%02d | "
- "Cycles: %d | ACK OK: %d (miss:%d) | Duty OK: %s | BMC: %s | CT: %s",
- (elapsed / self.target_seconds) * 100.0,
- h, m, s, rh, rm, rs,
- self.total_cycles,
- self.set_ack_success,
- self.set_ack_miss,
- 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",
- b_str, c_str
- )
-
- time.sleep(self.interval_s)
-
- finally:
- shutdown_ok = self.send_safe_stop()
- failed = bool(self.set_ack_miss or self.get_miss or self.duty_mismatch_count
- or self.reconnect_count or not self.total_cycles or not shutdown_ok)
- completed = time.time() - self.start_time >= self.target_seconds
- self.update_status_json(status="FAIL" if failed else ("PASS" if completed else "STOPPED"))
- if self.ser and self.ser.is_open:
- try:
- self.ser.close()
- except Exception:
- pass
- logging.info("Stress test complete. Total cycles: %d. Summary saved to %s",
- self.total_cycles, self.status_file)
- return 1 if failed else 0
- def main():
- parser = argparse.ArgumentParser(description="24-Hour Continuous 24-PTC Stress Test")
- parser.add_argument("--hours", type=float, default=24.0, help="Target test duration in hours (default: 24.0)")
- parser.add_argument("--interval", type=float, default=5.0, help="Loop interval in seconds (default: 5.0)")
- parser.add_argument("--ptc-duty", type=int, default=50, help="PTC duty percent (default: 50)")
- parser.add_argument("--fan-duty", type=int, default=20, help="Fan duty percent (default: 20)")
- parser.add_argument("--port", type=str, default="/dev/ttyUSB0", help="Serial port (default: /dev/ttyUSB0)")
- parser.add_argument("--baud", type=int, choices=(921600, 460800, 230400, 115200), default=921600, help="Baud rate (default: 921600)")
- parser.add_argument("--log-dir", type=Path, default=Path("/home/user/stress_logs"), help="Log directory")
- parser.add_argument("--status-file", type=Path, default=Path("/home/user/stress_status.json"), help="Status JSON file")
-
- args = parser.parse_args()
- if serial is None:
- parser.error("pyserial is required; install with python -m pip install pyserial")
- if not 0 <= args.ptc_duty <= 100 or not 0 <= args.fan_duty <= 100:
- parser.error("duties must be 0..100 percent")
- if args.hours <= 0 or not 0 < args.interval < 25:
- parser.error("hours must be positive and interval must be 0..25 seconds for the 30s watchdog")
-
- args.log_dir.mkdir(parents=True, exist_ok=True)
- stamp = datetime.now().strftime("%Y%m%d_%H%M%S")
- log_file = args.log_dir / f"stress_24ptc_{stamp}.log"
- latest_symlink = args.log_dir / "stress_24ptc_latest.log"
-
- # Configure logging
- log_format = "%(asctime)s [%(levelname)s] %(message)s"
- logging.basicConfig(
- level=logging.INFO,
- format=log_format,
- handlers=[
- logging.StreamHandler(sys.stdout),
- logging.FileHandler(str(log_file), encoding="utf-8")
- ]
- )
-
- # Update latest symlink
- try:
- if latest_symlink.is_symlink() or latest_symlink.exists():
- latest_symlink.unlink()
- latest_symlink.symlink_to(log_file.name)
- except Exception:
- pass
-
- tester = StressTester(
- port=args.port,
- baud=args.baud,
- target_hours=args.hours,
- interval_s=args.interval,
- ptc_duty=args.ptc_duty,
- fan_duty=args.fan_duty,
- log_dir=args.log_dir,
- status_file=args.status_file
- )
- return tester.run()
- if __name__ == "__main__":
- sys.exit(main())
|