/*
Basic ESP8266 MQTT example
This sketch demonstrates the capabilities of the pubsub library in combination
with the ESP8266 board/library.
It connects to an MQTT server then:
- publishes "hello world" to the topic "outTopic" every two seconds
- subscribes to the topic "inTopic", printing out any messages
it receives. NB - it assumes the received payloads are strings not binary
- If the first character of the topic "inTopic" is an 1, switch ON the ESP Led,
else switch it off
It will reconnect to the server if the connection is lost using a blocking
reconnect function. See the 'mqtt_reconnect_nonblocking' example for how to
achieve the same result without blocking the main loop.
To install the ESP8266 board, (using Arduino 1.6.4+):
- Add the following 3rd party board manager under "File -> Preferences -> Additional Boards Manager URLs":
http://arduino.esp8266.com/stable/package_esp8266com_index.json
- Open the "Tools -> Board -> Board Manager" and click install for the ESP8266"
- Select your ESP8266 in "Tools -> Board"
*/
#include
#include
#include
// Update these with values suitable for your network.
const char* ssid = "*******";
const char* password = "*******";
const char* mqtt_server = "jcckiot.com";
const char* mqtt_username = "*******"; //为注册时填的邮箱
const char* mqtt_password = "*******"; //为注册时填的密码
WiFiClient espClient;
PubSubClient client(espClient);
unsigned long lastMsg = 0;
#define MSG_BUFFER_SIZE (50)
char msg[MSG_BUFFER_SIZE];
int value = 0;
uint8_t mac[6];
char mac_string[32]; //该mac地址将作为clientid
char report_status_topic[64];
char control_device_topic[64];
char device_disconnect_topic[64];
void setup_wifi() {
delay(10);
// We start by connecting to a WiFi network
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
randomSeed(micros());
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}
void set_topic()
{
WiFi.macAddress(mac);
sprintf(mac_string, "%02X:%02X:%02X:%02X:%02X:%02X", mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
Serial.println("MAC address: ");
Serial.println(mac_string);//将打印的mac地址在添加设备的时候填入
Serial.println("mac地址将在添加设备的时候填入,请保存");
Serial.println("");
sprintf(report_status_topic, "/device/%s/status/%s", mqtt_username,mac_string);
Serial.print("report_status_topic:");
Serial.println(report_status_topic);
sprintf(control_device_topic, "/device/%s/control/%s", mqtt_username,mac_string);
Serial.print("control_device_topic:");
Serial.println(control_device_topic);
sprintf(device_disconnect_topic, "/device/%s/disconnect/%s", mqtt_username,mac_string);
Serial.print("device_disconnect_topic:");
Serial.println(device_disconnect_topic);
}
void callback(char* topic, byte* payload, unsigned int length) {
Serial.print("Message arrived [");
Serial.print(topic);
Serial.print("] ");
char msg[64]={0};
for (int i = 0; i < length; i++) {
msg[i] = (char)payload[i];
}
Serial.println(msg);
JSONVar myObject = JSON.parse(msg);
Serial.println((const char *)myObject["meteName"]);
Serial.println(myObject["meteValue"]);
// Switch on the LED if an 1 was received as first character
if (!strcmp((const char *)myObject["meteName"],"switch1") && (int)myObject["meteValue"] == 1) {
digitalWrite(BUILTIN_LED, LOW); // Turn the LED on (Note that LOW is the voltage level
Serial.println("set led: low");
client.publish(report_status_topic, "1");
// but actually the LED is on; this is because
// it is active low on the ESP-01)
}
if (!strcmp((const char *)myObject["meteName"],"switch1") && (int)myObject["meteValue"] == 0) {
digitalWrite(BUILTIN_LED, HIGH); // Turn the LED off by making the voltage HIGH
Serial.println("set led: HIGH");
client.publish(report_status_topic, "0");
}
}
void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
Serial.println("Attempting MQTT connection...");
// Create a random client ID
String clientId = mac_string;
Serial.print("MQTT clientId:");
Serial.println(clientId);
// Attempt to connect
if (client.connect(clientId.c_str(),mqtt_username,mqtt_password,device_disconnect_topic,0,false,"0")) {
Serial.println("connected");
client.subscribe(control_device_topic);
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}
void setup() {
pinMode(BUILTIN_LED, OUTPUT); // Initialize the BUILTIN_LED pin as an output
Serial.begin(115200);
setup_wifi();
set_topic();
client.setServer(mqtt_server, 1883);
client.setCallback(callback);
}
void loop() {
if (!client.connected()) {
reconnect();
}
client.loop();
}