Im tearing my hair over this code and hope you can shine some light on it
I have a String containing some http code; payload. Now I want to extract some specific data in that string but no matter how I try I cant wrap my head around the functions of String.
The data I want to extract is the temperature found in this specific code: <span id="tempC1">24.75</span>
Now this is what I have made so far but Its problematic.
String payload = "{}"; //String that contain HTLM
String searchThis = "tempC1"; // what to search for to find the data
String cutout = ""; //string that I want to contain the temperature
if (httpResponseCode>0) {
Serial.print("HTTP Response code: ");
Serial.println(httpResponseCode);
payload = http.getString();
cutout = payload.substring(payload.indexOf(searchThis), payload.indexOf(searchThis)+5);payload.indexOf(payload));
Serial.println(cutout);
}
Start from less difficult example.
Remove all HTML related parts from the code, work with Strins only:
String payload = "<span id=\"tempC1\">24.75</span>";
String searchThis = "tempC1"; // what to search for to find the data
String cutout; //string that I want to contain the temperature
cutout = payload.substring(payload.indexOf(searchThis),payload.indexOf(searchThis)+5);
payload.indexOf(payload); // <<<< what is purpose of this string?
Serial.println(cutout);
Run this code and show< what you see in the Serial
By the way - what is purpose of the last line of the code before Serial.print statement?
String httpGETRequest(const char* serverName) {
WiFiClient client;
HTTPClient http;
// Your IP address with path or Domain name with URL path
http.begin(client, serverName);
// If you need Node-RED/server authentication, insert user and password below
//http.setAuthorization("REPLACE_WITH_SERVER_USERNAME", "REPLACE_WITH_SERVER_PASSWORD");
// Send HTTP POST request
int httpResponseCode = http.GET();
String payload = "{}"; //String that contain HTLM
String searchThis = "tempC1"; // what to search for to find the data
String cutout = ""; //string that I want to contain the temperature
String index = "";
if (httpResponseCode>0) {
Serial.print("HTTP Response code: ");
Serial.println(httpResponseCode);
//payload = http.getString();
String payload = "<span id=\"tempC1\">24.75</span>";
cutout = payload.substring(payload.indexOf(searchThis),payload.indexOf(searchThis)+5);
index = payload.indexOf(searchThis);
Serial.println(cutout);
Serial.println(payload);
Serial.println(index);
}
else {
Serial.print("Error code: ");
Serial.println(httpResponseCode);
}
// Free resources
http.end();
return cutout;
}
And what is problem with it?
It seems to be a correct output of your code.
To output the temperature value instead of field name you need to add an offset to the substring() parameters to shift the substring window to the part of the responce where the value is situated