subscribeToCharacteristic method

  1. @override
Stream<BleCharacteristicValue> subscribeToCharacteristic(
  1. BleCharacteristic characteristic
)
override

Subscribes to a Bluetooth characteristic to listen for updates.

A caller to this function will receive a Stream of BleCharacteristicValue objects. A caller should listen to this stream and establish a callback function invoked each time a new value is emitted to the stream. Once subscribed, any updates to the characteristic value will be sent as a stream of BleCharacteristicValue objects.

Implementation

@override
Stream<BleCharacteristicValue> subscribeToCharacteristic(
  BleCharacteristic characteristic,
) {
  final StreamController<BleCharacteristicValue> streamController =
      StreamController<BleCharacteristicValue>.broadcast();

  // Listen for characteristic updates from the platform side.
  channel.setMethodCallHandler((MethodCall call) async {
    if (call.method == 'onCharacteristicChanged') {
      final BleCharacteristicValue value;
      try {
        value = BleCharacteristicValue.fromMap(call.arguments as Map<dynamic, dynamic>);
      } catch (e) {
        streamController.addError(Exception('Failed to parse characteristic value: $e'));
        return;
      }
      streamController.add(value);
    }
  });

  // Trigger the subscription to the characteristic on the platform side.
  try {
    channel.invokeMethod('subscribeToCharacteristic', {
      'address': characteristic.address,
      'characteristicUuid': characteristic.uuid,
    });
  } on PlatformException catch (e) {
    // Handle different error types accordingly.
    if (e.message?.contains('permissions') ?? false) {
      streamController.addError(
        BluetoothPermissionException('Permission error: ${e.message}'),
      );
      throw BluetoothPermissionException('Permission error: ${e.message}');
    } else {
      streamController.addError(
        BluetoothSubscriptionException(
          'Failed to subscribe to BLE characteristic: ${e.message}',
        ),
      );
      throw BluetoothSubscriptionException(
        'Failed to subscribe to BLE characteristic: ${e.message}',
      );
    }
  }

  return streamController.stream;
}