#include <stdint.h>
#include <string.h>

#include "nrf_gpio.h"
#include "lmp.h"
#include "twi.h"

//Not used:
//#include "app_util_platform.h"
//#include "ba.h"
//#include "io.h"
//#include "nrf_drv_adc.h"
//#include "nrf_delay.h"

#define LMP_ADDR                        (0b10010000 >> 1)
#define LMP_STATUS_REGISTER_ADDR        0x00
#define LMP_LOCK_REGISTER_ADDR          0x01
#define LMP_TIACN_REGISTER_ADDR 	0x10
#define LMP_REFCN_REGISTER_ADDR 	0x11
#define LMP_MODE_REGISTER_ADDR          0x12

void lmp_enable()
{
  nrf_gpio_pin_clear(LMP_ENABLE_PIN);
}

void lmp_disable()
{
  nrf_gpio_pin_set(LMP_ENABLE_PIN);
}
        
void lmp_init()
{
  // Configure LMP enable pin as output
  nrf_gpio_cfg_output(LMP_ENABLE_PIN);
  // Enable LMP TWI IO
  nrf_gpio_pin_clear(LMP_ENABLE_PIN); 
  // Unlock TIA and REF register writes
  lmp_unlock();
  // Set LMP FET_SHORT = OFF (Ox00), OP_MODE = 3_LD_AMP (0x03)
  lmp_write_modecn(0x03);
  // Set LMP TIA GAIN_R = 120K (0x18), LOAD_R = 10Ohm (0x00)
  lmp_write_tiacn(0x18);
  // Set LMP REF_SRC = EXT (0x80), REF_ZERO = 20% (0x00), 
      // BIAS_POLARITY = + (0x10), BIAS_LEVEL = 4% (0x03)
  lmp_write_refcn(0x80 + 0x10 + 0x03);
  lmp_lock(); // Lockout writes to TIA and REF registers
  nrf_gpio_pin_set(LMP_ENABLE_PIN); // disable LMP TWI IO
}

void lmp_unlock()
{
  // RAR - added register address to enable single transaction register writes
  //        ditto all register writes below
  twi_reg_write(LMP_ADDR, LMP_LOCK_REGISTER_ADDR, 0x00);
  //twi_write(LMP_ADDR, LMP_LOCK_REGISTER_ADDR);
  //twi_write(LMP_ADDR, 0x00);  clear lock bit
}

void lmp_lock()
{
  twi_reg_write(LMP_ADDR, LMP_LOCK_REGISTER_ADDR, 0x01);
}

void lmp_write_tiacn(uint8_t input)
{
  twi_reg_write(LMP_ADDR, LMP_TIACN_REGISTER_ADDR, input);
}

void lmp_write_refcn(uint8_t input)
{
  twi_reg_write(LMP_ADDR, LMP_REFCN_REGISTER_ADDR, input);
}

void lmp_write_modecn(uint8_t input)
{
  twi_reg_write(LMP_ADDR, LMP_MODE_REGISTER_ADDR, input);
}

uint8_t lmp_read_status()
{
  uint8_t buffer;
  twi_write(LMP_ADDR, LMP_STATUS_REGISTER_ADDR);
  buffer = twi_read(LMP_ADDR);
  return buffer;
}

uint8_t lmp_read_tiacn()
{
  uint8_t buffer;
  twi_write(LMP_ADDR, LMP_TIACN_REGISTER_ADDR);
  buffer = twi_read(LMP_ADDR);
  return buffer;
}

uint8_t lmp_read_refcn()
{
  uint8_t buffer;
  twi_write(LMP_ADDR, LMP_REFCN_REGISTER_ADDR);
  buffer = twi_read(LMP_ADDR);
  return buffer;
}

uint8_t lmp_read_modecn()
{
  uint8_t buffer;
  twi_write(LMP_ADDR, LMP_MODE_REGISTER_ADDR);
  buffer = twi_read(LMP_ADDR);
  return buffer;
}

uint8_t lmp_read_lock()
{
  uint8_t buffer;
  twi_write(LMP_ADDR, LMP_LOCK_REGISTER_ADDR);
  buffer = twi_read(LMP_ADDR);
  return buffer;
}