#include <dummy.h>

#include "doubleSerial.h"
#include "cmdInterpreter.h"
#include "pca9635.h"

#define LED_PIN				2
#define OE_PIN				27
#define MAX_PWM_BOARDS		12	// limited to the fact that not more i2c addresses are available with HW rev A1

doubleSerial doubleS;
cmdInterpreter cmdI;
pca9635 pwm_driver[MAX_PWM_BOARDS];

/**
 * read from selected Serial if available
 * write it to cmdInterpreter and return if end of command is detected
 */
boolean fillBuffer(void) {
	uint8_t d = 0;
	boolean r = doubleS.readSerial(&d);
	
	//something got read?
	if (r) {
		return cmdI.addToBuffer(d);
	}
	return false;
}



void setOE(boolean enable) {
	digitalWrite(OE_PIN, enable);
}

/**
 * setup task
 */
void setup() {
	doubleS.selectSerial(false);
	cmdI.prepareForNextCommand();

	pinMode(LED_PIN, OUTPUT);
	digitalWrite(LED_PIN, 0);

	pinMode(OE_PIN, OUTPUT);
	digitalWrite(OE_PIN, HIGH);

	for (uint8_t i = 0; i < MAX_PWM_BOARDS; i++) {
		if (!i) {
			// init i2c on the first device
			pwm_driver[i].begin(0x04, true, true);
		} else {
			// skip i2c init on others
			pwm_driver[i].begin(0x04+i, false, true);
		}
		pwm_driver[i].set_led_mode(2);
	}
}


/**
 * task
 */
void loop() {
	static uint8_t ButtonlastPinState = 1;
	static uint16_t ledBlink = 0;
	uint8_t pinState = digitalRead(0);

	//button handling
	if(!pinState && ButtonlastPinState){
		boolean useBT = !doubleS.isBT(); 
		digitalWrite(LED_PIN, useBT);
		doubleS.selectSerial(useBT);
		cmdI.prepareForNextCommand();
	}
	ButtonlastPinState = pinState;

	//command handling
	if (fillBuffer()) {
		//cmd end received, lets analyse the command
		uint8_t r = cmdI.interprete(pwm_driver, MAX_PWM_BOARDS, OE_PIN);
		cmdI.prepareForNextCommand();
		doubleS.writeSerial(r);
	}

	// let the led blink, if a user is connected to bluetooth serial console 
	if (doubleS.isBT()) {
		if (ledBlink++ == 0) {
			if (doubleS.hasClient()) {
				digitalWrite(LED_PIN, !digitalRead(LED_PIN));
			} else {
				digitalWrite(LED_PIN, true);
			}
		} 
	}
}
