'xamarin forms: How to get Bluetooth LE Notify

I use this plugin https://github.com/xabre/xamarin-bluetooth-le

Now, I'm trying to write characteristic and get the response from BLE device. After sending command to BLE device, I would like to use characteristic.ValueUpdated to get response. But my code doesn't work. So I would like to know how to use characteristic.ValueUpdated and characteristic.StartUpdatesAsync().

Steps to reproduce

  1. Connect BLE device and get Device, Service and Characteristic
  2. Use await characteristic.WriteAsync(command) to send command to BLE device
  3. Use characteristic.ValueUpdated and await characteristic.StartUpdatesAsync() to get response from BLE device.

Expected behavior: The event characteristic.ValueUpdated shall be called and I can get the response.

Actual behavior: characteristic.ValueUpdated is not be called.

Configuration: **Version of the Plugin:2.0.0-pre1 **Platform: iOS 12.1 / Android 7.1 **Device: iPhone XR / Asus Android

public int SendCommand(byte[] command)
{
    if (device == null || service == null || characteristic == null)
    {
        return 1;
    }

    var result1 = WriteCharacteristic(command);

    receive_data = GetResponse().Result;

    if (receive_data == null || receive_data[1] != 0x00)
    {
        return 1;
    }

    return 0;
}

private async Task<bool> WriteCharacteristic(byte[] command)
{
    await characteristic.WriteAsync(command);
    return true;
}

private async Task<byte[]> GetResponse()
{
    byte[] bytes = new byte[20];

    characteristic.ValueUpdated += (o, args) =>
    {
        bytes = args.Characteristic.Value;
    };

    await characteristic.StartUpdatesAsync();

    return bytes;
}


Solution 1:[1]

You actually need to do a couple of things before the ValueUpdated will be called correctly.

After getting your characteristic out of the service, you need to hook up the ValueUpdated method:

characteristic.ValueUpdated += (o, args) => { bytes = args.Characteristic.Value;};

await characteristic.StartUpdatesAsync();

Once the call from StartUpdatesAsync is returned, anytime a response from your characteristic is received, it will get called.

Now you can do a call to your characteristic:

await characteristic.WriteAsync(command);

Your code is calling the method to receive values after you have written your value to the characteristic, whereby a response can already be made but your characteristic isn't wired up yet, so you are probably missing the value updated event.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Josh