| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239 |
- """Randomized full-UART Host framing and resynchronization coverage."""
- from __future__ import annotations
- from dataclasses import dataclass
- import warnings
- import cocotb
- from cocotb.triggers import RisingEdge, Timer, with_timeout
- from hypothesis import HealthCheck, given, settings, strategies as st
- from hypothesis.errors import HypothesisSideeffectWarning
- from thermal_6400_uart import (
- CLOCK_NS,
- HOST_CLKS_PER_BIT,
- SET_TARGET,
- SET_TARGET_ACK,
- clock_cycles,
- crc16,
- encode_frame,
- receive_frame,
- send_uart,
- wait_for,
- )
- @dataclass(frozen=True)
- class FrameCase:
- frame_type: int
- declared_length: int
- payload: bytes
- good_crc: bool
- @property
- def accepted_target(self) -> int | None:
- if not self.good_crc or self.frame_type != SET_TARGET or self.declared_length != 1:
- return None
- target = self.payload[0]
- return target if target == 0 or 20 <= target <= 70 else None
- def encode(self) -> bytes:
- body = bytes((self.frame_type, self.declared_length)) + self.payload
- checksum = crc16(body)
- if not self.good_crc:
- checksum ^= 0x0001
- return b"\xA5\x5A" + body + checksum.to_bytes(2, "little")
- @st.composite
- def frame_cases(draw) -> FrameCase:
- frame_type = draw(st.sampled_from((0x00, 0x01, 0x04, 0x7F, 0x80, 0x81, 0xFF)))
- declared_length = draw(st.integers(min_value=0, max_value=255))
- if declared_length <= 33:
- payload = draw(st.binary(min_size=declared_length, max_size=declared_length))
- else:
- # RTL rejects the oversized declaration before consuming payload. A
- # bounded tail exercises recovery without letting an embedded header
- # become a separate, accidental test case.
- tail = draw(st.binary(min_size=0, max_size=12))
- payload = tail.replace(b"\xA5", b"\xA4")
- return FrameCase(frame_type, declared_length, payload, draw(st.booleans()))
- def generated_cases() -> list[FrameCase]:
- values: list[FrameCase] = []
- @settings(
- max_examples=96,
- derandomize=True,
- database=None,
- deadline=None,
- suppress_health_check=(HealthCheck.too_slow,),
- )
- @given(frame_cases())
- def collect(value: FrameCase) -> None:
- values.append(value)
- # Cocotb imports tests through its pytest plugin, then invokes this
- # collector deliberately from the running coroutine. Hypothesis warns
- # about any strategy evaluation in plugin-owned code even though this is
- # the test body and the database/storage are both isolated.
- with warnings.catch_warnings():
- warnings.simplefilter("ignore", HypothesisSideeffectWarning)
- collect()
- return values
- async def send_uart_with_period(signal, data: bytes, clocks_per_bit: int) -> None:
- for value in data:
- signal.value = 0
- await Timer(clocks_per_bit * CLOCK_NS, units="ns")
- for bit in range(8):
- signal.value = (value >> bit) & 1
- await Timer(clocks_per_bit * CLOCK_NS, units="ns")
- signal.value = 1
- await Timer(clocks_per_bit * CLOCK_NS, units="ns")
- async def send_uart_jittered(signal, data: bytes) -> None:
- periods = (27, 26, 28, 27, 28, 26, 27, 26, 28, 27)
- for value in data:
- bits = (0, *((value >> bit) & 1 for bit in range(8)), 1)
- for level, clocks in zip(bits, periods, strict=True):
- signal.value = level
- await Timer(clocks * CLOCK_NS, units="ns")
- async def wait_unlocked(dut) -> None:
- await wait_for(
- dut,
- lambda: int(dut.host_locked_mon.value) == 0,
- cycles=1800,
- label="Host selector unlock",
- )
- async def target_transaction(dut, target: int, sender=send_uart) -> None:
- response = cocotb.start_soon(receive_frame(dut.host_rs232_tx))
- frame = encode_frame(SET_TARGET, bytes((target,)))
- if sender is send_uart:
- await sender(dut.host_rs232_rx, frame, HOST_CLKS_PER_BIT)
- else:
- await sender(dut.host_rs232_rx, frame)
- kind, payload = await with_timeout(response, 20, "ms")
- assert (kind, payload) == (SET_TARGET_ACK, b"")
- await Timer(HOST_CLKS_PER_BIT * CLOCK_NS * 2, units="ns")
- await wait_unlocked(dut)
- assert int(dut.current_target_mon.value) == target
- @cocotb.test()
- async def test_host_random_frames_timeout_resync_and_port_lock(dut):
- dut.host_rs232_rx.value = 1
- dut.host_ttl_rx.value = 1
- dut.bmc_rs232_rx.value = 1
- dut.tick_1s_test.value = 0
- await with_timeout(RisingEdge(dut.rst_n_mon), 1, "ms")
- await clock_cycles(dut, 8)
- # Hypothesis supplies arbitrary declared lengths, payloads, CRC validity,
- # legal targets, illegal targets, and unknown types. Every invalid case
- # is a silent drop and must leave both the target and response counters
- # unchanged; valid target frames commit exactly once and ACK exactly once.
- for case in generated_cases():
- commits_before = int(dut.target_commit_count_mon.value)
- responses_before = int(dut.host_response_count_mon.value)
- target_before = int(dut.current_target_mon.value)
- accepted = case.accepted_target
- if accepted is not None:
- response = cocotb.start_soon(receive_frame(dut.host_rs232_tx))
- await send_uart(dut.host_rs232_rx, case.encode(), HOST_CLKS_PER_BIT)
- assert await with_timeout(response, 20, "ms") == (SET_TARGET_ACK, b"")
- await Timer(HOST_CLKS_PER_BIT * CLOCK_NS * 2, units="ns")
- else:
- await send_uart(dut.host_rs232_rx, case.encode(), HOST_CLKS_PER_BIT)
- await wait_unlocked(dut)
- if accepted is None:
- assert int(dut.target_commit_count_mon.value) == commits_before
- assert int(dut.host_response_count_mon.value) == responses_before
- assert int(dut.current_target_mon.value) == target_before
- else:
- assert int(dut.target_commit_count_mon.value) == commits_before + 1
- assert int(dut.host_response_count_mon.value) == responses_before + 1
- assert int(dut.current_target_mon.value) == accepted
- assert int(dut.host_rs232_tx.value) == 1
- assert int(dut.host_ttl_tx.value) == 1
- # Noise and overlapping A5 candidates must resynchronize to the next full
- # header without resetting the UART or parser.
- response = cocotb.start_soon(receive_frame(dut.host_rs232_tx))
- noisy = b"\x00\xFF\xA5\xA5\x00\xA5" + encode_frame(SET_TARGET, b"\x3E")
- await send_uart(dut.host_rs232_rx, noisy, HOST_CLKS_PER_BIT)
- assert await with_timeout(response, 20, "ms") == (SET_TARGET_ACK, b"")
- await Timer(HOST_CLKS_PER_BIT * CLOCK_NS * 2, units="ns")
- await wait_unlocked(dut)
- assert int(dut.current_target_mon.value) == 62
- # A half-frame is discarded after the accelerated test timeout; the next
- # valid frame must not inherit its type, length, payload, or CRC state.
- commits_before = int(dut.target_commit_count_mon.value)
- responses_before = int(dut.host_response_count_mon.value)
- await send_uart(dut.host_rs232_rx, b"\xA5\x5A\x01\x01", HOST_CLKS_PER_BIT)
- await clock_cycles(dut, 1200)
- await wait_unlocked(dut)
- assert int(dut.target_commit_count_mon.value) == commits_before
- assert int(dut.host_response_count_mon.value) == responses_before
- await target_transaction(dut, 61)
- # There is no command queue: a second complete frame arriving while the
- # first physical ACK is active is dropped, and a later retransmission is
- # accepted after the response boundary retires.
- commits_before = int(dut.target_commit_count_mon.value)
- responses_before = int(dut.host_response_count_mon.value)
- response = cocotb.start_soon(receive_frame(dut.host_rs232_tx))
- await send_uart(dut.host_rs232_rx, encode_frame(SET_TARGET, b"\x14"), HOST_CLKS_PER_BIT)
- await send_uart(dut.host_rs232_rx, encode_frame(SET_TARGET, b"\x46"), HOST_CLKS_PER_BIT)
- assert await with_timeout(response, 20, "ms") == (SET_TARGET_ACK, b"")
- await Timer(HOST_CLKS_PER_BIT * CLOCK_NS * 2, units="ns")
- await wait_unlocked(dut)
- assert int(dut.target_commit_count_mon.value) == commits_before + 1
- assert int(dut.host_response_count_mon.value) == responses_before + 1
- assert int(dut.current_target_mon.value) == 20
- await target_transaction(dut, 70)
- # Simultaneous start bits deterministically select RS-232 for the entire
- # request/response lock. TTL traffic cannot splice payload or steal TX.
- commits_before = int(dut.target_commit_count_mon.value)
- response = cocotb.start_soon(receive_frame(dut.host_rs232_tx))
- rs232 = cocotb.start_soon(
- send_uart(dut.host_rs232_rx, encode_frame(SET_TARGET, b"\x3C"), HOST_CLKS_PER_BIT)
- )
- ttl = cocotb.start_soon(
- send_uart(dut.host_ttl_rx, encode_frame(SET_TARGET, b"\x46"), HOST_CLKS_PER_BIT)
- )
- await rs232
- await ttl
- assert await with_timeout(response, 20, "ms") == (SET_TARGET_ACK, b"")
- assert int(dut.host_ttl_tx.value) == 1
- await Timer(HOST_CLKS_PER_BIT * CLOCK_NS * 2, units="ns")
- await wait_unlocked(dut)
- assert int(dut.target_commit_count_mon.value) == commits_before + 1
- assert int(dut.current_target_mon.value) == 60
- # Integrate the raw UART tolerance proof with a legal frame: fixed -1/+1
- # clock baud error and balanced per-bit jitter must preserve framing/CRC.
- await target_transaction(dut, 64, lambda signal, data: send_uart_with_period(signal, data, 26))
- await target_transaction(dut, 63, lambda signal, data: send_uart_with_period(signal, data, 28))
- await target_transaction(dut, 65, send_uart_jittered)
- # A declared 255-byte unknown frame plus a long zero tail is discarded
- # without a response, state mutation, or loss of the next valid command.
- commits_before = int(dut.target_commit_count_mon.value)
- responses_before = int(dut.host_response_count_mon.value)
- long_invalid = b"\xA5\x5A\x7F\xFF" + bytes(260)
- await send_uart(dut.host_rs232_rx, long_invalid, HOST_CLKS_PER_BIT)
- await wait_unlocked(dut)
- assert int(dut.target_commit_count_mon.value) == commits_before
- assert int(dut.host_response_count_mon.value) == responses_before
- await target_transaction(dut, 66)
|