电脑连接上ESP8266的板子
在arduino编写代码(arduino按照之前的配置,已安装好esp的开发板和几个库ArduinoJson我选了5.的版本,PubSubclient,Crypto,AliyunIoTSDK并且修改pubsubclient的参数)
在项目,加载库,管理库中搜索安装即可
修改pubsubclient的参数,进入目录(不同安装环境可能稍有不同),用记事本打开C:\Users\Administrator\Documents\Arduino\libraries\PubSubClient\src\PubSubClient.h
找到此处进行更改,如果已经打开arduino,关闭重新打开一次
// MQTT_VERSION : Pick the version
//#define MQTT_VERSION MQTT_VERSION_3_1
#ifndef MQTT_VERSION
#define MQTT_VERSION MQTT_VERSION_3_1_1
#endif
// MQTT_MAX_PACKET_SIZE : Maximum packet size
#ifndef MQTT_MAX_PACKET_SIZE
#define MQTT_MAX_PACKET_SIZE 1024
#endif
// MQTT_KEEPALIVE : keepAlive interval in Seconds
#ifndef MQTT_KEEPALIVE
#define MQTT_KEEPALIVE 300
#endif
// MQTT_SOCKET_TIMEOUT: socket timeout interval in Seconds
#ifndef MQTT_SOCKET_TIMEOUT
#define MQTT_SOCKET_TIMEOUT 60
#endif
下面新建arduino的文件,代码如下,参考文章https://blog.csdn.net/dpjcn1990/article/details/117549363
#include <ESP8266WiFi.h>
#include <ArduinoJson.h>
#include <PubSubClient.h>
#include <WiFiClientSecure.h>const char* WIFI_SSID = "xxx"; // WiFi账号密码,注意wifi有时候5G频的不行要连24的
const char* WIFI_PASSWORD = "xxxx"; // WiFi密码/******************产品/设备配置(每个人需要根据自己的产品设备信息去动态更换)**********************/
#define PRODUCT_KEY "a1hyxxxx" //产品key 从产品详情获取
#define DEVICE_NAME "LEDxxxx" //设备deviceName 从设备详情获取
// 服务端相关
#define MQTT_SERVER PRODUCT_KEY ".iot-as-mqtt.cn-shanghai.aliyuncs.com" //阿里云MQTT服务地址
#define MQTT_PORT 1883 //MQTT服务端口
// 校验三元组
#define MQTT_CLIENT_ID DEVICE_NAME "|securemode=2,signmethod=hmacsha1|" //mqtt clientid
#define MQTT_USERNAME DEVICE_NAME "&" PRODUCT_KEY //mqtt username
#define MQTT_PASSWORD "A223500DBC4xxxxxxxx" //mqtt password 通过生成工具获得,工具中clientID就填DEVICE_NAME
// 相关主题 自定义一个主题
#define TOPIC1 "/a1hyxxxx/LEDxxxx/thing/service/OpenDevice"
/*************************************************************************************************/void mqtt_callback (char* topic, byte* payload, unsigned int length);
void doWiFiTick();
void connect_wifi();
void connectToMqtt();
const __FlashStringHelper* connectErrorToString(int8_t code);WiFiClient client;
PubSubClient mqttclient(MQTT_SERVER, MQTT_PORT, &mqtt_callback, client);bool ICACHE_FLASH_ATTR connectHTTPS() {Serial.print("connecting to ");Serial.println(MQTT_SERVER);if (!client.connect(MQTT_SERVER, MQTT_PORT)) {Serial.println(F("connection failed"));return false;}else {Serial.println(F("connection succeed"));return true;}
}void setup() {// put your setup code here, to run once:delay(2000);Serial.begin(115200);
// Serial.print("MQTT_SERVER:");
// Serial.println(MQTT_SERVER);
// Serial.print("MQTT_CLIENT_ID:");
// Serial.println(MQTT_CLIENT_ID);
// Serial.print("MQTT_USERNAME:");
// Serial.println(MQTT_USERNAME);
// Serial.print("TOPIC1:");
// Serial.println(TOPIC1);pinMode(LED_BUILTIN, OUTPUT);Serial.println("");
}void loop() {// put your main code here, to run repeatedly:ESP.wdtFeed();doWiFiTick();if (WiFi.status() == WL_CONNECTED) {connectToMqtt();mqttclient.loop();}delay(2000);
}/*** 功能:连接到WiFi热点*/
void connect_wifi() {WiFi.disconnect();WiFi.mode(WIFI_STA);WiFi.begin(WIFI_SSID, WIFI_PASSWORD);while (WiFi.status() != WL_CONNECTED) {delay(500);Serial.print(".");}Serial.print(F("\nWiFi connected to "));Serial.println(WIFI_SSID);Serial.print(F("IP address: "));Serial.println(WiFi.localIP());
}/*** 功能:连接到Mqtt*/
void connectToMqtt() {if (mqttclient.connected()) {return;}Serial.print(F("Connecting to MQTT... "));int8_t ret;uint8_t retries = 3;while (!mqttclient.connect(MQTT_CLIENT_ID, MQTT_USERNAME,MQTT_PASSWORD)) { // connect will return true for connectedSerial.println(connectErrorToString(mqttclient.state()));Serial.println(F("Retrying MQTT connection in 5 seconds..."));mqttclient.disconnect();delay(5000); // wait 5 secondsretries--;if (retries == 0) {// basically die and wait for WDT to reset mewhile (1);}yield();}Serial.println(F("Success!"));// 订阅主题mqttclient.subscribe(TOPIC1);}/*** 功能:连接路由心跳函数*/
void doWiFiTick() {static bool taskStarted = false;static bool startSTAFlag = false;static uint32_t lastWiFiCheckTick = 0;if (!startSTAFlag) {startSTAFlag = true;Serial.print("connect to ap:");Serial.println(WIFI_SSID);WiFi.disconnect();WiFi.mode(WIFI_STA);WiFi.begin(WIFI_SSID, WIFI_PASSWORD);Serial.printf("Heap size:%d\r\n", ESP.getFreeHeap());}//未连接1s重连if ( WiFi.status() != WL_CONNECTED ) {if (millis() - lastWiFiCheckTick > 1000) {lastWiFiCheckTick = millis();Serial.print(".");}}//连接成功建立else {if (taskStarted == false) {taskStarted = true;Serial.print("\r\nGet IP Address: ");Serial.println(WiFi.localIP());}}
}/*** 功能:MQTT回调* 参数:* 1. topic 主题* 2. payload 载体* 3. length 载体长度*/
void mqtt_callback (char* topic, byte* payload, unsigned int length) {byte *end = payload + length;for (byte *p = payload; p < end; ++p) {Serial.print(*((const char *)p));}Serial.println("");parseMqttResponse((char *)payload);
}/*** 解析mqtt数据*/
void parseMqttResponse(char* payload){Serial.println("start parseOneNetMqttResponse");StaticJsonBuffer<100> jsonBuffer;// StaticJsonBuffer 在栈区分配内存 它也可以被 DynamicJsonBuffer(内存在堆区分配) 代替// DynamicJsonBuffer jsonBuffer;JsonObject& root = jsonBuffer.parseObject(payload);// Test if parsing succeeds.if (!root.success()) {Serial.println("parseObject() failed");return ;}//String deviceName = root["dn"];//int status = root["s"];String method = root["method"];Serial.println(method);// if(strcmp(DEVICE_NAME,deviceName.c_str())== 0){
// if (status == 1) {
// digitalWrite(LED_BUILTIN, LOW);
// } else {
// digitalWrite(LED_BUILTIN, HIGH);
// }
// }if (method == "thing.service.CloseDevice") {digitalWrite(LED_BUILTIN, HIGH);} else {digitalWrite(LED_BUILTIN, LOW);}
}/*** 功能:打印错误* 参数:* 1. code 错误码*/
const __FlashStringHelper* connectErrorToString(int8_t code) {switch (code) {case 1: return F("The Server does not support the level of the MQTT protocol requested");case 2: return F("The Client identifier is correct UTF-8 but not allowed by the Server");case 3: return F("The MQTT service is unavailable");case 4: return F("The data in the user name or password is malformed");case 5: return F("Not authorized to connect");case 6: return F("Exceeded reconnect rate limit. Please try again later.");case 7: return F("You have been banned from connecting. Please contact the MQTT server administrator for more details.");case -1: return F("Connection failed");case -2: return F("Failed to subscribe");case -3: return F("Connection Lost");case -4: return F("Connection Timeout");default: return F("Unknown error");}
}
arduino代码中这一行信息,用此签名工具计算得出,双击sign的网页
#define MQTT_PASSWORD "A223500DBC4xxxxxxxx" //mqtt password 通过生成工具获得,工具中clientID就填DEVICE_NAME
其中productKey和devicename,devicSecret在阿里云的设备管理页面都可以获取,clientID和devicename一致,timestamp可以不填,生成即可
上传,编译验证就可以发现阿里云的网页上该设备上线