// MQTT callback
void mqttCallback(char* topic, byte* payload, unsigned int length) {
  //Serial.print("Message arrived [");
  //Serial.print(topic);
  //Serial.println("] ");
  /*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, mqtt_allOnOffTopic) == 0) { //if topic = mqtt_allOnOffTopic
    Serial.print("received MQTT ");
    Serial.println(mqtt_allOnOffTopic);

    char tmpPayload[length + 1];

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

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

    if (strcmp(tmpPayload, "ON") == 0 || strcmp(tmpPayload, "On") == 0 || strcmp(tmpPayload, "on") == 0) {
      allRelaisOn();
    }
    else if (strcmp(tmpPayload, "OFF") == 0 || strcmp(tmpPayload, "Off") == 0 || strcmp(tmpPayload, "off") == 0) {
      allRelaisOff();
    }
  }//if topic = mqtt_allOnOffTopic

  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 (mqttclient.subscribe(mqtt_topic_in)) {
      Serial.println(mqtt_topic_in);
    }
    if (strlen(mqtt_allOnOffTopic) > 0) {
      if (mqttclient.subscribe(mqtt_allOnOffTopic)) {
        Serial.println(mqtt_allOnOffTopic);
      }
    }
    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
  }
}
