/*
 * \file   main.c
 *
 * \brief  Main routine for the bootloader for FR5739
 *
 */
/* --COPYRIGHT--,BSD
 * Copyright (c) 2012, Texas Instruments Incorporated
 * All rights reserved.
 *
 * 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.
 * --/COPYRIGHT--*/
//
//  Include files
//
#include "msp430.h"
#include "TI_MSPBoot_Common.h"
#include "TI_MSPBoot_CI.h"
#include "TI_MSPBoot_MI.h"
#include "TI_MSPBoot_AppMgr.h"

//
//  Local function prototypes
//
static void clock_init(void);
static void HW_init(void);
static void MPU_init(void);

/******************************************************************************
 *
 * @brief   Main function
 *  - Initializes the MCU
 *  - Selects whether to run application or bootloader
 *  - If bootloader:
 *      - Initializes the peripheral interface
 *      - Waits for a command
 *      - Sends the corresponding response
 *  - If application:
 *      - Jump to application
 *
 *  @note   USI interrupts are enabled after this function
 * @return  none
 *****************************************************************************/
int main_boot( void )
{
    // Stop watchdog timer to prevent time out reset
    WDTCTL = WDTPW + WDTHOLD;

    // Initialize MPU
    MPU_init();
    
    // Initialize MCU
    HW_init();
    clock_init();

    // Validate the application and jump if needed
    if (TI_MSPBoot_AppMgr_ValidateApp() == TRUE_t)
        TI_MSPBoot_APPMGR_JUMPTOAPP();

    TI_MSPBoot_CI_Init();      // Initialize the Communication Interface

#ifndef NDEBUG
    PJDIR |= BIT0|BIT1;     // Used for debugging purposes to show entry to MSPBoot
    PJOUT |= BIT0|BIT1;
#endif

    while(1)
    {
        // Poll PHY and Data Link interface for new packets
        TI_MSPBoot_CI_PHYDL_Poll();

        // If a new packet is detected, process it
        if (TI_MSPBoot_CI_Process() == RET_JUMP_TO_APP)
        {
            // If Packet indicates a jump to App
            TI_MSPBoot_AppMgr_JumpToApp();
        }
#ifdef NDEBUG
        // Feed the dog every ~1000ms
        WATCHDOG_FEED();
#endif
    }


}

/******************************************************************************
 *
 * @brief   Initializes the MSP430 Clock
 *
 * @return  none
 *****************************************************************************/
//inline static void clock_init(void)
static void clock_init(void)
{
    CSCTL0_H = 0xA5;
    CSCTL1 = DCOFSEL0 + DCOFSEL1;                         // Set DCO = 8Mhz
    CSCTL2 = SELA__VLOCLK + SELM__DCOCLK + SELS__DCOCLK;  // set ACLK = VLO
                                                          // MCLK=SMCLK=DCO
    
#if (MCLK==1000000)
    CSCTL3 = DIVA__1 + DIVS__8 + DIVM__8;                 // Divide DCO/8
#elif (MCLK==4000000)
    CSCTL3 = DIVA__1 + DIVS__2 + DIVM__2;                 // Divide DCO/2
    #elif (MCLK==8000000)
    CSCTL3 = DIVA__1 + DIVS__1 + DIVM__1;                 // Divide DCO/1
#else
#error "Please define a valid MCLK or add configuration"
#endif

}


/******************************************************************************
 *
 * @brief   Initializes the basic MCU HW
 *
 * @return  none
 *****************************************************************************/
static void HW_init(void)
{
    // Just initialize S2 button to force BSL mode
    P4OUT |= BIT1;
    P4REN |= BIT1;
}

/******************************************************************************
 *
 * @brief   Initializes the Memory Protection Unit of FR5739
 *          This allows for HW protection of Bootloader area
 *
 * @return  none
 *****************************************************************************/
static void MPU_init(void)
{
    // These calculations work for FR5739 (check user guide for MPUSEG values)
    #define MPUB1 (((APP_START_ADDR)&0x3F00)>>9)
    #define MPUB2 (((APP_END_ADDR+1)&0x3F00)>>9)
    
    // Enable access to MPU registers
    MPUCTL0 = MPUPW;
    // Seg1 = 0x0000 - App , Seg2 = App - Boot, Seg3 = Boot - 0xFFFF
    //MPUSEG = (MPUB2 << 8) | MPUB1;
    MPUSEGB1 = MPUB1;
    MPUSEGB2 = MPUB2;
    // Seg 3 doesn't have write-access and generates a PUC
    MPUSAM = 0x7D77;
    // Enable MPU
    MPUCTL0 = MPUPW |MPUENA;
    // Disable access to MPU Registers
    MPUCTL0_H = 0x00;
    
}
