BLE HELP: Only getting the value the second time the method is called?

SophieHerSophieHer Member ✭✭

Hi,
I am currently developing a BLE App using this BLE plugin. What I am trying to do is that when the user presses "Battery" (item in a TableView) the Battery_Tapped event handler gets fired. In this event handler I am trying to send 3 bytes to the device connected to the BLE and the device should send the battery level back. This works (I have tested it), but for some reason the event handler does not receive the byte the first time it gets fired. But if i go back to the status page and click "Battery" again, this time the byte is received (unsure if it is the previous one or a new one being received).
Here is my code for the Battery_Tapped event handler:

private async void Battery_Tapped(object sender, EventArgs e)
        {
            await Navigation.PushAsync(BatteryPage);
            try
            {
                Xamarin.Forms.Device.BeginInvokeOnMainThread(async () =>
                {
                    await App.writeCharacteristic.WriteAsync(BatteryTxBytes);
                });
            }
            catch (Exception ex)
            {
                await DisplayAlert("Notice", ex.Message.ToString(), "Eor !");
            }

            try
            {
                App.readCharacteristic.ValueUpdated += (o, args) =>
                {
                    BatteryRxBytes = args.Characteristic.Value;
                };
                await App.readCharacteristic.StartUpdatesAsync();

            }
            catch (Exception ex)
            {
                await DisplayAlert("Notice", ex.Message.ToString(), "Error !");
            }
            try
            {
                BatteryPage.UpdateBatteryLevel(BatteryRxBytes[0]);
            }
            catch(Exception ex)
            {
                await DisplayAlert("Notice", ex.Message.ToString(), "ye");
            }
        }

I am suspecting it might have something to do with the await operators, but I am fairly new to Xamarin and C# so I am not sure how to work around this. Any help would be highly appreciated!
Thanks,
Sophie

Sign In or Register to comment.