/**************************************************************************//**
 * @file     main.c
 * @version  V1.00
 * $Date: 19/10/30 16:17 $
 * @note
 * Copyright (C) 2019 Panchip Technology Corp. All rights reserved.
 *
 ******************************************************************************/
#include <stdio.h>
#include "comm_prf.h"
#include "dongle_usb.h"
#include "common.h"
#include "dongle_p24c02.h"

struct ring_buf ringbuf_raw;
struct ring_buf ringbuf_raw2;
uint8_t ringbuf_data[RINGBUFFER_SIZE];
uint8_t ringbuf_data2[RINGBUFFER_SIZE];
uint8_t m_chip_mac[6] = {0x11, 0x22, 0x33, 0x44, 0x55, 0x66};


void data_printf(uint8_t const *data, uint32_t len)
{
	uint32_t i = 0;

	if (len == 0) 
	{
		return;
	}

	for (; i < len; i++) 
	{
		mini_printf("%x ", data[i]);
	}
	mini_printf("\n");
}

void systick_delay_ms(uint16_t ms)
{
	uint32_t ticks = 0;

	ticks = SystemCoreClock / 1000 * ms;
	if(ticks > 16777216)
	{
		ticks = 16777216;
	}

	SysTick->LOAD = ticks;
	SysTick->VAL =0x00;
	SysTick->CTRL = (SysTick_CTRL_ENABLE_Msk | SysTick_CTRL_CLKSOURCE_Msk);

	/* Waiting for down-count to zero */
    while((SysTick->CTRL & SysTick_CTRL_COUNTFLAG_Msk) == 0);

	SysTick->CTRL = 0;
}

void Clock_Init(void)
{
	PMU->SYS_CLK_CTRL |= SYS_CLK_CTRL_OTP_READ_MODE_SEL_Msk;
	PMU->SYS_CLK_CTRL &= ~(SYS_CLK_CTRL_OTP_CLK_HIGH_CYCLE_Msk | SYS_CLK_CTRL_OTP_CLK_LOW_CYCLE_Msk);
	PMU->SYS_CLK_CTRL |= ((0X1 << SYS_CLK_CTRL_OTP_CLK_HIGH_CYCLE_Pos) | (0x0 << SYS_CLK_CTRL_OTP_CLK_LOW_CYCLE_Pos));
	PMU->SYS_CLK_CTRL |= SYS_CLK_CTRL_OTP_SW_UP_CYCLE_EN_Msk;
	#ifndef FPGA_MODE
	PMU->ANA_ANALDO |= ANA_ANALDO_EN_LDO_FSYN_AON_Msk;
    //MCU
	CLK_XthStartupConfig();
	PMU->XTH_CTRL |= XTH_CTRL_FSYNXO_BUFEN_AON_Msk;
	PMU->XTH_CTRL |= XTH_CTRL_FSYNXO_EN_AON_Msk;
	CLK_WaitClockReady(CLK_SYS_SRCSEL_XTH);

	CLK_HCLKConfig(0);

	CLK_SYSCLKConfig(CLK_DPLL_REF_CLKSEL_XTH,CLK_DPLL_OUT_48M); 
	CLK_RefClkSrcConfig(CLK_SYS_SRCSEL_DPLL);
	#endif

	CLK_AHBPeriphClockCmd(CLK_AHBPeriph_APB1 | CLK_AHBPeriph_USB_AHB | CLK_AHBPeriph_USB_48M,ENABLE);
	CLK_APB1PeriphClockCmd(CLK_APB1Periph_ADC|CLK_APB1Periph_UART0,ENABLE);
	
	//PMU->XTH_CTRL = (PMU->XTH_CTRL & ~XTH_CTRL_FSYNXO_CAPSEL_AON_Msk) | (0x30 << XTH_CTRL_FSYNXO_CAPSEL_AON_Pos);
}


void Sys_Init(void)
{
    /* Unlock protected registers */
    SYS_UnlockReg();

    /* Init I/O Multi-function  */
	SYS_SET_MFP(P0,6,UART0_RX);
	SYS_SET_MFP(P0,5,UART0_TX);
	GPIO_EnableDigitalPath(P0,BIT6);

	UART_Init(UART0, 115200);
	
    SYS_LockReg();
}


/*------------------
    Main function
 ------------------*/
int main(void)
{
    Clock_Init();
    Sys_Init();
	
	mini_printf("CPU @ %dHz\n", SystemCoreClock);
	
	IIC_Init();
	
	usb_init();
	
	ring_buf_init(&ringbuf_raw, RINGBUFFER_SIZE, ringbuf_data);
	ring_buf_init(&ringbuf_raw2, RINGBUFFER_SIZE, ringbuf_data2);

	dongle_prf_init();
	while(1) {	
		usb_report();
		write_pair_addr();
	}
}
