/*
 * DS18B20.cpp
 *
 *  Created on: Feb 28, 2018
 *      Author: sebastian
 */



#define READ_SCRATCH	0xBE
#define WRITE_SCRATCH	0x4E
#define READ_ROM	0x33
#define SKIP_ROM	0xCC
#define CONVERT_T	0x44


#include "DS18B20.h"

/*
 * | -- 8 BIT CRC -- | -- 48 BIT SERIAL NUMBER -- | -- 8 BIT FAMILY CODE (28h) -- |
 */
uint8_t rom[8] = {0,0,0,0,0,0,0,0};
double deviceID;

/**
 * initialize the Temperature Sensor
 * This lib is written for only ONE device on the 1-Wire Bus
 */

void DS18B20_init(void){
	OneWire_init();
	if(OW_reset()){
		logger_error("Unable to reset 1-Wire Bus, no device present %s\n", strerror(errno));
		return;
	}
	logger(V_HAL, "Checking 1-Wire Bus for sensors..\n");
	DS18B20_readRom();
	deviceID = double (rom[1]);// | ROM[5] << 8 | ROM[5] << 16 | ROM[5] << 24 | ROM[5] << 32 | ROM[5] << 40);
	if(rom[7] == 0x28){
		logger(V_HAL, "Found temperature sensor on 1-Wire Bus\n");
		logger(V_HAL, "Device ID: %12X\n", deviceID);
	}
}

void DS18B20_readRom(void){
	OW_writeByte(READ_ROM);
	int i;
	for(i = 7; i >= 0; i--){
		rom[i] = OW_readByte();
	}
}

/**
 * Transmits a command to the sensor
 * @param cmd Command byte
 */

void DS18B20_cmd(uint8_t cmd) {
	if(OW_reset()){
		logger_error("Unable to reset 1-Wire Bus, no device present %s\n", strerror(errno));
	}
	OW_writeByte(SKIP_ROM);
	OW_writeByte(cmd);
}

/**
 * Reads the Temperature of the DS18B20 Sensor
 * It rounds the value read from the Sensor rounded to the next integer
 */

int8_t DS18B20_readTemp (void){
	DS18B20_cmd(CONVERT_T);
	while(!OW_readBit()){
		//wait to finish conversion
		//TODO don't wait forever
	}
	uint8_t scratchPad[9];
	uint8_t i;
	int8_t temp;

	DS18B20_cmd(READ_SCRATCH);
	for(i = 0; i < 9; i++){
		scratchPad[i] = OW_readByte();
	}
	//Information about temperature is stored in byte[0] and byte[1]
	temp = scratchPad[0] >> 4;
	temp |= (scratchPad[1] << 4) & 0xF0;
	return temp;
	//todo return a float value and do proper rounding
}
