参考文档:https://yq.aliyun.com/articles/740235?spm=a2c4e.11155472.0.0.241b1a23fnRgEJ

第一版

  1. #include <ESP8266WiFi.h>
  2. /* 依赖 PubSubClient 2.4.0 */
  3. #include <PubSubClient.h>
  4. /* 依赖 ArduinoJson 5.13.4 */
  5. #include <ArduinoJson.h>
  6. #define SENSOR_PIN 13
  7. /* 连接您的WIFI SSID和密码 */
  8. #define WIFI_SSID "3espace"
  9. #define WIFI_PASSWD "kekoukele1100"
  10. /* 设备的三元组信息*/
  11. #define PRODUCT_KEY "a1Cz4QmyJrC"
  12. #define DEVICE_NAME "esp8266-led1"
  13. #define DEVICE_SECRET "XhLZRM9adPmPts1QATVdsPmC29bUOh0M"
  14. #define REGION_ID "cn-shanghai"
  15. /* 线上环境域名和端口号,不需要改 */
  16. #define MQTT_SERVER PRODUCT_KEY ".iot-as-mqtt." REGION_ID ".aliyuncs.com"
  17. #define MQTT_PORT 1883
  18. #define MQTT_USRNAME DEVICE_NAME "&" PRODUCT_KEY
  19. #define CLIENT_ID "esp8266|securemode=3,timestamp=1234567890,signmethod=hmacsha1|"
  20. #define MQTT_PASSWD "参考上面password教程,算法工具生成"
  21. #define ALINK_BODY_FORMAT "{\"id\":\"123\",\"version\":\"1.0\",\"method\":\"thing.event.property.post\",\"params\":%s}"
  22. #define ALINK_TOPIC_PROP_POST "/sys/" PRODUCT_KEY "/" DEVICE_NAME "/thing/event/property/post"
  23. unsigned long lastMs = 0;
  24. WiFiClient espClient;
  25. PubSubClient client(espClient);
  26. void callback(char *topic, byte *payload, unsigned int length)
  27. {
  28. Serial.print("Message arrived [");
  29. Serial.print(topic);
  30. Serial.print("] ");
  31. payload[length] = '\0';
  32. Serial.println((char *)payload);
  33. }
  34. void wifiInit()
  35. {
  36. WiFi.mode(WIFI_STA);
  37. WiFi.begin(WIFI_SSID, WIFI_PASSWD);
  38. while (WiFi.status() != WL_CONNECTED)
  39. {
  40. delay(1000);
  41. Serial.println("WiFi not Connect");
  42. }
  43. Serial.println("Connected to AP");
  44. Serial.println("IP address: ");
  45. Serial.println(WiFi.localIP());
  46. Serial.print("espClient [");
  47. client.setServer(MQTT_SERVER, MQTT_PORT); /* 连接WiFi之后,连接MQTT服务器 */
  48. client.setCallback(callback);
  49. }
  50. void mqttCheckConnect()
  51. {
  52. while (!client.connected())
  53. {
  54. Serial.println("Connecting to MQTT Server ...");
  55. if (client.connect(CLIENT_ID, MQTT_USRNAME, MQTT_PASSWD))
  56. {
  57. Serial.println("MQTT Connected!");
  58. }
  59. else
  60. {
  61. Serial.print("MQTT Connect err:");
  62. Serial.println(client.state());
  63. delay(5000);
  64. }
  65. }
  66. }
  67. void mqttIntervalPost()
  68. {
  69. char param[32];
  70. char jsonBuf[128];
  71. sprintf(param, "{\"idle\":%d}", digitalRead(13));
  72. sprintf(jsonBuf, ALINK_BODY_FORMAT, param);
  73. Serial.println(jsonBuf);
  74. boolean d = client.publish(ALINK_TOPIC_PROP_POST, jsonBuf);
  75. Serial.print("publish:0 失败;1成功");
  76. Serial.println(d);
  77. }
  78. void setup()
  79. {
  80. pinMode(SENSOR_PIN, INPUT);
  81. /* initialize serial for debugging */
  82. Serial.begin(115200);
  83. Serial.println("Demo Start");
  84. wifiInit();
  85. }
  86. // the loop function runs over and over again forever
  87. void loop()
  88. {
  89. if (millis() - lastMs >= 5000)
  90. {
  91. lastMs = millis();
  92. mqttCheckConnect();
  93. /* 上报 */
  94. mqttIntervalPost();
  95. }
  96. client.loop();
  97. if (digitalRead(SENSOR_PIN) == HIGH){
  98. Serial.println("Motion detected!");
  99. delay(2000);
  100. }
  101. else {
  102. Serial.println("Motion absent!");
  103. delay(2000);
  104. }
  105. }

第二版完整代码:

  1. #include <ESP8266WiFi.h>
  2. /* 依赖 PubSubClient 2.4.0 */
  3. #include <PubSubClient.h>
  4. /* 依赖 ArduinoJson 5.13.4 */
  5. #include <ArduinoJson.h>
  6. #define SENSOR_PIN 13
  7. /* 连接您的WIFI SSID和密码 */
  8. #define WIFI_SSID "3espace"
  9. #define WIFI_PASSWD "kekoukele1100"
  10. /* 设备的三元组信息*/
  11. #define PRODUCT_KEY "a1Cz4QmyJrC"
  12. #define DEVICE_NAME "esp8266-led1"
  13. #define DEVICE_SECRET "XhLZRM9adPmPts1QATVdsPmC29bUOh0M"
  14. #define REGION_ID "cn-shanghai"
  15. /* 线上环境域名和端口号,不需要改 */
  16. #define MQTT_SERVER PRODUCT_KEY ".iot-as-mqtt." REGION_ID ".aliyuncs.com"
  17. #define MQTT_PORT 1883
  18. #define MQTT_USRNAME DEVICE_NAME "&" PRODUCT_KEY
  19. #define CLIENT_ID "esp8266|securemode=3,signmethod=hmacsha1,timestamp=1539421321846|"
  20. #define MQTT_PASSWD "5547bf3ae082851a958e65635ddba86327b4c2d6"
  21. #define ALINK_BODY_FORMAT "{\"id\":\"123\",\"version\":\"1.0\",\"method\":\"thing.event.property.post\",\"params\":%s}"
  22. #define ALINK_TOPIC_PROP_POST "/sys/" PRODUCT_KEY "/" DEVICE_NAME "/thing/event/property/post"
  23. int led13Status=0;
  24. unsigned long lastMs = 0;
  25. WiFiClient espClient;
  26. PubSubClient client(espClient);
  27. void callback(char *topic, byte *payload, unsigned int length)
  28. {
  29. Serial.print("Message arrived [");
  30. Serial.print(topic);
  31. Serial.println("] ");
  32. payload[length] = '\0';
  33. Serial.println((char *)payload);
  34. led13Status = 1-led13Status;
  35. Serial.print("led13Status");
  36. Serial.println(led13Status);
  37. digitalWrite(13,led13Status);
  38. delay(200);
  39. }
  40. void wifiInit()
  41. {
  42. WiFi.mode(WIFI_STA);
  43. WiFi.begin(WIFI_SSID, WIFI_PASSWD);
  44. while (WiFi.status() != WL_CONNECTED)
  45. {
  46. delay(1000);
  47. Serial.println("WiFi not Connect");
  48. }
  49. Serial.println("Connected to AP");
  50. Serial.println("IP address: ");
  51. Serial.println(WiFi.localIP());
  52. Serial.print("espClient [");
  53. client.setServer(MQTT_SERVER, MQTT_PORT); /* 连接WiFi之后,连接MQTT服务器 */
  54. client.setCallback(callback);
  55. }
  56. void mqttCheckConnect()
  57. {
  58. while (!client.connected())
  59. {
  60. Serial.println("Connecting to MQTT Server ...");
  61. if (client.connect(CLIENT_ID, MQTT_USRNAME, MQTT_PASSWD))
  62. {
  63. Serial.println("MQTT Connected!");
  64. }
  65. else
  66. {
  67. Serial.print("MQTT Connect err:");
  68. Serial.println(client.state());
  69. delay(5000);
  70. }
  71. }
  72. }
  73. void mqttIntervalPost()
  74. {
  75. char param[32];
  76. char jsonBuf[128];
  77. sprintf(param, "{\"LEDSwitch\":%d}", digitalRead(13));
  78. sprintf(jsonBuf, ALINK_BODY_FORMAT, param);
  79. Serial.println(jsonBuf);
  80. boolean d = client.publish(ALINK_TOPIC_PROP_POST, jsonBuf);
  81. Serial.print("publish:0 失败;1成功");
  82. Serial.println(d);
  83. }
  84. void setup()
  85. {
  86. led13Status = digitalRead(13);
  87. pinMode(SENSOR_PIN, OUTPUT);
  88. /* initialize serial for debugging */
  89. Serial.begin(115200);
  90. Serial.println("Demo Start");
  91. wifiInit();
  92. }
  93. // the loop function runs over and over again forever
  94. void loop()
  95. {
  96. if (millis() - lastMs >= 5000)
  97. {
  98. lastMs = millis();
  99. mqttCheckConnect();
  100. /* 上报 */
  101. mqttIntervalPost();
  102. }
  103. client.loop();
  104. digitalWrite(SENSOR_PIN,led13Status);
  105. if (digitalRead(SENSOR_PIN) == HIGH){
  106. Serial.println("Motion detected!");
  107. delay(2000);
  108. }
  109. else {
  110. Serial.println("Motion absent!");
  111. delay(2000);
  112. }
  113. }

1、按照文章描述,开始不知道如何生成密码,arduino中不知道有没有sha1密码生成函数,最后借助工具,按照格式生成了免密。
2、pubsubclient.h库要按照文章的要求去修改几处信息。

难点

在arduino中不知道如何处理字符串。

第三版 更改Arduino版本为5.x

  1. #include <ESP8266WiFi.h>
  2. /* 依赖 PubSubClient 2.4.0 */
  3. #include <PubSubClient.h>
  4. /* 依赖 ArduinoJson 5.13.4 */
  5. #include <ArduinoJson.h>
  6. #define SENSOR_PIN 13
  7. /* 连接您的WIFI SSID和密码 */
  8. #define WIFI_SSID "3espace"
  9. #define WIFI_PASSWD "kekoukele1100"
  10. /* 设备的三元组信息*/
  11. #define PRODUCT_KEY "a1Cz4QmyJrC"
  12. #define DEVICE_NAME "esp8266-led1"
  13. #define DEVICE_SECRET "XhLZRM9adPmPts1QATVdsPmC29bUOh0M"
  14. #define REGION_ID "cn-shanghai"
  15. /* 线上环境域名和端口号,不需要改 */
  16. #define MQTT_SERVER PRODUCT_KEY ".iot-as-mqtt." REGION_ID ".aliyuncs.com"
  17. #define MQTT_PORT 1883
  18. #define MQTT_USRNAME DEVICE_NAME "&" PRODUCT_KEY
  19. #define CLIENT_ID "esp8266|securemode=3,signmethod=hmacsha1,timestamp=1539421321846|"
  20. #define MQTT_PASSWD "5547bf3ae082851a958e65635ddba86327b4c2d6"
  21. #define ALINK_BODY_FORMAT "{\"id\":\"123\",\"version\":\"1.0\",\"method\":\"thing.event.property.post\",\"params\":%s}"
  22. #define ALINK_TOPIC_PROP_POST "/sys/" PRODUCT_KEY "/" DEVICE_NAME "/thing/event/property/post"
  23. int led13Status=0;
  24. unsigned long lastMs = 0;
  25. WiFiClient espClient;
  26. PubSubClient client(espClient);
  27. void callback(char *topic, byte *payload, unsigned int length)
  28. {
  29. Serial.print("Message arrived [");
  30. Serial.print(topic);
  31. Serial.println("] ");
  32. payload[length] = '\0';
  33. Serial.println((char *)payload);
  34. StaticJsonBuffer<400> jsonBuffer;
  35. JsonObject &root = jsonBuffer.parseObject(payload);
  36. if (!root.success())
  37. {
  38. Serial.println("parseObject() failed");
  39. }
  40. else
  41. {
  42. Serial.println("parseObject() success");
  43. //redLedState0 = json解析后的"S_D0"的值
  44. char redLedState0 = root["params"]["LEDSwitch"];
  45. Serial.print(redLedState0);
  46. Serial.println(" set sucess");
  47. Serial.println();
  48. }
  49. led13Status = 1-led13Status;
  50. Serial.print("led13Status");
  51. Serial.println(led13Status);
  52. digitalWrite(13,led13Status);
  53. delay(200);
  54. }
  55. void wifiInit()
  56. {
  57. WiFi.mode(WIFI_STA);
  58. WiFi.begin(WIFI_SSID, WIFI_PASSWD);
  59. while (WiFi.status() != WL_CONNECTED)
  60. {
  61. delay(1000);
  62. Serial.println("WiFi not Connect");
  63. }
  64. Serial.println("Connected to AP");
  65. Serial.println("IP address: ");
  66. Serial.println(WiFi.localIP());
  67. Serial.print("espClient [");
  68. client.setServer(MQTT_SERVER, MQTT_PORT); /* 连接WiFi之后,连接MQTT服务器 */
  69. client.setCallback(callback);
  70. }
  71. void mqttCheckConnect()
  72. {
  73. while (!client.connected())
  74. {
  75. Serial.println("Connecting to MQTT Server ...");
  76. if (client.connect(CLIENT_ID, MQTT_USRNAME, MQTT_PASSWD))
  77. {
  78. Serial.println("MQTT Connected!");
  79. }
  80. else
  81. {
  82. Serial.print("MQTT Connect err:");
  83. Serial.println(client.state());
  84. delay(5000);
  85. }
  86. }
  87. }
  88. void mqttIntervalPost()
  89. {
  90. char param[32];
  91. char jsonBuf[128];
  92. sprintf(param, "{\"LEDSwitch\":%d}", digitalRead(13));
  93. sprintf(jsonBuf, ALINK_BODY_FORMAT, param);
  94. Serial.println(jsonBuf);
  95. boolean d = client.publish(ALINK_TOPIC_PROP_POST, jsonBuf);
  96. Serial.print("publish:0 失败;1成功");
  97. Serial.println(d);
  98. }
  99. void setup()
  100. {
  101. led13Status = digitalRead(13);
  102. pinMode(SENSOR_PIN, OUTPUT);
  103. /* initialize serial for debugging */
  104. Serial.begin(115200);
  105. Serial.println("Demo Start");
  106. wifiInit();
  107. }
  108. // the loop function runs over and over again forever
  109. void loop()
  110. {
  111. if (millis() - lastMs >= 5000)
  112. {
  113. lastMs = millis();
  114. mqttCheckConnect();
  115. /* 上报 */
  116. mqttIntervalPost();
  117. }
  118. client.loop();
  119. digitalWrite(SENSOR_PIN,led13Status);
  120. if (digitalRead(SENSOR_PIN) == HIGH){
  121. Serial.println("Motion detected!");
  122. delay(2000);
  123. }
  124. else {
  125. Serial.println("Motion absent!");
  126. delay(2000);
  127. }
  128. }

为了解析buffer数据,应用了Arduino5.x版本

终极版本,换回Arduino6.x版本

  1. #include <ESP8266WiFi.h>
  2. /* 依赖 PubSubClient 2.4.0 */
  3. #include <PubSubClient.h>
  4. /* 依赖 ArduinoJson 5.13.4 */
  5. #include <ArduinoJson.h>
  6. #define SENSOR_PIN 13
  7. /* 连接您的WIFI SSID和密码 */
  8. #define WIFI_SSID "3espace"
  9. #define WIFI_PASSWD "kekoukele1100"
  10. /* 设备的三元组信息*/
  11. #define PRODUCT_KEY "a1Cz4QmyJrC"
  12. #define DEVICE_NAME "esp8266-led1"
  13. #define DEVICE_SECRET "XhLZRM9adPmPts1QATVdsPmC29bUOh0M"
  14. #define REGION_ID "cn-shanghai"
  15. /* 线上环境域名和端口号,不需要改 */
  16. #define MQTT_SERVER PRODUCT_KEY ".iot-as-mqtt." REGION_ID ".aliyuncs.com"
  17. #define MQTT_PORT 1883
  18. #define MQTT_USRNAME DEVICE_NAME "&" PRODUCT_KEY
  19. #define CLIENT_ID "esp8266|securemode=3,signmethod=hmacsha1,timestamp=1539421321846|"
  20. #define MQTT_PASSWD "5547bf3ae082851a958e65635ddba86327b4c2d6"
  21. #define ALINK_BODY_FORMAT "{\"id\":\"123\",\"version\":\"1.0\",\"method\":\"thing.event.property.post\",\"params\":%s}"
  22. #define ALINK_TOPIC_PROP_POST "/sys/" PRODUCT_KEY "/" DEVICE_NAME "/thing/event/property/post"
  23. //初始化次态
  24. int led13Status=0;
  25. //初始化现态
  26. int last0 = 0;
  27. unsigned long lastMs = 0;
  28. WiFiClient espClient;
  29. PubSubClient client(espClient);
  30. void callback(char *topic, byte *payload, unsigned int length)
  31. {
  32. Serial.print("Message arrived [");
  33. Serial.print(topic);
  34. Serial.println("] ");
  35. payload[length] = '\0';
  36. Serial.println((char *)payload);
  37. StaticJsonDocument<200> doc;
  38. deserializeJson(doc, (char *)payload);
  39. const char* data_method = doc["method"];
  40. Serial.print("data_method:");
  41. Serial.println(data_method);
  42. int data_ledstatus = doc["params"]["LEDSwitch"];
  43. Serial.print("data_ledstatus:");
  44. Serial.println(data_ledstatus);
  45. led13Status = data_ledstatus;
  46. Serial.print("led13Status");
  47. Serial.println(led13Status);
  48. digitalWrite(13,led13Status);
  49. delay(200);
  50. }
  51. void wifiInit()
  52. {
  53. WiFi.mode(WIFI_STA);
  54. WiFi.begin(WIFI_SSID, WIFI_PASSWD);
  55. while (WiFi.status() != WL_CONNECTED)
  56. {
  57. delay(1000);
  58. Serial.println("WiFi not Connect");
  59. }
  60. Serial.println("Connected to AP");
  61. Serial.println("IP address: ");
  62. Serial.println(WiFi.localIP());
  63. Serial.print("espClient [");
  64. client.setServer(MQTT_SERVER, MQTT_PORT); /* 连接WiFi之后,连接MQTT服务器 */
  65. client.setCallback(callback);
  66. }
  67. void mqttCheckConnect()
  68. {
  69. while (!client.connected())
  70. {
  71. Serial.println("Connecting to MQTT Server ...");
  72. if (client.connect(CLIENT_ID, MQTT_USRNAME, MQTT_PASSWD))
  73. {
  74. Serial.println("MQTT Connected!");
  75. }
  76. else
  77. {
  78. Serial.print("MQTT Connect err:");
  79. Serial.println(client.state());
  80. delay(5000);
  81. }
  82. }
  83. }
  84. void mqttIntervalPost()
  85. {
  86. char param[32];
  87. char jsonBuf[128];
  88. sprintf(param, "{\"LEDSwitch\":%d}", digitalRead(13));
  89. sprintf(jsonBuf, ALINK_BODY_FORMAT, param);
  90. Serial.println(jsonBuf);
  91. boolean d = client.publish(ALINK_TOPIC_PROP_POST, jsonBuf);
  92. Serial.print("publish:0 失败;1成功");
  93. Serial.println(d);
  94. }
  95. void setup()
  96. {
  97. led13Status = digitalRead(13);
  98. pinMode(SENSOR_PIN, OUTPUT);
  99. /* initialize serial for debugging */
  100. Serial.begin(115200);
  101. Serial.println("Demo Start");
  102. wifiInit();
  103. }
  104. // the loop function runs over and over again forever
  105. void loop()
  106. {
  107. if (millis() - lastMs >= 5000)
  108. {
  109. lastMs = millis();
  110. mqttCheckConnect();
  111. /* 上报 */
  112. mqttIntervalPost();
  113. }
  114. if (last0 != led13Status)
  115. {
  116. last0 = led13Status;
  117. mqttIntervalPost();
  118. Serial.println();
  119. }
  120. client.loop();
  121. }