Files
Arduino-GSM-Chata/lib/Device/WebServer.cpp
T
Ondrej Trochta 0caeec996e test chata
2024-09-26 20:58:31 +02:00

137 lines
3.1 KiB
C++

/*#include <Arduino.h>
#include <Ethernet.h>
#include "WebServer.h"
#include "WebServerData.h"
#include "DebugLog.h"
// Constructor
WebServer::WebServer() : _server(80) {}
WebServer::WebServer(byte mac[6], IPAddress ip, uint16_t port) : _ip(ip), _server(port)
{
memcpy(_mac, mac, 6);
}
// Initialize the Ethernet and start the server
void WebServer::init()
{
Ethernet.begin(_mac, _ip);
#ifdef DEBUG
DebugLog::log("Ethernet IP: " + Ethernet.localIP());
#endif
_server.begin();
#ifdef DEBUG
DebugLog::log("Server Start");
#endif
}
// Move the declaration of EthernetClient inside the WebServer class
EthernetClient client;
// Handle client requests
WebServerData WebServer::getWebServerData()
{
// Check if a client has connected
client = _server.available();
if (client)
{
if (client.connected())
{
#ifdef DEBUG
DebugLog::log("Client connected");
#endif
unsigned long startTime = millis();
while (client.available() == 0)
{
if (millis() - startTime >= 10000)
{
break;
}
delay(10);
}
client.println(F("HTTP/1.1 200 OK")); // Respond together with the Web page in the HTML
client.println(F("Content-Type: text/html"));
client.println(F("Connection: close"));
client.println();
String request = client.readStringUntil('\r');
if (request.startsWith("GET / HTTP/1.1"))
{
#ifdef DEBUG
DebugLog::log("EMPTY DATA: " + request);
#endif
return WebServerData();
}
// client.flush(); // Clear the incoming buffer after reading the GET request
// If you've gotten to the end of the line (received a newline
// character) and the line is blank, the http request has ended,
// so you can send a reply
if (request.startsWith("GET /"))
{
#ifdef DEBUG
DebugLog::log("GET WEB SERVER DATA: " + request);
#endif
WebServerData webServerData = WebServerData(request);
return webServerData;
}
}
}
return WebServerData();
// Give the web browser time to receive the data
}
// Return a default-constructed WebServerData object if no client is available
void WebServer::endServer()
{
if (_server.available())
{
delay(10);
// Close the connection
client.stop();
}
}
void WebServer::SendToBrowser(const String &dataString)
{
const byte chunkSize = 50;
// Send data in chunks
unsigned int stringIndex = 0;
unsigned long startTime = millis();
while (stringIndex < dataString.length())
{
if (client.availableForWrite() > 0)
{
int chunkLength = min(chunkSize, dataString.length() - stringIndex);
const String chunk = dataString.substring(stringIndex, stringIndex + chunkLength);
// Send the chunk (consider error handling)
#ifdef DEBUG
DebugLog::log("StBC: " + chunk);
#endif
client.print(chunk);
stringIndex += chunkLength;
delay(5); // Optional delay between chunks
}
else if (millis() - startTime >= 10000)
{
return; // Timeout
}
delay(5); // Optional delay between chunks
}
client.println("");
}
*/