Как подключить и использовать bluetooth-гарнитуру в Windows с C# - PullRequest
0 голосов
/ 04 августа 2020

Я просто не могу получить Windows 10 для использования моего Jambra Evolve 65 с помощью моего кода.

Все работает нормально при использовании Windows 10 PopUp для сопряжения устройства Bluetooth. Я слышу и говорю через гарнитуру. Дело в том, что у меня нет explorer.exe, работающего в системе, где я хочу выполнить сопряжение и использовать гарнитуру. Так что мне нужно написать что-нибудь самостоятельно.

Я уже могу подключить гарнитуру к своему приложению. Но сопряжение теряется, как только я закрываю приложение.

Хотя оно сопряжено, оно не распознается как аудиоустройство в Windows. Поэтому я не могу использовать его для ввода / вывода звука.

Вот текущее состояние моего кода:

Частные поля и их инициализация

private BluetoothClient _bluetoothClient;
private BluetoothEndPoint _bluetoothEndPoint;
private BluetoothComponent _bluetoothComponent;
private List<BluetoothDeviceInfo> _btDevicesList;

_bluetoothEndPoint = new BluetoothEndPoint(BluetoothAddress.Parse("local MAC of BT USB Stick"), BluetoothService.Headset);
_bluetoothClient = new BluetoothClient(_bluetoothEndPoint);
_bluetoothComponent = new BluetoothComponent(_bluetoothClient);
_bluetoothComponent.DiscoverDevicesProgress += BluetoothComponentOnDiscoverDevicesProgress;
_bluetoothComponent.DiscoverDevicesComplete += BluetoothComponentOnDiscoverDevicesComplete;
authenticator = new BluetoothWin32Authentication(handleAuthRequests);
_bluetoothComponent.DiscoverDevicesAsync(255, true, true, true, true, null);

обработчики событий

private void BluetoothComponentOnDiscoverDevicesProgress(object sender, DiscoverDevicesEventArgs e)
{
    _btDevicesList.AddRange(e.Devices);
    foreach (BluetoothDeviceInfo bluetoothDeviceInfo in _btDevicesList)
    {
        Log.Debug(bluetoothDeviceInfo.DeviceName);

        DeviceList.Add(new BtDevice() { Name = bluetoothDeviceInfo.DeviceName, Connected = bluetoothDeviceInfo.Connected.ToString(), Address = bluetoothDeviceInfo.DeviceAddress, BtDeviceInfo = bluetoothDeviceInfo, Services = bluetoothDeviceInfo.ClassOfDevice.Service.ToString() });
    }
    Log.Info($"Found {_btDevicesList.Count} Bluetooth devices:");
}

private void BluetoothComponentOnDiscoverDevicesComplete(object sender, DiscoverDevicesEventArgs e)
{
    Busy = false;
}

private void handleAuthRequests(object sender, BluetoothWin32AuthenticationEventArgs e)
{
    e.Confirm = true;
}

Вспомогательный метод

public void PairDevice()
{
    // here I have an UI where to see all discovered bluetooth hardware. The selected one will be paired
    var selectedDevice = DeviceList.FirstOrDefault(n => n.IsSelected);
    if (selectedDevice == null) return;

    BluetoothSecurity.PairRequest(selectedDevice.Address, null);
    selectedDevice.BtDeviceInfo.SetServiceState(BluetoothService.Headset, true);
}
...