Read topic in MQTT when restart Arduino

Hello, I have a raspberry with MOSQUITTO installed. I am trying to read topics values when Arduino restart or reconnect but it doesn't work.


/////////////////////////////////////////////////
// FUNCION PARA MQTT
////////////////////////////////////////////////

void callback(char* topic, byte* message, unsigned int length) {
  Serial.print("Message arrived on topic: ");
  Serial.print(topic);
  Serial.print(". Message: ");
  String messageTemp;
  
  for (int i = 0; i < length; i++) {
    Serial.print((char)message[i]);
    messageTemp += (char)message[i];
  }
  Serial.println();
  Serial.print("messageTemp: ");
  Serial.println(messageTemp);
  
  // Changes the output state according to the message
    modo_ai = messageTemp.toInt();
    Serial.print("Changing modo_ai to ");
    Serial.println(modo_ai);
}
void sendDataTopic()
{
  client.publish( MQTT_SERIAL_PUBLISH_CH "acu/agua", String(temp_agua).c_str());
  client.publish( MQTT_SERIAL_PUBLISH_CH "acu/habitacion", String(tempHB).c_str());
}

/////////////////////////////////////////////////
// FUNCION PARA RECONECTAR
////////////////////////////////////////////////

void reconnectWifi() {
    Serial.println("Iniciar conexión a la red WIFI");
    while(status != WL_CONNECTED) {
        Serial.print("Intentando conectarse a WPA SSID: ");
        Serial.println(ssid);
        //Conectar a red WPA/WPA2
        status = WiFi.begin(ssid, pass);
        delay(500);
    }
    Serial.println("Conectado a la red WIFI");
}

void reconnectClient() {
  // Loop until we're reconnected
  while (!client.connected()) {
    delay(200);
    Serial.print("Attempting MQTT connection...");
    // Create a random client ID
    String clientId = "ESP32Client-";
    clientId += String(random(0xffff), HEX);
    Serial.println(clientId.c_str());
    // Attempt to connect
    if (client.connect(clientId.c_str(),mqttUser,mqttPassword)) {
      Serial.println("connected");
      //Once connected, publish an announcement...
      client.publish(MQTT_SERIAL_PUBLISH_CH "acu/status", "conectado!");
      // ... and resubscribe
     client.subscribe("acu/modo_ai");
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      // Wait 5 seconds before retrying
      delay(5000);
    }
  }
}
/////////////////////////////////////////////////////////////////////////////
void loop() {
   
    //Validamos si el modulo WiFi aun esta conectado a la red   //Si falla la conexión, reconectamos el modulo
    status = WiFi.status();
    if(status != WL_CONNECTED) {
        reconnectWifi();
    }
    
    //Validamos si esta la conexión del servidor  //Si falla reintentamos la conexión
    if(!client.connected() ) {
        reconnectClient();
    } 
    delay(100);  
     // cliente a la escucha    
     client.loop();
          
   #ifdef CONTADOR 
   contador_1 ++;  //   Serial.print(contador_global);
   if (contador_1 == 20) {
    //Serial.println("contador 20");
    check_temp();        // Comprueba valores temperatura
   }
       if (contador_1 == 40) {
  //  Serial.println("contador 40");    
    check_ventilador();  // Comprueba si activa ventilador
       }
       if (contador_1 == 60) {
   // Serial.println("contador 60");    
    check_calentador();  // Comprueba si activa el calentador
    check_UV();          // Comprobamos horario para encender UV
    check_ai();          // Comprobamos horario para encender AIREADOR
       }
       if (contador_1 == 100) {
    Serial.println("contador 100 y 0");       
    sendDataTopic();             // Envia datos a mqtt

    #ifdef pantalla
    // ############## Inicio "picture loop" ####### 
     u8g2.firstPage(); 
     do { 
      draw();
     } while( u8g2.nextPage() ); 
   // ############## Fin "picture loop" ########## 
   #endif
   
    contador_1 = 0;  
   }
   #endif
    
  //  peris();             // comprueba peristalticas
    check_nivel_acu();   // Comprobamos el nivel del agua del acuario
      
}

for example, in MQTT value of mod_ai=3 but when I restart Arduino It load as 0. Then if I change value in MQTT it updates in Arduino.

When publishing topics, set the retain bit to true.

Sorry, I dont understand you.
What I am not be able to do is when restart arduino READ all topics to run the correct value for the code

So, when the ide run first time read all topics what it is subscribe.

Have you take a look at the PubSubClient library API?

See how the publish method has several options; boolean publish (topic, payload, [length], [retained])?

[url=https://pubsubclient.knolleary.net/api#publish]Arduino Client for MQTT

One of those options is the retained flag.

If the retained flag is set then what happens is documented.

image

This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.