#include <Arduino.h>
#include "carroEsp32.h"
#include "OpenTB6612FNG/OpenTB6612FNG.h"
#include "wifi_config.hpp"
#include "SPIFFS.h"
#include <ArduinoOTA.h>
#include "config_ota.hpp"
TaskHandle_t TareaProcesador1;
TaskHandle_t TareaProcesador2;
void loop1(void *pvParameters);
void loop2(void *pvParameters);
int anterior = millis();
char sensorCadena[16];


OpenTB6612FNG misMotores(0);

#include "managerServer.hpp"

void setup()
{
  Serial.begin(115200);
  wifi();
  ota_init();
  SPIFFS.begin();
  init_sensores();

  webSocket.begin();
  webSocket.onEvent(webSocketEvent);
  server.begin();
  xTaskCreatePinnedToCore(loop1, "Tarea1", 10000, NULL, 1, &TareaProcesador1, 0);
  xTaskCreatePinnedToCore(loop2, "Tarea2", 10000, NULL, 1, &TareaProcesador2, 1);
  delay(200);

  Serial.println("Carro Esp32");

  // handle index
  server.on("/", []() {
    File index = SPIFFS.open("/index.html", "r");
    server.streamFile(index, "text/html");
    index.close();
  });
}

void loop()
{
}
void loop1(void *pvParameters)
{
  for (;;)
  {
    webSocket.loop();
    ArduinoOTA.handle();
    server.handleClient();
    delay(10);
  }
}

void loop2(void *pvParameters)
{
  for (;;)
  {
       
    if (((millis() - anterior) > 100) && (nCliente > -1))
    {
      anterior = millis();
      
       sprintf(sensorCadena, "%d",readSensors(0));
      webSocket.sendTXT(nCliente, sensorCadena);
    }
  }
}