library ieee;
use ieee.std_logic_1164.all;
use ieee.numeric_std.all;

library osvvm; -- Utility Library
context osvvm.OsvvmContext;

use work.rtps_package.all;
use work.user_config.all;
use work.rtps_config_package.all;
use work.rtps_test_package.all;

-- This testbench tests the handling of remote Liveliness Assertions
-- The testbench matches 2 remote Participants, P0 and P1. P0 sends an automatic liveliness assertion, while P1 sends a manual liveliness assertion.
-- P0 also sends a manual liveliness assertion with extra Bytes.

entity L0_rtps_builtin_endpoint_test7 is
end entity;

architecture testbench of L0_rtps_builtin_endpoint_test7 is
    
    -- *TYPE DECLARATION*
    type TEST_STAGE_TYPE is (IDLE, BUSY);
    
    -- *SIGNAL DECLARATION*
    signal clk, in_empty, rd_sig, last_word_in, last_word_out: std_logic := '0';
    signal reset : std_logic := '1';
    signal endpoint_wr, endpoint_full   : std_logic_vector(0 to NUM_ENDPOINTS-1) := (others => '0');
    signal data_in, data_out : std_logic_vector(WORD_WIDTH-1 downto 0) := (others => '0');
    signal stim_stage : TEST_STAGE_TYPE := IDLE;
    shared variable stimulus, reference : TEST_PACKET_TYPE := EMPTY_TEST_PACKET;
    signal packet_sent : std_logic := '0';
    signal cnt_stim : natural := 0;
    signal start : std_logic := '0';
    shared variable SB_out : work.ScoreBoardPkg_builtin_endpoint.ScoreBoardPType;
    signal stim_done, check_done, mem_check : std_logic := '0';
    
    -- *FUNCTION DECLARATION*
    procedure wait_on_complete is
    begin
        wait until rising_edge(packet_sent);
    end procedure;
    
    function gen_sn(input : natural) return SEQUENCENUMBER_TYPE is
        variable ret : SEQUENCENUMBER_TYPE;
    begin
        ret(0)  := (others => '0');
        ret(1)  := unsigned(int(input, WORD_WIDTH));
        return ret;
    end function;
    
begin
    
    -- Unit Under Test
    uut : entity work.rtps_builtin_endpoint(arch)
        generic map (
            MAX_REMOTE_PARTICIPANTS => 2
        )
        port map (
            clk             => clk,
            reset           => reset,
            empty           => in_empty or packet_sent,
            rd              => rd_sig,
            data_in         => data_in,
            data_out        => data_out,
            last_word_in    => last_word_in,
            time            => TIME_ZERO,
            endpoint_full   => endpoint_full,
            endpoint_wr     => endpoint_wr,
            rtps_wr         => open,
            rtps_full       => '0',
            last_word_out   => last_word_out,
            alive           => (others => '0')
        );
    
    stimulus_prc : process
        variable sub                : RTPS_SUBMESSAGE_TYPE := DEFAULT_RTPS_SUBMESSAGE;
        variable RV                 : RandomPType;
        variable p0, p1, participant: PARTICIPANT_DATA_TYPE := DEFAULT_PARTICIPANT_DATA;
        variable wr_sig             : std_logic_vector(0 to NUM_ENDPOINTS-1) := (others => '0');
        variable rand_data          : TEST_PACKET_TYPE := EMPTY_TEST_PACKET;
        
        -- Wrapper to use procedure as function
        impure function gen_rand_loc_2 return LOCATOR_TYPE is
            variable ret : LOCATOR_TYPE := EMPTY_LOCATOR;
        begin
            gen_rand_loc(RV, ret);
            return ret;
        end function;
        
        impure function gen_rand_guid_prefix return GUIDPREFIX_TYPE is
            variable ret : GUIDPREFIX_TYPE;
        begin
            ret := (0 => RV.RandSlv(WORD_WIDTH), 1 => RV.RandSlv(WORD_WIDTH), 2 => RV.RandSlv(WORD_WIDTH));
            return ret;
        end function;
        
        procedure push_reference is
        begin
            for i in 0 to reference.length-1 loop
                SB_out.Push(wr_sig & reference.last(i) & reference.data(i));
            end loop;
        end procedure;
        
        procedure start_test is
        begin
            start   <= '1';
            wait until rising_edge(clk);
            start   <= '0';
            wait until rising_edge(clk);
        end procedure;
    begin
        
        assert (TEST_STRING = "TEST_CONFIG_1") report "user_config incompatible with testbench." severity FAILURE;
        
        SetAlertLogName("rtps_builtin_endpoint - Level 0 - Remote Liveliness Assertion Handling");
        SetAlertEnable(FAILURE, TRUE);
        SetAlertEnable(ERROR, TRUE);
        SetAlertEnable(WARNING, TRUE);
        SetLogEnable(DEBUG, FALSE);
        SetLogEnable(PASSED, FALSE);
        SetLogEnable(INFO, TRUE);
        RV.InitSeed(RV'instance_name);
        
        -- Participant RTPS Submessage
        sub                                    := DEFAULT_RTPS_SUBMESSAGE;
        sub.submessageID                       := SID_DATA;
        sub.writerId                           := ENTITYID_SPDP_BUILTIN_PARTICIPANT_ANNOUNCER;
        sub.readerId                           := ENTITYID_SPDP_BUILTIN_PARTICIPANT_DETECTOR;
        sub.flags(SUBMESSAGE_DATA_FLAG_POS)    := '1';
        
        -- Participant 0
        p0.guidPrefix                   := gen_rand_guid_prefix;
        p0.nr                           := 0;
        p0.defaultUnicastLocatorList    := (numLocators => int(1,CDR_LONG_WIDTH), locator => (0 => gen_rand_loc_2, others => EMPTY_LOCATOR));
        p0.availableBuiltinEndpoints(DISC_BUILTIN_ENDPOINT_SUBSCRIPTIONS_DETECTOR) := '1';
        p0.availableBuiltinEndpoints(DISC_BUILTIN_ENDPOINT_SUBSCRIPTIONS_ANNOUNCER):= '1';
        p0.availableBuiltinEndpoints(DISC_BUILTIN_ENDPOINT_PUBLICATIONS_DETECTOR)  := '1';
        p0.availableBuiltinEndpoints(DISC_BUILTIN_ENDPOINT_PUBLICATIONS_ANNOUNCER) := '1';
        
        -- Participant 1
        p1.guidPrefix                   := gen_rand_guid_prefix;
        p1.nr                           := 1;
        p1.defaultUnicastLocatorList    := (numLocators => int(1,CDR_LONG_WIDTH), locator => (0 => gen_rand_loc_2, others => EMPTY_LOCATOR));
        p1.availableBuiltinEndpoints(DISC_BUILTIN_ENDPOINT_SUBSCRIPTIONS_DETECTOR) := '1';
        p1.availableBuiltinEndpoints(DISC_BUILTIN_ENDPOINT_SUBSCRIPTIONS_ANNOUNCER):= '1';
        p1.availableBuiltinEndpoints(DISC_BUILTIN_ENDPOINT_PUBLICATIONS_DETECTOR)  := '1';
        p1.availableBuiltinEndpoints(DISC_BUILTIN_ENDPOINT_PUBLICATIONS_ANNOUNCER) := '1';
        
        for i in 0 to RV.RandInt(1,10) loop
            rand_data.data(i)   := RV.RandSlv(WORD_WIDTH);
            rand_data.length    := rand_data.length + 1;
        end loop;
        
        Log("Initiating Test", INFO);
        stim_done   <= '0';
        start       <= '0';
        reset       <= '1';
        wait until rising_edge(clk);
        wait until rising_edge(clk);
        reset   <= '0';
        
        -- *PARTICIPANT*
        Log("Current Time: 0s", INFO);
        Log("Match Participant 0", INFO);
        sub                 := DEFAULT_RTPS_SUBMESSAGE;
        sub.submessageID    := SID_DATA;
        sub.writerId        := ENTITYID_SPDP_BUILTIN_PARTICIPANT_ANNOUNCER;
        sub.readerId        := ENTITYID_SPDP_BUILTIN_PARTICIPANT_DETECTOR;
        sub.writerSN        := gen_sn(1);
        sub.flags(SUBMESSAGE_DATA_FLAG_POS)    := '1';
        participant         := p0;
        gen_participant_data(participant, sub.data);
        gen_sentinel(sub.data);
        gen_rtps_handler_out(sub, participant, stimulus);
        start_test;
        wait_on_complete;
        stimulus    := EMPTY_TEST_PACKET;
        reference   := EMPTY_TEST_PACKET;
        
        Log("Match Participant 1", INFO);
        sub                 := DEFAULT_RTPS_SUBMESSAGE;
        sub.submessageID    := SID_DATA;
        sub.writerId        := ENTITYID_SPDP_BUILTIN_PARTICIPANT_ANNOUNCER;
        sub.readerId        := ENTITYID_SPDP_BUILTIN_PARTICIPANT_DETECTOR;
        sub.writerSN        := gen_sn(1);
        sub.flags(SUBMESSAGE_DATA_FLAG_POS)    := '1';
        participant         := p1;
        gen_participant_data(participant, sub.data);
        gen_sentinel(sub.data);
        gen_rtps_handler_out(sub, participant, stimulus);
        start_test;
        wait_on_complete;
        stimulus    := EMPTY_TEST_PACKET;
        reference   := EMPTY_TEST_PACKET;
        
        Log("Participant 0 Automatic Liveliness Assertion", INFO);
        sub                 := DEFAULT_RTPS_SUBMESSAGE;
        sub.submessageID    := SID_DATA;
        sub.writerId        := ENTITYID_P2P_BUILTIN_PARTICIPANT_MESSAGE_WRITER;
        sub.readerId        := ENTITYID_P2P_BUILTIN_PARTICIPANT_MESSAGE_READER;
        sub.writerSN        := gen_sn(1);
        sub.flags(SUBMESSAGE_DATA_FLAG_POS) := '1';
        participant         := p0;
        gen_liveliness_assertion(p0, FALSE, sub.data);
        gen_rtps_handler_out(sub, participant, stimulus);
        gen_liveliness_update_frame(p0, reference);
        wr_sig := AUTOMATIC_LIVELINESS_READERS;
        push_reference;
        start_test;
        wait_on_complete;
        stimulus    := EMPTY_TEST_PACKET;
        reference   := EMPTY_TEST_PACKET;
        
        Log("Participant 1 Manual Liveliness Assertion", INFO);
        sub                 := DEFAULT_RTPS_SUBMESSAGE;
        sub.submessageID    := SID_DATA;
        sub.writerId        := ENTITYID_P2P_BUILTIN_PARTICIPANT_MESSAGE_WRITER;
        sub.readerId        := ENTITYID_P2P_BUILTIN_PARTICIPANT_MESSAGE_READER;
        sub.writerSN        := gen_sn(1);
        sub.flags(SUBMESSAGE_DATA_FLAG_POS) := '1';
        participant         := p1;
        gen_liveliness_assertion(p1, TRUE, sub.data);
        gen_rtps_handler_out(sub, participant, stimulus);
        gen_liveliness_update_frame(p1, reference);
        wr_sig := MANUAL_BY_PARTICIPANT_LIVELINESS_READERS;
        push_reference;
        start_test;
        wait_on_complete;
        stimulus    := EMPTY_TEST_PACKET;
        reference   := EMPTY_TEST_PACKET;
        
        Log("Participant 0 Manual Liveliness Assertion [+DATA Bytes]", INFO);
        sub                 := DEFAULT_RTPS_SUBMESSAGE;
        sub.submessageID    := SID_DATA;
        sub.writerId        := ENTITYID_P2P_BUILTIN_PARTICIPANT_MESSAGE_WRITER;
        sub.readerId        := ENTITYID_P2P_BUILTIN_PARTICIPANT_MESSAGE_READER;
        sub.writerSN        := gen_sn(2);
        sub.flags(SUBMESSAGE_DATA_FLAG_POS) := '1';
        participant         := p0;
        gen_liveliness_assertion(p0, TRUE, rand_data, sub.data);
        gen_rtps_handler_out(sub, participant, stimulus);
        gen_liveliness_update_frame(p0, reference);
        wr_sig := MANUAL_BY_PARTICIPANT_LIVELINESS_READERS;
        push_reference;
        start_test;
        wait_on_complete;
        stimulus    := EMPTY_TEST_PACKET;
        reference   := EMPTY_TEST_PACKET;
        
        TranscriptOpen(RESULTS_FILE, APPEND_MODE);
        SetTranscriptMirror;
        stim_done   <= '1';
        wait until check_done = '1';
        AlertIf(not SB_out.empty, "Incomplete test run");
        ReportAlerts;
        TranscriptClose;
        std.env.stop;
        wait;
    end process;
    
    clock_prc : process
    begin
        clk <= '0';
        wait for 25 ns;
        clk <= '1';
        wait for 25 ns;
    end process;
    
    in_empty_prc : process
    begin
        in_empty        <= '0';
        wait until rd_sig = '1';
        wait until rising_edge(clk);
        in_empty        <= '1';
        wait until rising_edge(clk);
    end process;
    
    endpoint_full_prc : process
    begin
        endpoint_full   <= (others => '0');
        wait until (or endpoint_wr) = '1';
        wait until rising_edge(clk);
        endpoint_full   <= (others => '1');
        wait until rising_edge(clk);
    end process;
    
    alert_prc : process(all)
    begin
        if rising_edge(clk) then
            alertif(in_empty = '1' and rd_sig = '1', "Input FIFO read signal high while empty signal high", ERROR);
            alertif(endpoint_full /= (0 to NUM_ENDPOINTS-1 => '0') and (endpoint_wr /= (0 to NUM_ENDPOINTS-1 => '0')), "Endpoint FIFO write signal high while full signal high", ERROR);
        end if;
    end process;
    
    input_prc : process(all)
    begin
        data_in         <= stimulus.data(cnt_stim);
        last_word_in    <= stimulus.last(cnt_stim);
        
        if rising_edge(clk) then
            if (reset = '1') then
                cnt_stim    <= 0;
                stim_stage  <= IDLE;
                packet_sent <= '1';
            else
                case (stim_stage) is
                    when IDLE =>
                        if (start = '1' and stimulus.length /= 0) then
                            stim_stage  <= BUSY;
                            packet_sent <= '0';
                        end if;
                    when BUSY =>
                        if (rd_sig = '1') then
                            if (cnt_stim = stimulus.length-1) then
                                stim_stage  <= IDLE;
                                packet_sent <= '1';
                                cnt_stim    <= 0;
                            else
                                cnt_stim    <= cnt_stim + 1;
                            end if;
                        end if;
                end case;
            end if;
        end if;
    end process;
    
    output_check_prc : process(all)
    begin
        check_done  <= '0';
        if rising_edge(clk) then
            if (endpoint_wr /= (0 to NUM_ENDPOINTS-1 => '0')) then
                SB_out.Check(endpoint_wr & last_word_out & data_out);
            end if;
            if (stim_done = '1' and SB_out.empty) then
                check_done  <= '1';
            end if;
        end if;
    end process;
    
    watchdog : process
    begin
        wait for 1 ms;
        Alert("Test timeout", FAILURE);
        std.env.stop;
    end process;
    
end architecture;