Azure IoT common library

Dependents:   STM32F746_iothub_client_sample_mqtt f767zi_mqtt iothub_client_sample_amqp iothub_client_sample_http ... more

Revision:
41:dc93369d5ed4
Parent:
35:98add15351f3
Child:
45:1119d0f2c4d8
--- a/xlogging.c	Thu Feb 15 11:37:42 2018 -0800
+++ b/xlogging.c	Mon Mar 05 17:43:09 2018 -0800
@@ -67,4 +67,71 @@
 }
 #endif
 
+/* Print up to 16 bytes per line. */
+#define LINE_SIZE 16
+
+/* Return the printable char for the provided value. */
+#define PRINTABLE(c)         ((c >= ' ') && (c <= '~')) ? (char)c : '.'
+
+/* Convert the lower nibble of the provided byte to a hexadecimal printable char. */
+#define HEX_STR(c)           (((c) & 0xF) < 0xA) ? (char)(((c) & 0xF) + '0') : (char)(((c) & 0xF) - 0xA + 'A')
+
+void LogBinary(const char* comment, const void* data, size_t size)
+{
+    char charBuf[LINE_SIZE + 1];
+    char hexBuf[LINE_SIZE * 3 + 1];
+    size_t countbuf = 0;
+    size_t i = 0;
+    const unsigned char* bufAsChar = (const unsigned char*)data;
+    const unsigned char* startPos = bufAsChar;
+
+    LOG(AZ_LOG_TRACE, LOG_LINE, "%s     %zu bytes", comment, size);
+
+    /* Print the whole buffer. */
+    for (i = 0; i < size; i++)
+    {
+        /* Store the printable value of the char in the charBuf to print. */
+        charBuf[countbuf] = PRINTABLE(*bufAsChar);
+
+        /* Convert the high nibble to a printable hexadecimal value. */
+        hexBuf[countbuf * 3] = HEX_STR(*bufAsChar >> 4);
+
+        /* Convert the low nibble to a printable hexadecimal value. */
+        hexBuf[countbuf * 3 + 1] = HEX_STR(*bufAsChar);
+
+        hexBuf[countbuf * 3 + 2] = ' ';
+
+        countbuf++;
+        bufAsChar++;
+        /* If the line is full, print it to start another one. */
+        if (countbuf == LINE_SIZE)
+        {
+            charBuf[countbuf] = '\0';
+            hexBuf[countbuf * 3] = '\0';
+            LOG(AZ_LOG_TRACE, LOG_LINE, "%p: %s    %s", startPos, hexBuf, charBuf);
+            countbuf = 0;
+            startPos = bufAsChar;
+        }
+    }
+
+    /* If the last line does not fit the line size. */
+    if (countbuf > 0)
+    {
+        /* Close the charBuf string. */
+        charBuf[countbuf] = '\0';
+
+        /* Fill the hexBuf with spaces to keep the charBuf alignment. */
+        while ((countbuf++) < LINE_SIZE - 1)
+        {
+            hexBuf[countbuf * 3] = ' ';
+            hexBuf[countbuf * 3 + 1] = ' ';
+            hexBuf[countbuf * 3 + 2] = ' ';
+        }
+        hexBuf[countbuf * 3] = '\0';
+
+        /* Print the last line. */
+        LOG(AZ_LOG_TRACE, LOG_LINE, "%p: %s    %s", startPos, hexBuf, charBuf);
+    }
+}
+
 #endif