/** @file 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 "CanIf_Integration.h"

// Removing of compiler warnings and errors because of type re-declaration between hal_stdtypes.h and Std_Types.h
#define _BOOLEAN_DECLARED
#define _UINT8_DECLARED
#define _UINT16_DECLARED
#define _UINT32_DECLARED
#define _UINT64_DECLARED
#define _SINT8_DECLARED
#define _SINT16_DECLARED
#define _SINT32_DECLARED
#define _SINT64_DECLARED
#define _FLOAT32_DECLARED
#define _FLOAT64_DECLARED
#define _STD_RETURN_TYPE_DECLARED
#define _STDVERSION_DECLARED
//
#include <crc_hal.h>

/* USER CODE END */

/* Include Files */

#include "sys_common.h"

/* USER CODE BEGIN (1) */
#include "system.h"
#include "sys_vim.h"
#include "sys_core.h"
#include "can.h"
#include "rti.h"
#include "het.h"
#include "gio.h"
#include "crc_tbl.h"
#include "ti_fee.h"
#include "F021.h"
#include "Ios_DefineCatalog.h"
#include "Ios_IntrTimerManagement.h"
#include "Ios_BoardLedMngt.h"
#include "Ios_BootLoaderVersion.h"
#include "Ios_RunTimeInstance.h"
#include "Ios_CheckBootLoaderSignature.h"
#include "Ios_Flash.h"
#include "Ios_Std.h"
#include "Ios_Terminal.h"
#include "Ios_BoardExtWdgMngt.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) */

extern uint32 BootLInfoLoadStart;
extern uint32 BootLInfoRunStart;
extern uint32 BootLInfoLoadSize;

extern void Fbl_Port_BLSM_Init(void);
extern void func_10ms(void);

/* USER CODE END */

int main(void)
{
/* USER CODE BEGIN (3) */

    // Copy the flash APIs to SRAM
    memcpy(&FlsApiRunStart, &FlsApiLoadStart, (uint32)&FlsApiLoadSize);

    // Copy the .const section
    memcpy(&FlsApiconstRunStart, &FlsApiconstLoadStart, (uint32)&FlsApiconstLoadSize);

    // Copy boot info section
    memcpy(&BootLInfoRunStart, &BootLInfoLoadStart, (uint32)&BootLInfoLoadSize);

    //Terminal Initialization
    fnIosTerminalInitialise();

    /** - Enable IRQ and FIQ interrupt in Cortex R4 */
    _enable_interrupt_();

    wcu_printf(CLEAR_SCREEN);
    wcu_printf("VX BMU Booting...\n");
    wcu_printf("Boot SW Part Number: 605UN00004A01\n");
    wcu_printf("Boot Version   : %d.%d.%d\n"
               "Boot Build Date: %s\n", BOOT_VERSION_MAJOR, BOOT_VERSION_MINOR, BOOT_VERSION_REVISION,  __DATE__);
    fnIosFlushTxQueue();


    Fbl_Port_BLSM_Init();

    /* USER CODE END */

    return 0;
}


/* USER CODE BEGIN (4) */

void func_10ms(void)
{
    static uint32 ulTimerCounter = 0;


    if(ulTimerCounter >= 0xFFFFFFFE)
    {
        ulTimerCounter = 0;
    }
    // Every 10ms
    ulTimerCounter++;

    //Kick External Watchdog
    fnIosKickExternalWdg();

    // Every 250ms
    if((ulTimerCounter % 25) == 0) // Toggle LED every 250ms
    {
#if defined(HW_TYPE) && (HW_TYPE == EVALBOARD)
        fnIosToggleLed_D3();
#else
        fnIosAnimateBoardLeds();
#endif
    }

    // Every 1000ms
    if((ulTimerCounter% 1000) == 0) // Send Can boot frame every 1sec
    {

    }
}

void fnIosCanwrite(uint16 Hth,uint8 Length, uint8* data, uint16 TxPdID)
{
    uint8 bCANMsgPayLoad[8] = {0};
    int i;

    uint8 bRunTimeInstance = fnIosGetRunTimeInstance();

    for(i = 0; i <Length ; i++)
    {
        bCANMsgPayLoad[i]= data[i];
    }

    if(bRunTimeInstance  == RUNTIME_INST_BMS1)
    {
        if(Hth == 0 ) // UDS Master
        {
            canTransmit(canREG1, canMESSAGE_BOX3, bCANMsgPayLoad);
        }
        else if(( Hth == 2 ) && (0 != bCANMsgPayLoad[0])) //FBL Master
        {
            canTransmit(canREG1,canMESSAGE_BOX1, bCANMsgPayLoad);
        }
    }
    else
    {

        if( Hth == 1) // UDS Slave
        {
            canTransmit(canREG1, canMESSAGE_BOX4, bCANMsgPayLoad);
        }
        else if(( Hth == 3) && (0 != bCANMsgPayLoad[0])) //FBL Slave
        {
            canTransmit(canREG1,canMESSAGE_BOX2, bCANMsgPayLoad);
        }
    }

    //wcu_printf("Hth: %d\n", Hth);

}

void fnIosPollCanwrite(void)
{
    //Code to detect successful Can transmit

}

void fnIosPollCanRead(void)
{
    uint8 bCANMsgPayLoad[8] = {0};
    uint8 bCanReadRtn = 0;
    uint8 bRunTimeInstance = fnIosGetRunTimeInstance();
    uint8 bMsgBoxIndex = 0;

    //static uint32 uNumCanIfRxInd = 0;

    if(bRunTimeInstance  == RUNTIME_INST_BMS1)
    {
        for(bMsgBoxIndex = canMESSAGE_BOX5; bMsgBoxIndex <= canMESSAGE_BOX12; bMsgBoxIndex++)
        {
            if(canIsMessageBoxValid(canREG1, bMsgBoxIndex) && canIsRxMessageArrived(canREG1, bMsgBoxIndex))
            {
                bCanReadRtn = canGetData(canREG1, bMsgBoxIndex, bCANMsgPayLoad);
                //wcu_printf("CanRx Ind : %d - 1st byte :%d\n", uNumCanIfRxInd, bCANMsgPayLoad[0]);
                //uNumCanIfRxInd++;

                if(1 == bCanReadRtn)
                {
                    // Send payload to Master UDS PDU
                    CanIf_RxIndication(0,0x40,8,bCANMsgPayLoad);

                }
                else if (3 == bCanReadRtn)
                {
                    // Send payload to Master UDS PDU
                    CanIf_RxIndication(0,0x40,8,bCANMsgPayLoad);
                    //Debug - Check if messages lost
                    wcu_printf("Can Read rtn : %d - Msgbx: %d\n", bCanReadRtn,bMsgBoxIndex);
                }
                else
                {
                    break; //break for Loop
                }
            }
            else
            {
                break; //break for Loop
            }

            //Debug if messages are getting lost
            //if(bMsgBoxIndex > canMESSAGE_BOX5) wcu_printf("MsgBxId: %d\n", bMsgBoxIndex);
        }
    }
    else
    {
        for(bMsgBoxIndex = canMESSAGE_BOX13; bMsgBoxIndex <= canMESSAGE_BOX20; bMsgBoxIndex++)
        {
            if(canIsMessageBoxValid(canREG1, bMsgBoxIndex) && canIsRxMessageArrived(canREG1, bMsgBoxIndex))
            {
                bCanReadRtn = canGetData(canREG1, bMsgBoxIndex, bCANMsgPayLoad);
                //wcu_printf("CanRx Ind : %d - 1st byte :%d\n", uNumCanIfRxInd, bCANMsgPayLoad[0]);
                //uNumCanIfRxInd++;

                if(1 == bCanReadRtn)
                {
                    // Send payload to slave UDS PDU
                    CanIf_RxIndication(1,0x44,8,bCANMsgPayLoad);

                }
                else if (3 == bCanReadRtn)
                {
                    // Send payload to slave UDS PDU
                    CanIf_RxIndication(1,0x44,8,bCANMsgPayLoad);
                    //Debug - Check if messages lost
                    //wcu_printf("Can Read rtn : %d\n", bCanReadRtn);
                }
                else
                {
                    break; //break for Loop
                }
            }
            else
            {
                break; //break for Loop
            }

            //Debug if messages are getting lost
            //if(bMsgBoxIndex > canMESSAGE_BOX13) wcu_printf("MsgBxId: %d\n", bMsgBoxIndex);

        }
    }
}

/* USER CODE END */
