From a2f655a2b12af4a0f1b682df48b3948e9dc9296d Mon Sep 17 00:00:00 2001
From: Paul-Winpenny <92634321+Paul-Winpenny@users.noreply.github.com>
Date: Fri, 25 Oct 2024 16:20:43 +0100
Subject: [PATCH] okay so it looks like the problem with  the "ObjectDisposed"
 exception is related to accessing characteristics after they have been
 discarded, solution might be to have the "SCAN" be sent dring the scan wifi
 networks method, and just use the service saved instead of saving
 charactersitics.

---
 App/RobobinApp/App.xaml.cs                    | 44 ++++++++----
 .../ViewModels/ConnectionPageViewModel.cs     | 72 +++++++++++++------
 2 files changed, 81 insertions(+), 35 deletions(-)

diff --git a/App/RobobinApp/App.xaml.cs b/App/RobobinApp/App.xaml.cs
index 0feb8e72..5f31488a 100644
--- a/App/RobobinApp/App.xaml.cs
+++ b/App/RobobinApp/App.xaml.cs
@@ -1,29 +1,43 @@
 using Microsoft.Extensions.Logging;
+using Plugin.BLE;
+using Plugin.BLE.Abstractions.Contracts;
+
 namespace RobobinApp;
 
 public partial class App : Application
 {
+    public static IBluetoothLE BluetoothLE { get; private set; }
+    public static IAdapter BluetoothAdapter { get; private set; }
+
     public App()
     {
         InitializeComponent();
         ConfigureLogging();
+
+        // Initialize the Bluetooth adapter
+        InitializeBluetoothAdapter();
+
         MainPage = new AppShell();
     }
-        private void ConfigureLogging()
+
+    private void ConfigureLogging()
+    {
+        var loggerFactory = LoggerFactory.Create(builder =>
         {
-            // Create a LoggerFactory
-            var loggerFactory = LoggerFactory.Create(builder =>
-            {
-                builder
-                    .AddConsole() 
-                    .AddDebug(); 
-            });
-
-            // Store the logger factory for later use
-            Logger = loggerFactory.CreateLogger<App>();
-        }
-
-        public ILogger<App> Logger { get; private set; }
-}
+            builder
+                .AddConsole()
+                .AddDebug();
+        });
+
+        Logger = loggerFactory.CreateLogger<App>();
+    }
 
+    private void InitializeBluetoothAdapter()
+    {
+        
+        BluetoothLE = CrossBluetoothLE.Current;
+        BluetoothAdapter = BluetoothLE.Adapter;
+    }
 
+    public ILogger<App> Logger { get; private set; }
+}
diff --git a/App/RobobinApp/ViewModels/ConnectionPageViewModel.cs b/App/RobobinApp/ViewModels/ConnectionPageViewModel.cs
index 265a9f81..7751a26a 100644
--- a/App/RobobinApp/ViewModels/ConnectionPageViewModel.cs
+++ b/App/RobobinApp/ViewModels/ConnectionPageViewModel.cs
@@ -72,6 +72,17 @@ namespace RobobinApp.ViewModels
                 OnPropertyChanged();
             }
         }
+        private IService _readWriteService;
+        public IService ReadWriteService
+        {
+            get => _readWriteService;
+            set
+            {
+                _readWriteService = value;
+                OnPropertyChanged();
+            }
+        }
+
 
         public ICharacteristic WriteCharacteristic
         {
@@ -115,8 +126,9 @@ namespace RobobinApp.ViewModels
         public ConnectionPageViewModel()
         {
 
-            _bluetoothLE = CrossBluetoothLE.Current;
-            _adapter = CrossBluetoothLE.Current.Adapter;
+
+            _bluetoothLE = App.BluetoothLE;
+            _adapter = App.BluetoothAdapter;
 
 
             BluetoothDevices = new ObservableCollection<BluetoothDevice>();
@@ -140,9 +152,17 @@ namespace RobobinApp.ViewModels
 
         private void OnSendWifiInfo(object obj)
         {
-            var SSID = SelectedWifiNetwork.SSID;
-            var result = WriteOperationAsync("CONNECT", SSID + "," + password);
-            Debug.WriteLine($"Result: {result}");
+            try
+            {
+                var SSID = SelectedWifiNetwork.SSID;
+
+                var result = WriteOperationAsync("CONNECT", SSID + "," + password);
+                Debug.WriteLine($"Result: {result}");
+            }
+            catch (Exception e)
+            {
+                Debug.WriteLine("There is a problem sending wifi info ", e.Message);
+            }
         }
 
         private async Task PingPiASync()
@@ -163,8 +183,7 @@ namespace RobobinApp.ViewModels
             WifiNetworks.Clear();
             Debug.WriteLine("Retrieving Wifi networks from readCharacteristic");
 
-            //Delay 5 seconds
-            await Task.Delay(2500);
+      
 
             var networks = await ReadOperationAsync();
             //var networks = "Network1\nNetwork2\nNetwork3"; // For testing
@@ -350,7 +369,7 @@ namespace RobobinApp.ViewModels
 
             try
             {
-                await _adapter.StopScanningForDevicesAsync();
+                //await _adapter.StopScanningForDevicesAsync();
                 IsConnected = true;
 
                 _connectedDevice = await TryConnectAsync(Guid.Parse(SelectedDevice.MacAddress));
@@ -364,6 +383,8 @@ namespace RobobinApp.ViewModels
                     IsWifiNetworkSelectionVisible = true;
                     // Iterate through the discovered services
                     //var service = await _connectedDevice.GetServiceAsync(Guid.Parse("00000001-710e-4a5b-8d75-3e5b444bc3cf"));
+
+                    await Task.Delay(2000);
                     foreach (var service in services)
 
                     {
@@ -372,7 +393,10 @@ namespace RobobinApp.ViewModels
                         if (service.Id.Equals(Guid.Parse("00000001-710e-4a5b-8d75-3e5b444bc3cf")) )
                         {
                             Debug.WriteLine("Found RW service");
-                            var characteristics = await service.GetCharacteristicsAsync();
+                            ReadWriteService = service;
+                            ScanForWifiNetworks();
+                            return;
+                            /***var characteristics = await service.GetCharacteristicsAsync();
 
                             foreach (var characteristic in characteristics)
                             {
@@ -400,13 +424,10 @@ namespace RobobinApp.ViewModels
                                     ScanForWifiNetworks();
 
                                 }
-                            }
+                            }**/
                         }
                     }
-                    var transmissionService = services.FirstOrDefault(s => s.Id == Guid.Parse(SendReceiveServiceUUID));
-                    var readCharacteristic = await transmissionService.GetCharacteristicAsync(Guid.Parse(rxUUID));
 
-                    var result2 = await ReadOperationAsync();
 
                 }
                 else
@@ -441,9 +462,9 @@ namespace RobobinApp.ViewModels
 
         private async Task<string> ReadOperationAsync(int retryCount = 3)
         {
-            if (ReadCharacteristic == null)
+            if (ReadCharacteristic == null || !IsConnected)
             {
-                Debug.WriteLine("Read characteristic is not set.");
+                Debug.WriteLine("Read characteristic is not set or device is not connected.");
                 return "Failure";
             }
             Debug.WriteLine($"READ COMMAND : {ReadCharacteristic.Uuid}");
@@ -517,13 +538,11 @@ namespace RobobinApp.ViewModels
                 try
                 {
                     Debug.WriteLine($"Attempting to disconnect from {_connectedDevice.Name}");
+                    ResetState();
                     await _adapter.DisconnectDeviceAsync(_connectedDevice);
                     Debug.WriteLine("Disconnected successfully.");
                     IsWifiNetworkSelectionVisible = false;
-                    // Dispose of the device reference
-                    if (_connectedDevice != null)
-                    //    _connectedDevice.Dispose();
-                        _connectedDevice = null;
+                    ResetState();
                     IsConnected = false;
                     ScanDevices();
                     await Application.Current.MainPage.DisplayAlert("Disconnected", "Device disconnected successfully.", "OK");
@@ -539,8 +558,21 @@ namespace RobobinApp.ViewModels
                 Debug.WriteLine("No device to disconnect.");
             }
         }
-   
+
+        private void ResetState()
+        {
+            IsConnected = false;
+            SelectedDevice = null;
+            SelectedWifiNetwork = null;
+            WifiNetworks.Clear();
+            BluetoothDevices.Clear();
+            ReadCharacteristic = null;
+            WriteCharacteristic = null;
+            IsWifiNetworkSelectionVisible = false;
+
+        }
 
     }
 
+
 }
-- 
GitLab