From ff9c4885bfc4984668477d45d839ce3cd9ddb7a8 Mon Sep 17 00:00:00 2001
From: Wesley Ellis <tahnok@gmail.com>
Date: Thu, 27 Feb 2025 20:57:19 -0500
Subject: [PATCH] Trim whitespace from end of bluetooth device names

I have a speaker at home with a name of "Pebble V3\r\n" that renders
poorly without this change.
---
 src/drivers/bluetooth.cpp | 17 +++++++++++++++--
 1 file changed, 15 insertions(+), 2 deletions(-)

diff --git a/src/drivers/bluetooth.cpp b/src/drivers/bluetooth.cpp
index 64e45e23..3697b33d 100644
--- a/src/drivers/bluetooth.cpp
+++ b/src/drivers/bluetooth.cpp
@@ -364,8 +364,21 @@ auto Scanner::HandleDeviceDiscovery(const esp_bt_gap_cb_param_t& param)
     return;
   }
 
-  device.name = std::pmr::string{reinterpret_cast<char*>(name),
-                                 static_cast<size_t>(length)};
+  // Create string from the device name
+  std::pmr::string deviceName{reinterpret_cast<char*>(name),
+                              static_cast<size_t>(length)};
+
+  // Trim trailing whitespace (spaces, tabs, \r, \n)
+  const std::string::size_type lastChar = deviceName.find_last_not_of(" \n\r\t");
+  if (lastChar != std::string::npos) {
+    deviceName.erase(lastChar + 1);
+  }
+
+  if (deviceName.empty()) {
+    return;
+  }
+
+  device.name = deviceName;
   events::DeviceDiscovered ev{.device = device};
   tinyfsm::FsmList<bluetooth::BluetoothState>::dispatch(ev);
 }