-- See the file "LICENSE" for the full license governing this code. --
LIBRARY ieee;
USE ieee.std_logic_1164.ALL;
USE ieee.numeric_std.ALL;

LIBRARY work;
USE work.lt16soc_peripherals.ALL;
USE work.wishbone.ALL;
USE work.wb_tp.ALL;
USE work.config.ALL;

ENTITY timer_tb IS
END ENTITY;

ARCHITECTURE sim OF timer_tb IS

	constant CLK_PERIOD : time := 10 ns;

	signal clk 	: std_logic := '0';
	signal rst	: std_logic;
	signal data	: std_logic_vector(WB_PORT_SIZE-1 downto 0);
	
    signal interrupt : std_logic;

	signal slvi	: wb_slv_in_type;
	signal slvo	: wb_slv_out_type;

BEGIN

	SIM_SLV: wb_timer
		generic map(
			memaddr		=> CFG_BADR_TIMER,
			addrmask	=> CFG_MADR_TIMER
		)
		port map(
			clk		=> clk,
			rst		=> rst,
			wslvi	=> slvi,
			wslvo	=> slvo,
			interrupt => interrupt
		);

	clk_gen: process
	begin
		clk	<= not clk;
		wait for CLK_PERIOD/2;
	end process clk_gen;

	stimuli: process
	begin
		rst	<= '1';
		wait for CLK_PERIOD;
		rst	<= '0';
		wait for CLK_PERIOD;
		wait for CLK_PERIOD;
		wait for CLK_PERIOD;
		
		-- Configure timer...
		data	<= (others => '0');
		data(0) <= '1'; -- enable
		data(1) <= '1'; -- repeat
		generate_sync_wb_single_write(slvi,slvo,clk,data, ADR_OFFSET => 4);
		
		wait until interrupt = '1';
		wait for CLK_PERIOD*20;
		
        -- Read counter value
        data	<= (others => '0');
		generate_sync_wb_single_read(slvi,slvo,clk,data);
		
		wait for CLK_PERIOD*4;
		
		-- Disable repeat and reset timer...
        data	<= (others => '0');
        data(1) <= '0'; -- repeat
		data(2) <= '1'; -- reset
		generate_sync_wb_single_write(slvi,slvo,clk,data, ADR_OFFSET => 4);
		
		wait until interrupt = '1';
		wait for CLK_PERIOD*20;
		
        -- Restart timer...
        data	<= (others => '0');
        data(0) <= '1'; -- enable
        generate_sync_wb_single_write(slvi,slvo,clk,data, ADR_OFFSET => 4);
        
        wait for CLK_PERIOD*20;
        
        -- Change target value
        data <= std_logic_vector(to_unsigned(1024, data'length));
        generate_sync_wb_single_write(slvi,slvo,clk,data);
        
        -- Read status register
        data	<= (others => '0');
        generate_sync_wb_single_read(slvi,slvo,clk,data, ADR_OFFSET => 4);
        
        wait until interrupt = '1';
        wait for CLK_PERIOD * 5;
        assert false report "Simulation terminated!" severity failure;

		wait;
	end process stimuli;

END ARCHITECTURE;
