nanohub: firmware: flush usart

Entering in sleep-mode freezes several clock in the device; if usart is
still transmitting, this will cause sending incorrect data.

Wait for usart to complete transmission.

Change-Id: Ide972e55b1e850d3310e935912697e9aa17a638c
Signed-off-by: Antonio Borneo <[email protected]>
diff --git a/firmware/os/inc/usart.h b/firmware/os/inc/usart.h
index ab7a477..1ef18e5 100644
--- a/firmware/os/inc/usart.h
+++ b/firmware/os/inc/usart.h
@@ -63,6 +63,7 @@
                 UsatStopBitsCfg stop_bits, UsartParityCfg parity,
                 UsartFlowControlCfg flow_control);
 void usartClose(const struct usart* __restrict usart);
+void usartFlush(const struct usart* __restrict usart);
 void usartPutchar(const struct usart* __restrict usart, char c);
 
 #ifdef __cplusplus
diff --git a/firmware/os/platform/stm32/platform.c b/firmware/os/platform/stm32/platform.c
index 5c8082c..befafe9 100644
--- a/firmware/os/platform/stm32/platform.c
+++ b/firmware/os/platform/stm32/platform.c
@@ -184,6 +184,9 @@
 
 void platLogFlush(void *userData)
 {
+#ifdef DEBUG_UART_UNITNO
+    usartFlush(&mDbgUart);
+#endif
 #if defined(DEBUG_LOG_EVT)
     if (userData && mLateBoot)
         osEnqueueEvtOrFree(EVENT_TYPE_BIT_DISCARDABLE | EVT_DEBUG_LOG, userData, heapFree);
diff --git a/firmware/os/platform/stm32/usart.c b/firmware/os/platform/stm32/usart.c
index 302cb85..26f644f 100644
--- a/firmware/os/platform/stm32/usart.c
+++ b/firmware/os/platform/stm32/usart.c
@@ -144,6 +144,17 @@
     gpioRelease(usart->tx);
 }
 
+/*
+ * don't use this immediately after usart initialization
+ * the test is valid only after the first char has been sent out
+ */
+void usartFlush(const struct usart* __restrict usart)
+{
+    struct StmUsart *block = (struct StmUsart*)mUsartPorts[usart->unit];
+
+    while ((block->SR & 0x00c0) != 0x00c0);
+}
+
 void usartPutchar(const struct usart* __restrict usart, char c)
 {
     struct StmUsart *block = (struct StmUsart*)mUsartPorts[usart->unit];