/*
   Código demonstrativo para a aula de Sistemas Embarcados,
   Curso de Ciência da Computação e Engenharia da Computação
   EEP.
*/

#include <WiFi.h>
#include <PubSubClient.h>

const char* ssid = "Wokwi-GUEST";
const char* password = "";
const char* mqtt_server = "test.mosquitto.org";

char a0[20];
char a1[20];
char a2[20];
char a3[20];

WiFiClient espClient;
PubSubClient client(espClient);

void callback(char* topic, byte* payload, unsigned int length) {

  // Serial.print("Mensagem recebida no topico: ");

  Serial.print(topic);
  Serial.print(" : ");

  char payloadString[length + 1];

  //Serial.print("Mensagem:");

  for (int i = 0; i < length; i++) {
    payloadString[i] = (char)payload[i];

    // Serial.print((char)payload[i]); // Recebe caracter por caracter.

  }

  payloadString[length] = '\0'; // Contém todos os caracteres recebidos.
  //Serial.println(payloadString);

  if (strcmp(topic, "node00/a0") == 0) {
    sprintf(a0, "%s", payloadString);
    Serial.println(a0);
  }
  if (strcmp(topic, "node00/a1") == 0) {
    sprintf(a1, "%s", payloadString);
    Serial.println(a1);
  }
  if (strcmp(topic, "node00/a2") == 0) {
    sprintf(a2, "%s", payloadString);
    Serial.println(a2);
  }
  if (strcmp(topic, "node00/a3") == 0) {
    sprintf(a3, "%s", payloadString);
    Serial.println(a3);
  }

}

void reconnect() {

  //client.setKeepAlive(60); // Mantém a sessao aberta por 60 segundos.

  while (!client.connected()) {

    Serial.print("");
    Serial.print("Tentativa de conexao com servidor MQTT: ");

    String clientId = "mqtt-explorer-584bcd18";
    clientId += String(random(0xffff), HEX);

    if (client.connect(clientId.c_str())) {

      Serial.println("Conectado.");
      Serial.print("");

      client.subscribe("node00/a0");
      client.subscribe("node00/a1");
      client.subscribe("node00/a2");
      client.subscribe("node00/a3");

    } else {

      Serial.print("Falhou, Status=");
      Serial.print(client.state());
      Serial.println(" Nova tentativa em 5 segundos.");
      delay(1000);

    }

  }
}

void setup() {

  Serial.begin(115200);

  while (!Serial)    {     }

  WiFi.begin("Wokwi-GUEST", "");

  while (WiFi.status() != WL_CONNECTED) {
    delay(250);
  }

  Serial.println("-----------------------------------------------");
  Serial.print("Endereco IP: ");
  Serial.println(WiFi.localIP());
  Serial.println("-----------------------------------------------");

  delay(1000);

  client.setServer(mqtt_server, 1883);
  client.setCallback(callback);

}

void loop() {

  if (!client.connected()) {
    reconnect();
  }
  client.loop();
}