### Import flutter_reactive_ble in Dart
Source: https://pub.dev/packages/flutter_reactive_ble/install
Import the package into your Dart files to start using its functionalities. Ensure this line is present in your .dart files.
```dart
import 'package:flutter_reactive_ble/flutter_reactive_ble.dart';
```
--------------------------------
### Observe Host Device BLE Status
Source: https://pub.dev/packages/flutter_reactive_ble
Listen to the statusStream for updates on the host device's Bluetooth Low Energy status, such as whether BLE is enabled or permissions are granted. Use `_ble.status` to get the current status.
```dart
_ble.statusStream.listen((status) {
//code for handling status update
});
```
--------------------------------
### Connect to Advertising Device (Android Workaround)
Source: https://pub.dev/packages/flutter_reactive_ble
Connect to a device by first scanning for it, then connecting if found. This method is useful for working around Android BLE stack issues where direct connection attempts might hang. It includes parameters for prescan duration and connection timeout.
```dart
flutterReactiveBle.connectToAdvertisingDevice(
id: foundDeviceId,
withServices: [serviceUuid],
prescanDuration: const Duration(seconds: 5),
servicesWithCharacteristicsToDiscover: {serviceId: [char1, char2]},
connectionTimeout: const Duration(seconds: 2),
).listen((connectionState) {
// Handle connection state updates
}, onError: (dynamic error) {
// Handle a possible error
});
```
--------------------------------
### Initialize FlutterReactiveBle
Source: https://pub.dev/packages/flutter_reactive_ble
Instantiate the FlutterReactiveBle class to begin using the library's functionalities.
```dart
final flutterReactiveBle = FlutterReactiveBle();
```
--------------------------------
### Connect to a BLE Device
Source: https://pub.dev/packages/flutter_reactive_ble
Establish a connection to a discovered BLE device using its ID. Optionally, specify services and characteristics to discover upon connection and set a connection timeout. On iOS, specifying services can speed up connection.
```dart
flutterReactiveBle.connectToDevice(
id: foundDeviceId,
servicesWithCharacteristicsToDiscover: {serviceId: [char1, char2]},
connectionTimeout: const Duration(seconds: 2),
).listen((connectionState) {
// Handle connection state updates
}, onError: (Object error) {
// Handle a possible error
});
```
--------------------------------
### Request MTU Size Negotiation
Source: https://pub.dev/packages/flutter_reactive_ble
Requests a new MTU size to potentially increase throughput. The returned value is the actual negotiated MTU, which may not match the requested size. iOS has a fixed default MTU that cannot be negotiated.
```dart
final mtu = await flutterReactiveBle.requestMtu(deviceId: foundDeviceId, mtu: 250);
```
--------------------------------
### Add flutter_reactive_ble Dependency
Source: https://pub.dev/packages/flutter_reactive_ble/install
Use this command to add the package to your Flutter project's dependencies. This command automatically updates your pubspec.yaml file.
```bash
$ flutter pub add flutter_reactive_ble
```
--------------------------------
### Request Connection Priority (Android)
Source: https://pub.dev/packages/flutter_reactive_ble
On Android, requests a change in the connection priority to optimize for performance or battery usage. This operation is not supported on iOS.
```APIDOC
## Request Connection Priority (Android)
### Description
On Android devices, this operation allows requesting a change in the BLE connection priority. Options include `highPerformance` (increases battery usage but speeds up GATT operations) and others defined in `ConnectionPriority`.
### Method
`requestConnectionPriority`
### Endpoint
N/A (SDK method)
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
- **priority** (ConnectionPriority) - Required - The desired connection priority (e.g., `ConnectionPriority.highPerformance`).
### Request Example
```dart
await flutterReactiveBle.requestConnectionPriority(deviceId: foundDeviceId, priority: ConnectionPriority.highPerformance);
```
### Response
#### Success Response
None (operation is asynchronous)
#### Response Example
None
```
--------------------------------
### Android Permissions for BLE
Source: https://pub.dev/packages/flutter_reactive_ble
Add these permissions to your AndroidManifest.xml file to enable Bluetooth Low Energy functionalities. Ensure correct usage flags and target API levels are considered.
```xml
```
--------------------------------
### Write Characteristic with Response
Source: https://pub.dev/packages/flutter_reactive_ble
Writes a value to a characteristic and waits for an acknowledgement of reception. Throws an exception if the write fails.
```APIDOC
## Write Characteristic with Response
### Description
Writes a value to a characteristic and awaits an acknowledgement of reception. The operation succeeds if acknowledged, otherwise an exception is thrown.
### Method
`writeCharacteristicWithResponse`
### Endpoint
N/A (SDK method)
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
- **value** (List) - Required - The data to write to the characteristic.
### Request Example
```dart
final characteristic = QualifiedCharacteristic(serviceId: serviceUuid, characteristicId: characteristicUuid, deviceId: foundDeviceId);
await flutterReactiveBle.writeCharacteristicWithResponse(characteristic, value: [0x00]);
```
### Response
#### Success Response (void)
- The operation is acknowledged.
#### Response Example
(No specific example provided, as the response is an acknowledgement or an exception)
```
--------------------------------
### Request MTU Size
Source: https://pub.dev/packages/flutter_reactive_ble
Requests to negotiate a new Maximum Transmission Unit (MTU) size for the connection to improve throughput. The actual negotiated size may differ.
```APIDOC
## Negotiate MTU Size
### Description
Requests to negotiate a new Maximum Transmission Unit (MTU) size for the connection to potentially increase throughput. The returned value is the actual negotiated MTU size.
### Method
`requestMtu`
### Endpoint
N/A (SDK method)
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
```dart
final mtu = await flutterReactiveBle.requestMtu(deviceId: foundDeviceId, mtu: 250);
```
### Response
#### Success Response
- **mtu** (int) - The actual negotiated MTU size.
#### Response Example
(No specific example provided, depends on negotiated MTU)
```
--------------------------------
### Android ProGuard Rules for Reactive BLE
Source: https://pub.dev/packages/flutter_reactive_ble
Include these ProGuard rules in your `proguard-rules.pro` file to prevent issues with the reactive BLE library, particularly related to class obfuscation.
```proguard
-keep class com.signify.hue.** { *; }
```
--------------------------------
### Subscribe to Characteristic
Source: https://pub.dev/packages/flutter_reactive_ble
Subscribes to notifications or indications from a characteristic, allowing real-time updates when its value changes.
```APIDOC
## Subscribe to Characteristic
### Description
Subscribes to notifications or indications from a characteristic to receive updates when its value changes. This is an alternative to periodic reading.
### Method
`subscribeToCharacteristic`
### Endpoint
N/A (SDK method)
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
```dart
final characteristic = QualifiedCharacteristic(serviceId: serviceUuid, characteristicId: characteristicUuid, deviceId: foundDeviceId);
flutterReactiveBle.subscribeToCharacteristic(characteristic).listen((data) {
// code to handle incoming data
}, onError: (dynamic error) {
// code to handle errors
});
```
### Response
#### Success Response
- **data** (dynamic) - The incoming data from the characteristic.
#### Response Example
(No specific example provided, depends on characteristic type and data format)
```
--------------------------------
### Request BLE Connection Priority (Android)
Source: https://pub.dev/packages/flutter_reactive_ble
On Android, requests a connection priority update to potentially speed up GATT operations at the cost of increased battery usage. Use with caution, especially when managing multiple devices.
```dart
await flutterReactiveBle.requestConnectionPriority(deviceId: foundDeviceId, priority: ConnectionPriority.highPerformance);
```
--------------------------------
### Scan for BLE Devices
Source: https://pub.dev/packages/flutter_reactive_ble
Initiate a scan for BLE devices. Specify service IDs to filter results or use an empty list to discover all advertising devices. The scan mode can be adjusted for Android.
```dart
flutterReactiveBle.scanForDevices(withServices: [serviceId], scanMode: ScanMode.lowLatency).listen((device) {
//code for handling results
}, onError: () {
//code for handling error
});
```
--------------------------------
### Handle BLE Undeliverable Exception on Android
Source: https://pub.dev/packages/flutter_reactive_ble
This workaround should be placed in your Java/Kotlin code (e.g., MainActivity) to handle BLE undeliverable exceptions on Android. It ignores BleExceptions that do not have a subscriber, preventing app crashes.
```java
RxJavaPlugins.setErrorHandler { throwable ->
if (throwable is UndeliverableException && throwable.cause is BleException) {
return@setErrorHandler // ignore BleExceptions since we do not have subscriber
}
else {
throw throwable
}
}
```
--------------------------------
### Write BLE Characteristic with Response
Source: https://pub.dev/packages/flutter_reactive_ble
Writes a value to a BLE characteristic and waits for an acknowledgement. This operation confirms reception but not necessarily successful processing by the device. For request-response patterns, implement a custom mechanism like a control point.
```dart
final characteristic = QualifiedCharacteristic(serviceId: serviceUuid, characteristicId: characteristicUuid, deviceId: foundDeviceId);
await flutterReactiveBle.writeCharacteristicWithResponse(characteristic, value: [0x00]);
```
--------------------------------
### Read Characteristic
Source: https://pub.dev/packages/flutter_reactive_ble
Reads the current value of a Bluetooth characteristic. This is a direct read operation.
```APIDOC
## Read Characteristic
### Description
Reads the current value of a Bluetooth characteristic.
### Method
`readCharacteristic`
### Endpoint
N/A (SDK method)
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
```dart
final characteristic = QualifiedCharacteristic(serviceId: serviceUuid, characteristicId: characteristicUuid, deviceId: foundDeviceId);
final response = await flutterReactiveBle.readCharacteristic(characteristic);
```
### Response
#### Success Response
- **response** (dynamic) - The value read from the characteristic.
#### Response Example
(No specific example provided, depends on characteristic type)
```
--------------------------------
### Write Characteristic Without Response
Source: https://pub.dev/packages/flutter_reactive_ble
Writes a value to a characteristic without waiting for a response. Suitable for high-frequency writes.
```APIDOC
## Write Characteristic Without Response
### Description
Writes a value to a characteristic without waiting for a response. This method is optimized for performance and suitable for scenarios requiring multiple consecutive writes.
### Method
`writeCharacteristicWithoutResponse`
### Endpoint
N/A (SDK method)
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
- **value** (List) - Required - The data to write to the characteristic.
### Request Example
```dart
final characteristic = QualifiedCharacteristic(serviceId: serviceUuid, characteristicId: characteristicUuid, deviceId: foundDeviceId);
flutterReactiveBle.writeCharacteristicWithoutResponse(characteristic, value: [0x00]);
```
### Response
#### Success Response
None (as no response is expected)
#### Response Example
None
```
--------------------------------
### Subscribe to BLE Characteristic Notifications
Source: https://pub.dev/packages/flutter_reactive_ble
Listens for notifications when a characteristic's value changes, which is more efficient than periodic reading if the service supports notifications. Handles incoming data and potential errors.
```dart
final characteristic = QualifiedCharacteristic(serviceId: serviceUuid, characteristicId: characteristicUuid, deviceId: foundDeviceId);
flutterReactiveBle.subscribeToCharacteristic(characteristic).listen((data) {
// code to handle incoming data
}, onError: (dynamic error) {
// code to handle errors
});
```
--------------------------------
### Write BLE Characteristic without Response
Source: https://pub.dev/packages/flutter_reactive_ble
Writes a value to a BLE characteristic without waiting for an acknowledgement. This is faster for multiple consecutive writes, such as firmware uploads, but may overwhelm devices that cannot handle rapid writes. Periodically use `writeWithResponse` to maintain reliability.
```dart
final characteristic = QualifiedCharacteristic(serviceId: serviceUuid, characteristicId: characteristicUuid, deviceId: foundDeviceId);
flutterReactiveBle.writeCharacteristicWithoutResponse(characteristic, value: [0x00]);
```
--------------------------------
### Read BLE Characteristic
Source: https://pub.dev/packages/flutter_reactive_ble
Reads the current value of a BLE characteristic. Ensure the characteristic is correctly identified with service, characteristic, and device IDs.
```dart
final characteristic = QualifiedCharacteristic(serviceId: serviceUuid, characteristicId: characteristicUuid, deviceId: foundDeviceId);
final response = await flutterReactiveBle.readCharacteristic(characteristic);
```
--------------------------------
### Clear GATT Cache (Android)
Source: https://pub.dev/packages/flutter_reactive_ble
Invalidates the Android OS's cached service discovery table for a device. Use with extreme caution, as this is a greylisted operation and may be necessary after firmware updates that change services.
```dart
await flutterReactiveBle.clearGattCache(foundDeviceId);
```
--------------------------------
### Android BLUETOOTH_SCAN Permission Modification
Source: https://pub.dev/packages/flutter_reactive_ble
If using BLUETOOTH_SCAN for location, modify your AndroidManifest.xml as shown. This snippet demonstrates how to remove specific flags and set a target API level.
```xml
```
--------------------------------
### Clear GATT Cache (Android)
Source: https://pub.dev/packages/flutter_reactive_ble
On Android, invalidates the device's GATT service cache. Use with caution, especially after firmware updates, as it's a hidden operation.
```APIDOC
## Clear GATT Cache (Android)
### Description
On Android, this operation invalidates the cached GATT services for a specific device. This can be useful if the device's firmware has been updated and the cache is out of sync. This is a hidden BLE operation and should be used with extreme caution.
### Method
`clearGattCache`
### Endpoint
N/A (SDK method)
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
```dart
await flutterReactiveBle.clearGattCache(foundDeviceId);
```
### Response
#### Success Response
None (operation is asynchronous)
#### Response Example
None
```
--------------------------------
### Null Check Operator Warning in serial_disposable.dart
Source: https://pub.dev/packages/flutter_reactive_ble/score
This warning indicates the misuse of the null check operator (!) on a potentially nullable type parameter. Ensure proper null handling to avoid runtime errors.
```dart
if (_value != null) await _dispose(_value!);
```
```dart
await _dispose(_value!);
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.