test_pwm_scope_stream.py 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169
  1. """Reproduce startup residual-frame ACK starvation without hardware."""
  2. import io
  3. import json
  4. import types
  5. import unittest
  6. from unittest.mock import patch
  7. from tools import pwm_scope as scope
  8. ACK = bytes.fromhex('a5 5a 81 00 a6 35')
  9. GET_ACK = bytes.fromhex('a5 5a 82 00 f5 60')
  10. # Prefix seen in the user's 22:42:11.630955 BAD_CRC record, ending at SET_ACK.
  11. USER_RESIDUE = bytes.fromhex('a5 5a 42 56 ' + '00 '*16 + 'a6') + ACK
  12. class Clock:
  13. def __init__(self): self.now = 0.0
  14. def __call__(self): return self.now
  15. class Wire:
  16. def __init__(self, clock, initial=(), response=()):
  17. self.clock = clock
  18. self.chunks = list(initial)
  19. self.response = response
  20. self.writes = []
  21. @property
  22. def in_waiting(self):
  23. return len(self.chunks[0][1]) if self.chunks and self.chunks[0][0] <= self.clock.now else 0
  24. def read(self, count):
  25. limit = self.clock.now + 0.05
  26. if self.chunks and self.chunks[0][0] <= limit:
  27. due, data = self.chunks.pop(0)
  28. self.clock.now = max(self.clock.now, due)
  29. return data
  30. self.clock.now = limit
  31. return b''
  32. def write(self, raw):
  33. self.writes.append(raw)
  34. self.chunks.extend((self.clock.now + delta, data) for delta, data in self.response)
  35. self.chunks.sort(key=lambda x: x[0])
  36. return len(raw)
  37. def close(self): pass
  38. class ScopeStreamTests(unittest.TestCase):
  39. def setUp(self):
  40. self.clock = Clock()
  41. self.wire = Wire(self.clock)
  42. self.log = io.StringIO()
  43. self.time_patch = patch.object(scope.time, 'monotonic', self.clock)
  44. self.serial_patch = patch.dict('sys.modules', {'serial': types.SimpleNamespace(Serial=lambda *a, **k: self.wire)})
  45. self.time_patch.start(); self.serial_patch.start()
  46. self.addCleanup(self.time_patch.stop); self.addCleanup(self.serial_patch.stop)
  47. self.link = scope.Link('fixture', self.log)
  48. def events(self): return [json.loads(s) for s in self.log.getvalue().splitlines()]
  49. def test_user_residual_prefix_does_not_hide_valid_set_ack_until_next_auto_frame(self):
  50. self.wire.response = [(0.004, USER_RESIDUE)]
  51. self.assertEqual(self.link.request(1, 10), b'')
  52. self.assertLess(self.clock.now, 0.2)
  53. self.assertEqual(self.link.partial_timeouts, 1)
  54. self.assertEqual(len(self.wire.writes), 1) # no retry masking
  55. self.assertTrue(any(e['event'] == 'RX_PARTIAL_TIMEOUT' for e in self.events()))
  56. def test_startup_drain_is_before_first_tx_and_raw_bytes_remain_in_log(self):
  57. self.wire.chunks = [(0, USER_RESIDUE), (0.01, b'old tail')]
  58. self.link.synchronize(10)
  59. self.assertEqual(self.wire.writes, [])
  60. self.assertEqual(self.link.startup_bytes, len(USER_RESIDUE) + 8)
  61. self.assertEqual(self.link.bad_crc, 0)
  62. self.assertEqual(self.link.buf, b'')
  63. raw = b''.join(bytes.fromhex(e['hex']) for e in self.events() if e['event'] == 'STARTUP_RX')
  64. self.assertEqual(raw, USER_RESIDUE + b'old tail')
  65. self.wire.response = [(0.004, ACK)]
  66. self.assertEqual(self.link.request(1, 10), b'')
  67. def test_fragmented_valid_frame_with_embedded_ack_is_not_reinterpreted(self):
  68. payload = b'\x55'*12 + ACK + b'\x55'*68
  69. packet = scope.frame(0x42, payload)
  70. self.wire.response = [(0.004, packet[:24]), (0.044, packet[24:])]
  71. with self.assertRaises(TimeoutError): self.link.request(1, 10)
  72. self.assertEqual(self.link.bad_crc, 0)
  73. self.assertEqual(self.link.partial_timeouts, 0)
  74. self.assertIsNone(self.link.last_ack_at)
  75. def test_host_pause_does_not_discard_a_valid_frame_already_queued(self):
  76. payload = b'\x55'*12 + ACK + b'\x55'*68
  77. packet = scope.frame(0x42, payload)
  78. self.wire.chunks = [(0, packet[:24]), (0.04, packet[24:])]
  79. self.assertEqual(self.link.receive(), [])
  80. self.clock.now += 0.5
  81. self.assertEqual(self.link.receive(), [(0x42, payload)])
  82. self.assertEqual(self.link.partial_timeouts, 0)
  83. def test_split_header_and_ack_over_usb_reads(self):
  84. self.wire.response = [(0.004, ACK[:1]), (0.02, ACK[1:3]), (0.04, ACK[3:])]
  85. self.assertEqual(self.link.request(1, 10), b'')
  86. self.assertEqual(self.link.partial_timeouts, 0)
  87. def test_real_crc_failure_after_sync_is_counted_and_logged(self):
  88. self.link.synchronize(10)
  89. bad = bytearray(scope.frame(0x42, bytes(86))); bad[-1] ^= 1
  90. self.wire.response = [(0.004, bytes(bad) + ACK)]
  91. self.assertEqual(self.link.request(1, 10), b'')
  92. self.assertEqual(self.link.bad_crc, 1)
  93. self.assertTrue(any(e['event'] == 'BAD_CRC' for e in self.events()))
  94. def test_get_requires_ack_then_data_not_autonomous_data(self):
  95. wanted = bytes(range(86))
  96. self.wire.response = [(0.004, scope.frame(0x42, bytes(86))),
  97. (0.02, GET_ACK + scope.frame(0x42, wanted))]
  98. self.assertEqual(self.link.request(2, 10), wanted)
  99. def test_missing_ack_still_times_out_without_retry(self):
  100. self.wire.response = [(0.004, scope.frame(0x42, bytes(86)))]
  101. with self.assertRaises(TimeoutError): self.link.request(1, 10)
  102. self.assertGreaterEqual(self.clock.now, 0.7)
  103. self.assertEqual(len(self.wire.writes), 1)
  104. def test_expired_run_never_sends(self):
  105. with self.assertRaises(TimeoutError): self.link.request(1, 0)
  106. self.assertEqual(self.wire.writes, [])
  107. def test_timeout_panel_does_not_claim_good_feed_or_current_match(self):
  108. lines = scope.render_live_panel(scope.Style(False), cycles=1, total_cycles=900,
  109. elapsed=31, remaining=869, read_only=False, matches=None,
  110. outputs=scope.DUTIES, ct=None, errors=1, bad_crc=0,
  111. diag=None, diag_slots={}, last_error='SET等待应答超时', last_ack_age=31)
  112. text = '\n'.join(lines)
  113. self.assertIn('本轮应答未确认', text)
  114. self.assertIn('通信已超时', text)
  115. self.assertNotIn('✓', text)
  116. self.assertNotIn('喂狗正常', text)
  117. for line in lines: self.assertEqual(scope.disp_width(line), scope.BOX_WIDTH)
  118. def test_fan_pwm_alternates_5s_50_percent_and_5s_0_percent(self):
  119. for t in (0.0, 0.5, 1.0, 2.0, 3.0, 4.0, 4.999, 10.0, 14.0):
  120. self.assertEqual(scope.fan_duty_for_elapsed(t), 50, f"t={t}")
  121. for t in (5.0, 5.5, 6.0, 7.0, 8.0, 9.0, 9.999, 15.0, 19.0):
  122. self.assertEqual(scope.fan_duty_for_elapsed(t), 0, f"t={t}")
  123. self.assertEqual(list(scope.DUTIES[:24]), list(range(1, 25)))
  124. self.assertEqual(list(scope.DUTIES[24:32]), [50] * 8)
  125. self.assertEqual(list(scope.DUTIES[32:35]), [33, 34, 35])
  126. self.assertEqual(list(scope.DUTIES_FAN_ZERO[:24]), list(range(1, 25)))
  127. self.assertEqual(list(scope.DUTIES_FAN_ZERO[24:32]), [0] * 8)
  128. self.assertEqual(list(scope.DUTIES_FAN_ZERO[32:35]), [33, 34, 35])
  129. for expected in (scope.DUTIES, scope.DUTIES_FAN_ZERO):
  130. lines = scope.render_live_panel(
  131. scope.Style(False), cycles=6, total_cycles=900,
  132. elapsed=5.0, remaining=895.0, read_only=False, matches=True,
  133. outputs=expected, ct=[25] * 9, errors=0, bad_crc=0,
  134. diag=None, diag_slots={}, last_error=None, last_ack_age=0.1,
  135. expected_outputs=expected,
  136. )
  137. for line in lines:
  138. self.assertEqual(scope.disp_width(line), scope.BOX_WIDTH)
  139. def test_resolve_port_follows_replugged_usb1_and_rejects_usb0(self):
  140. old_path = "/dev/serial/by-path/pci-0000:00:14.0-usb-0:2:1.0-port0"
  141. new_path = "/dev/serial/by-path/pci-0000:00:14.0-usb-0:3:1.0-port0"
  142. with patch("os.path.exists", side_effect=lambda p: p == new_path), \
  143. patch("os.path.realpath", side_effect=lambda p: "/dev/ttyUSB1" if p == new_path else p):
  144. self.assertEqual(scope.resolve_port(old_path), new_path)
  145. with patch("os.path.realpath", return_value="/dev/ttyUSB0"):
  146. with self.assertRaises(RuntimeError):
  147. scope.resolve_port("/dev/serial/by-path/pci-0000:00:14.0-usb-0:6:1.0-port0")
  148. if __name__ == '__main__': unittest.main()