#include "dfu/cy_dfu.h"
#include "project.h"
#include "common.h"
#include "cy_si_config.h"

#include "COMM_IPC_Messages.h"

/* App1 Start Address, change define if different */
#define APP_1_START_ADDRESS     0x10040000

/* Cypress Standard Application Format Header */
CY_SECTION(".cy_app_header") __USED
const cy_stc_user_appheader_t applicationHeader =
{
    .objSize        = CY_DFU_APP1_VERIFY_LENGTH,        /* App Size to authenticate */
    .appId          = CY_SI_APP_VERSION,                /* App ID */
    .appAttributes  = 0UL,                              /* Reserved */
    .numCores       = 2UL,                              /* Number of cores in the application */
    .core0Vt        = (uint32_t)(&__Vectors[0]) - APP_1_START_ADDRESS - offsetof(cy_stc_user_appheader_t, core0Vt),              /* Offset to CM0+ Vector Table in flash */ 
    .core1Vt        = (uint32_t)(&__cy_app_core1_start_addr) - APP_1_START_ADDRESS - offsetof(cy_stc_user_appheader_t, core1Vt), /* Offset to CM4 Vector Table in flash */
    .core0Id        = CY_ARM_CM0P_CPUID,                /* ARM CM0+ CPU ID */
    .core1Id        = CY_ARM_CM4_CPUID,                 /* ARM CM4 CPU ID */
};


/*******************************************************************************
* Function Name: main()
********************************************************************************
*
* Summary:
*  Main function for the project.
*
*
*******************************************************************************/
int main(void)
{    

    /* Unfreeze IO after Hibernate */
    if(Cy_SysPm_GetIoFreezeStatus())
    {
        Cy_SysPm_IoUnfreeze();
    }

    /* Enable global interrupts. */
    __enable_irq(); 

#if(CY_BLE_CONFIG_HOST_CORE == CY_BLE_CORE_CORTEX_M0P)
    COMM_InitIPCMessages();
    
    /* Enable CM4.  CY_CORTEX_M4_APPL_ADDR must be updated if CM4 memory layout is changed. */
    Cy_SysEnableCM4( (uint32_t)(&__cy_app_core1_start_addr) );
    
    /* Run Host main */
    HostMain();

#else
    
    #if(CY_BLE_STACK_MODE_IPC)
        /* Start BLE Controller for dual core mode */
        Cy_BLE_Start(NULL);
    #endif /* (CY_BLE_STACK_MODE_IPC)*/
    
    COMM_InitIPCMessages();
    
    /* Enable CM4.  CY_CORTEX_M4_APPL_ADDR must be updated if CM4 memory layout is changed. */
    Cy_SysEnableCM4( (uint32_t)(&__cy_app_core1_start_addr) );
    
    while(true)
    {       
    #if(CY_BLE_STACK_MODE_IPC)
        /* Process BLE events continuously for controller in dual core mode */
        Cy_BLE_ProcessEvents();
    #endif /* CY_BLE_STACK_MODE_IPC */
    
        /* To achieve low power in the device */
        Cy_SysPm_DeepSleep(CY_SYSPM_WAIT_FOR_INTERRUPT); 
    }
    
#endif /* (CY_BLE_HOST_CORE == CY_CPU_CORTEX_M0P) */  
}

