eps32连接华为云iot,并且实现arkts控制点灯

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>

// 定义 LED 和按键引脚
const int led_pin = 48; // 根据你的实际硬件更改
const int button_pin = 0; // 通常用于ESP32的引脚

// 定义 LED 状态变量,默认为假即低电平,通过它判断 LED 的状态是否改变过
bool led_status = false;

// WiFi 连接参数
const char* ssid = "LMJZ"; // 修改为你的WiFi名称
const char* password = "12345678"; // 修改为你的WiFi密码

// MQTT 连接参数
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";

// MQTT 客户端
WiFiClient espClient;
PubSubClient client(espClient);

// MQTT 主题
#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() {
// 设置 LED 和按键引脚模式
pinMode(led_pin, OUTPUT);
pinMode(button_pin, INPUT_PULLUP);

// WiFi 初始化
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 初始化
MQTT_Init();
}

void loop() {
// 检测按键状态并控制 LED
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);
}
}

// MQTT 连接和数据上报
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);

// 解析JSON数据
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());

// 解析request id,设备响应时的topic需要包含命令的request id,且会动态变化
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); // 关闭LED
Serial.println("关灯");
} else if (ledcom == "OFF") {
digitalWrite(led_pin, HIGH); // 打开LED
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; // 更新LED状态为关闭
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 // 确保已经获取了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);
});
});
}