//******************************************************************************
//Oscilloscope		-	Library for interfacign with external FPGA oscilloscope
//
//By				-	Yi Yao			http://yyao.ca/
//Date				-	2006-01-05
//******************************************************************************

#include "Oscilloscope.h"


//Creates an instance with set buffer size
Oscilloscope::Oscilloscope(int BufferSize) {
	Buffer = new unsigned char[BufferSize];
	MaxBufferLength = BufferSize;
};


//Default destructor
Oscilloscope::~Oscilloscope(void) {
	CloseConnection();
	delete [] Buffer;
};


//Sets register n to an 8 bit value
//n is between 0 and 7 inclusive
//The byte sent over in two nibbles
void Oscilloscope::SetReg(int n, unsigned char Value) {
	unsigned char	c;

	//Send lower nibble first
	c = ((char) ((n * 2) << 4))			//Address
			| (Value & 0x0F);			//Value
	WriteComChar(c);

	//Send upper nibble
	c = ((char) ((n * 2 + 1) << 4))		//Address
			| ((Value >> 4) & 0x0F);	//Value
	WriteComChar(c);
};


//Sends a 16 bit word over in 2 bytes
//n is between 0 and 6 inclusive
//Register n will receive the least significant bits
//Register n + 1 will recieve the most significant bits
void Oscilloscope::SetWord(int n, unsigned int Value) {
	SetReg(n, ((char) Value) & 0xFF);
	SetReg(n + 1, ((char) (Value >> 8) & 0xFF));
};


//Opens connection to oscilloscope via COM port (returns true if error)
int Oscilloscope::OpenConnection(int ComPort) {
	OpenCom();
	return 0;
};


//Closes current connection
void Oscilloscope::CloseConnection(void) {
	CloseCom();
};


//Sets vertical shift (-5 to 5V)
void Oscilloscope::SetVerticalShift(float V) {
	unsigned int	Val = (unsigned int) (65535 * (0.5 - V / 10));

	SetWord(0, Val);
};


//Sets the trigger level (-5 to 5V)
void Oscilloscope::SetTriggerLevel(float V) {
	unsigned int	Val = (unsigned int) (65535 * (0.5 - V / 10));

	SetWord(2, Val);
};


//Sets the amplication level
void Oscilloscope::SetAmplification(OscAmpLevels AmpLevel) {
	SetReg(4, AmpLevel);
};


//Enables capture and sending of data
void Oscilloscope::EnableCapture(void) {
	SetReg(7, 0x00);
};


//Disables capture and sending of data
void Oscilloscope::DisableCapture(void) {
	SetReg(7, 0xFF);
};


//Fills Buffer with data if possible, number of bytes read will be returned
int Oscilloscope::ReadData(char *Buffer, int BufferLength) {
	return ReadCom(Buffer, BufferLength);
};


//Removes all characters from communication buffer
void Oscilloscope::FlushBuffer(void) {
	char	Buffer[1024];

	while (ReadCom(Buffer, 1024)) {};
};
