diff --git a/arduino/libretuya/core/LibreTuyaAPI.cpp b/arduino/libretuya/core/LibreTuyaAPI.cpp index 6476664..89e1aa4 100644 --- a/arduino/libretuya/core/LibreTuyaAPI.cpp +++ b/arduino/libretuya/core/LibreTuyaAPI.cpp @@ -8,7 +8,13 @@ String ipToString(const IPAddress &ip) { return String(szRet); } -static void lt_random_bytes(uint8_t *buf, size_t len) { +/** + * @brief Generate random bytes using rand(). + * + * @param buf destination pointer + * @param len how many bytes to generate + */ +void lt_rand_bytes(uint8_t *buf, size_t len) { int *data = (int *)buf; size_t i; for (i = 0; len >= sizeof(int); len -= sizeof(int)) { @@ -20,3 +26,36 @@ static void lt_random_bytes(uint8_t *buf, size_t len) { memcpy(buf + i * sizeof(int), pRem, len); } } + +/** + * @brief Print data pointed to by buf in hexdump-like format (hex+ASCII). + * + * @param buf source pointer + * @param len how many bytes to print + * @param offset increment printed offset by this value + * @param width how many bytes on a line + */ +void hexdump(uint8_t *buf, size_t len, uint32_t offset = 0, uint8_t width = 16) { + uint16_t pos = 0; + while (pos < len) { + // print hex offset + printf("%06x ", offset + pos); + // calculate current line width + uint8_t lineWidth = min(width, len - pos); + // print hexadecimal representation + for (uint8_t i = 0; i < lineWidth; i++) { + if (i % 8 == 0) { + printf(" "); + } + printf("%02x ", buf[pos + i]); + } + // print ascii representation + printf(" |"); + for (uint8_t i = 0; i < lineWidth; i++) { + char c = buf[pos + i]; + printf("%c", isprint(c) ? c : '.'); + } + printf("|\n"); + pos += lineWidth; + } +} diff --git a/arduino/libretuya/core/LibreTuyaAPI.h b/arduino/libretuya/core/LibreTuyaAPI.h index 1acead7..836eec1 100644 --- a/arduino/libretuya/core/LibreTuyaAPI.h +++ b/arduino/libretuya/core/LibreTuyaAPI.h @@ -43,10 +43,9 @@ extern "C" { #define FPSTR(pstr_pointer) (reinterpret_cast(pstr_pointer)) #define PGM_VOID_P const void * -// C functions void lt_rand_bytes(uint8_t *buf, size_t len); +void hexdump(uint8_t *buf, size_t len, uint32_t offset = 0, uint8_t width = 16); -// C++ only functions #ifdef __cplusplus String ipToString(const IPAddress &ip); #endif