ESP8266在阿里云上线(arduino)

时间:2024-06-07 16:38:40
#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 connected Serial.println(connectErrorToString(mqttclient.state())); Serial.println(F("Retrying MQTT connection in 5 seconds...")); mqttclient.disconnect(); delay(5000); // wait 5 seconds retries--; if (retries == 0) { // basically die and wait for WDT to reset me while (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"); } }