/******************************************************************************
  Filename: comlab_wrapper.c
  
  Description: 

  Notes: 
  
******************************************************************************/

/******************************************************************************
 * INCLUDES
 */
#include "hal_mcu.h"
#include "hal_spi_rf_trxeb.h"
#include "comlab_wrapper_trxeb.h"
#include "hal_board.h"
#include "comlab_rf.h"
/*******************************************************************************
* VARIABLES
*/
uint16 voltageThreshold;
/*******************************************************************************
* @fn          halBoardInit
*
* @brief       Init MCU
* @param       none
*
* @return      none
*/
void halBoardInit(void) {
  
  uint8 mclkFrequency;
  
  // Stop watchdog timer to prevent time out reset
  WDTCTL = WDTPW + WDTHOLD;
  
  // Initialize all GPIO configurations
  /* Settingcapacitor values for XT1, 32768 Hz */
    halMcuStartXT1();
    /* Clocks:
    * mclk  = mclkFrequency
    * smclk = mclkFrequency
    * aclk  = 32768 Hz
    */
    mclkFrequency = HAL_MCU_SYSCLK_8MHZ;
    halMcuSetSystemClock(mclkFrequency);

    /* Initialize LEDs as off */
    halLedInit();

    /* De-assert SPI CSn pins as default */
    MCU_IO_OUTPUT(HAL_BOARD_IO_LCD_CS_PORT,HAL_BOARD_IO_LCD_CS_PIN,1);      // LCD
    MCU_IO_OUTPUT(HAL_BOARD_IO_ACC_CS_PORT,HAL_BOARD_IO_ACC_CS_PIN,1);      // Accelerometer
    MCU_IO_OUTPUT(HAL_BOARD_IO_FLASH_CS_PORT,HAL_BOARD_IO_FLASH_CS_PIN,1);  // SPI Flash
    MCU_IO_OUTPUT(HAL_BOARD_RF_SPI0_CS_PORT,HAL_BOARD_RF_SPI0_CS_PIN,1);    // RF_SPI0
    MCU_IO_OUTPUT(HAL_BOARD_RF_SPI1_CS_PORT,HAL_BOARD_RF_SPI1_CS_PIN,1);    // RF_SPI1

    /* Power off MSP controlled peripheral units (IO default is GPIO input tristate) */
    MCU_IO_OUTPUT(HAL_BOARD_IO_FLASH_RST_PORT,HAL_BOARD_IO_FLASH_RST_PIN,0);            // Hold SPI flash in reset (to avoid inadvertent writes)
    MCU_IO_INPUT(HAL_BOARD_IO_ACC_PWR_PORT,HAL_BOARD_IO_ACC_PWR_PIN,MCU_IO_PULLDOWN);   // Accelerometer as pulldown
    MCU_IO_INPUT(HAL_BOARD_IO_ALS_PWR_PORT,HAL_BOARD_IO_ALS_PWR_PIN,MCU_IO_PULLDOWN);   // Lightsensor as pulldown

  
  // Care must be taken when handling power modes
  // - Peripheral units can request clocks and have them granted even if
  //   the system is in a power mode. Peripheral clock request is enabled
  //   as default.
  // - Simple Link only needs ACLK to be enabled to timers
  //   during power mode operation
  halMcuDisablePeripheralClockRequest((MCLKREQEN+SMCLKREQEN));

  // SPI flash uses same SPI interface as LCD -- we'll disable the SPI flash
  P8SEL &= BIT6; // ioflash_csn = gp. 
  P8DIR |= BIT6; // tpflash_csn = ouut.
  P8OUT |= BIT6; // flash_csn = 1.     
  
  // Init leds 
  halLedInit();

  // Init Buttons
  halButtonsInit();
  halButtonsInterruptEnable();

  // Init LCD
  halLcdInit();

  // Instantiate tranceiver RF spi interface to SCLK ~ 4 MHz */
  //input clockDivider - SMCLK/clockDivider gives SCLK frequency
  trxRfSpiInterfaceInit(0x02);

  // Enable global interrupt
  _BIS_SR(GIE);
}

/*******************************************************************************
* @fn          halLcdWriteLine
*
* @brief       Write line on LCD
*
* @param       line - line on display
*              text - text string
*
* @return      none
*/
void halLcdWriteLine(uint8 line, const char* text) {
  if (line == 1) {
    for (uint8 i = 0; i < 8; i++)
      halLcdClearHLine(0, 0, 127, i);
    
    halLcdPrintString(0, (char*)text, 0, 0);
  }
  else {
    for (uint8 i = 16; i < 24; i++)
      halLcdClearHLine(0, 0, 127, i);
       
    halLcdPrintString(0, (char*)text, 0, 2);
  }
  halLcdSendBuffer(0);
  halMcuWaitUs(5000);
}
/*******************************************************************************
* @fn          initAdc
*
* @brief       Init Adc on the MSP430 on trxEB
* @param       none
*
* @return      none
*/
void initAdc(uint8 powerSource) {
  
  // Set voltage threshold for brown out detection
  switch(powerSource){
   case POWER_SOURCE_BATT:
    voltageThreshold = VOLTAGE_3_0V;
    break;
   case POWER_SOURCE_EXT:
    voltageThreshold = VOLTAGE_1_8V;
    break;
   default:
    voltageThreshold = VOLTAGE_3_0V;
    break;
  }
  ADC12CTL0 &= ~ADC12ENC;				                    // Disable ADC
  // Initialize ADC12_A 
  ADC12CTL0 = ADC12ON+ADC12SHT0_8+ADC12MSC; // Turn on ADC12, set sampling time set multiple sample conversion
  
  // Initialize REF module /
  // Enable 2.0V shared reference, disable temperature sensor to save power
  REFCTL0 |= REFMSTR + REFVSEL_0 + REFON + REFTCOFF;
  ADC12MCTL0 |= ADC12SREF_1; //Select reference
  
  // Wait for reference to settle                                                     
  while(REFCTL0 & REFGENBUSY);                                       // Allow internal reference to stabilize
 
  //ADC12MCTL0 |= ADC12INCH_13;                // Input channel A13
  ADC12MCTL0 |= ADC12INCH_11;                // Input channel A13
  
  ADC12CTL1 = ADC12SHP + ADC12CONSEQ_2;       // Use sampling timer, set mode
  ADC12CTL2 = ADC12RES_0;                  // Set lowest resolution
  ADC12IE = 0x01;                           // Enable ADC12IFG.0

  // Enable and start conversion
  ADC12CTL0 |= ADC12ENC + ADC12SC;  // Enable conversions + Start conversion
}
#pragma vector=ADC12_VECTOR
__interrupt void ADC12ISR (void)
{
  

  if(ADC12MEM0 < voltageThreshold){ 
    comlabRfStopRadio();
    halLedSet(LED_ALL); // for debug
    halMcuWaitMs(2000);
    PMMCTL0 |= PMMSWBOR; // software enabled BOR for the MSP
    
  }
  else{ // for debug
    halLedClear(LED_ALL);
  }
  // Clear interrupt flag
  ADC12IFG &= ADC12IFG0;
}
/*******************************************************************************
  Copyright 2013 Texas Instruments Incorporated. All rights reserved.

  IMPORTANT: Your use of this Software is limited to those specific rights
  granted under the terms of a software license agreement between the user
  who downloaded the software, his/her employer (which must be your employer)
  and Texas Instruments Incorporated (the "License").  You may not use this
  Software unless you agree to abide by the terms of the License. The License
  limits your use, and you acknowledge, that the Software may not be modified,
  copied or distributed unless embedded on a Texas Instruments microcontroller
  or used solely and exclusively in conjunction with a Texas Instruments radio
  frequency transceiver, which is integrated into your product.  Other than for
  the foregoing purpose, you may not use, reproduce, copy, prepare derivative
  works of, modify, distribute, perform, display or sell this Software and/or
  its documentation for any purpose.

  YOU FURTHER ACKNOWLEDGE AND AGREE THAT THE SOFTWARE AND DOCUMENTATION ARE
  PROVIDED “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED,
  INCLUDING WITHOUT LIMITATION, ANY WARRANTY OF MERCHANTABILITY, TITLE,
  NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL
  TEXAS INSTRUMENTS OR ITS LICENSORS BE LIABLE OR OBLIGATED UNDER CONTRACT,
  NEGLIGENCE, STRICT LIABILITY, CONTRIBUTION, BREACH OF WARRANTY, OR OTHER
  LEGAL EQUITABLE THEORY ANY DIRECT OR INDIRECT DAMAGES OR EXPENSES
  INCLUDING BUT NOT LIMITED TO ANY INCIDENTAL, SPECIAL, INDIRECT, PUNITIVE
  OR CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, COST OF PROCUREMENT
  OF SUBSTITUTE GOODS, TECHNOLOGY, SERVICES, OR ANY CLAIMS BY THIRD PARTIES
  (INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), OR OTHER SIMILAR COSTS.

  Should you have any questions regarding your right to use this Software,
  contact Texas Instruments Incorporated at www.TI.com.
***********************************************************************************/