/* --COPYRIGHT--,BSD_EX
 * Copyright (c) 2014, 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.
 *
 *******************************************************************************
 *
 *                       MSP430 CODE EXAMPLE DISCLAIMER
 *
 * MSP430 code examples are self-contained low-level programs that typically
 * demonstrate a single peripheral function or device feature in a highly
 * concise manner. For this the code may rely on the device's power-on default
 * register values and settings such as the clock configuration and care must
 * be taken when combining code from several examples to avoid potential side
 * effects. Also see www.ti.com/grace for a GUI- and www.ti.com/msp430ware
 * for an API functional library-approach to peripheral configuration.
 *
 * --/COPYRIGHT--*/
//                MSP430FR5969
//                   Host
//             -----------------
//       RST -|     P2.5/UCA0TXD|---->
//            |     P2.6/UCA0RXD|<----
//            |                 |
//            |             P1.3|-->RST
//            |             P1.4|-->TEST
//            |             P1.5|-->TCK
//            |                 |
//            |             P4.6|-->LED (Show error)
//            |             P1.0|-->LED

#include <msp430.h> 
#include "stdint.h"
#include "bsl.h"
#include "uart.h"

#include <application_image.h>


//#define Hardware_Invoke




/**
 * main.c
 */
void BSP_configureMCU(void);
void UART_Init(void);
void ToggleLeds(void);

uint8_t* App_start_address(uint32_t * Addr_array, uint32_t *Size_array, uint8_t ** DataPtr_Array, \
                           uint8_t num_arrays);

BSL_error_t bsl_err;
uint8_t status;
//=============================================================================
// Here is password of the boot code for update. The last two bytes if the start address of the boot code.
const uint8_t BSL_PW_RESET[32] = {
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, \
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, \
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, \
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x40, 0xFF  \
};
// Here is password for mass erase. All the values are 0xFF.
const uint8_t BSL_PW_ERASE[32] = {
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, \
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, \
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, \
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF  \
};

uint16_t count1,count2;
uint8_t* start_address;
void main(void)
{
    uint8_t section;

	WDTCTL = WDTPW | WDTHOLD;	// stop watchdog timer

	start_address= App_start_address( (uint32_t *)&App1_Addr[0],
	                                           (uint32_t *)&App1_Size[0],
	                                           (uint8_t **)&App1_Ptr[0],
	                                           sizeof(App1_Addr)/ sizeof (App1_Addr[0]));

	BSP_configureMCU();
	UART_Init();
	while(1)
	{
	    if ((P4IN & BIT5)==0)
	      {
	       __delay_cycles(500);
	       if ((P4IN & BIT5)==0)
	          {
	           bsl_err=7;
	           ToggleLeds();              // Show we are starting BSL
    #ifdef Hardware_Invoke
	           Host_BSL_entry_sequence(); //PLACE TARGET INTO BSL MODE by hardware invoke
               __delay_cycles(500000);    // Allow at least 30msec for target to be up and running
    #endif
	           status = Status_check();   //Check the status of the target: BSL mode or application mode
	           if(status==0x51)           //BSL mode 0x51; application mode 0x22
	           {
	                 __delay_cycles(500000);    // Allow at least 30msec for target to be up and running
	                  //USE PASSWORD TO GAIN ACCESS TO TARGET BSL. Note: A wrong password causes a mass erase.
                         bsl_err = Host_BSL_loadPassword((uint8_t*)BSL_PW_RESET);

	           }
	           else  if(status==0x22)        //BSL mode 0x51; application mode 0x22
	                 {
	                   Host_BSL_entry_software(); //Send commend to make the device into BSL MODE
	                   __delay_cycles(500000);    // Allow at least 30msec for target to be up and running
                          //USE PASSWORD TO GAIN ACCESS TO TARGET BSL. Note: A wrong password causes a mass erase.
	                   status = Status_check();   //Check the status of the target: BSL mode or application mode
	                   __delay_cycles(50000);    // Allow at least 30msec for target to be up and running
	                   if(status==0x51)
	                   {
	                       bsl_err = Host_BSL_loadPassword((uint8_t*)BSL_PW_RESET);
	                   }
	                   else
	                   {
	                       P4OUT |= BIT6;// error
	                   }

	                 }
	                 else
	                 {
	                   P4OUT |= BIT6;// error
	                 }


               if(bsl_err == eBSL_success)
               {
                   P4OUT &= ~BIT6;
                   __delay_cycles(2000);
                   P4OUT |= BIT6;
                  __delay_cycles(2000);
                  P4OUT &= ~BIT6;

                  //WRITE THE ENTIRE PROGRAM MEMORY SECTION TO TARGET
                  for (section = 0; section < (sizeof(App1_Addr)/ sizeof (App1_Addr[0])) ; section++)
                  {
                      bsl_err = Host_BSL_writeMemory(App1_Addr[section],  App1_Ptr[section], App1_Size[section]);
                      if(bsl_err != eBSL_success) break;
                  }

                  if(bsl_err == eBSL_success)
                  {
                      __delay_cycles(20000); //allow target deal with the packet send before next packet
                      SetPC(start_address);
                  }
                  else
                      P4OUT |= BIT6;// error
               }
               else
               {
                 P4OUT |= BIT6;     // error
               }
	      }
	     }
        __delay_cycles(4000);
	}
}


void BSP_configureMCU(void)
{
    // LED
    P1OUT = 0;                           // Clear P1 output latch for a defined power-on state
    P1DIR |= BIT0;                            // Set P1.0 to output direction
    P3OUT = 0;
    P3DIR |= BIT6;                            // Set P1.0 to output direction

    P4OUT |= BIT5;                             // Pull-up resistor on P1.1
    P4REN = BIT5;                             // Select pull-up mode for P1.1
    P4DIR &= ~BIT5;
    // RST TEST Control GPIO
    P1OUT |= BIT3|BIT5;
    P1DIR |= BIT3|BIT4|BIT5;                            // Set P1.0 to output direction
    //Button detection
    P4OUT &= ~BIT6;
    P4DIR |= BIT6;
    PJSEL0 = BIT4 | BIT5;                     // For XT1
    // Disable the GPIO power-on default high-impedance mode to activate
    // previously configured port settings
    PM5CTL0 &= ~LOCKLPM5;

    // Startup clock system with max DCO setting ~8MHz
    CSCTL0_H = CSKEY >> 8;                    // Unlock clock registers
    CSCTL1 = DCOFSEL_3 | DCORSEL;             // Set DCO to 8MHz
    CSCTL2 = SELA__LFXTCLK | SELS__DCOCLK | SELM__DCOCLK;
    CSCTL3 = DIVA__1 | DIVS__1 | DIVM__1;     // Set all dividers
    CSCTL4 &= ~LFXTOFF;
    do
    {
      CSCTL5 &= ~LFXTOFFG;                    // Clear XT1 fault flag
      SFRIFG1 &= ~OFIFG;
    }while (SFRIFG1&OFIFG);                   // Test oscillator fault flag
    CSCTL0_H = 0;                             // Lock CS registers

}

void UART_Init(void)
{
    P2SEL1 = BIT5 + BIT6;
    P2SEL0 &= ~(BIT5 + BIT6);

    // Configure USCI_A0 for UART mode
    UCA1CTLW0 = UCSWRST;                      // Put eUSCI in reset
    UCA1CTLW0 |= UCSSEL__SMCLK| UCPEN | UCPAR;               // CLK = SMCLK  an even parity, and 1 stop bit
    // Baud Rate calculation
    // 8000000/(16*9600) = 52.083
    // Fractional portion = 0.083
    // User's Guide Table 21-4: UCBRSx = 0x04
    // UCBRFx = int ( (52.083-52)*16) = 1
    UCA1BR0 = 52;                             // 8000000/16/9600
    UCA1BR1 = 0x00;
    UCA1MCTLW |= UCOS16  | (0x49 << 1) |  UCBRF_1;
    UCA1CTLW0 &= ~UCSWRST;                    // Initialize eUSCI
   // UCA0IE |= UCRXIE;                         // Enable USCI_A0 RX interrupt

}

/*
 * Toggle the LEDs to show we are going to BSL the target
 */
void ToggleLeds(void)
{
    uint8_t ui8Count = 2;
    while(--ui8Count)
    {
     P1OUT &= ~BIT0;
     __delay_cycles(2000000);
     P1OUT |= BIT0;
    __delay_cycles(2000000);
    }
    P1OUT &= ~BIT0;
}

uint8_t* App_start_address(uint32_t * Addr_array, uint32_t *Size_array, uint8_t ** DataPtr_Array, \
                                                           uint8_t num_arrays)
{
    uint16_t i;
    uint8_t* res=0;
    for (i = 0; i < num_arrays; i ++)
    {
        // Check if address is defined by application image
        if (0xFF3E == (Addr_array[i] + Size_array[i]) )
        {
            res = DataPtr_Array[i] + (0xFF3C - Addr_array[i]);
            break;
        }
    }
    return res;
}

