// Serial Functions.cpp
// This file contians the functions relating to Serial transmision

#include "main.h"
#include <fstream> //used to read from files
#include "SCI Functions.h"
#include "LFAE SCI Functions.h"
#include <conio.h> //needed for getchar
#include "Serial.h"
#include <time.h> // needed for sleep function and timer
using namespace std;  //needed by <fstream>

//*******************************************
// function to count the number of bytes to be transmitted
//*******************************************
short SRecordByteCount(char* fileName)
{
	//local variables
	char line[1000];//maximum number of chars per line is 1000
	int lineLength = 0;
	short totalBytes = 0x0000;
	

	//opening the s-record
	ifstream s_record;
	s_record.open(fileName, ios::in); //open file for input purposes
	if (s_record.is_open())
	{	
		while (! s_record.eof() ) //while not the end of the file	
		{
			s_record.getline(line,1000);//max chars per line - 1000
			if (line[1] == '1') 
			{
				lineLength = hex2dec(line,2) - 3; //get line length, remove address bytes and checksum
				totalBytes += lineLength;
			}				
		}
		s_record.close();
		return totalBytes; 
	}
	else
	{
		printf("Error: Unable to open s-record, ensure file is in 'bin' directory\n");
		printf("and that the SRecordFilename is correct\n");
		getch(); //pause until key is pressed
		return 1;
	}
}





//*******************************************
// function to transmit S-Record via SCI
//*******************************************
int SCI_interface(void)
{
	// Loacal Variables
	short byteCount = 0x0000;
	char SendBuffer = 0x00;
	unsigned char RecBuffer = 0x00;
	unsigned char checkSumTotal = 0x00;
	char line[1000];//max chars per line is 1000
	CSerial serial;//create instance of CVCanDrv 

	if(serial.Open(SCIPort,BaudRate)) //open port 1 at predefined baud rate
	{	
		SendBuffer = 0x55; //synchronization value
		printf("Attempting to synchronize...\n");
		while(serial.ReadDataWaiting() == 0) //while receive buffer is empty
		{
			serial.SendData(&SendBuffer,1); //send synchronization byte
			_sleep(50);
		}
		serial.ReadData(&RecBuffer, 1);
		if (RecBuffer != 0xaa)
		{
			printf("Error: Synchronization packet incorrect.\n");
			printf("Press any key to exit...\n");
			getch();
			return 1; 
		}
		

		//sending start address
		SendBuffer = StartAddressMSB;
		checkSumTotal = StartAddressMSB;
		serial.SendData(&SendBuffer,1);
		SendBuffer = StartAddressLSB;
		checkSumTotal += StartAddressLSB;
		serial.SendData(&SendBuffer,1);
		
		//send number of bytes
		byteCount = SRecordByteCount(SRecordFilename);
		SendBuffer = (byteCount & 0xFF00)>>8; //get the MSB
		checkSumTotal += (byteCount & 0xFF00)>>8; 
		serial.SendData(&SendBuffer,1);
		SendBuffer = (byteCount & 0x00FF); //get the LSB
		checkSumTotal += (byteCount & 0x00FF); 
		serial.SendData(&SendBuffer,1);

		//send data
		printf("Synchronized! Transmitting data...\n");
		ifstream s_record;
		s_record.open(SRecordFilename, ios::in); //open file for input purposes
		if (s_record.is_open())
		{	
			while (! s_record.eof() ) //while not the end of the file	
			{
				s_record.getline(line,1000); //maximum chars per line is 1000
				SCI_s_line_process(line, &serial, &checkSumTotal);//process the captured s-line
			}
			s_record.close();	
		}

		//send checksum total
		SendBuffer = checkSumTotal;
		serial.SendData(&SendBuffer,1);
		printf("Primary S-Record transmitted successfully!\n");
		return LFAE_SCI_interface(&serial);
	}
	else
	{
		printf("Error: Could not open serial port.\n");
		printf("Ensure no other applications are using port,\n");
		printf("and that the defined baud rate is valid\n");
		printf("Press any key to exit...\n");
		getch();
		return 1;
	}
}

//*******************************************
// function to analyse an s-line and transmit via SCI
//*******************************************
void SCI_s_line_process(char *line, CSerial *Serial, unsigned char *checkSumTotal)
{
	//local variables
	int lineLength = 0;
	int loop;
	char Buff; //array for data


	// main code
	switch (line[1]) 
	{
		case '0':
			// S0 - header - ignore
			break;
		case '1':
			// 2 byte addressing
			lineLength = hex2dec(line,2) - 3; //get line length, remove address bytes and checksum
			for(loop=8; loop <= (2*lineLength + 7) ; loop = loop+2)
			{
				Buff = hex2dec(line,loop);
				*checkSumTotal += Buff;
				Serial->SendData(&Buff,1);
			}
			break;
		case '9':
			// end of data
			break;

		default:
			//error! line not recognised
			printf("Line not recognised/n");
			break;
	}
}


