/**
  ******************************************************************************
  * @file    Radio.c
  * @author  Johan Zwarteveld
  * @version V0.1
  * @date    04-08-2015
  * @brief   Radio Driver
  ******************************************************************************
  */

/* Includes ------------------------------------------------------------------*/
#include "Radio.h"

/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
/* Private macro -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* Private function prototypes -----------------------------------------------*/
static void Radio_WriteSettings(const rfsettings *settings);
static void Radio_WritePATable(const uint8_t *patable, uint8_t count);
/* Exported functions --------------------------------------------------------*/
void Radio_Init(void)
{
	/* Set the High-Power Mode Request Enable bit so LPM3 can be entered with active radio enabled */
	PMMCTL0_H = 0xA5;
	PMMCTL0_L |= PMMHPMRE_L;
	PMMCTL0_H = 0x00;

	Radio_Reset();

	// Write Configuration
	Radio_WriteSettings(&RadioSettings_868MHz_38kBaud);
	Radio_WritePATable(patablesettings, 8);

}
void Radio_Reset(void)
{
	HAL_RF1A_CommandStrobe(RF_SRES);		// Reset radio
	HAL_RF1A_CommandStrobe(RF_SNOP);		// Reset radio pointer
}

void Radio_Transmit(uint8_t *buffer, uint8_t count)
{
	RF1AIES |= BIT9;                          					// Raise interrupt on falling edge
	RF1AIN &= ~BIT9;
	RF1AIFG &= ~BIT9;                         					// Clear pending interrupts
	RF1AIE |= BIT9;                           					// Enable TX end-of-packet interrupt

	HAL_RF1A_RegisterBurstWrite(RF_TXFIFOWR, buffer, count);	// write transmit fifo

	HAL_RF1A_CommandStrobe( RF_STX );             	            // Strobe STX to start transmit.
//TODO hang point
	if ((RF1AIE & BIT9) == BIT9)
	{
		__no_operation();
		__bis_SR_register(LPM1_bits + GIE);
	}

	HAL_RF1A_CommandStrobe( RF_SFTX );             	            // Strobe STX to start transmit.
	HAL_RF1A_CommandStrobe( RF_SPWD );             	            // Strobe STX to start transmit.
}
/* Private functions  --------------------------------------------------------*/
static void Radio_WriteSettings(const rfsettings *settings)
{
	HAL_RF1A_RegisterBurstWrite(IOCFG2, (uint8_t *) settings, sizeof(rfsettings));
}

static void Radio_WritePATable(const uint8_t *patable, uint8_t count)
{
	HAL_RF1A_RegisterBurstWrite(PATABLE, (uint8_t *)patable, count);

	HAL_RF1A_CommandStrobe(RF_SNOP);
}
/* Interrupt Service Routine -------------------------------------------------*/
