// 
// UDPIO.cpp
// 

#include "Globals.h"
#include "EnergySensor.h"
#include "Relais.h"
#include "UDPIO.h"

uint8_t UDPIOClass::begin(const IPAddress remoteIP, const uint16_t remotePort, const uint16_t subscriberPort) {
  return UrsUdpSerial::begin(remoteIP, remotePort, subscriberPort);
}

void UDPIOClass::handle() {
  EnergyData x;
  int c = read();

  if (c > -1) {
    switch (c) {
    case 'q': //TEST: testweise disconnect für UrsWiFi
      println(F("ok:q"));
      WiFi.disconnect();
      break;
    case 'c':
      println(F("ok:c"));
      EnergySensor.reset();
      break;
    case '1':
      println(F("ok:1"));
      Relais.setState(RelaisState::on);
      break;
    case '0':
      println(F("ok:0"));
      Relais.setState(RelaisState::off);
      break;
    case 'x':
      println(F("ok:x"));
      print(F("data:"));
      print(EnergySensor.getLastReading().toString()); // Energie-Messwerte
      println(Relais.isOn() ? ";on" : ";off"); // Relais
      break;
    case 'r':
      println(F("ok:r"));
      raiseEvent(EventType::Reboot);
      delay(100);
      ESP.restart();
    case 'i':
      println(F("ok:i"));
      print(F("IP:"));
      println(WiFi.localIP());
      break;
    case 'd': // Daten-Log einschalten
      println(F("ok:d"));
      DataLog = true;
      break;
    case 'o': // Daten-Log aussschalten
      println(F("ok:o"));
      DataLog = false;
      break;
    default:
      print("got: "); println((char)c);
      break;
    }

    xmit();
    flush();
  }
} // handle;

void UDPIOClass::raiseEvent(EventType event) {
  switch (event) {
  case EventType::On:
    println(F("event:On"));
    break;
  case EventType::Off:
    println(F("event:Off"));
    break;
  case EventType::Reset:
    println(F("event:Reset"));
    break;
  case EventType::Reboot:
    println(F("event:Reboot"));
    break;
  case EventType::Restart:
    println(F("event:Restart"));
    break;
  default:
    break;
  }
} // raiseEvent
UDPIOClass UDPIO;

