From 6bf0d868c969ab44d821bc397a04aa05b59370a7 Mon Sep 17 00:00:00 2001
From: Paul-Winpenny <92634321+Paul-Winpenny@users.noreply.github.com>
Date: Mon, 21 Oct 2024 15:33:40 +0100
Subject: [PATCH] Reduced complexity in app and added updates to BLE.

---
 .../ViewModels/ConnectionPageViewModel.cs     | 39 +++++----------
 ButtonControls/RPiBluetooth.py                | 49 +++++--------------
 2 files changed, 23 insertions(+), 65 deletions(-)

diff --git a/App/RobobinApp/ViewModels/ConnectionPageViewModel.cs b/App/RobobinApp/ViewModels/ConnectionPageViewModel.cs
index d13f6ddd..0166490e 100644
--- a/App/RobobinApp/ViewModels/ConnectionPageViewModel.cs
+++ b/App/RobobinApp/ViewModels/ConnectionPageViewModel.cs
@@ -341,42 +341,26 @@ namespace RobobinApp.ViewModels
                 await _adapter.StopScanningForDevicesAsync();
                 Debug.WriteLine("Stopped scanning for devices.");
                 IsConnected = true;
+
+                // Connect to the selected device
                 _connectedDevice = await TryConnectAsync(Guid.Parse(SelectedDevice.MacAddress));
 
                 Debug.WriteLine($"Successfully connected to {SelectedDevice.Name}.");
+
+                // Try to get services
                 var services = await _connectedDevice.GetServicesAsync();
 
-                foreach (var service in services)
+                if (services != null && services.Count > 0)
                 {
-                    Debug.WriteLine($"Service: ID={service.Id}, Name={service.Name}");
-
-                    // Check if the service is the UART service
-                    if (service.Id == Guid.Parse("6e400001-b5a3-f393-e0a9-e50e24dcca9e"))
+                    foreach (var service in services)
                     {
-                        Debug.WriteLine("Found UART service!");
-
-                        // Get the characteristics of the UART service
-                        var characteristics = await service.GetCharacteristicsAsync();
-                        foreach (var characteristic in characteristics)
-                        {
-                            Debug.WriteLine($"Characteristic: ID={characteristic.Id}, Properties={characteristic.Properties}");
-
-                            if (characteristic.Id == Guid.Parse("6e400002-b5a3-f393-e0a9-e50e24dcca9e"))
-                            {
-                                IsWifiNetworkSelectionVisible = true;
-                                Debug.WriteLine("Found RX characteristic (for writing data)");
-                                // Convert the string to a byte array
-                                byte[] data = System.Text.Encoding.UTF8.GetBytes("Hello World");
-                                // Write to the characteristic
-                                await characteristic.WriteAsync(data);
-                            }
-                            else if (characteristic.Id == Guid.Parse("6e400003-b5a3-f393-e0a9-e50e24dcca9e"))
-                            {
-                                Debug.WriteLine("Found TX characteristic (for notifications)");
-                            }
-                        }
+                        Debug.WriteLine($"Service: ID={service.Id}, Name={service.Name}");
                     }
                 }
+                else
+                {
+                    Debug.WriteLine("No services found.");
+                }
             }
             catch (DeviceConnectionException ex)
             {
@@ -398,6 +382,7 @@ namespace RobobinApp.ViewModels
         }
 
 
+
         private async void OnDisconnect()
         {
             if (_connectedDevice != null)
diff --git a/ButtonControls/RPiBluetooth.py b/ButtonControls/RPiBluetooth.py
index 5ad351d4..cb10a936 100644
--- a/ButtonControls/RPiBluetooth.py
+++ b/ButtonControls/RPiBluetooth.py
@@ -1,62 +1,35 @@
 import dbus
+import dbus.service
 from dbus.mainloop.glib import DBusGMainLoop
 from gi.repository import GLib
 
-ADVERTISING_UUID = '00001801-0000-1000-8000-00805f9b34fb'
+# Define a UUID for your service
+SERVICE_UUID = '00001801-0000-1000-8000-00805f9b34fb'
 
-def register_ad_cb():
-    print("Advertisement registered")
-
-def register_ad_error_cb(error):
-    print(f"Failed to register advertisement: {error}")
-
-def register_advertisement(adapter, advertisement):
-    ad_manager = dbus.Interface(adapter, 'org.bluez.LEAdvertisingManager1')
-    ad_manager.RegisterAdvertisement(advertisement.get_path(), {},
-                                     reply_handler=register_ad_cb,
-                                     error_handler=register_ad_error_cb)
-
-class BLEAdvertisement(dbus.service.Object):
+class BLEService(dbus.service.Object):
     def __init__(self, bus, index):
-        self.path = f"/org/bluez/example/advertisement{index}"
+        self.path = f"/org/bluez/example/service{index}"
         self.props = {
-            'Type': dbus.String('peripheral'),
-            'ServiceUUIDs': dbus.Array([dbus.String(ADVERTISING_UUID)]),
-            'LocalName': dbus.String('MyRaspberryPi')
+            'UUID': dbus.String(SERVICE_UUID),
+            'Primary': dbus.Boolean(True),
         }
         super().__init__(bus, self.path)
 
-    def get_path(self):
-        return dbus.ObjectPath(self.path)
-
-    @dbus.service.method('org.bluez.LEAdvertisement1', in_signature='', out_signature='a{sv}')
+    @dbus.service.method('org.bluez.GattService1', in_signature='', out_signature='a{sv}')
     def GetProperties(self):
         return self.props
 
-    @dbus.service.method('org.bluez.LEAdvertisement1', in_signature='', out_signature='')
+    @dbus.service.method('org.bluez.GattService1', in_signature='', out_signature='')
     def Release(self):
         print(f"{self.path}: Released")
 
 def main():
     DBusGMainLoop(set_as_default=True)
     bus = dbus.SystemBus()
-    
-    # Access the Bluetooth adapter
-    adapter = dbus.Interface(bus.get_object('org.bluez', '/org/bluez/hci0'), 'org.bluez.Adapter1')
-
-    # Make sure the adapter is powered on
-    adapter_props = dbus.Interface(bus.get_object('org.bluez', '/org/bluez/hci0'), 'org.freedesktop.DBus.Properties')
-    adapter_props.Set('org.bluez.Adapter1', 'Powered', dbus.Boolean(1))
 
-    # Create the BLE advertisement and register it
-    advertisement = BLEAdvertisement(bus, 0)
-    ad_manager = dbus.Interface(bus.get_object('org.bluez', '/org/bluez/hci0'), 'org.bluez.LEAdvertisingManager1')
-    
-    ad_manager.RegisterAdvertisement(advertisement.get_path(), {},
-                                     reply_handler=register_ad_cb,
-                                     error_handler=register_ad_error_cb)
+    service = MyBLEService(bus, 0)
 
-    print("BLE Advertising started. Press Ctrl+C to stop.")
+    print("BLE Service running. Press Ctrl+C to stop.")
     mainloop = GLib.MainLoop()
     mainloop.run()
 
-- 
GitLab