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

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

#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


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

 
WiFiClient espClient;
PubSubClient client(espClient);

            
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());

  //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);
}
void loop() {
  //mqtt
  client.loop();

  delay(10000);
  Temperature = dht.readTemperature(); // Gets the values of the temperature
  Humidity = dht.readHumidity(); // Gets the values of the humidity 
  
  //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());
    }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 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------------");
}
