/**
   httpUpdate.ino

    Created on: 27.11.2015

*/

#include <Arduino.h>

#include <ESP8266WiFi.h>
#include <ESP8266WiFiMulti.h>

#include <ESP8266HTTPClient.h>
#include <ESP8266httpUpdate.h>
#include <PubSubClient.h>
//#include <DHTesp.h>
//DHTesp dht;
#include <HDC2080.h>
#define ADDR 0x40
#define sensor_pin 12
HDC2080 sensor(ADDR);

float temperature = 0, humidity = 0;

#define durationSleep 300 // secondes
#define NB_TRYWIFI 20 // nbr d'essai connexion WiFi, number of try to connect WiFi
#define durationPub 10 // millisecondes entre 2 publications

#ifndef APSSID
#define APSSID "SFR_6190"
#define APPSK  "catmaruvtofabricnak4"
#endif

#define VERSION 003

const char* mqtt_server = "192.168.1.73";

ESP8266WiFiMulti WiFiMulti;
WiFiClient espClient;
PubSubClient pubclient(espClient);
long lastMsg = 0;
#define MSG_BUFFER_SIZE  (50)
char msg[MSG_BUFFER_SIZE];
char Topic_Humid[MSG_BUFFER_SIZE];
char Topic_Temp[MSG_BUFFER_SIZE];

int value = 0;
int _try = 0;

void setup() {
  unsigned long now = millis();
  Serial.begin(115200);
  Serial.println();
  Serial.println();
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(APSSID);
  WiFi.mode(WIFI_STA);
  WiFiMulti.addAP(APSSID, APPSK);
  //WiFi.begin(APSSID, APPSK);
Serial.println(millis() - now);
  int _try = 0;

  while (WiFiMulti.run() != WL_CONNECTED) {
  //while (WiFi.status() != WL_CONNECTED) {
    delay(300);
    Serial.print(".");
    _try++;
    Serial.println(millis() - now);
    if ( _try >= NB_TRYWIFI ) {
      Serial.println("Impossible to connect WiFi network, go to deep sleep");
      ESP.deepSleep(durationSleep * 1000000);
    }
  }
  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
Serial.println(millis() - now);
  pinMode(sensor_pin, OUTPUT);
  digitalWrite(sensor_pin, HIGH);
  delay(100);
  // Initialize I2C communication
  sensor.begin();
Serial.println(millis() - now);
  // Begin with a device reset
  sensor.reset();

  // Configure Measurements
  sensor.setMeasurementMode(TEMP_AND_HUMID);  // Set measurements to temperature and humidity
  sensor.setRate(MANUAL);                     // Set measurement frequency to 1 Hz
  sensor.setTempRes(FOURTEEN_BIT);
  sensor.setHumidRes(FOURTEEN_BIT);
  sensor.setTempOffsetAdjust(0); // offset 0°C
  sensor.setHumidityOffsetAdjust(0); // offset 0%RH
Serial.println(millis() - now);
  sensor.triggerMeasurement();
 Serial.println(millis() - now);
 pubclient.setServer(mqtt_server, 1883);
  //  pubclient.setCallback(callback);
  delay(10);
  Serial.println(" je lance reconnect");
  delay(durationPub);
  Serial.println(millis() - now);
  temperature = sensor.readTemp();
  humidity = sensor.readHumidity();
  Serial.println(millis() - now);
  digitalWrite(sensor_pin, LOW);
  // reconnect();
  _try = 0;
  while (!pubclient.connected()) {
    Serial.print("Attempting MQTT connection...");
    Serial.println(millis() - now);
    // Create a random client ID
    String clientId = "ESP8266Client-";
    clientId += String(WiFi.macAddress()).c_str();
    // Attempt to connect
    if (pubclient.connect(clientId.c_str())) {
      Serial.println("connected");
      Serial.println(millis() - now);
      Serial.print("status, rc=");
      Serial.println(pubclient.state());
      delay(durationPub);
      // Once connected, publish an announcement...
      snprintf (msg, MSG_BUFFER_SIZE, "%.2f ", temperature);
      snprintf (Topic_Temp, MSG_BUFFER_SIZE, "Temp-%s", String(WiFi.macAddress()).c_str());
      pubclient.publish(Topic_Temp, msg);
      Serial.print("Temperature:");
      Serial.println(msg);
      Serial.println(millis() - now);
      pubclient.loop();
      Serial.println(millis() - now);
      delay(durationPub);
      snprintf (msg, MSG_BUFFER_SIZE, "%.2f ", humidity);
      snprintf (Topic_Humid, MSG_BUFFER_SIZE, "Humid-%s", String(WiFi.macAddress()).c_str());
      pubclient.publish(Topic_Humid, msg);
      Serial.print("Humidity:");
      Serial.println(msg);
      pubclient.loop();
      Serial.println(millis() - now);
      delay(durationPub);
      //E8:9F:6D:86:CB:44
    } else {
      Serial.print("failed, rc=");
      Serial.print(pubclient.state());
      Serial.println(" try again in 5 seconds");
      // Wait 5 seconds before retrying
      delay(5000);
    }
    _try++;
    if ( _try >= NB_TRYWIFI ) {
      Serial.println("Impossible to connect broker, go to deep sleep");
      ESP.deepSleep(durationSleep * 1000000);
    }
  }
  Serial.println("end of reconnect");
  Serial.println("Published");
  Serial.print("end of setup--> sleep for ");
  Serial.print(durationSleep);
  Serial.println(" secondes");
  Serial.println(millis() - now);
  ESP.deepSleep(durationSleep * 1000000);
}

void loop() {
}
