/*********************************************************
Plantilla de conexionado WiFi-MQTT IoT DAC
Sustituir el valor de mqtt_server con la dirección habitual
Después de la primera ejecución sustituir el valor final de ID_PLACA con el número aleatorio generado u otro,
pero ya fijo, de esta forma en siguientes ejecuciones usaremos el mismo identificador y los mismos topics
**********************************************************/
/*
Basic ESP32 MQTT example
Principales diferencias con el ejemplo de la librería PubSubClient:
Uso del tipo String para manejar texto
Utiliza el indentificador de hostname en setup() para:
- construir un identificador único para conectar con MQTT (esp32c3-??????)
- construir topics únicos para esta placa (infind/esp32c3-??????/+)
Conecta a MQTT usando usuario/contraseña (conecta_mqtt())
Configura el servidor MQTT para admitir mensajes hasta 512 bytes (setup())
En callback():
- copia el mensaje (buffer de bytes) a un String
- comprueba el valor del topic
Al enviar un mensaje enciende momentaneamente el LED RGB en blanco
*/
// definimos macro para indicar función y línea de código en los mensajes
#define DEBUG_STRING "["+String(__FUNCTION__)+"():"+String(__LINE__)+"] "
#include <WiFi.h>
#include <PubSubClient.h>
WiFiClient wClient;
PubSubClient mqtt_client(wClient);
// Update these with values suitable for your network.
const String ssid = "Wokwi-GUEST";
const String password = "";
// Pon aquí el broker MQTT que usamos normalmente
const String mqtt_server = "*** broker mqtt aqui ***";
const String mqtt_user = "wokwi";
const String mqtt_pass = "wokpass";
// cadenas para topics e ID
String ID_PLACA;
String topic_PUBLICACION;
String topic_SUSCRIPCION;
// estado led
int estado_led = 0;
//-----------------------------------------------------
void conecta_wifi() {
Serial.println(DEBUG_STRING+"Connecting to " + ssid);
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(200);
Serial.print(".");
}
Serial.println();
Serial.println(DEBUG_STRING+"WiFi connected, IP address: " + WiFi.localIP().toString());
}
//-----------------------------------------------------
void conecta_mqtt() {
// Loop until we're reconnected
while (!mqtt_client.connected()) {
Serial.print(DEBUG_STRING+"Attempting MQTT connection...");
// Attempt to connect
if (mqtt_client.connect(ID_PLACA.c_str(), mqtt_user.c_str(), mqtt_pass.c_str())) {
Serial.println(" conectado a broker: " + mqtt_server);
mqtt_client.subscribe(topic_SUSCRIPCION.c_str());
} else {
Serial.println(DEBUG_STRING+"ERROR:"+ String(mqtt_client.state()) +" reintento en 5s" );
// Wait 5 seconds before retrying
delay(5000);
}
}
}
//-----------------------------------------------------
void procesa_mensaje(char* topic, byte* payload, unsigned int length) {
String mensaje=""; // mejor String que el buffer de bytes
for(int i=0; i<length; i++) mensaje+= (char)payload[i];
Serial.println(DEBUG_STRING+"Mensaje recibido ["+ String(topic) +"] \"" + mensaje + "\" "+String(length)+" bytes" );
// compruebo el topic
if(String(topic)==topic_SUSCRIPCION)
{
if (mensaje[0] == '1') {
neopixelWrite(RGB_BUILTIN, 255, 0, 0); // RGB LED = RED
estado_led = 1;
} else {
digitalWrite(RGB_BUILTIN, LOW); // RGB LED = OFF
estado_led = 0;
}
}
}
//-----------------------------------------------------
// SETUP
//-----------------------------------------------------
void setup() {
Serial.begin(115200);
Serial.println();
Serial.println(DEBUG_STRING+"Empieza setup...");
// crea topics usando id único de la placa
ID_PLACA= String(WiFi.getHostname())+"-"+String(esp_random()).substring(7);
topic_PUBLICACION="infind/"+ ID_PLACA +"/publicacion";
topic_SUSCRIPCION="infind/"+ ID_PLACA +"/recepcion";
conecta_wifi();
mqtt_client.setServer(mqtt_server.c_str(), 1883);
mqtt_client.setBufferSize(512); // para poder enviar mensajes de hasta X bytes
mqtt_client.setCallback(procesa_mensaje);
conecta_mqtt();
Serial.println(DEBUG_STRING+"Identificador placa : "+ ID_PLACA);
Serial.println(DEBUG_STRING+"Topic publicacion : "+ topic_PUBLICACION);
Serial.println(DEBUG_STRING+"Topic suscripcion : "+ topic_SUSCRIPCION);
Serial.println(DEBUG_STRING+"Termina setup en " + String(millis()) + " ms");
}
//-----------------------------------------------------
unsigned long ultimo_mensaje=0;
//-----------------------------------------------------
// LOOP
//-----------------------------------------------------
void loop() {
if (!mqtt_client.connected()) conecta_mqtt();
mqtt_client.loop(); // esta llamada para que la librería recupere el control
unsigned long ahora = millis();
if (ahora - ultimo_mensaje >= 10000 || ultimo_mensaje==0) {
ultimo_mensaje = ahora;
String mensaje="Mensaje enviado desde "+ ID_PLACA +" en "+ String(ahora) +" ms";
Serial.println();
Serial.println(DEBUG_STRING+"Topic : "+ topic_PUBLICACION);
Serial.println(DEBUG_STRING+"Payload : "+ mensaje);
mqtt_client.publish(topic_PUBLICACION.c_str(), mensaje.c_str());
digitalWrite(RGB_BUILTIN, HIGH); // enciende el led al enviar mensaje
}
if (digitalRead(RGB_BUILTIN)==HIGH && ahora-ultimo_mensaje>=300)
// apaga el destello un poco después de enviar el mensaje
if (estado_led == 1) {
neopixelWrite(RGB_BUILTIN, 255, 0, 0); // RGB LED = RED
}else {
digitalWrite(RGB_BUILTIN, LOW);
}
}