From 2eac55865a8b009850f778ad31b05c595dedb102 Mon Sep 17 00:00:00 2001
From: Jannis Rieger <omniskopus@gmail.com>
Date: Thu, 22 Aug 2019 15:27:44 +0200
Subject: [PATCH] feat(ble): Read the advertised device name from a file

---
 epicardium/ble/ble_main.c | 35 +++++++++++++++++++++++++++--------
 1 file changed, 27 insertions(+), 8 deletions(-)

diff --git a/epicardium/ble/ble_main.c b/epicardium/ble/ble_main.c
index af041f9c..04ec8a4a 100644
--- a/epicardium/ble/ble_main.c
+++ b/epicardium/ble/ble_main.c
@@ -328,16 +328,35 @@ static void bleSetup(bleMsg_t *pMsg)
   char buf[32];
   char a, b, c, d, e, f, K;
 
-  if (fs_read_text_file("mac.txt", buf, sizeof(buf)))
+  // read the device name from file
+  int name_length = fs_read_text_file("device_name.txt", buf, sizeof(buf));
+  // check if the file was present and contained data
+  if (name_length > 0) {
+    // truncate name_length to the maximum length a device name can be (bleScanDataDisc[0] - 1)
+    if (bleScanDataDisc[0] - 1 < name_length)
+      name_length = bleScanDataDisc[0] - 1;
+    // now copy the name
+    memcpy(bleScanDataDisc + 2, buf, name_length);
+    // if the name is shorter than the maximum device name length
+    // we pad the rest with spaces
+    while(name_length < bleScanDataDisc[0] - 1) {
+      bleScanDataDisc[2 + name_length++] = ' ';
+    }
+  }
+  else
   {
-    if (sscanf(buf, "%c%c:%c%c:%c%c:%c%c:%c%c:%c%c", &K,&K,&K,&K,&K,&K, &a, &b, &c, &d, &e, &f) == 12)
+    // if the device_name file was not present use the default name with the mac address
+    if (fs_read_text_file("mac.txt", buf, sizeof(buf)))
     {
-      bleScanDataDisc[9]  = a;
-      bleScanDataDisc[10] = b;
-      bleScanDataDisc[11] = c;
-      bleScanDataDisc[12] = d;
-      bleScanDataDisc[13] = e;
-      bleScanDataDisc[14] = f;
+      if (sscanf(buf, "%c%c:%c%c:%c%c:%c%c:%c%c:%c%c", &K,&K,&K,&K,&K,&K, &a, &b, &c, &d, &e, &f) == 12)
+      {
+        bleScanDataDisc[9]  = a;
+        bleScanDataDisc[10] = b;
+        bleScanDataDisc[11] = c;
+        bleScanDataDisc[12] = d;
+        bleScanDataDisc[13] = e;
+        bleScanDataDisc[14] = f;
+      }
     }
   }
   
-- 
GitLab