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

Now there shouldn't be a windows problem with the bluetooth.

parent cbe29e19
No related branches found
No related tags found
1 merge request!1App now has a basic structure and BLE support
This commit is part of merge request !1. Comments created here will be created in the context of that merge request.
......@@ -16,6 +16,7 @@ Global
{6D394E71-6C39-4FAC-A1D4-054609783EFF}.Debug|Any CPU.Deploy.0 = Debug|Any CPU
{6D394E71-6C39-4FAC-A1D4-054609783EFF}.Release|Any CPU.ActiveCfg = Release|Any CPU
{6D394E71-6C39-4FAC-A1D4-054609783EFF}.Release|Any CPU.Build.0 = Release|Any CPU
{6D394E71-6C39-4FAC-A1D4-054609783EFF}.Release|Any CPU.Deploy.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
......
......@@ -10,4 +10,7 @@
<uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />
<uses-permission android:name="android.permission.BLUETOOTH_PRIVILEGED" />
<uses-permission android:name="android.permission.BLUETOOTH_SCAN" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
</manifest>
\ No newline at end of file
......@@ -41,6 +41,7 @@
<Capabilities>
<rescap:Capability Name="runFullTrust" />
<DeviceCapability Name="bluetooth" />
</Capabilities>
</Package>
......@@ -12,4 +12,5 @@
<dpiAwareness xmlns="http://schemas.microsoft.com/SMI/2016/WindowsSettings">PerMonitorV2, PerMonitor</dpiAwareness>
</windowsSettings>
</application>
</assembly>
......@@ -10,9 +10,18 @@
<PropertyGroup Condition="'$(Configuration)|$(TargetFramework)|$(Platform)'=='Debug|net8.0-android|AnyCPU'">
<DebuggerFlavor>ProjectDebugger</DebuggerFlavor>
</PropertyGroup>
<PropertyGroup Condition="'$(TargetPlatformIdentifier)'=='iOS'">
<RuntimeIdentifier>ios-arm64</RuntimeIdentifier>
<PlatformTarget>arm64</PlatformTarget>
</PropertyGroup>
<ItemGroup>
<MauiXaml Update="Views\ConnectionPage.xaml">
<SubType>Designer</SubType>
</MauiXaml>
</ItemGroup>
<ItemGroup>
<None Update="Platforms\Windows\Package.appxmanifest">
<SubType>Designer</SubType>
</None>
</ItemGroup>
</Project>
\ No newline at end of file
using System.Collections.ObjectModel;
using System.Diagnostics; // Add this for Debug.WriteLine
using System.Windows.Input;
using Microsoft.Maui.Controls;
using RobobinApp.Views;
using Plugin.BLE;
using Plugin.BLE.Abstractions.Contracts;
using Plugin.BLE.Abstractions.Exceptions;
//using Microsoft.Maui.E
using Plugin.BLE.Abstractions.EventArgs;
namespace RobobinApp.ViewModels
{
......@@ -30,7 +32,11 @@ namespace RobobinApp.ViewModels
_bluetoothLE = CrossBluetoothLE.Current;
_adapter = _bluetoothLE.Adapter;
// Subscribe to the DeviceDiscovered event
_adapter.DeviceDiscovered += OnDeviceDiscovered;
// Check and request Bluetooth permissions before scanning
Debug.WriteLine("Checking and requesting Bluetooth permissions.");
CheckAndRequestBluetoothPermissions();
}
......@@ -44,31 +50,35 @@ namespace RobobinApp.ViewModels
}
}
private async void CheckAndRequestBluetoothPermissions()
{
// Check if the Bluetooth scan permission is granted
Debug.WriteLine("Checking Bluetooth permissions.");
var status = await Permissions.CheckStatusAsync<Permissions.Bluetooth>();
if (status != PermissionStatus.Granted)
{
Debug.WriteLine("Bluetooth permission not granted, requesting permission.");
// Request permission
status = await Permissions.RequestAsync<Permissions.Bluetooth>();
}
if (status == PermissionStatus.Granted)
{
Debug.WriteLine("Bluetooth permission granted, proceeding to scan devices.");
// Permission granted, proceed with scanning devices
ScanDevices();
}
else
{
// Permission denied, handle accordingly
Debug.WriteLine("Bluetooth permission denied.");
await Application.Current.MainPage.DisplayAlert("Permissions", "Bluetooth scan permission is required to discover devices.", "OK");
}
}
public async Task OnGoHome()
{
Debug.WriteLine("Navigating to home page.");
await Application.Current.MainPage.Navigation.PushAsync(new MainPage());
}
......@@ -76,63 +86,96 @@ namespace RobobinApp.ViewModels
{
// Clear the current list of devices before scanning
BluetoothDevices.Clear();
Debug.WriteLine("Cleared existing Bluetooth devices. Starting scan...");
try
{
if (!_bluetoothLE.IsAvailable)
{
Debug.WriteLine("Bluetooth is not available.");
await Application.Current.MainPage.DisplayAlert("Bluetooth", "Bluetooth is not available.", "OK");
return;
}
if (!_bluetoothLE.IsOn)
{
Debug.WriteLine("Bluetooth is turned off.");
await Application.Current.MainPage.DisplayAlert("Bluetooth", "Please turn on Bluetooth.", "OK");
return;
}
_adapter.DeviceDiscovered += (s, a) =>
{
// Add discovered devices to the list
BluetoothDevices.Add(new BluetoothDevice
{
Name = a.Device.Name ?? "Unknown Device",
MacAddress = a.Device.Id.ToString()
});
};
// Start scanning for devices
Debug.WriteLine("Starting scanning for devices...");
await _adapter.StartScanningForDevicesAsync();
}
catch (Exception ex)
{
Debug.WriteLine($"Error during scanning: {ex.Message}");
await Application.Current.MainPage.DisplayAlert("Error", $"Failed to scan for devices: {ex.Message}", "OK");
}
}
// New method to handle discovered devices
private void OnDeviceDiscovered(object sender, DeviceEventArgs e)
{
Debug.WriteLine($"Discovered device: {e.Device.Name} ({e.Device.Id})");
var bluetoothDevice = new BluetoothDevice
{
Name = e.Device.Name,
MacAddress = e.Device.Id.ToString() // Ensure this aligns with how you handle MAC addresses
};
// Check if the device is already in the list to avoid duplicates
if (!BluetoothDevices.Any(d => d.MacAddress == bluetoothDevice.MacAddress))
{
// Use the Device.BeginInvokeOnMainThread to add the device on the UI thread
Device.BeginInvokeOnMainThread(() =>
{
BluetoothDevices.Add(bluetoothDevice);
Debug.WriteLine($"Added device to list: {bluetoothDevice.Name} ({bluetoothDevice.MacAddress})");
});
}
}
private async void OnConnect()
{
if (SelectedDevice == null) return;
if (SelectedDevice == null)
{
Debug.WriteLine("No device selected for connection.");
return;
}
// Logic to connect to the selected Bluetooth device
Debug.WriteLine($"Attempting to connect to {SelectedDevice.Name}...");
await Application.Current.MainPage.DisplayAlert("Connection", $"Connecting to {SelectedDevice.Name}...", "OK");
try
{
// Stop scanning before attempting connection
await _adapter.StopScanningForDevicesAsync();
Debug.WriteLine("Stopped scanning for devices.");
// Find the device using the MAC address
var device = await _adapter.ConnectToKnownDeviceAsync(Guid.Parse(SelectedDevice.MacAddress));
// Display successful connection
Debug.WriteLine($"Successfully connected to {SelectedDevice.Name}.");
await Application.Current.MainPage.DisplayAlert("Connected", $"Connected to {SelectedDevice.Name}.", "OK");
}
catch (DeviceConnectionException ex)
{
// Handle connection failure
Debug.WriteLine($"Connection error: {ex.Message}");
await Application.Current.MainPage.DisplayAlert("Connection Error", $"Failed to connect: {ex.Message}", "OK");
}
catch (Exception ex)
{
Debug.WriteLine($"General connection error: {ex.Message}");
await Application.Current.MainPage.DisplayAlert("Connection Error", $"An error occurred: {ex.Message}", "OK");
}
}
}
......
......@@ -35,4 +35,5 @@
HorizontalOptions="Center"
VerticalOptions="End" />
</StackLayout>
</ContentPage>
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment