/*
 * ir.cpp
 * handles IRTX, IRRX, and light sensing functionality.
 *
 * $Id$
*/


#include "ir.h"

#include "hw/adc.h"


uint16_t lsens_counts;
uint16_t lsens_level;
uint16_t lsens_scaled;

IRRecv irrx(RMT_CHANNEL_0);
IRSend irtx(RMT_CHANNEL_1);

static uint8_t ir_idx = 0;

typedef struct IRCode {
	uint32_t code;
	const char *type;
} IRCode;

IRCode ir_code[4] = {
	{0xE0E040BF, "samsung"},	// samsung
	{0x20DF10EF, "lg"},			// lg
	{0x04fb08f7, "nec"},		// vizio
	{0x02fd48b7, "nec"}			// toshiba
};


// pin config
inline void _irtx_config()
{
	pinMode(IRTX_PIN_A, OUTPUT);
	pinMode(IRTX_PIN_K, OUTPUT);
	digitalWrite(IRTX_PIN_A, LOW);
	digitalWrite(IRTX_PIN_K, LOW);
}
inline void _irrx_config()
{
	pinMode(IRRX_PIN, INPUT);
}

// module config
void ir_tx_start()
{
	_irtx_config();
	irtx.start(IRTX_PIN_A, ir_code[ir_idx].type);
}

void ir_tx_stop()
{
	irtx.stop();
	_irtx_config();
}

void ir_rx_start()
{
	_irrx_config();
	irrx.start(IRRX_PIN);
}

// module helpers
uint8_t ir_tx_is_busy()
{
	return irtx.is_busy() ? 1 : 0;
}
uint8_t ir_tx_is_active()
{
	return irtx.is_active() ? 1 : 0;
}

// operations
void ir_tx_test()
{
	if (irtx.is_active()) {
		irtx.send(ir_code[ir_idx].code, ir_code[ir_idx].type);

		ir_idx++;
		ir_idx %= 4;
	}
}

uint8_t ir_rx_test()
{
	while (irrx.available()) {
		char *rcvGroup;
		uint32_t result = irrx.read(rcvGroup);
		if (result) {
			Serial.printf("Received: %s/0x%x\n", rcvGroup, result);
			return 1;
		}
	}

	return 0;
}
