AI Excerpt

Explore the mystery of ESP8266 PubSubClient publishing delay. Why is MQTT push always half a beat late? After checking that the board and the server are both fine, the key is the lack of buffering after publish in the loop. After increasing the delay, the publishing takes effect immediately!

I updated the power-meter project two days ago and planned to use PubSubClient library to connect to homeassistant

But when running the project, I found that esp8266 mqtt push is extremely unstable

I checked the mqtt server and the client that receives the message, but no problems were found.

I wrote a loop push using esp8266, which is also very stable, eliminating the problem of the board itself

for(int i = 1; i <= 100; i++){
    sprintf(message, "%d", i);
    client.publish(topic, message);
    yield();
    delay(500);
}

Code snippet:

void loop(){
    while(1){
        light1 = analogRead(A0);
        if(light1 > powerledPin_average){
            // led on
            timeA = micros();

            delay(300);
            break;
        }
        yield();
        client.loop();
    }
    

    time_light = timeA - timeB;

    power = 1. / powerledPin_rate * 1000 * 3600 * 1000000 / time_light;

    Serial.println(power);
    sprintf(message, "%f", power);
    client.publish(topic, message);

    delay(100); // 加入延时
}

I guess the last line of publish code is not processed in time and continues to loop.So add a delay after pushing the code, and the problem is solved.