// Code to connect to the KA-WLAN and download UTF-8 file with API request
// Libraries used
#include <WiFi.h> // Library to connect to the internet via WiFi
#include <Arduino.h> // Library to work with the ESP32 as an arduino
#include <HTTPClient.h> // Library for API requests
// Constants
const char* ssid = "Wokwi-GUEST"; // Name of the network
const char* password = ""; // Password of the network
const char *apiEndpoint = "https://raumzeit.hka-iwi.de/api/v1/timetables/room/E-201?reload=t"; // API endpoint for room E-201
const char *authHeaderName = "X-API-Key";
const char *apiKey = "ghu438$Q#BJ!";
// Function to connect to the WiFi network that you want to use
void connectToWiFi(){
Serial.print("Connecting to the WiFi network: ");
Serial.print(ssid);
WiFi.begin(ssid, password); // Used to connect to the network that you want to use
// Prints a dot while the ESP32 is not connected to the network
while(WiFi.status()!=WL_CONNECTED){
Serial.print(".");
delay(500);
}
Serial.println("\nConnected to the WiFi network");
Serial.print("IP Adress: ");
Serial.println(WiFi.localIP());
}
// Login to the captive portal of KA -Wlan
void captiveLogin(){
HTTPClient http;
http.begin("https://cph.ka-wlan.de/login");
http.addHeader("Content-Type", "application/x-www-form-urlencoded");
Serial.println(WiFi.macAddress());
int httpCode = http.POST("dst=&popup=false&username=" + WiFi.macAddress() + "&password=wSwb8w096");
if (httpCode != 200){
Serial.println("Failed");
}
else{
Serial.println("Connected");
}
delay(3000);
}
void downloadSchedule(){
HTTPClient http;
http.begin(apiEndpoint);
http.addHeader(authHeaderName, apiKey);
int httpCode = http.GET();
String payload = http.getString();
Serial.println(payload);
if (httpCode > 0) {
Serial.printf("[HTTP] GET... code: %d\n", httpCode);
if (httpCode == HTTP_CODE_OK) {
String payload = http.getString();
Serial.println(payload);
}
} else {
Serial.printf("[HTTP] GET... failed, error: %s\n", http.errorToString(httpCode).c_str());
}
delay(3000);
}
void setup(){
Serial.begin(115200); // Baud rate used
delay(3000);
connectToWiFi(); // Setup to connect to WiFi network
delay(5000);
captiveLogin();
delay(10000);
if((WiFi.status() == WL_CONNECTED)){
downloadSchedule();
}
else{
Serial.println("Connection lost");
}
}
void loop(){
}