3

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?

Community
  • 1
  • 1
mr.
  • 679
  • 12
  • 30

1 Answers1

1

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
}
GrooverFromHolland
  • 971
  • 1
  • 11
  • 18