| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081 |
- """Real UART-bit e2e scenario for the refactored top.
- This test is intentionally kept independent of the Python protocol model at the
- wire boundary: bytes are serialized as 8N1 bits at 217 system clocks/bit.
- """
- import cocotb
- from cocotb.clock import Clock
- from cocotb.triggers import RisingEdge, Timer
- CLKS_PER_BIT = 217
- SET_ALL = 0x01
- GET_TEMPERATURE = 0x02
- TEMPERATURE_DATA = 0x82
- def crc16(data: bytes) -> int:
- crc = 0xFFFF
- for value in data:
- crc ^= value << 8
- for _ in range(8):
- crc = ((crc << 1) ^ 0x1021) & 0xFFFF if crc & 0x8000 else (crc << 1) & 0xFFFF
- return crc
- def frame(kind: int, payload: bytes) -> bytes:
- body = bytes((kind, len(payload))) + payload
- return b"\xA5\x5A" + body + crc16(body).to_bytes(2, "little")
- async def clocks(dut, count: int) -> None:
- for _ in range(count):
- await RisingEdge(dut.sys_clk)
- async def send_uart_byte(dut, value: int) -> None:
- dut.host_uart_rx.value = 0
- await clocks(dut, CLKS_PER_BIT)
- for bit in range(8):
- dut.host_uart_rx.value = (value >> bit) & 1
- await clocks(dut, CLKS_PER_BIT)
- dut.host_uart_rx.value = 1
- await clocks(dut, CLKS_PER_BIT)
- async def send_frame(dut, packet: bytes) -> None:
- for value in packet:
- await send_uart_byte(dut, value)
- async def receive_uart_byte(dut) -> int:
- while int(dut.host_uart_tx.value) != 0:
- await RisingEdge(dut.sys_clk)
- await clocks(dut, CLKS_PER_BIT + CLKS_PER_BIT // 2)
- value = 0
- for bit in range(8):
- value |= int(dut.host_uart_tx.value) << bit
- await clocks(dut, CLKS_PER_BIT)
- await clocks(dut, CLKS_PER_BIT)
- return value
- @cocotb.test()
- async def test_set_all_get_temperature_over_real_uart(dut):
- cocotb.start_soon(Clock(dut.sys_clk, 40, units="ns").start())
- dut.host_uart_rx.value = 1
- dut.temp_scl.value = 1
- dut.temp_sda.value = 1
- await clocks(dut, 1100)
- payload = bytes(range(24)) + bytes((0x80, 0x90, 0xA0, 0xB0, 0, 1))
- await send_frame(dut, frame(SET_ALL, payload))
- await Timer(1100, units="ms")
- await send_frame(dut, frame(GET_TEMPERATURE, b""))
- response = bytes([await receive_uart_byte(dut) for _ in range(33)])
- assert response[:4] == bytes((0xA5, 0x5A, TEMPERATURE_DATA, 27))
- assert len(response) == 33
- assert response[-2:] == crc16(response[2:-2]).to_bytes(2, "little")
- assert set(response[4:31]) == {0xFF}
|