/**************************************************
  Beispiel: ThingSpeak MKR ENV
***************************************************/

//-----------------------------------------------------------
#include <WiFi.h>
#include <ThingSpeak.h>

//-----------------------------------------------------------
// WiFi:
const char WIFI_SSID[] = "Wokwi-GUEST";
const char WIFI_PASSWORD[] = "";

WiFiClient wifinetwork;

//-----------------------------------------------------------
// ThingSpeak:
const unsigned long THINGSPEAK_CHANNEL_ID = 855942;
const char THINGSPEAK_WRITEAPP_KEY[] = "4AXZC21NB90EPKB1";

String myStatus = "Device switched on";

//-----------------------------------------------------------
void setup() {
  //---
  // UART starten (115200 Baud)
  Serial.begin(115200);

  //---
  // WiFi verbinden
  WiFi.begin(WIFI_SSID, WIFI_PASSWORD, 6);
  Serial.print("Verbinde mit ");
  Serial.print(WIFI_SSID);

  // Warten bis mit WiFi verbunden...
  while (WiFi.status() != WL_CONNECTED) {
    Serial.print(".");
    delay(250);
  }
  Serial.println(" Verbunden!");

  //---
  ThingSpeak.begin(wifinetwork);
}

//-----------------------------------------------------------
void loop() {
  //---
  float temperature = random(0, 100);
  float humidity    = random(0, 100);
  float pressure    = random(0, 100);
  float illuminance = random(0, 100);
  float uva         = random(0, 100);
  float uvb         = random(0, 100);
  float uvIndex     = random(0, 100);

  //---
  // set the fields with the values
  ThingSpeak.setField(1, temperature);
  ThingSpeak.setField(2, humidity);
  ThingSpeak.setField(3, pressure);
  ThingSpeak.setField(4, illuminance);
  ThingSpeak.setField(5, uva);
  ThingSpeak.setField(6, uvb);
  ThingSpeak.setField(7, uvIndex);

  // set the status
  ThingSpeak.setStatus(myStatus);

  //---
  // write to the ThingSpeak channel
  int x = ThingSpeak.writeFields(THINGSPEAK_CHANNEL_ID, THINGSPEAK_WRITEAPP_KEY);
  if (x == 200) {
    Serial.println("Channel update successful.");
  }
  else {
    Serial.println("Problem updating channel. HTTP error code " + String(x));
  }

  //---
  delay(20000); // Wait 20 seconds to update the channel again
  myStatus = "Device is running";

  // delay() nur nötig für bessere Simulatorleistung!!!
  // Beim realen ESP32 diesen delay() entfernen!!!
  delay(10);
}