
// MQTT callback
void mqttCallback(char* topic, byte* payload, unsigned int length) {
//  Serial.print("Message arrived [");
//  Serial.print(topic);
//  Serial.print("] ");
//  for (int i = 0; i < length; i++) {
//    Serial.print((char)payload[i]);
//  }
//  Serial.println();

  if (strcmp(topic, mqtt_topic_in) == 0) { //if topic = mqtt_topic_in
    Serial.print("received MQTT ");
    Serial.println(mqtt_topic_in);

    for (int i = 0; i < length; i++) {
      cmdPayload[i] = (char)payload[i];
    }
    cmdPayload[length + 1] = '\0';

    Serial.print("cmdPayload:");
    Serial.println(cmdPayload);

    cmdInQueue = true;

  }//if topic = mqtt_topic_in

  if (strcmp(topic, outTemp_topic_in) == 0) { //if topic = outTemp_topic_in
    char inValue[length + 1];
    for (int i = 0; i < length; i++) {
      inValue[i] = (char)payload[i];
    }
    inValue[sizeof(inValue) - 1] = '\0';
    //Serial.print(inValue);
    //Serial.println();
    float invalueFloat = atof(inValue);
    outTemp = invalueFloat;
    outTempHumLastUpdate = millis();
    Serial.print("atemp=");
    Serial.println(invalueFloat);
  }//if topic = outTemp_topic_in

  if (strcmp(topic, outHum_topic_in) == 0) { //if topic = outHum_topic_in
    char inValue[length + 1];
    for (int i = 0; i < length; i++) {
      inValue[i] = (char)payload[i];
    }
    inValue[sizeof(inValue) - 1] = '\0';
    //Serial.print(inValue);
    //Serial.println();
    outHum = atoi(inValue);
    outTempHumLastUpdate = millis();
    Serial.print("ahum=");
    Serial.println(inValue);
  }//if topic = outHum_topic_in

  if (strcmp(topic, domoticz_out_topic) == 0) { //if topic = domoticz_out_topic
    Serial.print("received MQTT ");
    Serial.println(domoticz_out_topic);
    if ( !domoticzOutParserBusy ) {
      for (int i = 0; i < length; i++) {
        domoticzOutPayload[i] = (char)payload[i];
      }
      domoticzOutPayload[length + 1] = '\0';
      domoticzOutParseData = true; // parse domoticz data in the next loop()
    }
  }//if topic = domoticz_out_topic
}//mqttCallback

void mqttPrepareConnection() {
  Serial.print("MQTT connection with ");
  if (strlen(mqtt_user) > 0 && strlen(mqtt_willTopic) == 0) {
    // user and password, no Last Will
    Serial.println("user and password, no Last Will");
    mqttMode = 2;
  }
  else if (strlen(mqtt_user) > 0 && strlen(mqtt_willTopic) > 0) {
    // user, password and Last Will
    Serial.println("user, password and Last Will");
    mqttMode = 3;
  }
  else if (strlen(mqtt_user) == 0 && strlen(mqtt_willTopic) > 0) {
    // Last Will but no user and password
    Serial.println("Last Will but no user and password");
    mqttMode = 4;
  }
  else {
    // no user, password and no Last Will
    Serial.println("no user, password and no Last Will");
    mqttMode = 1;
  }
}

boolean mqttReconnect() {
  // Create a random MQTT client ID
  String mqttClientId = "ESP8266Client-";
  mqttClientId += String(random(0xffff), HEX);

  Serial.print("MQTT connection with ");

  boolean connRes;

  switch (mqttMode) {
    case 1:
      Serial.println("no user, password and no Last Will");
      connRes = mqttclient.connect(mqttClientId.c_str());
      break;
    case 2:
      Serial.println("user and password, no Last Will");
      connRes = mqttclient.connect(mqttClientId.c_str(), mqtt_user, mqtt_pass);
      break;
    case 3:
      Serial.println("user, password and Last Will");
      connRes = mqttclient.connect(mqttClientId.c_str(), mqtt_user, mqtt_pass, mqtt_willTopic, mqtt_willQos, mqtt_willRetain, mqtt_willMsg);
      break;
    case 4:
      Serial.println("Last Will, no user and password");
      connRes = mqttclient.connect(mqttClientId.c_str(), mqtt_willTopic, mqtt_willQos, mqtt_willRetain, mqtt_willMsg);
      break;
  }

  if (connRes) {
    Serial.print("MQTT connected. Reconnects: ");
    Serial.println(mqttReconnects);
    mqttReconnects++;

    // Once connected, publish an announcement...
    //    char outMsg[30];
    //    sprintf(outMsg, "connected, %d reconnects", mqttReconnects);
    //    mqttclient.publish(mqtt_topic_out, outMsg, mqtt_outRetain);
    publishStatus();
    //mqttclient.publish(mqtt_topic_out, "connected");
    // ... and resubscribe
    Serial.println("Subscribed to:");
    if (strlen(mqtt_topic_in) > 0) {
      if (mqttclient.subscribe(mqtt_topic_in)) {
        Serial.println(mqtt_topic_in);
      }
    }
    if (strlen(outTemp_topic_in) > 0) {
      if (mqttclient.subscribe(outTemp_topic_in)) {
        Serial.println(outTemp_topic_in);
      }
    }
    if (strlen(outHum_topic_in) > 0) {
      if (mqttclient.subscribe(outHum_topic_in)) {
        Serial.println(outHum_topic_in);
      }
    }
    if (useDomoticz && strlen(domoticz_out_topic) > 0) {
      if (mqttclient.subscribe(domoticz_out_topic)) {
        Serial.println(domoticz_out_topic);
      }
    }
  }
  return mqttclient.connected();
} //mqttReconnect



void mqttClientInit() {
  mqttclient.setServer(mqtt_server, mqtt_port);
  mqttclient.setCallback(mqttCallback);
  mqttLastReconnectAttempt = 0;
}

void mqttHandleConnection() {
  if ( WiFi.status() == WL_CONNECTED ) {
    // MQTT reconnect if not connected (nonblocking)
    if (!mqttclient.connected()) {
      long now = millis();

      if (now - mqttLastReconnectAttempt > 5000) {
        mqttLastReconnectAttempt = now;
        if (mqttReconnect()) { // Attempt to reconnect
          mqttLastReconnectAttempt = 0;
        }
      }
    } else { // Client connected
      mqttclient.loop();
    }//else
  }
}

void publishStatus() {
  char outMsg[60];
  long upTime = millis() / 1000;
  sprintf(outMsg, "connected, reconnects: %d, uptime: %d, free heap: %d", mqttReconnects - 1, upTime, ESP.getFreeHeap());
  mqttclient.publish(mqtt_topic_out, outMsg, mqtt_outRetain);
}

void sendStatus(char* payload) {
  char buf[101];
  strlcpy(buf, payload, 101);
  Serial.println(buf);
  if (mqttclient.connected()) mqttclient.publish(mqtt_topic_out, buf, mqtt_outRetain);
}

void publishCurrentThermostatValues() {
  char tmp_topic_out[50];

  float curr_setTemp;
  if (heatingMode == 1) curr_setTemp = setTemp;
  else if (heatingMode == 2) curr_setTemp = setTempLow;

  char setTemp_chararr[6];
  char currSetTemp_chararr[6];

  dtostrf(setTemp, 1, 1, setTemp_chararr );
  dtostrf(curr_setTemp, 1, 1, currSetTemp_chararr );

  Serial.print("heatingMode: '");
  Serial.print(heatingMode);
  Serial.println("'");
  Serial.print("set temp: '");
  Serial.print(setTemp_chararr);
  Serial.println("'");
  Serial.print("current set temp: '");
  Serial.print(currSetTemp_chararr);
  Serial.println("'");

  sprintf(tmp_topic_out, "%s/%s", mqtt_topic_out, "setTemp");
  mqttclient.publish(tmp_topic_out, setTemp_chararr);

  sprintf(tmp_topic_out, "%s/%s", mqtt_topic_out, "currSetTemp");
  mqttclient.publish(tmp_topic_out, currSetTemp_chararr);

  sprintf(tmp_topic_out, "%s/%s", mqtt_topic_out, "heatingMode");
  char heatingMode_chararr[3];
  sprintf(heatingMode_chararr, "%d", heatingMode);
  mqttclient.publish(tmp_topic_out, heatingMode_chararr);

  char turnHeatingOn_char[5];
  if (turnHeatingOn) strcpy(turnHeatingOn_char, "on");
  else strcpy(turnHeatingOn_char, "off");
  sprintf(tmp_topic_out, "%s/%s", mqtt_topic_out, "heating");
  mqttclient.publish(tmp_topic_out, turnHeatingOn_char);

  char buf[101];
  sprintf(buf, "%d", heatingOnTime);
  sprintf(tmp_topic_out, "%s/%s", mqtt_topic_out, "heatingOnTime");
  mqttclient.publish(tmp_topic_out, buf);

  sprintf(buf, "%d", heatingOffTime);
  sprintf(tmp_topic_out, "%s/%s", mqtt_topic_out, "heatingOffTime");
  mqttclient.publish(tmp_topic_out, buf);
}

void publishCurrentSensorValues() {
  if ( lastTempUpdate != 0 && (millis() - lastTempUpdate) < 120000 ) {
    char tmp_topic_out[50];

    char temp_chararr[6];
    char hum_chararr[4];
    dtostrf(temperature, 1, 1, temp_chararr );
    sprintf(hum_chararr, "%2i", humidity);

    Serial.print("temp: '");
    Serial.print(temp_chararr);
    Serial.println("'");
    sprintf(tmp_topic_out, "%s/%s", mqtt_topic_out, "temp");
    mqttclient.publish(tmp_topic_out, temp_chararr);

    Serial.print("humidity: '");
    Serial.print(humidity);
    Serial.println("'");
    sprintf(tmp_topic_out, "%s/%s", mqtt_topic_out, "hum");
    mqttclient.publish(tmp_topic_out, hum_chararr);
  }
}

