• This repository has been archived on 24/Aug/2023
  • Stars
    star
    405
  • Rank 106,656 (Top 3 %)
  • Language
    C#
  • License
    MIT License
  • Created about 8 years ago
  • Updated over 4 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Easy to use, cross platform, REACTIVE BluetoothLE Plugin for Xamarin

UPDATE - This library is moving to the Shiny Framework at https://github.com/shinyorg/shiny Support will remain until Shiny is out of beta

ACR Reactive BluetoothLE Plugin

Easy to use, cross platform, REACTIVE BluetoothLE Plugin for ALL platforms!

SUPPORT THIS PROJECT

Change Log - November 17, 2018

NuGet Build status

PLATFORMS

Platform Version
Android 4.3+
iOS 7+
macOS Latest
tvOS Latest
Windows UWP 16299+

UWP is still in beta!

  • Client cannot disconnect
  • Server WIP
  • PRs only during beta please!

FEATURES

  • Scan for advertisement packets and devices (with full control of the scanning features)
  • Monitor adapter status (and control it on android)
  • Open Bluetooth settings screen
  • Persistent connections
  • Deals with the Android threading and defect headaches
  • Discover services, characteristics, & descriptors
  • Read, write, & receive notifications for characteristics
  • Support for reliable write transactions
  • Read & write descriptors
  • Request & monitor MTU changes
  • Connect to heart rate monitors
  • Deals with most of the Android fubars
  • Manages iOS backgrounding by allowing hooks to WhenWillRestoreState
  • Control the adapter state on Android
  • Pair with devices
  • GATT Server and Advertising Support
    • Advertising
      • Manufactuer Data
      • Service UUIDs
    • Charactertistics
      • Read
      • Write
      • Notify & Broadcast
      • Manage Subscribers
      • Status Replies
  • Android Issues
    • We manage the GATT 133 (mostly, hopefully)
    • Don't like the serial way you have to work with BLE, don't worry, we cover that too. Read/Write away!
    • Don't know what thread to run a method on? Don't worry - we got that covered.... just make the read/write call and relax

SETUP

Be sure to install the Plugin.BluetoothLE nuget package in all of your main platform projects as well as your core/NETStandard project

NuGet

Android

Add the following to your AndroidManifest.xml PLEASE NOTE THAT YOU HAVE TO REQUEST THESE PERMISSIONS USING Activity.RequestPermission or a Plugin

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

<!--this is necessary for Android v6+ to get the device name and address-->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

iOS

If you want to use background BLE periperhals, add the following to your Info.plist

<key>UIBackgroundModes</key>
<array>
    <!--for connecting to devices (client)-->
	<string>bluetooth-central</string>

    <!--for server configurations if needed-->
	<string>bluetooth-peripheral</string>
</array>

<!--To add a description to the Bluetooth request message (on iOS 10 this is required!)-->
<key>NSBluetoothPeripheralUsageDescription</key>
<string>YOUR CUSTOM MESSAGE</string>

HOW TO USE - CLIENT BASICS

// discover some devices
CrossBleAdapter.Current.Scan().Subscribe(scanResult => {});

// Once finding the device/scanresult you want
scanResult.Device.Connect();

Device.WhenAnyCharacteristicDiscovered().Subscribe(characteristic => {
    // read, write, or subscribe to notifications here
    var result = await characteristic.Read(); // use result.Data to see response
    await characteristic.Write(bytes);

    characteristic.EnableNotifications();
    characteristic.WhenNotificationReceived().Subscribe(result => {
    	//result.Data to get at response
    });
});

HOW TO USE - SERVER BASICS

Most important things - you should setup all of your services and characteristics BEFORE you Start() the server!

var server = CrossBleAdapter.Current.CreateGattServer();
var service = server.AddService(Guid.NewGuid(), true);

var characteristic = service.AddCharacteristic(
    Guid.NewGuid(),
    CharacteristicProperties.Read | CharacteristicProperties.Write | CharacteristicProperties.WriteWithoutResponse,
    GattPermissions.Read | GattPermissions.Write
);

var notifyCharacteristic = service.AddCharacteristic
(
    Guid.NewGuid(),
    CharacteristicProperties.Indicate | CharacteristicProperties.Notify,
    GattPermissions.Read | GattPermissions.Write
);

IDisposable notifyBroadcast = null;
notifyCharacteristic.WhenDeviceSubscriptionChanged().Subscribe(e =>
{
    var @event = e.IsSubscribed ? "Subscribed" : "Unsubcribed";

    if (notifyBroadcast == null)
    {
        this.notifyBroadcast = Observable
            .Interval(TimeSpan.FromSeconds(1))
            .Where(x => notifyCharacteristic.SubscribedDevices.Count > 0)
            .Subscribe(_ =>
            {
                Debug.WriteLine("Sending Broadcast");
                var dt = DateTime.Now.ToString("g");
                var bytes = Encoding.UTF8.GetBytes(dt);
                notifyCharacteristic.Broadcast(bytes);
            });
    }
});

characteristic.WhenReadReceived().Subscribe(x =>
{
    var write = "HELLO";

    // you must set a reply value
    x.Value = Encoding.UTF8.GetBytes(write);

    x.Status = GattStatus.Success; // you can optionally set a status, but it defaults to Success
});
characteristic.WhenWriteReceived().Subscribe(x =>
{
    var write = Encoding.UTF8.GetString(x.Value, 0, x.Value.Length);
    // do something value
});

await server.Start(new AdvertisementData
{
    LocalName = "TestServer"
});

DOCUMENTATION

FAQ

Q. Why is everything reactive instead of events/async

I wanted event streams as I was scanning devices. I also wanted to throttle things like characteristic notification feeds. Lastly, was the proper cleanup of events and resources.

Q. Why are Device.Connect, Characteristic.Read, and Descriptor.Read observable when async would do just fine?

True, but observables with RX are actually awaitable as well and far easier to chain into other things.

Q. Why are devices cleared on a new scan?

Some platforms yield a "new" device and therefore new hooks. This was observed on some android devices.

Q. My characteristic read/writes/notifications are not working

If you store your discovered characteristics in your own variables, make sure to refresh them with each (re)connect

Q. I cannot see the device name in Android 6+

You need to enable permissions for android.permission.ACCESS_COARSE_LOCATION

Q. I cannot see the device name when scanning in the background on iOS

This is the work of iOS. The library cannot fix this. You should scan by service UUIDs instead

Q. Does this support Bluetooth v2?

No - please read about bluetooth specifications before using this library. LE (Low Energy) is part of the v4.0 specification.

Q. Why can't I disconnect devices selectively in the GATT server?

On android, you can, but exposing this functionality in xplat proves challenging since iOS does not support A LOT of things

Q. Why can't I configure the device name on Android?

Please read the advertising docs on this

GENERAL RULES TO FOLLOW

  • DO NOT reuse services, characteristics, and descriptors between connnections
  • DO catch errors in your subscriptions (ie. Reads/Writes)
  • DO set timeouts on all connected operations using Observable.Timeout(TimeSpan). Timeout throws errors that you must also manage!
  • DO NOT manage reconnection yourself
  • DO NOT scan with the adapter while you have an open GATT connection
  • If you have a TX/RX setup using Notify/Write, use 2 characteristics, not one

CONTRIBUTORS

Thank you for all your help

More Repositories

1

userdialogs

A cross platform library that allows you to call for standard user dialogs from a core .net standard library, Actionsheets, alerts, confirmations, loading, login, progress, prompt, toast... async just for fun
C#
990
star
2

acr-xamarin-forms

Camera/Gallery, Barcode Scanning, User Dialogs, Geo-Location, Network Utils, Device Info, Settings, E-Mail, Phone, SMS all for Xamarin.Forms
C#
252
star
3

notifications

Local notifications for iOS, Android, & Windows. Includes badges, scheduled notifications, sounds, & context actions
C#
102
star
4

httptransfertasks

Cross Platform HTTP Transfers for downloading and uploading (supports background operations)
C#
86
star
5

jobs

Background Jobs Framework for Xamarin & UWP
C#
82
star
6

speechrecognition

Easy to use cross platform speech recognition (speech to text) plugin for Xamarin & UWP
C#
77
star
7

deviceinfo

ACR Device Information for Xamarin & Windows
C#
73
star
8

settings

A cross platform settings plugin for Xamarin and Windows. Unlike other setting libraries in the wild, this library provides several unique features. Store almost any object, monitor change events, iOS app groups, iCloud Provider, and Old school windows settings
C#
71
star
9

geofences

Cross platform geofencing library that works on iOS, Android, and Windows
C#
61
star
10

acrmvvmcross

Several MvvmCross plugins that I have used on a few projects
C#
45
star
11

sensors

Reactive mobile device sensors plugin for iOS, Android, & UWP. Support sensors - accelerometer, ambient light, barometer, compass, gyroscope, magnetometer, pedometer, and proximity
C#
43
star
12

estimotes-xplat

Estimotes Plugin for Xamarin to allow for cross platform development using the Estimote SDK
C#
40
star
13

ShinyGpsSync

An example of how people can use real time connectivity/location to move data
C#
9
star
14

biometrics

This library is no longer supported. Please use https://www.nuget.org/packages/Plugin.Fingerprint/
C#
9
star
15

mvxgoodies

C#
7
star
16

barcodes

A cross platform barcode scanning and creating library built on top of ZXing.Net.Mobile
C#
7
star
17

talks

C#
6
star
18

beacons

Cross platform beacons
C#
6
star
19

Stream-Todo

C#
6
star
20

TOMobileGroupShinySample

C#
4
star
21

extensions

C#
4
star
22

userdialogsforms

C#
3
star
23

BeatTheBank

C#
3
star
24

DigitalScoreboard

C#
3
star
25

support

C#
1
star
26

aritchie.github.io

HTML
1
star
27

cache

Cache abstraction with several PCL implementations
C#
1
star
28

xdsworkshop

C#
1
star