test_prod2u_door_temp_uart_e2e.py 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171
  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. from cocotb.clock import Clock
  7. from cocotb.triggers import Event, NextTimeStep, ReadOnly, ReadWrite, RisingEdge, SimTimeoutError, 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. for _ in range(count):
  27. await RisingEdge(dut.sys_clk)
  28. async def send_uart_byte(dut, value: int) -> None:
  29. await ReadWrite()
  30. dut.host_uart_rx.value = 0
  31. await clocks(dut, CLKS_PER_BIT)
  32. for bit in range(8):
  33. dut.host_uart_rx.value = (value >> bit) & 1
  34. await clocks(dut, CLKS_PER_BIT)
  35. dut.host_uart_rx.value = 1
  36. await clocks(dut, CLKS_PER_BIT)
  37. async def send_frame(dut, packet: bytes) -> None:
  38. await NextTimeStep()
  39. for value in packet:
  40. await send_uart_byte(dut, value)
  41. async def observe_motor_steps(dut, observed: dict[str, int | bool], completion: Event) -> None:
  42. previous_x = 0
  43. previous_y = 0
  44. while True:
  45. await RisingEdge(dut.sys_clk)
  46. await ReadOnly()
  47. if not dut.x_step.value.is_resolvable or not dut.y_step.value.is_resolvable:
  48. previous_x = 0
  49. previous_y = 0
  50. continue
  51. current_x = int(dut.x_step.value)
  52. current_y = int(dut.y_step.value)
  53. if current_x and not previous_x:
  54. observed["x"] = int(observed["x"]) + 1
  55. if current_y and not previous_y:
  56. observed["y"] = int(observed["y"]) + 1
  57. if current_x and current_y:
  58. observed["overlap"] = True
  59. previous_x = current_x
  60. previous_y = current_y
  61. if observed["x"] == MOTOR_STEPS and observed["y"] == MOTOR_STEPS:
  62. completion.set()
  63. return
  64. async def receive_uart_byte(dut) -> int:
  65. while int(dut.host_uart_tx.value) != 0:
  66. await RisingEdge(dut.sys_clk)
  67. await clocks(dut, CLKS_PER_BIT + CLKS_PER_BIT // 2)
  68. value = 0
  69. for bit in range(8):
  70. value |= int(dut.host_uart_tx.value) << bit
  71. await clocks(dut, CLKS_PER_BIT)
  72. assert int(dut.host_uart_tx.value) == 1
  73. return value
  74. async def wait_for_stage(awaitable, timeout_ms: int, stage: str, byte_index: int = -1):
  75. """Apply a bounded wait with a stable, machine-searchable failure message."""
  76. try:
  77. return await with_timeout(awaitable, timeout_ms, "ms")
  78. except SimTimeoutError as exc:
  79. suffix = "" if byte_index < 0 else f" byte_index={byte_index}"
  80. raise AssertionError(
  81. f"timeout stage={stage} timeout_ms={timeout_ms}{suffix}"
  82. ) from exc
  83. def stop_background_task(task) -> None:
  84. if task is None:
  85. return
  86. if hasattr(task, "kill"):
  87. task.kill()
  88. elif hasattr(task, "cancel"):
  89. task.cancel()
  90. @cocotb.test()
  91. async def test_set_all_get_temperature_over_real_uart(dut):
  92. clock_task = None
  93. observer_task = None
  94. observed = {"x": 0, "y": 0, "overlap": False}
  95. motor_completion = Event()
  96. try:
  97. clock_task = cocotb.start_soon(Clock(dut.sys_clk, 40, units="ns").start())
  98. observer_task = cocotb.start_soon(
  99. observe_motor_steps(dut, observed, motor_completion)
  100. )
  101. dut.host_uart_rx.value = 1
  102. dut.x_limit_raw.value = 0
  103. dut.y_limit_raw.value = 0
  104. dut.temp_scl.value = 1
  105. dut.temp_sda.value = 1
  106. await clocks(dut, 1100)
  107. payload = bytes(range(8)) + bytes((10, 20, 30, 40, 1, 2))
  108. await send_frame(dut, frame(SET_ALL, payload))
  109. try:
  110. await with_timeout(motor_completion.wait(), MOTOR_COMPLETION_TIMEOUT_MS, "ms")
  111. except SimTimeoutError as exc:
  112. raise AssertionError(
  113. "timeout stage=motor_completion "
  114. f"timeout_ms={MOTOR_COMPLETION_TIMEOUT_MS} "
  115. f"observed_x={observed['x']} observed_y={observed['y']}"
  116. ) from exc
  117. assert observed["x"] == MOTOR_STEPS
  118. assert observed["y"] == MOTOR_STEPS
  119. assert observed["overlap"] is True
  120. assert int(dut.motor_en_n.value) == 0
  121. while True:
  122. await RisingEdge(dut.sys_clk)
  123. await ReadOnly()
  124. if int(dut.x_step.value) == 0 and int(dut.y_step.value) == 0:
  125. break
  126. await clocks(dut, 4)
  127. await send_frame(dut, frame(GET_TEMPERATURE, b""))
  128. response = bytearray()
  129. for byte_index in range(33):
  130. response.append(
  131. await wait_for_stage(
  132. receive_uart_byte(dut),
  133. TEMPERATURE_BYTE_TIMEOUT_MS,
  134. "temperature_response",
  135. byte_index,
  136. )
  137. )
  138. response = bytes(response)
  139. assert response[:4] == bytes((0xA5, 0x5A, TEMPERATURE_DATA, 27))
  140. assert len(response) == 33
  141. assert response[-2:] == crc16(response[2:-2]).to_bytes(2, "little")
  142. assert set(response[4:31]) == {0xFF}
  143. finally:
  144. stop_background_task(observer_task)
  145. stop_background_task(clock_task)