//////////////////////////////////////////////////////////////////
//
// App:			API: TWI I/O Expander TCA6416
// Author:		Milan Korinek
// Version:		1.0
// Notice:		Abstract layer of I/O Expander TCA6416
//////////////////////////////////////////////////////////////////

#include "TWI_IO_Expander.h"

const uint32_t _ports_pull_res_mask[] = {IOEXP_PA_PULL_RES_MASK, IOEXP_PB_PULL_RES_MASK, IOEXP_PC_PULL_RES_MASK, IOEXP_PD_PULL_RES_MASK};

const uint32_t _ports_pull_res_enable[] = {IOEXP_PA_PULL_RES_ENABLE, IOEXP_PB_PULL_RES_ENABLE, IOEXP_PC_PULL_RES_ENABLE, IOEXP_PD_PULL_RES_ENABLE};
const uint32_t _ports_pull_res_disable[] = {IOEXP_PA_PULL_RES_DISABLE, IOEXP_PB_PULL_RES_DISABLE, IOEXP_PC_PULL_RES_DISABLE, IOEXP_PD_PULL_RES_DISABLE};

const uint32_t _ports_pull_res_up_res[] = {IOEXP_PA_PULL_UP_RES, IOEXP_PB_PULL_UP_RES, IOEXP_PC_PULL_UP_RES, IOEXP_PD_PULL_UP_RES};
const uint32_t _ports_pull_res_down_res[] = {IOEXP_PA_PULL_DOWN_RES, IOEXP_PB_PULL_DOWN_RES, IOEXP_PC_PULL_DOWN_RES, IOEXP_PD_PULL_DOWN_RES};

const uint32_t _ports_dir_mask[] = {IOEXP_PA_DIR_MASK, IOEXP_PB_DIR_MASK, IOEXP_PC_DIR_MASK, IOEXP_PD_DIR_MASK};

const uint32_t _ports_dir_output[] = {IOEXP_PA_DIR_OUTPUT, IOEXP_PB_DIR_OUTPUT, IOEXP_PC_DIR_OUTPUT, IOEXP_PD_DIR_OUTPUT};
const uint32_t _ports_dir_input[] = {IOEXP_PA_DIR_INPUT, IOEXP_PB_DIR_INPUT, IOEXP_PC_DIR_INPUT, IOEXP_PD_DIR_INPUT};

status_code_t freertos_io_expander_configure(void)
{
	status_code_t ret;
	
	/* Run LED default configuration (LED Off) */
	ret = freertos_io_expander_run_led_configure();
	if (ret != STATUS_OK) return ret;
	vTaskDelay(50 / portTICK_RATE_MS); 
	
	ret = freertos_io_expander_run_led_off(); // !!! unknown problem, without delay, LED stay On
	if (ret != STATUS_OK) return ret;
	vTaskDelay(50 / portTICK_RATE_MS);
	
	/* Ports power default configuration (Power-off) */
	ret = freertos_io_expander_ports_pwr_configure();
	if (ret != STATUS_OK) return ret;
	vTaskDelay(50 / portTICK_RATE_MS);
	
	ret = freertos_io_expander_ports_pwr_off();
	if (ret != STATUS_OK) return ret;
	vTaskDelay(50 / portTICK_RATE_MS);

	/* Ports direction default configuration (Outputs) */
	ret = freertos_io_expander_ports_dir_configure();
	if (ret != STATUS_OK) return ret;
	vTaskDelay(50 / portTICK_RATE_MS);
	
	/* Ports resistor nets default configuration (Enable, Pull-Up) */
	ret = freertos_io_expander_ports_pull_res_configure();
	
	return ret;
}

status_code_t freertos_io_expander_ports_pull_res(uint32_t resistor_nets_mask, uint32_t enable_flags, uint32_t settings_flags)
{
	status_code_t ret;
	
	 /* Enable - configure as outputs, Disable - configure as inputs */
	ret = freertos_io_expander_tca6416_set(IOEXP_TCA6416_CMD_CONFIGURATION_PORT_0 , resistor_nets_mask, enable_flags);
	if (ret != STATUS_OK) return ret;
	
	/* Relevant only for enabled resistor nets: Pull-Up/Pull-Down configuration  */
	ret = freertos_io_expander_tca6416_set(IOEXP_TCA6416_CMD_OUTPUT_PORT_0, resistor_nets_mask, settings_flags);
	
	return ret;
}