/*
 * Copyright (C) 2016 Texas Instruments Incorporated - http://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.
 *
*/

//******************************************************************************
// Version history:
// 1.0 07/17             Initial version. (Nima Eskandari)
// 1.1 07/17             Added Comments. (Nima Eskandari)
//----------------------------------------------------------------------------
//   Designed 2017 by Texas Instruments
//
//   Nima Eskandari
//   Texas Instruments Inc.
//   August 2017
//   Built with CCS Version: Code Composer Studio v7
//******************************************************************************

#include <stdio.h>
#include <stdbool.h>
#include <stddef.h>
#include <config.h>
#include <utils.h>
#include <uart_if.h>
#include <bsl.h>

#include <debug.h>

//*****************************************************************************
// MSP430 Image to use ********************************************************
//*****************************************************************************

#include <image/msp430fr_image.h>

//*****************************************************************************
// Program the MSP430 with the specified image ********************************
//*****************************************************************************
//*****************************************************************************
// Program the MSP430FR with the specified image ******************************
//*****************************************************************************
bool ProgramMSP430()
{
    bool numberOfErrors = 0;
    bool result = true;
    uint16_t section = 0;
    uint8_t * framStartOfData = 0;

    for (section = 0; section < fram_sections; section++)
    {
        Debug_UART_printStringWithNumber("\r\n\r\n****Section: %d****\r\n\r\n", section);
        Debug_UART_printStringWithNumber("Address: 0x%X\r\n", fram_address[section]);
        if (section == 0)
        {
            framStartOfData = fram;
        }
        else
        {
            framStartOfData = framStartOfData + fram_length_of_sections[section - 1];
        }


        result = WriteLargeDataToMemory(fram_address[section], fram_length_of_sections[section], framStartOfData);
        if (!result)
        {
            Debug_UART_printString("Write Large Data To Memory failed\r\n");
            return false;
        }
        else
        {
            Debug_UART_printString("Write Large Data To Memory successful\r\n");
        }

    }

    if (numberOfErrors != 0)
    {
        return false;
    }
    return true;
}

#define MAX_RETRY   5

int BSL_main()
{
    bool result = true;
    UART_Initialize();
    uint8_t retry = MAX_RETRY;

    while (retry)
    {
        Debug_UART_printString("\r\n\r\n*****New Attempt*****\r\n\r\n");
        BSLEntrySequence();
        MsDelay(100);
        result = WritePasswordDefault();
        if (!result)
        {
            Debug_UART_printString("Write password failed\r\n");
            retry --;
            continue;
        }
        Debug_UART_printString("Write Password was successful\r\n");
        uint8_t deviceIDBytes[2] = {0};
        result = ReadMemory(0x1A04, 2, deviceIDBytes);
        if (!result)
        {
            Debug_UART_printString("Device ID read failed\r\n");
            retry --;
            continue;
        }
        uint16_t deviceID = deviceIDBytes[0] << 8 | deviceIDBytes[1];
        Debug_UART_printStringWithNumber("Device ID: 0x%X\r\n", deviceID);

        result = ProgramMSP430();
        if (!result)
        {
            Debug_UART_printString("\r\nMSP430 programming failed\r\n");
            retry --;
            continue;
        }

        Debug_UART_printString("\r\nMSP430 programmed successfully\r\n");
        UART_Close();
        Reset();
        Debug_UART_printString("Device is reset\r\n");
        return 0;
    }

    UART_Close();
    Debug_UART_printString("Max retries exceeded\r\n");
    return 1;
}


