#include "interface.h"
#include "usbtenki_cmds.h"
#include "oddebug.h"
#include "i2c.h"
#include "mcp9800.h"
#include <util/delay.h>     /* for _delay_ms() */
#include <avr/wdt.h>

#define MCP9800_ADDR    (MCP9800_ADDR_BASE + 7)
void set_address(unsigned char addr);
/* each bit value stands for a sensor. 0 = offline, 1 = online. */
static unsigned int stat = 0;

/* come back good if at least one sensor came up 
 * Good meaning we return false as the interface dictates.
 * So if stat is 0 non of the sensors came up and that's bad.
 */
int sensors_init(void)
{
	unsigned char i;
	unsigned int b;
	i2c_init();
	DBG1(0x50, &stat , 2);
	for (i = 0; i < MAX_DAC; i++) {
		set_address(i);
		DBG1(0x51, &i , 1);
		if (!mcp9800_configure(MCP9800_ADDR, MCP9800_CFG_12BITS)) {
			b = 1 << i;
			DBG1(0x5a, &b , 2);
			stat  |= _BV(i);
			DBG1(0x52, &stat , 2);
		}
	}
	DBG1(0x53, &stat , 2);
	return stat == 0;
}

int sensors_getNumChannels(void)
{
	return MAX_DAC;
}

int sensors_getChipID(unsigned char id)
{
	return USBTENKI_CHIP_MCP98_00 + id;
}
	
void set_address(unsigned char addr)
{
	_SETDACBIT(0, addr);
	_SETDACBIT(1, addr);
	_SETDACBIT(2, addr);
	_SETDACBIT(3, addr);
	/* a little settling time */
	_delay_us(10);
}

int sensors_getRaw(unsigned char id, unsigned char *dst)
{
	int res;
	if (!(stat & _BV(id))) {
		/* not initialized so zap the reading */
		DBG1(0x60, &id , 1);
		dst[0] = 0x80;
		dst[1] = 0x00;
		return 2;
	}
	set_address(id);
	res = mcp9800_readRegister(MCP9800_ADDR, MCP9800_REG_TEMP, dst, 2);
	if (res) {
		/* we had an error so zap the reading */
		DBG1(0x61, &res , 1);
		dst[0] = 0x80;
		dst[1] = 0x00;
		/* also take sensor offline */
		stat &= ~_BV(id);
		DBG1(0x62, &stat , 1);
		if (!stat) while(1) { /* timeout for a reset */ }
		return res;
	}
	return 2;
}


