gpt4 book ai didi

c# - 是否可以使 GattCharacteristic ValueChange 事件发生在多个设备上?

转载 作者:行者123 更新时间:2023-11-30 17:33:49 24 4
gpt4 key购买 nike

This question和我的问题类似。但在我的情况下,我有不止一台设备想要为他们捕获更改事件。在字段级创建 GattCharacteristic 和 GattDeviceService 对象的实例解决了问题,但连接的设备数量应该是可变的。

 var devices = await DeviceInformation.FindAllAsync(GattDeviceService.GetDeviceSelectorFromUuid(new Guid("00002000-0000-1000-8000-00805f9b34fb")), null);
for (int i = 0; i < devices.Count; i++)
{

GattDeviceService service= await GattDeviceService.FromIdAsync(devices[i].Id);
GattCharacteristic characteristic = service.GetCharacteristics(new Guid("00002001-0000-1000-8000-00805f9b34fb")).FirstOrDefault();
characteristic.ValueChanged += CounterCharacteristic_ValueChanged;
await characteristic.WriteClientCharacteristicConfigurationDescriptorAsync(GattClientCharacteristicConfigurationDescriptorValue.Notify);
}

如果我们像上面那样定义change事件一段时间后它停止运行。如何解决多台设备的问题?

最佳答案

在您的代码示例中,您添加了多个事件处理程序,这是您必须避免的事情。为了防止你可以这样做:

var devices = await   DeviceInformation.FindAllAsync(GattDeviceService.GetDeviceSelectorFromUuid(new Guid("00002000-0000-1000-8000-00805f9b34fb")), null);
for (int i = 0; i<devices.Count; i++)
{
GattDeviceService service = await GattDeviceService.FromIdAsync(devices[i].Id);
GattCharacteristic characteristic = service.GetCharacteristics(new Guid("00002001-0000-1000-8000-00805f9b34fb")).FirstOrDefault();
await characteristic.WriteClientCharacteristicConfigurationDescriptorAsync(GattClientCharacteristicConfigurationDescriptorValue.Notify);
AddValueChangedHandler(characteristic);
}

private bool isValueChangedHandlerRegistered = false;//make this a field!

private void AddValueChangedHandler(GattCharacteristic selectedCharacteristic )
{
if (!isValueChangedHandlerRegistered)
{
selectedCharacteristic.ValueChanged += CounterCharacteristic_ValueChanged;
isValueChangedHandlerRegistered = true;
}
}

在你的eventHandler中你可以通过

区分不同的设备
if (sender.Service.Device == bluetoothLeDevice_1) 
{
//do something
}
if (sender.Service.Device == bluetoothLeDevice_2)
{
//do something
}

关于c# - 是否可以使 GattCharacteristic ValueChange 事件发生在多个设备上?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43247744/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com