#include "stm32l1xx_hal.h"
#include "core/csect.h"
#include "core/config.h"
#include "core/config_pins.h"
#include "drivers/power_management/power_management.h"
#include "drivers/adc/adc.h"
#include "app/led/led.h"

static bool PM_Init();
static void PM_DeInit();
static void INPTRG( bool state );
static void INPTRG_1( bool state );
static void INPTRG_EN( bool state );
static void EXT_REG_MR( bool state );
 
 const PM_Handle_t PMHandle = {

    PM_Init,
    PM_DeInit,
    INPTRG,
    INPTRG_1,
    INPTRG_EN,
    EXT_REG_MR
 };

static inline void INPTRG( bool state )
{
    HAL_GPIO_WritePin( CONFIG_PORT__INPTRG, CONFIG_PIN__INPTRG, (state)?GPIO_PIN_SET:GPIO_PIN_RESET );
}

static inline void INPTRG_1( bool state )
{
    HAL_GPIO_WritePin( CONFIG_PORT__INPTRG_1, CONFIG_PIN__INPTRG_1, (state)?GPIO_PIN_SET:GPIO_PIN_RESET );
}

static inline void INPTRG_EN( bool state )
{
    HAL_GPIO_WritePin( CONFIG_PORT__INPTRG_EN, CONFIG_PIN__INPTRG_EN, (state)?GPIO_PIN_SET:GPIO_PIN_RESET );
}

static inline void EXT_REG_MR( bool state )
{
    HAL_GPIO_WritePin( CONFIG_PORT__EXT_REG_MR, CONFIG_PIN__EXT_REG_MR, (state)?GPIO_PIN_SET:GPIO_PIN_RESET );
}
 
 static bool PM_Init()
 {
   bool bRet = true;
   DI();
   GPIO_InitTypeDef GPIO_CTRL = {0};
   GPIO_CTRL.Pin = CONFIG_PIN__INPTRG | CONFIG_PIN__INPTRG_1; 
   GPIO_CTRL.Mode = GPIO_MODE_INPUT;
   GPIO_CTRL.Pull = GPIO_PULLUP;
   GPIO_CTRL.Speed = GPIO_SPEED_FREQ_MEDIUM;        
   HAL_GPIO_Init(CONFIG_PORT__INPTRG, &GPIO_CTRL);
   
   GPIO_InitTypeDef GPIO_CTRL_PWR = {0};
   GPIO_CTRL_PWR.Pin = CONFIG_PIN__EXT_REG_MR | CONFIG_PIN__INPTRG_EN; 
   GPIO_CTRL_PWR.Mode = GPIO_MODE_OUTPUT_PP;
   GPIO_CTRL_PWR.Pull = GPIO_PULLUP;
   GPIO_CTRL_PWR.Speed = GPIO_SPEED_FREQ_MEDIUM;        
   HAL_GPIO_Init(CONFIG_PORT__EXT_REG_MR, &GPIO_CTRL_PWR);
   
   //VRF_EN_5(false); // Выключаем питание на плату управления (FPGA)
   INPTRG_EN(true); // Запрет триггера от VNA
   EXT_REG_MR(false);  // PowerUP with active RESET signal on external shift REG
   EI();

   // После инициализации необходима задержка 0.5 секунд!!!
   return bRet;
 }

static void PM_DeInit()
{  
    
}