#include <ESP8266MQTT.h>
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <ArduinoJson.h>
int open = 5;
int close = 4;

void onConnectionEstablished();

ESP8266MQTT client(
  "www.360xyz.cn",             // Wifi ssid
  "qq282246101",             // Wifi password
  "5DY2NRSW8D.iotcloud.tencentdevices.com",    // MQTT broker ip
  1883,               // MQTT broker port
  "5DY2NRSW8DSwitchKfb1;12010126;VU8K5;1657637931",              // MQTT username
  "7418dac5c7f14c94d80b67281ee4bce77879d3d28e6202489b26570766a958bf;hmacsha256",         // MQTT password
  "SwitchKfb1",            // Client name
  onConnectionEstablished, // Connection established callback
  true,               // Enable web updater
  true                // Enable debug messages
);

void setup() {
  Serial.begin(19200);
  pinMode(open, OUTPUT);
  pinMode(close, OUTPUT);
}

void onConnectionEstablished() {
  // 订阅主题并且将该主题内收到的消息通过串口发送
  client.subscribe("5DY2NRSW8D/SwitchKfb1/control", [](const String & payload) {
//    Serial.println(payload);
//    DynamicJsonDocument  jsonBuffer(100);
//    deserializeJson(jsonBuffer, payload);
//    JsonObject root = jsonBuffer.as<JsonObject>();
//    String user = payload;
    String state = payload;
    if (state == "1") {
      //开
      Serial.println("开");
      digitalWrite(close, LOW);
      delay(200);
      digitalWrite(open, HIGH);
      client.publish("5DY2NRSW8D/SwitchKfb1/event", payload);
    }
    if (state == "0") {
      //关 
      Serial.println("关");
      digitalWrite(open, LOW);
      delay(200);
      digitalWrite(close, HIGH);
      //腾讯云 设置好了发布必须为json
      client.publish("5DY2NRSW8D/SwitchKfb1/event", payload);
    }
    Serial.println(payload);//此处可以编写一个函数来代替
  });

  // 向某个主题发送消息
  client.publish("5DY2NRSW8D/SwitchKfb1/event", "This is a message");

}

void loop() {
  client.loop();
}