//
// Echo Serial Led Strip Controller
//

// Serial Connection Variables
//
const byte serialBufferSize = 100;
char serialBuffer[serialBufferSize];
const char startMarker = '<';
const char endMarker = '>';
byte serialBytesReceived = 0;
boolean serialReadInProgress = false;
boolean newSerialData = false;
char serialData[serialBufferSize] = {0};
char commandLimiter[2] = ":";


void setup() {
  // Init Serial Connection
  Serial.begin(115200);
  
  // Init LED Strip
  initLedStrip();

  // Send Init Complete signal
  Serial.println("<1:1:1>");
}

void loop() { 
  // Handle Serial Comms
  handleSerial();

  // Handle Led Strip
  handleLedStrip();
}

// Serial Handling
//
void handleSerial() {
  if(Serial.available() > 0) {
    char x = Serial.read();

    // the order of these IF clauses is significant
    if (x == endMarker) {
      serialReadInProgress = false;
      newSerialData = true;
      serialBuffer[serialBytesReceived] = 0;
      parseData();
    }
    
    if(serialReadInProgress) {
      serialBuffer[serialBytesReceived] = x;
      serialBytesReceived ++;
      if (serialBytesReceived == serialBufferSize) {
        serialBytesReceived = serialBufferSize - 1;
      }
    }

    if (x == startMarker) { 
      serialBytesReceived = 0; 
      serialReadInProgress = true;
    }
  }
}

void parseData() {
  char * strtokIndex;
  char deviceUUID[10];
  char command[20];
  char data[69];

  // Get Device UUID
  strtokIndex = strtok(serialBuffer, ":");
  strcpy(deviceUUID, strtokIndex);

  strtokIndex = strtok(NULL, ":");
  strcpy(command, strtokIndex);

  strtokIndex = strtok(NULL, ":");
  strcpy(data, strtokIndex);

  handleCommand(deviceUUID, command, data);
}

void sendSerialCommand(char* deviceUUID, char* command, char* data) {
  char serialCommandBuffer[serialBufferSize];
  char _startMarker[2] = "<";
  char _endMarker[2] = ">";
  sprintf(serialCommandBuffer, "%s%s:%s:%s%s", _startMarker, deviceUUID, command, data, _endMarker);
  Serial.println(serialCommandBuffer);
}

void handleCommand(char* deviceUUID, char* command, char* data) {
  
  //
  // Led Strip
  //
  
  if (strcmp(deviceUUID, "34gr-54jf") == 0) {
    ledStripCommand(deviceUUID, command, data);
  }

}
