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adr8faqU9GY/rOPNk3sgrDQoo//fb4hVC1CLQJ13hef4Y53CI
rU7m2Ys6xt0nUW7/vGT1M0NPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV
HRMBAf8EBTADAQH/MB0GA1UdDgQWBBR5tFnme7bl5AFzgAiIyBpY9umbbjANBgkq
hkiG9w0BAQsFAAOCAgEAVR9YqbyyqFDQDLHYGmkgJykIrGF1XIpu+ILlaS/V9lZL
ubhzEFnTIZd+50xx+7LSYK05qAvqFyFWhfFQDlnrzuBZ6brJFe+GnY+EgPbk6ZGQ
3BebYhtF8GaV0nxvwuo77x/Py9auJ/GpsMiu/X1+mvoiBOv/2X/qkSsisRcOj/KK
NFtY2PwByVS5uCbMiogziUwthDyC3+6WVwW6LLv3xLfHTjuCvjHIInNzktHCgKQ5
ORAzI4JMPJ+GslWYHb4phowim57iaztXOoJwTdwJx4nLCgdNbOhdjsnvzqvHu7Ur
TkXWStAmzOVyyghqpZXjFaH3pO3JLF+l+/+sKAIuvtd7u+Nxe5AW0wdeRlN8NwdC
jNPElpzVmbUq4JUagEiuTDkHzsxHpFKVK7q4+63SM1N95R1NbdWhscdCb+ZAJzVc
oyi3B43njTOQ5yOf+1CceWxG1bQVs5ZufpsMljq4Ui0/1lvh+wjChP4kqKOJ2qxq
4RgqsahDYVvTH9w7jXbyLeiNdd8XM2w9U/t7y0Ff/9yi0GE44Za4rF2LN9d11TPA
mRGunUHBcnWEvgJBQl9nJEiU0Zsnvgc/ubhPgXRR4Xq37Z0j4r7g1SgEEzwxA57d
emyPxgcYxn/eR44/KJ4EBs+lVDR3veyJm+kXQ99b21/+jh5Xos1AnX5iItreGCc=
-----END CERTIFICATE-----
)EOF";


void mqtt_reconnect() 
{
// Loop until we’re reconnected - add here mechanism not to stop the script! - right now is bad! - maybe done in loop() already?
  while (!mqtt_client.connected()) 
  {
    Serial.printf("[%s]: Attempting MQTT connection…",__func__);
    // String clientId = CLIENT;
    // Attempt to connect
    if (mqtt_client.connect(mac_org_char, mqtt_username, mqtt_password)) 
    {
      // commands topic:
      char mqtt_topic[MAX_MQTT_TOPIC];
      snprintf(mqtt_topic, sizeof(mqtt_topic),"%s/+/+/cmd/#",CLIENT);
      Serial.println("\tconnected");
      mqtt_client.subscribe(mqtt_topic); 
      Serial.printf("[%s]: Subscribed to CMD topic: %s\n",__func__,mqtt_topic); 
      // // sensors topic:
      // snprintf(mqtt_topic, sizeof(mqtt_topic),"%s/+/+/sensors/#",CLIENT);
      // Serial.println("\tconnected");
      // mqtt_client.subscribe(mqtt_topic); 
      // Serial.printf("[%s]: Subscribed to SENSORS topic: %s\n",__func__,mqtt_topic); 

      WEBLOG("[%s]: MQTT (re)connected\n",__func__);
      mqtt_errors = 0;
    } else 
    {
      Serial.print("\tfailed, rc=");
      Serial.println(mqtt_client.state());
      WEBLOG("[%s]: MQTT NOT connected for %d times!\n",__func__,mqtt_errors);
      LOG0("[%s]: MQTT NOT connected for %d times!\n",__func__,mqtt_errors);
      ++mqtt_errors;
      if (mqtt_errors > MAX_MQTT_ERRORS)
      {
        do_restart_esp("MQTT not connected too many times - restarting");
      }
      return;
    }
  }
}

void mqtt_callback(char* topic, byte* payload, unsigned int length) 
{
  String incommingMessage = "";
  for (int i = 0; i < length; i++) 
  {
    incommingMessage+=(char)payload[i];
  }
  const char* mqtt_message = incommingMessage.c_str();
  #ifdef DEBUG
    Serial.printf("[%s]: Message arrived: topic=[%s], payload=[%s]\n",__func__,topic,mqtt_message);
    // Serial.printf("[%s]: Free heap=%u bytes\n",__func__,ESP.getFreeHeap());
  #endif

  // update 
  char mqtt_topic[MAX_MQTT_TOPIC];
  snprintf(mqtt_topic, sizeof(mqtt_topic),"%s/bridge/%s/cmd/update",CLIENT,HOSTNAME);
  if (strcmp(topic,mqtt_topic) == 0)
  {
    #ifdef DEBUG
      Serial.printf("[%s]: PROPER command received: %s\n",__func__,mqtt_message);
      Serial.println(topic); Serial.println(mqtt_topic); 
    #endif
    if ((atoi(mqtt_message)) == 1)
    {
      Serial.printf("[%s]: Update requested\n",__func__);
      if (publishMessage(mqtt_topic,"",true))
      {
        Serial.printf("[%s]: Calling FW update...\n",__func__);
        do_update();
      } else 
      {
        Serial.printf("[%s]: cannot clean MQTT - FW update cancelled\n",__func__);
      }
    }
  } 

  // restart
  snprintf(mqtt_topic, sizeof(mqtt_topic),"%s/bridge/%s/cmd/restart",CLIENT,HOSTNAME);
  if (strcmp(topic,mqtt_topic) == 0)
  {
    #ifdef DEBUG
      Serial.printf("[%s]: PROPER command received: %s\n",__func__,mqtt_message);
      Serial.println(topic); Serial.println(mqtt_topic); 
    #endif
    if ((atoi(mqtt_message)) == 1)
    {
      Serial.printf("[%s]: Restart requested\n",__func__);
      if (publishMessage(mqtt_topic,"",true))
      {
        Serial.printf("[%s]: Calling restart...\n",__func__);
        do_restart_esp("Restart on MQTT command");
      } else 
      {
        Serial.printf("[%s]: cannot clean MQTT - restart cancelled\n",__func__);
      }
    }
  } 


}

bool publishMessage(const char* topic, const char* payload , boolean retained)
{
  if (!mqtt_client.connected()) return false;
  if (mqtt_client.publish(topic, payload, true))
  {
    #ifdef DEBUG
      Serial.printf("[%s]: Message published: topic=[%s], payload=[%s]\n",__func__,topic,payload);
    #endif
    return true;
  } else 
  {
    #ifdef DEBUG
      Serial.printf("[%s]: Message NOT published: topic=[%s], payload=[%s]\n",__func__,topic,payload);
    #endif
    return false;
  }
}

#endif