From 67cd7bc031c68143ad388f9ae90dcea78096a435 Mon Sep 17 00:00:00 2001
From: Fernando Governatore <fernando@syspac.com.br>
Date: Mon, 3 Jul 2017 15:48:12 -0300
Subject: [PATCH 1/2] MQTT fix mqtt_timer_left_ms

  mqtt_timer_left_ms: timer->end_time is in ticks, now is in ticks, so left
is in ticks. left * portTICK_PERIOD_MS is the time left.

  With that change, the select in both mqtt_esp_read and mqtt_esp_write
seems to work as expected(with time, not ticks)
---
 extras/paho_mqtt_c/MQTTESP8266.c | 12 +++++-------
 1 file changed, 5 insertions(+), 7 deletions(-)

diff --git a/extras/paho_mqtt_c/MQTTESP8266.c b/extras/paho_mqtt_c/MQTTESP8266.c
index e7a14d9..cebf24a 100644
--- a/extras/paho_mqtt_c/MQTTESP8266.c
+++ b/extras/paho_mqtt_c/MQTTESP8266.c
@@ -53,7 +53,7 @@ int  mqtt_timer_left_ms(mqtt_timer_t* timer)
 {
     TickType_t now = xTaskGetTickCount();
     int32_t left = timer->end_time - now;
-    return (left < 0) ? 0 : left / portTICK_PERIOD_MS;
+    return (left < 0) ? 0 : left * portTICK_PERIOD_MS;
 }
 
 
@@ -72,9 +72,8 @@ int  mqtt_esp_read(mqtt_network_t* n, unsigned char* buffer, int len, int timeou
     int rcvd = 0;
     FD_ZERO(&fdset);
     FD_SET(n->my_socket, &fdset);
-    // It seems tv_sec actually means FreeRTOS tick
-    tv.tv_sec = timeout_ms / portTICK_PERIOD_MS;
-    tv.tv_usec = 0;
+    tv.tv_sec = timeout_ms / 1000;
+    tv.tv_usec = (timeout_ms % 1000) * 1000;
     rc = select(n->my_socket + 1, &fdset, 0, 0, &tv);
     if ((rc > 0) && (FD_ISSET(n->my_socket, &fdset)))
     {
@@ -97,9 +96,8 @@ int  mqtt_esp_write(mqtt_network_t* n, unsigned char* buffer, int len, int timeo
 
     FD_ZERO(&fdset);
     FD_SET(n->my_socket, &fdset);
-    // It seems tv_sec actually means FreeRTOS tick
-    tv.tv_sec = timeout_ms / portTICK_PERIOD_MS;
-    tv.tv_usec = 0;
+    tv.tv_sec = timeout_ms / 1000;
+    tv.tv_usec = (timeout_ms % 1000) * 1000;
     rc = select(n->my_socket + 1, 0, &fdset, 0, &tv);
     if ((rc > 0) && (FD_ISSET(n->my_socket, &fdset)))
     {

From c1747fb8dac3e1b36c7f3edf2edc925e662de73c Mon Sep 17 00:00:00 2001
From: Fernando Governatore <fernando@syspac.com.br>
Date: Mon, 3 Jul 2017 15:49:05 -0300
Subject: [PATCH 2/2] MQTT fix mqtt_timer_expired

  If the user passes 0 as a timeout, we should not sleep(the timer has
already expired).
---
 extras/paho_mqtt_c/MQTTESP8266.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/extras/paho_mqtt_c/MQTTESP8266.c b/extras/paho_mqtt_c/MQTTESP8266.c
index cebf24a..a6f1e75 100644
--- a/extras/paho_mqtt_c/MQTTESP8266.c
+++ b/extras/paho_mqtt_c/MQTTESP8266.c
@@ -32,7 +32,7 @@ char  mqtt_timer_expired(mqtt_timer_t* timer)
 {
     TickType_t now = xTaskGetTickCount();
     int32_t left = timer->end_time - now;
-    return (left < 0);
+    return (left <= 0);
 }