#include "MaxHandler.h"

void Max_Init(uint8_t ch,uint8_t initMode) {
	sSPI_select(ch);

	sSPI_write_byte(0x80);
	if (initMode == AutoConversion)
		sSPI_write_byte((1<<7)|(1<<5)|(1<<0));  //Auto conversion + OC 33ms detection + 50hz rejection
	else if (initMode == OneShotConversion)
		sSPI_write_byte((1<<6)|(1<<5)|(1<<0));  //OneShot conversion + OC 33ms detection + 50hz rejection
	else 
		sSPI_write_byte((1<<5)|(1<<0));			//OC 33ms detection + 50hz rejection

	sSPI_write_byte(0b0011|(0b0011<<4));	//TC type K + 8 samples

	sSPI_free();		
	
	uint8_t i = 0;

	if (ch < THERMO_CHN_COUNT) {
		i = ch;
		++ch;
	}

	for (; i < ch; i++) {
		ThermoSensor[i].lastTick = System_GetSysTick();
		ThermoSensor[i].state = 4;	//Set NO_DATA error
		ThermoSensor[i].captureFlags = initMode; 	
	}
}

uint8_t IsMaxDRDYLow(uint8_t ch) {
	if (ch > THERMO_CHN_COUNT-1) ch = THERMO_CHN_COUNT-1;

	if ( ( RSLink_DipsRead() & (1<<(4+ch)) ) == 0) return 1;

	return 0;		
}

void Max_Handler(){
	ThermoData *Selected = &ThermoSensor[MaxSelectedChannel];

	//If conversion ready or 5s timeout
	if ((IsMaxDRDYLow(MaxSelectedChannel) || (System_GetSysTickDifference(Selected->lastTick)>2000)) && Selected->captureFlags != 0) {
			sSPI_select(MaxSelectedChannel);
			Selected->lastTick = System_GetSysTick();
			sSPI_write_byte(0x0A);
			Selected->CJTemp = (uint16_t)sSPI_read_byte()<<8;
			Selected->CJTemp |= sSPI_read_byte();
			Selected->Temperature = (uint32_t)sSPI_read_byte()<<11;
			Selected->Temperature |= (uint32_t)sSPI_read_byte()<<3;
			Selected->Temperature |= (uint32_t)sSPI_read_byte()>>5;
			Selected->state = sSPI_read_byte()&(~4);
			sSPI_free();
			if ((Selected->captureFlags & OneShotConversion) != 0){
				Selected->captureFlags &= ~(OneShotConversion);
			}
	}
		
	MaxSelectedChannel++;
	if (MaxSelectedChannel == THERMO_CHN_COUNT) MaxSelectedChannel = 0;	
}
