Forum Xamarin.Forms

Announcement:

The Xamarin Forums have officially moved to the new Microsoft Q&A experience. Microsoft Q&A is the home for technical questions and answers at across all products at Microsoft now including Xamarin!

To create new threads and ask questions head over to Microsoft Q&A for .NET and get involved today.

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

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

Answers

  • loinguyen216loinguyen216 Member ✭✭

    Hello,

    I know this is an old thread, but did you figure this issue out yet? I hate to bother you. But, I have a much similar situation where I need to send byte data using bluetooth to another device. I wrote writeasync on mainthread like you did above and then call defined ValueUpdated and call StartUpdateAsync but it never go into my ValueUpdated.

    Any help would be greatly appreciate.

    Thanks again!

Sign In or Register to comment.