/* -*- c++ -*-
 *
 * SOCLIB_LGPL_HEADER_BEGIN
 *
 * This file is part of SoCLib, GNU LGPLv2.1.
 *
 * SoCLib is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as published
 * by the Free Software Foundation; version 2.1 of the License.
 *
 * SoCLib is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with SoCLib; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
 * 02110-1301 USA
 *
 * SOCLIB_LGPL_HEADER_END
 *
 * Copyright (c) UPMC, Lip6, Asim
 *         Sebastien Cerdan <sebcerdan@gmail.com>, 2014
 *
 */
#ifndef SOCLIB_VCI_SPI_H
#define SOCLIB_VCI_SPI_H

#include <stdint.h>
#include <systemc>
#include "vci_target_fsm.h"
#include "caba_base_module.h"
#include "mapping_table.h"

#include "spi.h"

namespace soclib {
namespace caba {

using namespace sc_core;

template<typename vci_param>
class VciSpi
	: public caba::BaseModule
{
private:
    soclib::caba::VciTargetFsm<vci_param, true> m_vci_target_fsm;

    bool on_write(int seg, typename vci_param::addr_t addr, typename vci_param::data_t data, int be);
    bool on_read(int seg, typename vci_param::addr_t addr, typename vci_param::data_t &data);
    void transition();
    void genMoore();

    uint32_t _ctrl;
    uint32_t _clkdiv;
    uint32_t _cstgl;
    uint32_t _irqpend;
    uint32_t _irqmsk;
    uint32_t _gpirqpend;
    uint32_t _gpirqm;
    uint32_t _gpirqmode;
    uint32_t _gpirqpol;
    uint32_t _wbuffer;
    uint32_t _rbuffer;

    sc_signal<uint32_t> s_clkcnt;
    sc_signal<uint32_t> s_tlen;
    sc_signal<uint32_t> s_status;
    sc_signal<bool> s_sending;
    sc_signal<uint32_t> s_gpin;
    sc_signal<uint32_t> s_gpout;

    /* RX and TX buffer */
    GenericFifo<uint32_t> * _rxb; 
    GenericFifo<uint32_t> * _txb; 

    size_t _ngpout;
    size_t _ngpin;
    size_t _fsize;
    size_t _wsize;
    size_t _bitcnt;

    uint32_t format_data(uint32_t);
    bool set_mosi();
    void get_miso();
    void invert_sclk();

protected:
    SC_HAS_PROCESS(VciSpi);

public:
    sc_in<bool> p_clk;
    sc_in<bool> p_resetn;
    sc_out<bool> p_irq;
    soclib::caba::VciTarget<vci_param> p_vci_target;

    sc_out<bool> p_sclk;
    sc_out<bool> p_mosi;
    sc_in<bool>  p_miso;
    sc_out<bool> *p_gpout;
    sc_in<bool>  *p_gpin;

    VciSpi(
      sc_module_name name,
      size_t fsize,
      size_t ngpin,
      size_t ngpout,
      const soclib::common::MappingTable &mt,
      const soclib::common::IntTab &tgtid);
};

}}

#endif /* SOCLIB_VCI_SPI_H */


