// 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

    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
      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


boolean mqttReconnect() {
  // Create a random MQTT client ID
  String mqttClientId = "ESP8266Client-";
  mqttClientId += String(random(0xffff), HEX);
  if (mqttclient.connect(mqttClientId.c_str())) {
    Serial.println("MQTT connected");
    // Once connected, publish an announcement...
    mqttclient.publish(mqtt_topic_out, "connected");
    // ... and resubscribe
    mqttclient.subscribe(mqtt_topic_in);
    mqttclient.subscribe(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
  }
}
