#include <sys/select.h>

#include "ifi_radio.h"
#include "serial.h"

int ifi_radio_reply_wait(int handle)
{
	fd_set fds;
	struct timeval tv;

	FD_ZERO(&fds);
	FD_SET(handle, &fds);
	tv.tv_sec = 0;
	tv.tv_usec = 100000;
	if (select(handle + 1, &fds, NULL, NULL, &tv) < 1)
		return 0;

	return 1;
}

int ifi_radio_reply(int handle)
{
	char resp[4];

	if (!radio_reply_wait())
		return 0;

	ser_recv_buf(handle, resp, 4);

	return !strncmp(resp, "OK\r\n", 4);
}

void ifi_radio_command_mode(int handle)
{
	int status;

	ioctl(handle, TIOCMGET, &status);
	status |= TIOCM_RTS;
	ioctl(handle, TIOCMSET, &status);
} 

void ifi_radio_data_mode(int handle)
{
	int status;

	ioctl(handle, TIOCMGET, &status);
	status &= ~TIOCM_RTS;
	ioctl(handle, TIOCMSET, &status);

	radio_reply();
}

int ifi_radio_attention(int handle)
{
	char resp[4];
	int i;

	radio_command_mode(handle);

	for (i = 0; i < 10; i++)
	{
		ser_send_buf(handle, "X", 1);
		if (radio_reply_wait(handle))
		{
			ser_recv_buf(handle, resp, 4);
			if (!strncmp(resp, "ER\r\n", 4))
				return 1;
		}
	}

	return 0;
}

int ifi_radio_init(int handle)
{
	if (!radio_attention(handle))
		return 0;

	/* Turn off transmitter */
	ser_send_str(handle, "Tf");
	if (!radio_reply(handle))
		return 0;

	/* Enable all channels */
	ser_send_str(handle, "Ec0mp");
	if (!radio_reply(handle))
		return 0;

	return 1;
}

int ifi_radio_set_channel(int handle, int channel)
{
	char buf[2];

	if (channel < 1 || channel > 40)
		return 0;

	buf[0] = 'C';
	buf[1] = 0x30 + channel;
	ser_send_buf(handle, buf, 2);

	return radio_reply(handle);
}

int ifi_radio_enable_transmitter(int handle, int enable)
{
	char buf[2];

	buf[0] = 'T';
	buf[1] = enable ? 'n' : 'f';
	ser_send_buf(handle, buf, 2);

	return radio_reply(handle);
}

void ifi_radio_shutdown(int handle)
{
	radio_command_mode(handle);
	ser_send_buf(handle, "Tf", 2);
	radio_reply(handle);
}

