Xamarin bluetooth low energy

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

Bluetooth LE plugin for Xamarin/MAUI, supporting Android, iOS, Mac, Windows

License

dotnet-bluetooth-le/dotnet-bluetooth-le

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

Bluetooth LE plugin for Xamarin & MAUI

Xamarin, MAUI and MvvMCross plugin for accessing the bluetooth functionality. The plugin is loosely based on the BLE implementation of Monkey Robotics.

Important Note: With the term «vanilla» we mean the non-MvvmCross version, i.e. the pure Xamarin or MAUI plugin. You can use it without MvvmCross, if you download the vanilla package.

Platform Version Limitations
Xamarin.Android 4.3
Xamarin.iOS 7.0
Xamarin.Mac 10.9 (Mavericks) >= 2.1.0
Xamarin.UWP 1709 — 10.0.16299 >= 2.2.0
MAUI (all 4 OS) >= 3.0.0
// stable Install-Package Plugin.BLE // or pre-release Install-Package Plugin.BLE -Pre 
Install-Package MvvmCross.Plugin.BLE // or Install-Package MvvmCross.Plugin.BLE -Pre 

Add these permissions to AndroidManifest.xml. For Marshmallow and above, please follow Requesting Runtime Permissions in Android Marshmallow and don’t forget to prompt the user for the location permission.

uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> uses-permission android:name="android.permission.BLUETOOTH" /> uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />

Android 12 and above may require one or more of the following additional runtime permissions, depending on which features of the library you are using (see the android Bluetooth permissions documentation)

uses-permission android:name="android.permission.BLUETOOTH_SCAN" /> uses-permission android:name="android.permission.BLUETOOTH_CONNECT" /> uses-permission android:name="android.permission.BLUETOOTH_ADVERTISE" />

Add this line to your manifest if you want to declare that your app is available to BLE-capable devices only:

uses-feature android:name="android.hardware.bluetooth_le" android:required="true"/>

On iOS you must add the following keys to your Info.plist

UIBackgroundModes  bluetooth-central bluetooth-peripheral  NSBluetoothPeripheralUsageDescription YOUR CUSTOM MESSAGE NSBluetoothAlwaysUsageDescription YOUR CUSTOM MESSAGE 

On MacOS (version 11 and above) you must add the following keys to your Info.plist :

 NSBluetoothAlwaysUsageDescription YOUR CUSTOM MESSAGE 

Add this line to the Package Manifest (.appxmanifest):

DeviceCapability Name="bluetooth" />

We provide a sample Xamarin.Forms app, that is a basic bluetooth LE scanner. With this app, it’s possible to

  • check the ble status
  • discover devices
  • connect/disconnect
  • discover the services
  • discover the characteristics
  • see characteristic details
  • read/write and register for notifications of a characteristic
Читайте также:  Тихий звук bluetooth наушников windows 10

Have a look at the code and use it as starting point to learn about the plugin and play around with it.

var ble = CrossBluetoothLE.Current; var adapter = CrossBluetoothLE.Current.Adapter;

The MvvmCross plugin registers IBluetoothLE and IAdapter as lazy initialized singletons. You can resolve/inject them as any other MvvmCross service. You don’t have to resolve/inject both. It depends on your use case.

var ble = Mvx.ResolveIBluetoothLE>(); var adapter = Mvx.ResolveIAdapter>();
MyViewModel(IBluetoothLE ble, IAdapter adapter)  this.ble = ble; this.adapter = adapter; >

Please make sure you have this code in your LinkerPleaseLink.cs file

public void Include(MvvmCross.Plugins.BLE.Plugin plugin)  plugin.Load(); >

You can also listen for State changes. So you can react if the user turns on/off bluetooth on your smartphone.

ble.StateChanged += (s, e) =>  Debug.WriteLine($"The bluetooth state changed to e.NewState>"); >;
adapter.DeviceDiscovered += (s,a) => deviceList.Add(a.Device); await adapter.StartScanningForDevicesAsync();
var scanFilterOptions = new ScanFilterOptions(); scanFilterOptions.ServiceUuids = new [] guid1, guid2, etc>; // cross platform filter scanFilterOptions.ManufacturerDataFilters = new []  new ManufacturerDataFilter(1), new ManufacturerDataFilter(2) >; // android only filter scanFilterOptions.DeviceAddresses = new [] "80:6F:B0:43:8D:3B","80:6F:B0:25:C3:15",etc>; // android only filter await adapter.StartScanningForDevicesAsync(scanFilterOptions);

Set adapter.ScanTimeout to specify the maximum duration of the scan.

Set adapter.ScanMode to specify scan mode. It must be set before calling StartScanningForDevicesAsync() . Changing it while scanning, will not affect the current scan.

ConnectToDeviceAsync returns a Task that finishes if the device has been connected successful. Otherwise a DeviceConnectionException gets thrown.

try  await _adapter.ConnectToDeviceAsync(device); > catch(DeviceConnectionException e)  // . could not connect to device >

ConnectToKnownDeviceAsync can connect to a device with a given GUID. This means that if the device GUID is known, no scan is necessary to connect to a device. This can be very useful for a fast background reconnect. Always use a cancellation token with this method.

  • On iOS it will attempt to connect indefinitely, even if out of range, so the only way to cancel it is with the token.
  • On Android this will throw a GATT ERROR in a couple of seconds if the device is out of range.
try  await _adapter.ConnectToKnownDeviceAsync(guid, cancellationToken); > catch(DeviceConnectionException e)  // . could not connect to device >
var services = await connectedDevice.GetServicesAsync();

or get a specific service:

var service = await connectedDevice.GetServiceAsync(Guid.Parse("ffe0ecd2-3d16-4f8d-90de-e89e7fc396a5"));
var characteristics = await service.GetCharacteristicsAsync();

or get a specific characteristic:

var characteristic = await service.GetCharacteristicAsync(Guid.Parse("d8de624e-140f-4a22-8594-e2216b84a5f2"));
var bytes = await characteristic.ReadAsync();
await characteristic.WriteAsync(bytes);
characteristic.ValueUpdated += (o, args) =>  var bytes = args.Characteristic.Value; >; await characteristic.StartUpdatesAsync();
var descriptors = await characteristic.GetDescriptorsAsync();
var bytes = await descriptor.ReadAsync();
await descriptor.WriteAsync(bytes);

Returns all BLE devices connected or bonded (only Android) to the system. In order to use the device in the app you have to first call ConnectAsync.

  • For iOS the implementation uses get retrieveConnectedPeripherals(services)
  • For Android this function merges the functionality of the following API calls:
    • getConnectedDevices
    • getBondedDevices()
    var systemDevices = adapter.GetSystemConnectedOrPairedDevices(); foreach(var device in systemDevices)  await _adapter.ConnectToDeviceAsync(device); >

    Caution! Important remarks / API limitations

    The BLE API implementation (especially on Android) has the following limitations:

    • Characteristic/Descriptor Write: make sure you call characteristic.WriteAsync(. ) from the main thread, failing to do so will most probably result in a GattWriteError.
    • Sequential calls: Always wait for the previous BLE command to finish before invoking the next. The Android API needs its calls to be serial, otherwise calls that do not wait for the previous ones will fail with some type of GattError. A more explicit example: if you call this in your view lifecycle (onAppearing etc) all these methods return void and 100% don’t guarantee that any await bleCommand() called here will be truly awaited by other lifecycle methods.
    • Scan with services filter: On specifically Android 4.3 the scan services filter does not work (due to the underlying android implementation). For android 4.3 you will have to use a workaround and scan without a filter and then manually filter by using the advertisement data (which contains the published service GUIDs).
    • Surround Async API calls in try-catch blocks. Most BLE calls can/will throw an exception in certain cases, this is especially true for Android. We will try to update the xml doc to reflect this.
    try  await _adapter.ConnectToDeviceAsync(device); > catch(DeviceConnectionException ex)  //specific > catch(Exception ex)  //generic >
    • Avoid caching of Characteristic or Service instances between connection sessions. This includes saving a reference to them in your class between connection sessions etc. After a device has been disconnected all Service & Characteristic instances become invalid. Allways use GetServiceAsync and GetCharacteristicAsync to get a valid instance.
    • Scanning: Avoid performing ble device operations like Connect, Read, Write etc while scanning for devices. Scanning is battery-intensive.
      • try to stop scanning before performing device operations (connect/read/write/etc)
      • try to stop scanning as soon as you find the desired device
      • never scan on a loop, and set a time limit on your scan

      How to build the nuget package

      1. Build Open a console, change to the folder «dotnet-bluetooth-le/.build» and run cake .
      2. pack the nuget nuget pack ../Source/Plugin.BLE/Plugin.BLE.csproj nuget pack ../Source/MvvmCross.Plugins.BLE/MvvmCross.Plugins.BLE.csproj

      We usually do our development work on a branch with the name of the milestone. So please base your pull requests on the currently open development branch.

      About

      Bluetooth LE plugin for Xamarin/MAUI, supporting Android, iOS, Mac, Windows

      Источник

      Bluetooth LE plugin for Xamarin released

      The first release candidate of our BLE plugin is now available.

      Adrian (@secelead) and I pushed the first release candidate of our bluetooth low energy plugin for xamarin and MvvmCross to NuGet, today. The code is available on github. It is based on Monkey robotics, but heavily refactored.

      It currently supports Android and iOS and the following features are implemented.

      Bluetooth State

      You can check if the device supports bluetooth LE, check whether it is turned on or off and subscribe to any changes on this state.

      NuGet

      Sample app

      We provide a sample Xamarin.Forms app, that is a basic bluetooth LE scanner. With this app, it’s possible to

      • check the bluetooth LE status
      • discover devices
      • connect/disconnect
      • discover the services
      • discover the characteristics
      • see characteristic details
      • read/write and register for notifications of a characteristic

      Have a look at the code and use it as starting point to learn about the plugin and play around with it.

      Our goals for v 1.0

      Adrian started this project last year as MvvmCross plugin. He fixed alot of bugs and made it stable. It has been in v 0.9.x for quite a while and we wanted to bring it to v 1.0. In recent weeks, we refactored it with the goals

      • provide a “vanilla” Xamarin plugin
      • provide a sample app
      • streamline the API (make it asnyc and use cancelable)
      • get rid of old code

      What next?

      We are aiming for a soon stable release. We invite everybody to give some feedback and suggestions. Feel free, to create an issue on github or contact us directly on twitter or slack. The open issues can be found on github.

      • better build process
      • more documentation
      • get rid of fat single gatt callback (split it)
      • unit tests
      • extend IBluetooth
        • request permission
        • enable bluetooth
        • basic info like IsBleAvailable, MaxSupportedVersion, …

        Copyright © Sven-Michael Stübe 2021

        Источник

Оцените статью
Adblock
detector