我正试图写一个小的流甲板插件来连接我配对的耳机后,他们已经配对到另一个设备,还没有连接到我的电脑自动。我基本上想启动与在Windows 11设备列表中单击Connect
相同的过程。
我能列举我的设备,找到正确的设备根据设备ID,并确定是否已经连接,但是我不知道如何使音乐和聊天如果断开的连接。
这就是我所拥有的
string[] requestedProperties = {
"System.Devices.Aep.IsConnected",
};
var devices = await DeviceInformation.FindAllAsync(BluetoothDevice.GetDeviceSelector(), requestedProperties);
foreach (DeviceInformation di in devices) {
if (!di.Properties.ContainsKey("System.Devices.Aep.IsConnected")) {
continue;
}
if (di.Properties[ConnectedKey] is true) {
Debug.WriteLine($"Connected Device Name {di.Name}");
Debug.WriteLine($"Connected Device Id {di.Id}");
continue;
}
if ("<myHeadphonesBluetoothId>" == di.Id) {
// Not sure where to go at this point to initiate those connections
}
}
一直在谷歌几个小时没有任何成功,并给予一些尝试在AudioPlaybackConnection
,BluetoothDevice
,和RfcommDeviceService
类没有成功。
我最大的问题是对架构的误解,涉及到设备、服务等的工作方式。
我能够得到一个小样本应用程序的工作目标是net6.0-windows10.0.22000.0
const string targetDeviceId = "Bluetooth#Bluetooth00:00:00:00:00:00-00:00:00:0:0:00";
const int serialPortShortId = 0x1101;
using var streamSocket = new StreamSocket();
await EstablishConnection();
async ValueTask EstablishConnection() {
RfcommServiceId targetServiceId = RfcommServiceId.FromShortId(serialPortShortId);
BluetoothAdapter adapter = await BluetoothAdapter.GetDefaultAsync();
if (adapter is not null)
{
Radio btRadio = await adapter.GetRadioAsync();
if (btRadio.State == RadioState.Off)
{
await btRadio.SetStateAsync(RadioState.On);
Console.WriteLine("Bluetooth adapter was off. Turned it on.");
}
}
using BluetoothDevice btDevice = await BluetoothDevice.FromIdAsync(targetDeviceId);
btDevice.ConnectionStatusChanged += (sender, args) => Console.WriteLine("Bluetooth device connected");
RfcommDeviceServicesResult services = await btDevice.GetRfcommServicesForIdAsync(targetServiceId);
RfcommDeviceService service = services.Services.Single();
if (btDevice.ConnectionStatus != BluetoothConnectionStatus.Connected && service.DeviceAccessInformation.CurrentStatus == DeviceAccessStatus.Allowed) {
try {
await streamSocket.ConnectAsync(service.ConnectionHostName, service.ConnectionServiceName,
SocketProtectionLevel.BluetoothEncryptionAllowNullAuthentication);
}
catch (COMException e) when ((uint)e.HResult == 0x8007277C) {
Console.WriteLine("Bluetooth device is not on or in range.");
}
}
}
运行后,设备将连接,windows将初始化连接到它的麦克风和扬声器设备。