xamarin.android蓝牙,GitHub - xabre/xamarin-bluetooth-le: Bluetooth LE plugin for Xamarin

62eebaaab2bbf9731d31b01b28c299a2.png Bluetooth LE plugin for Xamarin 68747470733a2f2f6170702e626974726973652e696f2f6170702f336665353464306135663433633262662f7374617475732e7376673f746f6b656e3d69394c555934724965635a57645f336a376877586777

Xamarin 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/pure Xamarin version. You can use it without MvvmCross, if you download the vanilla package.

Support & Limitations

Platform

Version

Limitations

Xamarin.Android

4.3

Xamarin.iOS

7.0

Xamarin.Mac

10.9 (Mavericks)

>= v2.1.0

UWP

1709 - 10.0.16299 (Fall Creators Update)

TBA

Installation

Vanilla

// stable

Install-Package Plugin.BLE

// or pre-release

Install-Package Plugin.BLE -Pre

68747470733a2f2f696d672e736869656c64732e696f2f6e756765742f762f506c7567696e2e424c452e7376673f6c6162656c3d4e75476574267374796c653d666c61742d73717561726568747470733a2f2f696d672e736869656c64732e696f2f6e756765742f767072652f506c7567696e2e424c452e7376673f6c6162656c3d4e7547657425323042657461267374796c653d666c61742d737175617265

MvvmCross

Install-Package MvvmCross.Plugin.BLE

// or

Install-Package MvvmCross.Plugin.BLE -Pre

68747470733a2f2f696d672e736869656c64732e696f2f6e756765742f762f4d76766d43726f73732e506c7567696e2e424c452e7376673f6c6162656c3d4e754765742532304d76764d43726f7373267374796c653d666c61742d73717561726568747470733a2f2f696d672e736869656c64732e696f2f6e756765742f767072652f4d76766d43726f73732e506c7567696e2e424c452e7376673f6c6162656c3d4e754765742532304d76764d43726f737325323042657461267374796c653d666c61742d737175617265

Android

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.

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

iOS

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

MacOS

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

NSBluetoothAlwaysUsageDescription

YOUR CUSTOM MESSAGE

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 ble 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.

Usage

Vanilla

var ble = CrossBluetoothLE.Current;

var adapter = CrossBluetoothLE.Current.Adapter;

MvvmCross

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.Resolve();

var adapter = Mvx.Resolve();

or

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.iOS.Plugin plugin)

{

plugin.Load();

}

IBluetoothLE

Get the bluetooth status

var state = ble.State;

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

ble.StateChanged += (s, e) =>

{

Debug.WriteLine($"The bluetooth state changed to {e.NewState}");

};

IAdapter

Scan for devices

adapter.DeviceDiscovered += (s,a) => deviceList.Add(a.Device);

await adapter.StartScanningForDevicesAsync();

ScanTimeout

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

ScanMode

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

Connect to device

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

}

Connect to known 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

}

Get services

var services = await connectedDevice.GetServicesAsync();

or get a specific service:

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

Get characteristics

var characteristics = await service.GetCharacteristicsAsync();

or get a specific characteristic:

var characteristic = await service.GetCharacteristicAsync(Guid.Parse("d8de624e-140f-4a22-8594-e2216b84a5f2"));

Read characteristic

var bytes = await characteristic.ReadAsync();

Write characteristic

await characteristic.WriteAsync(bytes);

Characteristic notifications

characteristic.ValueUpdated += (o, args) =>

{

var bytes = args.Characteristic.Value;

};

await characteristic.StartUpdatesAsync();

Get descriptors

var descriptors = await characteristic.GetDescriptorsAsync();

Read descriptor

var bytes = await descriptor.ReadAsync();

Write descriptor

await descriptor.WriteAsync(bytes);

Get System Devices

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 Android this function merges the functionality of thw following API calls:

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 it's 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 quarantee that any await bleCommand() called here will be truly awaited by other lifecycle methods.

Scan wit 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).

Best practice

API

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 you 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.

General BLE iOS, Android

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

Build

Open a console, change to the folder "xamarin-bluetooth-le/.build" and run cake.

pack the nuget

nuget pack Plugin.BLE.nuspec

nuget pack MvvmCross.Plugin.BLE.nuspec

Extended topics

Useful Links

How to contribute

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.

Licence

  • 0
    点赞
  • 0
    评论
  • 0
    收藏
  • 一键三连
    一键三连
  • 扫一扫,分享海报

表情包
插入表情
评论将由博主筛选后显示,对所有人可见 | 还能输入1000个字符
©️2021 CSDN 皮肤主题: 1024 设计师:白松林 返回首页
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值