/* 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,p 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 htim6;

UART_HandleTypeDef huart3;

/* USER CODE BEGIN PV */
unsigned char ring_buffer[150];
unsigned int ring_header = 0;
unsigned int ring_tail = 0;
uint8_t rx1_data[1];



uint8_t UartDataisReved;
uint8_t RGB_SensorIDAutoset = 0;
volatile uint32_t UartTimerCnt = 0;
volatile uint32_t LedTimerCnt = 0;
volatile uint8_t rx3_data[1] = {0,};
uint8_t buf[buf_size] = {0,};

uint8_t MyControllerID = 0;
uint8_t  SensorID = 1;

/* USER CODE END PV */

/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
static void MX_GPIO_Init(void);
static void MX_TIM6_Init(void);
static void MX_USART3_UART_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] = rx1_data[0];
        ring_header = ring_header +1;
        if(ring_header>=100){ ring_header = 0; }

        HAL_UART_Receive_IT(&huart3,&rx1_data[0],1);
    }

    
}
void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim)
{

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


void Uart3_Data_Send(uint8_t* data,uint8_t size){
    HAL_UART_Transmit(&huart3, data,size, 10); 
}

int _write (int file, uint8_t *ptr, uint16_t len) 
{
    HAL_UART_Transmit (&huart3, ptr, len, 10); 
    return len;
}
void Uart_dataCheck(uint8_t* cnt){

    etError crccheck = 0;
#if 0
    for(uint8_t i = 0; i < (* cnt); i++){
        printf("%02x ",buf[i]);
    }
        printf("\r\n");
#endif  

    crccheck = STH30_CheckCrc(&buf[blucell_type],buf[blucell_length],buf[buf[blucell_length] + 1]);
    if(crccheck == CHECKSUM_ERROR){
        for(uint8_t i = 0; i < (*cnt); i++){
            printf("%02x ",buf[i]);
        }
        printf("Original CRC : %02x RecvCRC : %02x \r\n",crccheck,buf[buf[blucell_length] + 1]);
    }
    else if(crccheck == NO_ERROR){
        RGB_Controller_Func(&buf[blucell_stx]);
    }
    else{
         printf("What Happen?\r\n");
        /*NOP*/
    }

    *cnt = 0;
    
    memset(buf,0x00,buf_size);
}
#define StartAddr  ((uint32_t)0x08030000)

#if 1 // PYJ.2019.03.19_BEGIN -- 
//----------------------------------------------------
#define FLASH_USER  StartAddr
#define START_ADDR  FLASH_USER
#define END_ADDR    FLASH_USER + 262144 // 256K
//----------------------------------------------------
#if 0 // PYJ.2019.03.20_BEGIN -- 
void test_write() // ?摪旮绊暔?垬
{

    __HAL_RCC_TIM7_CLK_DISABLE(); // 毵れ澑???澊毹鸽?? ?爼歆??暕?媹?嫟
    uint32_t  Address = 0;
    Address = StartAddr;
//    printf("================First============ \r\n");

//    for(uint8_t i=0;i<16;i++)
//    {
//        printf("%08x: %X\r\n", Address, *(uint32_t*)Address);
//        Address += 4;
//    }  

//    HAL_FLASH_Unlock(); // lock ??旮?
//    HAL_FLASH_Program(FLASH_TYPEPROGRAM_WORD, START_ADDR, (uint32_t)0x12345678); //test
//    HAL_FLASH_Lock(); // lock ?灎攴戈赴
//    __HAL_RCC_TIM7_CLK_ENABLE(); // 毵れ澑???澊毹鸽?? ?灛?嫓?瀾?暕?媹?嫟
    Address = StartAddr;
    printf("================Second============ \r\n");

   //while(Address < 0x0803FFFF)
   for(uint16_t i = 0; i<37273 ; i++)
    {
        printf("%02X", *(uint8_t*)Address);
        Address ++;
    }     
    printf("%08x:",Address);
}
#endif // PYJ.2019.03.20_END -- 

#define DATA_16_1                 ((uint32_t)0x1234)
#define DATA_16_2                 ((uint32_t)0x5678)


#if 1 // PYJ.2019.03.20_BEGIN -- 
void test_read(void) // ?摪旮绊暔?垬
{
    uint32_t Address = 0x08000000;
    uint8_t aa = 0;
    for(uint32_t i = Address; i <= Address + 0x35d8; i++ ){
        printf("%02X ",*(uint8_t*)i);
        aa++;
        if(aa > 15){
            printf("\n");
            aa= 0;
        }
    }
        
}
#endif // PYJ.2019.03.20_END -- 
#define ADDR_FLASH_PAGE_TEST   ((uint32_t)0x08030000) /* Base @ of Page 127, 1 Kbytes */

#define FLASH_USER_START_ADDR   ADDR_FLASH_PAGE_TEST   /* Start @ of user Flash area */
#define FLASH_USER_END_ADDR     ADDR_FLASH_PAGE_TEST + ((uint32_t)0x0000FFFF)   /* End @ of user Flash area */
void Flash_RGB_Data_Write(uint32_t Addr,uint8_t* data){

    uint16_t temp_Red = 0,temp_Green = 0,temp_Blue = 0,temp_ret1 = 0,temp_ret2 = 0;

    temp_Red  = ((data[blucell_red_H] << 8)   |data[blucell_red_L]);     //R
    temp_Green= ((data[blucell_green_H] << 8) |data[blucell_green_L]);  //G
    temp_Blue = ((data[blucell_blue_H] << 8)  |data[blucell_blue_L]);   //B

    HAL_FLASH_Program(FLASH_TYPEPROGRAM_HALFWORD,Addr + 0 ,   (uint16_t)temp_Red);
    HAL_FLASH_Program(FLASH_TYPEPROGRAM_HALFWORD,Addr + 2 ,   (uint16_t)temp_Green);
    HAL_FLASH_Program(FLASH_TYPEPROGRAM_HALFWORD,Addr + 4 ,   (uint16_t)temp_Blue);

}
void Flash_write(uint8_t* data) // ?摪旮绊暔?垬
{
   
    /*Variable used for Erase procedure*/
    static FLASH_EraseInitTypeDef EraseInitStruct;
    uint32_t Address = 0, PAGEError = 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;
     Address = START_ADDR;

    __HAL_RCC_TIM7_CLK_DISABLE(); // 毵れ澑???澊毹鸽?? ?爼歆??暕?媹?嫟
    HAL_FLASH_Unlock(); // lock ??旮?
//    if (HAL_FLASHEx_Erase(&EraseInitStruct, &PAGEError) != HAL_OK){
//        printf("Erase Failed \r\n");
//    }else{
//        printf("Erase Success \r\n");
//    }
  
    switch(data[blucell_dstid]){
        case 1:
            Address += 0;
            break;
        case 2:
            Address += 6;
            break;
        case 3:
            Address += 12;
            break;
        case 4:
            Address += 18;
            break;
        case 5:
            Address += 24;
            break;
        case 6:
            Address += 30;       
            break;
        case 7:
            Address += 36; 
            break;
        case 8:
            Address += 42;    
            break;            

    }
    Flash_RGB_Data_Write(Address,&data[blucell_stx]);
    HAL_FLASH_Lock(); // lock ?灎攴戈赴
    __HAL_RCC_TIM7_CLK_ENABLE(); // 毵れ澑???澊毹鸽?? ?灛?嫓?瀾?暕?媹?嫟

}
void Flash_InitRead(void) // ?摪旮绊暔?垬
{
    uint32_t  Address = 0;
    Address = StartAddr;
    for(uint8_t i = 1; i <= 8; i++ ){
        printf("%08x : %04X \n",Address ,*(uint16_t*)Address);
        Address += 2;
        printf("%08x : %04X \n",Address ,*(uint16_t*)Address);
        Address += 2;        
        printf("%08x : %04X \n",Address ,*(uint16_t*)Address);        
        Address += 2;
    }

}


#endif // PYJ.2019.03.19_END -- 

/* USER CODE END 0 */

/**
  * @brief  The application entry point.
  * @retval int
  */
int main(void)
{
  /* USER CODE BEGIN 1 */
  uint8_t data[100] = {0,};
  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_TIM6_Init();
  MX_USART3_UART_Init();

  /* Initialize interrupts */
  MX_NVIC_Init();
  /* USER CODE BEGIN 2 */
  HAL_TIM_Base_Start_IT(&htim6);
  HAL_UART_Receive_IT(&huart3, &rx3_data[0],1);
  setbuf(stdout, NULL); // \n ?锟斤拷?锟斤拷?锟斤拷, printf 锟???????锟斤拷?锟斤拷锟?????? ?锟斤拷?锟斤拷?锟斤拷  
#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);

  /* USER CODE END 2 */

  /* Infinite loop */
  /* USER CODE BEGIN WHILE */

  while (1)
  {

     if(ring_tail != ring_header){ // <------- 
        data[cnt++] = ring_buffer[ring_tail++];
        ring_tail = ring_tail +1;
        if(ring_tail >= 100){ ring_tail = 0; }
        UartTimerCnt = 0;
        uartrecv = 1;
    }
    if(uartrecv == 1 && UartTimerCnt > 25){
        for(uint8_t i = 0; i < cnt; i++)
        printf("%02x",data[i]);

        memset(&data[0],0,100);
        cnt = 0;
        uartrecv = 0;
    }
    if(LedTimerCnt > 500){
        HAL_GPIO_TogglePin(GPIOC,GPIO_PIN_15);
        LedTimerCnt = 0;
    }
    HAL_Delay(1);
    /* 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_HSE;
  RCC_OscInitStruct.HSEState = RCC_HSE_ON;
  RCC_OscInitStruct.HSEPredivValue = RCC_HSE_PREDIV_DIV1;
  RCC_OscInitStruct.HSIState = RCC_HSI_ON;
  RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
  RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE;
  RCC_OscInitStruct.PLL.PLLMUL = RCC_PLL_MUL2;
  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)
{
  /* TIM6_IRQn interrupt configuration */
  HAL_NVIC_SetPriority(TIM6_IRQn, 0, 0);
  HAL_NVIC_EnableIRQ(TIM6_IRQn);
  /* USART3_IRQn interrupt configuration */
  HAL_NVIC_SetPriority(USART3_IRQn, 0, 0);
  HAL_NVIC_EnableIRQ(USART3_IRQn);
}

/**
  * @brief TIM6 Initialization Function
  * @param None
  * @retval None
  */
static void MX_TIM6_Init(void)
{

  /* USER CODE BEGIN TIM6_Init 0 */

  /* USER CODE END TIM6_Init 0 */

  TIM_MasterConfigTypeDef sMasterConfig = {0};

  /* USER CODE BEGIN TIM6_Init 1 */

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

  /* USER CODE END TIM6_Init 2 */

}

/**
  * @brief USART3 Initialization Function
  * @param None
  * @retval None
  */
static void MX_USART3_UART_Init(void)
{

  /* USER CODE BEGIN USART3_Init 0 */

  /* USER CODE END USART3_Init 0 */

  /* USER CODE BEGIN USART3_Init 1 */

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

  /* USER CODE END USART3_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_GPIOD_CLK_ENABLE();
  __HAL_RCC_GPIOB_CLK_ENABLE();

  /*Configure GPIO pin Output Level */
  HAL_GPIO_WritePin(GPIOC, GPIO_PIN_15, GPIO_PIN_RESET);

  /*Configure GPIO pin : PC15 */
  GPIO_InitStruct.Pin = GPIO_PIN_15;
  GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
  GPIO_InitStruct.Pull = GPIO_NOPULL;
  GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
  HAL_GPIO_Init(GPIOC, &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****/
