/** @file HL_sys_main.c 
*   @brief Application main file
*   @date 11-Dec-2018
*   @version 04.07.01
*
*   This file contains an empty main function,
*   which can be used for the application.
*/

/* 
* Copyright (C) 2009-2018 Texas Instruments Incorporated - www.ti.com  
* 
* 
*  Redistribution and use in source and binary forms, with or without 
*  modification, are permitted provided that the following conditions 
*  are met:
*
*    Redistributions of source code must retain the above copyright 
*    notice, this list of conditions and the following disclaimer.
*
*    Redistributions in binary form must reproduce the above copyright
*    notice, this list of conditions and the following disclaimer in the 
*    documentation and/or other materials provided with the   
*    distribution.
*
*    Neither the name of Texas Instruments Incorporated nor the names of
*    its contributors may be used to endorse or promote products derived
*    from this software without specific prior written permission.
*
*  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 
*  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 
*  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
*  A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 
*  OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 
*  SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 
*  LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
*  DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
*  THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 
*  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 
*  OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/


/* USER CODE BEGIN (0) */
#include "FreeRTOS.h"
#include "os_task.h"
#include "stdio.h"
/* USER CODE END */

/* Include Files */

#include "HL_sys_common.h"

/* USER CODE BEGIN (1) */
#include "F021.h"
#include "HL_gio.h"
#include "HL_sci.h"
#include "string.h"
#include "HL_adc.h"
#include "HL_reg_esm.h"
#include "test.h"
#include "xprintf.h"
#include "user_list.h"
#include "bl_flash.h"
/* USER CODE END */

/** @fn void main(void)
*   @brief Application main function
*   @note This function is empty by default.
*
*   This function is called after startup.
*   The user can use this function to implement the application.
*/

/* USER CODE BEGIN (2) */
void uart1_putc (uint8_t d);
void frame_received_callback(FrameData *frame, void *user_data);
//extern unsigned int apiLoadStart;
//extern unsigned int apiRunStart;
//extern unsigned int apiLoadSize;

//extern uint32 App_Flash_Erase_API_LoadStart;
//extern uint32 App_Flash_Erase_API_LoadEnd;
//extern uint32 App_Flash_Erase_API_Size;
//extern uint32 App_Flash_Erase_API_StartAddr;
//extern uint32 App_Flash_Erase_API_EndAddr;
//
//extern uint32 App_Flash_Program_API_LoadStart;
//extern uint32 App_Flash_Program_API_LoadEnd;
//extern uint32 App_Flash_Program_API_Size;
//extern uint32 App_Flash_Program_API_StartAddr;
//extern uint32 App_Flash_Program_API_EndAddr;

extern unsigned int constLoadStart;
extern unsigned int constLoadSize;
extern unsigned int constRunStart;

void os_init(void)
{
    TC_RawData_Init();
}

void frame_received_callback(FrameData *frame, void *user_data)
{

}

void System_ManageTask(void *pArg)
{
    uint32_t nRxCnt = 0;
    uint8_t *pRxBuf = NULL;
    St_RxTC_pkt *pst_RawData = NULL;
    FrameParser parser;
    frame_parser_init(&parser);
    xputs("System_ManageTask\n");
    for(;;)
    {
        pst_RawData = NULL;
        if (pdPASS == xQueueReceive(g_hQTCFrm, &pst_RawData,3))
        {
            if (NULL != pst_RawData)
            {
                nRxCnt = pst_RawData->nLen;
                pRxBuf = pst_RawData->mBuff;//接收到的数据就在这里

                int frames = parse_frame_data(&parser, pRxBuf, nRxCnt,
                                             frame_received_callback, NULL);

                memset(pst_RawData->mBuff, 0, pst_RawData->nLen);
                pst_RawData->nLen = 0; //这里清零，就是让下一次使用到的时候从第0个位置存储并释放节点。
            }
        }
    }
}



void LED_Task(void *pArg)
{
    xputs("LED_Task\n");
    while(1)
    {
        gioToggleBit(gioPORTB, 6);
        vTaskDelay(100);
    }
}

uint8_t flash_buf[1024] = {0};
uint8_t flash_buf2[1024] = {0};
void Flash_Task(void *pArg)
{
    uint32_t count=0;
//    _disable_IRQ_interrupt_();


//     _enable_IRQ_interrupt_();

    while(1)
    {
        xprintf("Flash_task:%d\n",count++);

        vTaskDelay(1000);
    }
}

/* USER CODE END */

uint8	emacAddress[6U] = 	{0xFFU, 0xFFU, 0xFFU, 0xFFU, 0xFFU, 0xFFU};
uint32 	emacPhyAddress	=	1U;

int main(void)
{
/* USER CODE BEGIN (3) */
//    memcpy(&apiRunStart, &apiLoadStart, (uint32)&apiLoadSize);
    memcpy(&constRunStart, &constLoadStart, (uint32)&constLoadSize);
//    memcpy(&App_Flash_Erase_API_StartAddr, &App_Flash_Erase_API_LoadStart, (uint32)&App_Flash_Erase_API_Size);
//    memcpy(&App_Flash_Program_API_StartAddr, &App_Flash_Program_API_LoadStart, (uint32)&App_Flash_Program_API_Size);
    double k = 1.0f;
    for(int i = 0;i < 6000000;i++)
    {
        k = k*1.0;
    }
//    memcpy(&apiRunStart, &apiLoadStart, (uint32)&apiLoadSize);
//    os_init();
    vimInit();
    /*硬件相关初始化*/
    if (0 == esmError())
    {
        esmTriggerErrorPinReset();
    }
//    Esm_EnableAction();
    _mpuInit_();
    _mpuDisable_();
    _mpuEnable_();
    _enable_interrupt_();

    gioInit();
    adcInit();
    sciInit();
    xdev_out(uart1_putc);
    xputs("APP:start\n");

    Fapi_BlockRead(0x00200000,(uint32_t)flash_buf,sizeof(flash_buf));//读flash
    xprintf("read1:%02X %02X %02X %02X %02X %02X %02X %02X %02X %02X\n",
         flash_buf[0],flash_buf[1],flash_buf[2],flash_buf[3],flash_buf[4],flash_buf[5],flash_buf[6],flash_buf[7],flash_buf[8],flash_buf[9]);
    Fapi_BlockErase(0x00200000 ,128*1024); //0x00010020
    xputs("Fapi_BlockErase\n");
    for(int i=0;i<sizeof(flash_buf);i++)
    {
        flash_buf[i] = 0xAA;
    }
    Fapi_BlockProgram(0x00200000, (uint32_t)flash_buf, sizeof(flash_buf));
    Fapi_BlockRead(0x00200000,(uint32_t)flash_buf2,sizeof(flash_buf2));//读flash
    xprintf("read2:%02X %02X %02X %02X %02X %02X %02X %02X %02X %02X\n",
          flash_buf2[0],flash_buf2[1],flash_buf2[2],flash_buf2[3],flash_buf2[4],flash_buf2[5],flash_buf2[6],flash_buf2[7],flash_buf2[8],flash_buf2[9]);
    xputs("Fapi_BlockProgram\n");



    if(xTaskCreate((TaskFunction_t)LED_Task,"LEDTask",256, NULL, 1, NULL) != pdPASS)
        xputs("Create LEDTask error\n");
    if(xTaskCreate((TaskFunction_t)Flash_Task,"FlashTask",1024, NULL, 2, NULL) != pdPASS)
        xputs("Create FlashTask error\n");
    xprintf("Create task ok\n");
    vTaskStartScheduler();

    /* Run forever */
    while(1);
/* USER CODE END */

    return 0;
}


/* USER CODE BEGIN (4) */

void uart1_putc (uint8_t d)
{
    sciSendByte(sciREG1, d);
}


uint8_t g_rx_buff1[512] = { 0 };
void sciNotification(sciBASE_t *sci, uint32 flags)
{
    char Byte=0;
    static uint16_t g_stTCRXDate_cnt = 0; //接收到的数据长度技术
    static uint8_t get_head_flag = 0;    //检测是否接收到包头 //如果检测到头为1   没有检测到位0
    static uint16_t head_type = 0;       //头的类型
    static uint16_t lend_num_data = 0;   //包数据域长度减1

    if(sci == sciREG1)
    {
        Byte = sciReceiveByte(sciREG1);
        if(get_head_flag == 0) //没有检测到头
        {
            g_stTCRXDate_cnt = 0;
            head_type = (head_type & 0xFF00) + Byte;
            switch(head_type)
            {
                case 0xEB90:
                    get_head_flag = 2;
                    g_stTCRXDate_cnt = 0;
                    break;
                default:
                    get_head_flag = 0;
                    head_type = head_type << 8 ;
                    break;
            }
        }
        else if(get_head_flag == 2) // 检测到0xEB90
        {
            g_rx_buff1[0] = 0xEB;
            g_rx_buff1[1] = 0x90;
            g_rx_buff1[g_stTCRXDate_cnt+2] = Byte;
            if(g_stTCRXDate_cnt >= 2)//获取指令长度
            {
                lend_num_data = g_rx_buff1[4] + 1;
                if(g_stTCRXDate_cnt == lend_num_data + 3) //接收到最后一位
                {
                    TC_Get_DataFromeISR(g_rx_buff1,lend_num_data + 6);
                    g_stTCRXDate_cnt = 0;
                    get_head_flag = 0;
                    head_type = 0;
                }
            }
            g_stTCRXDate_cnt++;
            if(g_stTCRXDate_cnt>=255+6)
            {
                g_stTCRXDate_cnt = 0;
                get_head_flag = 0;
                head_type = 0;
                return;
            }
        }
    }

}

/* USER CODE END */
