/* --COPYRIGHT--,BSD
 * Copyright (c) 2012, Texas Instruments Incorporated
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * *  Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * *  Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * *  Neither the name of Texas Instruments Incorporated nor the names of
 *    its contributors may be used to endorse or promote products derived
 *    from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
 * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
 * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 * --/COPYRIGHT--*/

/*******************************************************************************
 *
 * tmp006.c - Driver for the TMP006 Module.
 *
 ******************************************************************************/
#include <msp430.h>
#include <math.h>
#include "tmp006.h"

/* Holds tDie of 4 readings for transient correction
 * with tDie[0] = oldest, tdie[3] = newest
 */
long double tDie[4] = {0};

/*!
 *
 * Initializes the TMP006 for operation.
 *
 * @param drdyPinEn \b 1 \b - DRDY pin enabled \n
 *                  \b 0 \b - DRDY pin disabled
 * @param conversionTime set conversion time. Valid values are:\n
 *                       \b TMP006_CR_4 \n
 *                       \b TMP006_CR_2 \n
 *                       \b TMP006_CR_1 \n
 *                       \b TMP006_CR_0_5 \n
 *                       \b TMP006_CR_0_25 \n
 *
 * This function initializes the TMP006 temperature sensor using USCI_B0 in
 * I2C Master mode.
 *
 * It also powers up the TMP006 and assign GPIO port
 *
 * @return None.
 *
 */
void tmp006_init(unsigned char drdyPinEn, unsigned int conversionTime)
{
    /* Assign I2C pins to USCI_B0 */
    P1SEL |= BIT6 + BIT7;
    /* Assign I2C pins to USCI_B0 */
    P1SEL2|= BIT6 + BIT7;
    /* Enable SW reset */
    UCB0CTL1 |= UCSWRST;
    /* I2C Master, synchronous mode */
    UCB0CTL0 = UCMST + UCMODE_3 + UCSYNC;
    /* Use SMCLK, keep SW reset */
    UCB0CTL1 = UCSSEL_2 + UCSWRST;
    /* fSCL = SMCLK/11 = 95.3kHz */
    UCB0BR0 = 11;
    UCB0BR1 = 0;
    /* Slave Address is 048h */
    UCB0I2CSA = 0x40;
    /* Clear SW reset, resume operation */
    UCB0CTL1 &= ~UCSWRST;

    /* Reset TMP006 */
    tmp006_write(TMP006_P_WRITE_REG, TMP006_RST);

    /* Enable TMP006 with the DRDY pin used */
    if (drdyPinEn)
    {
        tmp006_write(TMP006_P_WRITE_REG, TMP006_POWER_UP + conversionTime + TMP006_EN);
    }
    else
    {
        tmp006_write(TMP006_P_WRITE_REG, TMP006_POWER_UP + conversionTime);
    }
}

/*!
 *
 * Wakes up TMP006 from power down mode without reconfiguring I2C ports.
 *
 * @param None
 *
 * @return None
 *
 */
void tmp006_wakeup(void)
{
    unsigned int settings;

    /* Read current settings */
    settings = tmp006_read(TMP006_P_WRITE_REG);

    /* Power-up TMP006 */
    settings |= TMP006_POWER_UP;

    tmp006_write(TMP006_P_WRITE_REG, settings);
}

/*!
 *
 * Disables TMP006 by putting it into power down mode.
 *
 * @param None
 *
 * @return None
 *
 */
void tmp006_disable(void)
{
    unsigned int settings;

    /* Read current settings */
    settings = tmp006_read(TMP006_P_WRITE_REG);

    /* Mask out and power down TMP006 */
    settings &= ~(TMP006_POWER_UP);

    /* Power down TMP006 */
    tmp006_write(TMP006_P_WRITE_REG, settings);
}

/*!
 *
 * Function to poll and check if TMP006 data is ready to be read out.
 * This function reads the status of DRDY from TMP006.
 *
 * @param None
 *
 * @return \b 0 \b - Data not ready \n
 *         \b 1 \b - Data is ready
 *
 */
unsigned char tmp006_ready(void)
{
    /* Read DRDY status from Config register */
    return (TMP006_DRDY & tmp006_read(TMP006_P_WRITE_REG));
}

/*!
 *
 * Function to calulate and return the temperature and raw values from TMP006
 * sensor with transient correction.
 *
 * @param None
 *
 * @return TempReading structure
 *
 */
struct TempReading tmp006_getTemp(void)
{
    struct TempReading tempRead;
    long double vObjcorr = 0;
    long double tslope = 0;
    long double alpha = 2.96 * pow(10, -4);

    /* Shift oldest tdie temp out */
    tDie[0] = tDie[1];
    tDie[1] = tDie[2];
    tDie[2] = tDie[3];

    /* Read the object voltage. Assuming that the data is ready. */
    tempRead.vObj = tmp006_read(TMP006_P_VOBJ);
    /* Read the ambient temperature */
    tempRead.tDie = tmp006_read(TMP006_P_TABT);

    /* Convert latest tDie measurement to Kelvin */
    tDie[3] = (((long double)(tempRead.tDie >> 2)) * .03125) + 273.15;

    if(tDie[0] != 0)
    {
        /* Executes only if all 4 tdie variables are non-zero */

        /* Calculate tslope */
        tslope = -(0.3*tDie[0]) - (0.1*tDie[1]) + (0.1*tDie[2]) + (0.3*tDie[3]);

        /* Correct sensor voltage */
        vObjcorr = (((long double)(tempRead.vObj)) * .00000015625) + (tslope * alpha);
    }
    else
    {
        /* Executes if all 4 tdie variables have not yet been filled */
        vObjcorr = ((long double)(tempRead.vObj)) * .00000015625;
    }

    tempRead.temp = tmp006_calculateTemp(&tDie[3], &vObjcorr);
    return tempRead;
}

/*!
 *
 * Function to calulate temperature based on tdie and vobj
 *
 * @param tDie temperature of the die converted to Kelvin
 * @param vObj object voltage converted first by multiplying 1.5625e-7
 *
 * @return temperature value in Celcius
 *
 */
long double tmp006_calculateTemp(long double * tDie, long double * vObj)
{
    /* Calculate TMP006. This needs to be reviewed and calibrated by TMP group */
    long double S0 = 6 * pow(10, -14);       /* Default S0 cal value */
    long double a1 = 1.75*pow(10, -3);
    long double a2 = -1.678*pow(10, -5);
    long double b0 = -2.94*pow(10, -5);
    long double b1 = -5.7*pow(10, -7);
    long double b2 = 4.63*pow(10, -9);
    long double c2 = 13.4;
    long double Tref = 298.15;
    long double S = S0*(1+a1*(*tDie - Tref)+a2*pow((*tDie - Tref),2));
    long double Vos = b0 + b1*(*tDie - Tref) + b2*pow((*tDie - Tref),2);
    long double fObj = (*vObj - Vos) + c2*pow((*vObj - Vos),2);
    long double Tobj = pow(pow(*tDie,4) + (fObj/S),.25);
    return (Tobj - 273.15);
}

/*!
 *
 * Reads data out of the TMP006 via I2C.
 *
 * @param writeByte is the register address to read from.
 *
 * This function reads the TMP006 temperature sensor using USCI_B0 in
 * I2C Master mode. It requires the address to point to in the device and
 * returns to the user.
 *
 * @return the value in integer.
 *
 */
int tmp006_read (unsigned char writeByte)
{
    int val = 0;

    /* I2C TX, start condition
     * This will also send out slave address
     */
    UCB0CTL1 |= UCTR + UCTXSTT;

    /* Wait for TX buffer to empty */
    while (!(IFG2&UCB0TXIFG));
    /* Send Control byte */
    UCB0TXBUF = writeByte;

    /* Wait for TX buffer to empty */
    while (!(IFG2&UCB0TXIFG));

    /* Generate Stop condition */
    UCB0CTL1 |= UCTXSTP;
    /* Wait for Stop to finish */
    while (UCB0CTL1&UCTXSTP);

    /* I2C Reciever mode */
    UCB0CTL1 &= ~UCTR;
    /* Generate Start condition Read mode
     * This sends out the slave address and continues to read
     * until you issue a STOP
     */
    UCB0CTL1 |= UCTXSTT;

    /* Wait for RX buffer to fill */
    while (!(IFG2&UCB0RXIFG));
    /* Read from I2C RX register */
    val = UCB0RXBUF;

    /* Generate Stop condition */
    UCB0CTL1 |= UCTXSTP;
    /* Wait for Stop to finish */
    while (UCB0CTL1&UCTXSTP);

    /* Shift vals to top MSB */
    val = (val << 8);

    /* Read from I2C RX Register and write to LSB of val */
    val |= UCB0RXBUF;

    /* Return val */
    return val;
}

/*!
 *
 * Writes data to TMP006 via I2C
 *
 * @param pointer is the base address of the I2C Master module.
 * @param writeByte is the clocksource.
 *
 * This function transmit data to TMP006 via the pointer and data to be
 * transmitted.
 *
 * @return None.
 *
 */
void tmp006_write (unsigned char pointer, unsigned int writeByte)
{
    /* Clear USCI_B0 TX int flag */
    IFG2 &= ~UCB0TXIFG;
    /* I2C TX, start condition
     * This will also send out slave address
     */
    UCB0CTL1 |= UCTR + UCTXSTT;

    /* Wait for TX buffer to empty */
    while (!(IFG2&UCB0TXIFG));
    /* Send pointer byte */
    UCB0TXBUF = pointer;

    /* Wait for TX buffer to empty */
    while (!(IFG2&UCB0TXIFG));
    /* Send MSB byte */
    UCB0TXBUF = (unsigned char)(writeByte>>8);

    /* Wait for TX buffer to empty */
    while (!(IFG2&UCB0TXIFG));
    /* Send LSB byte */
    UCB0TXBUF = (unsigned char)(writeByte&0x0F);

    /* Wait for TX buffer to empty */
    while (!(IFG2&UCB0TXIFG));

    /* Generate Stop condition */
    UCB0CTL1 |= UCTXSTP;
    /* Wait for Stop to finish */
    while (UCB0CTL1&UCTXSTP);
}
