From f1b6a19fa51edbec6f1cc0406eef277608075848 Mon Sep 17 00:00:00 2001
From: "tommaso.lamon@skywarder.eu" <tommaso.lamon@skywarder.eu>
Date: Fri, 10 Jan 2025 14:43:57 +0100
Subject: [PATCH] [USART] Created new function writeFile

This function, given a filename sends the content of
the file through the USART interface in 1 KB chunks
---
 src/shared/drivers/usart/USART.cpp | 21 +++++++++++++++++++++
 src/shared/drivers/usart/USART.h   |  8 ++++++++
 2 files changed, 29 insertions(+)

diff --git a/src/shared/drivers/usart/USART.cpp b/src/shared/drivers/usart/USART.cpp
index 846d2219a..c3a3044d5 100644
--- a/src/shared/drivers/usart/USART.cpp
+++ b/src/shared/drivers/usart/USART.cpp
@@ -27,6 +27,7 @@
 #include <utils/Debug.h>
 #include <utils/Numeric.h>
 
+#include <fstream>
 #include <string>
 
 #include "arch/common/drivers/serial.h"
@@ -592,6 +593,26 @@ void USART::writeString(const char* buffer)
     };
 }
 
+bool USART::writeFile(const std::string& fileName)
+{
+    std::ifstream file(fileName, std::ifstream::binary);
+    std::vector<uint8_t> buffer(1024, 0);  // 1024 Bytes buffer.
+
+    if (!file.is_open())
+    {
+        LOG_ERR(logger, "Failed to open file {}", fileName);
+        return false;
+    }
+
+    while (file.read(reinterpret_cast<char*>(buffer.data()), buffer.size()))
+    {
+        std::streamsize s = file.gcount();
+        if (s > 0)
+            write(buffer.data(), static_cast<size_t>(s));
+    }
+    return true;
+}
+
 void USART::clearQueue()
 {
     char buf[INTERNAL_QUEUE_LENGTH];
diff --git a/src/shared/drivers/usart/USART.h b/src/shared/drivers/usart/USART.h
index 1e0f378ad..c39ad9445 100644
--- a/src/shared/drivers/usart/USART.h
+++ b/src/shared/drivers/usart/USART.h
@@ -267,6 +267,14 @@ public:
      */
     void writeString(const char* buffer);
 
+    /**
+     * @brief Given a filename, uses the USART interface to stream the file in
+     * 1KB chunks
+     * @param fileName String containing the name of the file to stream.
+     * @return A boolean value (true if stream is complete, false otherwise).
+     */
+    bool writeFile(const std::string& fileName);
+
     /**
      * @brief Set the length of the word to 8 or to 9.
      *
-- 
GitLab