From 20b1c695ab2757186305999ce99f845ae6a65b1f Mon Sep 17 00:00:00 2001 From: Robert Lubos Date: Fri, 17 Jan 2020 13:03:16 +0100 Subject: [PATCH] net: mqtt: Add keep alive timeout helper Add function that returns remaining time until next keep alive message shall be sent. Such function could be used for instance as a source for `poll` timeout. Signed-off-by: Robert Lubos --- include/net/mqtt.h | 12 ++++++++++++ subsys/net/lib/mqtt/mqtt.c | 18 ++++++++++++++++++ 2 files changed, 30 insertions(+) diff --git a/include/net/mqtt.h b/include/net/mqtt.h index cac22cf8428..7e0283c1498 100644 --- a/include/net/mqtt.h +++ b/include/net/mqtt.h @@ -707,6 +707,18 @@ int mqtt_abort(struct mqtt_client *client); */ int mqtt_live(struct mqtt_client *client); +/** + * @brief Helper function to determine when next keep alive message should be + * sent. Can be used for instance as a source for `poll` timeout. + * + * @param[in] client Client instance for which the procedure is requested. + * + * @return Time in milliseconds until next keep alive message is expected to + * be sent. Function will return UINT32_MAX if keep alive messages are + * not enabled. + */ +u32_t mqtt_keepalive_time_left(const struct mqtt_client *client); + /** * @brief Receive an incoming MQTT packet. The registered callback will be * called with the packet content. diff --git a/subsys/net/lib/mqtt/mqtt.c b/subsys/net/lib/mqtt/mqtt.c index 745b6120d44..ecc77fa3872 100644 --- a/subsys/net/lib/mqtt/mqtt.c +++ b/subsys/net/lib/mqtt/mqtt.c @@ -597,6 +597,24 @@ int mqtt_live(struct mqtt_client *client) return 0; } +u32_t mqtt_keepalive_time_left(const struct mqtt_client *client) +{ + u32_t elapsed_time = mqtt_elapsed_time_in_ms_get( + client->internal.last_activity); + u32_t keepalive_ms = 1000U * client->keepalive; + + if (client->keepalive == 0) { + /* Keep alive not enabled. */ + return UINT32_MAX; + } + + if (keepalive_ms <= elapsed_time) { + return 0; + } + + return keepalive_ms - elapsed_time; +} + int mqtt_input(struct mqtt_client *client) { int err_code = 0;