//测试没有通过,连接不上ALiyun IoT,暂时不知道原因,是Wokwi的 public Gateway不支持吗?
//运行后串口输出的信息如下
//Attempting MQTT connection...failed, rc=2 try again in 5 seconds这条信息一直显示。
/*----------------------------
ets Jul 29 2019 12:21:46

rst:0x1 (POWERON_RESET),boot:0x13 (SPI_FAST_FLASH_BOOT)
configsip: 0, SPIWP:0xee
clk_drv:0x00,q_drv:0x00,d_drv:0x00,cs0_drv:0x00,hd_drv:0x00,wp_drv:0x00
mode:DIO, clock div:2
load:0x3fff0030,len:1156
load:0x40078000,len:11456
ho 0 tail 12 room 4
load:0x40080400,len:2972
entry 0x400805dc
Connecting to Wokwi-GUEST
...
WiFi connected
IP Adderss: 10.10.0.2
userName=***&***
Attempting MQTT connection...failed, rc=2 try again in 5 seconds
Attempting MQTT connection...
-----------------*/
#include <WiFi.h>
#include <PubSubClient.h>
#include <ArduinoJson.h>
#include "DFRobot_Aliyun.h"

#define BEDROOD_LIGHT  2     //如果不是连接的D2,此处根据实际连接的数字引脚号做相应修改;否则不用修改

/*配置WIFI名和密码*/
const char * WIFI_SSID     = "Wokwi-GUEST";//"修改为自己手机热点名称";
const char * WIFI_PASSWORD = "";//"修改为自己手机热点密码";

/*配置设备证书信息*/
String ProductKey = "";//"";//"修改为自己在阿里物联网云平台创建产品的名称";
String ClientId = "12345";/*自定义ID*/
String DeviceName = "";//"";//"修改为自己在阿里物联网云平台创建设备的名称";
String DeviceSecret = "";//"";//"修改为自己在阿里物联网云平台创建设备的密钥";

/*配置域名和端口号*/
String ALIYUN_SERVER = "iot-as-mqtt.cn-shanghai.aliyuncs.com";
uint16_t PORT = 1883;

/*需要操作的产品标识符*/
String Identifier = "";//"";//"修改为在阿里物联网云平台创建的自定义功能标识符";

/*需要上报和订阅的两个TOPIC*/
const char * subTopic = "";//"";//"修改为在阿里物联网云平台创建产品的订阅topic,以set结尾的topic";//****set
const char * pubTopic = "";//"";//"修改为在阿里物联网云平台创建产品的发布topic,以post结尾的topic";//******post

DFRobot_Aliyun myAliyun;
WiFiClient espClient;
PubSubClient client(espClient);

static void openLight(){
  digitalWrite(BEDROOD_LIGHT, HIGH);
}

static void closeLight(){
  digitalWrite(BEDROOD_LIGHT, LOW);
}

void connectWiFi(){
  Serial.print("Connecting to ");
  Serial.println(WIFI_SSID);
  WiFi.begin(WIFI_SSID,WIFI_PASSWORD);
  while(WiFi.status() != WL_CONNECTED){
    delay(500);
    Serial.print(".");
  }
  Serial.println();
  Serial.println("WiFi connected");
  Serial.print("IP Adderss: ");
  Serial.println(WiFi.localIP());
}

void callback(char * topic, byte * payload, unsigned int len){
  Serial.print("Recevice [");
  Serial.print(topic);
  Serial.print("] ");
  for (int i = 0; i < len; i++){
    Serial.print((char)payload[i]);
  }
  Serial.println();
  StaticJsonBuffer<300> jsonBuffer;
  JsonObject& root = jsonBuffer.parseObject((const char *)payload);
  if(!root.success()){
    Serial.println("parseObject() failed");
    return;
  }
  const uint16_t LightStatus = root["params"][Identifier];
  if(LightStatus == 1){
    openLight();
  }else{
    closeLight();
  }
  String tempMseg = "{\"id\":"+ClientId+",\"params\":{\""+Identifier+"\":"+(String)LightStatus+"},\"method\":\"thing.event.property.post\"}";
  char sendMseg[tempMseg.length()];
  strcpy(sendMseg,tempMseg.c_str());
  client.publish(pubTopic,sendMseg);
}

void ConnectAliyun(){
  while(!client.connected()){
    Serial.print("Attempting MQTT connection...");
    /*根据自动计算的用户名和密码连接到Alinyun的设备,不需要更改*/
    if(client.connect(myAliyun.client_id,myAliyun.username,myAliyun.password)){
      Serial.println("connected");
      client.subscribe(subTopic);
    }else{
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      delay(5000);
    }
  }
}
void setup(){
  Serial.begin(115200);
  pinMode(BEDROOD_LIGHT,OUTPUT);
  
  digitalWrite(BEDROOD_LIGHT, HIGH);

  /*连接WIFI*/
  connectWiFi();
  
  /*初始化Alinyun的配置,可自动计算用户名和密码*/
  myAliyun.init(ALIYUN_SERVER,ProductKey,ClientId,DeviceName,DeviceSecret);
  
  client.setServer(myAliyun.mqtt_server,PORT);
  
  /*设置回调函数,当收到订阅信息时会执行回调函数*/
  client.setCallback(callback);
  
  /*连接到Aliyun*/
  ConnectAliyun();
  
  /*开机先关灯*/
  closeLight();
  
  /*上报关灯信息*/
  client.publish(pubTopic,("{\"id\":"+ClientId+",\"params\":{\""+Identifier+"\":0},\"method\":\"thing.event.property.post\"}").c_str());
}

void loop(){
  if(!client.connected()){
    ConnectAliyun();
  }
  client.loop();
}