--
-- VHDL Architecture FACT_FAD_lib.spi_distributor.beha
--
-- Created:
--          by - Benjamin Krumm.UNKNOWN (EEPC8)
--          at - 09:24:21 23.04.2010
--
-- using Mentor Graphics HDL Designer(TM) 2009.1 (Build 12)
--
-- modified by Q. Weitzel
--

LIBRARY ieee;
USE ieee.std_logic_1164.all;
USE ieee.std_logic_arith.all;
USE ieee.std_logic_unsigned.all;
library ftu_definitions;
USE ftu_definitions.ftu_array_types.all;

ENTITY FTU_spi_distributor IS
  PORT(
    clk               : IN    std_logic; -- 50MHz
    config_start      : IN    std_logic;
    config_ready      : OUT   std_logic := '0'; 
    config_started    : OUT   std_logic := '0'; 
    dac_array         : IN    dac_array_type;
    dac_config_start  : OUT   std_logic := '0';
    dac_config_ready  : IN    std_logic;
    dac_id            : OUT   std_logic_vector(2 downto 0) := (others => '0');
    data              : OUT std_logic_vector(15 downto 0) := (others => '0')
  );
END ENTITY FTU_spi_distributor;

ARCHITECTURE beha OF FTU_spi_distributor IS

  type TYPE_SPI_DISTRIBUTION_STATE is (INIT, IDLE, CONFIG_DAC);
    
  signal spi_distr_state       : TYPE_SPI_DISTRIBUTION_STATE := INIT;
  signal dac_id_cnt            : integer range 0 to 7 := 0;
  
BEGIN
  
  spi_distribute_proc: process (clk)
  begin
    
    if rising_edge(clk) then
      data <= (others => '0');
      case spi_distr_state is
        when INIT =>
          data <= (others => '0');
          spi_distr_state <= IDLE;
        when IDLE =>
          data <= (others => '0');
         -- start DAC configuration
          if (config_start = '1') then
            config_started <= '1';
            config_ready <= '0';
            dac_config_start <= '1';
            dac_id <= conv_std_logic_vector(dac_id_cnt, dac_id'length);
            data <= conv_std_logic_vector(dac_array(dac_id_cnt),data'length);          
            spi_distr_state <= CONFIG_DAC;
          end if;
                 
        -- DAC configuration
        when CONFIG_DAC =>
          dac_config_start <= '1';
          dac_id <= conv_std_logic_vector(dac_id_cnt, dac_id'length);
          data <= conv_std_logic_vector(dac_array(dac_id_cnt),data'length);
          if (dac_config_ready = '1') then
            dac_config_start <= '0';
            if (dac_id_cnt < 7) then
              dac_id_cnt <= dac_id_cnt + 1;
              dac_config_start <= '1';
              spi_distr_state <= CONFIG_DAC;             
            else
              dac_id_cnt <= 0;
              config_started <= '0';
              config_ready <= '1';
              spi_distr_state <= IDLE;
            end if;
          end if; 
      end case;  
    end if;
    
  end process spi_distribute_proc;
  
END ARCHITECTURE beha;

