参考文档:https://yq.aliyun.com/articles/740235?spm=a2c4e.11155472.0.0.241b1a23fnRgEJ
第一版
#include <ESP8266WiFi.h>
/* 依赖 PubSubClient 2.4.0 */
#include <PubSubClient.h>
/* 依赖 ArduinoJson 5.13.4 */
#include <ArduinoJson.h>
#define SENSOR_PIN 13
/* 连接您的WIFI SSID和密码 */
#define WIFI_SSID "3espace"
#define WIFI_PASSWD "kekoukele1100"
/* 设备的三元组信息*/
#define PRODUCT_KEY "a1Cz4QmyJrC"
#define DEVICE_NAME "esp8266-led1"
#define DEVICE_SECRET "XhLZRM9adPmPts1QATVdsPmC29bUOh0M"
#define REGION_ID "cn-shanghai"
/* 线上环境域名和端口号,不需要改 */
#define MQTT_SERVER PRODUCT_KEY ".iot-as-mqtt." REGION_ID ".aliyuncs.com"
#define MQTT_PORT 1883
#define MQTT_USRNAME DEVICE_NAME "&" PRODUCT_KEY
#define CLIENT_ID "esp8266|securemode=3,timestamp=1234567890,signmethod=hmacsha1|"
#define MQTT_PASSWD "参考上面password教程,算法工具生成"
#define ALINK_BODY_FORMAT "{\"id\":\"123\",\"version\":\"1.0\",\"method\":\"thing.event.property.post\",\"params\":%s}"
#define ALINK_TOPIC_PROP_POST "/sys/" PRODUCT_KEY "/" DEVICE_NAME "/thing/event/property/post"
unsigned long lastMs = 0;
WiFiClient espClient;
PubSubClient client(espClient);
void callback(char *topic, byte *payload, unsigned int length)
{
Serial.print("Message arrived [");
Serial.print(topic);
Serial.print("] ");
payload[length] = '\0';
Serial.println((char *)payload);
}
void wifiInit()
{
WiFi.mode(WIFI_STA);
WiFi.begin(WIFI_SSID, WIFI_PASSWD);
while (WiFi.status() != WL_CONNECTED)
{
delay(1000);
Serial.println("WiFi not Connect");
}
Serial.println("Connected to AP");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
Serial.print("espClient [");
client.setServer(MQTT_SERVER, MQTT_PORT); /* 连接WiFi之后,连接MQTT服务器 */
client.setCallback(callback);
}
void mqttCheckConnect()
{
while (!client.connected())
{
Serial.println("Connecting to MQTT Server ...");
if (client.connect(CLIENT_ID, MQTT_USRNAME, MQTT_PASSWD))
{
Serial.println("MQTT Connected!");
}
else
{
Serial.print("MQTT Connect err:");
Serial.println(client.state());
delay(5000);
}
}
}
void mqttIntervalPost()
{
char param[32];
char jsonBuf[128];
sprintf(param, "{\"idle\":%d}", digitalRead(13));
sprintf(jsonBuf, ALINK_BODY_FORMAT, param);
Serial.println(jsonBuf);
boolean d = client.publish(ALINK_TOPIC_PROP_POST, jsonBuf);
Serial.print("publish:0 失败;1成功");
Serial.println(d);
}
void setup()
{
pinMode(SENSOR_PIN, INPUT);
/* initialize serial for debugging */
Serial.begin(115200);
Serial.println("Demo Start");
wifiInit();
}
// the loop function runs over and over again forever
void loop()
{
if (millis() - lastMs >= 5000)
{
lastMs = millis();
mqttCheckConnect();
/* 上报 */
mqttIntervalPost();
}
client.loop();
if (digitalRead(SENSOR_PIN) == HIGH){
Serial.println("Motion detected!");
delay(2000);
}
else {
Serial.println("Motion absent!");
delay(2000);
}
}
第二版完整代码:
#include <ESP8266WiFi.h>
/* 依赖 PubSubClient 2.4.0 */
#include <PubSubClient.h>
/* 依赖 ArduinoJson 5.13.4 */
#include <ArduinoJson.h>
#define SENSOR_PIN 13
/* 连接您的WIFI SSID和密码 */
#define WIFI_SSID "3espace"
#define WIFI_PASSWD "kekoukele1100"
/* 设备的三元组信息*/
#define PRODUCT_KEY "a1Cz4QmyJrC"
#define DEVICE_NAME "esp8266-led1"
#define DEVICE_SECRET "XhLZRM9adPmPts1QATVdsPmC29bUOh0M"
#define REGION_ID "cn-shanghai"
/* 线上环境域名和端口号,不需要改 */
#define MQTT_SERVER PRODUCT_KEY ".iot-as-mqtt." REGION_ID ".aliyuncs.com"
#define MQTT_PORT 1883
#define MQTT_USRNAME DEVICE_NAME "&" PRODUCT_KEY
#define CLIENT_ID "esp8266|securemode=3,signmethod=hmacsha1,timestamp=1539421321846|"
#define MQTT_PASSWD "5547bf3ae082851a958e65635ddba86327b4c2d6"
#define ALINK_BODY_FORMAT "{\"id\":\"123\",\"version\":\"1.0\",\"method\":\"thing.event.property.post\",\"params\":%s}"
#define ALINK_TOPIC_PROP_POST "/sys/" PRODUCT_KEY "/" DEVICE_NAME "/thing/event/property/post"
int led13Status=0;
unsigned long lastMs = 0;
WiFiClient espClient;
PubSubClient client(espClient);
void callback(char *topic, byte *payload, unsigned int length)
{
Serial.print("Message arrived [");
Serial.print(topic);
Serial.println("] ");
payload[length] = '\0';
Serial.println((char *)payload);
led13Status = 1-led13Status;
Serial.print("led13Status");
Serial.println(led13Status);
digitalWrite(13,led13Status);
delay(200);
}
void wifiInit()
{
WiFi.mode(WIFI_STA);
WiFi.begin(WIFI_SSID, WIFI_PASSWD);
while (WiFi.status() != WL_CONNECTED)
{
delay(1000);
Serial.println("WiFi not Connect");
}
Serial.println("Connected to AP");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
Serial.print("espClient [");
client.setServer(MQTT_SERVER, MQTT_PORT); /* 连接WiFi之后,连接MQTT服务器 */
client.setCallback(callback);
}
void mqttCheckConnect()
{
while (!client.connected())
{
Serial.println("Connecting to MQTT Server ...");
if (client.connect(CLIENT_ID, MQTT_USRNAME, MQTT_PASSWD))
{
Serial.println("MQTT Connected!");
}
else
{
Serial.print("MQTT Connect err:");
Serial.println(client.state());
delay(5000);
}
}
}
void mqttIntervalPost()
{
char param[32];
char jsonBuf[128];
sprintf(param, "{\"LEDSwitch\":%d}", digitalRead(13));
sprintf(jsonBuf, ALINK_BODY_FORMAT, param);
Serial.println(jsonBuf);
boolean d = client.publish(ALINK_TOPIC_PROP_POST, jsonBuf);
Serial.print("publish:0 失败;1成功");
Serial.println(d);
}
void setup()
{
led13Status = digitalRead(13);
pinMode(SENSOR_PIN, OUTPUT);
/* initialize serial for debugging */
Serial.begin(115200);
Serial.println("Demo Start");
wifiInit();
}
// the loop function runs over and over again forever
void loop()
{
if (millis() - lastMs >= 5000)
{
lastMs = millis();
mqttCheckConnect();
/* 上报 */
mqttIntervalPost();
}
client.loop();
digitalWrite(SENSOR_PIN,led13Status);
if (digitalRead(SENSOR_PIN) == HIGH){
Serial.println("Motion detected!");
delay(2000);
}
else {
Serial.println("Motion absent!");
delay(2000);
}
}
坑
1、按照文章描述,开始不知道如何生成密码,arduino中不知道有没有sha1密码生成函数,最后借助工具,按照格式生成了免密。
2、pubsubclient.h库要按照文章的要求去修改几处信息。
难点
在arduino中不知道如何处理字符串。
第三版 更改Arduino版本为5.x
#include <ESP8266WiFi.h>
/* 依赖 PubSubClient 2.4.0 */
#include <PubSubClient.h>
/* 依赖 ArduinoJson 5.13.4 */
#include <ArduinoJson.h>
#define SENSOR_PIN 13
/* 连接您的WIFI SSID和密码 */
#define WIFI_SSID "3espace"
#define WIFI_PASSWD "kekoukele1100"
/* 设备的三元组信息*/
#define PRODUCT_KEY "a1Cz4QmyJrC"
#define DEVICE_NAME "esp8266-led1"
#define DEVICE_SECRET "XhLZRM9adPmPts1QATVdsPmC29bUOh0M"
#define REGION_ID "cn-shanghai"
/* 线上环境域名和端口号,不需要改 */
#define MQTT_SERVER PRODUCT_KEY ".iot-as-mqtt." REGION_ID ".aliyuncs.com"
#define MQTT_PORT 1883
#define MQTT_USRNAME DEVICE_NAME "&" PRODUCT_KEY
#define CLIENT_ID "esp8266|securemode=3,signmethod=hmacsha1,timestamp=1539421321846|"
#define MQTT_PASSWD "5547bf3ae082851a958e65635ddba86327b4c2d6"
#define ALINK_BODY_FORMAT "{\"id\":\"123\",\"version\":\"1.0\",\"method\":\"thing.event.property.post\",\"params\":%s}"
#define ALINK_TOPIC_PROP_POST "/sys/" PRODUCT_KEY "/" DEVICE_NAME "/thing/event/property/post"
int led13Status=0;
unsigned long lastMs = 0;
WiFiClient espClient;
PubSubClient client(espClient);
void callback(char *topic, byte *payload, unsigned int length)
{
Serial.print("Message arrived [");
Serial.print(topic);
Serial.println("] ");
payload[length] = '\0';
Serial.println((char *)payload);
StaticJsonBuffer<400> jsonBuffer;
JsonObject &root = jsonBuffer.parseObject(payload);
if (!root.success())
{
Serial.println("parseObject() failed");
}
else
{
Serial.println("parseObject() success");
//redLedState0 = json解析后的"S_D0"的值
char redLedState0 = root["params"]["LEDSwitch"];
Serial.print(redLedState0);
Serial.println(" set sucess");
Serial.println();
}
led13Status = 1-led13Status;
Serial.print("led13Status");
Serial.println(led13Status);
digitalWrite(13,led13Status);
delay(200);
}
void wifiInit()
{
WiFi.mode(WIFI_STA);
WiFi.begin(WIFI_SSID, WIFI_PASSWD);
while (WiFi.status() != WL_CONNECTED)
{
delay(1000);
Serial.println("WiFi not Connect");
}
Serial.println("Connected to AP");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
Serial.print("espClient [");
client.setServer(MQTT_SERVER, MQTT_PORT); /* 连接WiFi之后,连接MQTT服务器 */
client.setCallback(callback);
}
void mqttCheckConnect()
{
while (!client.connected())
{
Serial.println("Connecting to MQTT Server ...");
if (client.connect(CLIENT_ID, MQTT_USRNAME, MQTT_PASSWD))
{
Serial.println("MQTT Connected!");
}
else
{
Serial.print("MQTT Connect err:");
Serial.println(client.state());
delay(5000);
}
}
}
void mqttIntervalPost()
{
char param[32];
char jsonBuf[128];
sprintf(param, "{\"LEDSwitch\":%d}", digitalRead(13));
sprintf(jsonBuf, ALINK_BODY_FORMAT, param);
Serial.println(jsonBuf);
boolean d = client.publish(ALINK_TOPIC_PROP_POST, jsonBuf);
Serial.print("publish:0 失败;1成功");
Serial.println(d);
}
void setup()
{
led13Status = digitalRead(13);
pinMode(SENSOR_PIN, OUTPUT);
/* initialize serial for debugging */
Serial.begin(115200);
Serial.println("Demo Start");
wifiInit();
}
// the loop function runs over and over again forever
void loop()
{
if (millis() - lastMs >= 5000)
{
lastMs = millis();
mqttCheckConnect();
/* 上报 */
mqttIntervalPost();
}
client.loop();
digitalWrite(SENSOR_PIN,led13Status);
if (digitalRead(SENSOR_PIN) == HIGH){
Serial.println("Motion detected!");
delay(2000);
}
else {
Serial.println("Motion absent!");
delay(2000);
}
}
为了解析buffer数据,应用了Arduino5.x版本
终极版本,换回Arduino6.x版本
#include <ESP8266WiFi.h>
/* 依赖 PubSubClient 2.4.0 */
#include <PubSubClient.h>
/* 依赖 ArduinoJson 5.13.4 */
#include <ArduinoJson.h>
#define SENSOR_PIN 13
/* 连接您的WIFI SSID和密码 */
#define WIFI_SSID "3espace"
#define WIFI_PASSWD "kekoukele1100"
/* 设备的三元组信息*/
#define PRODUCT_KEY "a1Cz4QmyJrC"
#define DEVICE_NAME "esp8266-led1"
#define DEVICE_SECRET "XhLZRM9adPmPts1QATVdsPmC29bUOh0M"
#define REGION_ID "cn-shanghai"
/* 线上环境域名和端口号,不需要改 */
#define MQTT_SERVER PRODUCT_KEY ".iot-as-mqtt." REGION_ID ".aliyuncs.com"
#define MQTT_PORT 1883
#define MQTT_USRNAME DEVICE_NAME "&" PRODUCT_KEY
#define CLIENT_ID "esp8266|securemode=3,signmethod=hmacsha1,timestamp=1539421321846|"
#define MQTT_PASSWD "5547bf3ae082851a958e65635ddba86327b4c2d6"
#define ALINK_BODY_FORMAT "{\"id\":\"123\",\"version\":\"1.0\",\"method\":\"thing.event.property.post\",\"params\":%s}"
#define ALINK_TOPIC_PROP_POST "/sys/" PRODUCT_KEY "/" DEVICE_NAME "/thing/event/property/post"
//初始化次态
int led13Status=0;
//初始化现态
int last0 = 0;
unsigned long lastMs = 0;
WiFiClient espClient;
PubSubClient client(espClient);
void callback(char *topic, byte *payload, unsigned int length)
{
Serial.print("Message arrived [");
Serial.print(topic);
Serial.println("] ");
payload[length] = '\0';
Serial.println((char *)payload);
StaticJsonDocument<200> doc;
deserializeJson(doc, (char *)payload);
const char* data_method = doc["method"];
Serial.print("data_method:");
Serial.println(data_method);
int data_ledstatus = doc["params"]["LEDSwitch"];
Serial.print("data_ledstatus:");
Serial.println(data_ledstatus);
led13Status = data_ledstatus;
Serial.print("led13Status");
Serial.println(led13Status);
digitalWrite(13,led13Status);
delay(200);
}
void wifiInit()
{
WiFi.mode(WIFI_STA);
WiFi.begin(WIFI_SSID, WIFI_PASSWD);
while (WiFi.status() != WL_CONNECTED)
{
delay(1000);
Serial.println("WiFi not Connect");
}
Serial.println("Connected to AP");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
Serial.print("espClient [");
client.setServer(MQTT_SERVER, MQTT_PORT); /* 连接WiFi之后,连接MQTT服务器 */
client.setCallback(callback);
}
void mqttCheckConnect()
{
while (!client.connected())
{
Serial.println("Connecting to MQTT Server ...");
if (client.connect(CLIENT_ID, MQTT_USRNAME, MQTT_PASSWD))
{
Serial.println("MQTT Connected!");
}
else
{
Serial.print("MQTT Connect err:");
Serial.println(client.state());
delay(5000);
}
}
}
void mqttIntervalPost()
{
char param[32];
char jsonBuf[128];
sprintf(param, "{\"LEDSwitch\":%d}", digitalRead(13));
sprintf(jsonBuf, ALINK_BODY_FORMAT, param);
Serial.println(jsonBuf);
boolean d = client.publish(ALINK_TOPIC_PROP_POST, jsonBuf);
Serial.print("publish:0 失败;1成功");
Serial.println(d);
}
void setup()
{
led13Status = digitalRead(13);
pinMode(SENSOR_PIN, OUTPUT);
/* initialize serial for debugging */
Serial.begin(115200);
Serial.println("Demo Start");
wifiInit();
}
// the loop function runs over and over again forever
void loop()
{
if (millis() - lastMs >= 5000)
{
lastMs = millis();
mqttCheckConnect();
/* 上报 */
mqttIntervalPost();
}
if (last0 != led13Status)
{
last0 = led13Status;
mqttIntervalPost();
Serial.println();
}
client.loop();
}