#include <Arduino.h>
#include <config.h>
#include <input.h>
#include <SoftwareSerial.h>

extern uint8_t customKey;
extern SoftwareSerial nexSerial;
extern bool trig_key;
extern void toggle_usb(void);
uint16_t i1;
uint8_t c1;
static uint8_t __buffer[10];

void serialEvent() {
    while (nexSerial.available() > 0 ){   
        
        c1 = nexSerial.read();
        if (0x65 == c1 ||__buffer[0] == 0x65)
        {
            if (0x65 == c1){
              __buffer[0] = c1; 
              i1++;
            }else{
              __buffer[i1]=c1; 
              i1++; 
            if (i1>=7)
            {
                __buffer[i1] = 0x00;
                if (0xFF == __buffer[4] && 0xFF == __buffer[5] && 0xFF == __buffer[6])
                {
                    if (__buffer[1]==0){
                      customKey=__buffer[2];
                      switch(customKey){
                        case BUTTON_SERIAL:
                          toggle_usb();
                          break;
                        case BUTTON_TRIGGER:
                          trig_key = true;
                          break;
                      }

                    }
                }
              memset(__buffer,0x00,8);
              i1=0;  
            }
        }
    }
    }
}
