#define MQTT

#include "grafik.h"
#include "main.h"
#include "weifi.h"
#include "interpolation.h"
#include "mqtt.h"


JsonDocument doc;

//-----------------------------------------
// MQTT message arrives
void onmessage(char *tp, byte *msg, unsigned int length)
{
  String topic = String(tp);
  msg[length] = '\0';
  String message = String((char *)(msg));
  Serial.printf("Message arrived: %s %s\n", topic.c_str(), message.c_str());
  DeserializationError error = deserializeJson(doc, message);
  if (error) {
    Serial.print(F("deserializeJson() failed: "));
    Serial.println(error.c_str());
    return;
  }
  bool istemp = true;
  float val = 0.0;

  if (topic == "CYD/set/hm/aussen") {
    if(doc.containsKey("temperature")) {
      istemp = true;
      val = doc["temperature"];
    }
    if(doc.containsKey("humidity")) {
      istemp = false;
      val = doc["humidity"];
    }
    setAussenDataValues(val, istemp, timeinfo);
  } else if (topic ==  "CYD/set/parameter") {
    if(doc.containsKey("bmerate")) {
      setBMEreadtime(doc["bmerate"]);
//      showRate(doc["bmerate"]);
    }
    if(doc.containsKey("updaterate")) {
      setBMEreadtime(doc["updaterate"]);
//      showRate(doc["updaterate"]);
    }
    if(doc.containsKey("tempoffset")) {
      tempOffset = (float)doc["tempoffset"];
    }
    if(doc.containsKey("humoffset")) {
      humOffset = (float)doc["humoffset"];
    }
    Serial.printf("tempoffset: %.1f,  humoffset: %.1f\n",tempOffset, humOffset);    
  }
}

// Connect or reconnect to MQTT and subscribe
void reconnect(void)
{
  while (!client.connected())
  {
    Serial.print("Reconnecting...");
    char * chipID = getChipID();
    bool erg = client.connect(chipID, MQTT_USER, MQTT_PASSWD);
    Serial.println(erg);

    if (!client.connect(chipID, MQTT_USER, MQTT_PASSWD))
    {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" retrying in 5 seconds");
      delay(5000);
    }
  }
  Serial.println("Connected");
  client.subscribe(MQTT_TOPIC "#");
}

void doPublish(float temp, float hum, float tm, float hm) {
    char payload[80];
    sprintf(payload, "{\"temperature\":%.1f,\"tempmess\":%.1f,\"humidity\":%.1f,\"hummess\":%.1f}", temp, tm, hum, hm);
    char * chipID = getChipID();
    char topic[50];
    sprintf(topic, "CYD/get/%s/bme280", chipID);
    client.publish(topic, payload);
    Serial.printf("Published: %s %s\n", MQTT_PUB_TEMP, payload);
}


// check MQTT in the loop
void checkMQTT(void) {
  if (!client.connected())
  {
    
    Serial.println("try to reconnect");
    reconnect();
  }
  client.loop();
}


// Setup MQTT client
void setup_mqtt(void) {
  Serial.printf("Setup MQTT to broker %s ...\n", MQTT_BROKER);
  client.setClient(espClient);
  client.setServer(MQTT_BROKER, MQTT_PORT);
  client.setCallback(onmessage);
}

