#include <Arduino.h>
#include <ESP8266WiFi.h>
#include <ArduinoJson.h>
#include <NTPClient.h>
#include <WiFiUdp.h>
#define DEBUG 0
#if DEBUG==1
#define debug(x) Serial.println(x)
#else
#define debug(x)
#endif
WiFiUDP ntpUDP;
NTPClient timeClient(ntpUDP, "0.south-america.pool.ntp.org", -18000, 6000);
const char *ssid = "mdchaparror";
const char *password = "un260874";
long timeAnterior;
long matrix_time;
int matrix_speed = 150;

#include "matrix.hpp"
#include "mqtt.hpp"
#include "ota.hpp"

void setup()
{
  Serial.begin(921600);
  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);
  while (WiFi.waitForConnectResult() != WL_CONNECTED)
  {
    delay(5000);
    ESP.restart();
  }

 debug(WiFi.localIP());
  ota_init();
  mqtt_init();

  timeClient.begin();
  matrix_init();
}

void loop()
{
   ArduinoOTA.handle();
  
  if ((millis() - matrix_time) > (long unsigned int)matrix_speed)
  {
    matrix_time = millis();
    show_matrix();
  }

  if ((millis() - timeAnterior) > 2500)
  {
    timeAnterior = millis();
    yield();
    timeClient.update(); //sincronizamos con el server NTP
    yield();
    hora = timeClient.getFormattedTime();
    texto = mensaje + " " + hora;
    longitud = texto.length() * 5 + 64;
  }


if (!client.connected())
    { 
      reconnect();
    }
  client.loop();
  yield();
  debug("\n\n Free RAM -> ");
  debug(ESP.getFreeHeap());
}

