#include <SPI.h>



#include <PubSubClient.h>
#include <Wire.h>
#include "MqttUtiles.h"
//**************************************************************************************************************************************************

bool MqttUtiles::pasa_incre( unsigned long *tt, unsigned long incre)
{
  unsigned long t=millis();
  if(t<*tt)
  {
    *tt=t;
    return true;
  }
  if((*tt+incre)>=t)
    return false;
 *tt=t;
  return true;
}

bool MqttUtiles::pasa_incre( volatile unsigned long *tt, unsigned long incre)
{
  unsigned long t=millis();
  if(t<*tt)
  {
    *tt=t;
    return true;
  }
  if((*tt+incre)>=t)
    return false;
 *tt=t;
  return true;
}
//**************************************************************************************************************************************************
WifiManager::WifiManager()
{
    
}
  
void WifiManager::inicia( WiFiClient *espclient,char *ssid, char* key)
{
   espClient= espclient;
   strcpy(nred, ssid);
   strcpy(pass, key);
}

bool WifiManager::loop()
{
    if((WiFi.status() == WL_CONNECTED))
     return true;
    WiFi.mode(WIFI_STA);
    WiFi.begin(nred, pass);

    for(int i=0; i<5 && WiFi.status() != WL_CONNECTED; i++)
    {
      delay(500);
    }
    
    return WiFi.status() == WL_CONNECTED;
}
//**************************************************************************************************************************************************
MqttManager::MqttManager()
{
  
}

void MqttManager::inicia(PubSubClient *mqttClient,char *ideEsp, char *host, int port, MqttReceiver* classReceiver)
{
  strcpy(idEsp,ideEsp);
  MqttManager::listener=classReceiver;
  client_mqtt=mqttClient;
  client_mqtt->setServer(host, port);
  client_mqtt->setCallback(MqttManager::OnMqtt);
}

bool MqttManager::loop()
{
   if(client_mqtt->loop())
    return true;
    
   if(client_mqtt->connect(idEsp))
  {
     subscribe_mqtt();
     return true;
     
  }
}
void MqttManager::subscribe_mqtt()
{
  if(MqttManager::listener==NULL)
    return;
   MqttManager::listener->SubscribeMqtt(client_mqtt);
}
//auxiliar------------------
void MqttManager::OnMqtt(char* topic, byte* payload, unsigned int length)
{
  if(MqttManager::listener==NULL)
  return;
   int i;
  char buf[32];
  i=31;
  if(i>length)
    i=length;
  memcpy(buf, payload, i);
  buf[i]=0;
  MqttManager::listener->OnMqtt(topic, buf);
  
}
