Skip to content
Snippets Groups Projects
Commit 7483fcb1 authored by Paul-Winpenny's avatar Paul-Winpenny
Browse files

Task cancelled is less of a problem now.

parent ef2fea87
No related branches found
No related tags found
No related merge requests found
......@@ -40,7 +40,11 @@
</Applications>
<Capabilities>
<Capability Name="internetClient" />
<rescap:Capability Name="runFullTrust" />
<rescap:Capability Name="bluetooth" />
<rescap:Capability Name="bluetoothGenericAttributeProfile" />
<rescap:Capability Name="location" />
</Capabilities>
</Package>
......@@ -14,6 +14,11 @@
<RuntimeIdentifier>ios-arm64</RuntimeIdentifier>
<PlatformTarget>arm64</PlatformTarget>
</PropertyGroup>
<ItemGroup>
<AppxManifest Update="Platforms\Windows\Package.appxmanifest">
<SubType>Designer</SubType>
</AppxManifest>
</ItemGroup>
<ItemGroup>
<MauiXaml Update="Views\ConnectionPage.xaml">
<SubType>Designer</SubType>
......
......@@ -154,6 +154,11 @@ namespace RobobinApp.ViewModels
{
try
{
if (SelectedWifiNetwork == null)
{
Debug.WriteLine("No Network Selected");
return ;
}
var SSID = SelectedWifiNetwork.SSID;
var result = WriteOperationAsync("CONNECT", SSID + "," + password);
......@@ -372,66 +377,36 @@ namespace RobobinApp.ViewModels
try
{
//await _adapter.StopScanningForDevicesAsync();
IsConnected = true;
_connectedDevice = await TryConnectAsync(Guid.Parse(SelectedDevice.MacAddress));
if (_connectedDevice != null)
{
Debug.WriteLine($"Successfully connected to {SelectedDevice.Name}.");
//
var services = await _connectedDevice.GetServicesAsync();
Debug.WriteLine("Services gotten");
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)
{
Debug.WriteLine($"Service: ID={service.Id}, Name={service.Name}");
if (service.Id.Equals(Guid.Parse("00000001-710e-4a5b-8d75-3e5b444bc3cf")) )
if (service.Id.Equals(Guid.Parse(SendReceiveServiceUUID)))
{
Debug.WriteLine("Found RW service");
Debug.WriteLine("Found Read/Write service");
ReadWriteService = service;
ScanForWifiNetworks();
return;
/***var characteristics = await service.GetCharacteristicsAsync();
foreach (var characteristic in characteristics)
{
var descriptors = await characteristic.GetDescriptorsAsync();
foreach (var descriptor in descriptors)
{
var descriptorValue = await descriptor.ReadAsync();
var descriptorValueString = Encoding.UTF8.GetString(descriptorValue);
Debug.WriteLine($"Descriptor: {descriptor.Id} | Value: {descriptorValueString}");
}
Debug.WriteLine($"{characteristic.Uuid} |{characteristic.Name}");
if (characteristic.Name.Equals(readCharacteristicName))
{
ReadCharacteristic = characteristic;
var result = await ReadOperationAsync();
var characteristics = await ReadWriteService.GetCharacteristicsAsync();
}
else if (characteristic.Name.Equals(writeCharacteristicName))
{
WriteCharacteristic = characteristic;
const string command = "SCAN";
//await WriteOperationAsync(command);
ReadCharacteristic = await ReadWriteService.GetCharacteristicAsync(Guid.Parse(rxUUID));
WriteCharacteristic = await ReadWriteService.GetCharacteristicAsync(Guid.Parse(wxUUID));
Debug.WriteLine("Characteristics initialized successfully.");
ScanForWifiNetworks();
}
}**/
break;
}
}
if (ReadWriteService == null || ReadCharacteristic == null || WriteCharacteristic == null)
{
Debug.WriteLine("Failed to initialize BLE service or characteristics.");
OnDisconnect();
}
}
else
{
......@@ -443,42 +418,31 @@ namespace RobobinApp.ViewModels
{
Debug.WriteLine($"Connection error: {ex.Message}");
await Application.Current.MainPage.DisplayAlert("Connection Error", $"Failed to connect: {ex.Message}", "OK");
OnDisconnect();
}
catch (Exception ex)
{
Debug.WriteLine($"General connection error: {ex.Message}");
await Application.Current.MainPage.DisplayAlert("Connection Error", $"An error occurred: {ex.Message}", "OK");
}
finally
{
// Ensure we reset connection state
if (_connectedDevice == null)
{
IsConnected = false;
// Consider resetting any other related UI state
}
OnDisconnect();
}
}
private async Task<string> ReadOperationAsync(int retryCount = 3)
{
if (ReadWriteService == null || !IsConnected)
if (ReadCharacteristic == null || !IsConnected)
{
Debug.WriteLine("Read characteristic is not set or device is not connected.");
Debug.WriteLine("Read characteristic is not initialized or device is not connected.");
return "Failure";
}
ReadCharacteristic = await ReadWriteService.GetCharacteristicAsync(Guid.Parse(rxUUID));
Debug.WriteLine($"READ COMMAND : {ReadCharacteristic.Uuid}");
for (int attempt = 1; attempt <= retryCount; attempt++)
{
try
{
Debug.WriteLine($"Attempt {attempt}: Reading from characteristic {ReadCharacteristic.Uuid}");
Debug.WriteLine($"Attempt {attempt}: Reading from characteristic");
var temperatureData = await ReadCharacteristic.ReadAsync();
var temperatureValue = System.Text.Encoding.UTF8.GetString(temperatureData.data);
var temperatureValue = Encoding.UTF8.GetString(temperatureData.data);
Debug.WriteLine($"Temperature Value: {temperatureValue}");
return temperatureValue;
}
......@@ -487,12 +451,16 @@ namespace RobobinApp.ViewModels
Debug.WriteLine($"Read attempt {attempt} failed: {ex.Message}");
if (attempt == retryCount)
{
Debug.WriteLine("Max retry attempts reached for reading.");
throw;
} else
Debug.WriteLine("Max retry attempts reached for reading. Attempting reconnection...");
if (await TryReconnect())
{
await Task.Delay(1000);
Debug.WriteLine("Reconnected successfully. Retrying read operation.");
return await ReadOperationAsync(retryCount); // Retry after reconnection
}
Debug.WriteLine("Reconnection failed. Returning failure.");
return "Failure";
}
await Task.Delay(1000);
}
}
return "Failure";
......@@ -500,16 +468,15 @@ namespace RobobinApp.ViewModels
private async Task<string> WriteOperationAsync(string command, string arguments = "", int retryCount = 3)
{
if (ReadWriteService == null)
if (WriteCharacteristic == null || !IsConnected)
{
Debug.WriteLine("Write characteristic is not set.");
Debug.WriteLine("Write characteristic is not initialized or device is not connected.");
return "Failure";
}
//Get Characteristic
WriteCharacteristic = await ReadWriteService.GetCharacteristicAsync(Guid.Parse(wxUUID));
string joinedData = command + ":" + arguments;
Debug.WriteLine($"WRITE COMMAND {joinedData}, UUID: {WriteCharacteristic}");
byte[] data = System.Text.Encoding.UTF8.GetBytes(joinedData);
string joinedData = $"{command}:{arguments}";
byte[] data = Encoding.UTF8.GetBytes(joinedData);
Debug.WriteLine($"WRITE COMMAND {joinedData}, UUID: {WriteCharacteristic.Uuid}");
for (int attempt = 1; attempt <= retryCount; attempt++)
{
......@@ -524,18 +491,66 @@ namespace RobobinApp.ViewModels
Debug.WriteLine($"Write attempt {attempt} failed: {ex.Message}");
if (attempt == retryCount)
{
Debug.WriteLine("Max retry attempts reached for writing.");
throw;
} else
Debug.WriteLine("Max retry attempts reached for writing. Attempting reconnection...");
if (await TryReconnect())
{
await Task.Delay(1000);
Debug.WriteLine("Reconnected successfully. Retrying write operation.");
return await WriteOperationAsync(command, arguments, retryCount); // Retry after reconnection
}
Debug.WriteLine("Reconnection failed. Returning failure.");
return "Failure";
}
await Task.Delay(1000);
}
}
return "Failure";
}
private async Task<bool> TryReconnect()
{
if (SelectedDevice == null)
{
Debug.WriteLine("No device is selected for reconnection.");
return false;
}
Debug.WriteLine($"Attempting to reconnect to {SelectedDevice.Name}, MAC Address {SelectedDevice.MacAddress}");
try
{
IsConnected = false;
_connectedDevice = await TryConnectAsync(Guid.Parse(SelectedDevice.MacAddress));
if (_connectedDevice != null)
{
Debug.WriteLine($"Successfully reconnected to {SelectedDevice.Name}.");
// Re-initialize services and characteristics
var services = await _connectedDevice.GetServicesAsync();
ReadWriteService = services.FirstOrDefault(s => s.Id.Equals(Guid.Parse(SendReceiveServiceUUID)));
if (ReadWriteService != null)
{
ReadCharacteristic = await ReadWriteService.GetCharacteristicAsync(Guid.Parse(rxUUID));
WriteCharacteristic = await ReadWriteService.GetCharacteristicAsync(Guid.Parse(wxUUID));
IsConnected = true;
return true;
}
}
else
{
Debug.WriteLine("Failed to reconnect to the device.");
return false;
}
}
catch (Exception ex)
{
Debug.WriteLine($"Reconnection error: {ex.Message}");
return false;
}
return false;
}
private async void OnDisconnect()
{
......@@ -544,13 +559,9 @@ namespace RobobinApp.ViewModels
try
{
Debug.WriteLine($"Attempting to disconnect from {_connectedDevice.Name}");
ResetState();
await _adapter.DisconnectDeviceAsync(_connectedDevice);
Debug.WriteLine("Disconnected successfully.");
IsWifiNetworkSelectionVisible = false;
ResetState();
IsConnected = false;
ScanDevices();
await Application.Current.MainPage.DisplayAlert("Disconnected", "Device disconnected successfully.", "OK");
}
catch (Exception ex)
......@@ -574,11 +585,11 @@ namespace RobobinApp.ViewModels
BluetoothDevices.Clear();
ReadCharacteristic = null;
WriteCharacteristic = null;
ReadWriteService = null;
IsWifiNetworkSelectionVisible = false;
}
}
}
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment