/*
 * MCP9808_handle.c
 *
 *      Author: Martin Mitter
 */
#include "MCP9808_handle.h"

void thermometer_set_res (uint8_t adr, uint8_t res)	{
	//choose resolution settings register
	buf[0]=REG_RES;
	ret = HAL_I2C_Master_Transmit(&hi2c2, adr, (uint8_t *)buf, 1, 500);
	if (ret != HAL_OK ) {
		Tx_error();
		return;
	}
	//set the resolution
	buf[0]=res;
	ret = HAL_I2C_Master_Transmit(&hi2c2, adr, (uint8_t *)buf, 1, 500);
	if (ret != HAL_OK ) {
		Tx_error();
		return;
	}
}

temperature_t get_temp(uint8_t adr) {
	//choose measured temperature register
	buf[0]=REG_TEMP;
	ret = HAL_I2C_Master_Transmit(&hi2c2, adr, (uint8_t *)buf, 1, 500);
	if (ret != HAL_OK ) {
		Tx_error();
		return 666*TEMP_SCALE;
		}
	//read 2B from temperature reg.
	ret = HAL_I2C_Master_Receive(&hi2c2, adr, (uint8_t *)buf, 2, 500);
	if (ret != HAL_OK ) {
		Rx_error();
		return 666*TEMP_SCALE;
	}
	//raw data to float
	int flag_zero=buf[0]&0x1000;	//get symptom of negative temperature
	buf[0] = buf[0] & 0b00011111;	//mask non-essential bits

	Temperature = (buf[0] * TEMP_SCALE * 16);
	Temperature += (buf[1] * TEMP_SCALE) / 16;
	if(flag_zero) {
		Temperature=(256*TEMP_SCALE)-Temperature;
	}
	HAL_GPIO_WritePin(error_red_GPIO_Port, error_red_Pin, 0);
	HAL_GPIO_WritePin(error_green_GPIO_Port, error_green_Pin, 1);
	return Temperature;
}

void Tx_error() {
	lcd_clear();
	lcd_put_cur(1,0);
	lcd_send_string("ErrorTx-set res");
	HAL_GPIO_WritePin(error_red_GPIO_Port, error_red_Pin, 1);
	HAL_GPIO_WritePin(error_green_GPIO_Port, error_green_Pin, 0);
	HAL_Delay(1500);
	Set_temp_output();
}

void Rx_error() {
	lcd_clear();
	lcd_put_cur(1,0);
	lcd_send_string("ErrorRx-set res");
	HAL_GPIO_WritePin(error_red_GPIO_Port, error_red_Pin, 1);
	HAL_GPIO_WritePin(error_green_GPIO_Port, error_green_Pin, 0);
	HAL_Delay(1500);
	Set_temp_output();
}

void print_temp(temperature_t Temp, uint8_t row, uint8_t column) {
	//Temperature data to string
	sprintf(text, "%s%2li,%02lu%s",
			((Temp < 0) ? ("-") : ("+")),
			((Temp < 0) ? (-Temp  / TEMP_SCALE) : Temp / TEMP_SCALE),
			((Temp < 0) ? (-Temp  % TEMP_SCALE) : Temp % TEMP_SCALE),
			DEGREE_CELS);
  	lcd_put_cur(row, column);
  	lcd_send_string(text);
}
