#include "m31820.h"

struct {
  uint8_t sign;
  uint8_t integer_part;
  uint16_t float_part;
} temp_float;

  
void m31820_print_float(uint32_t usart){
  if(temp_float.sign)
    printstr_blocking(usart,"-");
  print_uint(usart,temp_float.integer_part);
  if(temp_float.float_part){
    printstr_blocking(usart,".");
    if(temp_float.float_part<1000)
      printstr_blocking(usart,"0");
    print_uint(usart,temp_float.float_part);

  }
}

void m31820_conv(uint8_t num,uint8_t bits,uint64_t rom){
  uint8_t conf;
  uint16_t tconv;
  uint64_t scratchpad;
  uint8_t crc;
  uint32_t t;
  D1W_write8(num,M31820_WRITE_SCRATCHPAD);
  D1W_write8(num,0);
  D1W_write8(num,0);    
  switch(bits){
  case 9:
    tconv = TCONV_9BITS;
    conf = M31820_CONFIG_9BITS;
    break;
  case 10:
    tconv= TCONV_10BITS;
    conf = M31820_CONFIG_10BITS;
    break;
  case 11:
    tconv = TCONV_11BITS;
    conf = M31820_CONFIG_11BITS;
    break;
  case 12:
    tconv = TCONV_12BITS;
    conf = M31820_CONFIG_12BITS;
    break;
  }
  D1W_write8(num,conf);
  D1W_detect_presence(num);
  D1W_matchrom(num,rom);
  D1W_write8(num,M31820_CONVERT);
  D1W_blockfor_ms(num,tconv);
  D1W_detect_presence(num);
  D1W_matchrom(num,rom);
  D1W_write8(num,M31820_READ_SCRATCHPAD);
  scratchpad = D1W_read64(num);
  crc =  D1W_read8(num);
  if(crc == D1W_getcrc(((uint8_t*)&scratchpad),8)){
    uint8_t tlsb = *((uint8_t*) &scratchpad);
    uint8_t tmsb = *(((uint8_t*) &scratchpad)+1);

    // datasheet p 6
    if(tmsb & 0x80){
      // negative temp
       temp_float.sign=1;
       tmsb = ~tmsb;
       tlsb = ~tlsb;       
    }else{
      // positive temp
      temp_float.sign=0;
    }
    temp_float.integer_part = (tmsb << 4) | (tlsb >>4);
    temp_float.float_part   = (tlsb & 7) * 625;
    
    /*
    print_hex_64(USART1,scratchpad);
    printstr_rn(USART1);
    printstr_blocking(USART1,"CRC:");
    print_hex_8(USART1,crc);
    printstr_rn(USART1);
    printstr_blocking(USART1,"MSB:");
    print_hex_8(USART1,tmsb);
    printstr_rn(USART1);
    printstr_blocking(USART1,"LSB:");
    print_hex_8(USART1,tlsb);
    printstr_rn(USART1);
    */
    
    printstr_blocking(USART1,"temperature read :");
    m31820_print_float(USART1);
    printstr_rn(USART1);
  }


  
  
  
}

uint32_t m31820_get_temp(uint8_t num,uint8_t id){
  uint64_t rom =  D1W_get_rom(id);
  if(!rom)
    return -1;
  GPIOC_ODR ^= (1<<13);
  GPIOC_ODR ^= (1<<13);
  D1W_detect_presence(num);
  D1W_matchrom(num,rom);
  m31820_conv(num,12,rom);
  


}
