1. BluetoothLEDevice.GetGattServicesForUuidAsync 方法用于获取指定 UUID 的 GATT 服务。GATT(Generic Attribute Profile)是一种用于与蓝牙设备交换数据的通用协议,它将设备的数据组织成服务和特征(Characteristics),每个特征都有一个唯一的 UUID。
GattDeviceServicesResult result = await bluetoothLeDevice?.GetGattServicesForUuidAsync(ServiceUuid, bluetoothCacheMode);
上述代码中,我们使用 BluetoothLEDevice 对象的 GetGattServicesForUuidAsync 方法来获取指定 UUID 的 GATT 服务。ServiceUuid 是要查找的服务的 UUID,bluetoothCacheMode 则指定了服务的缓存模式。bluetoothCacheMode 参数控制是否使用缓存的方式获取服务信息,可以为以下值之一:
BluetoothCacheMode.Uncached:不使用缓存,直接从设备获取最新的服务信息。
BluetoothCacheMode.Cached:优先使用缓存,如果缓存中存在服务信息,则直接从缓存中获取,否则从设备获取。
2. 获取服务信息后,我们可以通过 GattDeviceServicesResult.Services 属性来获取返回的 GATT 服务列表。
GattDeviceService Service = result.Services[0];
上述代码中,我们从 GattDeviceServicesResult.Services 中获取第一个服务对象,并将其赋值给 Service 变量。这样,我们就可以通过 Service 对象来进一步操作该 GATT 服务,例如获取特定 UUID 的特征(Characteristics)信息。
var accessStatus = await Service.RequestAccessAsync();
用于请求对蓝牙设备的显式访问。这将调用设备同意,并且必须在 UI 线程上调用。
异步操作完成后,返回设备访问状态枚举值。
3.GattDeviceService.GetCharacteristicsForUuidAsync 方法用于获取指定 UUID 的 GATT 特征信息。
var result_Characteristics = await Service.GetCharacteristicsForUuidAsync(CharacteristicUuid, BluetoothCacheMode.Cached);
上述代码中,我们使用 GattDeviceService 对象的 GetCharacteristicsForUuidAsync 方法来获取指定 UUID 的 GATT 特征信息。CharacteristicUuid 是要查找的特征的 UUID,BluetoothCacheMode 则指定了特征的缓存模式,用法和之前解释的相同。
获取特征信息后,我们可以通过 GattCharacteristicsResult.Characteristics 属性来获取返回的 GATT 特征列表。
4.BluetoothLEDevice.FromBluetoothAddressAsync: 这是一个静态方法,用于通过蓝牙设备的蓝牙地址(Bluetooth Address)来获取一个 BluetoothLEDevice 对象。
它是从指定的蓝牙地址异步获取设备对象的方式。该方法返回一个代表蓝牙设备的 BluetoothLEDevice 对象,或者在连接失败时返回 null。
参数说明:
rootPage.bluetoothAddress: 要连接的蓝牙设备的蓝牙地址。
rootPage.bluetoothAddressType: 蓝牙地址类型,指示蓝牙地址的类型,可以是 BluetoothAddressType.Public 或 BluetoothAddressType.Random。
5.registeredCharacteristic?.WriteClientCharacteristicConfigurationDescriptorAsync: 这是一个用于写入客户端特征配置描述符(Client Characteristic Configuration Descriptor)的异步方法。
客户端特征配置描述符用于配置通知或指示的特征值的通知方式。通过写入特定的配置值,可以订阅或取消订阅设备发送的通知。
参数说明:
GattClientCharacteristicConfigurationDescriptorValue.None: 这是一个枚举值,表示不启用通知或指示。通过写入这个值,可以取消订阅设备发送的通知。
该方法的返回值是一个 GattCommunicationStatus 枚举,表示写入操作的结果。可能的返回值有:Success 表示写入成功,Unreachable 表示设备不可达,AccessDenied 表示写入被拒绝等。
在代码中使用了 await 关键字,这表示该异步操作将在完成后返回结果。这样可以确保在等待写入完成后再继续执行后续操作。
关于gattCharacteristic.Service (GattDeviceService 类) 的释放