ESP8266随机切割响应

ESP8266 randomly cutting response

我想让我的 NodeMCU V3 从 OpenWeatherMapApi 获取天气数据。我找到了一些示例代码如何发送 GET 请求,但响应被随机切断。阅读响应后,我打印收到的 JSON 响应的长度。响应应该有大约 16k 个字符,但每个请求都是随机的。有时它应该是 16k,有时是 11k,有时是 13k 等等。这是我的代码:

#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>

WiFiClient client;

const char *url = "/data/2.5/onecall?lat=51.039117&lon=21.072800&appid=xxx&lang=pl&units=metric&exclude=minutely";
const char *host = "api.openweathermap.org";

int fetchWeatherJson(struct weatherDataPacketStruct *wdps) {
  if (!isConnected())
    return -1;
  Serial.println("Fetching weather");
  if (!client.connect(host, 80)) {
    Serial.println("Connection failed");
    return -1;
  }
  client.setTimeout(15000);
  client.print(String("GET ") + url + " HTTP/1.1\r\n" +
               "Host: " + host + "\r\n" +
               "Connection: close\r\n\r\n");

  while (client.connected()) {
    String line = client.readStringUntil('\n');
    if (line == "\r") {
      Serial.println("headers received");
      break;
    }
  }

  Serial.println("reply was:");
  Serial.println("==========");
  String line;
  while (client.available()) {
    line = client.readStringUntil('\n');  //Read Line by Line
   // Serial.println(line); //Print response
  }
  Serial.println(line.length());
  parseWeatherJson(line.c_str(), wdps);

  return 1;
}

有什么问题吗?谢谢。

我在这里找到了一些解决方案:
使用 read() 而不是 readString() 并放置 delay(1) 一开始似乎可以工作,但是当我保存将字符读取到数组而不是打印它,响应再次被切断。然而,当我删除延迟(1)时,一切都开始工作,不知道为什么。这是最终代码:

#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>

WiFiClient client;

const char *url = "/data/2.5/onecall?lat=51.039117&lon=21.072800&appid=xxx&lang=pl&units=metric&exclude=minutely";
const char *host = "api.openweathermap.org";
char responseBuff[18000];

int fetchWeatherJson(struct weatherDataPacketStruct *wdps) {
  client.flush();
  if (!isConnected())
    return -1;

  Serial.println("FETCHING weather");
  if (!client.connect(weatherHost, 80)) {
    Serial.println("connection failed");

    return -1;
  }
  client.setTimeout(15000);
  client.print(String("GET ") + weatherUrl + " HTTP/1.1\r\n" +
               "Host: " + weatherHost + "\r\n" +
               "Connection: close\r\n\r\n");

  while (client.connected()) {
    String line = client.readStringUntil('\n');
    Serial.println(line);
    if (line == "\r") {
      Serial.println("headers received");
      break;
    }
  }
  
  long int time = millis();
  long int wait = 1000 * 10;
  int counter = 0;
  while ((time + wait) > millis()) {
    while (client.available()) {
      char c = client.read();
      responseBuff[counter] = c;
      counter++;

      Serial.print(c);

      if (c == '[=10=]')
        continue;
    }
  }
  Serial.println(counter);

  return parseWeatherJson(responseBuff, wdps);
}