ESP32连接华为云
我使用的是arduinoied所写的代码,要注意,在mqtt请求华为云中,需要写心跳间隔,不然上云不了(client.setKeepAlive(60); //心跳间隔,很重要!!!)。代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147
| #include <ArduinoJson.h> #include <WiFi.h> #include <PubSubClient.h>
const int led_pin = 48; const int button_pin = 0;
bool led_status = false;
const char* ssid = "LMJZ"; const char* password = "12345678";
const char* mqttServer = "f31531a1fe.iot-mqtts.cn-north-4.myhuaweicloud.com"; const int mqttPort = 1883; const char* clientId ="65f5bd99fb8177243a4f32c3_wenshidu_0_0_2024033011"; const char* mqttUser ="65f5bd99fb8177243a4f32c3_wenshidu"; const char* mqttPassword = "def7f41de80e802a96a29f04eec1561c6a63057d2d0a0ed0aba966041ee6a5f1";
WiFiClient espClient; PubSubClient client(espClient);
#define device_id "65f5bd99fb8177243a4f32c3_wenshidu" #define secret "630aa442fa0fa9956ea95016189a5186" #define Iot_link_Body_Format "{\"services\":[{\"service_id\":\"BasicData\",\"properties\":{%s"
#define Iot_link_MQTT_Topic_Report "$oc/devices/" device_id "/sys/properties/report"
#define Iot_link_MQTT_Topic_Commands "$oc/devices/" device_id "/sys/commands/#"
#define Iot_link_MQTT_Topic_CommandsRes "$oc/devices/" device_id "/sys/commands/response/request_id="
int data_temp = 20; long lastMsg = 0;
void setup() { pinMode(led_pin, OUTPUT); pinMode(button_pin, INPUT_PULLUP);
Serial.begin(115200); WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.println("Connecting to WiFi.."); } Serial.println("Connected to the WiFi network");
MQTT_Init(); }
void loop() { if (digitalRead(button_pin) == LOW) { delay(100); if (digitalRead(button_pin) == LOW) { while(digitalRead(button_pin) == LOW); led_status = !led_status; digitalWrite(led_pin, led_status ? HIGH : LOW); } }
if (!client.connected()) { MQTT_Init(); } else { client.loop(); } long now = millis(); if (now - lastMsg > 5000) { lastMsg = now; MQTT_POST(); data_temp++; } }
void MQTT_Init() { client.setKeepAlive(60); client.setServer(mqttServer, mqttPort); client.setCallback(callback); while (!client.connected()) { Serial.println("Attempting to connect to MQTT server..."); if (client.connect(clientId, mqttUser, mqttPassword)) { Serial.println("Connected to MQTT server"); client.subscribe(Iot_link_MQTT_Topic_Commands);
} else { Serial.print("Failed to connect to MQTT server, state: "); Serial.println(client.state()); delay(5000); } } }
void MQTT_POST() { char properties[50]; char jsonBuf[200]; sprintf(properties, "\"temperature\":%d}}]}", data_temp); sprintf(jsonBuf, Iot_link_Body_Format, properties); client.publish(Iot_link_MQTT_Topic_Report, jsonBuf); Serial.println("MQTT Publish OK!"); }
void callback(char* topic, byte* payload, unsigned int length) { String recdata = ""; Serial.printf("接收到订阅的消息:主题为:%s\n", topic); Serial.print("数据内容:"); for (int i = 0; i < length; i++) { recdata += (char)payload[i]; } Serial.println(recdata);
DynamicJsonDocument jsonBuffer(1024); deserializeJson(jsonBuffer, recdata); JsonObject obj = jsonBuffer.as<JsonObject>(); JsonObject paras = obj["paras"].as<JsonObject>(); String ledcom = paras["value"]; Serial.printf("解析命令:%s\n", ledcom.c_str());
String request_id = topic; request_id.remove(0, request_id.lastIndexOf('=') + 1); Serial.printf("request_id:%s\n", request_id.c_str());
String response = "{}"; client.publish((Iot_link_MQTT_Topic_CommandsRes + request_id).c_str(), response.c_str());
if (ledcom == "ON") { digitalWrite(led_pin, LOW); Serial.println("关灯"); } else if (ledcom == "OFF") { digitalWrite(led_pin, HIGH); Serial.println("开灯"); } }
|
在鸿蒙开发中,要进行http请求,arkts代码
下面是ui代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| Button('点击').onClick(async () => { if (this.led) { try { await greenHousesHttpRequest.sendDeviceCommand('BasicData', 'Switch', 'OFF'); console.log('LED已关闭'); this.led = false; this.leddevice = '离线'; } catch (error) { console.error('关闭LED失败', error); } } else { try { await greenHousesHttpRequest.sendDeviceCommand('BasicData', 'Switch', 'ON'); console.log('LED已点亮'); this.led = true; this.leddevice = '在线'; } catch (error) { console.error('点亮LED失败', error); } } }).margin({top:10});
|
http请求代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
| async sendDeviceCommand(serviceId, commandName, commandValue) { if (!this.token) { await this.getAuthToken(); }
return new Promise((resolve, reject) => { let httpRequest = http.createHttp(); const url = "https://f31531a1fe.iotda.cn-north-4.myhuaweicloud.com:443/v5/iot/34dd0bcb3a0b46fab400809bca1b6e3e/devices/65f5bd99fb8177243a4f32c3_wenshidu/commands" httpRequest.request(url,{ method: http.RequestMethod.POST, header: { 'Content-Type': 'application/json', 'X-Auth-Token': this.token }, extraData: { "service_id": serviceId, "command_name": commandName, "paras": { "value": commandValue } } }).then(resp => { if (resp.responseCode == 200) { resolve(JSON.parse(resp.result.toString())); } else { reject('Failed to send command, response code: ' + resp.responseCode); } }).catch(error => { console.error('Error sending command:', JSON.stringify(error)); reject(error); }); }); }
|