#include <DHT.h>//调用dht11驱动库
#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
#include <ESP8266HTTPClient.h>
#include <PubSubClient.h>
// #include "SSD1306Wire.h"

//安装DHT11库  DHT sensor library
//安装mqtt客户端 PubSubClient 库

// const int I2C_ADDR = 0x3c;  // oled屏幕的I2c地址
// #define SDA_PIN D4           // SDA引脚，默认gpio4(D2)
// #define SCL_PIN D5           // SCL引脚，默认gpio5(D1)
// SSD1306Wire oled(I2C_ADDR, SDA_PIN, SCL_PIN);
// #define DHTPIN D1 //说明数据接口为8266开发板的D4口，也可以写为#define DHTPIN 2既8266芯片的IO口2


#define DHTPIN D4 //说明数据接口为8266开发板的D4口，也可以写为#define DHTPIN 2既8266芯片的IO口2
#define DHTTYPE DHT11//说明使用的模块是DHT11
DHT dht(DHTPIN,DHTTYPE);//DHT11初始化
//定义浮点类型变量保存测量值
float Temperature;
float Humidity;

//定义WIFI信息
// const char* ssid = "rehome";  // Enter SSID here
// const char* password = "Ruihong123";  //Enter Password here

const char* ssid = "mac_mini";  // Enter SSID here
const char* password = "452131wW";  //Enter Password here

//定义http服务端接口IP 端口 地址
// const char* host = "192.168.2.210:8873";

// MQTT代理配置
const char *mqtt_broker = "47.242.184.139";
const char *topic = "/device/esp8266/005";
const char *mqtt_username = "admin";
const char *mqtt_password = "publish452131wW452131wW$";
const int mqtt_port = 1883;

 
WiFiClient espClient;
PubSubClient client(espClient);


ESP8266WebServer server(80);
            
void setup() {    
  pinMode(D2, OUTPUT);
  digitalWrite(D2,HIGH);//IO口2设置为高电平，点亮数字2口LED
  //digitalWrite(D2,LOW);//IO口2设置为高电平，点亮数字2口LED
  Serial.begin(115200);
  delay(100);
  dht.begin();              
  Serial.println("Connecting to ");
  Serial.println(ssid);
  //connect to your local wi-fi network
  WiFi.begin(ssid, password);
  //check wi-fi is connected to wi-fi network
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("WiFi connected..!");
  Serial.print("Got IP: ");  Serial.println(WiFi.localIP());

  server.on("/", handle_OnConnect);
  server.onNotFound(handle_NotFound);

  server.begin();
  Serial.println("HTTP server started");

  //mqtt init
  //连接到mqtt代理
  client.setServer(mqtt_broker, mqtt_port);
  client.setCallback(callback);
  while (!client.connected()) {
      String client_id = "esp8266-client-";
      client_id += String(WiFi.macAddress());
      Serial.printf("The client %s connects to the public mqtt broker\n", client_id.c_str());
      if (client.connect(client_id.c_str(), mqtt_username, mqtt_password)) {
          Serial.println("Public emqx mqtt broker connected");
      } else {
          Serial.print("failed with state ");
          Serial.print(client.state());
          delay(2000);
      }
  }
  // 发布和订阅
  //client.publish(topic, "hello emqx");
  // client.subscribe(topic01);
  client.subscribe(topic);

  /* 2. oled屏幕初始化 */
  // oled.init();
  // oled.flipScreenVertically();  // 设置屏幕翻转
  // oled.setContrast(255);        // 设置屏幕亮度
  // drawRect();                   // 测试屏幕显示
  // oled.clear();
  // oled.display();  // 清除屏幕
}
void loop() {
  //http
  server.handleClient();
  //mqtt
  client.loop();

  delay(10000);
  Temperature = dht.readTemperature(); // Gets the values of the temperature
  Humidity = dht.readHumidity(); // Gets the values of the humidity 
  if(server.getServer().status()==1){
    Serial.print("当前湿度:");//发送字符“当前湿度：”
    Serial.print(Humidity);//发送湿度值
    Serial.println("%");//发送湿度值
    
    Serial.print("当前温度:");//发送字符“当前温度：”
    Serial.print(Temperature);//发送温度值
    Serial.println("℃");//发送湿度值
  }
  //Check the current connection status
  // Serial.println("------------http start-----------");
  // if (WiFi.status() == WL_CONNECTED) {
  //   HTTPClient http;
  //   WiFiClient wifiClient;
  //   String url = "http://"+ String(host) + "/web/temperature/esp/saveEspTemperature?temperature="+Temperature+"&humidity="+Humidity;
  //   Serial.println("url:"+url);
  //   // http.begin(client,"http://jsonplaceholder.typicode.com/todos/1");
  //   http.begin(wifiClient,url); //Specify the URL
  //   int httpCode = http.GET(); //Send the request
  //   //Check for the returning code
  //   if (httpCode > 0) { //Check for the returning code
  //     String payload = http.getString(); //Get the request response payload
  //     Serial.println(httpCode);
  //     if (httpCode == 200) {
  //       Serial.println("http请求 发送温湿度成功");
  //       Serial.print("http响应结果：");
  //       Serial.println(payload);
  //     }
  //   } else {
  //     Serial.println("Error on sending request");
  //   }
  //   http.end(); //Close connection
  // }else{
  //   Serial.println("Error in WiFi connection");
  // }
  // Serial.println("------------http end-----------");
  //mqtt发布消息
  Serial.println("------------mqtt publish start-----------");
  if (WiFi.status() == WL_CONNECTED) {
    if(client.connected()){
      String sendStr = String(Temperature)+" "+String(Humidity);
      String wendu = String("Tem:")+String(Temperature);
      String shidu = String("Hum:")+String(Humidity);

      Serial.println(sendStr);
      client.publish(topic,sendStr.c_str());

      // oled.clear();
      // oled.setFont(ArialMT_Plain_16);        // 设置字体
      // oled.drawString(0, 0, wendu);  // 将要显示的文字写入缓存
      // oled.drawString(0, 20,shidu);  // 将要显示的文字写入缓存
      // oled.drawString(0, 40,sendStr);  // 将要显示的文字写入缓存
      // oled.display();                        // 将缓存里的文字在屏幕上显示
      
    }else{
      Serial.println(client.state());
      String client_id = "esp8266-client-";
      client_id += String(WiFi.macAddress());
      Serial.printf("The client %s connects to the public mqtt broker\n", client_id.c_str());
      if(client.connect(client_id.c_str(), mqtt_username, mqtt_password)) {
        Serial.println("Public emqx mqtt broker connected");
        // client.subscribe(topic01);
        client.subscribe(topic);
      }else{
          Serial.print("failed with state ");
          Serial.print(client.state());
        }  
    }
  }
  Serial.println("------------mqtt publish end-----------");
}

void handle_OnConnect() {
  Temperature = dht.readTemperature(); // Gets the values of the temperature
  Humidity = dht.readHumidity(); // Gets the values of the humidity 
  server.send(200, "text/html", SendHTML(Temperature,Humidity)); 
}

void handle_NotFound(){
  server.send(404, "text/plain", "Not found");
}

String SendHTML(float Temperaturestat,float Humiditystat){
  String ptr = "<!DOCTYPE html> <html>\n";
  ptr +="<head> <meta name=\"viewport\" content=\"width=device-width,  initial-scale=1.0, user-scalable=no\">\n";
  ptr +="<link href=\"https://fonts.googleapis.com/css?family=Open+Sans:300,400,600\" rel=\"stylesheet\">\n";
  ptr +="<meta charset=\"UTF-8\">\n";
  ptr +="<title>温湿计</title>\n";
  ptr +="<style>html { font-family: 'Open Sans', sans-serif; display: block; margin: 0px auto; text-align: center;color: #333333;}\n";
  ptr +="body{margin-top: 50px;}\n";
  ptr +="h1 {margin: 50px auto 30px;}\n";
  ptr +=" .wd {margin: 50px auto 30px;width: auto;color: #f39c12}\n";
  ptr +=" .wd1 {margin: 50px auto 30px;width: auto;color: #3498db}\n";
  ptr +=".side-by-side{display: inline-block;vertical-align: middle;position: relative;}\n";
  ptr +=".humidity-text{font-weight: 600;padding-left: 15px;font-size: 19px;width: 160px;text-align: left;}\n";
  ptr +=".humidity{font-weight: 300;font-size: 60px;color: #3498db;}\n";
  ptr +=".temperature-text{font-weight: 600;padding-left: 15px;font-size: 19px;width: 160px;text-align: left;}\n";
  ptr +=".temperature{font-weight: 300;font-size: 60px;color: #f39c12;}\n";
  ptr +=".superscript{font-size: 17px;font-weight: 600;position: absolute;right: -20px;top: 15px;}\n";
  ptr +=".data{padding: 10px;}\n";
  ptr +="</style>\n";
  ptr +="</head>\n";
  ptr +="<body>\n";
  ptr +="<div id=\"webpage\">\n";
  ptr +="<h1>温湿度检测系统</h1>\n";
  ptr +="<div class=\"data\">\n";
  ptr +="</div>\n";
  ptr +="<div class=\"side-by-side temperature-text\">温度：</div>\n";
  ptr +="<div class=\"side-by-side temperature\">";
  ptr +=Temperaturestat;
  ptr +="<span class=\"superscript\">°C</span></div>\n";
  ptr +="</div>\n";
  ptr +="<div class=\"data\">\n";
  ptr +="</div>\n";
  ptr +="<div class=\"side-by-side humidity-text\">湿度：</div>\n";
  ptr +="<div class=\"side-by-side humidity\">";
  ptr +=Humiditystat;
  ptr +="<span class=\"superscript\">%</span></div>\n";
  ptr +="</div>\n";
  ptr +="</div>\n";
  ptr +="</body>\n";
  ptr +="</html>\n";
  return ptr;
}

void callback(char *topic, byte *payload, unsigned int length) {
  Serial.println("-----------callback------------");
  Serial.print("Message arrived in topic:");
  Serial.println(topic);
  Serial.print("Message:");
  for (int i = 0; i < length; i++) {
      Serial.print((char) payload[i]);
  }
  Serial.println();
  Serial.println("-----------callback------------");
}

// void drawRect(void) {
//   for (int16_t i = 0; i < oled.getHeight() / 2; i += 2) {
//     oled.drawRect(i, i, oled.getWidth() - 2 * i, oled.getHeight() - 2 * i);
//     oled.display();
//     delay(50);
//   }
// }
