// 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 ( useDomoticz ) {
  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()
    }
  }
  //}


}//mqttCallback

int mqttReconnects=0;

boolean mqttReconnect() {
  // Create a random MQTT client ID
  String mqttClientId = "ESP8266Client-";
  mqttClientId += String(random(0xffff), HEX);
  boolean connRes;
  Serial.print("MQTT connection with ");
  if (strlen(mqtt_user) > 0 && strlen(mqtt_willTopic) == 0) {
    // user and password, no Last Will
    // boolean connect(const char* id, const char* user, const char* pass);
    connRes = mqttclient.connect(mqttClientId.c_str(), mqtt_user, mqtt_pass);
    Serial.println("user and password, no Last Will");
  }
  else if (strlen(mqtt_user) > 0 && strlen(mqtt_willTopic) > 0) {
    // user, password and Last Will
    // boolean connect(const char* id, const char* user, const char* pass, const char* willTopic, uint8_t willQos, boolean willRetain, const char* willMessage);
    connRes = mqttclient.connect(mqttClientId.c_str(), mqtt_user, mqtt_pass, mqtt_willTopic, mqtt_willQos, mqtt_willRetain, mqtt_willMsg);
    Serial.println("user, password and Last Will");
  }
  else if (strlen(mqtt_user) == 0 && strlen(mqtt_willTopic) > 0) {
    // Last Will but no user and password
    // boolean connect(const char* id, const char* willTopic, uint8_t willQos, boolean willRetain, const char* willMessage);
    connRes = mqttclient.connect(mqttClientId.c_str(), mqtt_willTopic, mqtt_willQos, mqtt_willRetain, mqtt_willMsg);
    Serial.println("Last Will but no user and password");
  }
  else {
    // no user, password and no Last Will
    Serial.println("no user, password and no Last Will");
    connRes = mqttclient.connect(mqttClientId.c_str());
  }


  if (connRes) {
    Serial.print("MQTT connected. Reconnects: ");
    Serial.println(mqttReconnects);
    
    // Once connected, publish an announcement...
    char outMsg[30];
    sprintf(outMsg, "connected, %d reconnects", mqttReconnects);
    mqttclient.publish(mqtt_topic_out, outMsg);
    //mqttclient.publish(mqtt_topic_out, "connected");
    // ... and resubscribe
    Serial.println("Subscribed to:");
    if (mqttclient.subscribe(mqtt_topic_in)) {
      Serial.println(mqtt_topic_in);
    }
    if (useDomoticz && strlen(domoticz_out_topic) > 0) {
      if (mqttclient.subscribe(domoticz_out_topic)) {
        Serial.println(domoticz_out_topic);
      }
    }
  }
  mqttReconnects++;
  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
  }
}
