/* therm.c */

#include "common.h"
#include "therm.h"

#include "spi.h"

uint8_t therm_cjth;
uint8_t therm_cjtl;
uint8_t therm_ltcbh;
uint8_t therm_ltcbm;
uint8_t therm_ltcbl;
uint8_t therm_sr;

void therm_init(void)
{
    spi_init();

    spi_start();
    spi_txbyte(0x80);
    spi_txbyte(0x91); /* Automatic conversion, open detection on, 50Hz */
    spi_txbyte(0x03); /* No averaging, K-type */
    spi_txbyte(0x00); /* No masking. ~FAULT asserted for most faults. */
    spi_stop();
}

void therm_read(void)
{
    spi_start();
    spi_txbyte(0x0a);
    therm_cjth  = spi_rxbyte();
    therm_cjtl  = spi_rxbyte();
    therm_ltcbh = spi_rxbyte();
    therm_ltcbm = spi_rxbyte();
    therm_ltcbl = spi_rxbyte();
    therm_sr    = spi_rxbyte();
    spi_stop();
}

temp_t therm_reduce(int32_t temp)
{
    temp = (temp * 10) / 4096;
    temp += 2732;
    if (temp < 0)
        temp = 0;
    if (temp > 65535)
        temp = 65535;

    return (temp_t) temp;
}

temp_t therm_coldtemp(void)
{
    int16_t temp = (int16_t) (((int16_t)therm_cjth << 8) | therm_cjtl);
    return therm_reduce((int32_t)temp * 16);
}

temp_t therm_temp(void)
{
    int32_t temp = ((int32_t)therm_ltcbh << 16) | ((int32_t)therm_ltcbm << 8) | therm_ltcbl;

    return therm_reduce(temp);
}

uint8_t therm_fault(void)
{
    return therm_sr;
}
