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

#define MSG_BUFFER_SIZE  (50)

const char* mqtt_server = "test.mosquitto.org";

unsigned long lastMsg = 0;
unsigned int tamanho = 4;

WiFiClient espClient;
PubSubClient client(espClient);

void reconnect() {

  while (!client.connected()) {

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

    String clientId = "zerocool";
    clientId += String(random(0xffff), HEX);

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

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

    } 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);

}

void loop() {

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

  unsigned long now = millis();

  if (now - lastMsg > 5000) {

    lastMsg = now;

    int v1 = analogRead(32);
    int v2 = analogRead(33);
    int v3 = analogRead(34);
    int v4 = analogRead(35);

    char A0[5], A1[5], A2[5], A3[5];

    sprintf (A0, "%d", v1);
    Serial.print("A0: ");
    Serial.println(A0);
    client.publish("node00/a0", A0, true);

    sprintf (A1, "%d", v2);
    Serial.print("A1: ");
    Serial.println(A1);
    client.publish("node00/a1", A1, true);

    sprintf (A2, "%d", v3);
    Serial.print("A2: ");
    Serial.println(A2);
    client.publish("node00/a2", A2, true);

    sprintf (A3, "%d", v4);
    Serial.print("A3: ");
    Serial.println(A3);
    client.publish("node00/a3", A3, true);

    Serial.println("");

  }
}