/**
******************************************************************************
* @file    ow_port.c
* @brief   This file includes the driver for port for OneWire purposes
******************************************************************************
*/
#include "ow_port.h"
#include "onewire.h"
#include "tim.h"

/**
  * @brief  The internal function is used as gpio pin mode
  * @param  OW		OneWire HandleTypedef
  * @param  Mode	Input or Output
  */
void OneWire_Pin_Mode(OneWire_t* OW, PinMode Mode)
{
#ifdef CMSIS_Driver
	if(Mode == Input)
	{
    OW->DataPort->MODER &= ~((GPIO_MODER_MODE0_Msk) << 0);
    OW->DataPort->MODER |= (GPIO_MODE_INPUT << (0+2));
	}else{
    OW->DataPort->MODER &= ~((GPIO_MODER_MODE0_Msk) << 0);
    OW->DataPort->MODER |= (GPIO_MODE_OUTPUT_PP << 0);
	}
#else
#ifdef LL_Driver
	if(Mode == Input)
	{
		LL_GPIO_SetPinMode(OW->DataPort, OW->DataPin, LL_GPIO_MODE_INPUT);
	}else{
		LL_GPIO_SetPinMode(OW->DataPort, OW->DataPin, LL_GPIO_MODE_OUTPUT);
	}
#else
	GPIO_InitTypeDef GPIO_InitStruct = {0};
	GPIO_InitStruct.Pin = OW->DataPin;
	if(Mode == Input)
	{
		GPIO_InitStruct.Mode = GPIO_MODE_INPUT;
	}else{
		GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
    GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH;
	}
	HAL_GPIO_Init(OW->DataPort, &GPIO_InitStruct);
#endif
#endif
}

/**
  * @brief  The internal function is used as gpio pin level
  * @param  OW		OneWire HandleTypedef
  * @param  Mode	Level: Set/High = 1, Reset/Low = 0
  */
void OneWire_Pin_Level(OneWire_t* OW, uint8_t Level)
{
#ifdef CMSIS_Driver
  if (Level != GPIO_PIN_RESET)
  {
    OW->DataPort->BSRR = OW->DataPin;
  }
  else
  {
    OW->DataPort->BSRR = (uint32_t)OW->DataPin << 16u;
  }
#else
#ifdef LL_Driver
	if(Level == 1)
	{
		LL_GPIO_SetOutputPin(OW->DataPort, OW->DataPin);
	}else{
		LL_GPIO_ResetOutputPin(OW->DataPort, OW->DataPin);
	}
#else
	HAL_GPIO_WritePin(OW->DataPort, OW->DataPin, Level);
#endif
#endif
}

/**
  * @brief  The internal function is used to read data pin
  * @retval Pin level status
  * @param  OW		OneWire HandleTypedef
  */
uint8_t OneWire_Pin_Read(OneWire_t* OW)
{
#ifdef CMSIS_Driver
	return ((OW->DataPort->IDR & OW->DataPin) != 0x00U) ? 1 : 0;
#else
#ifdef LL_Driver
	return ((OW->DataPort->IDR & OW->DataPin) != 0x00U) ? 1 : 0;
#else
	return HAL_GPIO_ReadPin(OW->DataPort, OW->DataPin);
#endif
#endif
}

uint16_t start;
uint16_t end;
uint32_t tim_1us_period = 24;
void OneWire_Delay_uw(uint32_t us)
{
//	start = htim1.Instance->CNT;
//	end = start + us*tim_1us_period;
	TIM1->CNT = 0;
	end = us*tim_1us_period;
    
  while(TIM1->CNT < end) {};
}