#include "IDIBUS_CO2.h"

IdiBus_CO2::IdiBus_CO2 (IdiBusSerialLine *SlaveLine, uint8_t SlaveAddress) : IdiBusSlave(SlaveLine, SlaveAddress)
{
	for (uint8_t I=0; I<IDIBUS_CO2_CH_COUNT; I++)
	{
		this->CH[I].MMES_Error = 0;
		this->CH[I].Value = 0;
		//this->CH[I].STATUS.Enable = 0;
	}
}

IdiBus_CO2::IdiBus_CO2 () : IdiBusSlave()
{
	for (uint8_t I=0; I<IDIBUS_CO2_CH_COUNT; I++)
	{
		this->CH[I].MMES_Error = 0;
		this->CH[I].Value = 0;
		//this->CH[I].STATUS.Enable = 0;
	}
}

IDIBUS_CO2_DATA_TYPE IdiBus_CO2::getChData(uint8_t ChNum){
	if ( ChNum < IDIBUS_CO2_CH_COUNT ) { return this->CH[ChNum]; }
	else								{ return this->CH[IDIBUS_CO2_CH0_NUM]; }
}

uint8_t IdiBus_CO2::getCO2(uint8_t ChNum)
{
	if (ChNum >= IDIBUS_CO2_CH_COUNT) { return IDIERMST_INVALID_CHN_NUM; }
	IdiBusMMES MMES(this->Address);
	MMES.DEV.NUM	= IDIBUS_CO2_CNTRL_DEV;
	MMES.CHNL.NUM   = ChNum;
	MMES.ComFunc    = 0x01;	//Get Value
	uint8_t ChDataSize = 4;		//uint32_t
	uint8_t RequestError = this->SendRequestMMES(&MMES);
	if      ( RequestError   != IDIER_NOPE )          { this->CH[ChNum].MMES_Error = RequestError;   }
	else if ( MMES.RxDataLength == 1 )                { this->CH[ChNum].MMES_Error = MMES.RxData[0]; }
	else if ( MMES.RxDataLength != (ChDataSize + 1) ) { this->CH[ChNum].MMES_Error = IDIERMST_INVALID_RX_REQUEST_FORMAT; }
	else {
		this->CH[ChNum].MMES_Error = MMES.RxData[0];
		if ( this->CH[ChNum].MMES_Error == IDIER_NOPE )
		{
			this->CH[ChNum].Value = (uint32_t) (	 ((uint32_t)MMES.RxData[1]<<24) |
												     ((uint32_t)MMES.RxData[2]<<16) |
												     ((uint32_t)MMES.RxData[3]<<8)  |
												     ((uint32_t)MMES.RxData[4]) );
		}
	}
	return this->CH[ChNum].MMES_Error;

}

void IdiBus_CO2::setAllChErr(uint8_t ErrCode)
{
	for (uint8_t I=0; I<IDIBUS_CO2_CH_COUNT; I++) { this->CH[I].MMES_Error = ErrCode; }
}

/*
void IdiBus_CO2::initAllChs(void)
{
	//uint8_t TxData[2];
	//TxData[0] = (uint8_t)(CurrentLimit >> 8);
	//TxData[1] = (uint8_t)(CurrentLimit);
	IdiBusMMES MMES(this->Address);
	MMES.DEV.NUM       = IDIBUS_CO2_CNTRL_DEV;
	MMES.DEV.ALLCH	   = 1;
	MMES.ComFunc       = 0x01;
	uint8_t RequestError = this->SendRequestMMES(&MMES);
	if      ( RequestError != IDIER_NOPE )             { this->setAllChErr(RequestError); }
	else if (MMES.RxDataLength != IDIBUS_CO2_CH_COUNT) { this->setAllChErr(IDIERMST_INVALID_RX_REQUEST_FORMAT); }
	else
	{
		for (uint8_t I = 0; I < IDIBUS_CO2_CH_COUNT; I++)
		{
			this->CH[I].MMES_Error = MMES.RxData[I];
			//if ( this->CH[I].MMES_Error == IDIER_NOPE )
		}
	}
}
*/
