/// <summary> /// 连接到指定的蓝牙设备的RFComm服务 /// </summary> /// <param name="BL">要连接到的设备</param> /// <returns>主机对象的规范名称</returns> public async Task <string> ConnectToRfcommServiceAsync(BluetoothDeivceData BL) { if (BL == null) { throw new ArgumentNullException(nameof(BL), "Parameter could not be null"); } try { using (Windows.Devices.Bluetooth.BluetoothDevice Device = await Windows.Devices.Bluetooth.BluetoothDevice.FromIdAsync(BL.Id)) { RfcommDeviceServicesResult Services = await Device.GetRfcommServicesForIdAsync(RfcommServiceId.ObexObjectPush); if (Services.Services.Any()) { return(Services.Services.Select((Service) => Service.ConnectionHostName?.CanonicalName).Where((Name) => !string.IsNullOrEmpty(Name)).FirstOrDefault()); } else { throw new Exception(Globalization.GetString("BluetoothUI_Tips_Text_3")); } } } catch { throw new Exception(Globalization.GetString("BluetoothUI_Tips_Text_2")); } }
/// <summary> /// 异步启动蓝牙的配对过程 /// </summary> /// <param name="DeviceInfo"></param> /// <returns></returns> private async Task PairAsync(BluetoothDeivceData Device) { try { if (Device.DeviceInfo.Pairing.CanPair) { DeviceInformationCustomPairing CustomPairing = Device.DeviceInfo.Pairing.Custom; CustomPairing.PairingRequested += CustomPairInfo_PairingRequested; DevicePairingResult PairResult = await CustomPairing.PairAsync(DevicePairingKinds.ConfirmOnly | DevicePairingKinds.ConfirmPinMatch, DevicePairingProtectionLevel.EncryptionAndAuthentication); CustomPairing.PairingRequested -= CustomPairInfo_PairingRequested; if (PairResult.Status == DevicePairingResultStatus.Paired) { Device.Update(); } else { await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { Tips.Text = Globalization.GetString("BluetoothUI_Tips_Text_4"); Tips.Visibility = Visibility.Visible; }); } } else { LogTracer.Log($"Unable pair with Bluetooth device: \"{Device.Name}\", reason: CanPair property return false"); } } catch (Exception ex) { LogTracer.Log(ex, $"Unable pair with Bluetooth device: \"{Device.Name}\""); } }