#include "Arduino.h"
#include "port.h"
#include "keyboardpipe.h"
#include "esp32-hal-log.h"
#include "parse_hid.h"
#include "abc800_hidboot.h"
#include "WiFi.h"
#include "abc800_func.h"
#include "abc800_wifi.h"
#include "abc800_callback.h"
#include "abc800_web.h"
#include "abc800_keyboard.h"
#include "abc800_gpio.h"
#include "abc800_usb.h"
#include "abc800_littlefs.h"
#define LOG_LOCAL_LEVEL ESP_LOG_INFO
#include "esp_log.h"
#include <AsyncElegantOTA.h>
#include <SoftwareSerial.h>
#define DEVICE_ADDRESS 2
static const char TAG[] = __FILE__;

USBHostKeyboard port(2);
KeyboardReportParser keyparse;
abc800::wifi abc800_wifi;
abc800::std_abc800 abc800_std;
abc800::callback abc800_callback;
abc800::web abc800_web;
abc800::keyboard abc800_keyboard;
abc800::gpio abc800_gpio;
abc800::littlefs abc800_littlefs;
key800config abc800_configuration;
AsyncElegantOtaClass AsyncElegantOTA;
DNSServer dns;
AsyncWebServer server(80);
AsyncWiFiManager wifiManager(&server,&dns);

TaskHandle_t WiFi_Task = NULL;
TaskHandle_t Web_Task = NULL;
TaskHandle_t OTA_Task = NULL;
TaskHandle_t Keyboard_Task_Out = NULL;
TaskHandle_t Keyboard_ABC800_Task_In = NULL;
TaskHandle_t Config_Task = NULL;

TimerHandle_t repeat_delay_timer_out = NULL;
TimerHandle_t repeat_timer_out = NULL;
TimerHandle_t abc800_repeat_delay_timer = NULL;
TimerHandle_t abc800_repeat_timer = NULL;
TimerHandle_t abc800_check_timer = NULL;
SoftwareSerial abc800_serial_keyboard;

String macaddr;

QueueHandle_t abc800_key_queue_out = NULL;
QueueHandle_t abc800_key_queue_in = NULL;

portMUX_TYPE sync_isr = portMUX_INITIALIZER_UNLOCKED;

void setup()
{
  Serial.begin(KEY800_SERIAL_BAUD_RATE);
  Serial1.begin(KEY800_SERIALKETBOARD_BAUD_RATE,SERIAL_8N2,A800_RXD,A800_TXD);
  abc800_serial_keyboard.begin(KEY800_SERIALKETBOARD_BAUD_RATE,SWSERIAL_8N2,K800_RXD,K800_TXD,false);
  abc800_littlefs.setup();
  abc800_littlefs.loadconfig();
  abc800_gpio.init();

  abc800_key_queue_out = xQueueCreate(ABC800_KEY_OUT_BUFFER_SIZE, sizeof(key800queue));
  abc800_key_queue_in = xQueueCreate(ABC800_KEY_IN_BUFFER_SIZE, sizeof(key800queue));               

  if(port.init())
  {
    abc800_port_init();
  }
  
  digitalWrite(KEY800_LED,HIGH);
  abc800_keyboard.init();
  abc800_wifi.setup();
  //digitalWrite(A800_RST,HIGH);

}

void loop()
{
    delay(1000);
}