
#include <stdint.h>

#include "nrf_delay.h"
#include "nrf_gpio.h"
#include "io.h"
#include "ba.h"
#include "charger.h"

void charger_init()
{
  nrf_gpio_cfg_input(IO_CHARGER_CONNECTED_PIN, NRF_GPIO_PIN_NOPULL);
}

int charger_is_active()
{
  return (nrf_gpio_pin_read(IO_CHARGER_CONNECTED_PIN) != 0);
}

int charger_get_batt_voltage()
{
  int voltage;
  nrf_gpio_cfg_output(IO_CHARGER_BATT_MEASURE_ENABLE);
  nrf_gpio_pin_clear(IO_CHARGER_BATT_MEASURE_ENABLE);
  nrf_delay_ms(3);
  voltage = ba_read_battery_mv()*2;
  nrf_gpio_cfg_input(IO_CHARGER_BATT_MEASURE_ENABLE, NRF_GPIO_PIN_NOPULL);
  return voltage;
}

/*void charger_update()
{
  uint8_t charger_connected = nrf_gpio_pin_read(IO_CHARGER_CONNECTED_PIN);
  uint16_t batt_voltage;
  nrf_gpio_pin_clear(IO_CHARGER_BATT_MEASURE_ENABLE);							// Sets the pin to low so the bat voltage can be read properly
  batt_voltage = ba_read_battery();
  nrf_gpio_pin_set(IO_CHARGER_BATT_MEASURE_ENABLE);								// Disables the battery voltage divider so minimal current flows
  nrf_adc_input_select(NRF_ADC_CONFIG_INPUT_2);	// Switches the ADC selection back to the Breathalizer ADC INPUT
  nrf_delay_ms(5);
  if (charger_connected) 
  {
    if (batt_voltage < BATT_MAX_LEVEL) 
    {
      m_led_flash_timer++;
      if (m_led_flash_timer >= HALF_SECOND_20_MS) 
      {
        // Flash rate of once per second (on 1/2 sec, off 1/2 sec)
        //nrf_gpio_pin_toggle(LED_PIN);
        m_led_flash_timer = 0;
      }
    } 
    else if (BatteryVoltage >= BATT_MAX_LEVEL) 
    {
      //nrf_gpio_pin_clear(LED_PIN);
      m_led_flash_timer = 0;
    }
  }
  else 
  {
    //nrf_gpio_pin_set(LED_PIN);
    m_led_flash_timer = 0;
  }
}*/
