#include "system.h"
#include "test.h"
// ***** macro definition *****

// Driver instance
XGpioPs gpio;
XScuGic gic;
XAxiDma dma;
XUartPs uart;
XQspiPs qspi;
u8 uartRecvBuf[70];

XTime curTime, preTime;
volatile bool txDataReqIntr = 0;
volatile bool rxDataRecIntr = 0;
volatile bool recvDone = false;
volatile bool transDone = false;

volatile bool testFrameSyncFlag = false;
volatile uint32_t testFrameSyncTimes = 0;

int main(void)
{

    LOG_BLANK_LINE;
    LOG_BLANK_LINE;
    xil_printf(INFO_MSG("Program Compile Date: %s"), __DATE__);
    int32_t status;

    // Init system
    status = InitSystem();
    CHECK_STATUS(status, ERROR_MSG("system init fail"));
    int32_t gain = 0;
    while (true)
    {
        // push stack !!! this can't be delete, and must be in the while loop
        //        xemacif_input(netif);
        xemacpsif_input(netif);

        // handle event
        if (txDataReqIntr)
        {

        	if(testFrameSyncFlag)
        	{
        		if( testFrameSyncTimes == 0)
        		{
        			testFrameSyncFlag = false;
        			LOG_INFO("TEST FRAME SYNC DONE!");
        			// when the config done, tx req will not function
        			PhyConfigTdma(tdmaId, 0 ,SLOT_LEN,TIC_2_PS);
        			continue;
        		}
        		else
        		{
        			testFrameSyncTimes-- ;
        		}

        	}

			// approximately 28us 1400 period of the 50MHz clock
			MakeMacFrame(&txMacFrame, macSendQueue);
			Xil_DCacheFlushRange((uint32_t)&txMacFrame, MAC_FRAME_LEN);
			status = XAxiDma_SimpleTransfer(&dma, (UINTPTR)&txMacFrame, MAC_FRAME_LEN, XAXIDMA_DMA_TO_DEVICE);
//            CHECK_STATUS(status, "DMA Transfer start fail");
			txDataReqIntr = false;
        }
        if (rxDataRecIntr)
        {
            status = XAxiDma_SimpleTransfer(&dma, (UINTPTR)&rxMacFrame, MAC_FRAME_LEN, XAXIDMA_DEVICE_TO_DMA);
//            CHECK_STATUS(status, "DMA Transfer start fail");
            rxDataRecIntr = false;
            ad9361_get_rx_rf_gain(ad9361_phy, 0, &gain);
        }
        if (recvDone)
        {
            recvDone = false;
            Xil_DCacheInvalidateRange((uint32_t)&rxMacFrame, MAC_FRAME_LEN);
            uint8_t recvId = ParseMacFrame(&rxMacFrame);
            memset(&rxMacFrame, 0, sizeof(MacFrame));
            if (badFrames)
            {
                xil_printf(INFO_MSG("#%3d, B , Gain = %3d dB"), recvId, gain);
                badFrames = false;
            }
            else
            {
                xil_printf(INFO_MSG("#%3d, G , Gain = %3d dB"), recvId, gain);
            }
        }
        if (transDone)
        {
            memset(&txMacFrame, 0, sizeof(MacFrame));
            transDone = false;
        }
    }

    return 0;
}
