startNotify method
startNotify starts listening to notifications from a BLE characteristic. To stop listening, use stopNotify method and to get the notifications, use onNotify stream.
Implementation
@override
Future<bool?> startNotify({
required String serviceUuid,
required String characteristicUuid,
}) async {
if (_currentConnected == null) {
log("No device connected");
return false;
}
final services = await _currentConnected!.discoverServices();
final service = services.firstWhereOrNull((s) => s.uuid.toLowerCase() == serviceUuid.toLowerCase());
if (service == null) {
log("Service not found: $serviceUuid");
return false;
}
try {
final characteristic = await service.getCharacteristic(characteristicUuid);
if (characteristic.isNotifying) {
log("Already notifying");
return true;
}
await characteristic.startNotifications();
_notifications[characteristicUuid] = characteristic.value.listen((event) {
_notifyController.add(BleCharacteristicNotification(
serviceUuid: serviceUuid,
characteristicUuid: characteristicUuid,
value: event.buffer.asUint8List(),
));
});
return true;
} catch (e) {
log("Error getting characteristic: $e");
return false;
}
}