/*

Copyright © 2003, Russell C. Hay
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

i. Redistributions of source code must retain the above copyright notice, this
   list of conditions and the following disclaimer. 

ii. Redistributions in binary form must reproduce the above copyright notice,
    this list of conditions and the following disclaimer in the documentation
    and/or other materials provided with the distribution. 

iii. Neither the name of the dead[protocol]society nor the names of its
     contributors may be used to endorse or promote products derived from this
     software without specific prior written permission. 

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

*/
#include <sys/types.h>
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <termios.h>
#include "version.h"
#include "stl.h"
#include "mtxtype.h"
#include "action.h"
#include "device.h"

device::device()
: m_serial_device_name("/dev/lcd")
, m_priority_active(0)
, m_screen_width(20)
, m_screen_height(4)
, m_serial_fd(-1)
, m_serial_baud(B19200)
, m_serial_bits(8)
, m_serial_parity('N')
, m_serial_stopbit(1)
, m_serial_mode(DEVICE_MODE_EMPTY)
, m_status_flags(0)
{
}

device::device(const char *dev)
: m_serial_device_name(dev)
, m_priority_active(0)
, m_screen_width(20)
, m_screen_height(4)
, m_serial_fd(-1)
, m_serial_baud(B19200)
, m_serial_bits(8)
, m_serial_parity('N')
, m_serial_stopbit(1)
, m_serial_mode(DEVICE_MODE_EMPTY)
, m_status_flags(0)
{
}

device::device(const char *dev, int baud)
: m_serial_device_name(dev)
, m_priority_active(0)
, m_screen_width(20)
, m_screen_height(4)
, m_serial_fd(-1)
, m_serial_baud(baud)
, m_serial_bits(8)
, m_serial_parity('N')
, m_serial_stopbit(1)
, m_serial_mode(DEVICE_MODE_EMPTY)
, m_status_flags(0)
{
}

device::device(const char *dev, int baud, int bits, char parity, int stopbit)
: m_serial_device_name(dev)
, m_priority_active(0)
, m_screen_width(20)
, m_screen_height(4)
, m_serial_fd(-1)
, m_serial_baud(baud)
, m_serial_bits(bits)
, m_serial_parity(parity)
, m_serial_stopbit(stopbit)
, m_serial_mode(DEVICE_MODE_EMPTY)
, m_status_flags(0)
{
}

device::~device()
{
	Close();
}

int device::Open()
{
	char out[2];
	m_serial_fd = open(m_serial_device_name.data(),
			O_RDWR | O_NOCTTY | O_NDELAY);
	if (m_serial_fd == -1)
		return 0;

	BuildOptions();
	out[0] = DEVICE_CMD_START;
	out[1] = DEVICE_CMD_TYPE;
	write(m_serial_fd, out, 2);
	read(m_serial_fd, out, 1);

	m_serial_device_type = out[0];
	m_serial_device_constraints.Load("./devices.conf");
	printf("%s online with %dx%d\n",
			m_serial_device_constraints.GetName(m_serial_device_type), 
			m_serial_device_constraints.GetMaxWidth(m_serial_device_type),
			m_serial_device_constraints.GetMaxHeight(m_serial_device_type));

	Reset();

	return 1;
}

void device::Close()
{
	if (m_serial_fd != -1)
	{
		close(m_serial_fd);
		m_serial_fd = -1;
	}
}

int device::Push(action act)
{
	m_action_queue.push_back(act);
	return 1;
}

int device::Process()
{
	char *c;
	int cmd;

	while(!m_action_queue.empty())
	{
		action act = m_action_queue.front();

		c = 0;
		printf("Processing Action(%d/%s)\n",
				act.GetActionType(), act.GetActionName());
		SendCommand(act);

		m_action_queue.pop_front();
	}
}

int device::AddToFdSet(fd_set *fdset, int *max)
{
	FD_SET(m_serial_fd, fdset);
	if (*max < m_serial_fd)
		*max = m_serial_fd + 1;
}

void device::BuildOptions()
{
	fcntl(m_serial_fd, F_SETFL, 0);
	tcgetattr(m_serial_fd, &m_serial_options);

	cfsetospeed(&m_serial_options, m_serial_baud);
	cfsetispeed(&m_serial_options, m_serial_baud);
	cfmakeraw(&m_serial_options);
	// Disable flow control
	m_serial_options.c_cflag &= ~CRTSCTS;
	// Enable receiver and ignore modem control lines
	m_serial_options.c_cflag |= (CLOCAL | CREAD);
	
	// Set Character Size, default to 8 bits
	m_serial_options.c_cflag &= ~CSIZE;
	switch(m_serial_bits)
	{
		case 7:
			m_serial_options.c_cflag |= CS7;
			break;
		default:
			m_serial_options.c_cflag |= CS8;
			break;
	}

	// Set Parity, default to No Parity
	switch(m_serial_parity)
	{
		case 'E':
			break;
		case 'O':
			break;
		default:
			m_serial_options.c_cflag &= ~PARENB;
			break;
	}

	if (m_serial_stopbit)
	{
	} else {
		m_serial_options.c_cflag &= ~CSTOPB;
	}

	// Only receive one bit at a time.
	m_serial_options.c_cc[VMIN] = 0;
	m_serial_options.c_cc[VTIME] = 1;

	tcsetattr(m_serial_fd, TCSANOW, &m_serial_options);
}

void device::SendCommand(action act)
{
	int length = 0;
	char *out = 0;

	switch(act.GetActionType())
	{
		case ACTION_RESET:
			Reset();
			break;
		case ACTION_BACK:
			SendSingleCommand(DEVICE_CMD_BACK);
			break;
		case ACTION_FORWARD:
			SendSingleCommand(DEVICE_CMD_FORWARD);
			break;
		case ACTION_HOME:
			SendSingleCommand(DEVICE_CMD_HOME);
			break;
		case ACTION_HGRAPH:
			ActiveMode(DEVICE_MODE_HGRAPH);
			out = (char *)malloc(7);
			out[0] = DEVICE_CMD_START;
			out[1] = DEVICE_CMD_HGRAPH;
			out[2] = (char)act.GetActionParamInt(PARAM_XPOS);
			out[3] = (char)act.GetActionParamInt(PARAM_YPOS);
			out[4] = 0x00;
			out[5] = (char)act.GetActionParamInt(PARAM_VALUE);
			out[6] = '\0';
			length=6;
			break;
		case ACTION_VGRAPH:
			ActiveMode(DEVICE_MODE_VGRAPH);
			out = (char *)malloc(5);
			out[0] = DEVICE_CMD_START;
			out[1] = DEVICE_CMD_VGRAPH;
			out[2] = (char)act.GetActionParamInt(PARAM_XPOS);
			out[3] = (char)act.GetActionParamInt(PARAM_VALUE);
			out[4] = '\0';
			length=4;
			break;
		case ACTION_GPO:
			out = (char *)malloc(4);
			out[0] = DEVICE_CMD_START;
			out[2] = (char)act.GetActionParamInt(PARAM_GPO);
			out[3] = '\0';
			if(act.GetActionParamInt(PARAM_ONOFF))
				out[1] = DEVICE_CMD_GPOON;
			else
				out[1] = DEVICE_CMD_GPOOFF;
			length=3;
			break;
		case ACTION_CURSOR:
			out = (char *)malloc(5);
			out[0] = DEVICE_CMD_START;
			out[1] = DEVICE_CMD_CURSOR;
			out[2] = (char)act.GetActionParamInt(PARAM_XPOS);
			out[3] = (char)act.GetActionParamInt(PARAM_YPOS);
			out[4] = '\0';
			printf("Cursor Location (CMD#%d) (%d, %d)\n", out[1], out[2], out[3]);
			length=4;

			break;
		case ACTION_BIG:
			ActiveMode(DEVICE_MODE_BIGINT);
			out = (char *)malloc(5);
			out[0] = DEVICE_CMD_START;
			out[1] = DEVICE_CMD_BIGINT;
			out[2] = (char)act.GetActionParamInt(PARAM_XPOS);
			out[3] = (char)act.GetActionParamInt(PARAM_VALUE);
			out[4] = '\0';
			length=4;
			break;
		case ACTION_OUT:
			out = strdup(act.GetActionParamChar(PARAM_TEXT));
			length = strlen(out);
			break;

		case ACTION_CLEAR:
			SendSingleCommand(DEVICE_CMD_CLEAR);
			break;
	}

	if (out != 0);
	{
		write(m_serial_fd, out, length);
		free(out);
	}
}

void device::ActiveMode(unsigned char mode)
{
	char out[3];

	out[0] = DEVICE_CMD_START;
	out[2] = '\0';

	if (m_serial_mode != mode)
	{
		switch(mode)
		{
			case DEVICE_MODE_HGRAPH:
				out[1] = DEVICE_CMD_INIT_HGRAPH;
				break;
			case DEVICE_MODE_VGRAPH:
				out[1] = DEVICE_CMD_INIT_VGRAPH;
				break;
			case DEVICE_MODE_BIGINT:
				out[1] = DEVICE_CMD_INIT_BIGINT;
				break;
			case DEVICE_MODE_CCHAR:
				out[0] = 0;
				break;
		}
		m_serial_mode = mode;
		if (out[0] != 0)
			write(m_serial_fd, out, 2);
	}
}

void device::Backlight(int status)
{
	if (status)
	{
		char out[3];
		out[0] = DEVICE_CMD_START;
		out[1] = DEVICE_CMD_BACKLIGHT_ON;
		out[2] = 0;
		write(m_serial_fd, out, 3);
	} else
		SendSingleCommand(DEVICE_CMD_BACKLIGHT_OFF);
}

void device::SendSingleCommand(int cmd)
{
	char out[3];

	out[0] = DEVICE_CMD_START;
	out[1] = cmd;
	out[2] = '\0';
	write(m_serial_fd, out, 2);
}

void device::Reset()
{
	char out[14];

	out[0] = out[2] = out[4] = out[6] = out[8] = out[10] = out[12] =
		DEVICE_CMD_START;
	out[1] = DEVICE_CMD_CLEAR;
	out[3] = 96;
	out[5] = 65;
	out[7] = 68;
	out[9] = 82;
	out[11] = 75;
	out[13] = 84;
	write(m_serial_fd, out, 14);

	center(MTXORBD_VERSION_STR, 1);
	center(MTXORBD_AUTHOR_STR,	 2);
	center(MTXORBD_COPYRIGHT_STR, 4);
}

void device::center(char *str, int line)
{
	int len, pos;
	char out[4];

	len = strlen(str)+1;

	pos = (m_serial_device_constraints.GetMaxWidth((int)m_serial_device_type)
			- (len -1)) /2;

	out[0] = DEVICE_CMD_START;
	out[1] = DEVICE_CMD_CURSOR;
	out[2] = (char)pos;
	out[3] = (char) line;
	write(m_serial_fd, out, 4);

	write(m_serial_fd, str, len-1);
}

int device::IsSet(fd_set *fdset)
{
	return FD_ISSET(m_serial_fd, fdset);
}

char device::HandleIncoming()
{
	char buf[5];
	int len;

	if (len = read(m_serial_fd, buf, 9)<=0)
	{
		printf("Error reading incoming\n");
	}
	buf[len+1]=0;
	return buf[0];
}

int device::InPriority()
{
	return m_priority_active;
}

void device::StartPriority()
{
	m_priority_active = 1;
}

void device::StopPriority()
{
	m_priority_active = 0;
}


syntax highlighted by Code2HTML, v. 0.9.1