#include "dev_profile.h"
#include "spi.h"
#include "../config/app_config.h"
#include "../drivers/adc/ad9653/ad9653.h"
#include "../drivers/axi_core/spi_engine/spi_engine.h"
#include "../drivers/platform/xilinx_gpio.h"

static struct spi_engine_init_param spi_engine_param = {
	.ref_clk_hz = AD9653_SPI_ENGINE_REF_CLK,
	.type = SPI_ENGINE,
	.spi_engine_baseaddr = AD9653_SPI_ENGINE_BASEADDR,
	.cs_delay = AD9653_SPI_ENGINE_CS_DELAY,
	.data_width = AD9653_SPI_ENGINE_DATA_WIDTH
};

static struct xil_gpio_init_param xil_gpio_param = {
	.type = GPIO_PS,
	.device_id = AD9653_GPIO_DEVICE_ID
};

static struct spi_init_param ad9694_spi_init = {
	.device_id = AD9653_SPI_DEVICE_ID,
    .max_speed_hz = AD9653_SPI_ENGINE_MAX_SPEED,
	.mode = SPI_MODE_4,
	.chip_select = AD9653_SPI_CS,
	.platform_ops = SPI_OPS,
	.extra = SPI_PARAM
};

struct ad9694_init_param ad9694_default_init_param = {
	/* SPI */
	.spi_init = &ad9694_spi_init
};

const uint32_t ad9694_default_config_len = 36;
const struct ad9694_config ad9694_default_config[] = {
	// reset
	{0x0000, 0x81},
	{0x1228, 0x4F},	// JESD204B start-up circuit reset
	{0x1228, 0x0F},	// JESD204B start-up normal operation
	{0x1222, 0x04}, // PLL calibration
	{0x1222, 0x00}, // PLL normal operation
	{0x1262, 0x08}, // PLL loss of lock control - Clear loss of lock
	{0x1262, 0x00}, // PLL loss of lock control - Normal operation

	// system clock
	{0x0108, 0x00}, // Clock divider = 1 -> device clock = 368.64MHz
	{0x0201, 0x00}, // Chip decimation ration = 1 -> full sample rate

	// channel configuration
	{0x0009, 0x03}, // ADC Pair AB & CD receive all spi command
	{0x0571, 0x15}, // JESD204B map JTX Link Control 1
	{0x056E, 0x00}, // JESD204B map PLL control, lane rate 6.75~13.5Gbps, actual = 7.3728Gbps
	{0x0570, 0x49}, // JESD204B map JTX quick config: L=2 M=2 F=2
	{0x058B, 0x01}, // JESD204B map JTX SCR L config: scrambler disabled, L=2
	{0x0590, 0x2F}, // JESD204B map JTX Subclass & NP config: subclass 1, N' = 16
	{0x058D, 0x1F}, // JESD204B map JTX K config: K = 32
	{0x058F, 0x2D}, // JESD204B map JTX N config: CS = 0, N = 14
	{0x0571, 0x14}, // JESD204B map JTX Link Control 1
	{0x05B0, 0x00}, // SERDOUTx0, SERDOUTx1 power on
	{0x0120, 0x0A}, // SYSREF COntrol: continuous mode, captured on falling edge

	// fast detect control
	{0x0040, 0x00}, // FD_B/FD_D, FD_A/FD_C function as Fast Detect B/D, A/C output
	{0x0245, 0x01}, // Fine fast detect enabled
	{0x0247, 0xFE}, // Channel map fast detect upper threshold LSB
	{0x0248, 0x1F}, // Channel map fast detect upper threshold MSB, -> 8190
	{0x0249, 0xA4}, // Channel map fast detect lower threshold LSB
	{0x024A, 0x1F}, // Channel map fast detect lower threshold MSB, -> 8100
	{0x024B, 0x80}, // Channel map fast detect dwell time LSB
	{0x024C, 0x00}  // Channel map fast detect dwell time MSB, -> 128
};
