/* USER CODE BEGIN Header */
/**
  ******************************************************************************
  * @file           : main.c
  * @brief          : Main program body
  ******************************************************************************
  * @attention
  *
  * Copyright (c) 2024 STMicroelectronics.
  * All rights reserved.
  *
  * This software is licensed under terms that can be found in the LICENSE file
  * in the root directory of this software component.
  * If no LICENSE file comes with this software, it is provided AS-IS.
  *
  ******************************************************************************
  */
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "main.h"

/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
#include <stdbool.h>
/* USER CODE END Includes */

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

/* USER CODE END PTD */

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

uint8_t i2c_register;

#define I2C_REGISTER_DELTA 1
#define I2C_REGISTER_WIRES 2
#define I2C_REGISTER_BUTTON 3
#define I2C_REGISTER_RELAY_BUZZ 4
#define I2C_REGISTER_LED 5
#define I2C_REGISTER_ISSUE_STRIKE 6
#define I2C_REGISTER_STRIKE_BUZZ_LEN 7
#define I2C_REGISTER_STRIKE_RELAY_LEN 8

#define BUZZ_BIT_IDX 0
#define RELAY_BIT_IDX 1

#define DELTA_BIT_WIRES 0
#define DELTA_BIT_BUTTON 1

/* USER CODE END PD */

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

/* USER CODE END PM */

/* Private variables ---------------------------------------------------------*/
I2C_HandleTypeDef hi2c1;

UART_HandleTypeDef huart2;

/* USER CODE BEGIN PV */

uint8_t old_delta;
uint8_t delta;

uint8_t old_wires;
uint8_t wires;

uint8_t old_button;
uint8_t button;

uint8_t old_relay_buzz;
uint8_t relay_buzz;

uint8_t old_leds = 0;
uint8_t leds = 0;

uint16_t strike_buzz_len = 500;
uint16_t strike_relay_len = 1000;

bool strike_issued;
uint32_t strike_at;

/* USER CODE END PV */

/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
static void MX_GPIO_Init(void);
static void MX_I2C1_Init(void);
static void MX_USART2_UART_Init(void);
/* USER CODE BEGIN PFP */
#ifdef __GNUC__
/* With GCC/RAISONANCE, small printf (option LD Linker->Libraries->Small printf
   set to 'Yes') calls __io_putchar() */
#define PUTCHAR_PROTOTYPE int __io_putchar(int ch)
#else
#define PUTCHAR_PROTOTYPE int fputc(int ch, FILE *f)
#endif /* __GNUC__ */

void send_interupt(void);

void send_register(void);
void recv_register(void);

void init_interupt(void);
void init_leds(void);
void init_relay_buzz(void);

void scan_wires(void);
void scan_button(void);
void set_relay_buzz(void);
void set_leds(void);
void handle_strike(void);

/* USER CODE END PFP */

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

/* USER CODE END 0 */

/**
  * @brief  The application entry point.
  * @retval int
  */
int main(void)
{

  /* USER CODE BEGIN 1 */

  /* 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_I2C1_Init();
  MX_USART2_UART_Init();
  /* USER CODE BEGIN 2 */

  HAL_I2C_EnableListen_IT(&hi2c1);
  /* USER CODE END 2 */

  /* Infinite loop */
  /* USER CODE BEGIN WHILE */
  while (1)
  {
    /* USER CODE END WHILE */

    /* USER CODE BEGIN 3 */
	  scan_wires();
	  scan_button();
	  handle_strike();
	  set_relay_buzz();
	  set_leds();
	  send_interupt();

  }
  /* 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_PWREx_ControlVoltageScaling(PWR_REGULATOR_VOLTAGE_SCALE1);

  /** Initializes the RCC Oscillators according to the specified parameters
  * in the RCC_OscInitTypeDef structure.
  */
  RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI;
  RCC_OscInitStruct.HSIState = RCC_HSI_ON;
  RCC_OscInitStruct.HSIDiv = RCC_HSI_DIV1;
  RCC_OscInitStruct.HSICalibrationValue = RCC_HSICALIBRATION_DEFAULT;
  RCC_OscInitStruct.PLL.PLLState = RCC_PLL_NONE;
  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_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_HSI;
  RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
  RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV1;

  if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_0) != 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.Timing = 0x00303D5B;
  hi2c1.Init.OwnAddress1 = 250;
  hi2c1.Init.AddressingMode = I2C_ADDRESSINGMODE_7BIT;
  hi2c1.Init.DualAddressMode = I2C_DUALADDRESS_DISABLE;
  hi2c1.Init.OwnAddress2 = 0;
  hi2c1.Init.OwnAddress2Masks = I2C_OA2_NOMASK;
  hi2c1.Init.GeneralCallMode = I2C_GENERALCALL_DISABLE;
  hi2c1.Init.NoStretchMode = I2C_NOSTRETCH_DISABLE;
  if (HAL_I2C_Init(&hi2c1) != HAL_OK)
  {
    Error_Handler();
  }

  /** Configure Analogue filter
  */
  if (HAL_I2CEx_ConfigAnalogFilter(&hi2c1, I2C_ANALOGFILTER_ENABLE) != HAL_OK)
  {
    Error_Handler();
  }

  /** Configure Digital filter
  */
  if (HAL_I2CEx_ConfigDigitalFilter(&hi2c1, 0) != HAL_OK)
  {
    Error_Handler();
  }
  /* USER CODE BEGIN I2C1_Init 2 */

  /* USER CODE END I2C1_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;
  huart2.Init.OneBitSampling = UART_ONE_BIT_SAMPLE_DISABLE;
  huart2.Init.ClockPrescaler = UART_PRESCALER_DIV1;
  huart2.AdvancedInit.AdvFeatureInit = UART_ADVFEATURE_NO_INIT;
  if (HAL_UART_Init(&huart2) != HAL_OK)
  {
    Error_Handler();
  }
  if (HAL_UARTEx_SetTxFifoThreshold(&huart2, UART_TXFIFO_THRESHOLD_1_8) != HAL_OK)
  {
    Error_Handler();
  }
  if (HAL_UARTEx_SetRxFifoThreshold(&huart2, UART_RXFIFO_THRESHOLD_1_8) != HAL_OK)
  {
    Error_Handler();
  }
  if (HAL_UARTEx_DisableFifoMode(&huart2) != HAL_OK)
  {
    Error_Handler();
  }
  /* USER CODE BEGIN USART2_Init 2 */

  /* USER CODE END USART2_Init 2 */

}

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

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

  /*Configure GPIO pin Output Level */
  HAL_GPIO_WritePin(LED2_GPIO_Port, LED2_Pin, GPIO_PIN_RESET);

  /*Configure GPIO pin Output Level */
  HAL_GPIO_WritePin(GPIOA, LED3_Pin|HELP_BTN_Pin|INT_Pin, GPIO_PIN_RESET);

  /*Configure GPIO pin Output Level */
  HAL_GPIO_WritePin(GPIOB, RELAY1_Pin|RELAY2_Pin|BUZZ_Pin|LED4_Pin
                          |LED1_Pin, GPIO_PIN_RESET);

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

  /*Configure GPIO pins : LED3_Pin HELP_BTN_Pin INT_Pin */
  GPIO_InitStruct.Pin = LED3_Pin|HELP_BTN_Pin|INT_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 : WIRE8_Pin WIRE7_Pin WIRE6_Pin WIRE5_Pin */
  GPIO_InitStruct.Pin = WIRE8_Pin|WIRE7_Pin|WIRE6_Pin|WIRE5_Pin;
  GPIO_InitStruct.Mode = GPIO_MODE_INPUT;
  GPIO_InitStruct.Pull = GPIO_PULLUP;
  HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);

  /*Configure GPIO pins : WIRE4_Pin WIRE3_Pin WIRE2_Pin WIRE1_Pin */
  GPIO_InitStruct.Pin = WIRE4_Pin|WIRE3_Pin|WIRE2_Pin|WIRE1_Pin;
  GPIO_InitStruct.Mode = GPIO_MODE_INPUT;
  GPIO_InitStruct.Pull = GPIO_PULLUP;
  HAL_GPIO_Init(GPIOB, &GPIO_InitStruct);

  /*Configure GPIO pins : RELAY1_Pin RELAY2_Pin BUZZ_Pin LED4_Pin
                           LED1_Pin */
  GPIO_InitStruct.Pin = RELAY1_Pin|RELAY2_Pin|BUZZ_Pin|LED4_Pin
                          |LED1_Pin;
  GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
  GPIO_InitStruct.Pull = GPIO_NOPULL;
  GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
  HAL_GPIO_Init(GPIOB, &GPIO_InitStruct);

/* USER CODE BEGIN MX_GPIO_Init_2 */
/* USER CODE END MX_GPIO_Init_2 */
}

/* USER CODE BEGIN 4 */
PUTCHAR_PROTOTYPE
{
  /* Place your implementation of fputc here */
  /* e.g. write a character to the USART1 and Loop until the end of transmission */
  HAL_UART_Transmit(&huart2, (uint8_t *)&ch, 1, 0xFFFF);

  return ch;
}

bool has_received_data;
void HAL_I2C_ListenCpltCallback(I2C_HandleTypeDef *hi2c)
{
	i2c_register = 0;
	has_received_data = false;
	HAL_I2C_EnableListen_IT(hi2c);
}

void HAL_I2C_AddrCallback(I2C_HandleTypeDef *hi2c, uint8_t TransferDirection, uint16_t AddrMatchCode) {
	if (TransferDirection == I2C_DIRECTION_TRANSMIT) {
		HAL_I2C_Slave_Seq_Receive_IT(hi2c, &i2c_register, 1, I2C_NEXT_FRAME);
	} else {
		send_register();
	}

}

uint8_t send_data[2];
void send_register(void) {
	switch (i2c_register) {
	case I2C_REGISTER_DELTA:
		HAL_I2C_Slave_Seq_Transmit_IT(&hi2c1, &delta, 1, I2C_NEXT_FRAME);
		break;
	case I2C_REGISTER_WIRES:
		HAL_I2C_Slave_Seq_Transmit_IT(&hi2c1, &wires, 1, I2C_NEXT_FRAME);
		delta &= ~(1 << DELTA_BIT_WIRES);
		break;
	case I2C_REGISTER_BUTTON:
		HAL_I2C_Slave_Seq_Transmit_IT(&hi2c1, &button, 1, I2C_NEXT_FRAME);
		delta &= ~(1 << DELTA_BIT_BUTTON);
		break;
	case I2C_REGISTER_RELAY_BUZZ:
		HAL_I2C_Slave_Seq_Transmit_IT(&hi2c1, &relay_buzz, 1, I2C_NEXT_FRAME);
		break;
	case I2C_REGISTER_LED:
		HAL_I2C_Slave_Seq_Transmit_IT(&hi2c1, &leds, 1, I2C_NEXT_FRAME);
		break;
	case I2C_REGISTER_STRIKE_BUZZ_LEN:
		send_data[0] = strike_buzz_len & 0xFF;
		send_data[1] = strike_buzz_len >> 8;
		HAL_I2C_Slave_Seq_Transmit_IT(&hi2c1, send_data, 2, I2C_NEXT_FRAME);
		break;
	case I2C_REGISTER_STRIKE_RELAY_LEN:
		send_data[0] = strike_relay_len & 0xFF;
		send_data[1] = strike_relay_len >> 8;
		HAL_I2C_Slave_Seq_Transmit_IT(&hi2c1, send_data, 2, I2C_NEXT_FRAME);
		break;
	default:
		break;
	}
}


uint8_t recv_data[2];
void recv_register(void) {
	switch (i2c_register) {
	case I2C_REGISTER_RELAY_BUZZ:
		HAL_I2C_Slave_Seq_Receive_IT(&hi2c1, &relay_buzz, 1, I2C_NEXT_FRAME);
		break;
	case I2C_REGISTER_LED:
		HAL_I2C_Slave_Seq_Receive_IT(&hi2c1, &leds, 1, I2C_NEXT_FRAME);
		break;
	case I2C_REGISTER_STRIKE_BUZZ_LEN:
		HAL_I2C_Slave_Seq_Receive_IT(&hi2c1, recv_data, 2, I2C_NEXT_FRAME);
		break;
	case I2C_REGISTER_STRIKE_RELAY_LEN:
		HAL_I2C_Slave_Seq_Receive_IT(&hi2c1, recv_data, 2, I2C_NEXT_FRAME);
		break;
	default:
		break;
	}
	has_received_data = true;
}

void HAL_I2C_SlaveRxCpltCallback(I2C_HandleTypeDef *hi2c)
{
	if (i2c_register == I2C_REGISTER_ISSUE_STRIKE) {
		strike_issued = true;
	}
	if (has_received_data) {
		has_received_data = false;
		// reconstruct anything that needs to be reconstructed
		switch (i2c_register) {
		case I2C_REGISTER_STRIKE_BUZZ_LEN:
			strike_buzz_len = recv_data[0];
			strike_buzz_len |= ((uint16_t) recv_data[1]) << 8;
			break;
		case I2C_REGISTER_STRIKE_RELAY_LEN:
			strike_relay_len = recv_data[0];
			strike_relay_len |= ((uint16_t) recv_data[1]) << 8;
			break;
		default:
			break;
		}
	} else {
		recv_register();
	}
}

void HAL_I2C_SlaveTxCpltCallback(I2C_HandleTypeDef *hi2c)
{

}

void scan_wires(void)
{
	old_wires = wires;

	uint8_t new_wires = 0;
	new_wires |= (HAL_GPIO_ReadPin(WIRE1_GPIO_Port, WIRE1_Pin) == GPIO_PIN_RESET) << 0;
	new_wires |= (HAL_GPIO_ReadPin(WIRE2_GPIO_Port, WIRE2_Pin) == GPIO_PIN_RESET) << 1;
	new_wires |= (HAL_GPIO_ReadPin(WIRE3_GPIO_Port, WIRE3_Pin) == GPIO_PIN_RESET) << 2;
	new_wires |= (HAL_GPIO_ReadPin(WIRE4_GPIO_Port, WIRE4_Pin) == GPIO_PIN_RESET) << 3;
	new_wires |= (HAL_GPIO_ReadPin(WIRE5_GPIO_Port, WIRE5_Pin) == GPIO_PIN_RESET) << 4;
	new_wires |= (HAL_GPIO_ReadPin(WIRE6_GPIO_Port, WIRE6_Pin) == GPIO_PIN_RESET) << 5;
	new_wires |= (HAL_GPIO_ReadPin(WIRE7_GPIO_Port, WIRE7_Pin) == GPIO_PIN_RESET) << 6;
	new_wires |= (HAL_GPIO_ReadPin(WIRE8_GPIO_Port, WIRE8_Pin) == GPIO_PIN_RESET) << 7;
	wires = new_wires;

	if (wires != old_wires) {
		delta |= 1 << DELTA_BIT_WIRES;
	}
}


void scan_button(void)
{
	old_button = button;
	button = HAL_GPIO_ReadPin(HELP_BTN_GPIO_Port, HELP_BTN_Pin) == GPIO_PIN_RESET;

	if (button != old_button) {
		delta |= 1 << DELTA_BIT_BUTTON;
	}
}

void set_relay_buzz(void)
{
	if (relay_buzz != old_relay_buzz) {
		old_relay_buzz = relay_buzz;
		HAL_GPIO_WritePin(BUZZ_GPIO_Port, BUZZ_Pin, (relay_buzz >> BUZZ_BIT_IDX) & 1);
		HAL_GPIO_WritePin(RELAY1_GPIO_Port, RELAY1_Pin, (relay_buzz >> RELAY_BIT_IDX) & 1);
		HAL_GPIO_WritePin(RELAY2_GPIO_Port, RELAY2_Pin, (relay_buzz >> RELAY_BIT_IDX) & 1);
	}
}

void set_leds(void)
{
	if (leds != old_leds) {
		old_leds = leds;
		HAL_GPIO_WritePin(LED1_GPIO_Port, LED1_Pin, (leds >> 0) & 1);
		HAL_GPIO_WritePin(LED2_GPIO_Port, LED2_Pin, (leds >> 1) & 1);
		HAL_GPIO_WritePin(LED3_GPIO_Port, LED3_Pin, (leds >> 2) & 1);
		HAL_GPIO_WritePin(LED4_GPIO_Port, LED4_Pin, (leds >> 3) & 1);
	}
}

void send_interupt(void)
{
	if (delta != old_delta) {
		old_delta = delta;
		HAL_GPIO_WritePin(INT_GPIO_Port, INT_Pin, delta == 0);
	}
}

uint32_t old_tick;
void handle_strike(void) {
	if (strike_issued && (strike_at == 0)) {
		strike_issued = false;
		strike_at = HAL_GetTick();
		// start the buzzer and set the led
		relay_buzz |= 1 << BUZZ_BIT_IDX;
		leds |= 1 << 3;
	}

	if (strike_at == 0) {
		return;
	}
	uint32_t now = HAL_GetTick();

	uint32_t buzz_threshold = strike_at + strike_buzz_len;
	if (now > buzz_threshold && old_tick <= buzz_threshold) {
		// stop buzzing, start the relay
		relay_buzz = (1 << RELAY_BIT_IDX);
	}

	uint32_t relay_threshold = buzz_threshold + strike_relay_len;
	if (now > relay_threshold) {
		// stop the strike
		strike_at = 0;
		relay_buzz = 0;
		leds &= ~(1 << 3);
	}

	old_tick = now;
}

/* 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 */
  __disable_irq();
  while (1)
  {
  }
  /* 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,
     ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
  /* USER CODE END 6 */
}
#endif /* USE_FULL_ASSERT */
