/******************************************************************************
 * @file     download.c
 * @brief    download an image to internal Flash
 * @version  V4.0.0
 * @date     30-July-2026
 *
 * @note
 * Copyright (C) 2022 Spintrol Electronic Technology (Shanghai) Co., Ltd.. All rights reserved.
 *
 * @attention
 * THIS SOFTWARE JUST PROVIDES CUSTOMERS WITH CODING INFORMATION REGARDING
 * THEIR PRODUCTS, WHICH AIMS AT SAVING TIME FOR THEM. SPINTROL SHALL NOT BE
 * LIABLE FOR THE USE OF THE SOFTWARE. SPINTROL DOES NOT GUARANTEE THE
 * CORRECTNESS OF THIS SOFTWARE AND RESERVES THE RIGHT TO MODIFY THE SOFTWARE
 * WITHOUT NOTIFICATION.
 *
 ******************************************************************************/

#include "ymodem.h"
#include "common.h"
#include <stdio.h>


extern uint8_t au8FileName[FILE_NAME_LENGTH];




/******************************************************************************
 * @brief      Download a file via serial port
 *
 * @param[in]  none
 *
 * @return     none
 *
 ******************************************************************************/
void SerialDownload(void)
{
    int32_t Size = 0;

#if RS485_INTERFACE_ENABLED > 0
    /* RS485 Tx Enable */
    GPIO_WritePin(RS485_CONTROL_PIN, GPIO_LEVEL_LOW);
#endif

    printf("Waiting for the file to be sent ... (press 'a' to abort)\n\r");

#if RS485_INTERFACE_ENABLED > 0
    /* RS485 Rx Enable */
    GPIO_WritePin(RS485_CONTROL_PIN, GPIO_LEVEL_HIGH);
#endif

    Size = YModem_Receive();

#if RS485_INTERFACE_ENABLED > 0
    /* RS485 Tx Enable */
    GPIO_WritePin(RS485_CONTROL_PIN, GPIO_LEVEL_LOW);
#endif

    if (Size > 0)
    {
        printf("\n\n\r Programming Completed Successfully!\n\r--------------------------------\r\n");
        printf("Name: %s\n\r", au8FileName);
        printf("Size: %d Bytes\r\n", Size);
        printf("-------------------\n");
    }
    else if (Size == -1)
    {
        printf("\n\n\rThe image size is higher than the allowed space memory!\n\r");
    }
    else if (Size == -2)
    {
        printf("\n\n\rValidation failed!\n\r");
    }
    else if (Size == -3)
    {
        printf("\r\n\nAborted by user.\n\r");
    }
    else
    {
        printf("\n\rFailed to receive the file!\n\r");
    }

#if RS485_INTERFACE_ENABLED > 0
    /* RS485 Rx Enable */
    GPIO_WritePin(RS485_CONTROL_PIN, GPIO_LEVEL_HIGH);
#endif
}


/******************* Copyright (C) 2022 Spintrol Electronic Technology (Shanghai) Co., Ltd. ***** END OF FILE ****/
