/* USER CODE BEGIN Header */
/**
  ******************************************************************************
  * @file           : main.c
  * @brief          : Main program body
  ******************************************************************************
  ** This notice applies to any and all portions of this file
  * that are not between comment pairs USER CODE BEGIN and
  * USER CODE END. Other portions of this file, whether 
  * inserted by the user or by software development tools
  * are owned by their respective copyright owners.
  *
  * COPYRIGHT(c) 2019 STMicroelectronics
  *
  * Redistribution and use in source and binary forms, with or without modification,
  * are permitted provided that the following conditions are met:
  *   1. Redistributions of source code must retain the above copyright notice,
  *      this list of conditions and the following disclaimer.
  *   2. 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.
  *   3. Neither the name of STMicroelectronics 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 HOLDER 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.
  *
  ******************************************************************************
  */
/* USER CODE END Header */

/* Includes ------------------------------------------------------------------*/
#include "main.h"

/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */

/* USER CODE END Includes */

/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN PTD */

/* USER CODE END PTD */

/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */

/* USER CODE END PD */

/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM */

/* USER CODE END PM */

/* Private variables ---------------------------------------------------------*/
TIM_HandleTypeDef htim7;

UART_HandleTypeDef huart1;

/* USER CODE BEGIN PV */
uint8_t ring_buffer[255];
uint32_t ring_header = 0;
uint32_t ring_tail = 0;



volatile uint32_t UartTimerCnt = 0;
volatile uint32_t LedTimerCnt = 0;
volatile uint32_t FirmwareTimerCnt = 0;

volatile uint8_t rx3_data[1] = {0,};

#define FirmwareUpdataAck  0x11
#define FirmwareUpdataNak  0x22


/* USER CODE END PV */

/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
static void MX_GPIO_Init(void);
static void MX_USART1_UART_Init(void);
static void MX_TIM7_Init(void);
static void MX_NVIC_Init(void);
/* USER CODE BEGIN PFP */
void Uart1_Data_Send(uint8_t* data,uint8_t size);
/* USER CODE END PFP */

/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */



void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart)
{
    if(huart->Instance == USART1)//RGB Comunication 
    {
        ring_buffer[ring_header] = rx3_data[0];
        if(++ring_header>=100){ ring_header = 0; }

        HAL_UART_Receive_IT(&huart1,&rx3_data[0],1);
        
    }

    
}
void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim)
{

    if(htim->Instance == TIM7){
        UartTimerCnt++;
        LedTimerCnt++;
        FirmwareTimerCnt++;
    }
}


void Uart1_Data_Send(uint8_t* data,uint8_t size){
    HAL_UART_Transmit(&huart1, data,size, 10);
}

int _write (int file, uint8_t *ptr, uint16_t len) 
{
    HAL_UART_Transmit (&huart1, ptr, len, 10);
    return len;
}
#define StartAddr  ((uint32_t)0x08004000)

#if 1 // PYJ.2019.03.19_BEGIN -- 

#define FLASH_USER_START_ADDR   StartAddr   /* Start @ of user Flash area */
#define FLASH_USER_END_ADDR     StartAddr + ((uint32_t)0x000FFFF)   /* End @ of user Flash area */
uint32_t Address = StartAddr;

uint8_t Flash_RGB_Data_Write(uint8_t* data){
    uint16_t Firmdata = 0;
    uint8_t ret = 0;
    for(uint8_t i = 0; i < data[bluecell_length] - 2; i+=2){
        Firmdata  = ((data[(bluecell_length + 1) + i]) & 0x00FF);
        Firmdata  += ((data[(bluecell_length + 1) + (i + 1)] << 8) & 0xFF00);
        if(HAL_FLASH_Program(FLASH_TYPEPROGRAM_HALFWORD,Address ,   (uint16_t)Firmdata) != HAL_OK){
            printf("HAL NOT OK \n");
            ret = 1;
        }
        Address += 2;
    }
    return ret;
}
uint8_t flashinit = 0;
uint8_t Flash_write(uint8_t* data) // ?¡°¡Æe¢¬¡Æi?¡§???
{
   
    /*Variable used for Erase procedure*/
    static FLASH_EraseInitTypeDef EraseInitStruct;
    static uint32_t PAGEError = 0;
    uint8_t ret = 0;
    /* Fill EraseInit structure*/
    EraseInitStruct.TypeErase   = FLASH_TYPEERASE_PAGES;
    EraseInitStruct.PageAddress = FLASH_USER_START_ADDR;
    EraseInitStruct.NbPages     = (FLASH_USER_END_ADDR - FLASH_USER_START_ADDR) / FLASH_PAGE_SIZE;

    __HAL_RCC_TIM7_CLK_DISABLE(); // e¡×¢´i?¢¬????¢¥e¡§¢¬e?? ???i¡×???¨Ï?????¢´
    HAL_FLASH_Unlock(); // lock ??e¢¬?
    if(flashinit == 0){
        flashinit= 1;
        //FLASH_PageErase(StartAddr);
        if (HAL_FLASHEx_Erase(&EraseInitStruct, &PAGEError) != HAL_OK){
            printf("Erase Failed \r\n");
        }
    }
    ret = Flash_RGB_Data_Write(&data[bluecell_stx]);
    HAL_FLASH_Lock(); // lock ???e¡¤¢¬e¢¬¡Æ
    __HAL_RCC_TIM7_CLK_ENABLE(); // e¡×¢´i?¢¬????¢¥e¡§¢¬e?? ??¡þ??©«??¡®??¨Ï?????¢´
    return ret;

}
void Flash_InitRead(void) // ?¡°¡Æe¢¬¡Æi?¡§???
{
    uint32_t  Address = 0;
    Address = StartAddr;
    for(uint32_t i = 0; i < 16; i++ ){
        printf("%08x : %02X \n",Address ,*(uint8_t*)Address);
        Address++;
    }
}
typedef void (*fptr)(void);
fptr jump_to_app;
uint32_t jump_addr;
void Jump_App(void){
    __HAL_RCC_TIM7_CLK_DISABLE(); // e¡×¢´i?¢¬????¢¥e¡§¢¬e?? ???i¡×???¨Ï?????¢´
    printf("boot loader start\n");               //e¨Ï¡±i?¢¬i¡×¢æ i¢Ò©«e?¡Í
    jump_addr = *(__IO uint32_t*) (APPLICATION_ADDRESS + 4);
    jump_to_app = (fptr) jump_addr;
    
    /* init user app's sp */
    printf("jump!\n");
    __set_MSP(*(__IO uint32_t*) APPLICATION_ADDRESS);
    jump_to_app();
}
void FirmwareUpdateStart(uint8_t* data){
    uint8_t ret = 0,crccheck = 0;
    uint8_t tempdata[5] = {0xbe,FirmwareUpdataAck,0x02,0,0xbe};
    crccheck = STH30_CheckCrc(&data[bluecell_type],data[bluecell_length],data[data[bluecell_length] + 1]);
    if(crccheck == NO_ERROR){
        tempdata[bluecell_type] = FirmwareUpdataAck;
        if(data[bluecell_type] == 0xDD || data[bluecell_type] == 0xEE)//Start Firmware byte
            ret = Flash_write(&data[0]);
        if(ret == 1)
            tempdata[bluecell_type] = FirmwareUpdataNak;
    }else{
        for(uint8_t i = 0; i < data[bluecell_length] + 3; i++)
            printf("%02x ",data[i]);
        printf("Check Sum error \n");
        tempdata[bluecell_type] = FirmwareUpdataNak;
    }
    tempdata[bluecell_crc] = STH30_CreateCrc(&tempdata[bluecell_type],tempdata[bluecell_length]);
    if(data[bluecell_type] != 0xEE && data[bluecell_type] != RGB_Reset){
        Uart1_Data_Send(&tempdata[bluecell_stx],tempdata[bluecell_length] + 3); 
    }
    if(data[bluecell_type] == 0xEE)
        printf("update Complete \n");
}

#endif // PYJ.2019.03.19_END -- 
typedef  void (*pFunction)(void);
pFunction JumpToApplication;
uint32_t JumpAddress;
uint32_t FlashProtection = 0;

/* USER CODE END 0 */

/**
  * @brief  The application entry point.
  * @retval int
  */
int main(void)
{
  /* USER CODE BEGIN 1 */
  uint8_t data[255] = {0,};
  uint8_t bootdata[5] = {0xbe,RGB_BootStart,0x02,0,0xeb};
  uint8_t cnt = 0;
  uint8_t uartrecv = 0;
  /* USER CODE END 1 */

  /* MCU Configuration--------------------------------------------------------*/

  /* Reset of all peripherals, Initializes the Flash interface and the Systick. */
  HAL_Init();

  /* USER CODE BEGIN Init */

  /* USER CODE END Init */

  /* Configure the system clock */
  SystemClock_Config();

  /* USER CODE BEGIN SysInit */

  /* USER CODE END SysInit */

  /* Initialize all configured peripherals */
  MX_GPIO_Init();
  MX_USART1_UART_Init();
  MX_TIM7_Init();

  /* Initialize interrupts */
  MX_NVIC_Init();
  /* USER CODE BEGIN 2 */
  HAL_TIM_Base_Start_IT(&htim7);
  HAL_UART_Receive_IT(&huart1, &rx3_data[0],1);
  setbuf(stdout, NULL); // \n ?i¢¯¨öi¢¯¨ö?i¢¯¨öi¢¯¨ö?i¢¯¨öi¢¯¨ö, printf i¢¯???????i¢¯¨öi¢¯¨ö?i¢¯¨öi¢¯¨öi¢¯?????? ?i¢¯¨öi¢¯¨ö?i¢¯¨öi¢¯¨ö?i¢¯¨öi¢¯¨ö  
#if 1 // PYJ.2019.03.04_BEGIN -- 
  printf("****************************************\r\n");
  printf("RGB Project\r\n");
  printf("Build at %s %s\r\n", __DATE__, __TIME__);
  printf("Copyright (c) 2019. BLUECELL\r\n");
  printf("****************************************\r\n");
#endif // PYJ.2019.03.04_END -- 
//RGB_Sensor_PowerOnOff(0);
  FLASH_If_Init();
  Flash_InitRead();
//Flash_InitRead();
  bootdata[bluecell_crc] = STH30_CreateCrc(&bootdata[bluecell_type],bootdata[bluecell_length]);
  HAL_Delay(100);
  Uart1_Data_Send(&bootdata[bluecell_stx],bootdata[bluecell_length] + 3); 

  /* USER CODE END 2 */
  /* Infinite loop */
  /* USER CODE BEGIN WHILE */
  while (1)
  {
          /* Test if user code is programmed starting from address "APPLICATION_ADDRESS" */
      if(FirmwareTimerCnt > 3000){
          Jump_App();
      }
     if(ring_tail != ring_header){ // <------- 
        data[cnt++] = ring_buffer[ring_tail++];
        if(ring_tail >= 100){ ring_tail = 0; }
        UartTimerCnt = 0;
        uartrecv = 1;
    }
    if(uartrecv == 1 && UartTimerCnt > 100){
        FirmwareUpdateStart(&data[0]);
        memset(&data[0],0,100);
        cnt = 0;
        uartrecv = 0;
        FirmwareTimerCnt = 0;
    }
    if(LedTimerCnt > 500){
        HAL_GPIO_TogglePin(GPIOC,GPIO_PIN_15);
        LedTimerCnt = 0;
    }
    /* USER CODE END WHILE */
    /* USER CODE BEGIN 3 */
  }
  /* USER CODE END 3 */
}

/**
  * @brief System Clock Configuration
  * @retval None
  */
void SystemClock_Config(void)
{
  RCC_OscInitTypeDef RCC_OscInitStruct = {0};
  RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};

  /**Initializes the CPU, AHB and APB busses clocks 
  */
  RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI;
  RCC_OscInitStruct.HSIState = RCC_HSI_ON;
  RCC_OscInitStruct.HSICalibrationValue = RCC_HSICALIBRATION_DEFAULT;
  RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
  RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSI_DIV2;
  RCC_OscInitStruct.PLL.PLLMUL = RCC_PLL_MUL4;
  if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
  {
    Error_Handler();
  }
  /**Initializes the CPU, AHB and APB busses clocks 
  */
  RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
                              |RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;
  RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
  RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
  RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV2;
  RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;

  if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_0) != HAL_OK)
  {
    Error_Handler();
  }
}

/**
  * @brief NVIC Configuration.
  * @retval None
  */
static void MX_NVIC_Init(void)
{
  /* USART1_IRQn interrupt configuration */
  HAL_NVIC_SetPriority(USART1_IRQn, 0, 0);
  HAL_NVIC_EnableIRQ(USART1_IRQn);
  /* TIM7_IRQn interrupt configuration */
  HAL_NVIC_SetPriority(TIM7_IRQn, 0, 0);
  HAL_NVIC_EnableIRQ(TIM7_IRQn);
}

/**
  * @brief TIM7 Initialization Function
  * @param None
  * @retval None
  */
static void MX_TIM7_Init(void)
{

  /* USER CODE BEGIN TIM7_Init 0 */

  /* USER CODE END TIM7_Init 0 */

  TIM_MasterConfigTypeDef sMasterConfig = {0};

  /* USER CODE BEGIN TIM7_Init 1 */

  /* USER CODE END TIM7_Init 1 */
  htim7.Instance = TIM7;
  htim7.Init.Prescaler = 1600-1;
  htim7.Init.CounterMode = TIM_COUNTERMODE_UP;
  htim7.Init.Period = 10-1;
  htim7.Init.AutoReloadPreload = TIM_AUTORELOAD_PRELOAD_DISABLE;
  if (HAL_TIM_Base_Init(&htim7) != HAL_OK)
  {
    Error_Handler();
  }
  sMasterConfig.MasterOutputTrigger = TIM_TRGO_RESET;
  sMasterConfig.MasterSlaveMode = TIM_MASTERSLAVEMODE_DISABLE;
  if (HAL_TIMEx_MasterConfigSynchronization(&htim7, &sMasterConfig) != HAL_OK)
  {
    Error_Handler();
  }
  /* USER CODE BEGIN TIM7_Init 2 */

  /* USER CODE END TIM7_Init 2 */

}

/**
  * @brief USART1 Initialization Function
  * @param None
  * @retval None
  */
static void MX_USART1_UART_Init(void)
{

  /* USER CODE BEGIN USART1_Init 0 */

  /* USER CODE END USART1_Init 0 */

  /* USER CODE BEGIN USART1_Init 1 */

  /* USER CODE END USART1_Init 1 */
  huart1.Instance = USART1;
  huart1.Init.BaudRate = 115200;
  huart1.Init.WordLength = UART_WORDLENGTH_8B;
  huart1.Init.StopBits = UART_STOPBITS_1;
  huart1.Init.Parity = UART_PARITY_NONE;
  huart1.Init.Mode = UART_MODE_TX_RX;
  huart1.Init.HwFlowCtl = UART_HWCONTROL_NONE;
  huart1.Init.OverSampling = UART_OVERSAMPLING_16;
  if (HAL_UART_Init(&huart1) != HAL_OK)
  {
    Error_Handler();
  }
  /* USER CODE BEGIN USART1_Init 2 */

  /* USER CODE END USART1_Init 2 */

}

/**
  * @brief GPIO Initialization Function
  * @param None
  * @retval None
  */
static void MX_GPIO_Init(void)
{
  GPIO_InitTypeDef GPIO_InitStruct = {0};

  /* GPIO Ports Clock Enable */
  __HAL_RCC_GPIOC_CLK_ENABLE();
  __HAL_RCC_GPIOA_CLK_ENABLE();

  /*Configure GPIO pin Output Level */
  HAL_GPIO_WritePin(Boot_LD_GPIO_Port, Boot_LD_Pin, GPIO_PIN_RESET);

  /*Configure GPIO pin : Boot_LD_Pin */
  GPIO_InitStruct.Pin = Boot_LD_Pin;
  GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
  GPIO_InitStruct.Pull = GPIO_NOPULL;
  GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
  HAL_GPIO_Init(Boot_LD_GPIO_Port, &GPIO_InitStruct);

}

/* USER CODE BEGIN 4 */

/* USER CODE END 4 */

/**
  * @brief  This function is executed in case of error occurrence.
  * @retval None
  */
void Error_Handler(void)
{
  /* USER CODE BEGIN Error_Handler_Debug */
  /* User can add his own implementation to report the HAL error return state */

  /* USER CODE END Error_Handler_Debug */
}

#ifdef  USE_FULL_ASSERT
/**
  * @brief  Reports the name of the source file and the source line number
  *         where the assert_param error has occurred.
  * @param  file: pointer to the source file name
  * @param  line: assert_param error line source number
  * @retval None
  */
void assert_failed(uint8_t *file, uint32_t line)
{ 
  /* USER CODE BEGIN 6 */
  /* User can add his own implementation to report the file name and line number,
     tex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
  /* USER CODE END 6 */
}
#endif /* USE_FULL_ASSERT */

/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
