Ble.net
Cross-platform Bluetooth Low Energy (BLE) library for Android, iOS, and UWP
Install / Use
/learn @nexussays/Ble.netREADME
ble.net

ble.net is a cross-platform Bluetooth Low Energy (aka BLE, aka Bluetooth LE, aka Bluetooth Smart) library to enable simple development of BLE clients on Android, iOS, and UWP/Windows.
It provides a consistent API across all supported platforms and hides most of the problems and poor API decisions of the native BLE APIs.
Platform Support
| Platform | Version | | ---------------- | :-------: | | Xamarin.iOS | iOS 8.3+ | | Xamarin.Android | API 18+ | | Windows 10 (UWP) | 1709+ |
Note: Currently UWP only supports listening for broadcasts/advertisements, not connecting to devices.
Quick example
This is a quick overview of the API and usage; continue reading below for setup instructions and more comprehensive examples.
var connection = await ble.FindAndConnectToDevice(
new ScanFilter().AddAdvertisedService( service ),
TimeSpan.FromSeconds( 30 )
);
if(connection.IsSuccessful())
{
try
{
var gattServer = connection.GattServer;
var read = gattServer.ReadCharacteristicValue( service, char1 );
await Task.WhenAll( new Task[]
{
gattServer.WriteCharacteristicValue(
service, char1, new Byte[]{/* bytes */}
),
gattServer.WriteCharacteristicValue(
service, char2, new Byte[]{/* bytes */}
),
gattServer.WriteCharacteristicValue(
service2, char3, new Byte[]{/* bytes */}
)
} );
// Even though we await "read" after awaiting the write calls, the read was
// dispatched first and so will have executed prior to the write calls
originalValue = await read;
}
catch(GattException ex)
{
Debug.WriteLine( ex.ToString() );
}
finally
{
// The device will stay connected until you call Disconnect or the connection is lost through some external means.
await connection.GattServer.Disconnect();
}
}
Getting Started
1. Install NuGet packages
In your shared library project
Install the ble.net (API) package.
dotnet add package ble.net
NOTE: BLE.net switched from targetting
portable-net45+win8in version1.1.1, to.netstandard1.4in version1.2.0, to.netstandard2.0in1.2.1(where it will remain for the forseeable future). If you are having problems please file an issue
In your platform project(s)
Install the relevant platform package. (See table at the top of the readme for supported versions.)
dotnet add package ble.net-android
dotnet add package ble.net-ios
dotnet add package ble.net-uwp
2. Add relevant app permissions
Android
[assembly: UsesPermission( Manifest.Permission.Bluetooth )]
[assembly: UsesPermission( Manifest.Permission.BluetoothAdmin )]
If you are having issues discovering devices when scanning, try adding coarse location permissions. Android has inconsistent behavior across devices and adding this permission sometimes helps.
[assembly: UsesPermission( Manifest.Permission.AccessCoarseLocation )]Note also that this is a "dangerous" permission in API 23+, so if you are targeting Android 6.0 or higher you will need to request this permission from the user at runtime.
iOS
If you are only using BLE in the foreground, when your app is active, you don't need to do any further setup for iOS.
If you need to use BLE in the background:
- Add bluetooth-central to background modes
- Add a string value for key NSBluetoothPeripheralUsageDescription. iOS will display this value in a permission dialog box that the user must approve.
<!-- Info.plist -->
<key>UIBackgroundModes</key>
<array>
<string>bluetooth-central</string>
</array>
<key>NSBluetoothPeripheralUsageDescription</key>
<string>[MyAppNameHere] would like to use bluetooth.</string>
UWP
<!-- Package.appxmanifest -->
<Capabilities>
<DeviceCapability Name="bluetooth" />
</Capabilities>
3. Initialize BluetoothLowEnergyAdapter (Android-only)
There is no initialization needed for iOS or UWP.
If you want IBluetoothLowEnergyAdapter.DisableAdapter() and IBluetoothLowEnergyAdapter.EnableAdapter() to work, then in your main Activity add:
protected override void OnCreate( Bundle bundle )
{
// ...
BluetoothLowEnergyAdapter.Init( this );
// ...
}
If you want IBluetoothLowEnergyAdapter.CurrentState.Subscribe() to work, then in your calling Activity add:
protected sealed override void OnActivityResult( Int32 requestCode, Result resultCode, Intent data )
{
BluetoothLowEnergyAdapter.OnActivityResult( requestCode, resultCode, data );
}
4. Obtain a reference to BluetoothLowEnergyAdapter
Each platform project has a static method BluetoothLowEnergyAdapter.ObtainDefaultAdapter() which you call from your platform project and provide to your application code using whatever strategy you prefer (dependency injection, manual reference passing, a singleton or service locator, etc).
See the sample Xamarin Forms app for real-life examples:
- Android Xamarin.Forms example
- iOS Xamarin.Forms example
- UWP Xamarin.Forms example
API
See sample Xamarin Forms app included in the repo for further examples of how to integrate BLE.net into an app.
All the examples presume you have obtained the IBluetoothLowEnergyAdapter as per the setup notes above, e.g.:
IBluetoothLowEnergyAdapter ble = /* platform-provided adapter from BluetoothLowEnergyAdapter.ObtainDefaultAdapter()*/;
Control the Bluetooth Adapter on the device
Enable Bluetooth
There are corresponding methods to disable the adapter.
if(ble.AdapterCanBeEnabled && ble.CurrentState.IsDisabledOrDisabling()) {
await ble.EnableAdapter();
}
See & Observe Adapter Status
ble.CurrentState.Value; // e.g.: EnabledDisabledState.Enabled
// The adapter implements IObservable<EnabledDisabledState> so you can subscribe to its state
ble.CurrentState.Subscribe( state => Debug.WriteLine("New State: {0}", state) );
Scan for advertisements being broadcast by nearby BLE peripherals
var cts = new CancellationTokenSource(TimeSpan.FromSeconds( 30 ));
await ble.ScanForBroadcasts(
// providing ScanSettings is optional
new ScanSettings()
{
// Setting the scan mode is currently only applicable to Android and has no effect on other platforms.
// If not provided, defaults to ScanMode.Balanced
Mode = ScanMode.LowPower,
// Optional scan filter to ensure that the observer will only receive peripherals
// that pass the filter. If you want to scan for everything around, omit the filter.
Filter = new ScanFilter()
{
AdvertisedDeviceName = "foobar",
AdvertisedManufacturerCompanyId = 76,
// peripherals must advertise at-least-one of any GUIDs in this list
AdvertisedServiceIsInList = new List<Guid>(){ someGuid },
},
// ignore repeated advertisements from the same device during this scan
IgnoreRepeatBroadcasts = false
},
// Your IObserver<IBlePeripheral> or Action<IBlePeripheral> will be triggered for each discovered
// peripheral based on the provided scan settings and filter (if any).
( IBlePeripheral peripheral ) =>
{
// read the advertising data
var adv = peripheral.Advertisement;
Debug.WriteLine( adv.DeviceName );
Debug.WriteLine( adv.Services.Select( x => x.ToString() ).Join( "," ) );
Debug.WriteLine( adv.ManufacturerSpecificData.FirstOrDefault().CompanyName() );
Debug.WriteLine( adv.ServiceData );
// if we found what we needed, stop the scan manually
cts.Cancel();
// perhaps connect to the device (see next example)...
},
// Provide a CancellationToken to stop the scan, or use the overload that takes a TimeSpan.
// If you omit this argument, the scan will timeout after BluetoothLowEnergyUtils.DefaultScanTimeout
cts.Token
);
// scanning has stopped when code reached this point since the scan was awaited
You can also create a ScanFilter using a fluent builder syntax if you prefer that:
new ScanFilter()
.SetAdvertisedDeviceName( "foobar" )
.SetAdvertisedManufacturerCompanyId( 76 )
.AddAdvertisedService( someGuid )
Connect to a BLE device
If you have already scanned for and discovered a peripheral and you now want to connect to it:
var connection = await ble.ConnectToDevice(
// The IBlePeripheral to connect to
peripheral,
// TimeSpan or CancellationToken to stop the
// connection attempt.
// If you omit this argument, it will use
// Bluetoot
Related Skills
node-connect
333.3kDiagnose OpenClaw node connection and pairing failures for Android, iOS, and macOS companion apps
frontend-design
82.0kCreate distinctive, production-grade frontend interfaces with high design quality. Use this skill when the user asks to build web components, pages, or applications. Generates creative, polished code that avoids generic AI aesthetics.
openai-whisper-api
333.3kTranscribe audio via OpenAI Audio Transcriptions API (Whisper).
commit-push-pr
82.0kCommit, push, and open a PR
