ESP32异步网络请求

ESP32发起异步网络请求

之前做的GMartix在请求粉丝数量的时候,采用的是同步请求方式,同步请求会导致请求的时候产生阻塞。
很不够优雅,显得会卡住。所以这次做新作品,一定要试试异步请求,避免这种尴尬的阻塞!

异步请求库AsyncTCP-esphome

异步请求的操作由AsyncTCP-esphome提供。

示例代码

main.cpp
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
#include <Arduino.h>
#include <AsyncTCP.h>
#include <WiFi.h>
#include <Wire.h>

#define ssid "XXXXXX"
#define password "XXXXXX"

WiFiClient client;

String response;

void asyncReqeust() {
static AsyncClient *aClient;
if (aClient) {
// aClient already exists
// aClient 繁忙
return;
}
aClient = new AsyncClient();
if (!aClient) {
// could not allocate aClient
// aClient 无法创建
return;
}
aClient->onError(
[&](void *arg, AsyncClient *client, int error) {
Serial.println("getFollowersAsync:Connect Error");
aClient = NULL;
delete client;
},
NULL);

aClient->onConnect(
[&](void *arg, AsyncClient *client) {
Serial.println("getFollowersAsync:Connected");
aClient->onError(NULL, NULL);

// 连接断开的动作
client->onDisconnect(
[&](void *arg, AsyncClient *c) {
// finish = true;
aClient = NULL;
delete c;
Serial.println("getFollowersAsync:Disconnected");
},
NULL);

// 接收到服务器数据时候的动作
client->onData(
[&](void *arg, AsyncClient *c, void *data, size_t len) {
uint8_t *d = (uint8_t *)data;
for (size_t i = 0; i < len; i++) {
Serial.write(d[i]);
}
},
NULL);

// send the request
// 发送请求
client->write(
"GET /x/relation/stat?vmid=14374079 HTTP/1.1\r\nHost: "
"api.bilibili.com\r\nContent-Type: application/json; "
"charset=utf-8\r\n\r\n");
},
NULL);
if (!aClient->connect("api.bilibili.com", 80)) {
Serial.println("Connect Fail");
AsyncClient *client = aClient;
aClient = NULL;
delete client;
}
}

void setup() {
Serial.begin(115200);
client.setTimeout(1);
WiFi.begin(ssid, password);
WiFi.setAutoReconnect(true);
delay(3000);
asyncReqeust();
}

void loop() {}

正确连接WiFi后,打开串口就可以看到输出了