/**** Includes ****/
#include "../utils/utils.h"
#include "mcu/mcu_hal.h"
#include "dio.h"

using namespace board;

/**** Private definitions ****/
/**** Private constants ****/
/**** Private variables ****/
/**** Private function declarations ****/

/**** Public function definitions ****/
board::DigitalIO::DigitalIO(uint8_t gpio_ch, uint8_t init_read)
{
	this->gpio_ch = gpio_ch;
	
	if(init_read) this->last_read = (uint8_t)DIO_HIGH;
	else this->last_read = (uint8_t)DIO_LOW;
	
	this->write(DIO_HIZ);
}

board::DigitalIO::~DigitalIO(void)
{
	this->write(DIO_HIZ);
}

uint8_t board::DigitalIO::read(void)
{
	uint8_t lvl = mcu::gpio_read(this->gpio_ch);
	if(lvl>0) this->last_read = (uint8_t)DIO_HIGH;
	else this->last_read = (uint8_t)DIO_LOW;
	
	return this->last_read;
}

void board::DigitalIO::write(int8_t level)
{
	if(level > 0)
	{
		this->last_set = DIO_HIGH;
		mcu::gpio_write(this->gpio_ch, mcu::LEVEL_HIGH);
	}
	else if(level < 0)
	{
		this->last_set = DIO_HIZ;
		mcu::gpio_write(this->gpio_ch, mcu::LEVEL_HIZ);
	}
	else
	{
		this->last_set = DIO_LOW;
		mcu::gpio_write(this->gpio_ch, mcu::LEVEL_LOW);
	}
}

uint8_t board::DigitalIO::is_io_match(void)
{
	if(this->last_set == DIO_HIZ) return 1;
	
	uint8_t read_lvl = this->read();
	
	if(read_lvl == (uint8_t)this->last_set) return 1;
	else return 0;
}

int8_t board::DigitalIO::get_set_level(void)
{
	return this->last_set;
}

/**** Private function definitions ****/
