PlatformIO 的 ESP32 最小 JSON Web 服务器示例 (ESPAsyncWebserver)

这是我推荐的在 ESP32 上使用 PlatformIO 运行 Web 服务器的起点:

example-5.cpp
#include <WiFi.h>
#include <ESPAsyncWebServer.h>
#include <ArduinoJson.h>

AsyncWebServer server(80);

void setup() {
  Serial.begin(115200);
  // 连接 Wifi,如果不连接则重启
  // https://techoverflow.net/2021/01/21/how-to-fix-esp32-not-connecting-to-the-wifi-network/
  WiFi.begin("MyWifiSSID", "MyWifiPassword");
  uint32_t notConnectedCounter = 0;
  while (WiFi.status() != WL_CONNECTED) {
      delay(100);
      Serial.println("Wifi connecting...");
      notConnectedCounter++;
      if(notConnectedCounter > 150) { // 如果 15 秒后未连接则重置板
          Serial.println("Resetting due to Wifi not connecting...");
          ESP.restart();
      }
  }
  Serial.print("Wifi connected, IP address: ");
  Serial.println(WiFi.localIP());

  // 初始化 Web 服务器 URL
  server.on("/api/wifi-info", HTTP_GET, [](AsyncWebServerRequest *request) {
      AsyncResponseStream *response = request->beginResponseStream("application/json");
      DynamicJsonDocument json(1024);
      json["status"] = "ok";
      json["ssid"] = WiFi.SSID();
      json["ip"] = WiFi.localIP().toString();
      serializeJson(json, *response);
      request->send(response);
  });

  // 启动 Web 服务器
  server.begin();
}

void loop() {
  // 将你的主要代码放在这里,重复运行:
}

记住替换你的 Wifi 凭据!WiFi.begin("MyWifiSSID", "MyWifiPassword");

向你的 platformio.ini 添加:

example-4.ini
lib_deps =
    ESP Async Webserver@1.2.3
    ArduinoJSON@6.17.2

我的完整 platformio.ini 如下所示:

example-3.ini
platform = espressif32
board = nodemcu-32s
framework = arduino
monitor_speed = 115200
lib_deps =
    ESP Async Webserver@1.2.3
    ArduinoJSON@6.17.2

使用 PlatformIO 的上传并监控以便你可以在 Wifi 网络中看到设备的 IP 地址,例如:

example-2.txt

然后转到 http://192.168.178.90/api/wifi-info(将 192.168.178.90 替换为你可以在命令行上看到的 ESP32 的 IP 地址!)

你现在应该看到类似这样的 JSON:

example-1.json
     status: "ok",
     ssid: "MyWifiSSID",
     ip: "192.168.178.90"
}

记住你可以使用浏览器插件如 JSON Viewer for Chrome 来自动格式化 JSON 文档!


Check out similar posts by category: ESP8266/ESP32