#include <FastLED.h>
#include "cobs.h"
#define NUM_LEDS 19

#define DATA_PIN 3

CRGB leds[NUM_LEDS];

const size_t ENCODED_MAX = 4;
uint8_t encoded[ENCODED_MAX];
uint8_t decoded[3];
size_t encodedLen = 0;
bool droppingPacket = false;

void setup() {
  Serial.begin(115200);
  FastLED.addLeds<WS2812B, DATA_PIN, GRB>(leds, NUM_LEDS);
}

void loop() {
  while (Serial.available() > 0) {
    uint8_t b = (uint8_t)Serial.read();

    if (b == 0) {
      if (!droppingPacket && encodedLen > 0) {
        cobs_decode_result result = cobs_decode(
          decoded,
          sizeof(decoded),
          encoded,
          encodedLen
        );

        if (result.status == COBS_DECODE_OK &&
            result.out_len == 3) {
          uint8_t red   = decoded[0];
          uint8_t green = decoded[1];
          uint8_t blue  = decoded[2];

          setLEDS(red, green, blue);
        } else {
          // error happened but we just ignore it because we're cool like that
        }
      }

      encodedLen = 0;
      droppingPacket = false;
    } else if (!droppingPacket) {
      if (encodedLen < ENCODED_MAX) {
        encoded[encodedLen++] = b;
      } else {
        // Discard until the next packet delimiter.
        droppingPacket = true;
        encodedLen = 0;
      }
    }
  }
}


void setLEDS(uint8_t red, uint8_t green, uint8_t blue) {
  static CRGB previousColor;
  CRGB color = CRGB(red, green, blue);
  Serial.write((byte)red);
  Serial.write((byte)green);
  Serial.write((byte)blue);
  if (previousColor != color) {
    fill_solid(leds, NUM_LEDS, color);
    FastLED.show();
    previousColor = color;
  }
}
