//dht+bme+mqtt

#include <BMP280.h>
#include <DallasTemperature.h>
#include <Wire.h>
// #include <WiFiUdp.h> 
#include <WiFiClient.h>
#include <OneWire.h>
#include "wifi.h"
#include "Adafruit_MQTT.h"
#include "Adafruit_MQTT_Client.h"
#include <ESP8266WiFi.h>
#include <ESP8266mDNS.h>

double inTemp,outTemp, pressure;
const short ds18pin = 12, bmpsda = 4, bmpscl = 5;

/*
black - GND
red - +5V
white - DHT11/DHT22
yellow - DS18B20
grey - SCL
brown - SDA
*/

BMP280 bmp;
OneWire oneWire(ds18pin);
DallasTemperature DS18B20(&oneWire);

WiFiClient client;
Adafruit_MQTT_Client mqtt(&client, "192.168.100.100", 1883);
Adafruit_MQTT_Publish extTempMQTT = Adafruit_MQTT_Publish(&mqtt, "outTemp");
Adafruit_MQTT_Publish inTempMQTT = Adafruit_MQTT_Publish(&mqtt, "inTemp");
Adafruit_MQTT_Publish pressureMQTT = Adafruit_MQTT_Publish(&mqtt, "pressure");

void setup(){
  Serial.begin(115200);
  //==WIFI CONNECT==
  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(250);
    Serial.print(".");
  }
  Serial.println("Connected to " + String(ssid) + "; IP address: " + WiFi.localIP());
  //Sensors init
  if(!bmp.begin(bmpsda, bmpscl)){
      Serial.println("BMP init failed!\n Reset in 3 seconds");
      delay(3000);
      ESP.reset();
  }
  else {
    Serial.println("BMP init success!");  
    bmp.setOversampling(4);
  }
}

void loop(){
  getDS18();
  getBMP();
  MQTT_loop();
  serialPrint();
  delay(10000);
}

void getBMP(){
  char result = bmp.startMeasurment();
  if(result!=0){
    delay(result);
    bmp.getTemperatureAndPressure(inTemp,pressure);
  }
}

void getDS18(){
  do {
    DS18B20.requestTemperatures(); 
    outTemp = DS18B20.getTempCByIndex(0);
  } while (outTemp == 85.0 || outTemp == (-127.0));
}

void MQTT_loop() {
  MQTT_connect();

  if (! extTempMQTT.publish(outTemp)) 
    Serial.println(F("Failed"));

  if (! inTempMQTT.publish(inTemp)) 
    Serial.println(F("Failed"));

  if (! pressureMQTT.publish(pressure)) 
    Serial.println(F("Failed"));

  if(! mqtt.ping())
    mqtt.disconnect();
}

void MQTT_connect() {
  if (!mqtt.connected()) {
    while (mqtt.connect() != 0) {
      WiFi.disconnect();
      WiFi.begin(ssid, password);
      mqtt.disconnect();
      delay(1000);
    }
  }
}
void serialPrint() {
  Serial.println("====");
  Serial.println("BMP280 Temperature: " + String(inTemp) + "degC");
  Serial.println("Pressure: " + String(pressure) + "mBar");
  Serial.println("DS18B20 Temperature: " + String(outTemp) + "degC");
}
