This question is similar with my problem. But in my situation i have more than one device that i want to catch change event for them. Creating instance of GattCharacteristic and GattDeviceService objects in field-level solving the problem but number of connected device should be changable.
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);
}
if we define the change event like above after a while it stops running.How to solve this problem with more than one device?
In Your code example you are adding multiple eventhandlers, that is something You must avoid. To prevent that you can do someting like this:
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;
}
}
in Your eventHandler you can distinguish between different devices by
if (sender.Service.Device == bluetoothLeDevice_1)
{
//do something
}
if (sender.Service.Device == bluetoothLeDevice_2)
{
//do something
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With