Skip to content

Commit

Permalink
mqtt: deleted expired messages even when offline
Browse files Browse the repository at this point in the history
As long as the client was disconnect no cleanup were performed,
consuming memory for every message published. Even if they were already
expired and would be discarded when reconnected.

Also moves delete of expired msgs before retransmit is done.
This avoids situtations where a message could be sent even if it was
expired.

Closes espressif/esp-idf#5668
  • Loading branch information
ESP-Marius committed Aug 10, 2020
1 parent f7325bf commit bdadd77
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 8 deletions.
7 changes: 6 additions & 1 deletion include/mqtt_config.h
Original file line number Diff line number Diff line change
Expand Up @@ -84,11 +84,16 @@
#endif
#endif

#ifdef CONFIG_OUTBOX_EXPIRED_TIMEOUT_MS
#define OUTBOX_EXPIRED_TIMEOUT_MS CONFIG_OUTBOX_EXPIRED_TIMEOUT_MS
#else
#define OUTBOX_EXPIRED_TIMEOUT_MS (30*1000)
#endif

#define MQTT_ENABLE_SSL CONFIG_MQTT_TRANSPORT_SSL
#define MQTT_ENABLE_WS CONFIG_MQTT_TRANSPORT_WEBSOCKET
#define MQTT_ENABLE_WSS CONFIG_MQTT_TRANSPORT_WEBSOCKET_SECURE

#define OUTBOX_EXPIRED_TIMEOUT_MS (30*1000)

#define OUTBOX_MAX_SIZE (4*1024)
#endif
24 changes: 17 additions & 7 deletions mqtt_client.c
Original file line number Diff line number Diff line change
Expand Up @@ -1344,6 +1344,14 @@ static void esp_mqtt_task(void *pv)
break;
}

//Delete message after OUTBOX_EXPIRED_TIMEOUT_MS miliseconds
int deleted = outbox_delete_expired(client->outbox, platform_tick_get_ms(), OUTBOX_EXPIRED_TIMEOUT_MS);
client->mqtt_state.pending_msg_count -= deleted;

if (client->mqtt_state.pending_msg_count < 0) {
client->mqtt_state.pending_msg_count = 0;
}

// resend all non-transmitted messages first
outbox_item_handle_t item = outbox_dequeue(client->outbox, QUEUED, NULL);
if (item) {
Expand Down Expand Up @@ -1384,13 +1392,6 @@ static void esp_mqtt_task(void *pv)
client->state = MQTT_STATE_INIT;
}

//Delete message after 30 seconds
int deleted = outbox_delete_expired(client->outbox, platform_tick_get_ms(), OUTBOX_EXPIRED_TIMEOUT_MS);
client->mqtt_state.pending_msg_count -= deleted;
if (client->mqtt_state.pending_msg_count < 0) {
client->mqtt_state.pending_msg_count = 0;
}
//
outbox_cleanup(client->outbox, OUTBOX_MAX_SIZE);
break;
case MQTT_STATE_WAIT_TIMEOUT:
Expand Down Expand Up @@ -1637,6 +1638,15 @@ int esp_mqtt_client_publish(esp_mqtt_client_handle_t client, const char *topic,
if (qos > 0) {
ret = pending_msg_id;
}

//Delete message after OUTBOX_EXPIRED_TIMEOUT_MS miliseconds
int deleted = outbox_delete_expired(client->outbox, platform_tick_get_ms(), OUTBOX_EXPIRED_TIMEOUT_MS);
client->mqtt_state.pending_msg_count -= deleted;

if (client->mqtt_state.pending_msg_count < 0) {
client->mqtt_state.pending_msg_count = 0;
}

goto cannot_publish;
}

Expand Down

0 comments on commit bdadd77

Please sign in to comment.