/* 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"

/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
#include <string.h>
#include "MySensors.h"

/* USER CODE END Includes */

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

/* USER CODE END PTD */

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

#define IN_ID1 1
#define IN_ID2 2
#define RELAY_ID1 3
#define RELAY_ID2 4

/* USER CODE END PD */

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

/* USER CODE END PM */

/* Private variables ---------------------------------------------------------*/
UART_HandleTypeDef huart1;

/* USER CODE BEGIN PV */

/* USER CODE END PV */

/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
static void MX_GPIO_Init(void);
static void MX_USART1_UART_Init(void);
/* USER CODE BEGIN PFP */
//MyMessage msg;

/* 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_USART1_UART_Init();
  /* USER CODE BEGIN 2 */
  HAL_GPIO_WritePin(Relay1_GPIO_Port, Relay1_Pin, RESET);
  HAL_GPIO_WritePin(Relay2_GPIO_Port, Relay2_Pin, RESET);
  HAL_GPIO_WritePin(TEN_GPIO_Port, TEN_Pin, RESET);

  transportInitialise(&huart1);
  /* USER CODE END 2 */

  /* Infinite loop */
  /* USER CODE BEGIN WHILE */
  while (1)
  {
	  uint8_t value;
	  static uint16_t loopv;
	  static uint16_t counter;
	  static uint8_t sentValue1=2;
	  static uint8_t sentValue2=2;
	  static uint8_t sentStatus=0;
	  static uint8_t button=0;
	  MyMessage msg;

      transportProcess();	// Process incoming data

      loopv++;

      value = HAL_GPIO_ReadPin(IN1_GPIO_Port, IN1_Pin);

      if (value != sentValue1) {
    		// Value has changed from last transmission, send the updated value
    	  msg.version_length = V2_MYS_HEADER_PROTOCOL_VERSION + (1 << 3);
    	  msg.sensor = IN_ID1;
    	  msg.type = V_TRIPPED;
    	  msg.bValue = value;
    	  send(&msg, P_BYTE);
    	  sentValue1 = value;
      }

      value = HAL_GPIO_ReadPin(IN2_GPIO_Port, IN2_Pin);

      if (value != sentValue2) {
          	// Value has changed from last transmission, send the updated value
          msg.version_length = V2_MYS_HEADER_PROTOCOL_VERSION + (1 << 3);
          msg.sensor = IN_ID2;
          msg.type = V_TRIPPED;
          msg.bValue = value;
          send(&msg, P_BYTE);
          sentValue2 = value;
      }

      value = HAL_GPIO_ReadPin(Button_GPIO_Port, Button_Pin);

      if (value != button) {
    	  button = value;
    	  if (button) {
    		  sentValue1 = 2;
    		  sentValue2 = 2;
    		  sentStatus = 0;

    		  present_node();
    	  }
      }

      if (sentStatus == 0) {
    	  sentStatus = 1;

    	  value = HAL_GPIO_ReadPin(Relay1_GPIO_Port, Relay1_Pin);
          msg.version_length = V2_MYS_HEADER_PROTOCOL_VERSION + (1 << 3);
          msg.sensor = RELAY_ID1;
          msg.type = V_STATUS;
          if (value)
            strcpy(msg.data, "1");
          else
        	strcpy(msg.data, "0");
          send(&msg, P_STRING);

          value = HAL_GPIO_ReadPin(Relay2_GPIO_Port, Relay2_Pin);
          msg.version_length = V2_MYS_HEADER_PROTOCOL_VERSION + (1 << 3);
          msg.sensor = RELAY_ID2;
          msg.type = V_STATUS;
          if (value)
            strcpy(msg.data, "1");
          else
            strcpy(msg.data, "0");
          send(&msg, P_STRING);
      }

      if (loopv == 0) {
    	  HAL_GPIO_TogglePin(LED_GPIO_Port, LED_Pin);
    	  counter++;
    	  if (counter > 3600) {
       		  sentValue1 = 2;
        	  sentValue2 = 2;
        	  sentStatus = 0;
        	  counter = 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};
  RCC_PeriphCLKInitTypeDef PeriphClkInit = {0};

  /** 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_MUL3;
  RCC_OscInitStruct.PLL.PREDIV = RCC_PREDIV_DIV1;
  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_PLLCLK;
  RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
  RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV4;

  if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_0) != HAL_OK)
  {
    Error_Handler();
  }
  PeriphClkInit.PeriphClockSelection = RCC_PERIPHCLK_USART1;
  PeriphClkInit.Usart1ClockSelection = RCC_USART1CLKSOURCE_PCLK1;
  if (HAL_RCCEx_PeriphCLKConfig(&PeriphClkInit) != HAL_OK)
  {
    Error_Handler();
  }
}

/**
  * @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 = 9600;
  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;
  huart1.Init.OneBitSampling = UART_ONE_BIT_SAMPLE_DISABLE;
  huart1.AdvancedInit.AdvFeatureInit = UART_ADVFEATURE_NO_INIT;
  if (HAL_UART_Init(&huart1) != HAL_OK)
  {
    Error_Handler();
  }
  /* USER CODE BEGIN USART1_Init 2 */
  __HAL_UART_ENABLE_IT(&huart1, UART_IT_RXNE);
  /* 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_GPIOF_CLK_ENABLE();
  __HAL_RCC_GPIOA_CLK_ENABLE();
  __HAL_RCC_GPIOB_CLK_ENABLE();

  /*Configure GPIO pin Output Level */
  HAL_GPIO_WritePin(GPIOA, LED_Pin|TEN_Pin|Relay1_Pin, GPIO_PIN_RESET);

  /*Configure GPIO pin Output Level */
  HAL_GPIO_WritePin(Relay2_GPIO_Port, Relay2_Pin, GPIO_PIN_RESET);

  /*Configure GPIO pins : IN2_Pin IN1_Pin Button_Pin */
  GPIO_InitStruct.Pin = IN2_Pin|IN1_Pin|Button_Pin;
  GPIO_InitStruct.Mode = GPIO_MODE_INPUT;
  GPIO_InitStruct.Pull = GPIO_PULLUP;
  HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);

  /*Configure GPIO pins : LED_Pin Relay1_Pin */
  GPIO_InitStruct.Pin = LED_Pin|Relay1_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 pin : TEN_Pin */
  GPIO_InitStruct.Pin = TEN_Pin;
  GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
  GPIO_InitStruct.Pull = GPIO_NOPULL;
  GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH;
  HAL_GPIO_Init(TEN_GPIO_Port, &GPIO_InitStruct);

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

}

/* USER CODE BEGIN 4 */
void present_node(void)
{
  present(NODE_SENSOR_ID, S_ARDUINO_NODE,"STM Relay Board");
  sendSketchInfo("Relay_STM", "1.1");
  present(IN_ID1, S_DOOR, "Input ID1");
  present(IN_ID2, S_DOOR, "Input ID2");
  present(RELAY_ID1, S_BINARY, "Relay 1");
  present(RELAY_ID2, S_BINARY, "Relay 2");
  registerNode();
  HAL_Delay(20);
}

void receive(const MyMessage* mymsg)
{
	 uint8_t sensor;

	  // We only expect one type of message from controller. But we better check anyway.
	 if (mymsg->type == V_STATUS) {
	    sensor = mymsg->sensor;
	    if (sensor == 3)
	    	HAL_GPIO_WritePin(Relay1_GPIO_Port, Relay1_Pin, (mymsg->data[0]=='1')?SET:RESET);
	    if (sensor == 4)
	    	HAL_GPIO_WritePin(Relay2_GPIO_Port, Relay2_Pin, (mymsg->data[0]=='1')?SET:RESET);
	 }
}
/* 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 */

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