#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <WiFiManager.h>        //https://github.com/tzapu/WiFiManager
#include <ArduinoJson.h>          //https://github.com/bblanchon/ArduinoJson pentru salvarea credentialelor in eprom
#include <WiFiClient.h> 
#include <OneWire.h>

//ESP8266-01 nu are suficienta memorie pt update http
const char* mqtt_user="64x35up";
const char* mqtt_devid="5566";
#define DEBUG 0 //0=off 1=on
#define RELAY 0 //  pinul de date 

/********** NU edita mai jos ******************/
char mqttPassword[15]; //urmatoarele le va genera cu functia gen
char mqttSUB[22];
char espName[13];
char mqttESP[22];
char mqttRELAY[23];
char mqttLWT[22];
char mqttSTA[24];

const String model = "ESP8266 Releu";
const String ver = "v1.1.0";
const char* mqttServer = "mqtt.clickhome.ro";
const int mqttPort = 1883;
String mqttMessage;
const unsigned long interval_update=1000*60*60; // face update la 60 min 
unsigned long t_update=0;

WiFiClient espClient;
PubSubClient client(espClient);

void generate_vars(){
  strcpy (mqttPassword, "8219CH");
  strcat (mqttPassword, mqtt_user);

  strcpy (espName, mqtt_user);
  strcat (espName, "-");
  strcat (espName, mqtt_devid);

  strcpy (mqttSUB, "cmnd/");
  strcat (mqttSUB, espName);
  strcat (mqttSUB, "/ESP");

  strcpy (mqttESP, "stat/");
  strcat (mqttESP, espName);
  strcat (mqttESP, "/ESP");

  strcpy (mqttRELAY, "stat/");
  strcat (mqttRELAY, espName);
  strcat (mqttRELAY, "/RELAY");

  strcpy (mqttLWT, "tele/");
  strcat (mqttLWT, espName);
  strcat (mqttLWT, "/LWT");

  strcpy (mqttSTA, "tele/");
  strcat (mqttSTA, espName);
  strcat (mqttSTA, "/STATE");
}

String ipToString(IPAddress ip){
  String s="";
  for (int i=0; i<4; i++)
    s += i  ? "." + String(ip[i]) : String(ip[i]);
  return s;
}
String getMacAddress() {
  byte mac[6];
  WiFi.macAddress(mac);
  String cMac = "";
  for (int i = 0; i < 6; ++i) {
    cMac += String(mac[i],HEX);
    if(i<5)
    cMac += "-";
  }
  cMac.toUpperCase();
  return cMac;
}

void reconectez() {
  
  // ma conectez la mqtt server
  while (!client.connected()) {
    client.setServer(mqttServer, mqttPort);
    #if DEBUG
    Serial.print("AtloopTempting MQTT connection...");
    #endif
    // Incerc sa ma reconectez cu LWT din 5 in 5 secunde
    if (client.connect(espName, mqtt_user, mqttPassword, mqttLWT, 1, 1, "Offline")) {
      #if DEBUG
      Serial.println("connected");
      #endif
      client.publish(mqttLWT,"Online",TRUE);
        // trimit informatii utile cand ma conectez
        String esp_info = "{\"ESPMac\":\"";
        esp_info += getMacAddress();
        esp_info += "\",\"IPAddress\":\"";
        esp_info += ipToString(WiFi.localIP());    
        esp_info += "\"}";       
        String netinfo = "{\"Module\":\"";
        netinfo += String (model);
        netinfo += "\",\"Version\":\"";
        netinfo += String (ver);
        netinfo += "\"}";            
        
        client.publish(mqttESP, netinfo.c_str(),TRUE);
        #if DEBUG
        Serial.println(netinfo);
        #endif
        client.publish(mqttESP, esp_info.c_str(),TRUE);
        #if DEBUG
        Serial.println(esp_info);
        #endif
    
        // citesc starea si o trimit cand se reconecteaza si la boot
        String json = "{\"Relay\":\"";
        json += String (digitalRead(RELAY));
        json += "\"}";
        client.publish(mqttRELAY, json.c_str(),TRUE);

        client.subscribe(mqttSUB);
    } else {
      #if DEBUG
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 60 seconds");
      #endif
      // Wait 60 seconds before retrying
      delay(60000);
    }
  }
}


void setup()
{
  pinMode(RELAY,OUTPUT);

  #if DEBUG
  Serial.begin(115200);
  #endif

  generate_vars(); //genereaza topicurile de mqtt in baza mqtt_user si mqtt_devid

  // ma conectez la AP via wifi
   WiFiManager wifi;
   wifi.setConfigPortalTimeout(120); // a timeout so the ESP doesn't hang waiting to be configured, for instance after a power failure
   wifi.setTimeout(180); // sta AP 3 minute apoi se reseteaza din nou
   if (!wifi.autoConnect("ClickHome")) {
     #if DEBUG
     Serial.println("timeout - going to sleep");
     #endif
  }
  delay(200);

  reconectez();
  client.setCallback(getMessage); //setez functia care parseaza mesajele venite prin mqtt
  update_state(); //facem update la mqtt cu Uptime
}

void update_state(){ //facem update la mqtt cu Uptime
    String json = "{\"Uptime\":";
    json += (int)millis()/3600000; //exprimat in ore
    json += "}";
    client.publish(mqttSTA, json.c_str(),FALSE);
}

void getMessage(char* topic, byte* payload, unsigned int length) {
  float t = 0;
  mqttMessage="";
  #if DEBUG
  Serial.print("Message arrived in topic: ");
  Serial.println(topic);
  Serial.print("Message:");
  #endif
  for (int i = 0; i < length; i++) {
    mqttMessage += (char)payload[i];
  }
  #if DEBUG
  Serial.println(mqttMessage);
  #endif
 
  // daca a primit on
  if (mqttMessage == "ON")
  {
    #if DEBUG
    Serial.println("Pornesc releu");
    #endif
    digitalWrite(RELAY,HIGH);
    String json = "{\"Relay\":\"1\"}";
    client.publish(mqttRELAY, json.c_str(),TRUE);
  }  
  if (mqttMessage == "OFF")
  {
     long now = millis(); 
    #if DEBUG
    Serial.println("Opresc releu");
    Serial.println(now);
    #endif
    digitalWrite(RELAY,LOW);
    String json = "{\"Relay\":\"0\"}";
    client.publish(mqttRELAY, json.c_str(),TRUE);
  }

  if (mqttMessage == "stare")
  {
    // citesc starea si o trimit
    String json = "{\"Relay\":\"";
    json += String (digitalRead(RELAY));
    json += "\"}";
    client.publish(mqttRELAY, json.c_str(),TRUE);
  }
}

void loop()
{
  if (!client.connected()) 
  {
    reconectez();
  }
  client.loop();
  //facem update la $interval_update cu uptime
  if (millis() - t_update > interval_update){
    update_state();
    t_update=millis();
  }
  //end update

}

