diff --git a/include/mqtt_client.h b/include/mqtt_client.h index 07dd978..f6f4fe0 100644 --- a/include/mqtt_client.h +++ b/include/mqtt_client.h @@ -302,8 +302,10 @@ int esp_mqtt_client_unsubscribe(esp_mqtt_client_handle_t client, const char *top * - This API might block for several seconds, either due to network timeout (10s) * or if publishing payloads longer than internal buffer (due to message * fragmentation) - * - Client doesn't have to be connected to send publish message - * (although it would drop all qos=0 messages, qos>1 messages would be enqueued) + * - Client doesn't have to be connected for this API to work, enqueueing the messages + * with qos>1 (returning -1 for all the qos=0 messages if disconnected). + * If MQTT_SKIP_PUBLISH_IF_DISCONNECTED is enabled, this API will not attempt to publish + * when the client is not connected and will always return -1. * - It is thread safe, please refer to `esp_mqtt_client_subscribe` for details * * @param client mqtt client handle diff --git a/lib/include/mqtt_config.h b/lib/include/mqtt_config.h index 4932297..da2a93a 100644 --- a/lib/include/mqtt_config.h +++ b/lib/include/mqtt_config.h @@ -17,6 +17,8 @@ #define MQTT_MSG_ID_INCREMENTAL CONFIG_MQTT_MSG_ID_INCREMENTAL +#define MQTT_SKIP_PUBLISH_IF_DISCONNECTED CONFIG_MQTT_SKIP_PUBLISH_IF_DISCONNECTED + #if CONFIG_MQTT_BUFFER_SIZE #define MQTT_BUFFER_SIZE_BYTE CONFIG_MQTT_BUFFER_SIZE #else diff --git a/mqtt_client.c b/mqtt_client.c index 651515c..def0e28 100644 --- a/mqtt_client.c +++ b/mqtt_client.c @@ -1653,6 +1653,13 @@ static inline int mqtt_client_enqueue_priv(esp_mqtt_client_handle_t client, cons int esp_mqtt_client_publish(esp_mqtt_client_handle_t client, const char *topic, const char *data, int len, int qos, int retain) { MQTT_API_LOCK(client); +#if MQTT_SKIP_PUBLISH_IF_DISCONNECTED + if (client->state != MQTT_STATE_CONNECTED) { + ESP_LOGE(TAG, "Publish failed: client is not connected"); + MQTT_API_UNLOCK(client); + return -1; + } +#endif int pending_msg_id = mqtt_client_enqueue_priv(client, topic, data, len, qos, retain); if (pending_msg_id < 0) { MQTT_API_UNLOCK(client);