test_prod2u_door_temp_uart_e2e.py 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166
  1. """Real UART-bit e2e scenario for the refactored top.
  2. This test is intentionally kept independent of the Python protocol model at the
  3. wire boundary: bytes are serialized as 8N1 bits at 217 system clocks/bit.
  4. """
  5. import cocotb
  6. import cocotb.simulator as simulator
  7. from cocotb.triggers import Event, FallingEdge, NextTimeStep, ReadOnly, ReadWrite, RisingEdge, SimTimeoutError, Timer, with_timeout
  8. CLKS_PER_BIT = 217
  9. SET_ALL = 0x01
  10. GET_TEMPERATURE = 0x02
  11. TEMPERATURE_DATA = 0x82
  12. MOTOR_STEPS = 450
  13. MOTOR_COMPLETION_TIMEOUT_MS = 600
  14. TEMPERATURE_BYTE_TIMEOUT_MS = 100
  15. def crc16(data: bytes) -> int:
  16. crc = 0xFFFF
  17. for value in data:
  18. crc ^= value << 8
  19. for _ in range(8):
  20. crc = ((crc << 1) ^ 0x1021) & 0xFFFF if crc & 0x8000 else (crc << 1) & 0xFFFF
  21. return crc
  22. def frame(kind: int, payload: bytes) -> bytes:
  23. body = bytes((kind, len(payload))) + payload
  24. return b"\xA5\x5A" + body + crc16(body).to_bytes(2, "little")
  25. async def clocks(dut, count: int) -> None:
  26. await Timer(count * 40, units="ns")
  27. async def send_uart_byte(dut, value: int) -> None:
  28. await ReadWrite()
  29. dut.host_uart_rx.value = 0
  30. await clocks(dut, CLKS_PER_BIT)
  31. for bit in range(8):
  32. dut.host_uart_rx.value = (value >> bit) & 1
  33. await clocks(dut, CLKS_PER_BIT)
  34. dut.host_uart_rx.value = 1
  35. await clocks(dut, CLKS_PER_BIT)
  36. async def send_frame(dut, packet: bytes) -> None:
  37. await NextTimeStep()
  38. for value in packet:
  39. await send_uart_byte(dut, value)
  40. async def observe_motor_steps(dut, observed: dict[str, int | bool], completion: Event) -> None:
  41. while True:
  42. await RisingEdge(dut.x_step)
  43. await ReadOnly()
  44. if not dut.x_step.value.is_resolvable or not dut.y_step.value.is_resolvable:
  45. continue
  46. current_x = int(dut.x_step.value)
  47. current_y = int(dut.y_step.value)
  48. if current_x and observed["x"] < MOTOR_STEPS:
  49. observed["x"] = int(observed["x"]) + 1
  50. if current_y and observed["y"] < MOTOR_STEPS:
  51. observed["y"] = int(observed["y"]) + 1
  52. if current_x and current_y:
  53. observed["overlap"] = True
  54. if observed["x"] == MOTOR_STEPS and observed["y"] == MOTOR_STEPS:
  55. completion.set()
  56. return
  57. async def receive_uart_byte(dut) -> int:
  58. await FallingEdge(dut.host_uart_tx)
  59. await Timer((CLKS_PER_BIT + CLKS_PER_BIT // 2) * 40, units="ns")
  60. value = 0
  61. for bit in range(8):
  62. value |= int(dut.host_uart_tx.value) << bit
  63. await Timer(CLKS_PER_BIT * 40, units="ns")
  64. assert int(dut.host_uart_tx.value) == 1
  65. return value
  66. async def wait_for_stage(awaitable, timeout_ms: int, stage: str, byte_index: int = -1):
  67. """Apply a bounded wait with a stable, machine-searchable failure message."""
  68. try:
  69. return await with_timeout(awaitable, timeout_ms, "ms")
  70. except SimTimeoutError as exc:
  71. suffix = "" if byte_index < 0 else f" byte_index={byte_index}"
  72. raise AssertionError(
  73. f"timeout stage={stage} timeout_ms={timeout_ms}{suffix}"
  74. ) from exc
  75. def stop_background_task(task) -> None:
  76. if task is None:
  77. return
  78. if hasattr(task, "cancel"):
  79. task.cancel()
  80. elif hasattr(task, "kill"):
  81. task.kill()
  82. @cocotb.test()
  83. async def test_set_all_get_temperature_over_real_uart(dut):
  84. observer_task = None
  85. observed = {"x": 0, "y": 0, "overlap": False}
  86. motor_completion = Event()
  87. try:
  88. observer_task = cocotb.start_soon(
  89. observe_motor_steps(dut, observed, motor_completion)
  90. )
  91. dut.host_uart_rx.value = 1
  92. dut.x_limit_raw.value = 1
  93. dut.y_limit_raw.value = 1
  94. dut.temp_scl.value = 1
  95. dut.temp_sda.value = 1
  96. await clocks(dut, 1024)
  97. await RisingEdge(dut.u_dut.startup_done)
  98. payload = bytes((10, 20, 30, 40, 0, 0, 0, 0, 0, 1, 2))
  99. await send_frame(dut, frame(SET_ALL, payload))
  100. try:
  101. await with_timeout(motor_completion.wait(), MOTOR_COMPLETION_TIMEOUT_MS, "ms")
  102. except SimTimeoutError as exc:
  103. raise AssertionError(
  104. "timeout stage=motor_completion "
  105. f"timeout_ms={MOTOR_COMPLETION_TIMEOUT_MS} "
  106. f"observed_x={observed['x']} observed_y={observed['y']}"
  107. ) from exc
  108. assert observed["x"] == MOTOR_STEPS
  109. assert observed["y"] == MOTOR_STEPS
  110. assert observed["overlap"] is True
  111. assert int(dut.motor_en_n.value) == 0
  112. await with_timeout(
  113. FallingEdge(dut.x_step),
  114. MOTOR_COMPLETION_TIMEOUT_MS,
  115. "ms",
  116. )
  117. await RisingEdge(dut.u_dut.frame_accept_enable)
  118. await clocks(dut, 4)
  119. await send_frame(dut, frame(GET_TEMPERATURE, b""))
  120. response = bytearray()
  121. for byte_index in range(33):
  122. response.append(
  123. await wait_for_stage(
  124. receive_uart_byte(dut),
  125. TEMPERATURE_BYTE_TIMEOUT_MS,
  126. "temperature_response",
  127. byte_index,
  128. )
  129. )
  130. response = bytes(response)
  131. assert response[:4] == bytes((0xA5, 0x5A, TEMPERATURE_DATA, 27))
  132. assert len(response) == 33
  133. assert response[-2:] == crc16(response[2:-2]).to_bytes(2, "little")
  134. assert set(response[4:31]) == {0xFF}
  135. finally:
  136. stop_background_task(observer_task)
  137. try:
  138. simulator.stop_simulator()
  139. except Exception:
  140. pass