xamarin / Xamarin.Forms

Xamarin.Forms is no longer supported. Migrate your apps to .NET MAUI.
https://aka.ms/xamarin-upgrade
Other
5.64k stars 1.88k forks source link

How to do update MTU size to 128 or more on Android instantly whenever the device is connected in xamarin form #15809

Closed Priyabaghelgithub closed 10 months ago

Priyabaghelgithub commented 10 months ago

I'm implementing BLE in Xamarin forms using Plugin.BluetoothLE package, where I'm trying to send data larger than 20 bytes. So I used await _Device.RequestMtu(512) but its MTU size is not updating on central device(smartphone device or device inside the app) on Android only

''' public bool TrySetScanResult(IScanResult result) ///Method responsible for connecting device in mobile app { var response = false; try { if (Uuid == Guid.Empty || Device == null) { Device = result.Device; Uuid = Device.Uuid;

            Device.WhenStatusChanged()
                .ObserveOn(RxApp.MainThreadScheduler)
                .Subscribe(connstat =>
                {
                    SetDeviceInfo(connstat);

                }, onError: ex => ex.WriteLog().UploadLog())
                .DisposeWith(DeactivateWith);

            Device.WhenDisconnected()
                .ObserveOn(RxApp.MainThreadScheduler)
                .Subscribe(device =>
                {

                    if (this.isFired && device.Uuid == Device.Uuid)
                    {
                        this._watcher?.Dispose();
                        this._watcher = null;
                        this.isFired = false;
                    }
                }, onError: ex => ex.WriteLog().UploadLog())
                .DisposeWith(DeactivateWith);

} System.Diagnostics.Debug.WriteLine(Device.Status); if (this.Uuid == result.Device.Uuid) { if (!Device.IsConnected()) { response = true; IsDevicePairedWatcher(); } if (Device.IsConnected()) { UpdtaeMtuSize (); } } } catch (Exception ex) { ex.WriteLog().UploadLog(); } return response; }

private void IsDevicePairedWatcher() // this method is watching data of hooked characteristic { if (!isFired) { isFired = true; if (this._watcher != null) { _watcher?.Dispose(); _watcher = null; }

        this._watcher = Device.ConnectHook(ServiceUUID,
       WriteReadNotify_Results_CharacteristicUUID,
        ReadNotify_Calibration_CharacteristicUUID)
          .ObserveOn(RxApp.MainThreadScheduler)
          .Subscribe(async (result) =>
          {
              try
              {                   
              }
              catch (Exception er)
              {
                  er.WriteLog().UploadLog();
              }

          }, onError: (ex) =>
          {
              ex.WriteLog().UploadLog();
              isFired = false;
          });
    }
}

private async void UpdateMtuSize() //responsible for setting CustomCallback class and requesting Device to request MTU { int desiredMtuSize = 128; DependencyService.Get().GetConnectedBluetoothGatt(_currentDevice.Uuid); var currentMTU = await Device.RequestMtu(desiredMtuSize); if (currentMTU >= desiredMtuSize) { IsMTUupdate = true; Console.WriteLine("Successful, current MTU size: " + currentMTU); } else Console.WriteLine("Failed, current MTU size: " + currentMTU); // MTU negotiation failed, actualMtu is different from the desired MTU }

public class AndroidBluetoothLERenderer : IBluetoothManager //rendere setting bluetoothGatt instance { private BluetoothGatt GetBluetoothGatt; public void GetConnectedBluetoothGatt(Guid? deviceGuid) { try { var adapter = BluetoothAdapter.DefaultAdapter; string hexString = ConvertGuidToHexString(deviceGuid.Value); var device = adapter.GetRemoteDevice(hexString);

        if (device != null)
        {
            var customBluetoothGattCallbackhandler = new CustomBluetoothGattCallback();
            var gatt = device.ConnectGatt(Application.Context, false, customBluetoothGattCallbackhandler);
            GetBluetoothGatt = gatt;
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine("Error requesting MTU: " + ex.ToString());  // Handle any exceptions that may occur during the process.
    }
}
public bool DisconnectBluetoothGatt(bool mtuupdate)
{
    if (mtuupdate)
    {
        if (GetBluetoothGatt.Device != null)
        {
            GetBluetoothGatt.Close();
            GetBluetoothGatt.Dispose();
            return true;
        }
        else
            return false;
    }
    else return false;
}'''

where should I call the method UpdtaeMtuSize so that MTU is updated whenever the device connected instantly curently I called the method when the device is connected but MTU size is not updating properly on central device(device inside the app) sometimes it set or sometimes not why on Android only

suggest any alternative to set the MTU size properly

@jfversluis @jamesmontemagno

jfversluis commented 10 months ago

Hi and thanks for the report! This seems more of a how-to question rather than a potential issue in Xamarin.Forms. You will probably have better luck asking your question on online forums like Microsoft Q&A or Stack Overflow.

Unfortunately I don't have much experience with this so I don't have any answer for you. Good luck!