/**
  ******************************************************************************
  * @file    main.c
  * @author  MCU Application Team
  * @brief   Main program body
  ******************************************************************************
  * @attention
  *
  * <h2><center>&copy; Copyright (c) 2023 Puya Semiconductor Co.
  * All rights reserved.</center></h2>
  *
  * This software component is licensed by Puya under BSD 3-Clause license,
  * the "License"; You may not use this file except in compliance with the
  * License. You may obtain a copy of the License at:
  *                        opensource.org/licenses/BSD-3-Clause
  *
  ******************************************************************************
  * @attention
  *
  * <h2><center>&copy; Copyright (c) 2016 STMicroelectronics.
  * All rights reserved.</center></h2>
  *
  * This software component is licensed by ST under BSD 3-Clause license,
  * the "License"; You may not use this file except in compliance with the
  * License. You may obtain a copy of the License at:
  *                        opensource.org/licenses/BSD-3-Clause
  *
  ******************************************************************************
  */
/* Includes ------------------------------------------------------------------*/
#include "main.h"
#include "Flash_test.h"
#include "Emulated_EEPROM.h"

/* Private define ------------------------------------------------------------*/
#define FLASH_USER_START_ADDR     0x08004000

/* Private variables ---------------------------------------------------------*/
const uint32_t DATA[128] =
{
  0x01010101, 0x23456789, 0x3456789A, 0x456789AB, 0x56789ABC, 0x6789ABCD, 0x789ABCDE, 0x89ABCDEF,
  0x9ABCDEF0, 0xABCDEF01, 0xBCDEF012, 0xCDEF0123, 0xDEF01234, 0xEF012345, 0xF0123456, 0x01234567,
  0x01010101, 0x23456789, 0x3456789A, 0x456789AB, 0x56789ABC, 0x6789ABCD, 0x789ABCDE, 0x89ABCDEF,
  0x9ABCDEF0, 0xABCDEF01, 0xBCDEF012, 0xCDEF0123, 0xDEF01234, 0xEF012345, 0xF0123456, 0x01234567,
  0x23456789, 0xAAAAAAAA, 0x55555555, 0x23456789, 0xAAAAAAAA, 0x55555555, 0x23456789, 0xAAAAAAAA,
  0x23456789, 0xAAAAAAAA, 0x55555555, 0x23456789, 0xAAAAAAAA, 0x55555555, 0x23456789, 0xAAAAAAAA,
  0x23456789, 0xAAAAAAAA, 0x55555555, 0x23456789, 0xAAAAAAAA, 0x55555555, 0x23456789, 0xAAAAAAAA,
  0x23456789, 0xAAAAAAAA, 0x55555555, 0x23456789, 0xAAAAAAAA, 0x55555555, 0x23456789, 0xAAAAAAAA,
  0x01010101, 0x23456789, 0x3456789A, 0x456789AB, 0x56789ABC, 0x6789ABCD, 0x789ABCDE, 0x89ABCDEF,
  0x9ABCDEF0, 0xABCDEF01, 0xBCDEF012, 0xCDEF0123, 0xDEF01234, 0xEF012345, 0xF0123456, 0x01234567,
  0x01010101, 0x23456789, 0x3456789A, 0x456789AB, 0x56789ABC, 0x6789ABCD, 0x789ABCDE, 0x89ABCDEF,
  0x9ABCDEF0, 0xABCDEF01, 0xBCDEF012, 0xCDEF0123, 0xDEF01234, 0xEF012345, 0xF0123456, 0x01234567,
  0x23456789, 0xAAAAAAAA, 0x55555555, 0x23456789, 0xAAAAAAAA, 0x55555555, 0x23456789, 0xAAAAAAAA,
  0x23456789, 0xAAAAAAAA, 0x55555555, 0x23456789, 0xAAAAAAAA, 0x55555555, 0x23456789, 0xAAAAAAAA,
  0x23456789, 0xAAAAAAAA, 0x55555555, 0x23456789, 0xAAAAAAAA, 0x55555555, 0x23456789, 0xAAAAAAAA,
  0x23456789, 0xAAAAAAAA, 0x55555555, 0x23456789, 0xAAAAAAAA, 0x55555555, 0x23456789, 0xAAAAAAAA,
};

/* Private user code ---------------------------------------------------------*/
/* Private macro -------------------------------------------------------------*/
/* Private function prototypes -----------------------------------------------*/
static void APP_SystemClockConfig(void);
// static void APP_FlashErase(void);
// static void APP_FlashProgram(void);
// static void APP_FlashBlank(void);
// static void APP_FlashVerify(void);



// void xie_ce_shi(void);
// void ca_ce_shi(void);

/**
  * @brief  Main program.
  * @retval int
  */
int main(void)
{
  /* Reset of all peripherals, Initializes the Systick. */
  HAL_Init();
  
  /* System clock configuration */
  APP_SystemClockConfig();
  
  /* Initialize Button */
  BSP_PB_Init(BUTTON_KEY, BUTTON_MODE_GPIO);/*按键功能初始化*/
  
  /* Initialize LED */
  BSP_LED_Init(LED_GREEN); /*LED功能初始化*/

  NVS_Init();

  BSP_USART_Config();/*串口打印测试用，不调用串口不能打印*/

  // CAN_Config();
  
  BSP_LED_On(LED_GREEN);
  // printf("开始断电测试！！！！！\n\r");
  /* Wait for the button to be pressed */
  // while (BSP_PB_GetState(BUTTON_USER))
  // {
  // }

  // if (BSP_PB_GetState(BUTTON_USER))
  // {
    // Test_Flash_AppointSector_Erase(SECTOR_8_START_ADDR, 0X801FFFF);
  // }
  // Data_Create_Service();
  
  /* Unlock Flash */
  // HAL_FLASH_Unlock();

  /* Erase Flash */
  // APP_FlashErase();
  

  uint32_t zheshisha = 0;
  uint32_t addr = 0;
  static uint16_t koko[8] = {0x1111, 0x2222, 0x3333, 0x4444, 0x5555, 0x6666, 0x7777, 0x8888};
  static uint32_t laji[8] = {0};
  // static uint32_t laji[8] =
  // {
  //     0x11111111, 0x22222222, 0x33333333, 0x44444444, 0x55555555, 0x66666666, 0x77777777, 0x88888888
  // };
  // Flash_Data_PageErase(SECTOR_14_START_ADDR, 0x0801E7FFUL);

  // Flash_Data_Write(SECTOR_15_START_ADDR, koko, (8 * 2));


  // Flash_Data_Read(SECTOR_15_START_ADDR, laji, (8 * 2));

  // Flash_Data_CheckBlank(SECTOR_14_START_ADDR, 0x0801E7FFUL);

  

  // for (uint8_t j = 0; j < 4; j++)
  // {
    // for (uint8_t i = 0; i < 128; i++)
    // {
    //   zheshisha = HW32_REG(SECTOR_8_START_ADDR + addr);
    //   printf("%x\n\r" , zheshisha);
    //   addr += 4;
    // }
    // printf("shan qu %d du qu wan cheng\n\r",(11+j));
  // }

  // printf("--------------------------------------\n\r" );
  // printf("--------------------------------------\n\r" );
  /* Check Flash */
  // APP_FlashBlank();

  
  /* Program Flash */
  // APP_FlashProgram();
  // EEPROM_Write_Data(SECTOR_15_START_ADDR, koko, 8);
  // memset(koko,0,32);
  EEPROM_Init();
  // for(uint8_t i = 0; i < 202; i ++)
  // {
  //   EEPROM_Write_Data(EEPROM_BLOCK_UDS_FLAG, TestData,8);
  //   TestData[0] ++;
  // }
  
  zheshisha = 0;
  addr = 0;

  
  // for (uint8_t j = 0; j < 2; j++)
  // {
  //   for (uint8_t i = 0; i < 128; i++)
  //   {
  //     zheshisha = HW32_REG(SECTOR_14_START_ADDR + addr);
  //     printf("%x\n\r" , zheshisha);
  //     addr += 4;
  //   }
  //   printf("shan qu %d du qu wan cheng\n\r",(12+j));
  // }
  // EEPROM_Write_Data(EEPROM_BLOCK_UDS_FLAG, TestData1,8);

  

  // EEPROM_Write_Data(EEPROM_BLOCK_UDS_FLAG, TestData2,8);
  // EEPROM_Write_Data(EEPROM_BLOCK_UDS_FLAG, TestData,8);


  while(addr <= (0x0801E7FFUL - SECTOR_14_START_ADDR))
  {
    zheshisha = HW16_REG(SECTOR_14_START_ADDR + addr);
    if((zheshisha != 0xFFFF) && (zheshisha != 0x0))
    {
      printf("%x\n\r" , zheshisha);
    }
    
    addr += 2;
    if ((addr % 256) == 0U)
    {
      printf("---------------------------------\n\r");
    }
  }
  // Test_Flash_AppointAddress_Write(0x801C300, laji, 8);

  // printf("xie ru cheng gong le\n\r");
  /* Lock Flash */
  // HAL_FLASH_Lock();

  /* Verify Flash */
  // APP_FlashVerify();

  

  // zheshisha = 0;
  // addr = 0;
  // uint32_t dizhi = SECTOR_14_START_ADDR;

  // for (uint8_t j = 0; j < 40; j++)
  // {
  //   for (uint8_t i = 0; i < 64; i++)
  //   {
  //     zheshisha = HW32_REG(SECTOR_14_START_ADDR + addr);
  //     if (zheshisha != 0U)
  //     {
  //       printf("%x\n\r" , zheshisha);
  //     }
      
  //     addr += 4;
  //   }
  //   printf("page %d du qu wan cheng\n\r",(368+j));
  //   printf("zhe yi ge page de qi shi di zhi shi %x\n\r", dizhi);
  //   dizhi += 0x100U;
  // }
  
  printf("--------------- fen ge xian --------------------\n\r");
  printf("--------------- fen ge xian --------------------\n\r");
  printf("--------------- fen ge xian --------------------\n\r");

  EEPROM_Read_Data(EEPROM_BLOCK_UDS_FLAG, laji,8);
  for (uint8_t i = 0; i < 8; i++)
  {
    printf("%x\n\r" , laji[i]);
  }
  // printf("--------------- zhi xing jie shu --------------------\n\r");
  // printf("--------------- zai jian --------------------\n\r");
  // while (1)
  // {
  //   CAN_RX_Service();
  //   NVS_Test_Max_Service();
  //   CAN_TX_Service();
  // }




  // while(1)
  // {
  //   ca_ce_shi();
  //   printf("ca chu wan le！！！！！\n\r");
  //   xie_ce_shi();
  //   printf("xie wan le！！！！！\n\r");
  // }
}

/**
  * @brief  System clock configuration function
  * @param  None
  * @retval None
  */
static void APP_SystemClockConfig(void)
{
  RCC_OscInitTypeDef RCC_OscInitStruct = {0};
  RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};

  /* Oscillator configuration */
  RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE | RCC_OSCILLATORTYPE_HSI | RCC_OSCILLATORTYPE_LSI | RCC_OSCILLATORTYPE_LSE; /* Select oscillator HSE, HSI, LSI, LSE */
  RCC_OscInitStruct.HSIState = RCC_HSI_ON;                          /* Enable HSI */
  RCC_OscInitStruct.HSIDiv = RCC_HSI_DIV1;                          /* HSI 1 frequency division */
  RCC_OscInitStruct.HSICalibrationValue = RCC_HSICALIBRATION_8MHz;  /* Configure HSI clock 8MHz */
  RCC_OscInitStruct.HSEState = RCC_HSE_OFF;                         /* Close HSE*/
  /*RCC_OscInitStruct.HSEFreq = RCC_HSE_16_32MHz;*/
  RCC_OscInitStruct.LSIState = RCC_LSI_OFF;                         /* Close LSI */
  RCC_OscInitStruct.LSEState = RCC_LSE_OFF;                         /* Close LSE */
  /*RCC_OscInitStruct.LSEDriver = RCC_LSEDRIVE_MEDIUM;*/
  RCC_OscInitStruct.PLL.PLLState = RCC_PLL_OFF;                     /* Close PLL */
  /*RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_NONE;*/
  /*RCC_OscInitStruct.PLL.PLLMUL = RCC_PLL_MUL2;*/
  /* Configure oscillator */
  if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
  {
    APP_ErrorHandler();
  }

  /* Clock source configuration */
  RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK | RCC_CLOCKTYPE_SYSCLK | RCC_CLOCKTYPE_PCLK1; /* Choose to configure clock HCLK, SYSCLK, PCLK1 */
  RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_HSISYS; /* Select HSISYS as the system clock */
  RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;     /* AHB clock 1 division */
  RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV1;      /* APB clock 1 division */
  /* Configure clock source */
  if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_0) != HAL_OK)
  {
    APP_ErrorHandler();
  }
}


/**
  * @brief  Flash Erase
  * @param  None
  * @retval None
  */
// static void APP_FlashErase(void)
// {
//   uint32_t PAGEError = 0;

//   uint32_t jojojo = 0U;

//   FLASH_EraseInitTypeDef EraseInitStruct = {0};

//   EraseInitStruct.TypeErase   = FLASH_TYPEERASE_PAGEERASE;        /* Erase type FLASH_TYPEERASE_PAGEERASE=Page erase, FLASH_TYPEERASE_SECTORERASE=Sector Erase */
//   EraseInitStruct.PageAddress = FLASH_USER_START_ADDR;            /* Erase Start Address */
//   EraseInitStruct.NbPages  = sizeof(DATA) / FLASH_PAGE_SIZE;      /* Number of pages that need to be erased */
//   jojojo = sizeof(DATA) / FLASH_PAGE_SIZE;
//   printf("sizeof(DATA) / FLASH_PAGE_SIZE为：%x\n\r",jojojo);
//   if (HAL_FLASHEx_Erase(&EraseInitStruct, &PAGEError) != HAL_OK)  /* Executing page erasure, PAGEError returns the page with the erasure error and 0xFFFFFFFF, indicating successful erasure */
//   {
//     APP_ErrorHandler();
//   }
// }

/**
  * @brief  Flash Program
  * @param  None
  * @retval None
  */
// static void APP_FlashProgram(void)
// {
//   uint32_t flash_program_start = FLASH_USER_START_ADDR ;                /* flash program start address */
//   uint32_t flash_program_end = (FLASH_USER_START_ADDR + sizeof(DATA));  /* flash program end address */
//   uint32_t *src = (uint32_t *)DATA;                                     /* Program data */

//   while (flash_program_start < flash_program_end)
//   {
//     if (HAL_FLASH_Program(FLASH_TYPEPROGRAM_PAGE, flash_program_start, src) == HAL_OK)/* Program */
//     {
//       flash_program_start += FLASH_PAGE_SIZE; /* flash Start point first page */
//       src += FLASH_PAGE_SIZE / 4;             /* Update data point */
//     }
//   }
// }

/**
  * @brief  Flash Check
  * @param  None
  * @retval None
  */
// static void APP_FlashBlank(void)
// {
//   uint32_t addr = 0;

//   while (addr < sizeof(DATA))
//   {
//     if (0xFFFFFFFF != HW32_REG(FLASH_USER_START_ADDR + addr))
//     {
//       APP_ErrorHandler();
//     }
//     addr += 4;
//   }
// }

/**
  * @brief  Flash Verify
  * @param  None
  * @retval None
  */
// static void APP_FlashVerify(void)
// {
//   uint32_t addr = 0;

//   while (addr < sizeof(DATA))
//   {
//     if (DATA[addr / 4] != HW32_REG(FLASH_USER_START_ADDR + addr))
//     {
//       APP_ErrorHandler();
//     }
//     addr += 4;
//   }
// }
void ca_ce_shi(void)
{
  uint32_t PAGEError = 0;
    FLASH_EraseInitTypeDef EraseInitStruct = {0};

    /* Unlock Flash */
    HAL_FLASH_Unlock();
  
    EraseInitStruct.TypeErase   = FLASH_TYPEERASE_PAGEERASE;        /* Erase type FLASH_TYPEERASE_PAGEERASE=Page erase, FLASH_TYPEERASE_SECTORERASE=Sector Erase */
    EraseInitStruct.PageAddress = SECTOR_9_START_ADDR;                               /* Erase Start Address */
    EraseInitStruct.NbPages  = ((SECTOR_15_START_ADDR - SECTOR_9_START_ADDR) / 0x100);    /* Number of pages that need to be erased */
    if (HAL_FLASHEx_Erase(&EraseInitStruct, &PAGEError) != HAL_OK)  /* Executing page erasure, PAGEError returns the page with the erasure error and 0xFFFFFFFF, indicating successful erasure */
    {
      ;
    }
    else
    {
        ;
    }
    /* Lock Flash */
    HAL_FLASH_Lock();
}

void xie_ce_shi(void)
{
    uint32_t flash_program_start = SECTOR_9_START_ADDR ;                /* flash program start address */
    uint32_t flash_program_end = (SECTOR_15_START_ADDR - 1);  /* flash program end address */
    uint32_t *src = (uint32_t *)DATA;                                     /* Program data */
  
    HAL_FLASH_Unlock();
    while (flash_program_start < flash_program_end)
    {
      if (HAL_FLASH_Program(FLASH_TYPEPROGRAM_PAGE, flash_program_start, src) == HAL_OK)/* Program */
      {
        flash_program_start += FLASH_PAGE_SIZE; /* flash Start point first page */
        src += FLASH_PAGE_SIZE / 4;             /* Update data point */
      }
    }
    HAL_FLASH_Lock();
}

/**
  * @brief  This function is executed in case of error occurrence.
  * @param  None
  * @retval None
  */
void APP_ErrorHandler(void)
{
  while (1)
  {
  }
}

#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 can add his own implementation to report the file name and line number,
     ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */

  /* Infinite loop */
  while (1)
  {
  }
}
#endif /* USE_FULL_ASSERT */

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