BLE设备(rfduino)配对求助:已实现设备发现功能
看起来你已经成功实现了RFduino的BLE设备发现功能,很棒!接下来咱们聊聊如何完成配对流程,针对你使用的Windows Bluetooth LE API,我整理了具体的步骤和关键代码:
一、先从广告事件中获取完整的蓝牙设备对象
你当前的代码只记录了设备名称,要发起配对得先拿到BluetoothDevice实例,在OnAdvertisementReceived方法里可以补充这部分逻辑:
private async void OnAdvertisementReceived(BluetoothLEAdvertisementWatcher watcher, BluetoothLEAdvertisementReceivedEventArgs eventArgs) { var deviceName = eventArgs.Advertisement.LocalName; if (!string.IsNullOrEmpty(deviceName) && !items.Contains(deviceName)) { items.Add(deviceName); // 通过蓝牙地址获取设备对象,用于后续配对 BluetoothDevice bleDevice = await BluetoothDevice.FromBluetoothAddressAsync(eventArgs.BluetoothAddress); // 可以把bleDevice存储到全局集合中,方便点击列表项时发起配对 } }
二、发起配对请求并处理结果
拿到BluetoothDevice后,就可以调用配对API,这里要注意RFduino通常不需要PIN码,设置对应的保护级别即可:
private async Task PairTargetDevice(BluetoothDevice targetDevice) { // 先判断是否已经配对 if (targetDevice.DeviceInformation.Pairing.IsPaired) { Debug.WriteLine("该设备已配对,无需重复操作"); return; } // 设置配对保护级别,RFduino一般用None即可 var pairingSettings = DevicePairingProtectionLevel.None; // 发起配对请求 DevicePairingResult pairingResult = await targetDevice.DeviceInformation.Pairing.PairAsync(pairingSettings); // 根据配对结果做对应处理 switch (pairingResult.Status) { case DevicePairingResultStatus.Paired: Debug.WriteLine("配对成功!"); // 配对成功后就可以连接GATT服务进行数据交互了 break; case DevicePairingResultStatus.Failed: Debug.WriteLine($"配对失败:{pairingResult.ErrorMessage}"); break; case DevicePairingResultStatus.Canceled: Debug.WriteLine("配对操作被取消"); break; // 其他状态可按需扩展处理 } }
三、可选:监听配对状态变化
如果需要实时感知配对状态的变更,可以注册对应的事件:
// 在获取到BluetoothDevice后注册事件 targetDevice.DeviceInformation.Pairing.PairingStatusChanged += OnPairingStatusChanged; private void OnPairingStatusChanged(DeviceInformationPairing sender, object args) { switch (sender.PairingStatus) { case DevicePairingStatus.Paired: // 配对完成后的逻辑,比如更新UI提示 break; case DevicePairingStatus.NotPaired: // 配对断开或未配对的逻辑 break; } }
四、关键注意事项
- 权限配置:确保你的应用在
Package.appxmanifest中添加了蓝牙相关能力,比如bluetooth和bluetooth.genericAttributeProfile,否则会有权限问题。 - 设备配对模式:部分BLE设备需要手动进入配对模式才能被配对,确认你的RFduino已经处于可配对状态。
- 异常捕获:配对过程中可能遇到设备离线、蓝牙模块异常等情况,记得在代码中添加
try-catch块处理异常。
内容的提问来源于stack exchange,提问作者Yann Kang
相关产品推荐
相关产品推荐

