#include "stm32f0xx_hal.h"
#include "logic.h"
#include "pwm_in.h"
#include "gpio.h"
#include "pwm_out.h"


#define LED_ON      HAL_GPIO_WritePin(GPIOA, GPIO_PIN_2, GPIO_PIN_RESET);
#define LED_OFF     HAL_GPIO_WritePin(GPIOA, GPIO_PIN_2, GPIO_PIN_SET);

static uint8_t step_number = 0;

static IWDG_HandleTypeDef   IwdgHandle;


//
void logic_main(void)
{
    HAL_IWDG_Refresh(&IwdgHandle);
      
    if (get_button()) 
    {
        gpio_set_output(true);
        LED_ON;
        HAL_Delay(500);
        HAL_IWDG_Refresh(&IwdgHandle);
        LED_OFF;
        HAL_Delay(500);
        HAL_IWDG_Refresh(&IwdgHandle);
        logic_set_out_pwm();
        HAL_Delay(500);
        HAL_IWDG_Refresh(&IwdgHandle);
        gpio_set_output(false);
        tim_pwm_pulse_idle();
        
        set_button(false);
    }   
    
}

//
void logic_set_out_pwm(void)
{
    switch (step_number)
    {
        case 0:
            tim_pwm_out_set_pulse(PWM_OUT_CH_1, 1300);
        break;
    
        case 1:
            tim_pwm_out_set_pulse(PWM_OUT_CH_2, 1300);
        break;
    
        case 2:
            tim_pwm_out_set_pulse(PWM_OUT_CH_1, 1850);
        break;
    
        case 3:
            tim_pwm_out_set_pulse(PWM_OUT_CH_2, 1850);
        break;
    
        default : break;
    }
    
    step_number = step_number == 3 ? 0 : step_number + 1;
}

//
void wdt_init(void)
{
    RCC_OscInitTypeDef RCC_OscInitStruct;
  
    RCC_OscInitStruct.OscillatorType =  RCC_OSCILLATORTYPE_LSI;
    RCC_OscInitStruct.PLL.PLLState = RCC_PLL_NONE;
    RCC_OscInitStruct.LSIState = RCC_LSI_ON;
    HAL_RCC_OscConfig(&RCC_OscInitStruct);
    
    IwdgHandle.Instance = IWDG;
    IwdgHandle.Init.Prescaler = 32;
    IwdgHandle.Init.Reload = 1000;
    IwdgHandle.Init.Window = IWDG_WINDOW_DISABLE;
    
    HAL_IWDG_Init(&IwdgHandle);
}