smartPOC-tx/src/dwd.cpp
2025-03-30 15:15:54 +02:00

121 lines
3.3 KiB
C++

#include "dwd.h"
String emptyDWDResponse = "Es sind keine Warnungen";
DWDClient::DWDClient(WiFiClient *client)
{
_client = client;
}
void DWDClient::begin(int intervalMinutes, String region)
{
this->rssUrl = "https://wettwarn.de/rss/";
this->rssUrl.concat(region);
this->rssUrl.concat(".rss");
this->checkInterval = 60e3 * intervalMinutes;
Serial.printf("[DWD]: check Interval : %dms\n", this->checkInterval);
this->check();
}
void DWDClient::loop()
{
if (millis() - this->lastCheck >= this->checkInterval)
{
this->lastCheck = millis();
this->check();
}
}
bool DWDClient::isDirty()
{
if (this->_dirty)
{
this->_dirty = false;
return true;
}
return false;
}
void DWDClient::check()
{
Serial.println("[DWD]: checking " + this->rssUrl);
this->_http.begin(this->rssUrl);
int httpCode = this->_http.GET();
if (httpCode > 0)
{
this->rssData = this->_http.getString();
if (this->rssData.length() == 0)
{
Serial.println("Error: Empty RSS feed response!");
return;
}
this->currentMessage = this->parseRSS(this->rssData);
Serial.println("[DWD]: Current Message = " + this->currentMessage);
if (this->currentMessage.equals(this->lastMessage) == false)
{
if (this->currentMessage.indexOf(emptyDWDResponse) == -1) {
this->_dirty = true;
}
this->lastMessage = this->currentMessage;
}
}
else
{
Serial.printf("HTTP request failed, error: %s\n", this->_http.errorToString(httpCode).c_str());
}
this->_http.end();
}
String DWDClient::parseRSS(String xmlData)
{
int itemStart = 0, itemEnd = 0;
while ((itemStart = xmlData.indexOf("<item>", itemEnd)) != -1)
{
itemEnd = xmlData.indexOf("</item>", itemStart);
if (itemEnd == -1)
break;
String itemData = xmlData.substring(itemStart, itemEnd); // Extract the <item> block
// Extract Description (with CDATA)
// static String descriptionTag = ;
String description = this->extractTagContent(itemData, "description");
description.replace("DWD UNWETTERWARNUNG:", "DWD:");
description.replace("DWD WETTERWARNUNG:", "DWD:");
description.replace(" in ", " ");
description.replace(" von ", "/");
int pos = description.indexOf("Quelle:");
if (pos > -1)
{
description = description.substring(0, pos); // Truncate at "Quelle:"
}
return description;
}
return emptyString;
}
String DWDClient::extractTagContent(String source, String tag)
{
int start = source.indexOf("<" + tag + ">");
int end = source.indexOf("</" + tag + ">", start);
if (start == -1 || end == -1)
return "Not Found";
String content = source.substring(start + tag.length() + 2, end);
// Handle CDATA safely
int cdataStart = content.indexOf("<![CDATA[");
int cdataEnd = content.indexOf("]]>", cdataStart);
if (cdataStart != -1 && cdataEnd != -1 && cdataEnd > cdataStart)
{
content = content.substring(cdataStart + 9, cdataEnd); // Extract CDATA content
}
content.replace("<br />", " ");
content.replace("\n", " ");
return content;
}