Search code examples
bluetooth-lowenergywindows-runtimec++-winrt

c++ winrt BluetoothLEDevice::FromIdAsync() results in Access is denied


I am trying to write a c++ winrt application to connect to a Bluetooth LE device similar to the Microsoft example of BluetoothLE. In the example I can connect to the Bluetooth device. However, when I am trying to create a new c++ winrt application with the same code, I am receiving the exception: 80070005 Access is denied.

In both application, I placed a button in the MainPage.xaml and added the following code to the MainPage.cpp file:

fire_and_forget MainPage::ClickHandler(IInspectable const&, RoutedEventArgs const&)
{
Windows::Devices::Bluetooth::BluetoothLEDevice bluetoothLeDevice2{ nullptr };

        try {
         
            bluetoothLeDevice2 = co_await Windows::Devices::Bluetooth::BluetoothLEDevice::FromIdAsync(L"BluetoothLE#BluetoothLEd4:3b:04:bc:61:d1-88:33:14:d9:5b:88");
    
            if (bluetoothLeDevice2 == nullptr)
            {
                LogOnConsole(L"No connection.");
            }
        }
        catch (hresult_error & ex)
        {
            if (ex.to_abi() == HRESULT_FROM_WIN32(ERROR_DEVICE_NOT_AVAILABLE))
            {
                LogOnConsole(L"Bluetooth radio is not on.");
            }
            else
            {
                throw;
            }
        }

}

In the example of Microsoft it works but in my own application bluetoothLeDevice2 is nullptr.

I compared both application and noted that my application uses a newer winrt library, but I do not know how to fix my code.


Solution

  • UWP runs in a sandbox, if you want to use Bluetooth in UWP, you need to declare the bluetooth capability in the Package.appxmanifest.

    <Capabilities> <DeviceCapability Name="bluetooth" /> </Capabilities>