Hey Guys,
im making my first steps in the Arduino world, so please be kind if i have some basic errors here...
I want to ask a SSL JSON API for some values, to store them in a variable and later display them on a SH1106 Display. So first i need to get the Values and this is where im struggeling on multiple mystery problems..
First problem: I get the API-Answer mostly only on first loop, if i get an Answer at all.
Second problem: The parsing into my variables only works on first loop, if it works at all.
The strange thing is that the Code works sometimes, but mostly not. I have the feeling that its somehow memory related. I dont know if i have the correct SPIFFS-Setting, tried no or 3M but doesnt get better.
The API-Response is somewhat large (8,17 kb), is this to much to get parsed stable?
Board: NodeMcu v3 with ESP-8266
Settings: NodeMCU 1.0 (ESP-12E Module), 80 MHz, Flash, Disabled, 4M (3M SPIFFS), v2 Lower Memory, Disabled, None, Only Sketch
API: https://api.corrently.io/core/gsi?plz=97082
Values im interested: "forecast_0_eevalue" and "forecast_0_energyprice". More maybe later, but currently the current time (0) is enough.
So would you kindly please have a look at my code?
Heavy use of Serial.print and some tests for debugging, but didnt help..
The out-commented things are for debugging, later use or replaced from the sample code my code is based on.
#include <ESP8266WiFi.h>
#include <ESP8266Ping.h>
//#include <ESP8266HTTPClient.h>
#include <WiFiClientSecure.h>
#include <ArduinoJson.h>
// WiFi
const char* WIFI_SSID = "xxx";
const char* WIFI_PWD = "xxx";
// API-Server
const char* host = "api.corrently.io";
const int httpsPort = 443;
const char fingerprint[] PROGMEM = "CD B8 85 5C D3 0B D8 06 C3 B9 43 9A B9 06 4C 4E 36 B9 65 AE"; //Valid til Donnerstag, 7. November 2019
// Declaring Variables
//String line;
//Test API-Response
//const String lineTest = "{\"forecast\":[{\"epochtime\":155... Snip. Sample-API-Response-here...}";
void setup() {
Serial.begin(115200);
Serial.println();
Serial.print("connecting to ");
Serial.println(WIFI_SSID);
WiFi.mode(WIFI_STA);
WiFi.begin(WIFI_SSID, WIFI_PWD);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
}
void loop() {
// Declaring Variables
String line;
int pingResult;
// Check WiFi Status
if (WiFi.status() == WL_CONNECTED) {
long rssi = WiFi.RSSI();
Serial.print("RSSI: ");
Serial.println(rssi);
Ping.ping("corrently.io");
int pingResult = Ping.averageTime();
Serial.print(pingResult);
Serial.println(" ms ping");
// Use WiFiClientSecure class to create TLS connection
WiFiClientSecure client;
Serial.print("connecting to ");
Serial.println(host);
Serial.printf("Using fingerprint '%s'\n", fingerprint);
client.setFingerprint(fingerprint);
if (!client.connect(host, httpsPort)) {
Serial.println("TLS connection failed");
return;
}
// get the data
String url = "/core/gsi?plz=97082";
//Serial.println("wait 10s to relax the API");
//delay(10000);
Serial.print("requesting URL: ");
Serial.println(url);
// disable for use of lineTEST
client.print(String("GET ") + url + " HTTP/1.1\r\n" +
"Host: " + host + "\r\n" +
"User-Agent: GSIDisplayTEST\r\n" +
"Connection: close\r\n\r\n");
//DEBUG!!!
Serial.print(String("GET ") + url + " HTTP/1.1\r\n" +
"Host: " + host + "\r\n" +
"User-Agent: GSIDisplayTEST\r\n" +
"Connection: close\r\n\r\n");
// "Connection: open\r\n\r\n");
delay(1000); //DEBUG!!!!!!!!!!!
Serial.println("request sent");
while (client.connected()) {
String line = client.readStringUntil('\n');
Serial.println(line); //DEBUG!!!!!!!!!!!!!!!!!!
if (line == "") {
Serial.println("empty Line");
}
if (line == "\r") {
Serial.println("headers received");
break;
}
/** mysteries of old code....
while (client.available()) {
String line = client.readStringUntil('\n');
Serial.println(line);
**/
}
String line = client.readStringUntil('\n');
//String line = lineTest; //TEST-debug
//check reply
if (line.startsWith("{\"forecast\":[{\"epochtime\"")) {
Serial.println("Request successfull!");
} else {
Serial.println("Request has failed");
}
Serial.println("reply was:");
Serial.println("==========");
Serial.println(line);
Serial.println("==========");
Serial.println("HTTPS GET done");
//client.stop();
//Check the returning code
if (line.length() > 0) {
// if (1 > 0) {
// Parsing
Serial.println("parsing...");
const size_t capacity = JSON_ARRAY_SIZE(48) + 2*JSON_OBJECT_SIZE(2) + 48*JSON_OBJECT_SIZE(7) + 5600;
//const size_t capacity = JSON_ARRAY_SIZE(48) + 2*JSON_OBJECT_SIZE(2) + 48*JSON_OBJECT_SIZE(7) + 5900;
DynamicJsonBuffer jsonBuffer(capacity);
//JSON Source:
JsonObject& root = jsonBuffer.parseObject(line);
JsonArray& forecast = root["forecast"];
JsonObject& forecast_0 = forecast[0];
long forecast_0_epochtime = forecast_0["epochtime"]; // 1551621600
int forecast_0_eevalue = forecast_0["eevalue"]; // 56
int forecast_0_ewind = forecast_0["ewind"]; // 56
int forecast_0_esolar = forecast_0["esolar"]; // 5
int forecast_0_gsi = forecast_0["gsi"]; // 56
long forecast_0_timeStamp = forecast_0["timeStamp"]; // 1551621600000
//float forecast_0_energyprice = forecast_0["energyprice"]; // "-0.0280000"
const char* forecast_0_energyprice = forecast_0["energyprice"]; // "-0.0280000"
//snipp
const char* location_city = root["location"]["city"]; // "Würzburg"
if (!root.success()) {
Serial.println("Parsing root failed");
//return;
}
if (!forecast.success()) {
Serial.println("Parsing forecast failed");
//return;
}
// Output to serial monitor
Serial.print("Location: ");
Serial.println(location_city);
//Serial.print("Vorhersage für: ");
//Serial.println(forecast_0_epochtime);
Serial.print("EE Value: ");
Serial.println(forecast_0_eevalue);
Serial.print("Energyprice: ");
Serial.println(forecast_0_energyprice);
}
}
// Delay
delay(60000);
}
/**
https://randomnerdtutorials.com/decoding-and-encoding-json-with-arduino-or-esp8266/
https://www.instructables.com/id/ESP8266-Parsing-JSON/
https://github.com/esp8266/Arduino/blob/master/libraries/ESP8266WiFi/examples/HTTPSRequest/HTTPSRequest.ino
#include <JsonListener.h>
*/
Have an nice day