#include "testApp.h"


//--------------------------------------------------------------
void testApp::setup(){	 
	bSendSerialMessage = false;
	ofBackground(255,255,255);	
	ofSerialSetup("COM7", 9600);
	font.loadFont("DIN.otf",64);
	nTimesRead = 0;
	nBytesRead = 0;
	readTime = 0;
	memset(bytesReadString, 0, 4);
}

//--------------------------------------------------------------
void testApp::update(){
	
	if (bSendSerialMessage){
		
		// (1) write the letter "a" to serial:
		ofSerialWrite("a");
		
		// (2) read
		// now we try to read 3 bytes
		// since we might not get them all the time 3 - but sometimes 0, 6, or something else,
		// we will try to read three bytes, as much as we can
		// otherwise, we may have a "lag" if we don't read fast enough
		// or just read three every time. now, we will be sure to 
		// read as much as we can in groups of three...

		nTimesRead = 0;
		nBytesRead = 0;
		int nRead;  // a temp variable to keep count per read
		memset(bytesReadString, 0, 4);

		while((nRead = ofSerialRead(bytesRead, 3)) > 0){
			nTimesRead++;	
			nBytesRead = nRead;
			
		};
		
		for (int i = 0; i < nBytesRead; i++){
			sprintf(bytesReadString, "%s%c",bytesReadString, bytesRead[i]);
		}

		bSendSerialMessage = false;
		readTime = ofGetElapsedTimef();
	}
}

//--------------------------------------------------------------
void testApp::draw(){

	char tempStr[1024];
	sprintf(tempStr, "click to test serial:\nnBytes read %i\nnTimes read %i\nread: %s\n(at time %0.3f)", nBytesRead, nTimesRead, bytesReadString, readTime);
	
	if (nBytesRead > 0 && ((ofGetElapsedTimef() - readTime) < 0.5f)){
		ofSetColor(0x000000);
	} else {
		ofSetColor(0xdddddd);
	}
	font.drawString(tempStr, 50,100);

}


//--------------------------------------------------------------
void testApp::keyPressed  (int key){ 
	
}

//--------------------------------------------------------------
void testApp::mouseMoved(int x, int y ){
	
}

//--------------------------------------------------------------
void testApp::mouseDragged(int x, int y, int button){
	
}

//--------------------------------------------------------------
void testApp::mousePressed(int x, int y, int button){
	bSendSerialMessage = true;
}

//--------------------------------------------------------------
void testApp::mouseReleased(){
}
