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 (_connectedDevice == null) {
log("Not connected to any device");
return false;
}
final service = _connectedDevice!.gattServices.firstWhereOrNull((element) {
return element.uuid.toString().toLowerCase() == serviceUuid.toLowerCase();
});
if (service == null) {
log("Service not found: $serviceUuid");
return false;
}
final characteristic = service.characteristics.firstWhereOrNull((element) {
return element.uuid.toString().toLowerCase() == characteristicUuid.toLowerCase();
});
if (characteristic == null) {
log("Characteristic not found: $characteristicUuid");
return false;
}
if (characteristic.notifying) {
log("Characteristic already notifying: $characteristicUuid");
return false;
}
_notifications[characteristic.uuid] = characteristic.propertiesChanged.listen((events) {
for (final event in events) {
if (event == 'Value') {
final receivedValue = characteristic.value;
_notifyController.add(BleCharacteristicNotification(
serviceUuid: serviceUuid,
characteristicUuid: characteristicUuid,
value: Uint8List.fromList(receivedValue),
));
}
}
});
await characteristic.startNotify();
return true;
}