discoverServices method
Initiates the service discovery process for a connected Bluetooth Low Energy (BLE) device and returns a Stream of discovered services and their characteristics.
The service discovery process is a crucial step after establishing a BLE connection. It involves querying the connected peripheral to enumerate the services it offers along with their associated characteristics and descriptors. These services can represent various functionalities provided by the device, such as heart rate monitoring, temperature sensing, etc.
The method uses a StreamController to handle the asynchronous nature of service discovery. The native platform code Android sends updates when new services and characteristics are discovered, which are then parsed and added to the stream.
How Service Discovery Works
- After connecting to a BLE device, you invoke the
discoverServices()
method, passing in the device address. - The native code kicks off the service discovery process.
- As services and their characteristics are discovered, they are sent back to the Flutter app.
- These updates are received in the
_handleBleServicesDiscovered
method (not shown here), which then notifies all listeners to the stream.
Implementation
@override
Stream<List<BleService>> discoverServices(String deviceAddress) {
final StreamController<List<BleService>> servicesDiscoveredController =
StreamController<List<BleService>>.broadcast();
// Listen to the platform side for discovered services and their characteristics. The platform side differentiates
// services discovered for different Bluetooth peripherals by appending the device address to the method name.
_handleBleServicesDiscovered(deviceAddress, servicesDiscoveredController);
channel.invokeMethod('discoverServices', {'address': deviceAddress});
return servicesDiscoveredController.stream;
}