| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139 |
- """Current layouts and autonomous output on synthetic wires; no hardware access."""
- from collections import deque
- from contextlib import redirect_stdout
- import io
- from pathlib import Path
- import tempfile
- import types
- import unittest
- from unittest.mock import patch
- from tools import get_all, pwm_scope, run_ptc_cycle_test as cycle, prod2u_load_sweep as sweep
- from tools._vendor.hth_protocol import FrameType, encode_frame, decode_frame
- class Wire:
- def __init__(self, chunks):
- self.chunks = deque(chunks)
- self.writes = []
- def read(self, count):
- return self.chunks.popleft() if self.chunks else b""
- def write(self, raw):
- self.writes.append(raw)
- return len(raw)
- def close(self):
- pass
- class CurrentSerialToolTests(unittest.TestCase):
- def test_query_requires_ack_and_reports_current_channel_groups(self):
- automatic = bytes([7] * 86)
- requested = bytes([20] * 24 + list(range(1, 9)) + [255] * 51 + [0, 25, 100])
- wire = Wire([encode_frame(FrameType.GET_DATA, automatic),
- encode_frame(FrameType.GET_ACK) + encode_frame(FrameType.GET_DATA, requested)])
- payload, auto_count = get_all.query(wire)
- self.assertEqual(payload, requested)
- self.assertEqual(auto_count, 1)
- data = get_all.telemetry(payload)
- self.assertEqual(data["intake_chambers_1_to_4"], [1, 2, 3, 4])
- self.assertEqual(data["exhaust_chambers_1_to_4"], [5, 6, 7, 8])
- self.assertEqual(data["ptc_chambers_1_to_4"], [[20] * 6] * 4)
- self.assertEqual(data["ct_c"], [None] * 27)
- self.assertEqual(data["heater_cloths_percent"],
- {"SSR1_chamber1": 0, "SSR2_chambers2_and3": 25, "SSR4_chamber4": 100})
- with self.assertRaises(ValueError):
- get_all.telemetry(bytes(83))
- with self.assertRaises(TimeoutError):
- get_all.query(Wire([encode_frame(FrameType.GET_DATA, automatic)]), timeout=0.001)
- def test_diagnostic_between_get_ack_and_data_does_not_complete_query(self):
- diagnostic = bytes([1, 0x64, 3, 0, 0] + [0] * 15)
- requested = bytes([0] * 24 + [20] * 8 + [255] * 51 + [0] * 3)
- wire = Wire([encode_frame(FrameType.GET_ACK) + encode_frame(FrameType.DIAGNOSTIC, diagnostic),
- encode_frame(FrameType.GET_DATA, requested)])
- self.assertEqual(get_all.query(wire), (requested, 0))
- with self.assertRaises(TimeoutError):
- get_all.query(Wire([encode_frame(FrameType.GET_ACK)
- + encode_frame(FrameType.DIAGNOSTIC, diagnostic)]), timeout=0.001)
- def test_cycle_appends_zero_ssr_values_with_correct_crc(self):
- frame = decode_frame(cycle.build_set_all_frame([17] * 24, [20] * 4, [30] * 4))
- self.assertTrue(frame.crc_ok)
- self.assertEqual(frame.payload, bytes([17] * 24 + [20] * 4 + [30] * 4 + [0] * 3))
- def test_cycle_keeps_ack_when_automatic_data_is_in_same_chunk(self):
- combined = encode_frame(FrameType.SET_ACK) + encode_frame(FrameType.GET_DATA, bytes([255] * 83 + [0, 0, 0]))
- fake = types.SimpleNamespace(Serial=lambda *args, **kwargs: Wire([combined]))
- output = io.StringIO()
- with patch.dict("sys.modules", {"serial": fake}), redirect_stdout(output):
- result = cycle.main(["--port", "fixture", "--duration", "1", "--interval", "0.01"])
- self.assertEqual(result, 1) # later cycles have no ACK, so cannot claim overall success
- self.assertIn("累计ACK: 1/1", output.getvalue())
- self.assertIn("自动状态: 1 次", output.getvalue())
- @unittest.skipUnless(sweep.HTH_AVAILABLE, "HTH SDK required")
- def test_mock_sweep_uses_real_sdk_and_writes_honest_command_summary(self):
- with tempfile.TemporaryDirectory() as folder:
- runner = sweep.LoadSweepRunner(port="mock", duration=0.05, step_interval=0.01, log_dir=Path(folder))
- runner.start()
- self.assertTrue(runner.running)
- runner._thread.join(timeout=3)
- self.assertFalse(runner.running)
- self.assertIsNone(runner.error)
- self.assertGreater(runner.metrics.set_acks, 0)
- self.assertEqual(runner.metrics.command_errors, 0)
- self.assertEqual(runner.summary()["raw_capture"], "NOT_IMPLEMENTED")
- self.assertFalse((Path(folder) / "TX.bin").exists())
- @unittest.skipUnless(sweep.HTH_AVAILABLE, "HTH SDK required")
- def test_poll_uses_sdk_limit_masks(self):
- with tempfile.TemporaryDirectory() as folder:
- runner = sweep.LoadSweepRunner(log_dir=Path(folder))
- class Stop:
- count = 0
- def is_set(self): return self.count > 0
- def wait(self, timeout): self.count += 1; return False
- state = types.SimpleNamespace(duty={"fan": (0, 0, 0, 0)}, limit_masks=(1, 2))
- runner._heartbeat_poll_loop(types.SimpleNamespace(read_all=lambda **kw: state), Stop())
- self.assertEqual(runner.metrics.get_data, 1)
- self.assertEqual(runner.metrics.command_errors, 0)
- def test_pwm_scope_alignment_and_usb0_guard(self):
- output = io.StringIO()
- with redirect_stdout(output):
- rc = pwm_scope.main(["--dry-run"])
- self.assertEqual(rc, 0)
- lines = output.getvalue().splitlines()
- box_lines = [line for line in lines if line.startswith(("┌", "│", "├", "└"))]
- self.assertGreater(len(box_lines), 45)
- for line in box_lines:
- self.assertEqual(pwm_scope.disp_width(line), pwm_scope.BOX_WIDTH)
- panel = pwm_scope.render_live_panel(
- pwm_scope.Style(enabled=True),
- cycles=12,
- total_cycles=900,
- elapsed=12.0,
- remaining=888.0,
- read_only=False,
- matches=True,
- outputs=pwm_scope.DUTIES,
- ct=[25, 0, 21, 0, 0, 0, 0, 0, 0],
- errors=0,
- bad_crc=3,
- diag={"version": "3.0.2", "slot": 9, "address": 73, "register": 0x23,
- "error": 0, "raw": 0xFD00, "decode_mask": 0x1FF, "bus": 6, "flags": 0x11},
- diag_slots={0x23: {"raw": 0xFD00}, 0x30: {"raw": 0xFF9E},
- 0xC4: {"raw": 0x8000}, 0xFE: {"raw": 0x5959}, 0xFF: {"raw": 0x7428}},
- last_error=None,
- )
- for line in panel:
- self.assertEqual(pwm_scope.disp_width(line), pwm_scope.BOX_WIDTH)
- with patch("os.path.realpath", return_value="/dev/ttyUSB0"):
- with self.assertRaises(RuntimeError):
- pwm_scope.run(types.SimpleNamespace(port="/dev/ttyUSB0", minutes=1, interval=1,
- read_only=True, log=None, scroll=True, no_color=True))
- if __name__ == "__main__":
- unittest.main()
|