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);
}
如果我们在一段时间之后停止运行就像上面那样定义了变更事件。如何用多个设备解决这个问题?
答案 0 :(得分:1)
在您的代码示例中,您要添加多个事件处理程序,这是您必须避免的事情。 为了防止你这样做:
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
}