I have tried the following code (sorry, the comments are in finnish):
#include <WiFi.h>
#include <ArduinoJson.h>
#include <HttpClient.h>
const char *ssid = "xxxx";
const char *password = "xxxx";
const char *apiKey = "xxxx";
const char *apiEndpoint = "https://api.openweathermap.org/data/2.5/weather?lat=61.4981&lon=23.7444&appid=";
void getWeatherData() {
// Luo WiFiClient-objekti
WiFiClient client;
// Muodosta API-kutsu
String apiURL = String(apiEndpoint) + apiKey;
Serial.print("Lähetetään HTTP-pyyntö: ");
Serial.println(apiURL);
// Yhdistä palvelimeen
if (client.connect("api.openweathermap.org", 80)) {
// Lähetä HTTP-pyyntö
client.print(String("GET ") + apiURL + " HTTP/1.1\r\n" +
"Host: api.openweathermap.org\r\n" +
"User-Agent: ArduinoWiFi/1.1\r\n" +
"Connection: close\r\n\r\n");
} else {
Serial.println("Yhteys epäonnistui");
return;
}
// Odota vastausta
while (!client.available()) {
delay(4000);
}
// ##
String responseHeader = client.readStringUntil('\r\n\r\n');
String response = client.readString();
Serial.println("Vastaus:");
Serial.println(response);
// ##
// Lue vastaus JSON-muodossa
DynamicJsonDocument jsonDoc(2048);
DeserializationError jsonError = deserializeJson(jsonDoc, client);
serializeJsonPretty(jsonDoc, Serial);
if (jsonError) {
Serial.print("JSON-parsinta epäonnistui: ");
Serial.println(jsonError.c_str());
} else {
// Tulosta säätiedot
const char *description = jsonDoc["weather"][0]["description"];
float temperature = jsonDoc["main"]["temp"];
Serial.print("Sää: ");
Serial.println(description);
Serial.print("Lämpötila: ");
Serial.println(temperature);
}
// Sulje yhteys
client.stop();
}
void setup() {
Serial.begin(115200);
// Yhdistetään WiFi-verkkoon
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(5000);
Serial.println("Yhdistetään WiFi-verkkoon...");
}
Serial.println("Yhdistetty WiFi-verkkoon!");
// Hae säätiedot ja tulosta ne sarjaporttiin
getWeatherData();
}
void loop() {
// Ei tehdä mitään tässä ohjelmassa
}
and the output to serial is:
Vastaus:
Server: openresty
Date: Mon, 20 Nov 2023 15:12:32 GMT
Content-Type: application/json; charset=utf-8
Content-Length: 486
Connection: close
X-Cache-Key: /data/2.5/weather?lat=61.5&lon=23.74
Access-Control-Allow-Origin: *
Access-Control-Allow-Credentials: true
Access-Control-Allow-Methods: GET, POST
{"coord":{"lon":23.7444,"lat":61.4981},"weather":[{"id":803,"main":"Clouds","description":"broken clouds","icon":"04n"}],"base":"stations","main":{"temp":270.27,"feels_like":265.67,"temp_min":269.85,"temp_max":270.88,"pressure":1017,"humidity":94},"visibility":10000,"wind":{"speed":3.58,"deg":299,"gust":4.92},"clouds":{"all":75},"dt":1700493152,"sys":{"type":2,"id":2081862,"country":"FI","sunrise":1700462700,"sunset":1700487383},"timezone":7200,"id":661226,"name":"Amuri","cod":200}
nullJSON-parsinta epäonnistui: IncompleteInput
So I think the problem is in my JSON parsing code.
Unfortunately I have no idea how to fix it.
Can anyone help?