esp32-tutorial
esp32-tutorial copied to clipboard
21_mqtt: mqtt automatic reconnection issue
Hello, nice example!
I just have an issue that the mqtt automatic reconnection is not working. I think it is the while loop that prevents the disconnect callback so the mqtt client is never making a reconnection
I did set the .auto_reconnect = true and it works if I just comment out the while loop
So instead I believe that the sensor readings using the while loop and mqtt publishing maybe should be moved to a separate task - My initial tests seems to work but the last bit I cannot find out, the mqtt publishing from inside the task
So my code below looks something like this (simplified and using a temperatur sensor) and it builds correctly but it crashes when the mqtt publishing happens
- program starts correctly, mqtt client connects, xtask is created, sensor temperature is read correctly
- mqtt publishing -> crash
- I guess something goes wrong with pointer/address in data
- if I run the code without mqtt publishing, everything works fine, if I restart mqtt broker, the program reconnects perfectly
- happy for any suggestion how to make mqtt publishing correct instead, maybe putting it into a separate function?
Best regards, Walter
bool mqtt_conn = false;
void read_temp(void *data)
{
while(mqtt_conn)
{
float rt = ds18b20_get_temp();
char temp_string[10];
sprintf(temp_string, "%.1f", rt);
printf("%s\n",temp_string);
mqtt_publish(data, "/room/temperature", temp_string, strlen(temp_string), 0, 0);
vTaskDelay(5000 / portTICK_RATE_MS);
}
vTaskDelete( NULL );
}
// MQTT connected callback
void mqtt_connected_callback(mqtt_client *client, mqtt_event_data_t *event_data)
{
printf(" connected!\n");
mqtt_conn = true;
xTaskCreate(&read_temp, "read_temp_task", 10000, &client, 5, NULL);
}
// MQTT disconnected callback
void mqtt_disconnected_callback(mqtt_client *client, mqtt_event_data_t *event_data)
{
printf("MQTT disconnected!\n");
mqtt_conn = false;
}
Just to let you know, the above code works now, with a small but so important change
Changed
xTaskCreate(&read_temp, "read_temp_task", 10000, &client, 5, NULL);
to
xTaskCreate(&read_temp, "read_temp_task", 10000, client, 5, NULL);
I tried to pass the complete mqtt client struct when I started experimenting but I failed for some stupid reason, started to play with pointers...but hey, now it works!!! The ESP32 reconnects now automatically after a broker restart