#include "doubleSerial.h"

// Constructor
doubleSerial::doubleSerial() {
	this->useBT = false;
	this->BTName = "ActuBoard BLE";
}

doubleSerial::doubleSerial(const char *BT_Name) {
	this->useBT = false;
	this->BTName = BT_Name;
}



/**
 * select which serial is used to communicate
 *
 */
void doubleSerial::selectSerial(boolean useBluetooth) {
	if (useBluetooth) {
		Serial.end();
		SerialBT.begin(this->BTName); //Bluetooth device name
		SerialBT.flush();
	} else {
		SerialBT.end();
		Serial.begin(115200, SERIAL_8N1, -1, -1, false, 1100UL);
		Serial.flush();
	}
	this->useBT = useBluetooth;
}


/**
 * read from selected Serial if available
 * will return true if a character was read
 */
boolean doubleSerial::readSerial(uint8_t *data) {
	//check if we have something to read
	if (this->useBT) {
		if (SerialBT.available()){
			*data = SerialBT.read();
			return true;
		}
	} else {
		if (Serial.available()){
			*data = Serial.read();
			return true;
		}
	}
	return false;
}


/**
 * write one char to the selected Serial
 */
void doubleSerial::writeSerial(const char c) {
	 if (this->useBT) {
		SerialBT.write(c);
	} else {
		Serial.write(c);
	}
}


/**
 * write string char to the selected Serial
 */
void doubleSerial::writeSerial(const char *c) {
	while(*c != 0) {
		this->writeSerial(*c);
		c++;
	}
}


/**
 * return of there is a client on the other end of the serial console
 * in case of uart serial it is always true, bluetooth depends.
 */
boolean doubleSerial::hasClient(void) {
	if (this->useBT) {
		return SerialBT.hasClient();
	} else {
		return true;
	}
}

/**
 * return true if currently bluetooth is used for communication
 */
boolean doubleSerial::isBT(void) {
	return this->useBT;
}
