test_prod2u_door_temp_uart_e2e.py 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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 RisingEdge, Timer
  8. CLKS_PER_BIT = 217
  9. SET_ALL = 0x01
  10. GET_TEMPERATURE = 0x02
  11. TEMPERATURE_DATA = 0x82
  12. def crc16(data: bytes) -> int:
  13. crc = 0xFFFF
  14. for value in data:
  15. crc ^= value << 8
  16. for _ in range(8):
  17. crc = ((crc << 1) ^ 0x1021) & 0xFFFF if crc & 0x8000 else (crc << 1) & 0xFFFF
  18. return crc
  19. def frame(kind: int, payload: bytes) -> bytes:
  20. body = bytes((kind, len(payload))) + payload
  21. return b"\xA5\x5A" + body + crc16(body).to_bytes(2, "little")
  22. async def clocks(dut, count: int) -> None:
  23. for _ in range(count):
  24. await RisingEdge(dut.sys_clk)
  25. async def send_uart_byte(dut, value: int) -> None:
  26. dut.host_uart_rx.value = 0
  27. await clocks(dut, CLKS_PER_BIT)
  28. for bit in range(8):
  29. dut.host_uart_rx.value = (value >> bit) & 1
  30. await clocks(dut, CLKS_PER_BIT)
  31. dut.host_uart_rx.value = 1
  32. await clocks(dut, CLKS_PER_BIT)
  33. async def send_frame(dut, packet: bytes) -> None:
  34. for value in packet:
  35. await send_uart_byte(dut, value)
  36. async def receive_uart_byte(dut) -> int:
  37. while int(dut.host_uart_tx.value) != 0:
  38. await RisingEdge(dut.sys_clk)
  39. await clocks(dut, CLKS_PER_BIT + CLKS_PER_BIT // 2)
  40. value = 0
  41. for bit in range(8):
  42. value |= int(dut.host_uart_tx.value) << bit
  43. await clocks(dut, CLKS_PER_BIT)
  44. await clocks(dut, CLKS_PER_BIT)
  45. return value
  46. @cocotb.test()
  47. async def test_set_all_get_temperature_over_real_uart(dut):
  48. cocotb.start_soon(Clock(dut.sys_clk, 40, units="ns").start())
  49. dut.host_uart_rx.value = 1
  50. dut.temp_scl.value = 1
  51. dut.temp_sda.value = 1
  52. await clocks(dut, 1100)
  53. payload = bytes(range(24)) + bytes((0x80, 0x90, 0xA0, 0xB0, 0, 1))
  54. await send_frame(dut, frame(SET_ALL, payload))
  55. await Timer(1100, units="ms")
  56. await send_frame(dut, frame(GET_TEMPERATURE, b""))
  57. response = bytes([await receive_uart_byte(dut) for _ in range(33)])
  58. assert response[:4] == bytes((0xA5, 0x5A, TEMPERATURE_DATA, 27))
  59. assert len(response) == 33
  60. assert response[-2:] == crc16(response[2:-2]).to_bytes(2, "little")
  61. assert set(response[4:31]) == {0xFF}