/*
 * uart.c
 *
 * Created: 14.3.2015 23:11:22
 *  Author: Matej
 */ 

#include "uart.h"


unsigned char checkPNO(unsigned char packetNumber)
{
	return 0;
}

unsigned char checkCMD(unsigned char command)
{
	if (command == CMD || command == DATA)
		return 0;
	else 
		return 1;
}

unsigned char checkLENGTH(unsigned char length)
{
	if (length == 0x08)
		return 0;
	else
		return 1;
}

unsigned char checkCRC(unsigned char crcMSB, unsigned char crcLSB)
{
	unsigned char temp[6];
	temp[0] = gReciveBuffer[0];
	temp[1] = gReciveBuffer[1];
	temp[2] = gReciveBuffer[2];
	temp[3] = gReciveBuffer[3];
	temp[4] = gReciveBuffer[4];
	temp[5] = gReciveBuffer[5];
	
	if ( ( (getCRC16(temp, 6, 0x1083, 1)) >> 4 ) || ( (getCRC16(temp, 6, 0x1083, 1)) & 0x00FF ) )
		return 0;
	else 
		return 1;
}

unsigned char checkPACKET(void)
{
	if ( (checkPNO(gReciveBuffer[0]) + checkLENGTH(gReciveBuffer[1]) + checkCMD(gReciveBuffer[2]) + checkCRC(gReciveBuffer[6], gReciveBuffer[7])) == 0 )
		return 0;
	else
		return 1;
}

unsigned char doAnswer(void)
{
	unsigned char temp[6];
	unsigned char counter = 0;
	
	gTransmitBuffer[0] = gReciveBuffer[0];
	gTransmitBuffer[1] = 0x08;
	if (checkPACKET() == 0)
		gTransmitBuffer[2] = ACK;
	else 
		gTransmitBuffer[2] = NAK;
	gTransmitBuffer[3] = 0x01;
	gTransmitBuffer[4] = 0x01;
	gTransmitBuffer[5] = 0x01;
	
	temp[0] = gTransmitBuffer[0];
	temp[1] = gTransmitBuffer[1];
	temp[2] = gTransmitBuffer[2];
	temp[3] = gTransmitBuffer[3];
	temp[4] = gTransmitBuffer[4];
	temp[5] = gTransmitBuffer[5];
	
	gTransmitBuffer[6] = (getCRC16(temp, 6, 0x1083, 1) >> 4);
	gTransmitBuffer[7] = (getCRC16(temp, 6, 0x1083, 1) & 0x00FF);
		
	for (int i = 0; i < 8; i++)
	{
		if (gTransmitBuffer[i] == 0x00)
			counter++;		
	}
	
	if (counter == 0)
		return 0;
	else
		return 1;
}

void setGlobalDataCmd(void)
{
	if (gTransmitBuffer[2] == ACK)
	{
		switch(gReciveBuffer[2])
		{
			case CMD:	gCmd.direct = (gReciveBuffer[3] >> 4);
						gCmd.step = (gReciveBuffer[3] & 0x0F);
						gCmd.units = gReciveBuffer[4];
						gCmd.delay = gReciveBuffer[5];
						clearBuffer(gReciveBuffer, 8);
						break;
			case DATA:	gOriginal[0][gReciveBuffer[0]] = gReciveBuffer[3];
						gOriginal[1][gReciveBuffer[0]] = gReciveBuffer[4];
						gOriginal[2][gReciveBuffer[0]] = gReciveBuffer[5];
						clearBuffer(gReciveBuffer, 8);
						break;
			default:	clearBuffer(gReciveBuffer, 8);
						break;
		}
	}
}

void clearBuffer(unsigned char buff[], unsigned char size)
{
	for (int i = 0; i < size; i++)
		buff[i] = 0x00;
}
