// Bibliotecas
#include <EspMQTTClient.h> // EspMQTTClient
#include <ArduinoJson.h> // ArduinoJson
#define SIZE_LED_TOPIC 12
#define LED_PIN 26
#define PUSH_BUTTON_PIN 32
boolean changeState = true;
float numeroRandom=0.0;
DynamicJsonDocument dados(1024);
String dadosJson;
// Conexões WI-FI e MQTT
EspMQTTClient client(
"Wokwi-GUEST", //Rede wi-fi
"", // Senha wi-fi
"mqtt.tago.io", // Broker
"Default", // Usuário
"d46235f5-cda8-4cfc-9508-7339a4bb6404", // Token da plataforma Tago.io
"ESP32_Tutorial" // Identificação única
);
// Define a função de callback associada ao delay
void delayedFunction() {
// MQTT (Publish) e controle (alteração de valores)
Serial.println("Publicando topico le_botao_push_button caso conexao OK...");
Serial.println(dadosJson);
client.publish("le_botao_pushbutton", dadosJson);
// chama novamente função de callback
client.executeDelayed(5000, delayedFunction);
}
// Setup
void setup() {
client.enableMQTTPersistence();
client.setMqttReconnectionAttemptDelay(2000);
client.setWifiReconnectionAttemptDelay(3000);
client.setKeepAlive(20);
client.enableDebuggingMessages(true);
client.setMaxPacketSize(256);
client.executeDelayed(5000, delayedFunction);
pinMode(LED_PIN, OUTPUT);
pinMode(PUSH_BUTTON_PIN, INPUT);
Serial.begin(115200);
}
// Loop
void loop() {
client.loop();
// Insere os dados no JSON
dados[0]["variable"] = "estado_chave";
dados[0]["unit"] = "";
dados[0]["value"] = digitalRead(PUSH_BUTTON_PIN) == HIGH ? "CHAVE ABERTA" : "CHAVE FECHADA";
dados[1]["variable"] = "numero_ramdomico";
//dados[1]["unit"] = "°C";
dados[1]["unit"] = "";
dados[1]["value"] = numeroRandom;
// conversão da estrutura de dados (JSON)
serializeJson(dados, dadosJson);
numeroRandom = random(1,41) + ( 2 - random(1,4))*0.25;
}
// MQTT (Função que recebe dados do Subscribe)
void onMessageReceived(const String& msg) {
// payload always "estado_led 0" or "estado_led 1"
int estadoLed;
int msgLength = msg.length();
if ( msgLength == SIZE_LED_TOPIC) { // Check if topic length is correct
estadoLed = msg.charAt(SIZE_LED_TOPIC-1) - '0'; // Extract the character at index 11 (assuming space after 'led') and convert it to an integer by subtracting '0'
if (estadoLed == 1) {
digitalWrite(LED_PIN,HIGH);
Serial.println("Led ligado por MQTT");
} else if (estadoLed == 0) {
digitalWrite(LED_PIN,LOW);
Serial.println("Led desligado por MQTT");
}
} else {
// Handle error: topic length unexpected
Serial.println("Erro: tamanho do topica invalido!");
}
}
// MQTT (Subscribe)
void onConnectionEstablished() {
Serial.println("Conexao com tago.io estabelecida, assinando topicos...");
Serial.println("Assinando o topico le_botao_pushbutton sem função de callback....");
client.subscribe("le_botao_pushbutton", [] (const String &payload) {
});
Serial.println("Assinando o topico liga_desliga_led com função de callback....");
client.subscribe("liga_desliga_led", onMessageReceived); // necessário registrar a função de callback pra tratar
}