
/* USER CODE BEGIN Header */
/**
 ******************************************************************************
 * @file           : main.c
 * @brief          : Main program body
 ******************************************************************************
 * @attention
 *
 * <h2><center>&copy; Copyright (c) 2020 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
 *
 ******************************************************************************
 */
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "main.h"

#include <stdlib.h>

/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */

#include "libPLX/plx.h"
#include "libPLX/displayinfo.h"
#include "libPLX/commsLib.h"
#include "libSerial/serialUtils.H"

#include "libSmallPrintf/small_printf.h"
#include "libNMEA/nmea.h"
#include "switches.h"
#include <string.h>

/* 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 ---------------------------------------------------------*/
I2C_HandleTypeDef hi2c1;

SPI_HandleTypeDef hspi1;

TIM_HandleTypeDef htim2;
TIM_HandleTypeDef htim3;
TIM_HandleTypeDef htim9;

UART_HandleTypeDef huart4;
UART_HandleTypeDef huart1;
UART_HandleTypeDef huart2;
UART_HandleTypeDef huart3;

/* USER CODE BEGIN PV */
/* Private variables ---------------------------------------------------------*/

///@brief  timeout when the ignition is switched off
uint32_t const IGNITION_OFF_TIMEOUT = 30000UL;

/// @brief 1000mS per logger period, print average per period
uint32_t const LOGGER_INTERVAL = 250UL;

/// @brief  about 10 seconds after twiddle, save the dial position.
const int DialTimeout = 100;

/// @brief Unused Observation
uniqueObs_t const nullObs = {PLX_MAX_OBS,
                             PLX_MAX_INST};

/// @brief Null context
context_t const nullContext = {.knobPos = -1,
                               .dial_timer = 0,
                               .dial0 = -1,
                               .dial1 = -1,
                               .OldObservation = nullObs};

/// @brief Define a null item
info_t const nullInfo = {.Max = 0,
                         .Min = 0xFFF,
                         .sum = 0,
                         .count = 0,
                         .updated = 0,
                         .lastUpdated = 0,
                         .observation = nullObs};

context_t contexts[MAX_DISPLAYS];

/// @brief Data storage for readings
info_t Info[MAXRDG];

uint32_t Latch_Timer;

// location for GPS data
Location loc;

/// @brief Time when the logged data will be sent
uint32_t nextTickReload;

// data timeout
uint32_t dataTimeout = 0; //

// USART buffers
uint8_t uc1_tx_buffer[TX_USART_BUFF_SIZ];
uint8_t uc1_rx_buffer[RX_USART_BUFF_SIZ];

uint8_t uc2_tx_buffer[TX_USART_BUFF_SIZ];
uint8_t uc2_rx_buffer[RX_USART_BUFF_SIZ];

uint8_t uc3_tx_buffer[TX_USART_BUFF_SIZ];
uint8_t uc3_rx_buffer[RX_USART_BUFF_SIZ];

uint8_t uc4_tx_buffer[TX_USART_BUFF_SIZ];
uint8_t uc4_rx_buffer[RX_USART_BUFF_SIZ];

/* USER CODE END PV */

/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
static void MX_GPIO_Init(void);
static void MX_SPI1_Init(void);
static void MX_USART1_UART_Init(void);
static void MX_USART2_UART_Init(void);
static void MX_USART3_UART_Init(void);
static void MX_TIM3_Init(void);
static void MX_TIM9_Init(void);
static void MX_TIM2_Init(void);
static void MX_UART4_Init(void);
static void MX_I2C1_Init(void);
/* USER CODE BEGIN PFP */

// the dial is the switch number we are using.
// suppress is the ItemIndex we wish to suppress on this display
int DisplayCurrent(int dial, int suppress)
{
  return cc_display(dial, suppress);
}

/// \note  HC-05 only accepts : 9600,19200,38400,57600,115200,230400,460800 baud
/// \brief Setup Bluetooth module
void initModule(struct usart_ctl *ctl, uint32_t baudRate)
{
  char initBuf[60];
  // switch to command mode
  HAL_GPIO_WritePin(BT_RESET_GPIO_Port, BT_RESET_Pin, GPIO_PIN_SET);
  HAL_Delay(500);
  // clear the button press
  HAL_GPIO_WritePin(BT_RESET_GPIO_Port, BT_RESET_Pin, GPIO_PIN_RESET);
  HAL_Delay(500);
  setBaud(ctl, 38400);
  int initLen = small_sprintf(initBuf, "AT\nAT+UART?\nAT+UART=%ld,0,0\n", baudRate);
  const char buf[] = "AT+RESET\n";
  sendString(ctl, initBuf, initLen);
  HAL_Delay(500);
  initLen = small_sprintf(initBuf, buf);
  sendString(ctl, initBuf, initLen);

  TxWaitEmpty(ctl);

  // switch back to normal comms at new baud rate
  setBaud(ctl, baudRate);
  HAL_Delay(100);
}

// workspace for RMC data read from GPS module.
volatile uint16_t rmc_length;

uint8_t rmc_callback(uint8_t *data, uint16_t length)
{
  // send it back out
  rmc_length = length;

  sendString(&uc3, (const char *)data, length);

  nextTickReload = HAL_GetTick() + LOGGER_INTERVAL;

  return 0;
}

// check if bluetooth connected
uint8_t btConnected()
{
  return HAL_GPIO_ReadPin(BT_STATE_GPIO_Port, BT_STATE_Pin) == GPIO_PIN_SET;
}

/// @brief return true if this slot is unused
/// @param ptr pointer to the slot to
uint8_t isUnused(int index)
{
  if (index < 0 || index > MAXRDG)
    return false;

  return Info[index].observation.Instance == PLX_MAX_INST && Info[index].observation.Obs == PLX_MAX_OBS;
}

/// @brief Determine if an entry is currently valid
/// @param index the number of the array entry to display
/// @return true if the entry contains data which is fresh
uint8_t isValid(int index)
{
  if (index < 0 || index > MAXRDG)
    return false;
  if (isUnused(index))
    return false;

  uint32_t age = HAL_GetTick() - Info[index].lastUpdated;

  if (age > 300)
    return false;

  return true;
}

/* USER CODE END PFP */

/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */
void libPLXcallbackSendUserData(struct usart_ctl * instance)
{
  (void)instance;
}


void libPLXcallbackRecievedData(PLX_SensorInfo *info)
{
  // received some data , timeout is reset
  dataTimeout = 0;

  // search to see if the item already has a slot in the Info[] array
  // match the observation and instance: if found, update entry
  enum PLX_Observations observation = ConvPLX(info->AddrH,
                                              info->AddrL);

  char instance = info->Instance;

  int16_t data = ConvPLX(info->ReadingH,
                         info->ReadingL);

  // validate the current item, discard out of range
  if ((instance > PLX_MAX_INST) || (observation > PLX_MAX_OBS))
    return;

  // search for the item in the list
  int currentSlot;
  for (currentSlot = 0; currentSlot < MAXRDG; ++currentSlot)
  {
    if ((Info[currentSlot].observation.Obs == observation) && (Info[currentSlot].observation.Instance == instance))
      break;
  }
  // fallen off the end of the list of existing items without a match, so j points at next new item
  //
  // Find an unused slot

  if (currentSlot == MAXRDG)
  {
    int k;
    {
      for (k = 0; k < MAXRDG; ++k)
        if (!isValid(k))
        {
          currentSlot = k; // found a spare slot
          Info[currentSlot] = nullInfo;
          break;
        }
    }
    if (k == MAXRDG)
      return; // abandon this iteration
  }

  // give up if we are going to fall off the end of the array
  if (currentSlot >= MAXRDG)
    return;

  Info[currentSlot].observation.Obs = observation;

  Info[currentSlot].observation.Instance = instance;
  Info[currentSlot].data = data;
  if (data > Info[currentSlot].Max)
  {
    Info[currentSlot].Max = data;
  }
  if (data < Info[currentSlot].Min)
  {
    Info[currentSlot].Min = data;
  }
  // take an average
  Info[currentSlot].sum += data;
  Info[currentSlot].count++;
  // note the last update time
  Info[currentSlot].lastUpdated = HAL_GetTick();
  Info[currentSlot].updated = 1; // it has been updated

  // scan through and invalidate all old items
  for (int i = 0; i < MAXRDG; ++i)
  {
    if (!isValid(i))
      Info[i] = nullInfo;
  }
}
/* USER CODE END 0 */

/**
 * @brief  The application entry point.
 * @retval int
 */
int main(void)
{
  /* USER CODE BEGIN 1 */
  __HAL_RCC_SPI1_CLK_ENABLE();
  __HAL_RCC_USART1_CLK_ENABLE(); // PLX main port
  __HAL_RCC_USART2_CLK_ENABLE(); // debug port
  __HAL_RCC_USART3_CLK_ENABLE(); // Bluetooth port
  __HAL_RCC_UART4_CLK_ENABLE();  // NMEA0183 port

  __HAL_RCC_TIM3_CLK_ENABLE();

  __HAL_RCC_TIM9_CLK_ENABLE();

  /* 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 */
  // Switch handler called on sysTick interrupt.
  InitSwitches();

  /* USER CODE END SysInit */

  /* Initialize all configured peripherals */
  MX_GPIO_Init();
  MX_SPI1_Init();
  MX_USART1_UART_Init();
  MX_USART2_UART_Init();
  MX_USART3_UART_Init();
  MX_TIM3_Init();
  MX_TIM9_Init();
  MX_TIM2_Init();
  MX_UART4_Init();
  MX_I2C1_Init();
  /* USER CODE BEGIN 2 */

  /* Turn on USART1 IRQ */
  HAL_NVIC_SetPriority(USART1_IRQn, 2, 0);
  HAL_NVIC_EnableIRQ(USART1_IRQn);

  /* Turn on USART2 IRQ  */
  HAL_NVIC_SetPriority(USART2_IRQn, 4, 0);
  HAL_NVIC_EnableIRQ(USART2_IRQn);

  /* turn on USART3 IRQ */
  HAL_NVIC_SetPriority(USART3_IRQn, 4, 0);
  HAL_NVIC_EnableIRQ(USART3_IRQn);

  /* turn on UART4 IRQ */
  HAL_NVIC_SetPriority(UART4_IRQn, 4, 0);
  HAL_NVIC_EnableIRQ(UART4_IRQn);

  /* setup the USART control blocks */
  init_usart_ctl(&uc1, &huart1, uc1_tx_buffer,
                 uc1_rx_buffer,
                 TX_USART_BUFF_SIZ,
                 TX_USART_BUFF_SIZ);
  init_usart_ctl(&uc2, &huart2, uc2_tx_buffer,
                 uc2_rx_buffer,
                 TX_USART_BUFF_SIZ,
                 TX_USART_BUFF_SIZ);
  init_usart_ctl(&uc3, &huart3, uc3_tx_buffer,
                 uc3_rx_buffer,
                 TX_USART_BUFF_SIZ,
                 TX_USART_BUFF_SIZ);
  init_usart_ctl(&uc4, &huart4, uc4_tx_buffer,
                 uc4_rx_buffer,
                 TX_USART_BUFF_SIZ,
                 TX_USART_BUFF_SIZ);

  EnableSerialRxInterrupt(&uc1);
  EnableSerialRxInterrupt(&uc2);
  EnableSerialRxInterrupt(&uc3);
  EnableSerialRxInterrupt(&uc4);

  HAL_TIM_Encoder_Start(&htim3, TIM_CHANNEL_ALL);

  HAL_TIM_Encoder_Start(&htim9, TIM_CHANNEL_ALL);

  initModule(&uc3, 38400);

  // Initialise UART for 4800 baud NMEA
  setBaud(&uc2, 4800);

  // Initialuse UART4 for 4800 baud NMEA.
  setBaud(&uc4, 4800);

  cc_init();

  for (int i = 0; i < MAX_DISPLAYS; ++i)
  {
    contexts[i] = nullContext; // set the knob position
  }

  /* reset the display timeout, latch on power from accessories */
  Latch_Timer = IGNITION_OFF_TIMEOUT;
  HAL_GPIO_WritePin(POWER_LATCH_GPIO_Port, POWER_LATCH_Pin, GPIO_PIN_RESET);

  /// @brief Time when the logged data will be sent

  setRmcCallback(&rmc_callback);

  // used in NMEA style logging
  uint32_t nextTick = 0; ///< time to send next
  nextTickReload = 0;
  uint32_t offsetTicks = 0; ///< time to print as offset in mS for each loop


  for (int i = 0; i < MAXRDG; ++i)
  {
    Info[i] = nullInfo;
  }

  uint32_t resetCounter = 0; // record time at which both reset buttons were first pressed.

  resetPLX();
  /* USER CODE END 2 */

  /* Infinite loop */
  /* USER CODE BEGIN WHILE */
  while (1)
  {

    /* while ignition is on, keep resetting power latch timer */
    if (HAL_GPIO_ReadPin(IGNITION_GPIO_Port, IGNITION_Pin) == GPIO_PIN_RESET)
    {
      Latch_Timer = HAL_GetTick() + IGNITION_OFF_TIMEOUT;
    }
    else
    {
      /* if the ignition has been off for a while, then turn off power */
      if (HAL_GetTick() > Latch_Timer)
      {
        HAL_GPIO_WritePin(POWER_LATCH_GPIO_Port, POWER_LATCH_Pin,
                          GPIO_PIN_RESET);
      }
    }

    // Handle the bluetooth pairing / reset function by pressing both buttons.
    if ((push_pos[0] == 1) && (push_pos[1] == 1))
    {
      HAL_GPIO_WritePin(BT_BUTTON_GPIO_Port, BT_BUTTON_Pin,
                        GPIO_PIN_RESET);
      if (resetCounter == 0)
        resetCounter = HAL_GetTick();
    }
    else
    {
      HAL_GPIO_WritePin(BT_BUTTON_GPIO_Port, BT_BUTTON_Pin,
                        GPIO_PIN_SET);

      if (resetCounter != 0)
      {
        // Held down reset button for 10 seconds, clear NVRAM.
        if ((HAL_GetTick() - resetCounter) > 10000)
        {
          for (int i = 0; i < MAX_DISPLAYS; i++)
          {
            contexts[i] = nullContext;
            contexts[i].dial_timer = 1; // timeout immediately when decremented
          }
          erase_nvram();
        }
        resetCounter = 0;
      }
    }

    // poll GPS Position/time on UART4
    (void)updateLocation(&loc, &uc4);
    if (loc.valid == 'V')
      memset(loc.time, '-', 6);

    // if permitted, log data from RMC packet
    if (btConnected())
    {
      // Timeout for data logging regularly
      if (HAL_GetTick() > nextTick)
      {
        nextTick = nextTickReload;
        nextTickReload += LOGGER_INTERVAL;

        // Send items  to BT if it is in connected state
        // print timestamp as a $PLTIM record.
        char linebuff[20];
        strftime(linebuff, sizeof(linebuff), "%H%M%S", &loc.tv);

        char outbuff[100];
        int cnt = small_sprintf(outbuff, "$PLTIM,%s.%03lu\n", linebuff, offsetTicks);
        sendString(&uc3, outbuff, cnt);
        offsetTicks += LOGGER_INTERVAL;

        // increment timer
        if (offsetTicks >= (1000))
        {
          offsetTicks -= 1000;
          loc.tv.tm_sec++;
          if (loc.tv.tm_sec >= 60)
          {
            loc.tv.tm_sec = 0;
            loc.tv.tm_min++;
            if (loc.tv.tm_min >= 60)
            {
              loc.tv.tm_hour++;
              if (loc.tv.tm_hour >= 24)
                loc.tv.tm_hour = 0;
            }
          }
        }

        for (int i = 0; i < MAXRDG; ++i)
        {
          if (!isValid(i))
            continue;
          // format output
          // avoid division by zero for items with no sample data this iteration
          if (Info[i].count == 0)
            continue;
          double average = (double)Info[i].sum / Info[i].count;
          enum PLX_Observations Observation = Info[i].observation.Obs;

          double cur_rdg = ConveriMFDRaw2Data((enum PLX_Observations)Observation, DisplayInfo[Observation].Units,
                                              average);
          int cnt;
          int intPart;
          // depending on digits after the decimal point,
          // choose how to format data
          switch (DisplayInfo[Observation].DP)
          {
          default:
          case 0:
            cnt = small_sprintf(outbuff,
                                "$PLLOG,%s,%d,%d",
                                DisplayInfo[Info[i].observation.Obs].name,
                                Info[i].observation.Instance,
                                (int)cur_rdg);

            break;
          case 1:
            intPart = (int)(cur_rdg * 10);
            cnt = small_sprintf(outbuff,
                                "$PLLOG,%s,%d,%d.%1d",
                                DisplayInfo[Info[i].observation.Obs].name,
                                Info[i].observation.Instance,
                                intPart / 10, abs(intPart) % 10);

            break;
          case 2:
            intPart = (int)(cur_rdg * 100);
            cnt = small_sprintf(outbuff,
                                "$PLLOG,%s,%d,%d.%02d",
                                DisplayInfo[Info[i].observation.Obs].name,
                                Info[i].observation.Instance,
                                intPart / 100, abs(intPart) % 100);

            break;
          }

          Info[i].count = 0;
          Info[i].sum = 0;

          // NMEA style checksum
          int ck;
          int sum = 0;
          for (ck = 1; ck < cnt; ck++)
            sum += outbuff[ck];
          cnt += small_sprintf(outbuff + cnt, "*%02X\n",
                               sum & 0xFF);
          sendString(&uc3, outbuff, cnt);
        }
      }
    }

    // poll data into libPLX
    libPLXpollData(&uc1);

    // determine if we are getting any data from the interface

    dataTimeout++;
    if (btConnected() && (dataTimeout % 1000 == 0))
    {
      const char msg[] = "Timeout\r\n";
      sendString(&uc3, msg, sizeof(msg));
    }

    if (dataTimeout > 60000)
    {

      // do turn off screen
    }
    // wait for a bit if nothing came in.
    HAL_Delay(1);
  }

  // handle switch rotation
  for (int i = 0; i < MAX_DIALS; ++i)
  {
    int delta = get_dial_diff(i);
    int pos = contexts[i].knobPos;
    if (pos < 0)
      break; // dont process until we have read NVRAM for the first time .
    int start = pos;
    // move in positive direction
    while (delta > 0)
    {
      // skip invalid items, dont count
      if (pos < MAXRDG - 1)
        pos++;
      else
        pos = 0;

      if (isValid(pos))
        delta--; // count a valid item

      // wrap
      if (pos == start)
        break;
    }

    // move in negative direction
    while (delta < 0)
    {
      // skip invalid items, dont count
      if (pos > 0)
        pos--;
      else
        pos = MAXRDG - 1;

      if (isValid(pos))
        delta++; // count a valid item

      // wrap
      if (pos == start)
        break;
    }

    contexts[i].knobPos = pos;
    if (pos != start)
      contexts[i].dial_timer = DialTimeout;
  }

  int suppress = -1;
  for (int i = 0; i < MAX_DISPLAYS; ++i)
  { // now to display the information
    suppress = DisplayCurrent(i, suppress);

    cc_check_nvram(i);
  }
  /* 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};

  /** Configure the main internal regulator output voltage
   */
  __HAL_PWR_VOLTAGESCALING_CONFIG(PWR_REGULATOR_VOLTAGE_SCALE1);

  /** Initializes the RCC Oscillators according to the specified parameters
   * in the RCC_OscInitTypeDef structure.
   */
  RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE;
  RCC_OscInitStruct.HSEState = RCC_HSE_ON;
  RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
  RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE;
  RCC_OscInitStruct.PLL.PLLMUL = RCC_PLL_MUL12;
  RCC_OscInitStruct.PLL.PLLDIV = RCC_PLL_DIV3;
  if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
  {
    Error_Handler();
  }

  /** Initializes the CPU, AHB and APB buses 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_DIV1;
  RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;

  if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_1) != HAL_OK)
  {
    Error_Handler();
  }
}

/**
 * @brief I2C1 Initialization Function
 * @param None
 * @retval None
 */
static void MX_I2C1_Init(void)
{

  /* USER CODE BEGIN I2C1_Init 0 */

  /* USER CODE END I2C1_Init 0 */

  /* USER CODE BEGIN I2C1_Init 1 */

  /* USER CODE END I2C1_Init 1 */
  hi2c1.Instance = I2C1;
  hi2c1.Init.ClockSpeed = 100000;
  hi2c1.Init.DutyCycle = I2C_DUTYCYCLE_2;
  hi2c1.Init.OwnAddress1 = 0;
  hi2c1.Init.AddressingMode = I2C_ADDRESSINGMODE_7BIT;
  hi2c1.Init.DualAddressMode = I2C_DUALADDRESS_DISABLE;
  hi2c1.Init.OwnAddress2 = 0;
  hi2c1.Init.GeneralCallMode = I2C_GENERALCALL_DISABLE;
  hi2c1.Init.NoStretchMode = I2C_NOSTRETCH_DISABLE;
  if (HAL_I2C_Init(&hi2c1) != HAL_OK)
  {
    Error_Handler();
  }
  /* USER CODE BEGIN I2C1_Init 2 */

  /* USER CODE END I2C1_Init 2 */
}

/**
 * @brief SPI1 Initialization Function
 * @param None
 * @retval None
 */
static void MX_SPI1_Init(void)
{

  /* USER CODE BEGIN SPI1_Init 0 */

  /* USER CODE END SPI1_Init 0 */

  /* USER CODE BEGIN SPI1_Init 1 */

  /* USER CODE END SPI1_Init 1 */
  /* SPI1 parameter configuration*/
  hspi1.Instance = SPI1;
  hspi1.Init.Mode = SPI_MODE_MASTER;
  hspi1.Init.Direction = SPI_DIRECTION_1LINE;
  hspi1.Init.DataSize = SPI_DATASIZE_8BIT;
  hspi1.Init.CLKPolarity = SPI_POLARITY_HIGH;
  hspi1.Init.CLKPhase = SPI_PHASE_1EDGE;
  hspi1.Init.NSS = SPI_NSS_SOFT;
  hspi1.Init.BaudRatePrescaler = SPI_BAUDRATEPRESCALER_8;
  hspi1.Init.FirstBit = SPI_FIRSTBIT_MSB;
  hspi1.Init.TIMode = SPI_TIMODE_DISABLE;
  hspi1.Init.CRCCalculation = SPI_CRCCALCULATION_DISABLE;
  hspi1.Init.CRCPolynomial = 10;
  if (HAL_SPI_Init(&hspi1) != HAL_OK)
  {
    Error_Handler();
  }
  /* USER CODE BEGIN SPI1_Init 2 */

  /* USER CODE END SPI1_Init 2 */
}

/**
 * @brief TIM2 Initialization Function
 * @param None
 * @retval None
 */
static void MX_TIM2_Init(void)
{

  /* USER CODE BEGIN TIM2_Init 0 */

  /* USER CODE END TIM2_Init 0 */

  TIM_ClockConfigTypeDef sClockSourceConfig = {0};
  TIM_MasterConfigTypeDef sMasterConfig = {0};

  /* USER CODE BEGIN TIM2_Init 1 */

  /* USER CODE END TIM2_Init 1 */
  htim2.Instance = TIM2;
  htim2.Init.Prescaler = 0;
  htim2.Init.CounterMode = TIM_COUNTERMODE_UP;
  htim2.Init.Period = 65535;
  htim2.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
  htim2.Init.AutoReloadPreload = TIM_AUTORELOAD_PRELOAD_DISABLE;
  if (HAL_TIM_Base_Init(&htim2) != HAL_OK)
  {
    Error_Handler();
  }
  sClockSourceConfig.ClockSource = TIM_CLOCKSOURCE_INTERNAL;
  if (HAL_TIM_ConfigClockSource(&htim2, &sClockSourceConfig) != HAL_OK)
  {
    Error_Handler();
  }
  sMasterConfig.MasterOutputTrigger = TIM_TRGO_RESET;
  sMasterConfig.MasterSlaveMode = TIM_MASTERSLAVEMODE_DISABLE;
  if (HAL_TIMEx_MasterConfigSynchronization(&htim2, &sMasterConfig) != HAL_OK)
  {
    Error_Handler();
  }
  /* USER CODE BEGIN TIM2_Init 2 */

  /* USER CODE END TIM2_Init 2 */
}

/**
 * @brief TIM3 Initialization Function
 * @param None
 * @retval None
 */
static void MX_TIM3_Init(void)
{

  /* USER CODE BEGIN TIM3_Init 0 */

  /* USER CODE END TIM3_Init 0 */

  TIM_Encoder_InitTypeDef sConfig = {0};
  TIM_MasterConfigTypeDef sMasterConfig = {0};

  /* USER CODE BEGIN TIM3_Init 1 */

  /* USER CODE END TIM3_Init 1 */
  htim3.Instance = TIM3;
  htim3.Init.Prescaler = 0;
  htim3.Init.CounterMode = TIM_COUNTERMODE_UP;
  htim3.Init.Period = 65535;
  htim3.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
  htim3.Init.AutoReloadPreload = TIM_AUTORELOAD_PRELOAD_DISABLE;
  sConfig.EncoderMode = TIM_ENCODERMODE_TI1;
  sConfig.IC1Polarity = TIM_ICPOLARITY_RISING;
  sConfig.IC1Selection = TIM_ICSELECTION_DIRECTTI;
  sConfig.IC1Prescaler = TIM_ICPSC_DIV1;
  sConfig.IC1Filter = 15;
  sConfig.IC2Polarity = TIM_ICPOLARITY_RISING;
  sConfig.IC2Selection = TIM_ICSELECTION_DIRECTTI;
  sConfig.IC2Prescaler = TIM_ICPSC_DIV1;
  sConfig.IC2Filter = 15;
  if (HAL_TIM_Encoder_Init(&htim3, &sConfig) != HAL_OK)
  {
    Error_Handler();
  }
  sMasterConfig.MasterOutputTrigger = TIM_TRGO_RESET;
  sMasterConfig.MasterSlaveMode = TIM_MASTERSLAVEMODE_DISABLE;
  if (HAL_TIMEx_MasterConfigSynchronization(&htim3, &sMasterConfig) != HAL_OK)
  {
    Error_Handler();
  }
  /* USER CODE BEGIN TIM3_Init 2 */

  /* USER CODE END TIM3_Init 2 */
}

/**
 * @brief TIM9 Initialization Function
 * @param None
 * @retval None
 */
static void MX_TIM9_Init(void)
{

  /* USER CODE BEGIN TIM9_Init 0 */

  /* USER CODE END TIM9_Init 0 */

  TIM_Encoder_InitTypeDef sConfig = {0};
  TIM_MasterConfigTypeDef sMasterConfig = {0};

  /* USER CODE BEGIN TIM9_Init 1 */

  /* USER CODE END TIM9_Init 1 */
  htim9.Instance = TIM9;
  htim9.Init.Prescaler = 0;
  htim9.Init.CounterMode = TIM_COUNTERMODE_UP;
  htim9.Init.Period = 65535;
  htim9.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
  htim9.Init.AutoReloadPreload = TIM_AUTORELOAD_PRELOAD_DISABLE;
  sConfig.EncoderMode = TIM_ENCODERMODE_TI1;
  sConfig.IC1Polarity = TIM_ICPOLARITY_RISING;
  sConfig.IC1Selection = TIM_ICSELECTION_DIRECTTI;
  sConfig.IC1Prescaler = TIM_ICPSC_DIV1;
  sConfig.IC1Filter = 15;
  sConfig.IC2Polarity = TIM_ICPOLARITY_RISING;
  sConfig.IC2Selection = TIM_ICSELECTION_DIRECTTI;
  sConfig.IC2Prescaler = TIM_ICPSC_DIV1;
  sConfig.IC2Filter = 0;
  if (HAL_TIM_Encoder_Init(&htim9, &sConfig) != HAL_OK)
  {
    Error_Handler();
  }
  sMasterConfig.MasterOutputTrigger = TIM_TRGO_RESET;
  sMasterConfig.MasterSlaveMode = TIM_MASTERSLAVEMODE_DISABLE;
  if (HAL_TIMEx_MasterConfigSynchronization(&htim9, &sMasterConfig) != HAL_OK)
  {
    Error_Handler();
  }
  /* USER CODE BEGIN TIM9_Init 2 */

  /* USER CODE END TIM9_Init 2 */
}

/**
 * @brief UART4 Initialization Function
 * @param None
 * @retval None
 */
static void MX_UART4_Init(void)
{

  /* USER CODE BEGIN UART4_Init 0 */

  /* USER CODE END UART4_Init 0 */

  /* USER CODE BEGIN UART4_Init 1 */

  /* USER CODE END UART4_Init 1 */
  huart4.Instance = UART4;
  huart4.Init.BaudRate = 4800;
  huart4.Init.WordLength = UART_WORDLENGTH_8B;
  huart4.Init.StopBits = UART_STOPBITS_1;
  huart4.Init.Parity = UART_PARITY_NONE;
  huart4.Init.Mode = UART_MODE_TX_RX;
  huart4.Init.HwFlowCtl = UART_HWCONTROL_NONE;
  huart4.Init.OverSampling = UART_OVERSAMPLING_16;
  if (HAL_UART_Init(&huart4) != HAL_OK)
  {
    Error_Handler();
  }
  /* USER CODE BEGIN UART4_Init 2 */

  /* USER CODE END UART4_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 = 19200;
  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 USART2 Initialization Function
 * @param None
 * @retval None
 */
static void MX_USART2_UART_Init(void)
{

  /* USER CODE BEGIN USART2_Init 0 */

  /* USER CODE END USART2_Init 0 */

  /* USER CODE BEGIN USART2_Init 1 */

  /* USER CODE END USART2_Init 1 */
  huart2.Instance = USART2;
  huart2.Init.BaudRate = 115200;
  huart2.Init.WordLength = UART_WORDLENGTH_8B;
  huart2.Init.StopBits = UART_STOPBITS_1;
  huart2.Init.Parity = UART_PARITY_NONE;
  huart2.Init.Mode = UART_MODE_TX_RX;
  huart2.Init.HwFlowCtl = UART_HWCONTROL_NONE;
  huart2.Init.OverSampling = UART_OVERSAMPLING_16;
  if (HAL_UART_Init(&huart2) != HAL_OK)
  {
    Error_Handler();
  }
  /* USER CODE BEGIN USART2_Init 2 */

  /* USER CODE END USART2_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 = 19200;
  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_GPIOH_CLK_ENABLE();
  __HAL_RCC_GPIOA_CLK_ENABLE();
  __HAL_RCC_GPIOC_CLK_ENABLE();
  __HAL_RCC_GPIOB_CLK_ENABLE();

  /*Configure GPIO pin Output Level */
  HAL_GPIO_WritePin(GPIOA, SPI_NSS1_Pin | BT_BUTTON_Pin | BT_RESET_Pin, GPIO_PIN_SET);

  /*Configure GPIO pin Output Level */
  HAL_GPIO_WritePin(SPI_CD_GPIO_Port, SPI_CD_Pin, GPIO_PIN_RESET);

  /*Configure GPIO pin Output Level */
  HAL_GPIO_WritePin(GPIOC, SPI_RESET_Pin | POWER_LATCH_Pin | USB_PWR_Pin, GPIO_PIN_RESET);

  /*Configure GPIO pin Output Level */
  HAL_GPIO_WritePin(SPI_NSS2_GPIO_Port, SPI_NSS2_Pin, GPIO_PIN_SET);

  /*Configure GPIO pins : SPI_NSS1_Pin SPI_CD_Pin */
  GPIO_InitStruct.Pin = SPI_NSS1_Pin | SPI_CD_Pin;
  GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
  GPIO_InitStruct.Pull = GPIO_NOPULL;
  GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
  HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);

  /*Configure GPIO pins : SPI_RESET_Pin SPI_NSS2_Pin POWER_LATCH_Pin USB_PWR_Pin */
  GPIO_InitStruct.Pin = SPI_RESET_Pin | SPI_NSS2_Pin | POWER_LATCH_Pin | USB_PWR_Pin;
  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);

  /*Configure GPIO pins : BT_STATE_Pin SW1_PUSH_Pin SW2_PUSH_Pin */
  GPIO_InitStruct.Pin = BT_STATE_Pin | SW1_PUSH_Pin | SW2_PUSH_Pin;
  GPIO_InitStruct.Mode = GPIO_MODE_INPUT;
  GPIO_InitStruct.Pull = GPIO_PULLUP;
  HAL_GPIO_Init(GPIOB, &GPIO_InitStruct);

  /*Configure GPIO pin : IGNITION_Pin */
  GPIO_InitStruct.Pin = IGNITION_Pin;
  GPIO_InitStruct.Mode = GPIO_MODE_INPUT;
  GPIO_InitStruct.Pull = GPIO_NOPULL;
  HAL_GPIO_Init(IGNITION_GPIO_Port, &GPIO_InitStruct);

  /*Configure GPIO pin : BT_BUTTON_Pin */
  GPIO_InitStruct.Pin = BT_BUTTON_Pin;
  GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_OD;
  GPIO_InitStruct.Pull = GPIO_PULLUP;
  GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
  HAL_GPIO_Init(BT_BUTTON_GPIO_Port, &GPIO_InitStruct);

  /*Configure GPIO pin : BT_RESET_Pin */
  GPIO_InitStruct.Pin = BT_RESET_Pin;
  GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
  GPIO_InitStruct.Pull = GPIO_NOPULL;
  GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH;
  HAL_GPIO_Init(BT_RESET_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 */