losungepaper/http_grab.ino

78 lines
3.0 KiB
C++
Executable File

#include <HTTPClient.h>
String textBeginString = "<b>";
String textEndString = "</b><br>";
String sourceBeginString = textEndString; // because source begins where text ends
String sourceEndString = "</font></p>";
String getHTML(String url) {
String result = "";
if(WiFi.status() == WL_CONNECTED) {
HTTPClient http;
http.begin(url); // initialize the http instance
int httpCode = http.GET(); // get the page; httpCode will be negative on error
if(httpCode > 0) {
// HTTP header has been send and Server response header has been handled
Serial.printf("[HTTP] GET: %d\n", httpCode);
// file found at server
if(httpCode == HTTP_CODE_OK) {
result = http.getString();
}
} else {
Serial.printf("[HTTP] GET: %s\n", http.errorToString(httpCode).c_str());
}
http.end();
}
return result;
}
String getHTML() { // gets the date and year from time.h library
struct tm timeinfo;
char dayInMonth[3];
char month[3];
char year[5];
if(!getLocalTime(&timeinfo)){
Serial.println("Failed to obtain time");
return "";
}
strftime(dayInMonth,3, "%d", &timeinfo);
strftime(month,3, "%m", &timeinfo);
strftime(year,5, "%Y", &timeinfo);
return getHTML(String("https://www.losungen.de/fileadmin/media-losungen/heute/") + String(year) + String("/") + String(month) + String(dayInMonth) + String(".html"));
}
String getLosungFromHTML(String html) {
int losungBeginIndex = html.indexOf(textBeginString)+textBeginString.length();
int losungEndIndex = html.indexOf(textEndString);
return html.substring(losungBeginIndex, losungEndIndex);
}
String getLehrtextFromHTML(String html) {
String losung = getLosungFromHTML(html);
int losungIndex = html.indexOf(losung);
int lehrtextBeginIndex = html.indexOf(textBeginString, losungIndex)+textBeginString.length();
int lehrtextEndIndex = html.indexOf(textEndString, losungIndex+losung.length()+textEndString.length()); // calculating is needed for better performance and to get the second index, not the first
return html.substring(lehrtextBeginIndex, lehrtextEndIndex);
}
String getLosungSourceFromHTML(String html) { // get the source of losung in given html
int losungSourceBeginIndex = html.indexOf(sourceBeginString)+sourceBeginString.length();
int losungSourceEndIndex = html.indexOf(sourceEndString);
return html.substring(losungSourceBeginIndex, losungSourceEndIndex);
}
String getLehrtextSourceFromHTML(String html) { // get the source of losung in given html
String losungSource = getLosungSourceFromHTML(html);
int losungSourceIndex = html.indexOf(losungSource);
int lehrtextSourceBeginIndex = html.indexOf(sourceBeginString, losungSourceIndex)+sourceBeginString.length();
int lehrtextSourceEndIndex = html.indexOf(sourceEndString, losungSourceIndex+losungSource.length()+sourceEndString.length()); // calculating is needed for better performance and to get the second index, not the first
return html.substring(lehrtextSourceBeginIndex, lehrtextSourceEndIndex);
}