#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <ArduinoJson.h>
const char* ssid = "Sanby";
const char* password = "1234567890";
const char* mqtt_server = "182.92.223.22";
const char* mqtt_id = "v1/devices/me/telemetry";
const char* mqtt_subid = "v1/devices/me/rpc/request/+";
const int mqttPort = 1883;
WiFiClient espClient;
PubSubClient client(espClient);
int switch1=0;
int tempture=0;
void setup() {
Serial.begin(115200);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.println("Connecting to WiFi..");
}
Serial.println("Connected to the WiFi network");
client.setServer(mqtt_server, mqttPort);
client.setCallback(callback);
while (!client.connected()) {
Serial.println("Connecting to MQTT...");
if (client.connect("93834a00-2631-11eb-af1a-37260a6003e5","DHT11_DEMO_TOKEN","")) {
Serial.println("connected");
} else {
Serial.print("failed with state ");
Serial.print(client.state());
delay(2000);
}
}
client.publish(mqtt_id, "{'value':10.0}");
client.subscribe(mqtt_subid);
}
void callback(char* topic, byte* payload, unsigned int length) {
DynamicJsonDocument doc(1024);
Serial.print("Message arrived in topic: ");
Serial.println(topic);
Serial.print("Message:");
Serial.println((char *)payload);
DeserializationError error = deserializeJson(doc, payload);
if(error)return;
String method_=doc["method"];
String params_=doc["params"];
if(!method_.compareTo("setLight1SwitchStatus"))
{
if(!params_.compareTo("on")){digitalWrite(0,HIGH);pinMode(0,OUTPUT);}
if(!params_.compareTo("off")){digitalWrite(0,LOW);pinMode(0,OUTPUT);};
}
if(!method_.compareTo("setLight2SwitchStatus"))
{
if(!params_.compareTo("on")){digitalWrite(0,HIGH);pinMode(0,OUTPUT);}
if(!params_.compareTo("off")){digitalWrite(0,LOW);pinMode(0,OUTPUT);}
}
Serial.println(doc["method"].as<String>());
Serial.println(doc["params"].as<String>());
}
void loop() {
client.loop();
tempture++;
if(tempture%100000==0)
{
String bbbb= "{\"tongjinlv\":"+String(tempture)+"}";
client.publish(mqtt_id, bbbb.c_str());
Serial.println(bbbb.c_str());
}
if(!client.connected())setup();
if(WiFi.status() != WL_CONNECTED)ESP.reset();
}