`timescale 1ns/1ps module prod2u_p4_normal_v3_tx_tb; reg clk = 1'b0; reg rst_n = 1'b0; reg frame_valid = 1'b0; wire frame_ready; reg [7:0] frame_type = 8'h06; reg [7:0] frame_payload_len = 8'd8; reg [143:0] frame_payload = 144'h0800_1234_1602_2a01; wire tx_valid; reg tx_ready = 1'b1; wire [7:0] tx_data; reg [7:0] captured [0:40]; reg [15:0] expected_crc; integer count; integer index; prod2u_p4_normal_v3_tx dut ( .clk(clk), .rst_n(rst_n), .frame_valid(frame_valid), .frame_ready(frame_ready), .frame_type(frame_type), .frame_payload_len(frame_payload_len), .frame_payload(frame_payload), .tx_valid(tx_valid), .tx_ready(tx_ready), .tx_data(tx_data) ); always #5 clk = ~clk; always @(posedge clk) begin if (frame_ready) frame_valid <= 1'b0; end function [15:0] crc16_byte; input [15:0] crc_in; input [7:0] data; reg [15:0] value; integer bit_index; begin value = crc_in ^ {data, 8'h00}; for (bit_index = 0; bit_index < 8; bit_index = bit_index + 1) begin if (value[15]) value = (value << 1) ^ 16'h1021; else value = value << 1; end crc16_byte = value; end endfunction task capture_and_check; input [7:0] expected_type; input [7:0] expected_length; input [143:0] expected_payload; begin count = 0; while (count < 16 + expected_length) begin @(posedge clk); if (tx_valid && tx_ready) begin captured[count] = tx_data; count = count + 1; end end if (captured[0] !== 8'ha5 || captured[1] !== 8'h5a || captured[2] !== 8'h02 || captured[3] !== 8'h04 || captured[4] !== expected_type || captured[13] !== expected_length) $fatal; for (index = 5; index <= 12; index = index + 1) begin if (captured[index] !== 8'd0) $fatal; end for (index = 0; index < expected_length; index = index + 1) begin if (captured[14 + index] !== expected_payload[index * 8 +: 8]) $fatal; end expected_crc = 16'hffff; for (index = 2; index < 14 + expected_length; index = index + 1) begin expected_crc = crc16_byte(expected_crc, captured[index]); end if (captured[14 + expected_length] !== expected_crc[7:0] || captured[15 + expected_length] !== expected_crc[15:8]) $fatal; @(posedge clk); #1; @(negedge clk); end endtask task send_frame; input [7:0] next_type; input [7:0] next_length; input [143:0] next_payload; begin frame_type = next_type; frame_payload_len = next_length; frame_payload = next_payload; frame_valid = 1'b1; capture_and_check(next_type, next_length, next_payload); if (frame_valid) $fatal; end endtask initial begin repeat (4) @(negedge clk); rst_n = 1'b1; repeat (8) @(posedge clk); #1; if (tx_valid || frame_ready) $fatal(1, "TX emitted an unsolicited frame"); send_frame(8'h06, 8'd8, 144'h0800_1234_1602_2a01); send_frame(8'h12, 8'd10, 144'h03_6400_64ff_0703_0003); $display("PASS: prod2u_p4_normal_v3_tx_tb"); $finish; end endmodule